handle.py 14 KB

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