handle.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import re
  5. from enum import Enum
  6. from cached_property import cached_property
  7. from anytree import NodeMixin, RenderTree, PreOrderIter
  8. from win32api import GetSystemMetrics, SendMessage, MAKELONG, PostMessage
  9. from win32print import GetDeviceCaps
  10. from win32process import GetWindowThreadProcessId
  11. from win32gui import (GetWindowText, EnumWindows, FindWindow, FindWindowEx,
  12. IsWindow, GetWindowRect, GetWindowDC, DeleteObject,
  13. SetForegroundWindow, IsWindowVisible, GetDC, GetParent,
  14. EnumChildWindows)
  15. from win32con import (SRCCOPY, DESKTOPHORZRES, DESKTOPVERTRES, WM_LBUTTONUP,
  16. WM_LBUTTONDOWN, WM_ACTIVATE, WA_ACTIVE, MK_LBUTTON,
  17. WM_NCHITTEST, WM_SETCURSOR, HTCLIENT, WM_MOUSEMOVE)
  18. from module.config.config import Config
  19. from module.logger import logger
  20. def handle_title2num(title: str) -> int:
  21. """
  22. 从标题到句柄号
  23. :param title:
  24. :return: 如果没有找到就是返回零
  25. """
  26. return FindWindow(None, title)
  27. def handle_num2title(num: int) -> str:
  28. """
  29. 通过句柄号返回窗口的标题,如果传入句柄号不合法则返回None
  30. :param num:
  31. :return:
  32. """
  33. return None if num is None or num == 0 or num == '' else GetWindowText(num)
  34. def is_handle_valid(num: int) -> bool:
  35. """
  36. 输入一个句柄号,如果还在返回True
  37. :param num:
  38. :return:
  39. """
  40. return IsWindow(num)
  41. def handle_num2pid(num: int) -> int:
  42. """
  43. 通过句柄号获取句柄进程id,如果句柄号非法则返回0
  44. :param num:
  45. :return:
  46. """
  47. return 0 if num is None or num == 0 or num == '' else GetWindowThreadProcessId(num)[1]
  48. def window_scale_rate() -> float:
  49. """
  50. 获取window的系统缩放 一遍是1
  51. :return:
  52. """
  53. hDC = GetDC(0)
  54. # 物理上(真实的)的 横纵向分辨率
  55. wReal = GetDeviceCaps(hDC, DESKTOPHORZRES)
  56. hReal = GetDeviceCaps(hDC, DESKTOPVERTRES)
  57. # 缩放后的 分辨率
  58. wAfter = GetSystemMetrics(0)
  59. hAfter = GetSystemMetrics(1)
  60. # print(wReal, wAfter)
  61. return round(wReal / wAfter, 2)
  62. class WindowNode(NodeMixin):
  63. def __init__(self, name, num, parent=None):
  64. super().__init__()
  65. self.name = name
  66. self.num = num
  67. self.parent = parent
  68. @classmethod
  69. def get_tree_depth(cls, root_node: 'WindowNode'):
  70. if not root_node.children:
  71. return 1 if root_node else 0
  72. return max(node.depth for node in root_node.descendants) + 1
  73. class EmulatorFamily(Enum):
  74. FAMILY_MUMU = 10 # mumu模拟器
  75. FAMILY_NOX = 20 # 夜神模拟器
  76. FAMILY_LD = 30 # 雷电模拟器
  77. FAMILY_MEMU = 40 # 逍遥模拟器
  78. FAMILY_BLUESTACKS = 50 # 蓝叠模拟器
  79. FAMILY_OTHER = 60 # 其他模拟器 待定
  80. # 各个模拟器的句柄树*******************************************************************************************************
  81. """"
  82. <MuMu>系列
  83. 模拟器的窗口名字
  84. ----MuMuPlayer (!如果是mumu12是MuMuPlayer, 否则是NemuPlayer)
  85. --------nemudisplay
  86. <雷电模拟器系列>
  87. 雷电模拟器的窗口名字
  88. ----TheRender
  89. --------sub
  90. <夜神模拟器系列> =====> 这个模拟器窗口很复杂,而且有的时候还会变化
  91. 夜神模拟器的窗口名字
  92. ----Nox
  93. ----Nox
  94. --------toolbar_nox
  95. --------Nox
  96. ------------Nox
  97. ----------------sub
  98. ---Nox
  99. --------Nox
  100. --------Nox ==> 妈的太多了自己用spy++看吧
  101. <蓝叠模拟器>
  102. 蓝叠模拟器的窗口名字
  103. ----HD-Player
  104. --------_ctl.W
  105. """""
  106. # **********************************************************************************************************************
  107. class Handle:
  108. emulator_list = ['MuMu12',
  109. 'MuMu',
  110. '雷电',
  111. '夜神',
  112. '蓝叠',
  113. '逍遥',
  114. '模拟器'] # 最后一个我又不知道还有哪些模拟器
  115. emulator_handle = {
  116. # 夜神
  117. 'nox_player': ['root_handle_title', 'Nox'],
  118. 'nox_player_64': ['root_handle_title', 'Nox'],
  119. 'nox_player_family': ['root_handle_title', 'Nox'],
  120. # 雷电
  121. 'ld_player': ['TheRender'],
  122. 'ld_player_4': ['TheRender'],
  123. 'ld_player_9': ['TheRender'],
  124. 'ld_player_family': ['TheRender'],
  125. # 逍遥
  126. 'memu_player': ['root_handle_title'],
  127. 'memu_player_family': ['root_handle_title'],
  128. # mumu
  129. 'mumu_player': ['root_handle_title', 'NemuPlayer'],
  130. 'mumu_player_12': ['root_handle_title', 'MuMuPlayer'],
  131. 'mumu_player_family': ['root_handle_title', 'MuMuPlayer'],
  132. # 蓝叠
  133. 'bluestacks_5': ['root_handle_title'],
  134. 'bluestacks_family': ['root_handle_title']
  135. }
  136. config: Config = None
  137. def __init__(self, config) -> None:
  138. """
  139. :param config:
  140. """
  141. logger.hr('Handle')
  142. if self.config is None:
  143. if isinstance(config, str):
  144. self.config = Config(config, task=None)
  145. else:
  146. self.config = config
  147. if not self.config.script.device.handle:
  148. logger.info('Handle is empty. oas not use handle')
  149. return
  150. if self.config.script.device.handle == '':
  151. logger.info('Handle is empty. oas not use handle')
  152. return
  153. # 获取根的句柄
  154. self.root_handle_title = ''
  155. self.root_handle_num = 0
  156. self.root_handle = self.config.script.device.handle
  157. if self.root_handle == "auto":
  158. logger.info('Handle is auto. oas will find window emulator')
  159. window_list = Handle.all_windows()
  160. self.root_handle_title = self.auto_handle_title(window_list)
  161. self.root_handle_num = handle_title2num(self.root_handle_title)
  162. if isinstance(self.root_handle, str):
  163. try:
  164. self.root_handle_num = int(self.root_handle)
  165. logger.info('Handle is handle num. oas use it as root handle num')
  166. if is_handle_valid(self.root_handle_num):
  167. logger.info(f'Handle number {self.root_handle_num} is valid')
  168. self.root_handle_title = handle_num2title(self.root_handle_num)
  169. except ValueError:
  170. logger.info('Handle is handle string. oas use it as root handle title')
  171. if handle_title2num(self.root_handle) != 0:
  172. self.root_handle_num = handle_title2num(self.root_handle)
  173. self.root_handle_title = self.root_handle
  174. logger.info(f'The root handle title is {self.root_handle_title} and num is {self.root_handle_num}')
  175. # 获取句柄树
  176. self.root_node = WindowNode(name=self.root_handle_title, num=self.root_handle_num)
  177. Handle.handle_tree(self.root_handle_num, self.root_node)
  178. logger.info('Emulator handle structure:')
  179. for pre, fill, node in RenderTree(self.root_node):
  180. logger.info("%s%s" % (pre, node.name))
  181. for pre, fill, node in RenderTree(self.root_node):
  182. logger.info("%s%s" % (pre, node.num))
  183. # 判断是哪一个模拟器 通过句柄树结构
  184. logger.info(f'Emulator family: {self.emulator_family}')
  185. # window系统的缩放
  186. logger.info(f'Your window screen scale rate: {window_scale_rate()}')
  187. _ = self.screenshot_handle_num
  188. logger.info(f'Screenshot handle num: {self.screenshot_handle_num}')
  189. logger.info(f'Emulator screenshot size: {self.screenshot_size}')
  190. @staticmethod
  191. def all_windows() -> list:
  192. """
  193. 获取桌面上的所有窗体
  194. :return: 类似这样['MuMu模拟器']
  195. """
  196. def enum_windows_callback(hwnd, windows):
  197. window_text = GetWindowText(hwnd)
  198. windows.append(window_text)
  199. windows = []
  200. EnumWindows(enum_windows_callback, windows)
  201. return windows
  202. @classmethod
  203. def auto_handle_title(cls, windows: list) -> str:
  204. """
  205. 返回第一个找到的有模拟器的标题
  206. :param windows:
  207. :return:
  208. """
  209. if windows is None:
  210. logger.error("handle_auto not get all wnidow")
  211. emu_list = []
  212. for window_title in windows:
  213. for item in Handle.emulator_list:
  214. if window_title.find(item) != -1:
  215. emu_list.append(window_title)
  216. if not len(emu_list):
  217. logger.error('Can not find emulator handle, please check your emulator is running')
  218. return None
  219. emulator_title = ''
  220. # 测试mumu12的时候发现 获取的全部的窗体标题有这样的: 'MuMuPlayer', 'MuMuPlayer', 'MuMuPlayer', 'MuMu模拟器12'
  221. # 事实上 我们只需要最后一个 'MuMu模拟器12',其他的不重要
  222. if 'MuMu模拟器12' in emu_list and 'MuMuPlayer' in emu_list:
  223. emulator_title = 'MuMu模拟器12'
  224. # MuMu5.0更新,窗体标题改动: 'MuMu模拟器','MuMuNxDevice','MuMu安卓设备'
  225. # 如果没有匹配上旧版本,尝试匹配MuMu5.0窗口名
  226. if emulator_title == '' and 'MuMu安卓设备' in emu_list:
  227. emulator_title = 'MuMu安卓设备'
  228. if len(emu_list) > 1 and emulator_title == '':
  229. logger.warning(f'Find more than one emulator handle, oas will use the first one {emu_list[0]}')
  230. emulator_title = emu_list[0]
  231. if len(emu_list) == 1:
  232. emulator_title = emu_list[0]
  233. logger.info(f'Handle auto seclect to find {emulator_title} and use it as root_title')
  234. return emulator_title
  235. @staticmethod
  236. def handle_tree(hwnd, node: WindowNode, level: int = 0) -> None:
  237. """
  238. 生成一个窗口的句柄树
  239. :param hwnd:
  240. :param node:
  241. :param level:
  242. :return:
  243. """
  244. child_windows = []
  245. EnumChildWindows(hwnd, lambda hwnd, param: param.append(hwnd), child_windows)
  246. if not child_windows:
  247. return
  248. for child_hwnd in child_windows:
  249. if GetParent(child_hwnd) == hwnd:
  250. child_text = GetWindowText(child_hwnd)
  251. child_node = WindowNode(name=child_text, num=child_hwnd, parent=node)
  252. # 递归遍历子窗体的子窗体
  253. Handle.handle_tree(child_hwnd, child_node, level + 1)
  254. @cached_property
  255. def emulator_family(self) -> EmulatorFamily:
  256. """
  257. 通过句柄树来判断这个是那个模拟器大类
  258. :return:
  259. """
  260. children_num = len(self.root_node.children)
  261. if children_num == 1: #
  262. name = self.root_node.children[0].name
  263. if name == 'MuMuPlayer':
  264. return EmulatorFamily.FAMILY_MUMU
  265. elif name == 'MuMuNxDevice':
  266. return EmulatorFamily.FAMILY_MUMU
  267. elif name == 'NemuPlayer':
  268. return EmulatorFamily.FAMILY_MUMU
  269. elif name == 'TheRender':
  270. return EmulatorFamily.FAMILY_LD
  271. elif name == 'HD-Player':
  272. return EmulatorFamily.FAMILY_BLUESTACKS
  273. elif children_num >= 3:
  274. name = self.root_node.children[0].name
  275. if name == 'Nox':
  276. return EmulatorFamily.FAMILY_NOX
  277. # 基于句柄标题的判定
  278. for emu in Handle.emulator_list:
  279. if self.root_handle_title.find(emu) != -1:
  280. if emu == 'MuMu':
  281. return EmulatorFamily.FAMILY_MUMU
  282. elif emu == '雷电':
  283. return EmulatorFamily.FAMILY_LD
  284. elif emu == '夜神':
  285. return EmulatorFamily.FAMILY_NOX
  286. elif emu == '蓝叠':
  287. return EmulatorFamily.FAMILY_BLUESTACKS
  288. elif emu == '逍遥':
  289. return EmulatorFamily.FAMILY_MEMU
  290. return EmulatorFamily.FAMILY_OTHER
  291. @cached_property
  292. def screenshot_handle_num(self) -> int:
  293. """
  294. 截屏的句柄其实并不是根句柄
  295. :return: 出错返回None
  296. """
  297. if self.emulator_family == EmulatorFamily.FAMILY_MUMU:
  298. # 使用正则匹配12 来判定是不是mumu12这并不是一个好的方法
  299. name = self.root_node.children[0].name
  300. num = self.root_node.children[0].num
  301. if name == 'MuMuPlayer':
  302. logger.info('The emulator is MuMu模拟器12')
  303. return num
  304. elif name == 'NemuPlayer':
  305. logger.info('The emulator is MuMu模拟器')
  306. return num
  307. elif name == 'MuMuNxDevice':
  308. logger.info('The emulator is MuMu模拟器5.0')
  309. return num
  310. # 夜神
  311. elif self.emulator_family == EmulatorFamily.FAMILY_NOX:
  312. try:
  313. return self.root_node.children[1].children[1].num
  314. except:
  315. return self.root_node.children[2].children[1].num
  316. elif self.emulator_family == EmulatorFamily.FAMILY_LD:
  317. for node in PreOrderIter(self.root_node):
  318. if node.name == Handle.emulator_handle['ld_player_family'][0]:
  319. return node.num
  320. elif self.emulator_family == EmulatorFamily.FAMILY_MEMU:
  321. for node in PreOrderIter(self.root_node):
  322. if node.name == Handle.emulator_handle['memu_player_family']:
  323. return node.num
  324. elif self.emulator_family == EmulatorFamily.FAMILY_BLUESTACKS:
  325. for node in PreOrderIter(self.root_node):
  326. if node.name == Handle.emulator_handle['bluestacks_family']:
  327. return node.num
  328. return self.root_node.num
  329. @cached_property
  330. def screenshot_size(self) -> tuple or None:
  331. """
  332. 第一个是width 第二个是heigth
  333. 2023.7.1 在高缩放的设备上应该输出1280X720
  334. :return:
  335. """
  336. winRect = GetWindowRect(self.screenshot_handle_num)
  337. scale_rate = window_scale_rate()
  338. width_before: int = winRect[2] - winRect[0] # 右x-左x
  339. height_before: int = winRect[3] - winRect[1] # 下y - 上y 计算高度
  340. width, height = width_before, height_before
  341. if abs((width_before * scale_rate) - 1280) < 5:
  342. width = 1280
  343. if abs((height_before * scale_rate) - 720) < 5:
  344. height = 720
  345. if width is None or height is None:
  346. logger.error(f'Get screenshot size error, width={width}, height={height}')
  347. return None
  348. return width, height
  349. @cached_property
  350. def window_scale_rate(self) -> float:
  351. """
  352. 获取window的系统缩放 一般是1
  353. :return:
  354. """
  355. hDC = GetDC(0)
  356. # 物理上(真实的)的 横纵向分辨率
  357. wReal = GetDeviceCaps(hDC, DESKTOPHORZRES)
  358. hReal = GetDeviceCaps(hDC, DESKTOPVERTRES)
  359. # 缩放后的 分辨率
  360. wAfter = GetSystemMetrics(0)
  361. hAfter = GetSystemMetrics(1)
  362. # print(wReal, wAfter)
  363. return round(wReal / wAfter, 2)
  364. @classmethod
  365. def handle_has_children(cls, hwnd: int, name: str = 'MuMuPlayer12') -> bool:
  366. root_node = WindowNode(name=name, num=hwnd)
  367. Handle.handle_tree(hwnd=hwnd, node=root_node)
  368. handle_depth = WindowNode.get_tree_depth(root_node)
  369. if handle_depth > 1:
  370. logger.info(f'Window handle [{hwnd}] depth: {handle_depth}')
  371. return True
  372. return False
  373. if __name__ == '__main__':
  374. h = Handle(config='oas1')
  375. # logger.info(h.auto_handle_title(h.all_windows()))
  376. # logger.info(h.root_handle_num)
  377. # logger.info(h.emulator_family)