kotonebot 0.5.0__py3-none-any.whl → 0.7.0__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.
Files changed (107) hide show
  1. kotonebot/__init__.py +39 -39
  2. kotonebot/backend/bot.py +312 -312
  3. kotonebot/backend/color.py +525 -525
  4. kotonebot/backend/context/__init__.py +3 -3
  5. kotonebot/backend/context/context.py +1002 -1002
  6. kotonebot/backend/context/task_action.py +183 -183
  7. kotonebot/backend/core.py +86 -129
  8. kotonebot/backend/debug/entry.py +89 -89
  9. kotonebot/backend/debug/mock.py +78 -78
  10. kotonebot/backend/debug/server.py +222 -222
  11. kotonebot/backend/debug/vars.py +351 -351
  12. kotonebot/backend/dispatch.py +227 -227
  13. kotonebot/backend/flow_controller.py +196 -196
  14. kotonebot/backend/image.py +36 -5
  15. kotonebot/backend/loop.py +222 -208
  16. kotonebot/backend/ocr.py +535 -535
  17. kotonebot/backend/preprocessor.py +103 -103
  18. kotonebot/client/__init__.py +9 -9
  19. kotonebot/client/device.py +369 -529
  20. kotonebot/client/fast_screenshot.py +377 -377
  21. kotonebot/client/host/__init__.py +43 -43
  22. kotonebot/client/host/adb_common.py +101 -107
  23. kotonebot/client/host/custom.py +118 -118
  24. kotonebot/client/host/leidian_host.py +196 -196
  25. kotonebot/client/host/mumu12_host.py +353 -353
  26. kotonebot/client/host/protocol.py +214 -214
  27. kotonebot/client/host/windows_common.py +73 -58
  28. kotonebot/client/implements/__init__.py +65 -70
  29. kotonebot/client/implements/adb.py +89 -89
  30. kotonebot/client/implements/nemu_ipc/__init__.py +11 -11
  31. kotonebot/client/implements/nemu_ipc/external_renderer_ipc.py +284 -284
  32. kotonebot/client/implements/nemu_ipc/nemu_ipc.py +327 -327
  33. kotonebot/client/implements/remote_windows.py +188 -188
  34. kotonebot/client/implements/uiautomator2.py +85 -85
  35. kotonebot/client/implements/windows/__init__.py +1 -0
  36. kotonebot/client/implements/windows/print_window.py +133 -0
  37. kotonebot/client/implements/windows/send_message.py +324 -0
  38. kotonebot/client/implements/{windows.py → windows/windows.py} +175 -176
  39. kotonebot/client/protocol.py +69 -69
  40. kotonebot/client/registration.py +24 -24
  41. kotonebot/client/scaler.py +467 -0
  42. kotonebot/config/base_config.py +103 -96
  43. kotonebot/config/config.py +61 -0
  44. kotonebot/config/manager.py +36 -36
  45. kotonebot/core/__init__.py +13 -0
  46. kotonebot/core/entities/base.py +182 -0
  47. kotonebot/core/entities/compound.py +75 -0
  48. kotonebot/core/entities/ocr.py +117 -0
  49. kotonebot/core/entities/template_match.py +198 -0
  50. kotonebot/devtools/__init__.py +42 -0
  51. kotonebot/devtools/cli/__init__.py +6 -0
  52. kotonebot/devtools/cli/main.py +53 -0
  53. kotonebot/{tools → devtools}/mirror.py +354 -354
  54. kotonebot/devtools/project/project.py +41 -0
  55. kotonebot/devtools/project/scanner.py +202 -0
  56. kotonebot/devtools/project/schema.py +99 -0
  57. kotonebot/devtools/resgen/__init__.py +42 -0
  58. kotonebot/devtools/resgen/codegen.py +331 -0
  59. kotonebot/devtools/resgen/core.py +94 -0
  60. kotonebot/devtools/resgen/parsers.py +360 -0
  61. kotonebot/devtools/resgen/utils.py +158 -0
  62. kotonebot/devtools/resgen/validation.py +115 -0
  63. kotonebot/devtools/web/dist/assets/bootstrap-icons-BOrJxbIo.woff +0 -0
  64. kotonebot/devtools/web/dist/assets/bootstrap-icons-BtvjY1KL.woff2 +0 -0
  65. kotonebot/devtools/web/dist/assets/ext-language_tools-CD021WJ2.js +2577 -0
  66. kotonebot/devtools/web/dist/assets/index-B_m5f2LF.js +2836 -0
  67. kotonebot/devtools/web/dist/assets/index-BlEDyGGa.css +9 -0
  68. kotonebot/devtools/web/dist/assets/language-client-C9muzqaq.js +128 -0
  69. kotonebot/devtools/web/dist/assets/mode-python-CtHp76XS.js +476 -0
  70. kotonebot/devtools/web/dist/icons/symbol-class.svg +3 -0
  71. kotonebot/devtools/web/dist/icons/symbol-file.svg +3 -0
  72. kotonebot/devtools/web/dist/icons/symbol-method.svg +3 -0
  73. kotonebot/devtools/web/dist/index.html +25 -0
  74. kotonebot/devtools/web/server/__init__.py +0 -0
  75. kotonebot/devtools/web/server/rest_api.py +217 -0
  76. kotonebot/devtools/web/server/server.py +85 -0
  77. kotonebot/errors.py +76 -76
  78. kotonebot/interop/win/__init__.py +13 -9
  79. kotonebot/interop/win/_mouse.py +310 -310
  80. kotonebot/interop/win/message_box.py +313 -313
  81. kotonebot/interop/win/reg.py +37 -37
  82. kotonebot/interop/win/shake_mouse.py +224 -0
  83. kotonebot/interop/win/shortcut.py +43 -43
  84. kotonebot/interop/win/task_dialog.py +513 -513
  85. kotonebot/interop/win/window.py +89 -0
  86. kotonebot/logging/__init__.py +2 -2
  87. kotonebot/logging/log.py +17 -17
  88. kotonebot/primitives/__init__.py +19 -17
  89. kotonebot/primitives/geometry.py +1067 -862
  90. kotonebot/primitives/visual.py +143 -63
  91. kotonebot/ui/file_host/sensio.py +36 -36
  92. kotonebot/ui/file_host/tmp_send.py +54 -54
  93. kotonebot/ui/pushkit/__init__.py +3 -3
  94. kotonebot/ui/pushkit/image_host.py +88 -88
  95. kotonebot/ui/pushkit/protocol.py +13 -13
  96. kotonebot/ui/pushkit/wxpusher.py +54 -54
  97. kotonebot/ui/user.py +148 -148
  98. kotonebot/util.py +436 -436
  99. {kotonebot-0.5.0.dist-info → kotonebot-0.7.0.dist-info}/METADATA +84 -82
  100. kotonebot-0.7.0.dist-info/RECORD +109 -0
  101. {kotonebot-0.5.0.dist-info → kotonebot-0.7.0.dist-info}/WHEEL +1 -1
  102. kotonebot-0.7.0.dist-info/entry_points.txt +2 -0
  103. {kotonebot-0.5.0.dist-info → kotonebot-0.7.0.dist-info}/licenses/LICENSE +673 -673
  104. kotonebot/client/implements/adb_raw.py +0 -163
  105. kotonebot-0.5.0.dist-info/RECORD +0 -71
  106. /kotonebot/{tools → devtools/project}/__init__.py +0 -0
  107. {kotonebot-0.5.0.dist-info → kotonebot-0.7.0.dist-info}/top_level.txt +0 -0
@@ -1,327 +1,327 @@
1
- import os
2
- import ctypes
3
- import logging
4
- import time
5
- from dataclasses import dataclass
6
- from time import sleep
7
- from typing import Literal
8
- from typing_extensions import override
9
-
10
- import cv2
11
- import numpy as np
12
- from cv2.typing import MatLike
13
-
14
- from ...device import AndroidDevice, Device
15
- from ...protocol import Touchable, Screenshotable
16
- from ...registration import ImplConfig
17
- from .external_renderer_ipc import ExternalRendererIpc
18
- from kotonebot.errors import KotonebotError
19
-
20
- logger = logging.getLogger(__name__)
21
-
22
-
23
- class NemuIpcIncompatible(Exception):
24
- """MuMu12 版本过低或 dll 不兼容"""
25
- pass
26
-
27
-
28
- class NemuIpcError(KotonebotError):
29
- """调用 IPC 过程中发生错误"""
30
- pass
31
-
32
-
33
- @dataclass
34
- class NemuIpcImplConfig(ImplConfig):
35
- """nemu_ipc 能力的配置模型。"""
36
- nemu_folder: str
37
- r"""MuMu12 根目录(如 F:\Apps\Netease\MuMuPlayer-12.0)。"""
38
- instance_id: int
39
- """模拟器实例 ID。"""
40
- display_id: int | None = 0
41
- """目标显示器 ID,默认为 0(主显示器)。若为 None 且设置了 target_package_name,则自动获取对应的 display_id。"""
42
- target_package_name: str | None = None
43
- """目标应用包名,用于自动获取 display_id。"""
44
- app_index: int = 0
45
- """多开应用索引,传给 get_display_id 方法。"""
46
- wait_package_timeout: float = 60 # 单位秒,-1 表示永远等待,0 表示不等待,立即抛出异常
47
- wait_package_interval: float = 0.1 # 单位秒
48
-
49
-
50
- class NemuIpcImpl(Touchable, Screenshotable):
51
- """
52
- 利用 MuMu12 提供的 external_renderer_ipc.dll 进行截图与触摸控制。
53
- """
54
-
55
- def __init__(self, config: NemuIpcImplConfig):
56
- self.config = config
57
- self.__width: int = 0
58
- self.__height: int = 0
59
- self.__connected: bool = False
60
- self._connect_id: int = 0
61
- self.nemu_folder = config.nemu_folder
62
-
63
- # --------------------------- DLL 封装 ---------------------------
64
- self._ipc = ExternalRendererIpc(config.nemu_folder)
65
- logger.info("ExternalRendererIpc initialized and DLL loaded")
66
-
67
- @property
68
- def width(self) -> int:
69
- """
70
- 屏幕宽度。
71
-
72
- 若为 0,表示未连接或未获取到分辨率。
73
- """
74
- return self.__width
75
-
76
- @property
77
- def height(self) -> int:
78
- """
79
- 屏幕高度。
80
-
81
- 若为 0,表示未连接或未获取到分辨率。
82
- """
83
- return self.__height
84
-
85
- @property
86
- def connected(self) -> bool:
87
- """是否已连接。"""
88
- return self.__connected
89
-
90
- # ------------------------------------------------------------------
91
- # 基础控制
92
- # ------------------------------------------------------------------
93
-
94
- def _ensure_connected(self) -> None:
95
- if not self.__connected:
96
- self.connect()
97
-
98
- def _get_display_id(self) -> int:
99
- """获取有效的 display_id。"""
100
- # 如果配置中直接指定了 display_id,直接返回
101
- if self.config.display_id is not None:
102
- return self.config.display_id
103
-
104
- # 如果设置了 target_package_name,实时获取 display_id
105
- if self.config.target_package_name:
106
- self._ensure_connected()
107
-
108
- timeout = self.config.wait_package_timeout
109
- interval = self.config.wait_package_interval
110
- if timeout == -1:
111
- timeout = float('inf')
112
- start_time = time.time()
113
- while True:
114
- display_id = self._ipc.get_display_id(
115
- self._connect_id,
116
- self.config.target_package_name,
117
- self.config.app_index
118
- )
119
- if display_id >= 0:
120
- return display_id
121
- elif display_id == -1:
122
- # 可以继续等
123
- pass
124
- else:
125
- # 未知错误
126
- raise NemuIpcError(f"Failed to get display_id for package '{self.config.target_package_name}', error code={display_id}")
127
- if time.time() - start_time > timeout:
128
- break
129
- sleep(interval)
130
-
131
- raise NemuIpcError(f"Failed to get display_id for package '{self.config.target_package_name}' within {timeout}s")
132
-
133
- # 如果都没有设置,抛出错误
134
- raise NemuIpcError("display_id is None and target_package_name is not set. Please set display_id or target_package_name in config.")
135
-
136
- def connect(self) -> None:
137
- """连接模拟器。"""
138
- if self.__connected:
139
- return
140
-
141
- connect_id = self._ipc.connect(self.nemu_folder, self.config.instance_id)
142
- if connect_id == 0:
143
- raise NemuIpcError("nemu_connect failed, please check if the emulator is running and the instance ID is correct.")
144
-
145
- self._connect_id = connect_id
146
- self.__connected = True
147
- logger.debug("NemuIpc connected, connect_id=%d", connect_id)
148
-
149
- def disconnect(self) -> None:
150
- """断开连接。"""
151
- if not self.__connected:
152
- return
153
- self._ipc.disconnect(self._connect_id)
154
- self.__connected = False
155
- self._connect_id = 0
156
- logger.debug("NemuIpc disconnected.")
157
-
158
- # ------------------------------------------------------------------
159
- # Screenshotable 接口实现
160
- # ------------------------------------------------------------------
161
- @property
162
- def screen_size(self) -> tuple[int, int]:
163
- """获取屏幕分辨率。"""
164
- if self.__width == 0 or self.__height == 0:
165
- self._refresh_resolution()
166
- if self.__width == 0 or self.__height == 0:
167
- raise NemuIpcError("Screen resolution not obtained, please connect to the emulator first.")
168
- return self.__width, self.__height
169
-
170
- @override
171
- def detect_orientation(self):
172
- return self.get_display_orientation(self._get_display_id())
173
-
174
- def get_display_orientation(self, display_id: int = 0) -> Literal['portrait', 'landscape'] | None:
175
- """获取指定显示屏的方向。"""
176
- width, height = self.query_resolution(display_id)
177
- if width > height:
178
- return "landscape"
179
- if height > width:
180
- return "portrait"
181
- return None
182
-
183
- @override
184
- def screenshot(self) -> MatLike:
185
- self._ensure_connected()
186
-
187
- # 必须每次都更新分辨率,因为屏幕可能会旋转
188
- self._refresh_resolution()
189
-
190
- length = self.__width * self.__height * 4 # RGBA
191
- buf_type = ctypes.c_ubyte * length
192
- buffer = buf_type()
193
-
194
- w_ptr = ctypes.pointer(ctypes.c_int(self.__width))
195
- h_ptr = ctypes.pointer(ctypes.c_int(self.__height))
196
-
197
- ret = self._ipc.capture_display(
198
- self._connect_id,
199
- self._get_display_id(),
200
- length,
201
- ctypes.cast(w_ptr, ctypes.c_void_p),
202
- ctypes.cast(h_ptr, ctypes.c_void_p),
203
- ctypes.cast(buffer, ctypes.c_void_p),
204
- )
205
- if ret != 0:
206
- raise NemuIpcError(f"nemu_capture_display screenshot failed, error code={ret}")
207
-
208
- # 读入并转换数据
209
- img = np.ctypeslib.as_array(buffer).reshape((self.__height, self.__width, 4))
210
- # RGBA -> BGR
211
- img = cv2.cvtColor(img, cv2.COLOR_RGBA2BGR)
212
- cv2.flip(img, 0, dst=img)
213
- return img
214
-
215
- # --------------------------- 内部工具 -----------------------------
216
-
217
- def _refresh_resolution(self) -> None:
218
- """刷新分辨率信息。"""
219
- display_id = self._get_display_id()
220
- self.__width, self.__height = self.query_resolution(display_id)
221
-
222
- def query_resolution(self, display_id: int = 0) -> tuple[int, int]:
223
- """
224
- 查询指定显示屏的分辨率。
225
-
226
- :param display_id: 显示屏 ID。
227
- :return: 分辨率 (width, height)。
228
- :raise NemuIpcError: 查询失败。
229
- """
230
- self._ensure_connected()
231
-
232
- w_ptr = ctypes.pointer(ctypes.c_int(0))
233
- h_ptr = ctypes.pointer(ctypes.c_int(0))
234
- ret = self._ipc.capture_display(
235
- self._connect_id,
236
- display_id,
237
- 0,
238
- ctypes.cast(w_ptr, ctypes.c_void_p),
239
- ctypes.cast(h_ptr, ctypes.c_void_p),
240
- ctypes.c_void_p(),
241
- )
242
- if ret != 0:
243
- raise NemuIpcError(f"Call nemu_capture_display failed. Return value={ret}")
244
-
245
- return w_ptr.contents.value, h_ptr.contents.value
246
-
247
- # ------------------------------------------------------------------
248
- # Touchable 接口实现
249
- # ------------------------------------------------------------------
250
- def __convert_pos(self, x: int, y: int) -> tuple[int, int]:
251
- # Android 显示屏有两套坐标:逻辑坐标与物理坐标。
252
- # 逻辑坐标原点始终是画面左上角,而物理坐标原点则始终是显示屏的左上角。
253
- # 如果屏幕画面旋转,会导致两个坐标的原点不同,坐标也不同。
254
- # ========
255
- # 这里传给 MuMu 的是逻辑坐标,ExternalRendererIpc DLL 内部会
256
- # 自动判断旋转,并转换为物理坐标。但是这部分有个 bug:
257
- # 旋转没有考虑到多显示器,只是以主显示器为准,若两个显示器旋转不一致,
258
- # 会导致错误地转换坐标。因此需要在 Python 层面 workaround 这个问题。
259
- # 通过判断主显示器与当前显示器的旋转,将坐标进行预转换,抵消 DLL 层的错误转换。
260
- display_id = self._get_display_id()
261
- if display_id == 0:
262
- return x, y
263
- else:
264
- primary = self.get_display_orientation(0)
265
- primary_size = self.query_resolution(0)
266
- current = self.get_display_orientation(display_id)
267
- if primary == current:
268
- return x, y
269
- else:
270
- # 如果旋转不一致,视为顺时针旋转了 90°
271
- # 因此我们要提前逆时针旋转 90°
272
- self._refresh_resolution()
273
- x, y = y, primary_size[1] - x
274
- return x, y
275
-
276
- @override
277
- def click(self, x: int, y: int) -> None:
278
- self._ensure_connected()
279
- display_id = self._get_display_id()
280
- x, y = self.__convert_pos(x, y)
281
- self._ipc.input_touch_down(self._connect_id, display_id, x, y)
282
- sleep(0.01)
283
- self._ipc.input_touch_up(self._connect_id, display_id)
284
-
285
- @override
286
- def swipe(
287
- self,
288
- x1: int,
289
- y1: int,
290
- x2: int,
291
- y2: int,
292
- duration: float | None = None,
293
- ) -> None:
294
- self._ensure_connected()
295
-
296
- duration = duration or 0.3
297
- steps = max(int(duration / 0.01), 2)
298
- display_id = self._get_display_id()
299
- x1, y1 = self.__convert_pos(x1, y1)
300
- x2, y2 = self.__convert_pos(x2, y2)
301
-
302
- xs = np.linspace(x1, x2, steps, dtype=int)
303
- ys = np.linspace(y1, y2, steps, dtype=int)
304
-
305
- # 按下第一点
306
- self._ipc.input_touch_down(self._connect_id, display_id, xs[0], ys[0])
307
- sleep(0.01)
308
- # 中间移动
309
- for px, py in zip(xs[1:-1], ys[1:-1]):
310
- self._ipc.input_touch_down(self._connect_id, display_id, px, py)
311
- sleep(0.01)
312
-
313
- # 最终抬起
314
- self._ipc.input_touch_up(self._connect_id, display_id)
315
- sleep(0.01)
316
-
317
- if __name__ == '__main__':
318
- nemu = NemuIpcImpl(NemuIpcImplConfig(
319
- r'F:\Apps\Netease\MuMuPlayer-12.0', 0, None,
320
- target_package_name='com.android.chrome',
321
- ))
322
- nemu.connect()
323
- # while True:
324
- # nemu.click(0, 0)
325
- nemu.click(100, 100)
326
- nemu.click(100*3, 100)
327
- nemu.click(100*3, 100*3)
1
+ import os
2
+ import ctypes
3
+ import logging
4
+ import time
5
+ from dataclasses import dataclass
6
+ from time import sleep
7
+ from typing import Literal
8
+ from typing_extensions import override
9
+
10
+ import cv2
11
+ import numpy as np
12
+ from cv2.typing import MatLike
13
+
14
+ from ...device import AndroidDevice, Device
15
+ from ...protocol import Touchable, Screenshotable
16
+ from ...registration import ImplConfig
17
+ from .external_renderer_ipc import ExternalRendererIpc
18
+ from kotonebot.errors import KotonebotError
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ class NemuIpcIncompatible(Exception):
24
+ """MuMu12 版本过低或 dll 不兼容"""
25
+ pass
26
+
27
+
28
+ class NemuIpcError(KotonebotError):
29
+ """调用 IPC 过程中发生错误"""
30
+ pass
31
+
32
+
33
+ @dataclass
34
+ class NemuIpcImplConfig(ImplConfig):
35
+ """nemu_ipc 能力的配置模型。"""
36
+ nemu_folder: str
37
+ r"""MuMu12 根目录(如 F:\Apps\Netease\MuMuPlayer-12.0)。"""
38
+ instance_id: int
39
+ """模拟器实例 ID。"""
40
+ display_id: int | None = 0
41
+ """目标显示器 ID,默认为 0(主显示器)。若为 None 且设置了 target_package_name,则自动获取对应的 display_id。"""
42
+ target_package_name: str | None = None
43
+ """目标应用包名,用于自动获取 display_id。"""
44
+ app_index: int = 0
45
+ """多开应用索引,传给 get_display_id 方法。"""
46
+ wait_package_timeout: float = 60 # 单位秒,-1 表示永远等待,0 表示不等待,立即抛出异常
47
+ wait_package_interval: float = 0.1 # 单位秒
48
+
49
+
50
+ class NemuIpcImpl(Touchable, Screenshotable):
51
+ """
52
+ 利用 MuMu12 提供的 external_renderer_ipc.dll 进行截图与触摸控制。
53
+ """
54
+
55
+ def __init__(self, config: NemuIpcImplConfig):
56
+ self.config = config
57
+ self.__width: int = 0
58
+ self.__height: int = 0
59
+ self.__connected: bool = False
60
+ self._connect_id: int = 0
61
+ self.nemu_folder = config.nemu_folder
62
+
63
+ # --------------------------- DLL 封装 ---------------------------
64
+ self._ipc = ExternalRendererIpc(config.nemu_folder)
65
+ logger.info("ExternalRendererIpc initialized and DLL loaded")
66
+
67
+ @property
68
+ def width(self) -> int:
69
+ """
70
+ 屏幕宽度。
71
+
72
+ 若为 0,表示未连接或未获取到分辨率。
73
+ """
74
+ return self.__width
75
+
76
+ @property
77
+ def height(self) -> int:
78
+ """
79
+ 屏幕高度。
80
+
81
+ 若为 0,表示未连接或未获取到分辨率。
82
+ """
83
+ return self.__height
84
+
85
+ @property
86
+ def connected(self) -> bool:
87
+ """是否已连接。"""
88
+ return self.__connected
89
+
90
+ # ------------------------------------------------------------------
91
+ # 基础控制
92
+ # ------------------------------------------------------------------
93
+
94
+ def _ensure_connected(self) -> None:
95
+ if not self.__connected:
96
+ self.connect()
97
+
98
+ def _get_display_id(self) -> int:
99
+ """获取有效的 display_id。"""
100
+ # 如果配置中直接指定了 display_id,直接返回
101
+ if self.config.display_id is not None:
102
+ return self.config.display_id
103
+
104
+ # 如果设置了 target_package_name,实时获取 display_id
105
+ if self.config.target_package_name:
106
+ self._ensure_connected()
107
+
108
+ timeout = self.config.wait_package_timeout
109
+ interval = self.config.wait_package_interval
110
+ if timeout == -1:
111
+ timeout = float('inf')
112
+ start_time = time.time()
113
+ while True:
114
+ display_id = self._ipc.get_display_id(
115
+ self._connect_id,
116
+ self.config.target_package_name,
117
+ self.config.app_index
118
+ )
119
+ if display_id >= 0:
120
+ return display_id
121
+ elif display_id == -1:
122
+ # 可以继续等
123
+ pass
124
+ else:
125
+ # 未知错误
126
+ raise NemuIpcError(f"Failed to get display_id for package '{self.config.target_package_name}', error code={display_id}")
127
+ if time.time() - start_time > timeout:
128
+ break
129
+ sleep(interval)
130
+
131
+ raise NemuIpcError(f"Failed to get display_id for package '{self.config.target_package_name}' within {timeout}s")
132
+
133
+ # 如果都没有设置,抛出错误
134
+ raise NemuIpcError("display_id is None and target_package_name is not set. Please set display_id or target_package_name in config.")
135
+
136
+ def connect(self) -> None:
137
+ """连接模拟器。"""
138
+ if self.__connected:
139
+ return
140
+
141
+ connect_id = self._ipc.connect(self.nemu_folder, self.config.instance_id)
142
+ if connect_id == 0:
143
+ raise NemuIpcError("nemu_connect failed, please check if the emulator is running and the instance ID is correct.")
144
+
145
+ self._connect_id = connect_id
146
+ self.__connected = True
147
+ logger.debug("NemuIpc connected, connect_id=%d", connect_id)
148
+
149
+ def disconnect(self) -> None:
150
+ """断开连接。"""
151
+ if not self.__connected:
152
+ return
153
+ self._ipc.disconnect(self._connect_id)
154
+ self.__connected = False
155
+ self._connect_id = 0
156
+ logger.debug("NemuIpc disconnected.")
157
+
158
+ # ------------------------------------------------------------------
159
+ # Screenshotable 接口实现
160
+ # ------------------------------------------------------------------
161
+ @property
162
+ def screen_size(self) -> tuple[int, int]:
163
+ """获取屏幕分辨率。"""
164
+ if self.__width == 0 or self.__height == 0:
165
+ self._refresh_resolution()
166
+ if self.__width == 0 or self.__height == 0:
167
+ raise NemuIpcError("Screen resolution not obtained, please connect to the emulator first.")
168
+ return self.__width, self.__height
169
+
170
+ @override
171
+ def detect_orientation(self):
172
+ return self.get_display_orientation(self._get_display_id())
173
+
174
+ def get_display_orientation(self, display_id: int = 0) -> Literal['portrait', 'landscape'] | None:
175
+ """获取指定显示屏的方向。"""
176
+ width, height = self.query_resolution(display_id)
177
+ if width > height:
178
+ return "landscape"
179
+ if height > width:
180
+ return "portrait"
181
+ return None
182
+
183
+ @override
184
+ def screenshot(self) -> MatLike:
185
+ self._ensure_connected()
186
+
187
+ # 必须每次都更新分辨率,因为屏幕可能会旋转
188
+ self._refresh_resolution()
189
+
190
+ length = self.__width * self.__height * 4 # RGBA
191
+ buf_type = ctypes.c_ubyte * length
192
+ buffer = buf_type()
193
+
194
+ w_ptr = ctypes.pointer(ctypes.c_int(self.__width))
195
+ h_ptr = ctypes.pointer(ctypes.c_int(self.__height))
196
+
197
+ ret = self._ipc.capture_display(
198
+ self._connect_id,
199
+ self._get_display_id(),
200
+ length,
201
+ ctypes.cast(w_ptr, ctypes.c_void_p),
202
+ ctypes.cast(h_ptr, ctypes.c_void_p),
203
+ ctypes.cast(buffer, ctypes.c_void_p),
204
+ )
205
+ if ret != 0:
206
+ raise NemuIpcError(f"nemu_capture_display screenshot failed, error code={ret}")
207
+
208
+ # 读入并转换数据
209
+ img = np.ctypeslib.as_array(buffer).reshape((self.__height, self.__width, 4))
210
+ # RGBA -> BGR
211
+ img = cv2.cvtColor(img, cv2.COLOR_RGBA2BGR)
212
+ cv2.flip(img, 0, dst=img)
213
+ return img
214
+
215
+ # --------------------------- 内部工具 -----------------------------
216
+
217
+ def _refresh_resolution(self) -> None:
218
+ """刷新分辨率信息。"""
219
+ display_id = self._get_display_id()
220
+ self.__width, self.__height = self.query_resolution(display_id)
221
+
222
+ def query_resolution(self, display_id: int = 0) -> tuple[int, int]:
223
+ """
224
+ 查询指定显示屏的分辨率。
225
+
226
+ :param display_id: 显示屏 ID。
227
+ :return: 分辨率 (width, height)。
228
+ :raise NemuIpcError: 查询失败。
229
+ """
230
+ self._ensure_connected()
231
+
232
+ w_ptr = ctypes.pointer(ctypes.c_int(0))
233
+ h_ptr = ctypes.pointer(ctypes.c_int(0))
234
+ ret = self._ipc.capture_display(
235
+ self._connect_id,
236
+ display_id,
237
+ 0,
238
+ ctypes.cast(w_ptr, ctypes.c_void_p),
239
+ ctypes.cast(h_ptr, ctypes.c_void_p),
240
+ ctypes.c_void_p(),
241
+ )
242
+ if ret != 0:
243
+ raise NemuIpcError(f"Call nemu_capture_display failed. Return value={ret}")
244
+
245
+ return w_ptr.contents.value, h_ptr.contents.value
246
+
247
+ # ------------------------------------------------------------------
248
+ # Touchable 接口实现
249
+ # ------------------------------------------------------------------
250
+ def __convert_pos(self, x: int, y: int) -> tuple[int, int]:
251
+ # Android 显示屏有两套坐标:逻辑坐标与物理坐标。
252
+ # 逻辑坐标原点始终是画面左上角,而物理坐标原点则始终是显示屏的左上角。
253
+ # 如果屏幕画面旋转,会导致两个坐标的原点不同,坐标也不同。
254
+ # ========
255
+ # 这里传给 MuMu 的是逻辑坐标,ExternalRendererIpc DLL 内部会
256
+ # 自动判断旋转,并转换为物理坐标。但是这部分有个 bug:
257
+ # 旋转没有考虑到多显示器,只是以主显示器为准,若两个显示器旋转不一致,
258
+ # 会导致错误地转换坐标。因此需要在 Python 层面 workaround 这个问题。
259
+ # 通过判断主显示器与当前显示器的旋转,将坐标进行预转换,抵消 DLL 层的错误转换。
260
+ display_id = self._get_display_id()
261
+ if display_id == 0:
262
+ return x, y
263
+ else:
264
+ primary = self.get_display_orientation(0)
265
+ primary_size = self.query_resolution(0)
266
+ current = self.get_display_orientation(display_id)
267
+ if primary == current:
268
+ return x, y
269
+ else:
270
+ # 如果旋转不一致,视为顺时针旋转了 90°
271
+ # 因此我们要提前逆时针旋转 90°
272
+ self._refresh_resolution()
273
+ x, y = y, primary_size[1] - x
274
+ return x, y
275
+
276
+ @override
277
+ def click(self, x: int, y: int) -> None:
278
+ self._ensure_connected()
279
+ display_id = self._get_display_id()
280
+ x, y = self.__convert_pos(x, y)
281
+ self._ipc.input_touch_down(self._connect_id, display_id, x, y)
282
+ sleep(0.01)
283
+ self._ipc.input_touch_up(self._connect_id, display_id)
284
+
285
+ @override
286
+ def swipe(
287
+ self,
288
+ x1: int,
289
+ y1: int,
290
+ x2: int,
291
+ y2: int,
292
+ duration: float | None = None,
293
+ ) -> None:
294
+ self._ensure_connected()
295
+
296
+ duration = duration or 0.3
297
+ steps = max(int(duration / 0.01), 2)
298
+ display_id = self._get_display_id()
299
+ x1, y1 = self.__convert_pos(x1, y1)
300
+ x2, y2 = self.__convert_pos(x2, y2)
301
+
302
+ xs = np.linspace(x1, x2, steps, dtype=int)
303
+ ys = np.linspace(y1, y2, steps, dtype=int)
304
+
305
+ # 按下第一点
306
+ self._ipc.input_touch_down(self._connect_id, display_id, xs[0], ys[0])
307
+ sleep(0.01)
308
+ # 中间移动
309
+ for px, py in zip(xs[1:-1], ys[1:-1]):
310
+ self._ipc.input_touch_down(self._connect_id, display_id, px, py)
311
+ sleep(0.01)
312
+
313
+ # 最终抬起
314
+ self._ipc.input_touch_up(self._connect_id, display_id)
315
+ sleep(0.01)
316
+
317
+ if __name__ == '__main__':
318
+ nemu = NemuIpcImpl(NemuIpcImplConfig(
319
+ r'F:\Apps\Netease\MuMuPlayer-12.0', 0, None,
320
+ target_package_name='com.android.chrome',
321
+ ))
322
+ nemu.connect()
323
+ # while True:
324
+ # nemu.click(0, 0)
325
+ nemu.click(100, 100)
326
+ nemu.click(100*3, 100)
327
+ nemu.click(100*3, 100*3)