mobile-mcp-ai 2.3.4__py3-none-any.whl → 2.5.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -53,11 +53,41 @@ class BasicMobileToolsLite:
53
53
  }
54
54
  self.operation_history.append(record)
55
55
 
56
+ def _get_full_hierarchy(self) -> str:
57
+ """获取完整的 UI 层级 XML(包含 NAF 元素)
58
+
59
+ 优先使用 ADB 直接 dump,比 uiautomator2.dump_hierarchy 更完整
60
+ """
61
+ import sys
62
+
63
+ if self._is_ios():
64
+ # iOS 使用 page_source
65
+ ios_client = self._get_ios_client()
66
+ if ios_client and hasattr(ios_client, 'wda'):
67
+ return ios_client.wda.source()
68
+ return ""
69
+
70
+ # Android: 优先使用 ADB 直接 dump
71
+ try:
72
+ # 方法1: ADB dump(获取最完整的 UI 树,包括 NAF 元素)
73
+ self.client.u2.shell('uiautomator dump /sdcard/ui_dump.xml')
74
+ result = self.client.u2.shell('cat /sdcard/ui_dump.xml')
75
+ if result and isinstance(result, str) and result.strip().startswith('<?xml'):
76
+ xml_string = result.strip()
77
+ self.client.u2.shell('rm /sdcard/ui_dump.xml')
78
+ return xml_string
79
+ except Exception as e:
80
+ print(f" ⚠️ ADB dump 失败: {e}", file=sys.stderr)
81
+
82
+ # 方法2: 回退到 uiautomator2
83
+ return self.client.u2.dump_hierarchy(compressed=False)
84
+
56
85
  # ==================== 截图 ====================
57
86
 
58
87
  def take_screenshot(self, description: str = "", compress: bool = True,
59
- max_width: int = 720, quality: int = 75) -> Dict:
60
- """截图(支持压缩,省 token)
88
+ max_width: int = 720, quality: int = 75,
89
+ crop_x: int = 0, crop_y: int = 0, crop_size: int = 0) -> Dict:
90
+ """截图(支持压缩和局部裁剪)
61
91
 
62
92
  压缩原理:
63
93
  1. 先截取原始 PNG 图片
@@ -65,11 +95,20 @@ class BasicMobileToolsLite:
65
95
  3. 转换为 JPEG 格式 + 降低质量(如 100% → 75%)
66
96
  4. 最终文件从 2MB 压缩到约 80KB(节省 96%)
67
97
 
98
+ 局部裁剪(用于精确识别小元素):
99
+ - 第一次全屏截图,AI 返回大概坐标
100
+ - 第二次传入 crop_x, crop_y, crop_size 截取局部区域
101
+ - 局部区域不压缩,保持清晰度,AI 可精确识别
102
+ - 返回 crop_offset_x/y 用于坐标换算
103
+
68
104
  Args:
69
105
  description: 截图描述(可选)
70
106
  compress: 是否压缩(默认 True,推荐开启省 token)
71
107
  max_width: 压缩后最大宽度(默认 720,对 AI 识别足够)
72
108
  quality: JPEG 质量 1-100(默认 75,肉眼几乎看不出区别)
109
+ crop_x: 裁剪中心点 X 坐标(屏幕坐标,0 表示不裁剪)
110
+ crop_y: 裁剪中心点 Y 坐标(屏幕坐标,0 表示不裁剪)
111
+ crop_size: 裁剪区域大小(默认 0 不裁剪,推荐 200-400)
73
112
 
74
113
  压缩效果示例:
75
114
  原图 PNG: 2048KB
@@ -104,12 +143,74 @@ class BasicMobileToolsLite:
104
143
 
105
144
  original_size = temp_path.stat().st_size
106
145
 
107
- if compress:
108
- # 第2步:打开图片
109
- img = Image.open(temp_path)
146
+ # 第2步:打开图片
147
+ img = Image.open(temp_path)
148
+
149
+ # 第2.5步:局部裁剪(如果指定了裁剪参数)
150
+ crop_offset_x, crop_offset_y = 0, 0
151
+ is_cropped = False
152
+
153
+ if crop_x > 0 and crop_y > 0 and crop_size > 0:
154
+ # 计算裁剪区域(以 crop_x, crop_y 为中心)
155
+ half_size = crop_size // 2
156
+ left = max(0, crop_x - half_size)
157
+ top = max(0, crop_y - half_size)
158
+ right = min(img.width, crop_x + half_size)
159
+ bottom = min(img.height, crop_y + half_size)
160
+
161
+ # 记录偏移量(用于坐标换算)
162
+ crop_offset_x = left
163
+ crop_offset_y = top
164
+
165
+ # 裁剪
166
+ img = img.crop((left, top, right, bottom))
167
+ is_cropped = True
168
+
169
+ # ========== 情况1:局部裁剪截图(不压缩,保持清晰度)==========
170
+ if is_cropped:
171
+ # 生成文件名
172
+ if description:
173
+ safe_desc = re.sub(r'[^\w\s-]', '', description).strip().replace(' ', '_')
174
+ filename = f"screenshot_{platform}_crop_{safe_desc}_{timestamp}.png"
175
+ else:
176
+ filename = f"screenshot_{platform}_crop_{timestamp}.png"
177
+
178
+ final_path = self.screenshot_dir / filename
179
+
180
+ # 保存为 PNG(保持清晰度)
181
+ img.save(str(final_path), "PNG")
182
+
183
+ # 删除临时文件
184
+ temp_path.unlink()
185
+
186
+ cropped_size = final_path.stat().st_size
187
+
188
+ return {
189
+ "success": True,
190
+ "screenshot_path": str(final_path),
191
+ "screen_width": screen_width,
192
+ "screen_height": screen_height,
193
+ "image_width": img.width,
194
+ "image_height": img.height,
195
+ "crop_offset_x": crop_offset_x,
196
+ "crop_offset_y": crop_offset_y,
197
+ "file_size": f"{cropped_size/1024:.1f}KB",
198
+ "message": f"🔍 局部截图已保存: {final_path}\n"
199
+ f"📐 裁剪区域: ({crop_offset_x}, {crop_offset_y}) 起,{img.width}x{img.height} 像素\n"
200
+ f"📦 文件大小: {cropped_size/1024:.0f}KB\n"
201
+ f"🎯 【坐标换算】AI 返回坐标 (x, y) 后:\n"
202
+ f" 实际屏幕坐标 = ({crop_offset_x} + x, {crop_offset_y} + y)\n"
203
+ f" 或直接调用 mobile_click_at_coords(x, y, crop_offset_x={crop_offset_x}, crop_offset_y={crop_offset_y})"
204
+ }
205
+
206
+ # ========== 情况2:全屏压缩截图 ==========
207
+ elif compress:
208
+ # 🔴 关键:记录原始图片尺寸(用于坐标转换)
209
+ # 注意:截图尺寸可能和 u2.info 的 displayWidth 不一致!
210
+ original_img_width = img.width
211
+ original_img_height = img.height
110
212
 
111
213
  # 第3步:缩小尺寸(保持宽高比)
112
- # 记录压缩后的图片尺寸(用于坐标转换)
113
214
  image_width, image_height = img.width, img.height
114
215
 
115
216
  if img.width > max_width:
@@ -118,20 +219,16 @@ class BasicMobileToolsLite:
118
219
  new_h = int(img.height * ratio)
119
220
  # 兼容不同版本的 Pillow
120
221
  try:
121
- # Pillow 10.0.0+
122
222
  resample = Image.Resampling.LANCZOS
123
223
  except AttributeError:
124
224
  try:
125
- # Pillow 9.x
126
225
  resample = Image.LANCZOS
127
226
  except AttributeError:
128
- # Pillow 旧版本
129
227
  resample = Image.ANTIALIAS
130
228
  img = img.resize((new_w, new_h), resample)
131
- # 更新为压缩后的尺寸
132
229
  image_width, image_height = new_w, new_h
133
230
 
134
- # 第4步:生成最终文件名(JPEG 格式)
231
+ # 生成文件名(JPEG 格式)
135
232
  if description:
136
233
  safe_desc = re.sub(r'[^\w\s-]', '', description).strip().replace(' ', '_')
137
234
  filename = f"screenshot_{platform}_{safe_desc}_{timestamp}.jpg"
@@ -140,10 +237,8 @@ class BasicMobileToolsLite:
140
237
 
141
238
  final_path = self.screenshot_dir / filename
142
239
 
143
- # 第5步:保存为 JPEG(PNG 可能有透明通道,需转 RGB)
144
- # 先转换为 RGB 模式,处理可能的 RGBA 或 P 模式
240
+ # 保存为 JPEG(处理透明通道)
145
241
  if img.mode in ('RGBA', 'LA', 'P'):
146
- # 创建白色背景
147
242
  background = Image.new('RGB', img.size, (255, 255, 255))
148
243
  if img.mode == 'P':
149
244
  img = img.convert('RGBA')
@@ -153,8 +248,6 @@ class BasicMobileToolsLite:
153
248
  img = img.convert("RGB")
154
249
 
155
250
  img.save(str(final_path), "JPEG", quality=quality)
156
-
157
- # 第6步:删除临时 PNG
158
251
  temp_path.unlink()
159
252
 
160
253
  compressed_size = final_path.stat().st_size
@@ -165,21 +258,23 @@ class BasicMobileToolsLite:
165
258
  "screenshot_path": str(final_path),
166
259
  "screen_width": screen_width,
167
260
  "screen_height": screen_height,
168
- "image_width": image_width,
169
- "image_height": image_height,
261
+ "original_img_width": original_img_width, # 截图原始宽度
262
+ "original_img_height": original_img_height, # 截图原始高度
263
+ "image_width": image_width, # 压缩后宽度(AI 看到的)
264
+ "image_height": image_height, # 压缩后高度(AI 看到的)
170
265
  "original_size": f"{original_size/1024:.1f}KB",
171
266
  "compressed_size": f"{compressed_size/1024:.1f}KB",
172
267
  "saved_percent": f"{saved_percent:.0f}%",
173
268
  "message": f"📸 截图已保存: {final_path}\n"
174
- f"📐 屏幕尺寸: {screen_width}x{screen_height}\n"
175
- f"🖼️ 图片尺寸: {image_width}x{image_height}(AI 分析用)\n"
269
+ f"📐 原始尺寸: {original_img_width}x{original_img_height} → 压缩后: {image_width}x{image_height}\n"
176
270
  f"📦 已压缩: {original_size/1024:.0f}KB → {compressed_size/1024:.0f}KB (省 {saved_percent:.0f}%)\n"
177
- f"⚠️ 【重要】AI 返回的坐标需要转换!\n"
178
- f" 请使用 mobile_click_at_coords 并传入 image_width={image_width}, image_height={image_height}\n"
179
- f" 工具会自动将图片坐标转换为屏幕坐标"
271
+ f"⚠️ 【坐标转换】AI 返回坐标后,请传入:\n"
272
+ f" image_width={image_width}, image_height={image_height},\n"
273
+ f" original_img_width={original_img_width}, original_img_height={original_img_height}"
180
274
  }
275
+
276
+ # ========== 情况3:全屏不压缩截图 ==========
181
277
  else:
182
- # 不压缩,直接重命名临时文件
183
278
  if description:
184
279
  safe_desc = re.sub(r'[^\w\s-]', '', description).strip().replace(' ', '_')
185
280
  filename = f"screenshot_{platform}_{safe_desc}_{timestamp}.png"
@@ -189,19 +284,21 @@ class BasicMobileToolsLite:
189
284
  final_path = self.screenshot_dir / filename
190
285
  temp_path.rename(final_path)
191
286
 
192
- # 不压缩时,图片尺寸 = 屏幕尺寸
287
+ # 不压缩时,用截图实际尺寸(可能和 screen_width 不同)
193
288
  return {
194
289
  "success": True,
195
290
  "screenshot_path": str(final_path),
196
291
  "screen_width": screen_width,
197
292
  "screen_height": screen_height,
198
- "image_width": screen_width,
199
- "image_height": screen_height,
293
+ "original_img_width": img.width, # 截图实际尺寸
294
+ "original_img_height": img.height,
295
+ "image_width": img.width, # 未压缩,和原图一样
296
+ "image_height": img.height,
200
297
  "file_size": f"{original_size/1024:.1f}KB",
201
298
  "message": f"📸 截图已保存: {final_path}\n"
202
- f"📐 屏幕尺寸: {screen_width}x{screen_height}\n"
299
+ f"📐 截图尺寸: {img.width}x{img.height}\n"
203
300
  f"📦 文件大小: {original_size/1024:.0f}KB(未压缩)\n"
204
- f"💡 Cursor 分析图片后,返回的坐标可直接用于 mobile_click_at_coords"
301
+ f"💡 未压缩,坐标可直接使用"
205
302
  }
206
303
  except ImportError:
207
304
  # 如果没有 PIL,回退到原始方式(不压缩)
@@ -209,6 +306,507 @@ class BasicMobileToolsLite:
209
306
  except Exception as e:
210
307
  return {"success": False, "message": f"❌ 截图失败: {e}"}
211
308
 
309
+ def take_screenshot_with_grid(self, grid_size: int = 100, show_popup_hints: bool = True) -> Dict:
310
+ """截图并添加网格坐标标注(用于精确定位元素)
311
+
312
+ 在截图上绘制网格线和坐标刻度,帮助快速定位元素位置。
313
+ 如果检测到弹窗,会标注弹窗区域和可能的关闭按钮位置。
314
+
315
+ Args:
316
+ grid_size: 网格间距(像素),默认 100。建议值:50-200
317
+ show_popup_hints: 是否显示弹窗关闭按钮提示位置,默认 True
318
+
319
+ Returns:
320
+ 包含标注截图路径和弹窗信息的字典
321
+ """
322
+ try:
323
+ from PIL import Image, ImageDraw, ImageFont
324
+ import re
325
+
326
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
327
+ platform = "ios" if self._is_ios() else "android"
328
+
329
+ # 第1步:截图
330
+ temp_filename = f"temp_grid_{timestamp}.png"
331
+ temp_path = self.screenshot_dir / temp_filename
332
+
333
+ screen_width, screen_height = 0, 0
334
+ if self._is_ios():
335
+ ios_client = self._get_ios_client()
336
+ if ios_client and hasattr(ios_client, 'wda'):
337
+ ios_client.wda.screenshot(str(temp_path))
338
+ size = ios_client.wda.window_size()
339
+ screen_width, screen_height = size[0], size[1]
340
+ else:
341
+ return {"success": False, "message": "❌ iOS 客户端未初始化"}
342
+ else:
343
+ self.client.u2.screenshot(str(temp_path))
344
+ info = self.client.u2.info
345
+ screen_width = info.get('displayWidth', 720)
346
+ screen_height = info.get('displayHeight', 1280)
347
+
348
+ img = Image.open(temp_path)
349
+ draw = ImageDraw.Draw(img, 'RGBA')
350
+
351
+ # 尝试加载字体
352
+ try:
353
+ font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 14)
354
+ font_small = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 11)
355
+ except:
356
+ font = ImageFont.load_default()
357
+ font_small = font
358
+
359
+ img_width, img_height = img.size
360
+
361
+ # 第2步:绘制网格线和坐标
362
+ grid_color = (255, 0, 0, 80) # 半透明红色
363
+ text_color = (255, 0, 0, 200) # 红色文字
364
+
365
+ # 绘制垂直网格线
366
+ for x in range(0, img_width, grid_size):
367
+ draw.line([(x, 0), (x, img_height)], fill=grid_color, width=1)
368
+ # 顶部标注 X 坐标
369
+ draw.text((x + 2, 2), str(x), fill=text_color, font=font_small)
370
+
371
+ # 绘制水平网格线
372
+ for y in range(0, img_height, grid_size):
373
+ draw.line([(0, y), (img_width, y)], fill=grid_color, width=1)
374
+ # 左侧标注 Y 坐标
375
+ draw.text((2, y + 2), str(y), fill=text_color, font=font_small)
376
+
377
+ # 第3步:检测弹窗并标注
378
+ popup_info = None
379
+ close_positions = []
380
+
381
+ if show_popup_hints and not self._is_ios():
382
+ try:
383
+ import xml.etree.ElementTree as ET
384
+ xml_string = self._get_full_hierarchy()
385
+ root = ET.fromstring(xml_string)
386
+
387
+ # 检测弹窗区域
388
+ popup_bounds = None
389
+ for elem in root.iter():
390
+ bounds_str = elem.attrib.get('bounds', '')
391
+ class_name = elem.attrib.get('class', '')
392
+
393
+ if not bounds_str:
394
+ continue
395
+
396
+ match = re.match(r'\[(\d+),(\d+)\]\[(\d+),(\d+)\]', bounds_str)
397
+ if not match:
398
+ continue
399
+
400
+ x1, y1, x2, y2 = map(int, match.groups())
401
+ width = x2 - x1
402
+ height = y2 - y1
403
+ area = width * height
404
+ screen_area = screen_width * screen_height
405
+
406
+ is_container = any(kw in class_name for kw in ['Layout', 'View', 'Dialog', 'Card'])
407
+ area_ratio = area / screen_area if screen_area > 0 else 0
408
+ is_not_fullscreen = (width < screen_width * 0.98 or height < screen_height * 0.98)
409
+ is_reasonable_size = 0.08 < area_ratio < 0.85
410
+
411
+ if is_container and is_not_fullscreen and is_reasonable_size and y1 > 50:
412
+ if popup_bounds is None or area > (popup_bounds[2] - popup_bounds[0]) * (popup_bounds[3] - popup_bounds[1]):
413
+ popup_bounds = (x1, y1, x2, y2)
414
+
415
+ if popup_bounds:
416
+ px1, py1, px2, py2 = popup_bounds
417
+ popup_width = px2 - px1
418
+ popup_height = py2 - py1
419
+
420
+ # 绘制弹窗边框(蓝色)
421
+ draw.rectangle([px1, py1, px2, py2], outline=(0, 100, 255, 200), width=3)
422
+ draw.text((px1 + 5, py1 + 5), f"弹窗区域", fill=(0, 100, 255), font=font)
423
+
424
+ # 计算可能的 X 按钮位置(基于弹窗尺寸动态计算,适配不同分辨率)
425
+ offset_x = max(25, int(popup_width * 0.05)) # 宽度的5%,最小25px
426
+ offset_y = max(25, int(popup_height * 0.04)) # 高度的4%,最小25px
427
+ outer_offset = max(15, int(popup_width * 0.025)) # 外部偏移
428
+
429
+ close_positions = [
430
+ {"name": "右上角内", "x": px2 - offset_x, "y": py1 + offset_y, "priority": 1},
431
+ {"name": "右上角外", "x": px2 + outer_offset, "y": py1 - outer_offset, "priority": 2},
432
+ {"name": "正上方", "x": (px1 + px2) // 2, "y": py1 - offset_y, "priority": 3},
433
+ {"name": "底部下方", "x": (px1 + px2) // 2, "y": py2 + offset_y, "priority": 4},
434
+ ]
435
+
436
+ # 绘制可能的 X 按钮位置(绿色圆圈 + 数字)
437
+ for i, pos in enumerate(close_positions):
438
+ cx, cy = pos["x"], pos["y"]
439
+ if 0 <= cx <= img_width and 0 <= cy <= img_height:
440
+ # 绿色圆圈
441
+ draw.ellipse([cx-15, cy-15, cx+15, cy+15],
442
+ outline=(0, 255, 0, 200), width=2)
443
+ # 数字标注
444
+ draw.text((cx-5, cy-8), str(i+1), fill=(0, 255, 0), font=font)
445
+ # 坐标标注
446
+ draw.text((cx+18, cy-8), f"({cx},{cy})", fill=(0, 255, 0), font=font_small)
447
+
448
+ popup_info = {
449
+ "bounds": f"[{px1},{py1}][{px2},{py2}]",
450
+ "width": px2 - px1,
451
+ "height": py2 - py1,
452
+ "close_positions": close_positions
453
+ }
454
+
455
+ except Exception as e:
456
+ pass # 弹窗检测失败不影响主功能
457
+
458
+ # 第4步:保存标注后的截图
459
+ filename = f"screenshot_{platform}_grid_{timestamp}.jpg"
460
+ final_path = self.screenshot_dir / filename
461
+
462
+ # 转换为 RGB 并保存
463
+ if img.mode in ('RGBA', 'LA', 'P'):
464
+ background = Image.new('RGB', img.size, (255, 255, 255))
465
+ if img.mode == 'P':
466
+ img = img.convert('RGBA')
467
+ background.paste(img, mask=img.split()[-1] if img.mode == 'RGBA' else None)
468
+ img = background
469
+ elif img.mode != 'RGB':
470
+ img = img.convert("RGB")
471
+
472
+ img.save(str(final_path), "JPEG", quality=85)
473
+ temp_path.unlink()
474
+
475
+ result = {
476
+ "success": True,
477
+ "screenshot_path": str(final_path),
478
+ "screen_width": screen_width,
479
+ "screen_height": screen_height,
480
+ "image_width": img_width,
481
+ "image_height": img_height,
482
+ "grid_size": grid_size,
483
+ "message": f"📸 网格截图已保存: {final_path}\n"
484
+ f"📐 尺寸: {img_width}x{img_height}\n"
485
+ f"📏 网格间距: {grid_size}px"
486
+ }
487
+
488
+ if popup_info:
489
+ result["popup_detected"] = True
490
+ result["popup_bounds"] = popup_info["bounds"]
491
+ result["close_button_hints"] = close_positions
492
+ result["message"] += f"\n🎯 检测到弹窗: {popup_info['bounds']}"
493
+ result["message"] += f"\n💡 可能的关闭按钮位置(绿色圆圈标注):"
494
+ for pos in close_positions:
495
+ result["message"] += f"\n {pos['priority']}. {pos['name']}: ({pos['x']}, {pos['y']})"
496
+ else:
497
+ result["popup_detected"] = False
498
+
499
+ return result
500
+
501
+ except ImportError:
502
+ return {"success": False, "message": "❌ 需要安装 Pillow: pip install Pillow"}
503
+ except Exception as e:
504
+ return {"success": False, "message": f"❌ 网格截图失败: {e}"}
505
+
506
+ def take_screenshot_with_som(self) -> Dict:
507
+ """Set-of-Mark 截图:给每个可点击元素标上数字(超级好用!)
508
+
509
+ 在截图上给每个可点击元素画框并标上数字编号。
510
+ AI 看图后直接说"点击 3 号",然后调用 click_by_som(3) 即可。
511
+
512
+ Returns:
513
+ 包含标注截图和元素列表的字典
514
+ """
515
+ try:
516
+ from PIL import Image, ImageDraw, ImageFont
517
+ import re
518
+
519
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
520
+ platform = "ios" if self._is_ios() else "android"
521
+
522
+ # 第1步:截图
523
+ temp_filename = f"temp_som_{timestamp}.png"
524
+ temp_path = self.screenshot_dir / temp_filename
525
+
526
+ screen_width, screen_height = 0, 0
527
+ if self._is_ios():
528
+ ios_client = self._get_ios_client()
529
+ if ios_client and hasattr(ios_client, 'wda'):
530
+ ios_client.wda.screenshot(str(temp_path))
531
+ size = ios_client.wda.window_size()
532
+ screen_width, screen_height = size[0], size[1]
533
+ else:
534
+ return {"success": False, "message": "❌ iOS 客户端未初始化"}
535
+ else:
536
+ self.client.u2.screenshot(str(temp_path))
537
+ info = self.client.u2.info
538
+ screen_width = info.get('displayWidth', 720)
539
+ screen_height = info.get('displayHeight', 1280)
540
+
541
+ img = Image.open(temp_path)
542
+ draw = ImageDraw.Draw(img, 'RGBA')
543
+ img_width, img_height = img.size
544
+
545
+ # 尝试加载字体
546
+ try:
547
+ font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 16)
548
+ font_small = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 12)
549
+ except:
550
+ font = ImageFont.load_default()
551
+ font_small = font
552
+
553
+ # 第2步:获取所有可点击元素
554
+ elements = []
555
+ if self._is_ios():
556
+ # iOS 暂不支持
557
+ pass
558
+ else:
559
+ try:
560
+ import xml.etree.ElementTree as ET
561
+ xml_string = self._get_full_hierarchy()
562
+ root = ET.fromstring(xml_string)
563
+
564
+ for elem in root.iter():
565
+ clickable = elem.attrib.get('clickable', 'false') == 'true'
566
+ bounds_str = elem.attrib.get('bounds', '')
567
+ text = elem.attrib.get('text', '')
568
+ content_desc = elem.attrib.get('content-desc', '')
569
+ resource_id = elem.attrib.get('resource-id', '')
570
+ class_name = elem.attrib.get('class', '')
571
+
572
+ if not clickable or not bounds_str:
573
+ continue
574
+
575
+ match = re.match(r'\[(\d+),(\d+)\]\[(\d+),(\d+)\]', bounds_str)
576
+ if not match:
577
+ continue
578
+
579
+ x1, y1, x2, y2 = map(int, match.groups())
580
+ width = x2 - x1
581
+ height = y2 - y1
582
+
583
+ # 过滤太小或太大的元素
584
+ if width < 20 or height < 20:
585
+ continue
586
+ if width >= screen_width * 0.98 and height >= screen_height * 0.5:
587
+ continue # 全屏或大面积容器
588
+
589
+ center_x = (x1 + x2) // 2
590
+ center_y = (y1 + y2) // 2
591
+
592
+ # 生成描述
593
+ desc = text or content_desc or resource_id.split('/')[-1] if resource_id else class_name.split('.')[-1]
594
+ if len(desc) > 20:
595
+ desc = desc[:17] + "..."
596
+
597
+ elements.append({
598
+ 'bounds': (x1, y1, x2, y2),
599
+ 'center': (center_x, center_y),
600
+ 'text': text,
601
+ 'desc': desc,
602
+ 'resource_id': resource_id
603
+ })
604
+ except Exception as e:
605
+ pass
606
+
607
+ # 第3步:在截图上标注元素
608
+ # 颜色列表(循环使用)
609
+ colors = [
610
+ (255, 0, 0), # 红
611
+ (0, 255, 0), # 绿
612
+ (0, 100, 255), # 蓝
613
+ (255, 165, 0), # 橙
614
+ (255, 0, 255), # 紫
615
+ (0, 255, 255), # 青
616
+ ]
617
+
618
+ som_elements = [] # 保存标注信息,供 click_by_som 使用
619
+
620
+ for i, elem in enumerate(elements):
621
+ x1, y1, x2, y2 = elem['bounds']
622
+ cx, cy = elem['center']
623
+ color = colors[i % len(colors)]
624
+
625
+ # 画边框
626
+ draw.rectangle([x1, y1, x2, y2], outline=color + (200,), width=2)
627
+
628
+ # 画编号标签背景
629
+ label = str(i + 1)
630
+ label_w, label_h = 20, 18
631
+ label_x = x1
632
+ label_y = max(0, y1 - label_h - 2)
633
+ draw.rectangle([label_x, label_y, label_x + label_w, label_y + label_h],
634
+ fill=color + (220,))
635
+
636
+ # 画编号文字
637
+ draw.text((label_x + 4, label_y + 1), label, fill=(255, 255, 255), font=font_small)
638
+
639
+ som_elements.append({
640
+ 'index': i + 1,
641
+ 'center': (cx, cy),
642
+ 'bounds': f"[{x1},{y1}][{x2},{y2}]",
643
+ 'desc': elem['desc']
644
+ })
645
+
646
+ # 第3.5步:检测弹窗区域(用于标注)
647
+ popup_bounds = None
648
+
649
+ if not self._is_ios():
650
+ try:
651
+ # 检测弹窗区域
652
+ for elem in root.iter():
653
+ bounds_str = elem.attrib.get('bounds', '')
654
+ class_name = elem.attrib.get('class', '')
655
+
656
+ if not bounds_str:
657
+ continue
658
+
659
+ match = re.match(r'\[(\d+),(\d+)\]\[(\d+),(\d+)\]', bounds_str)
660
+ if not match:
661
+ continue
662
+
663
+ px1, py1, px2, py2 = map(int, match.groups())
664
+ p_width = px2 - px1
665
+ p_height = py2 - py1
666
+ p_area = p_width * p_height
667
+ screen_area = screen_width * screen_height
668
+
669
+ is_container = any(kw in class_name for kw in ['Layout', 'View', 'Dialog', 'Card', 'Frame'])
670
+ area_ratio = p_area / screen_area if screen_area > 0 else 0
671
+ is_not_fullscreen = (p_width < screen_width * 0.99 or p_height < screen_height * 0.95)
672
+ # 放宽面积范围:5% - 95%
673
+ is_reasonable_size = 0.05 < area_ratio < 0.95
674
+
675
+ if is_container and is_not_fullscreen and is_reasonable_size and py1 > 30:
676
+ if popup_bounds is None or p_area > (popup_bounds[2] - popup_bounds[0]) * (popup_bounds[3] - popup_bounds[1]):
677
+ popup_bounds = (px1, py1, px2, py2)
678
+
679
+ # 如果检测到弹窗,标注弹窗边界(不再猜测X按钮位置)
680
+ if popup_bounds:
681
+ px1, py1, px2, py2 = popup_bounds
682
+
683
+ # 只画弹窗边框(蓝色),不再猜测X按钮位置
684
+ draw.rectangle([px1, py1, px2, py2], outline=(0, 150, 255, 180), width=3)
685
+
686
+ # 在弹窗边框上标注提示文字
687
+ try:
688
+ draw.text((px1+5, py1-25), "弹窗区域", fill=(0, 150, 255), font=font_small)
689
+ except:
690
+ pass
691
+
692
+ except Exception as e:
693
+ pass # 弹窗检测失败不影响主功能
694
+
695
+ # 保存到实例变量,供 click_by_som 使用
696
+ self._som_elements = som_elements
697
+
698
+ # 第4步:保存标注后的截图
699
+ filename = f"screenshot_{platform}_som_{timestamp}.jpg"
700
+ final_path = self.screenshot_dir / filename
701
+
702
+ if img.mode in ('RGBA', 'LA', 'P'):
703
+ background = Image.new('RGB', img.size, (255, 255, 255))
704
+ if img.mode == 'P':
705
+ img = img.convert('RGBA')
706
+ background.paste(img, mask=img.split()[-1] if img.mode == 'RGBA' else None)
707
+ img = background
708
+ elif img.mode != 'RGB':
709
+ img = img.convert("RGB")
710
+
711
+ img.save(str(final_path), "JPEG", quality=85)
712
+ temp_path.unlink()
713
+
714
+ # 构建元素列表文字
715
+ elements_text = "\n".join([
716
+ f" [{e['index']}] {e['desc']} → ({e['center'][0]}, {e['center'][1]})"
717
+ for e in som_elements[:15] # 只显示前15个
718
+ ])
719
+ if len(som_elements) > 15:
720
+ elements_text += f"\n ... 还有 {len(som_elements) - 15} 个元素"
721
+
722
+ # 构建弹窗提示文字
723
+ hints_text = ""
724
+ if popup_bounds:
725
+ hints_text = f"\n🎯 检测到弹窗区域(蓝色边框)\n"
726
+ hints_text += f" 如需关闭弹窗,请观察图片中的 X 按钮位置\n"
727
+ hints_text += f" 然后使用 mobile_click_by_percent(x%, y%) 点击"
728
+
729
+ return {
730
+ "success": True,
731
+ "screenshot_path": str(final_path),
732
+ "screen_width": screen_width,
733
+ "screen_height": screen_height,
734
+ "image_width": img_width,
735
+ "image_height": img_height,
736
+ "element_count": len(som_elements),
737
+ "elements": som_elements,
738
+ "popup_detected": popup_bounds is not None,
739
+ "popup_bounds": f"[{popup_bounds[0]},{popup_bounds[1]}][{popup_bounds[2]},{popup_bounds[3]}]" if popup_bounds else None,
740
+ "message": f"📸 SoM 截图已保存: {final_path}\n"
741
+ f"🏷️ 已标注 {len(som_elements)} 个可点击元素\n"
742
+ f"📋 元素列表:\n{elements_text}{hints_text}\n\n"
743
+ f"💡 使用方法:\n"
744
+ f" - 点击标注元素:mobile_click_by_som(编号)\n"
745
+ f" - 点击任意位置:mobile_click_by_percent(x%, y%)"
746
+ }
747
+
748
+ except ImportError:
749
+ return {"success": False, "message": "❌ 需要安装 Pillow: pip install Pillow"}
750
+ except Exception as e:
751
+ return {"success": False, "message": f"❌ SoM 截图失败: {e}"}
752
+
753
+ def click_by_som(self, index: int) -> Dict:
754
+ """根据 SoM 编号点击元素
755
+
756
+ 配合 take_screenshot_with_som 使用。
757
+ 看图后直接说"点击 3 号",调用此函数即可。
758
+
759
+ Args:
760
+ index: 元素编号(从 1 开始)
761
+
762
+ Returns:
763
+ 点击结果
764
+ """
765
+ try:
766
+ if not hasattr(self, '_som_elements') or not self._som_elements:
767
+ return {
768
+ "success": False,
769
+ "message": "❌ 请先调用 mobile_screenshot_with_som 获取元素列表"
770
+ }
771
+
772
+ # 查找对应编号的元素
773
+ target = None
774
+ for elem in self._som_elements:
775
+ if elem['index'] == index:
776
+ target = elem
777
+ break
778
+
779
+ if not target:
780
+ return {
781
+ "success": False,
782
+ "message": f"❌ 未找到编号 {index} 的元素,有效范围: 1-{len(self._som_elements)}"
783
+ }
784
+
785
+ # 点击
786
+ cx, cy = target['center']
787
+ if self._is_ios():
788
+ ios_client = self._get_ios_client()
789
+ if ios_client and hasattr(ios_client, 'wda'):
790
+ ios_client.wda.click(cx, cy)
791
+ else:
792
+ self.client.u2.click(cx, cy)
793
+
794
+ time.sleep(0.3)
795
+
796
+ return {
797
+ "success": True,
798
+ "message": f"✅ 已点击 [{index}] {target['desc']} → ({cx}, {cy})\n💡 建议:再次截图确认操作是否成功",
799
+ "clicked": {
800
+ "index": index,
801
+ "desc": target['desc'],
802
+ "coords": (cx, cy),
803
+ "bounds": target['bounds']
804
+ }
805
+ }
806
+
807
+ except Exception as e:
808
+ return {"success": False, "message": f"❌ 点击失败: {e}\n💡 如果页面已变化,请重新调用 mobile_screenshot_with_som 刷新元素列表"}
809
+
212
810
  def _take_screenshot_no_compress(self, description: str = "") -> Dict:
213
811
  """截图(不压缩,PIL 不可用时的备用方案)"""
214
812
  try:
@@ -281,18 +879,24 @@ class BasicMobileToolsLite:
281
879
 
282
880
  # ==================== 点击操作 ====================
283
881
 
284
- def click_at_coords(self, x: int, y: int, image_width: int = 0, image_height: int = 0) -> Dict:
882
+ def click_at_coords(self, x: int, y: int, image_width: int = 0, image_height: int = 0,
883
+ crop_offset_x: int = 0, crop_offset_y: int = 0,
884
+ original_img_width: int = 0, original_img_height: int = 0) -> Dict:
285
885
  """点击坐标(核心功能,支持自动坐标转换)
286
886
 
287
887
  Args:
288
888
  x: X 坐标(来自截图分析或屏幕坐标)
289
889
  y: Y 坐标(来自截图分析或屏幕坐标)
290
- image_width: 截图的宽度(可选,传入后自动转换坐标)
291
- image_height: 截图的高度(可选,传入后自动转换坐标)
890
+ image_width: 压缩后图片宽度(AI 看到的图片尺寸)
891
+ image_height: 压缩后图片高度(AI 看到的图片尺寸)
892
+ crop_offset_x: 局部截图的 X 偏移量(局部截图时传入)
893
+ crop_offset_y: 局部截图的 Y 偏移量(局部截图时传入)
894
+ original_img_width: 截图原始宽度(压缩前的尺寸,用于精确转换)
895
+ original_img_height: 截图原始高度(压缩前的尺寸,用于精确转换)
292
896
 
293
897
  坐标转换说明:
294
- 如果截图被压缩过(如 1080→720),AI 返回的坐标是基于压缩图的。
295
- 传入 image_width/image_height 后,工具会自动将坐标转换为屏幕坐标。
898
+ 1. 全屏压缩截图:AI 坐标 → 原图坐标(基于 image/original_img 比例)
899
+ 2. 局部裁剪截图:AI 坐标 + 偏移量 = 屏幕坐标
296
900
  """
297
901
  try:
298
902
  # 获取屏幕尺寸
@@ -309,15 +913,30 @@ class BasicMobileToolsLite:
309
913
  screen_width = info.get('displayWidth', 0)
310
914
  screen_height = info.get('displayHeight', 0)
311
915
 
312
- # 🎯 坐标转换:如果传入了图片尺寸,将图片坐标转换为屏幕坐标
916
+ # 🎯 坐标转换
313
917
  original_x, original_y = x, y
314
918
  converted = False
315
- if image_width > 0 and image_height > 0 and screen_width > 0 and screen_height > 0:
316
- if image_width != screen_width or image_height != screen_height:
317
- # 按比例转换坐标
318
- x = int(x * screen_width / image_width)
319
- y = int(y * screen_height / image_height)
320
- converted = True
919
+ conversion_type = ""
920
+
921
+ # 情况1:局部裁剪截图 - 加上偏移量
922
+ if crop_offset_x > 0 or crop_offset_y > 0:
923
+ x = x + crop_offset_x
924
+ y = y + crop_offset_y
925
+ converted = True
926
+ conversion_type = "crop_offset"
927
+ # 情况2:全屏压缩截图 - 按比例转换到原图尺寸
928
+ elif image_width > 0 and image_height > 0:
929
+ # 优先使用 original_img_width/height(更精确)
930
+ # 如果没传,则用 screen_width/height(兼容旧版本)
931
+ target_width = original_img_width if original_img_width > 0 else screen_width
932
+ target_height = original_img_height if original_img_height > 0 else screen_height
933
+
934
+ if target_width > 0 and target_height > 0:
935
+ if image_width != target_width or image_height != target_height:
936
+ x = int(x * target_width / image_width)
937
+ y = int(y * target_height / image_height)
938
+ converted = True
939
+ conversion_type = "scale"
321
940
 
322
941
  # 执行点击
323
942
  if self._is_ios():
@@ -345,12 +964,19 @@ class BasicMobileToolsLite:
345
964
  )
346
965
 
347
966
  if converted:
348
- return {
349
- "success": True,
350
- "message": f"✅ 点击成功: ({x}, {y})\n"
351
- f" 📐 坐标已转换: ({original_x},{original_y}) → ({x},{y})\n"
352
- f" 🖼️ 图片尺寸: {image_width}x{image_height} → 屏幕: {screen_width}x{screen_height}"
353
- }
967
+ if conversion_type == "crop_offset":
968
+ return {
969
+ "success": True,
970
+ "message": f" 点击成功: ({x}, {y})\n"
971
+ f" 🔍 局部截图坐标转换: ({original_x},{original_y}) + 偏移({crop_offset_x},{crop_offset_y}) ({x},{y})"
972
+ }
973
+ else:
974
+ return {
975
+ "success": True,
976
+ "message": f"✅ 点击成功: ({x}, {y})\n"
977
+ f" 📐 坐标已转换: ({original_x},{original_y}) → ({x},{y})\n"
978
+ f" 🖼️ 图片尺寸: {image_width}x{image_height} → 屏幕: {screen_width}x{screen_height}"
979
+ }
354
980
  else:
355
981
  return {
356
982
  "success": True,
@@ -488,9 +1114,9 @@ class BasicMobileToolsLite:
488
1114
  return {"success": False, "message": f"❌ 点击失败: {e}"}
489
1115
 
490
1116
  def _find_element_in_tree(self, text: str) -> Optional[Dict]:
491
- """在 XML 树中查找包含指定文本的元素"""
1117
+ """在 XML 树中查找包含指定文本的元素(使用完整 UI 层级)"""
492
1118
  try:
493
- xml = self.client.u2.dump_hierarchy()
1119
+ xml = self._get_full_hierarchy()
494
1120
  import xml.etree.ElementTree as ET
495
1121
  root = ET.fromstring(xml)
496
1122
 
@@ -527,9 +1153,16 @@ class BasicMobileToolsLite:
527
1153
  except Exception:
528
1154
  return None
529
1155
 
530
- def click_by_id(self, resource_id: str) -> Dict:
531
- """通过 resource-id 点击"""
1156
+ def click_by_id(self, resource_id: str, index: int = 0) -> Dict:
1157
+ """通过 resource-id 点击(支持点击第 N 个元素)
1158
+
1159
+ Args:
1160
+ resource_id: 元素的 resource-id
1161
+ index: 第几个元素(从 0 开始),默认 0 表示第一个
1162
+ """
532
1163
  try:
1164
+ index_desc = f"[{index}]" if index > 0 else ""
1165
+
533
1166
  if self._is_ios():
534
1167
  ios_client = self._get_ios_client()
535
1168
  if ios_client and hasattr(ios_client, 'wda'):
@@ -537,103 +1170,475 @@ class BasicMobileToolsLite:
537
1170
  if not elem.exists:
538
1171
  elem = ios_client.wda(name=resource_id)
539
1172
  if elem.exists:
540
- elem.click()
541
- time.sleep(0.3)
542
- self._record_operation('click', element=resource_id, ref=resource_id)
543
- return {"success": True, "message": f"✅ 点击成功: {resource_id}"}
1173
+ # 获取所有匹配的元素
1174
+ elements = elem.find_elements()
1175
+ if index < len(elements):
1176
+ elements[index].click()
1177
+ time.sleep(0.3)
1178
+ self._record_operation('click', element=f"{resource_id}{index_desc}", ref=resource_id, index=index)
1179
+ return {"success": True, "message": f"✅ 点击成功: {resource_id}{index_desc}"}
1180
+ else:
1181
+ return {"success": False, "message": f"❌ 索引超出范围: 找到 {len(elements)} 个元素,但请求索引 {index}"}
544
1182
  return {"success": False, "message": f"❌ 元素不存在: {resource_id}"}
545
1183
  else:
546
1184
  elem = self.client.u2(resourceId=resource_id)
547
1185
  if elem.exists(timeout=0.5):
548
- elem.click()
549
- time.sleep(0.3)
550
- self._record_operation('click', element=resource_id, ref=resource_id)
551
- return {"success": True, "message": f"✅ 点击成功: {resource_id}"}
1186
+ # 获取匹配元素数量
1187
+ count = elem.count
1188
+ if index < count:
1189
+ elem[index].click()
1190
+ time.sleep(0.3)
1191
+ self._record_operation('click', element=f"{resource_id}{index_desc}", ref=resource_id, index=index)
1192
+ return {"success": True, "message": f"✅ 点击成功: {resource_id}{index_desc}" + (f" (共 {count} 个)" if count > 1 else "")}
1193
+ else:
1194
+ return {"success": False, "message": f"❌ 索引超出范围: 找到 {count} 个元素,但请求索引 {index}"}
552
1195
  return {"success": False, "message": f"❌ 元素不存在: {resource_id}"}
553
1196
  except Exception as e:
554
1197
  return {"success": False, "message": f"❌ 点击失败: {e}"}
555
1198
 
556
- # ==================== 输入操作 ====================
557
-
558
- def input_text_by_id(self, resource_id: str, text: str) -> Dict:
559
- """通过 resource-id 输入文本"""
560
- try:
561
- if self._is_ios():
562
- ios_client = self._get_ios_client()
563
- if ios_client and hasattr(ios_client, 'wda'):
564
- elem = ios_client.wda(id=resource_id)
565
- if not elem.exists:
566
- elem = ios_client.wda(name=resource_id)
567
- if elem.exists:
568
- elem.set_text(text)
569
- time.sleep(0.3)
570
- self._record_operation('input', element=resource_id, ref=resource_id, text=text)
571
- return {"success": True, "message": f"✅ 输入成功: '{text}'"}
572
- return {"success": False, "message": f"❌ 输入框不存在: {resource_id}"}
573
- else:
574
- elem = self.client.u2(resourceId=resource_id)
575
- if elem.exists(timeout=0.5):
576
- elem.set_text(text)
577
- time.sleep(0.3)
578
- self._record_operation('input', element=resource_id, ref=resource_id, text=text)
579
- return {"success": True, "message": f"✅ 输入成功: '{text}'"}
580
- return {"success": False, "message": f"❌ 输入框不存在: {resource_id}"}
581
- except Exception as e:
582
- return {"success": False, "message": f"❌ 输入失败: {e}"}
1199
+ # ==================== 长按操作 ====================
583
1200
 
584
- def input_at_coords(self, x: int, y: int, text: str) -> Dict:
585
- """点击坐标后输入文本(适合游戏)"""
1201
+ def long_press_at_coords(self, x: int, y: int, duration: float = 1.0,
1202
+ image_width: int = 0, image_height: int = 0,
1203
+ crop_offset_x: int = 0, crop_offset_y: int = 0,
1204
+ original_img_width: int = 0, original_img_height: int = 0) -> Dict:
1205
+ """长按坐标(核心功能,支持自动坐标转换)
1206
+
1207
+ Args:
1208
+ x: X 坐标(来自截图分析或屏幕坐标)
1209
+ y: Y 坐标(来自截图分析或屏幕坐标)
1210
+ duration: 长按持续时间(秒),默认 1.0
1211
+ image_width: 压缩后图片宽度(AI 看到的图片尺寸)
1212
+ image_height: 压缩后图片高度(AI 看到的图片尺寸)
1213
+ crop_offset_x: 局部截图的 X 偏移量(局部截图时传入)
1214
+ crop_offset_y: 局部截图的 Y 偏移量(局部截图时传入)
1215
+ original_img_width: 截图原始宽度(压缩前的尺寸,用于精确转换)
1216
+ original_img_height: 截图原始高度(压缩前的尺寸,用于精确转换)
1217
+
1218
+ 坐标转换说明:
1219
+ 1. 全屏压缩截图:AI 坐标 → 原图坐标(基于 image/original_img 比例)
1220
+ 2. 局部裁剪截图:AI 坐标 + 偏移量 = 屏幕坐标
1221
+ """
586
1222
  try:
587
- # 获取屏幕尺寸(用于转换百分比)
1223
+ # 获取屏幕尺寸
588
1224
  screen_width, screen_height = 0, 0
589
-
590
- # 先点击聚焦
591
1225
  if self._is_ios():
592
1226
  ios_client = self._get_ios_client()
593
1227
  if ios_client and hasattr(ios_client, 'wda'):
594
- ios_client.wda.click(x, y)
595
1228
  size = ios_client.wda.window_size()
596
1229
  screen_width, screen_height = size[0], size[1]
1230
+ else:
1231
+ return {"success": False, "message": "❌ iOS 客户端未初始化"}
597
1232
  else:
598
- self.client.u2.click(x, y)
599
1233
  info = self.client.u2.info
600
1234
  screen_width = info.get('displayWidth', 0)
601
1235
  screen_height = info.get('displayHeight', 0)
602
1236
 
603
- time.sleep(0.3)
1237
+ # 🎯 坐标转换
1238
+ original_x, original_y = x, y
1239
+ converted = False
1240
+ conversion_type = ""
604
1241
 
605
- # 输入文本
1242
+ # 情况1:局部裁剪截图 - 加上偏移量
1243
+ if crop_offset_x > 0 or crop_offset_y > 0:
1244
+ x = x + crop_offset_x
1245
+ y = y + crop_offset_y
1246
+ converted = True
1247
+ conversion_type = "crop_offset"
1248
+ # 情况2:全屏压缩截图 - 按比例转换到原图尺寸
1249
+ elif image_width > 0 and image_height > 0:
1250
+ target_width = original_img_width if original_img_width > 0 else screen_width
1251
+ target_height = original_img_height if original_img_height > 0 else screen_height
1252
+
1253
+ if target_width > 0 and target_height > 0:
1254
+ if image_width != target_width or image_height != target_height:
1255
+ x = int(x * target_width / image_width)
1256
+ y = int(y * target_height / image_height)
1257
+ converted = True
1258
+ conversion_type = "scale"
1259
+
1260
+ # 执行长按
606
1261
  if self._is_ios():
607
1262
  ios_client = self._get_ios_client()
608
- if ios_client and hasattr(ios_client, 'wda'):
609
- ios_client.wda.send_keys(text)
1263
+ # iOS 使用 tap_hold 或 swipe 原地实现长按
1264
+ if hasattr(ios_client.wda, 'tap_hold'):
1265
+ ios_client.wda.tap_hold(x, y, duration=duration)
1266
+ else:
1267
+ # 兜底:用原地 swipe 模拟长按
1268
+ ios_client.wda.swipe(x, y, x, y, duration=duration)
610
1269
  else:
611
- self.client.u2.send_keys(text)
1270
+ self.client.u2.long_click(x, y, duration=duration)
612
1271
 
613
1272
  time.sleep(0.3)
614
1273
 
615
- # 计算百分比坐标
1274
+ # 计算百分比坐标(用于跨设备兼容)
616
1275
  x_percent = round(x / screen_width * 100, 1) if screen_width > 0 else 0
617
1276
  y_percent = round(y / screen_height * 100, 1) if screen_height > 0 else 0
618
1277
 
1278
+ # 记录操作
619
1279
  self._record_operation(
620
- 'input',
1280
+ 'long_press',
621
1281
  x=x,
622
1282
  y=y,
623
1283
  x_percent=x_percent,
624
1284
  y_percent=y_percent,
625
- ref=f"coords_{x}_{y}",
626
- text=text
1285
+ duration=duration,
1286
+ screen_width=screen_width,
1287
+ screen_height=screen_height,
1288
+ ref=f"coords_{x}_{y}"
627
1289
  )
628
1290
 
629
- return {"success": True, "message": f"✅ 输入成功: ({x}, {y}) [相对位置: {x_percent}%, {y_percent}%] -> '{text}'"}
1291
+ if converted:
1292
+ if conversion_type == "crop_offset":
1293
+ return {
1294
+ "success": True,
1295
+ "message": f"✅ 长按成功: ({x}, {y}) 持续 {duration}s\n"
1296
+ f" 🔍 局部截图坐标转换: ({original_x},{original_y}) + 偏移({crop_offset_x},{crop_offset_y}) → ({x},{y})"
1297
+ }
1298
+ else:
1299
+ return {
1300
+ "success": True,
1301
+ "message": f"✅ 长按成功: ({x}, {y}) 持续 {duration}s\n"
1302
+ f" 📐 坐标已转换: ({original_x},{original_y}) → ({x},{y})\n"
1303
+ f" 🖼️ 图片尺寸: {image_width}x{image_height} → 屏幕: {screen_width}x{screen_height}"
1304
+ }
1305
+ else:
1306
+ return {
1307
+ "success": True,
1308
+ "message": f"✅ 长按成功: ({x}, {y}) 持续 {duration}s [相对位置: {x_percent}%, {y_percent}%]"
1309
+ }
630
1310
  except Exception as e:
631
- return {"success": False, "message": f"❌ 输入失败: {e}"}
1311
+ return {"success": False, "message": f"❌ 长按失败: {e}"}
1312
+
1313
+ def long_press_by_percent(self, x_percent: float, y_percent: float, duration: float = 1.0) -> Dict:
1314
+ """通过百分比坐标长按(跨设备兼容)
1315
+
1316
+ 百分比坐标原理:
1317
+ - 屏幕左上角是 (0%, 0%),右下角是 (100%, 100%)
1318
+ - 屏幕正中央是 (50%, 50%)
1319
+ - 像素坐标 = 屏幕尺寸 × (百分比 / 100)
1320
+
1321
+ Args:
1322
+ x_percent: X轴百分比 (0-100),0=最左,50=中间,100=最右
1323
+ y_percent: Y轴百分比 (0-100),0=最上,50=中间,100=最下
1324
+ duration: 长按持续时间(秒),默认 1.0
1325
+
1326
+ 优势:
1327
+ - 同样的百分比在不同分辨率设备上都能点到相同相对位置
1328
+ - 录制一次,多设备回放
1329
+ """
1330
+ try:
1331
+ # 第1步:获取屏幕尺寸
1332
+ if self._is_ios():
1333
+ ios_client = self._get_ios_client()
1334
+ if ios_client and hasattr(ios_client, 'wda'):
1335
+ size = ios_client.wda.window_size()
1336
+ width, height = size[0], size[1]
1337
+ else:
1338
+ return {"success": False, "message": "❌ iOS 客户端未初始化"}
1339
+ else:
1340
+ info = self.client.u2.info
1341
+ width = info.get('displayWidth', 0)
1342
+ height = info.get('displayHeight', 0)
1343
+
1344
+ if width == 0 or height == 0:
1345
+ return {"success": False, "message": "❌ 无法获取屏幕尺寸"}
1346
+
1347
+ # 第2步:百分比转像素坐标
1348
+ x = int(width * x_percent / 100)
1349
+ y = int(height * y_percent / 100)
1350
+
1351
+ # 第3步:执行长按
1352
+ if self._is_ios():
1353
+ ios_client = self._get_ios_client()
1354
+ if hasattr(ios_client.wda, 'tap_hold'):
1355
+ ios_client.wda.tap_hold(x, y, duration=duration)
1356
+ else:
1357
+ ios_client.wda.swipe(x, y, x, y, duration=duration)
1358
+ else:
1359
+ self.client.u2.long_click(x, y, duration=duration)
1360
+
1361
+ time.sleep(0.3)
1362
+
1363
+ # 第4步:记录操作
1364
+ self._record_operation(
1365
+ 'long_press',
1366
+ x=x,
1367
+ y=y,
1368
+ x_percent=x_percent,
1369
+ y_percent=y_percent,
1370
+ duration=duration,
1371
+ screen_width=width,
1372
+ screen_height=height,
1373
+ ref=f"percent_{x_percent}_{y_percent}"
1374
+ )
1375
+
1376
+ return {
1377
+ "success": True,
1378
+ "message": f"✅ 百分比长按成功: ({x_percent}%, {y_percent}%) → 像素({x}, {y}) 持续 {duration}s",
1379
+ "screen_size": {"width": width, "height": height},
1380
+ "percent": {"x": x_percent, "y": y_percent},
1381
+ "pixel": {"x": x, "y": y},
1382
+ "duration": duration
1383
+ }
1384
+ except Exception as e:
1385
+ return {"success": False, "message": f"❌ 百分比长按失败: {e}"}
1386
+
1387
+ def long_press_by_text(self, text: str, duration: float = 1.0) -> Dict:
1388
+ """通过文本长按
1389
+
1390
+ Args:
1391
+ text: 元素的文本内容(精确匹配)
1392
+ duration: 长按持续时间(秒),默认 1.0
1393
+ """
1394
+ try:
1395
+ if self._is_ios():
1396
+ ios_client = self._get_ios_client()
1397
+ if ios_client and hasattr(ios_client, 'wda'):
1398
+ elem = ios_client.wda(name=text)
1399
+ if not elem.exists:
1400
+ elem = ios_client.wda(label=text)
1401
+ if elem.exists:
1402
+ # iOS 元素长按
1403
+ bounds = elem.bounds
1404
+ x = int((bounds.x + bounds.x + bounds.width) / 2)
1405
+ y = int((bounds.y + bounds.y + bounds.height) / 2)
1406
+ if hasattr(ios_client.wda, 'tap_hold'):
1407
+ ios_client.wda.tap_hold(x, y, duration=duration)
1408
+ else:
1409
+ ios_client.wda.swipe(x, y, x, y, duration=duration)
1410
+ time.sleep(0.3)
1411
+ self._record_operation('long_press', element=text, duration=duration, ref=text)
1412
+ return {"success": True, "message": f"✅ 长按成功: '{text}' 持续 {duration}s"}
1413
+ return {"success": False, "message": f"❌ 文本不存在: {text}"}
1414
+ else:
1415
+ # 先查 XML 树,找到元素
1416
+ found_elem = self._find_element_in_tree(text)
1417
+
1418
+ if found_elem:
1419
+ attr_type = found_elem['attr_type']
1420
+ attr_value = found_elem['attr_value']
1421
+ bounds = found_elem.get('bounds')
1422
+
1423
+ # 根据找到的属性类型,使用对应的选择器
1424
+ if attr_type == 'text':
1425
+ elem = self.client.u2(text=attr_value)
1426
+ elif attr_type == 'textContains':
1427
+ elem = self.client.u2(textContains=attr_value)
1428
+ elif attr_type == 'description':
1429
+ elem = self.client.u2(description=attr_value)
1430
+ elif attr_type == 'descriptionContains':
1431
+ elem = self.client.u2(descriptionContains=attr_value)
1432
+ else:
1433
+ elem = None
1434
+
1435
+ if elem and elem.exists(timeout=1):
1436
+ elem.long_click(duration=duration)
1437
+ time.sleep(0.3)
1438
+ self._record_operation('long_press', element=text, duration=duration, ref=f"{attr_type}:{attr_value}")
1439
+ return {"success": True, "message": f"✅ 长按成功({attr_type}): '{text}' 持续 {duration}s"}
1440
+
1441
+ # 如果选择器失败,用坐标兜底
1442
+ if bounds:
1443
+ x = (bounds[0] + bounds[2]) // 2
1444
+ y = (bounds[1] + bounds[3]) // 2
1445
+ self.client.u2.long_click(x, y, duration=duration)
1446
+ time.sleep(0.3)
1447
+ self._record_operation('long_press', element=text, x=x, y=y, duration=duration, ref=f"coords:{x},{y}")
1448
+ return {"success": True, "message": f"✅ 长按成功(坐标兜底): '{text}' @ ({x},{y}) 持续 {duration}s"}
1449
+
1450
+ return {"success": False, "message": f"❌ 文本不存在: {text}"}
1451
+ except Exception as e:
1452
+ return {"success": False, "message": f"❌ 长按失败: {e}"}
1453
+
1454
+ def long_press_by_id(self, resource_id: str, duration: float = 1.0) -> Dict:
1455
+ """通过 resource-id 长按
1456
+
1457
+ Args:
1458
+ resource_id: 元素的 resource-id
1459
+ duration: 长按持续时间(秒),默认 1.0
1460
+ """
1461
+ try:
1462
+ if self._is_ios():
1463
+ ios_client = self._get_ios_client()
1464
+ if ios_client and hasattr(ios_client, 'wda'):
1465
+ elem = ios_client.wda(id=resource_id)
1466
+ if not elem.exists:
1467
+ elem = ios_client.wda(name=resource_id)
1468
+ if elem.exists:
1469
+ bounds = elem.bounds
1470
+ x = int((bounds.x + bounds.x + bounds.width) / 2)
1471
+ y = int((bounds.y + bounds.y + bounds.height) / 2)
1472
+ if hasattr(ios_client.wda, 'tap_hold'):
1473
+ ios_client.wda.tap_hold(x, y, duration=duration)
1474
+ else:
1475
+ ios_client.wda.swipe(x, y, x, y, duration=duration)
1476
+ time.sleep(0.3)
1477
+ self._record_operation('long_press', element=resource_id, duration=duration, ref=resource_id)
1478
+ return {"success": True, "message": f"✅ 长按成功: {resource_id} 持续 {duration}s"}
1479
+ return {"success": False, "message": f"❌ 元素不存在: {resource_id}"}
1480
+ else:
1481
+ elem = self.client.u2(resourceId=resource_id)
1482
+ if elem.exists(timeout=0.5):
1483
+ elem.long_click(duration=duration)
1484
+ time.sleep(0.3)
1485
+ self._record_operation('long_press', element=resource_id, duration=duration, ref=resource_id)
1486
+ return {"success": True, "message": f"✅ 长按成功: {resource_id} 持续 {duration}s"}
1487
+ return {"success": False, "message": f"❌ 元素不存在: {resource_id}"}
1488
+ except Exception as e:
1489
+ return {"success": False, "message": f"❌ 长按失败: {e}"}
1490
+
1491
+ # ==================== 输入操作 ====================
1492
+
1493
+ def input_text_by_id(self, resource_id: str, text: str) -> Dict:
1494
+ """通过 resource-id 输入文本
1495
+
1496
+ 优化策略:
1497
+ 1. 先用 resourceId 定位
1498
+ 2. 如果只有 1 个元素 → 直接输入
1499
+ 3. 如果有多个相同 ID(>5个说明 ID 不可靠)→ 改用 EditText 类型定位
1500
+ 4. 多个 EditText 时选择最靠上的(搜索框通常在顶部)
1501
+ """
1502
+ try:
1503
+ if self._is_ios():
1504
+ ios_client = self._get_ios_client()
1505
+ if ios_client and hasattr(ios_client, 'wda'):
1506
+ elem = ios_client.wda(id=resource_id)
1507
+ if not elem.exists:
1508
+ elem = ios_client.wda(name=resource_id)
1509
+ if elem.exists:
1510
+ elem.set_text(text)
1511
+ time.sleep(0.3)
1512
+ self._record_operation('input', element=resource_id, ref=resource_id, text=text)
1513
+ return {"success": True, "message": f"✅ 输入成功: '{text}'"}
1514
+ return {"success": False, "message": f"❌ 输入框不存在: {resource_id}"}
1515
+ else:
1516
+ elements = self.client.u2(resourceId=resource_id)
1517
+
1518
+ # 检查是否存在
1519
+ if elements.exists(timeout=0.5):
1520
+ count = elements.count
1521
+
1522
+ # 只有 1 个元素,直接输入
1523
+ if count == 1:
1524
+ elements.set_text(text)
1525
+ time.sleep(0.3)
1526
+ self._record_operation('input', element=resource_id, ref=resource_id, text=text)
1527
+ return {"success": True, "message": f"✅ 输入成功: '{text}'"}
1528
+
1529
+ # 多个相同 ID(<=5个),尝试智能选择
1530
+ if count <= 5:
1531
+ for i in range(count):
1532
+ try:
1533
+ elem = elements[i]
1534
+ info = elem.info
1535
+ # 优先选择可编辑的
1536
+ if info.get('editable') or info.get('focusable'):
1537
+ elem.set_text(text)
1538
+ time.sleep(0.3)
1539
+ self._record_operation('input', element=resource_id, ref=resource_id, text=text)
1540
+ return {"success": True, "message": f"✅ 输入成功: '{text}'"}
1541
+ except:
1542
+ continue
1543
+ # 没找到可编辑的,用第一个
1544
+ elements[0].set_text(text)
1545
+ time.sleep(0.3)
1546
+ self._record_operation('input', element=resource_id, ref=resource_id, text=text)
1547
+ return {"success": True, "message": f"✅ 输入成功: '{text}'"}
1548
+
1549
+ # ID 不可靠(不存在或太多),改用 EditText 类型定位
1550
+ edit_texts = self.client.u2(className='android.widget.EditText')
1551
+ if edit_texts.exists(timeout=0.5):
1552
+ et_count = edit_texts.count
1553
+ if et_count == 1:
1554
+ edit_texts.set_text(text)
1555
+ time.sleep(0.3)
1556
+ self._record_operation('input', element='EditText', ref='EditText', text=text)
1557
+ return {"success": True, "message": f"✅ 输入成功: '{text}' (通过 EditText 定位)"}
1558
+
1559
+ # 多个 EditText,选择最靠上的
1560
+ best_elem = None
1561
+ min_top = 9999
1562
+ for i in range(et_count):
1563
+ try:
1564
+ elem = edit_texts[i]
1565
+ top = elem.info.get('bounds', {}).get('top', 9999)
1566
+ if top < min_top:
1567
+ min_top = top
1568
+ best_elem = elem
1569
+ except:
1570
+ continue
1571
+
1572
+ if best_elem:
1573
+ best_elem.set_text(text)
1574
+ time.sleep(0.3)
1575
+ self._record_operation('input', element='EditText', ref='EditText', text=text)
1576
+ return {"success": True, "message": f"✅ 输入成功: '{text}' (通过 EditText 定位,选择最顶部的)"}
1577
+
1578
+ return {"success": False, "message": f"❌ 输入框不存在: {resource_id}"}
1579
+
1580
+ except Exception as e:
1581
+ return {"success": False, "message": f"❌ 输入失败: {e}"}
1582
+
1583
+ def input_at_coords(self, x: int, y: int, text: str) -> Dict:
1584
+ """点击坐标后输入文本(适合游戏)"""
1585
+ try:
1586
+ # 获取屏幕尺寸(用于转换百分比)
1587
+ screen_width, screen_height = 0, 0
1588
+
1589
+ # 先点击聚焦
1590
+ if self._is_ios():
1591
+ ios_client = self._get_ios_client()
1592
+ if ios_client and hasattr(ios_client, 'wda'):
1593
+ ios_client.wda.click(x, y)
1594
+ size = ios_client.wda.window_size()
1595
+ screen_width, screen_height = size[0], size[1]
1596
+ else:
1597
+ self.client.u2.click(x, y)
1598
+ info = self.client.u2.info
1599
+ screen_width = info.get('displayWidth', 0)
1600
+ screen_height = info.get('displayHeight', 0)
1601
+
1602
+ time.sleep(0.3)
1603
+
1604
+ # 输入文本
1605
+ if self._is_ios():
1606
+ ios_client = self._get_ios_client()
1607
+ if ios_client and hasattr(ios_client, 'wda'):
1608
+ ios_client.wda.send_keys(text)
1609
+ else:
1610
+ self.client.u2.send_keys(text)
1611
+
1612
+ time.sleep(0.3)
1613
+
1614
+ # 计算百分比坐标
1615
+ x_percent = round(x / screen_width * 100, 1) if screen_width > 0 else 0
1616
+ y_percent = round(y / screen_height * 100, 1) if screen_height > 0 else 0
1617
+
1618
+ self._record_operation(
1619
+ 'input',
1620
+ x=x,
1621
+ y=y,
1622
+ x_percent=x_percent,
1623
+ y_percent=y_percent,
1624
+ ref=f"coords_{x}_{y}",
1625
+ text=text
1626
+ )
1627
+
1628
+ return {"success": True, "message": f"✅ 输入成功: ({x}, {y}) [相对位置: {x_percent}%, {y_percent}%] -> '{text}'"}
1629
+ except Exception as e:
1630
+ return {"success": False, "message": f"❌ 输入失败: {e}"}
632
1631
 
633
1632
  # ==================== 导航操作 ====================
634
1633
 
635
- async def swipe(self, direction: str) -> Dict:
636
- """滑动屏幕"""
1634
+ async def swipe(self, direction: str, y: Optional[int] = None, y_percent: Optional[float] = None) -> Dict:
1635
+ """滑动屏幕
1636
+
1637
+ Args:
1638
+ direction: 滑动方向 (up/down/left/right)
1639
+ y: 左右滑动时指定的高度坐标(像素)
1640
+ y_percent: 左右滑动时指定的高度百分比 (0-100)
1641
+ """
637
1642
  try:
638
1643
  if self._is_ios():
639
1644
  ios_client = self._get_ios_client()
@@ -647,11 +1652,26 @@ class BasicMobileToolsLite:
647
1652
 
648
1653
  center_x, center_y = width // 2, height // 2
649
1654
 
1655
+ # 对于左右滑动,如果指定了 y 或 y_percent,使用指定的高度
1656
+ if direction in ['left', 'right']:
1657
+ if y_percent is not None:
1658
+ if not (0 <= y_percent <= 100):
1659
+ return {"success": False, "message": f"❌ y_percent 必须在 0-100 之间: {y_percent}"}
1660
+ swipe_y = int(height * y_percent / 100)
1661
+ elif y is not None:
1662
+ if not (0 <= y <= height):
1663
+ return {"success": False, "message": f"❌ y 坐标超出屏幕范围 (0-{height}): {y}"}
1664
+ swipe_y = y
1665
+ else:
1666
+ swipe_y = center_y
1667
+ else:
1668
+ swipe_y = center_y
1669
+
650
1670
  swipe_map = {
651
1671
  'up': (center_x, int(height * 0.8), center_x, int(height * 0.2)),
652
1672
  'down': (center_x, int(height * 0.2), center_x, int(height * 0.8)),
653
- 'left': (int(width * 0.8), center_y, int(width * 0.2), center_y),
654
- 'right': (int(width * 0.2), center_y, int(width * 0.8), center_y),
1673
+ 'left': (int(width * 0.8), swipe_y, int(width * 0.2), swipe_y),
1674
+ 'right': (int(width * 0.2), swipe_y, int(width * 0.8), swipe_y),
655
1675
  }
656
1676
 
657
1677
  if direction not in swipe_map:
@@ -664,9 +1684,23 @@ class BasicMobileToolsLite:
664
1684
  else:
665
1685
  self.client.u2.swipe(x1, y1, x2, y2, duration=0.5)
666
1686
 
667
- self._record_operation('swipe', direction=direction)
1687
+ # 记录操作信息
1688
+ record_info = {'direction': direction}
1689
+ if y is not None:
1690
+ record_info['y'] = y
1691
+ if y_percent is not None:
1692
+ record_info['y_percent'] = y_percent
1693
+ self._record_operation('swipe', **record_info)
1694
+
1695
+ # 构建返回消息
1696
+ msg = f"✅ 滑动成功: {direction}"
1697
+ if direction in ['left', 'right']:
1698
+ if y_percent is not None:
1699
+ msg += f" (高度: {y_percent}% = {swipe_y}px)"
1700
+ elif y is not None:
1701
+ msg += f" (高度: {y}px)"
668
1702
 
669
- return {"success": True, "message": f"✅ 滑动成功: {direction}"}
1703
+ return {"success": True, "message": msg}
670
1704
  except Exception as e:
671
1705
  return {"success": False, "message": f"❌ 滑动失败: {e}"}
672
1706
 
@@ -811,53 +1845,602 @@ class BasicMobileToolsLite:
811
1845
  "device": f"{info.get('brand', '')} {info.get('model', '')}"
812
1846
  }
813
1847
  except Exception as e:
814
- return {"success": False, "connected": False, "message": f"❌ 连接检查失败: {e}"}
815
-
816
- # ==================== 辅助工具 ====================
1848
+ return {"success": False, "connected": False, "message": f"❌ 连接检查失败: {e}"}
1849
+
1850
+ # ==================== 辅助工具 ====================
1851
+
1852
+ def list_elements(self) -> List[Dict]:
1853
+ """列出页面元素"""
1854
+ try:
1855
+ if self._is_ios():
1856
+ ios_client = self._get_ios_client()
1857
+ if ios_client and hasattr(ios_client, 'list_elements'):
1858
+ return ios_client.list_elements()
1859
+ return [{"error": "iOS 暂不支持元素列表,建议使用截图"}]
1860
+ else:
1861
+ xml_string = self._get_full_hierarchy()
1862
+ elements = self.client.xml_parser.parse(xml_string)
1863
+
1864
+ result = []
1865
+ for elem in elements:
1866
+ if elem.get('clickable') or elem.get('focusable'):
1867
+ result.append({
1868
+ 'resource_id': elem.get('resource_id', ''),
1869
+ 'text': elem.get('text', ''),
1870
+ 'content_desc': elem.get('content_desc', ''),
1871
+ 'bounds': elem.get('bounds', ''),
1872
+ 'clickable': elem.get('clickable', False)
1873
+ })
1874
+ return result
1875
+ except Exception as e:
1876
+ return [{"error": f"获取元素失败: {e}"}]
1877
+
1878
+ def find_close_button(self) -> Dict:
1879
+ """智能查找关闭按钮(不点击,只返回位置)
1880
+
1881
+ 从元素列表中找最可能的关闭按钮,返回其坐标和百分比位置。
1882
+ 适用于关闭弹窗广告等场景。
1883
+
1884
+ Returns:
1885
+ 包含关闭按钮位置信息的字典,或截图让 AI 分析
1886
+ """
1887
+ try:
1888
+ import re
1889
+
1890
+ if self._is_ios():
1891
+ return {"success": False, "message": "iOS 暂不支持,请使用截图+坐标点击"}
1892
+
1893
+ # 获取屏幕尺寸
1894
+ screen_width = self.client.u2.info.get('displayWidth', 720)
1895
+ screen_height = self.client.u2.info.get('displayHeight', 1280)
1896
+
1897
+ # 获取元素列表(使用完整 UI 层级)
1898
+ xml_string = self._get_full_hierarchy()
1899
+ import xml.etree.ElementTree as ET
1900
+ root = ET.fromstring(xml_string)
1901
+
1902
+ # 关闭按钮特征
1903
+ close_texts = ['×', 'X', 'x', '关闭', '取消', 'close', 'Close', '跳过', '知道了', '我知道了']
1904
+ candidates = []
1905
+
1906
+ for elem in root.iter():
1907
+ text = elem.attrib.get('text', '')
1908
+ content_desc = elem.attrib.get('content-desc', '')
1909
+ bounds_str = elem.attrib.get('bounds', '')
1910
+ class_name = elem.attrib.get('class', '')
1911
+ clickable = elem.attrib.get('clickable', 'false') == 'true'
1912
+
1913
+ if not bounds_str:
1914
+ continue
1915
+
1916
+ match = re.match(r'\[(\d+),(\d+)\]\[(\d+),(\d+)\]', bounds_str)
1917
+ if not match:
1918
+ continue
1919
+
1920
+ x1, y1, x2, y2 = map(int, match.groups())
1921
+ width = x2 - x1
1922
+ height = y2 - y1
1923
+ center_x = (x1 + x2) // 2
1924
+ center_y = (y1 + y2) // 2
1925
+
1926
+ # 计算百分比
1927
+ x_percent = round(center_x / screen_width * 100, 1)
1928
+ y_percent = round(center_y / screen_height * 100, 1)
1929
+
1930
+ score = 0
1931
+ reason = ""
1932
+
1933
+ # 策略1:关闭文本
1934
+ if text in close_texts:
1935
+ score = 100
1936
+ reason = f"文本='{text}'"
1937
+
1938
+ # 策略2:content-desc 包含关闭关键词
1939
+ elif any(kw in content_desc.lower() for kw in ['关闭', 'close', 'dismiss', '跳过']):
1940
+ score = 90
1941
+ reason = f"描述='{content_desc}'"
1942
+
1943
+ # 策略3:小尺寸的 clickable 元素(可能是 X 图标)
1944
+ elif clickable:
1945
+ min_size = max(20, int(screen_width * 0.03))
1946
+ max_size = max(120, int(screen_width * 0.12))
1947
+ if min_size <= width <= max_size and min_size <= height <= max_size:
1948
+ # 基于位置评分:角落位置加分
1949
+ rel_x = center_x / screen_width
1950
+ rel_y = center_y / screen_height
1951
+
1952
+ # 右上角得分最高
1953
+ if rel_x > 0.6 and rel_y < 0.5:
1954
+ score = 70 + (rel_x - 0.6) * 50 + (0.5 - rel_y) * 50
1955
+ reason = f"右上角小元素 {width}x{height}px"
1956
+ # 左上角
1957
+ elif rel_x < 0.4 and rel_y < 0.5:
1958
+ score = 60 + (0.4 - rel_x) * 50 + (0.5 - rel_y) * 50
1959
+ reason = f"左上角小元素 {width}x{height}px"
1960
+ # 其他位置的小元素
1961
+ elif 'Image' in class_name:
1962
+ score = 50
1963
+ reason = f"图片元素 {width}x{height}px"
1964
+ else:
1965
+ score = 40
1966
+ reason = f"小型可点击元素 {width}x{height}px"
1967
+
1968
+ if score > 0:
1969
+ candidates.append({
1970
+ 'score': score,
1971
+ 'reason': reason,
1972
+ 'bounds': bounds_str,
1973
+ 'center_x': center_x,
1974
+ 'center_y': center_y,
1975
+ 'x_percent': x_percent,
1976
+ 'y_percent': y_percent,
1977
+ 'size': f"{width}x{height}"
1978
+ })
1979
+
1980
+ if not candidates:
1981
+ # 没找到,截图让 AI 分析
1982
+ screenshot_result = self.take_screenshot(description="找关闭按钮", compress=True)
1983
+ return {
1984
+ "success": False,
1985
+ "message": "❌ 元素树未找到关闭按钮,已截图供 AI 分析",
1986
+ "screenshot": screenshot_result.get("screenshot_path", ""),
1987
+ "screen_size": {"width": screen_width, "height": screen_height},
1988
+ "image_size": {
1989
+ "width": screenshot_result.get("image_width"),
1990
+ "height": screenshot_result.get("image_height")
1991
+ },
1992
+ "original_size": {
1993
+ "width": screenshot_result.get("original_img_width"),
1994
+ "height": screenshot_result.get("original_img_height")
1995
+ },
1996
+ "tip": "请分析截图找到 X 关闭按钮,然后调用 mobile_click_by_percent(x_percent, y_percent)"
1997
+ }
1998
+
1999
+ # 按得分排序
2000
+ candidates.sort(key=lambda x: x['score'], reverse=True)
2001
+ best = candidates[0]
2002
+
2003
+ return {
2004
+ "success": True,
2005
+ "message": f"✅ 找到可能的关闭按钮",
2006
+ "best_candidate": {
2007
+ "reason": best['reason'],
2008
+ "center": {"x": best['center_x'], "y": best['center_y']},
2009
+ "percent": {"x": best['x_percent'], "y": best['y_percent']},
2010
+ "bounds": best['bounds'],
2011
+ "size": best['size'],
2012
+ "score": best['score']
2013
+ },
2014
+ "click_command": f"mobile_click_by_percent({best['x_percent']}, {best['y_percent']})",
2015
+ "other_candidates": [
2016
+ {"reason": c['reason'], "percent": f"({c['x_percent']}%, {c['y_percent']}%)", "score": c['score']}
2017
+ for c in candidates[1:4]
2018
+ ] if len(candidates) > 1 else [],
2019
+ "screen_size": {"width": screen_width, "height": screen_height}
2020
+ }
2021
+
2022
+ except Exception as e:
2023
+ return {"success": False, "message": f"❌ 查找关闭按钮失败: {e}"}
2024
+
2025
+ def close_popup(self) -> Dict:
2026
+ """智能关闭弹窗(改进版)
2027
+
2028
+ 核心改进:先检测弹窗区域,再在弹窗范围内查找关闭按钮
2029
+
2030
+ 策略(优先级从高到低):
2031
+ 1. 检测弹窗区域(非全屏的大面积容器)
2032
+ 2. 在弹窗边界内查找关闭相关的文本/描述(×、X、关闭、close 等)
2033
+ 3. 在弹窗边界内查找小尺寸的 clickable 元素(优先边角位置)
2034
+ 4. 如果都找不到,截图让 AI 视觉识别
2035
+
2036
+ 适配策略:
2037
+ - X 按钮可能在任意位置(上下左右都支持)
2038
+ - 使用百分比坐标记录,跨分辨率兼容
2039
+ """
2040
+ try:
2041
+ import re
2042
+ import xml.etree.ElementTree as ET
2043
+
2044
+ # 获取屏幕尺寸
2045
+ if self._is_ios():
2046
+ return {"success": False, "message": "iOS 暂不支持,请使用截图+坐标点击"}
2047
+
2048
+ screen_width = self.client.u2.info.get('displayWidth', 720)
2049
+ screen_height = self.client.u2.info.get('displayHeight', 1280)
2050
+
2051
+ # 获取原始 XML(使用完整 UI 层级)
2052
+ xml_string = self._get_full_hierarchy()
2053
+
2054
+ # 关闭按钮的文本特征
2055
+ close_texts = ['×', 'X', 'x', '关闭', '取消', 'close', 'Close', 'CLOSE', '跳过', '知道了']
2056
+ close_desc_keywords = ['关闭', 'close', 'dismiss', 'cancel', '跳过']
2057
+
2058
+ close_candidates = []
2059
+ popup_bounds = None # 弹窗区域
2060
+
2061
+ # 解析 XML
2062
+ try:
2063
+ root = ET.fromstring(xml_string)
2064
+ all_elements = list(root.iter())
2065
+
2066
+ # ===== 第一步:检测弹窗区域 =====
2067
+ # 弹窗特征:非全屏、面积较大、通常在屏幕中央的容器
2068
+ popup_containers = []
2069
+ for idx, elem in enumerate(all_elements):
2070
+ bounds_str = elem.attrib.get('bounds', '')
2071
+ class_name = elem.attrib.get('class', '')
2072
+
2073
+ if not bounds_str:
2074
+ continue
2075
+
2076
+ match = re.match(r'\[(\d+),(\d+)\]\[(\d+),(\d+)\]', bounds_str)
2077
+ if not match:
2078
+ continue
2079
+
2080
+ x1, y1, x2, y2 = map(int, match.groups())
2081
+ width = x2 - x1
2082
+ height = y2 - y1
2083
+ area = width * height
2084
+ screen_area = screen_width * screen_height
2085
+
2086
+ # 弹窗容器特征:
2087
+ # 1. 面积在屏幕的 10%-90% 之间(非全屏)
2088
+ # 2. 宽度或高度不等于屏幕尺寸
2089
+ # 3. 是容器类型(Layout/View/Dialog)
2090
+ is_container = any(kw in class_name for kw in ['Layout', 'View', 'Dialog', 'Card', 'Container'])
2091
+ area_ratio = area / screen_area
2092
+ is_not_fullscreen = (width < screen_width * 0.98 or height < screen_height * 0.98)
2093
+ is_reasonable_size = 0.08 < area_ratio < 0.9
2094
+
2095
+ # 排除状态栏区域(y1 通常很小)
2096
+ is_below_statusbar = y1 > 50
2097
+
2098
+ if is_container and is_not_fullscreen and is_reasonable_size and is_below_statusbar:
2099
+ popup_containers.append({
2100
+ 'bounds': (x1, y1, x2, y2),
2101
+ 'bounds_str': bounds_str,
2102
+ 'area': area,
2103
+ 'area_ratio': area_ratio,
2104
+ 'idx': idx, # 元素在 XML 中的顺序(越后越上层)
2105
+ 'class': class_name
2106
+ })
2107
+
2108
+ # 选择最可能的弹窗容器(优先选择:XML 顺序靠后 + 面积适中)
2109
+ if popup_containers:
2110
+ # 按 XML 顺序倒序(后出现的在上层),然后按面积适中程度排序
2111
+ popup_containers.sort(key=lambda x: (x['idx'], -abs(x['area_ratio'] - 0.3)), reverse=True)
2112
+ popup_bounds = popup_containers[0]['bounds']
2113
+
2114
+ # ===== 第二步:在弹窗范围内查找关闭按钮 =====
2115
+ for idx, elem in enumerate(all_elements):
2116
+ text = elem.attrib.get('text', '')
2117
+ content_desc = elem.attrib.get('content-desc', '')
2118
+ bounds_str = elem.attrib.get('bounds', '')
2119
+ class_name = elem.attrib.get('class', '')
2120
+ clickable = elem.attrib.get('clickable', 'false') == 'true'
2121
+
2122
+ if not bounds_str:
2123
+ continue
2124
+
2125
+ # 解析 bounds
2126
+ match = re.match(r'\[(\d+),(\d+)\]\[(\d+),(\d+)\]', bounds_str)
2127
+ if not match:
2128
+ continue
2129
+
2130
+ x1, y1, x2, y2 = map(int, match.groups())
2131
+ width = x2 - x1
2132
+ height = y2 - y1
2133
+ center_x = (x1 + x2) // 2
2134
+ center_y = (y1 + y2) // 2
2135
+
2136
+ # 如果检测到弹窗区域,检查元素是否在弹窗范围内或附近
2137
+ in_popup = True
2138
+ popup_edge_bonus = 0
2139
+ is_floating_close = False # 是否是浮动关闭按钮(在弹窗外部上方)
2140
+ if popup_bounds:
2141
+ px1, py1, px2, py2 = popup_bounds
2142
+
2143
+ # 关闭按钮可能在弹窗外部(常见设计:X 按钮浮在弹窗右上角外侧)
2144
+ # 扩大搜索范围:弹窗上方 200 像素,右侧 50 像素
2145
+ margin_top = 200 # 上方扩展范围(关闭按钮常在弹窗上方)
2146
+ margin_side = 50 # 左右扩展范围
2147
+ margin_bottom = 30 # 下方扩展范围
2148
+
2149
+ in_popup = (px1 - margin_side <= center_x <= px2 + margin_side and
2150
+ py1 - margin_top <= center_y <= py2 + margin_bottom)
2151
+
2152
+ # 检查是否是浮动关闭按钮(在弹窗外侧:上方或下方)
2153
+ # 上方浮动关闭按钮(常见:右上角外侧)
2154
+ if center_y < py1 and center_y > py1 - margin_top:
2155
+ if center_x > (px1 + px2) / 2: # 在弹窗右半部分上方
2156
+ is_floating_close = True
2157
+ # 下方浮动关闭按钮(常见:底部中间外侧)
2158
+ elif center_y > py2 and center_y < py2 + margin_top:
2159
+ # 下方关闭按钮通常在中间位置
2160
+ if abs(center_x - (px1 + px2) / 2) < (px2 - px1) / 2:
2161
+ is_floating_close = True
2162
+
2163
+ if in_popup:
2164
+ # 计算元素是否在弹窗边缘(关闭按钮通常在边缘)
2165
+ dist_to_top = abs(center_y - py1)
2166
+ dist_to_bottom = abs(center_y - py2)
2167
+ dist_to_left = abs(center_x - px1)
2168
+ dist_to_right = abs(center_x - px2)
2169
+ min_dist = min(dist_to_top, dist_to_bottom, dist_to_left, dist_to_right)
2170
+
2171
+ # 在弹窗边缘 100 像素内的元素加分
2172
+ if min_dist < 100:
2173
+ popup_edge_bonus = 3.0 * (1 - min_dist / 100)
2174
+
2175
+ # 浮动关闭按钮(在弹窗上方外侧)给予高额加分
2176
+ if is_floating_close:
2177
+ popup_edge_bonus += 5.0 # 大幅加分
2178
+
2179
+ if not in_popup:
2180
+ continue
2181
+
2182
+ # 相对位置(0-1)
2183
+ rel_x = center_x / screen_width
2184
+ rel_y = center_y / screen_height
2185
+
2186
+ score = 0
2187
+ match_type = ""
2188
+ position = self._get_position_name(rel_x, rel_y)
2189
+
2190
+ # ===== 策略1:精确匹配关闭文本(最高优先级)=====
2191
+ if text in close_texts:
2192
+ score = 15.0 + popup_edge_bonus
2193
+ match_type = f"text='{text}'"
2194
+
2195
+ # ===== 策略2:content-desc 包含关闭关键词 =====
2196
+ elif any(kw in content_desc.lower() for kw in close_desc_keywords):
2197
+ score = 12.0 + popup_edge_bonus
2198
+ match_type = f"desc='{content_desc}'"
2199
+
2200
+ # ===== 策略3:clickable 的小尺寸元素(优先于非 clickable)=====
2201
+ elif clickable:
2202
+ min_size = max(20, int(screen_width * 0.03))
2203
+ max_size = max(120, int(screen_width * 0.15))
2204
+ if min_size <= width <= max_size and min_size <= height <= max_size:
2205
+ # clickable 元素基础分更高
2206
+ base_score = 8.0
2207
+ # 浮动关闭按钮给予最高分
2208
+ if is_floating_close:
2209
+ base_score = 12.0
2210
+ match_type = "floating_close"
2211
+ elif 'Image' in class_name:
2212
+ score = base_score + 2.0
2213
+ match_type = "clickable_image"
2214
+ else:
2215
+ match_type = "clickable"
2216
+ score = base_score + self._get_position_score(rel_x, rel_y) + popup_edge_bonus
2217
+
2218
+ # ===== 策略4:ImageView/ImageButton 类型的小元素(非 clickable)=====
2219
+ elif 'Image' in class_name:
2220
+ min_size = max(15, int(screen_width * 0.02))
2221
+ max_size = max(120, int(screen_width * 0.12))
2222
+ if min_size <= width <= max_size and min_size <= height <= max_size:
2223
+ score = 5.0 + self._get_position_score(rel_x, rel_y) + popup_edge_bonus
2224
+ match_type = "ImageView"
2225
+
2226
+ # XML 顺序加分(后出现的元素在上层,更可能是弹窗内的元素)
2227
+ if score > 0:
2228
+ xml_order_bonus = idx / len(all_elements) * 2.0 # 最多加 2 分
2229
+ score += xml_order_bonus
2230
+
2231
+ close_candidates.append({
2232
+ 'bounds': bounds_str,
2233
+ 'center_x': center_x,
2234
+ 'center_y': center_y,
2235
+ 'width': width,
2236
+ 'height': height,
2237
+ 'score': score,
2238
+ 'position': position,
2239
+ 'match_type': match_type,
2240
+ 'text': text,
2241
+ 'content_desc': content_desc,
2242
+ 'x_percent': round(rel_x * 100, 1),
2243
+ 'y_percent': round(rel_y * 100, 1),
2244
+ 'in_popup': popup_bounds is not None
2245
+ })
2246
+
2247
+ except ET.ParseError:
2248
+ pass
2249
+
2250
+ if not close_candidates:
2251
+ # 如果检测到弹窗区域,先尝试点击常见的关闭按钮位置
2252
+ if popup_bounds:
2253
+ px1, py1, px2, py2 = popup_bounds
2254
+ popup_width = px2 - px1
2255
+ popup_height = py2 - py1
2256
+
2257
+ # 【优化】X按钮有三种常见位置:
2258
+ # 1. 弹窗内靠近顶部边界(内嵌X按钮)- 最常见
2259
+ # 2. 弹窗边界上方(浮动X按钮)
2260
+ # 3. 弹窗正下方(底部关闭按钮)
2261
+ offset_x = max(60, int(popup_width * 0.07)) # 宽度7%
2262
+ offset_y_above = max(35, int(popup_height * 0.025)) # 高度2.5%,在边界之上
2263
+ offset_y_near = max(45, int(popup_height * 0.03)) # 高度3%,紧贴顶边界内侧
2264
+
2265
+ try_positions = [
2266
+ # 【最高优先级】弹窗内紧贴顶部边界
2267
+ (px2 - offset_x, py1 + offset_y_near, "弹窗右上角"),
2268
+ # 弹窗边界上方(浮动X按钮)
2269
+ (px2 - offset_x, py1 - offset_y_above, "弹窗右上浮"),
2270
+ # 弹窗正下方中间(底部关闭按钮)
2271
+ ((px1 + px2) // 2, py2 + max(50, int(popup_height * 0.04)), "弹窗下方中间"),
2272
+ # 弹窗正上方中间
2273
+ ((px1 + px2) // 2, py1 - 40, "弹窗正上方"),
2274
+ ]
2275
+
2276
+ for try_x, try_y, position_name in try_positions:
2277
+ if 0 <= try_x <= screen_width and 0 <= try_y <= screen_height:
2278
+ self.client.u2.click(try_x, try_y)
2279
+ time.sleep(0.3)
2280
+
2281
+ # 尝试后截图,让 AI 判断是否成功
2282
+ screenshot_result = self.take_screenshot("尝试关闭后")
2283
+ return {
2284
+ "success": True,
2285
+ "message": f"✅ 已尝试点击常见关闭按钮位置",
2286
+ "tried_positions": [p[2] for p in try_positions],
2287
+ "screenshot": screenshot_result.get("screenshot_path", ""),
2288
+ "tip": "请查看截图确认弹窗是否已关闭。如果还在,可手动分析截图找到关闭按钮位置。"
2289
+ }
2290
+
2291
+ # 没有检测到弹窗区域,截图让 AI 分析
2292
+ screenshot_result = self.take_screenshot(description="页面截图", compress=True)
2293
+
2294
+ return {
2295
+ "success": False,
2296
+ "message": "❌ 未检测到弹窗区域,已截图供 AI 分析",
2297
+ "action_required": "请查看截图找到关闭按钮,调用 mobile_click_at_coords 点击",
2298
+ "screenshot": screenshot_result.get("screenshot_path", ""),
2299
+ "screen_size": {"width": screen_width, "height": screen_height},
2300
+ "image_size": {
2301
+ "width": screenshot_result.get("image_width", screen_width),
2302
+ "height": screenshot_result.get("image_height", screen_height)
2303
+ },
2304
+ "original_size": {
2305
+ "width": screenshot_result.get("original_img_width", screen_width),
2306
+ "height": screenshot_result.get("original_img_height", screen_height)
2307
+ },
2308
+ "search_areas": ["弹窗右上角", "弹窗正上方", "弹窗下方中间", "屏幕右上角"],
2309
+ "time_warning": "⚠️ 截图分析期间弹窗可能自动消失。如果是定时弹窗,建议等待其自动消失。"
2310
+ }
2311
+
2312
+ # 按得分排序,取最可能的
2313
+ close_candidates.sort(key=lambda x: x['score'], reverse=True)
2314
+ best = close_candidates[0]
2315
+
2316
+ # 点击
2317
+ self.client.u2.click(best['center_x'], best['center_y'])
2318
+ time.sleep(0.5)
2319
+
2320
+ # 点击后截图,让 AI 判断是否成功
2321
+ screenshot_result = self.take_screenshot("关闭弹窗后")
2322
+
2323
+ # 记录操作(使用百分比,跨设备兼容)
2324
+ self._record_operation(
2325
+ 'click',
2326
+ x=best['center_x'],
2327
+ y=best['center_y'],
2328
+ x_percent=best['x_percent'],
2329
+ y_percent=best['y_percent'],
2330
+ screen_width=screen_width,
2331
+ screen_height=screen_height,
2332
+ ref=f"close_popup_{best['position']}"
2333
+ )
2334
+
2335
+ # 返回候选按钮列表,让 AI 看截图判断
2336
+ # 如果弹窗还在,AI 可以选择点击其他候选按钮
2337
+ return {
2338
+ "success": True,
2339
+ "message": f"✅ 已点击关闭按钮 ({best['position']}): ({best['center_x']}, {best['center_y']})",
2340
+ "clicked": {
2341
+ "position": best['position'],
2342
+ "match_type": best['match_type'],
2343
+ "coords": (best['center_x'], best['center_y']),
2344
+ "percent": (best['x_percent'], best['y_percent'])
2345
+ },
2346
+ "screenshot": screenshot_result.get("screenshot_path", ""),
2347
+ "popup_detected": popup_bounds is not None,
2348
+ "popup_bounds": f"[{popup_bounds[0]},{popup_bounds[1]}][{popup_bounds[2]},{popup_bounds[3]}]" if popup_bounds else None,
2349
+ "other_candidates": [
2350
+ {
2351
+ "position": c['position'],
2352
+ "type": c['match_type'],
2353
+ "coords": (c['center_x'], c['center_y']),
2354
+ "percent": (c['x_percent'], c['y_percent'])
2355
+ }
2356
+ for c in close_candidates[1:4] # 返回其他3个候选,AI 可以选择
2357
+ ],
2358
+ "tip": "请查看截图判断弹窗是否已关闭。如果弹窗还在,可以尝试点击 other_candidates 中的其他位置;如果误点跳转了,请按返回键"
2359
+ }
2360
+
2361
+ except Exception as e:
2362
+ return {"success": False, "message": f"❌ 关闭弹窗失败: {e}"}
817
2363
 
818
- def list_elements(self) -> List[Dict]:
819
- """列出页面元素"""
820
- try:
821
- if self._is_ios():
822
- ios_client = self._get_ios_client()
823
- if ios_client and hasattr(ios_client, 'list_elements'):
824
- return ios_client.list_elements()
825
- return [{"error": "iOS 暂不支持元素列表,建议使用截图"}]
2364
+ def _get_position_name(self, rel_x: float, rel_y: float) -> str:
2365
+ """根据相对坐标获取位置名称"""
2366
+ if rel_y < 0.4:
2367
+ if rel_x > 0.6:
2368
+ return "右上角"
2369
+ elif rel_x < 0.4:
2370
+ return "左上角"
826
2371
  else:
827
- xml_string = self.client.u2.dump_hierarchy()
828
- elements = self.client.xml_parser.parse(xml_string)
829
-
830
- result = []
831
- for elem in elements:
832
- if elem.get('clickable') or elem.get('focusable'):
833
- result.append({
834
- 'resource_id': elem.get('resource_id', ''),
835
- 'text': elem.get('text', ''),
836
- 'content_desc': elem.get('content_desc', ''),
837
- 'bounds': elem.get('bounds', ''),
838
- 'clickable': elem.get('clickable', False)
839
- })
840
- return result
841
- except Exception as e:
842
- return [{"error": f"获取元素失败: {e}"}]
2372
+ return "顶部中间"
2373
+ elif rel_y > 0.6:
2374
+ if rel_x > 0.6:
2375
+ return "右下角"
2376
+ elif rel_x < 0.4:
2377
+ return "左下角"
2378
+ else:
2379
+ return "底部中间"
2380
+ else:
2381
+ if rel_x > 0.6:
2382
+ return "右侧"
2383
+ elif rel_x < 0.4:
2384
+ return "左侧"
2385
+ else:
2386
+ return "中间"
2387
+
2388
+ def _get_position_score(self, rel_x: float, rel_y: float) -> float:
2389
+ """根据位置计算额外得分(角落位置加分更多)"""
2390
+ # 弹窗关闭按钮常见位置得分:右上角 > 左上角 > 底部中间 > 其他角落
2391
+ if rel_y < 0.4: # 上半部分
2392
+ if rel_x > 0.6: # 右上角
2393
+ return 2.0 + (rel_x - 0.6) + (0.4 - rel_y)
2394
+ elif rel_x < 0.4: # 左上角
2395
+ return 1.5 + (0.4 - rel_x) + (0.4 - rel_y)
2396
+ else: # 顶部中间
2397
+ return 1.0
2398
+ elif rel_y > 0.6: # 下半部分
2399
+ if 0.3 < rel_x < 0.7: # 底部中间
2400
+ return 1.2 + (1 - abs(rel_x - 0.5) * 2)
2401
+ else: # 底部角落
2402
+ return 0.8
2403
+ else: # 中间区域
2404
+ return 0.5
843
2405
 
844
2406
  def assert_text(self, text: str) -> Dict:
845
- """检查页面是否包含文本"""
2407
+ """检查页面是否包含文本(支持精确匹配和包含匹配)"""
846
2408
  try:
2409
+ exists = False
2410
+ match_type = ""
2411
+
847
2412
  if self._is_ios():
848
2413
  ios_client = self._get_ios_client()
849
2414
  if ios_client and hasattr(ios_client, 'wda'):
850
- exists = ios_client.wda(name=text).exists or ios_client.wda(label=text).exists
851
- else:
852
- exists = False
2415
+ # 先尝试精确匹配
2416
+ if ios_client.wda(name=text).exists or ios_client.wda(label=text).exists:
2417
+ exists = True
2418
+ match_type = "精确匹配"
2419
+ # 再尝试包含匹配
2420
+ elif ios_client.wda(nameContains=text).exists or ios_client.wda(labelContains=text).exists:
2421
+ exists = True
2422
+ match_type = "包含匹配"
2423
+ else:
2424
+ # Android: 先尝试精确匹配
2425
+ if self.client.u2(text=text).exists():
2426
+ exists = True
2427
+ match_type = "精确匹配"
2428
+ # 再尝试包含匹配
2429
+ elif self.client.u2(textContains=text).exists():
2430
+ exists = True
2431
+ match_type = "包含匹配"
2432
+
2433
+ if exists:
2434
+ message = f"✅ 文本'{text}' 存在({match_type})"
853
2435
  else:
854
- exists = self.client.u2(text=text).exists()
2436
+ message = f"❌ 文本'{text}' 不存在"
855
2437
 
856
2438
  return {
857
2439
  "success": True,
858
2440
  "found": exists,
859
2441
  "text": text,
860
- "message": f"✅ 文本'{text}' {'存在' if exists else '不存在'}"
2442
+ "match_type": match_type if exists else None,
2443
+ "message": message
861
2444
  }
862
2445
  except Exception as e:
863
2446
  return {"success": False, "message": f"❌ 断言失败: {e}"}
@@ -968,6 +2551,22 @@ class BasicMobileToolsLite:
968
2551
  " return True",
969
2552
  "",
970
2553
  "",
2554
+ "def long_press_by_percent(d, x_percent, y_percent, duration=1.0):",
2555
+ ' """',
2556
+ ' 百分比长按(跨分辨率兼容)',
2557
+ ' ',
2558
+ ' 原理:屏幕左上角 (0%, 0%),右下角 (100%, 100%)',
2559
+ ' 优势:同样的百分比在不同分辨率设备上都能长按到相同相对位置',
2560
+ ' """',
2561
+ " info = d.info",
2562
+ " width = info.get('displayWidth', 0)",
2563
+ " height = info.get('displayHeight', 0)",
2564
+ " x = int(width * x_percent / 100)",
2565
+ " y = int(height * y_percent / 100)",
2566
+ " d.long_click(x, y, duration=duration)",
2567
+ " return True",
2568
+ "",
2569
+ "",
971
2570
  "def test_main():",
972
2571
  " # 连接设备",
973
2572
  " d = u2.connect()",
@@ -1073,6 +2672,48 @@ class BasicMobileToolsLite:
1073
2672
  script_lines.append(" time.sleep(0.5)")
1074
2673
  script_lines.append(" ")
1075
2674
 
2675
+ elif action == 'long_press':
2676
+ ref = op.get('ref', '')
2677
+ element = op.get('element', '')
2678
+ duration = op.get('duration', 1.0)
2679
+ has_coords = 'x' in op and 'y' in op
2680
+ has_percent = 'x_percent' in op and 'y_percent' in op
2681
+
2682
+ # 判断 ref 是否为坐标格式
2683
+ is_coords_ref = ref.startswith('coords_') or ref.startswith('coords:')
2684
+ is_percent_ref = ref.startswith('percent_')
2685
+
2686
+ # 优先级:ID > 文本 > 百分比 > 坐标
2687
+ if ref and (':id/' in ref or ref.startswith('com.')):
2688
+ # 使用 resource-id
2689
+ script_lines.append(f" # 步骤{step_num}: 长按元素 (ID定位,最稳定)")
2690
+ script_lines.append(f" d(resourceId='{ref}').long_click(duration={duration})")
2691
+ elif ref and not is_coords_ref and not is_percent_ref and ':' not in ref:
2692
+ # 使用文本
2693
+ script_lines.append(f" # 步骤{step_num}: 长按文本 '{ref}' (文本定位)")
2694
+ script_lines.append(f" d(text='{ref}').long_click(duration={duration})")
2695
+ elif ref and ':' in ref and not is_coords_ref and not is_percent_ref:
2696
+ actual_text = ref.split(':', 1)[1] if ':' in ref else ref
2697
+ script_lines.append(f" # 步骤{step_num}: 长按文本 '{actual_text}' (文本定位)")
2698
+ script_lines.append(f" d(text='{actual_text}').long_click(duration={duration})")
2699
+ elif has_percent:
2700
+ # 使用百分比
2701
+ x_pct = op['x_percent']
2702
+ y_pct = op['y_percent']
2703
+ desc = f" ({element})" if element else ""
2704
+ script_lines.append(f" # 步骤{step_num}: 长按位置{desc} (百分比定位,跨分辨率兼容)")
2705
+ script_lines.append(f" long_press_by_percent(d, {x_pct}, {y_pct}, duration={duration}) # 原坐标: ({op.get('x', '?')}, {op.get('y', '?')})")
2706
+ elif has_coords:
2707
+ # 坐标兜底
2708
+ desc = f" ({element})" if element else ""
2709
+ script_lines.append(f" # 步骤{step_num}: 长按坐标{desc} (⚠️ 坐标定位,可能不兼容其他分辨率)")
2710
+ script_lines.append(f" d.long_click({op['x']}, {op['y']}, duration={duration})")
2711
+ else:
2712
+ continue
2713
+
2714
+ script_lines.append(" time.sleep(0.5) # 等待响应")
2715
+ script_lines.append(" ")
2716
+
1076
2717
  elif action == 'swipe':
1077
2718
  direction = op.get('direction', 'up')
1078
2719
  script_lines.append(f" # 步骤{step_num}: 滑动 {direction}")
@@ -1115,3 +2756,538 @@ class BasicMobileToolsLite:
1115
2756
  "preview": script[:500] + "..."
1116
2757
  }
1117
2758
 
2759
+ # ========== 模板匹配功能 ==========
2760
+
2761
+ def template_match_close(self, screenshot_path: Optional[str] = None, threshold: float = 0.75) -> Dict:
2762
+ """使用模板匹配查找关闭按钮
2763
+
2764
+ 基于 OpenCV 模板匹配,从预设的X号模板库中查找匹配项。
2765
+ 比 AI 视觉识别更精准、更快速。
2766
+
2767
+ Args:
2768
+ screenshot_path: 截图路径(可选,不提供则自动截图)
2769
+ threshold: 匹配阈值 0-1,越高越严格,默认0.75
2770
+
2771
+ Returns:
2772
+ 匹配结果,包含坐标和点击命令
2773
+ """
2774
+ try:
2775
+ from .template_matcher import TemplateMatcher
2776
+
2777
+ # 如果没有提供截图,先截图
2778
+ if screenshot_path is None:
2779
+ screenshot_result = self.take_screenshot(description="模板匹配", compress=False)
2780
+ screenshot_path = screenshot_result.get("screenshot_path")
2781
+ if not screenshot_path:
2782
+ return {"success": False, "error": "截图失败"}
2783
+
2784
+ matcher = TemplateMatcher()
2785
+ result = matcher.find_close_buttons(screenshot_path, threshold)
2786
+
2787
+ return result
2788
+
2789
+ except ImportError:
2790
+ return {
2791
+ "success": False,
2792
+ "error": "需要安装 opencv-python: pip install opencv-python"
2793
+ }
2794
+ except Exception as e:
2795
+ return {"success": False, "error": f"模板匹配失败: {e}"}
2796
+
2797
+ def template_click_close(self, threshold: float = 0.75) -> Dict:
2798
+ """模板匹配并点击关闭按钮(一步到位)
2799
+
2800
+ 截图 -> 模板匹配 -> 点击最佳匹配位置
2801
+
2802
+ Args:
2803
+ threshold: 匹配阈值 0-1
2804
+
2805
+ Returns:
2806
+ 操作结果
2807
+ """
2808
+ try:
2809
+ # 先截图并匹配
2810
+ match_result = self.template_match_close(threshold=threshold)
2811
+
2812
+ if not match_result.get("success"):
2813
+ return match_result
2814
+
2815
+ # 获取最佳匹配的百分比坐标
2816
+ best = match_result.get("best_match", {})
2817
+ x_percent = best.get("percent", {}).get("x")
2818
+ y_percent = best.get("percent", {}).get("y")
2819
+
2820
+ if x_percent is None or y_percent is None:
2821
+ return {"success": False, "error": "无法获取匹配坐标"}
2822
+
2823
+ # 点击
2824
+ click_result = self.click_by_percent(x_percent, y_percent)
2825
+
2826
+ return {
2827
+ "success": True,
2828
+ "message": f"✅ 模板匹配并点击成功",
2829
+ "matched_template": best.get("template"),
2830
+ "confidence": best.get("confidence"),
2831
+ "clicked_position": f"({x_percent}%, {y_percent}%)",
2832
+ "click_result": click_result
2833
+ }
2834
+
2835
+ except Exception as e:
2836
+ return {"success": False, "error": f"模板点击失败: {e}"}
2837
+
2838
+ def template_add(self, screenshot_path: str, x: int, y: int,
2839
+ width: int, height: int, template_name: str) -> Dict:
2840
+ """从截图中裁剪并添加新模板
2841
+
2842
+ 当遇到新样式的X号时,用此方法添加到模板库。
2843
+
2844
+ Args:
2845
+ screenshot_path: 截图路径
2846
+ x, y: 裁剪区域左上角坐标
2847
+ width, height: 裁剪区域大小
2848
+ template_name: 模板名称(如 x_circle_gray)
2849
+
2850
+ Returns:
2851
+ 结果
2852
+ """
2853
+ try:
2854
+ from .template_matcher import TemplateMatcher
2855
+
2856
+ matcher = TemplateMatcher()
2857
+ return matcher.crop_and_add_template(
2858
+ screenshot_path, x, y, width, height, template_name
2859
+ )
2860
+ except ImportError:
2861
+ return {"success": False, "error": "需要安装 opencv-python"}
2862
+ except Exception as e:
2863
+ return {"success": False, "error": f"添加模板失败: {e}"}
2864
+
2865
+ def template_list(self) -> Dict:
2866
+ """列出所有关闭按钮模板"""
2867
+ try:
2868
+ from .template_matcher import TemplateMatcher
2869
+
2870
+ matcher = TemplateMatcher()
2871
+ return matcher.list_templates()
2872
+ except ImportError:
2873
+ return {"success": False, "error": "需要安装 opencv-python"}
2874
+ except Exception as e:
2875
+ return {"success": False, "error": f"列出模板失败: {e}"}
2876
+
2877
+ def template_delete(self, template_name: str) -> Dict:
2878
+ """删除指定模板"""
2879
+ try:
2880
+ from .template_matcher import TemplateMatcher
2881
+
2882
+ matcher = TemplateMatcher()
2883
+ return matcher.delete_template(template_name)
2884
+ except ImportError:
2885
+ return {"success": False, "error": "需要安装 opencv-python"}
2886
+ except Exception as e:
2887
+ return {"success": False, "error": f"删除模板失败: {e}"}
2888
+
2889
+ def close_ad_popup(self, auto_learn: bool = True) -> Dict:
2890
+ """智能关闭广告弹窗(专用于广告场景)
2891
+
2892
+ 按优先级尝试:
2893
+ 1. 控件树查找关闭按钮(最可靠)
2894
+ 2. 模板匹配(需要积累模板库)
2895
+ 3. 返回视觉信息供 AI 分析(如果前两步失败)
2896
+
2897
+ 自动学习:
2898
+ - 点击成功后,检查这个 X 是否已在模板库
2899
+ - 如果是新样式,自动裁剪并添加到模板库
2900
+
2901
+ Args:
2902
+ auto_learn: 是否自动学习新模板(点击成功后检查并保存)
2903
+
2904
+ Returns:
2905
+ 结果字典
2906
+ """
2907
+ import time
2908
+ import re
2909
+
2910
+ result = {
2911
+ "success": False,
2912
+ "method": None,
2913
+ "message": "",
2914
+ "learned_template": None
2915
+ }
2916
+
2917
+ if self._is_ios():
2918
+ return {"success": False, "error": "iOS 暂不支持此功能"}
2919
+
2920
+ try:
2921
+ import xml.etree.ElementTree as ET
2922
+
2923
+ # ========== 第1步:控件树查找关闭按钮(使用完整 UI 层级)==========
2924
+ xml_string = self._get_full_hierarchy()
2925
+ root = ET.fromstring(xml_string)
2926
+
2927
+ # 关闭按钮的常见特征
2928
+ close_keywords = ['关闭', '跳过', '×', 'X', 'x', 'close', 'skip', '取消']
2929
+ close_content_desc = ['关闭', '跳过', 'close', 'skip', 'dismiss']
2930
+
2931
+ close_candidates = []
2932
+
2933
+ for elem in root.iter():
2934
+ text = elem.attrib.get('text', '').strip()
2935
+ content_desc = elem.attrib.get('content-desc', '').strip()
2936
+ clickable = elem.attrib.get('clickable', 'false') == 'true'
2937
+ bounds_str = elem.attrib.get('bounds', '')
2938
+ resource_id = elem.attrib.get('resource-id', '')
2939
+
2940
+ if not bounds_str:
2941
+ continue
2942
+
2943
+ match = re.match(r'\[(\d+),(\d+)\]\[(\d+),(\d+)\]', bounds_str)
2944
+ if not match:
2945
+ continue
2946
+
2947
+ x1, y1, x2, y2 = map(int, match.groups())
2948
+ width = x2 - x1
2949
+ height = y2 - y1
2950
+ cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
2951
+
2952
+ score = 0
2953
+ reason = ""
2954
+
2955
+ # 文本匹配
2956
+ for kw in close_keywords:
2957
+ if kw in text:
2958
+ score += 10
2959
+ reason = f"文本含'{kw}'"
2960
+ break
2961
+
2962
+ # content-desc 匹配
2963
+ for kw in close_content_desc:
2964
+ if kw.lower() in content_desc.lower():
2965
+ score += 8
2966
+ reason = f"描述含'{kw}'"
2967
+ break
2968
+
2969
+ # 小尺寸可点击元素(可能是 X 按钮)
2970
+ if clickable and 30 < width < 200 and 30 < height < 200:
2971
+ screen_width = self.client.u2.info.get('displayWidth', 1440)
2972
+ screen_height = self.client.u2.info.get('displayHeight', 3200)
2973
+
2974
+ # 在屏幕右半边上半部分,很可能是 X
2975
+ if cx > screen_width * 0.6 and cy < screen_height * 0.5:
2976
+ score += 5
2977
+ reason = reason or "右上角小按钮"
2978
+ # 在屏幕上半部分的小按钮,也可能是 X
2979
+ elif cy < screen_height * 0.4:
2980
+ score += 2
2981
+ reason = reason or "上部小按钮"
2982
+
2983
+ # 只要是可点击的小按钮都考虑(即使没有文本)
2984
+ if score > 0 or (clickable and 30 < width < 150 and 30 < height < 150):
2985
+ if not reason and clickable:
2986
+ reason = "可点击小按钮"
2987
+ score = max(score, 1) # 确保有分数
2988
+ close_candidates.append({
2989
+ 'score': score,
2990
+ 'reason': reason,
2991
+ 'bounds': (x1, y1, x2, y2),
2992
+ 'center': (cx, cy),
2993
+ 'resource_id': resource_id,
2994
+ 'text': text
2995
+ })
2996
+
2997
+ # 按分数排序
2998
+ close_candidates.sort(key=lambda x: x['score'], reverse=True)
2999
+
3000
+ if close_candidates:
3001
+ best = close_candidates[0]
3002
+ cx, cy = best['center']
3003
+ bounds = best['bounds']
3004
+
3005
+ # 点击前截图(用于自动学习)
3006
+ pre_screenshot = None
3007
+ if auto_learn:
3008
+ pre_result = self.take_screenshot(description="关闭前", compress=False)
3009
+ pre_screenshot = pre_result.get("screenshot_path")
3010
+
3011
+ # 点击
3012
+ self.click_at_coords(cx, cy)
3013
+ time.sleep(0.5)
3014
+
3015
+ result["success"] = True
3016
+ result["method"] = "控件树"
3017
+ result["message"] = f"✅ 通过控件树找到关闭按钮并点击\n" \
3018
+ f" 位置: ({cx}, {cy})\n" \
3019
+ f" 原因: {best['reason']}"
3020
+
3021
+ # 自动学习:检查这个 X 是否已在模板库,不在就添加
3022
+ if auto_learn and pre_screenshot:
3023
+ learn_result = self._auto_learn_template(pre_screenshot, bounds)
3024
+ if learn_result:
3025
+ result["learned_template"] = learn_result
3026
+ result["message"] += f"\n📚 自动学习: {learn_result}"
3027
+
3028
+ return result
3029
+
3030
+ # ========== 第2步:模板匹配 ==========
3031
+ screenshot_path = None
3032
+ try:
3033
+ from .template_matcher import TemplateMatcher
3034
+
3035
+ # 截图用于模板匹配
3036
+ screenshot_result = self.take_screenshot(description="模板匹配", compress=False)
3037
+ screenshot_path = screenshot_result.get("screenshot_path")
3038
+
3039
+ if screenshot_path:
3040
+ matcher = TemplateMatcher()
3041
+ match_result = matcher.find_close_buttons(screenshot_path, threshold=0.75)
3042
+
3043
+ # 直接使用最佳匹配(已按置信度排序)
3044
+ if match_result.get("success") and match_result.get("best_match"):
3045
+ best = match_result["best_match"]
3046
+ x_pct = best["percent"]["x"]
3047
+ y_pct = best["percent"]["y"]
3048
+
3049
+ # 点击
3050
+ self.click_by_percent(x_pct, y_pct)
3051
+ time.sleep(0.5)
3052
+
3053
+ result["success"] = True
3054
+ result["method"] = "模板匹配"
3055
+ result["message"] = f"✅ 通过模板匹配找到关闭按钮并点击\n" \
3056
+ f" 模板: {best.get('template', 'unknown')}\n" \
3057
+ f" 置信度: {best.get('confidence', 'N/A')}%\n" \
3058
+ f" 位置: ({x_pct:.1f}%, {y_pct:.1f}%)"
3059
+ return result
3060
+
3061
+ except ImportError:
3062
+ pass # OpenCV 未安装,跳过模板匹配
3063
+ except Exception:
3064
+ pass # 模板匹配失败,继续下一步
3065
+
3066
+ # ========== 第3步:返回截图供 AI 分析 ==========
3067
+ if not screenshot_path:
3068
+ screenshot_result = self.take_screenshot(description="需要AI分析", compress=True)
3069
+
3070
+ result["success"] = False
3071
+ result["method"] = None
3072
+ result["message"] = "❌ 控件树和模板匹配都未找到关闭按钮\n" \
3073
+ "📸 已截图,请 AI 分析图片中的 X 按钮位置\n" \
3074
+ "💡 找到后使用 mobile_click_by_percent(x%, y%) 点击"
3075
+ result["screenshot"] = screenshot_result if not screenshot_path else {"screenshot_path": screenshot_path}
3076
+ result["need_ai_analysis"] = True
3077
+
3078
+ return result
3079
+
3080
+ except Exception as e:
3081
+ return {"success": False, "error": f"关闭弹窗失败: {e}"}
3082
+
3083
+ def _detect_popup_region(self, root) -> tuple:
3084
+ """从控件树中检测弹窗区域
3085
+
3086
+ Args:
3087
+ root: 控件树根元素
3088
+
3089
+ Returns:
3090
+ 弹窗边界 (x1, y1, x2, y2) 或 None
3091
+ """
3092
+ import re
3093
+
3094
+ screen_width = self.client.u2.info.get('displayWidth', 1440)
3095
+ screen_height = self.client.u2.info.get('displayHeight', 3200)
3096
+
3097
+ popup_candidates = []
3098
+
3099
+ for elem in root.iter():
3100
+ bounds_str = elem.attrib.get('bounds', '')
3101
+ if not bounds_str:
3102
+ continue
3103
+
3104
+ match = re.match(r'\[(\d+),(\d+)\]\[(\d+),(\d+)\]', bounds_str)
3105
+ if not match:
3106
+ continue
3107
+
3108
+ x1, y1, x2, y2 = map(int, match.groups())
3109
+ width = x2 - x1
3110
+ height = y2 - y1
3111
+
3112
+ # 弹窗特征:
3113
+ # 1. 不是全屏
3114
+ # 2. 在屏幕中央
3115
+ # 3. 有一定大小
3116
+ is_fullscreen = (width >= screen_width * 0.95 and height >= screen_height * 0.9)
3117
+ is_centered = (x1 > screen_width * 0.05 and x2 < screen_width * 0.95)
3118
+ is_reasonable_size = (width > 200 and height > 200 and
3119
+ width < screen_width * 0.95 and
3120
+ height < screen_height * 0.8)
3121
+
3122
+ if not is_fullscreen and is_centered and is_reasonable_size:
3123
+ # 计算"弹窗感"分数
3124
+ area = width * height
3125
+ center_x = (x1 + x2) / 2
3126
+ center_y = (y1 + y2) / 2
3127
+ center_dist = abs(center_x - screen_width/2) + abs(center_y - screen_height/2)
3128
+
3129
+ score = area / 1000 - center_dist / 10
3130
+ popup_candidates.append({
3131
+ 'bounds': (x1, y1, x2, y2),
3132
+ 'score': score
3133
+ })
3134
+
3135
+ if popup_candidates:
3136
+ # 返回分数最高的弹窗
3137
+ popup_candidates.sort(key=lambda x: x['score'], reverse=True)
3138
+ return popup_candidates[0]['bounds']
3139
+
3140
+ return None
3141
+
3142
+ def _auto_learn_template(self, screenshot_path: str, bounds: tuple, threshold: float = 0.6) -> str:
3143
+ """自动学习:检查 X 按钮是否已在模板库,不在就添加
3144
+
3145
+ Args:
3146
+ screenshot_path: 截图路径
3147
+ bounds: X 按钮的边界 (x1, y1, x2, y2)
3148
+ threshold: 判断是否已存在的阈值(高于此值认为已存在)
3149
+
3150
+ Returns:
3151
+ 新模板名称,如果是新模板的话;已存在或失败返回 None
3152
+ """
3153
+ try:
3154
+ from .template_matcher import TemplateMatcher
3155
+ from PIL import Image
3156
+ import time
3157
+
3158
+ x1, y1, x2, y2 = bounds
3159
+ cx, cy = (x1 + x2) // 2, (y1 + y2) // 2
3160
+ width = x2 - x1
3161
+ height = y2 - y1
3162
+
3163
+ # 扩展一点边界,确保裁剪完整
3164
+ padding = max(10, int(max(width, height) * 0.2))
3165
+
3166
+ # 打开截图
3167
+ img = Image.open(screenshot_path)
3168
+
3169
+ # 裁剪 X 按钮区域
3170
+ crop_x1 = max(0, x1 - padding)
3171
+ crop_y1 = max(0, y1 - padding)
3172
+ crop_x2 = min(img.width, x2 + padding)
3173
+ crop_y2 = min(img.height, y2 + padding)
3174
+
3175
+ cropped = img.crop((crop_x1, crop_y1, crop_x2, crop_y2))
3176
+
3177
+ # 保存临时文件用于匹配检查
3178
+ temp_path = self.screenshot_dir / "temp_new_x.png"
3179
+ cropped.save(str(temp_path))
3180
+
3181
+ # 检查是否已在模板库中(用模板匹配检测相似度)
3182
+ matcher = TemplateMatcher()
3183
+
3184
+ import cv2
3185
+ new_img = cv2.imread(str(temp_path), cv2.IMREAD_GRAYSCALE)
3186
+ if new_img is None:
3187
+ return None
3188
+
3189
+ is_new = True
3190
+ for template_file in matcher.template_dir.glob("*.png"):
3191
+ template = cv2.imread(str(template_file), cv2.IMREAD_GRAYSCALE)
3192
+ if template is None:
3193
+ continue
3194
+
3195
+ # 将两个图都调整到合适大小,然后用小模板在大图中搜索
3196
+ # 这样比较更接近实际匹配场景
3197
+
3198
+ # 新图作为搜索区域(稍大一点)
3199
+ new_resized = cv2.resize(new_img, (100, 100))
3200
+ # 模板调整到较小尺寸
3201
+ template_resized = cv2.resize(template, (60, 60))
3202
+
3203
+ # 在新图中搜索模板
3204
+ result = cv2.matchTemplate(new_resized, template_resized, cv2.TM_CCOEFF_NORMED)
3205
+ _, max_val, _, _ = cv2.minMaxLoc(result)
3206
+
3207
+ if max_val >= threshold:
3208
+ is_new = False
3209
+ break
3210
+
3211
+ # 清理临时文件
3212
+ if temp_path.exists():
3213
+ temp_path.unlink()
3214
+
3215
+ if is_new:
3216
+ # 生成唯一模板名
3217
+ timestamp = time.strftime("%m%d_%H%M%S")
3218
+ template_name = f"auto_x_{timestamp}.png"
3219
+ template_path = matcher.template_dir / template_name
3220
+
3221
+ # 保存新模板
3222
+ cropped.save(str(template_path))
3223
+
3224
+ return template_name
3225
+ else:
3226
+ return None # 已存在类似模板
3227
+
3228
+ except Exception as e:
3229
+ return None # 学习失败,不影响主流程
3230
+
3231
+ def template_add_by_percent(self, x_percent: float, y_percent: float,
3232
+ size: int, template_name: str) -> Dict:
3233
+ """通过百分比坐标添加模板(更方便!)
3234
+
3235
+ 自动截图 → 根据百分比位置裁剪 → 保存为模板
3236
+
3237
+ Args:
3238
+ x_percent: X号中心的水平百分比 (0-100)
3239
+ y_percent: X号中心的垂直百分比 (0-100)
3240
+ size: 裁剪区域大小(正方形边长,像素)
3241
+ template_name: 模板名称
3242
+
3243
+ Returns:
3244
+ 结果
3245
+ """
3246
+ try:
3247
+ from .template_matcher import TemplateMatcher
3248
+ from PIL import Image
3249
+
3250
+ # 先截图(不带 SoM 标注的干净截图)
3251
+ screenshot_result = self.take_screenshot(description="添加模板", compress=False)
3252
+ screenshot_path = screenshot_result.get("screenshot_path")
3253
+
3254
+ if not screenshot_path:
3255
+ return {"success": False, "error": "截图失败"}
3256
+
3257
+ # 读取截图获取尺寸
3258
+ img = Image.open(screenshot_path)
3259
+ img_w, img_h = img.size
3260
+
3261
+ # 计算中心点像素坐标
3262
+ cx = int(img_w * x_percent / 100)
3263
+ cy = int(img_h * y_percent / 100)
3264
+
3265
+ # 计算裁剪区域
3266
+ half = size // 2
3267
+ x1 = max(0, cx - half)
3268
+ y1 = max(0, cy - half)
3269
+ x2 = min(img_w, cx + half)
3270
+ y2 = min(img_h, cy + half)
3271
+
3272
+ # 裁剪并保存
3273
+ cropped = img.crop((x1, y1, x2, y2))
3274
+
3275
+ matcher = TemplateMatcher()
3276
+ output_path = matcher.template_dir / f"{template_name}.png"
3277
+ cropped.save(str(output_path))
3278
+
3279
+ return {
3280
+ "success": True,
3281
+ "message": f"✅ 模板已保存: {template_name}",
3282
+ "template_path": str(output_path),
3283
+ "center_percent": f"({x_percent}%, {y_percent}%)",
3284
+ "center_pixel": f"({cx}, {cy})",
3285
+ "crop_region": f"({x1},{y1}) - ({x2},{y2})",
3286
+ "size": f"{cropped.size[0]}x{cropped.size[1]}"
3287
+ }
3288
+
3289
+ except ImportError as e:
3290
+ return {"success": False, "error": f"需要安装依赖: {e}"}
3291
+ except Exception as e:
3292
+ return {"success": False, "error": f"添加模板失败: {e}"}
3293
+