handle.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. import re
  5. from cached_property import cached_property
  6. from anytree import NodeMixin, RenderTree
  7. from win32process import GetWindowThreadProcessId
  8. from win32gui import (GetWindowText, EnumWindows, FindWindow, FindWindowEx,
  9. IsWindow, GetWindowRect, GetWindowDC, DeleteObject,
  10. SetForegroundWindow, IsWindowVisible, GetDC, GetParent,
  11. EnumChildWindows)
  12. from module.config.config import Config
  13. from module.exception import RequestHumanTakeover, EmulatorNotRunningError
  14. from module.logger import logger
  15. def handle_title2num(title: str) -> int:
  16. """
  17. 从标题到句柄号
  18. :param title:
  19. :return: 如果没有找到就是返回零
  20. """
  21. return FindWindow(None, title)
  22. def handle_num2title(num: int) -> str:
  23. """
  24. 通过句柄号返回窗口的标题,如果传入句柄号不合法则返回None
  25. :param num:
  26. :return:
  27. """
  28. return None if num is None or num == 0 or num == '' else GetWindowText(num)
  29. def is_handle_valid(num: int) -> bool:
  30. """
  31. 输入一个句柄号,如果还在返回True
  32. :param num:
  33. :return:
  34. """
  35. return IsWindow(num)
  36. def handle_num2pid(num :int) -> int:
  37. """
  38. 通过句柄号获取句柄进程id,如果句柄号非法则返回0
  39. :param num:
  40. :return:
  41. """
  42. return 0 if num is None or num == 0 or num == '' else GetWindowThreadProcessId(num)[1]
  43. class WindowNode(NodeMixin):
  44. def __init__(self, name, num, parent=None):
  45. super().__init__()
  46. self.name = name
  47. self.num = num
  48. self.parent = parent
  49. class Handle:
  50. emulator_list = ['MuMu',
  51. '雷电',
  52. '夜神',
  53. '蓝叠',
  54. '逍遥',
  55. '模拟器'] # 最后一个我又不知道还有哪些模拟器
  56. emulator_handle = {
  57. # 夜神
  58. 'nox_player': ['root_handle_title', 'Nox'],
  59. 'nox_player_64': ['root_handle_title', 'Nox'],
  60. 'nox_player_family':['root_handle_title', 'Nox'],
  61. # 雷电
  62. 'ld_player': ['TheRender'],
  63. 'ld_player_4': ['TheRender'],
  64. 'ld_player_9': ['TheRender'],
  65. 'ld_player_family': ['TheRender'],
  66. # 逍遥
  67. 'memu_player': ['root_handle_title'],
  68. 'memu_player_family': ['root_handle_title'],
  69. # mumu
  70. 'mumu_player': ['root_handle_title', 'NemuPlayer'],
  71. 'mumu_player_12': ['root_handle_title', 'MuMuPlayer'],
  72. 'mumu_player_family': ['root_handle_title', 'MuMuPlayer'],
  73. # 蓝叠
  74. 'bluestacks_5': ['root_handle_title'],
  75. 'bluestacks_family': ['root_handle_title']
  76. }
  77. def __init__(self, config) -> None:
  78. """
  79. :param config:
  80. """
  81. logger.hr('Handle')
  82. if isinstance(config, str):
  83. self.config = Config(config, task=None)
  84. else:
  85. self.config = config
  86. # 获取根的句柄
  87. self.root_handle_title = ''
  88. self.root_handle_num = 0
  89. self.root_handle = self.config.get_arg('Script', 'Device', 'Handle')
  90. if self.root_handle == "auto":
  91. logger.info('handle is auto. oas will find window emulator')
  92. window_list = Handle.all_windows()
  93. self.root_handle_title = self.auto_handle_title(window_list)
  94. self.root_handle_num = handle_title2num(self.root_handle_title)
  95. elif isinstance(self.root_handle, int):
  96. logger.info('handle is handle num. oas use it as root handle num')
  97. if is_handle_valid(self.root_handle):
  98. logger.info(f'handle number {self.root_handle} is valid')
  99. self.root_handle_title = handle_num2title(self.root_handle)
  100. self.root_handle_num = self.root_handle
  101. elif isinstance(self.root_handle, str):
  102. logger.info('handle is handle string. oas use it as root handle title')
  103. if handle_title2num(self.root_handle) !=0:
  104. self.root_handle_num = handle_title2num(self.root_handle)
  105. self.root_handle_title = self.root_handle
  106. logger.info(f'the root handle title is {self.root_handle_title} and num is {self.root_handle_num}')
  107. # 获取句柄树
  108. self.root_node = WindowNode(name=self.root_handle_title, num=self.root_handle_num)
  109. Handle.handle_tree(self.root_handle_num, self.root_node)
  110. logger.info('the emulator handle structure is')
  111. for pre, fill, node in RenderTree(self.root_node):
  112. logger.info("%s%s" % (pre, node.name))
  113. @staticmethod
  114. def all_windows() -> list:
  115. """
  116. 获取桌面上的所有窗体
  117. :return: 类似这样['MuMu模拟器']
  118. """
  119. def enum_windows_callback(hwnd, windows):
  120. window_text = GetWindowText(hwnd)
  121. windows.append(window_text)
  122. windows = []
  123. EnumWindows(enum_windows_callback, windows)
  124. return windows
  125. @classmethod
  126. def auto_handle_title(cls, windows: list) -> str:
  127. """
  128. 返回第一个找到的有模拟器的标题
  129. :param windows:
  130. :return:
  131. """
  132. if windows is None:
  133. logger.error("handle_auto not get all wnidow")
  134. for window_title in windows:
  135. for item in Handle.emulator_list:
  136. if window_title.find(item) != -1:
  137. logger.info(f'handle auto seclect to find {window_title} and use it as root_title')
  138. return window_title
  139. return None
  140. @staticmethod
  141. def handle_tree(hwnd, node: WindowNode, level: int =0) -> None:
  142. """
  143. 生成一个窗口的句柄树
  144. :param hwnd:
  145. :param node:
  146. :param level:
  147. :return:
  148. """
  149. child_windows = []
  150. EnumChildWindows(hwnd, lambda hwnd, param: param.append(hwnd), child_windows)
  151. if not child_windows:
  152. return
  153. for child_hwnd in child_windows:
  154. if GetParent(child_hwnd) == hwnd:
  155. child_text = GetWindowText(child_hwnd)
  156. child_node = WindowNode(name=child_text, num=child_hwnd, parent=node)
  157. # 递归遍历子窗体的子窗体
  158. Handle.handle_tree(child_hwnd, child_node, level + 1)
  159. @cached_property
  160. def emulator_family(self) -> str:
  161. """
  162. 通过句柄标题来判断这个是那个模拟器大类
  163. :return:
  164. """
  165. for emu in Handle.emulator_list:
  166. if self.root_handle_title.find(emu) != -1:
  167. if emu == 'MuMu':
  168. return 'mumu_player_family'
  169. elif emu == '雷电':
  170. return 'ld_player_family'
  171. elif emu == '夜神':
  172. return 'nox_player_family'
  173. elif emu == '蓝叠':
  174. return 'bluestacks_player_family'
  175. elif emu == '逍遥':
  176. return 'memu_player_family'
  177. if __name__ == '__main__':
  178. h = Handle(config='oas1')
  179. logger.info(h.auto_handle_title(h.all_windows()))
  180. logger.info(h.root_handle_num)
  181. logger.info(h.emulator_family)