Files
yiyezhqiu-refactored/tools/acceptance/toolbar_ui.py
T

164 lines
7.4 KiB
Python

"""UI Automation helpers scoped to one toolbar process."""
from pywinauto import Application
from pywinauto.keyboard import send_keys
import ctypes
from PIL import Image
import win32gui
import win32process
import win32ui
from packaged_menu import wait_for
TOOLBAR_TITLE = "一叶知秋悬浮工具栏"
PANEL_TITLE = "一叶知秋_重构版"
PRIMARY_FEATURES = ("自动位号", "属性批改", "属性显示", "设计检查", "网络工具", "BOM 工具", "PDF 导出")
class ToolbarUI:
def __init__(self, pid):
self.pid = pid
self.app = Application(backend="uia").connect(process=pid, timeout=15)
self.toolbar = self.app.window(title=TOOLBAR_TITLE)
self.panel = self.app.window(title=PANEL_TITLE)
self.toolbar.wait("visible", timeout=15)
def click(self, control):
wrapper = control.wrapper_object() if hasattr(control, 'wrapper_object') else control
wrapper.top_level_parent().set_focus()
rect = wrapper.rectangle()
point = ((rect.left + rect.right) // 2, (rect.top + rect.bottom) // 2)
assert win32process.GetWindowThreadProcessId(win32gui.WindowFromPoint(point))[1] == self.pid
wrapper.click_input()
@staticmethod
def capture(window):
# Capture the owned window rather than a desktop rectangle. Desktop
# BitBlt can return stale composition while native Qt/UIA remains live.
handle = window.handle
left, top, right, bottom = win32gui.GetWindowRect(handle)
width, height = right - left, bottom - top
dc = win32gui.GetWindowDC(handle)
source = win32ui.CreateDCFromHandle(dc)
target = source.CreateCompatibleDC()
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(source, width, height)
previous = target.SelectObject(bitmap)
try:
assert ctypes.windll.user32.PrintWindow(handle, target.GetSafeHdc(), 2)
return Image.frombuffer('RGB', (width, height), bitmap.GetBitmapBits(True), 'raw', 'BGRX', 0, 1)
finally:
target.SelectObject(previous)
win32gui.DeleteObject(bitmap.GetHandle())
target.DeleteDC()
source.DeleteDC()
win32gui.ReleaseDC(handle, dc)
def menu_action(self, name):
overflow = [feature for feature in PRIMARY_FEATURES
if not self.toolbar.child_window(title=feature).exists(timeout=0.1)]
actions = overflow + ['操作历史', '设置', '刷新设计快照', '切换明暗主题', '退出工具']
assert name in actions, (name, actions)
more = next(button for button in self.toolbar.descendants(control_type="Button")
if button.window_text() in ("更多", "更多功能"))
def popup_handle():
handles = []
def inspect(handle, _):
if (win32process.GetWindowThreadProcessId(handle)[1] == self.pid
and win32gui.IsWindowVisible(handle)
and 'Popup' in win32gui.GetClassName(handle)):
handles.append(handle)
win32gui.EnumWindows(inspect, None)
return handles[0] if handles else None
previous = popup_handle()
if previous:
win32gui.PostMessage(previous, 0x100, 0x1B, 0)
win32gui.PostMessage(previous, 0x101, 0x1B, 0)
wait_for(lambda: not win32gui.IsWindowVisible(previous), 5)
self.click(more)
try:
popup = wait_for(popup_handle, 5)
except TimeoutError:
# Restoring focus can dismiss an already opening Qt popup. The
# second physical click is scoped and hit-tested to this process.
self.click(more)
popup = wait_for(popup_handle, 5)
# Qt menu actions lack a UIA Invoke provider. Address the owned popup
# directly so keyboard events never reach the user's host application.
# A freshly opened Qt menu has no current action. Home does not select
# its first action; the first Down does. Count that first Down too.
for key in [0x28] * (actions.index(name) + 1) + [0x0D]:
win32gui.PostMessage(popup, 0x100, key, 0)
win32gui.PostMessage(popup, 0x101, key, 0)
wait_for(lambda: not win32gui.IsWindowVisible(popup), 5)
def feature(self, name):
button = self.toolbar.child_window(title=name)
if button.exists(timeout=0.2) and button.is_visible():
self.click(button)
else:
self.menu_action(name)
self.panel.wait("visible", timeout=15)
wait_for(lambda: name in self.texts(self.panel), 10)
self.panel.set_focus()
def select_combo(self, combo, index, expected):
# Qt does not publish combo list items through UIA SelectionItem.
# Use the real list and send keys only after checking its owner.
def popups():
handles = []
win32gui.EnumWindows(lambda h, _: handles.append(h)
if win32process.GetWindowThreadProcessId(h)[1] == self.pid
and 'Popup' in win32gui.GetClassName(h) and win32gui.IsWindowVisible(h)
else None, None)
return handles
for handle in popups():
win32gui.PostMessage(handle, 0x100, 0x1B, 0)
win32gui.PostMessage(handle, 0x101, 0x1B, 0)
wait_for(lambda: not popups(), 5)
self.click(combo)
wait_for(popups, 5)
foreground = win32gui.GetForegroundWindow()
assert win32process.GetWindowThreadProcessId(foreground)[1] == self.pid
send_keys('{HOME}' + '{DOWN}' * index + '{ENTER}')
wait_for(lambda: not popups(), 5)
wait_for(lambda: combo.wrapper_object().iface_value.CurrentValue == expected, 5)
def native_dialog(self, title):
def find():
handles = []
win32gui.EnumWindows(lambda h, _: handles.append(h)
if win32process.GetWindowThreadProcessId(h)[1] == self.pid
and win32gui.GetWindowText(h) == title and win32gui.IsWindowVisible(h)
else None, None)
return handles[0] if handles else None
handle = wait_for(find, 10)
return Application(backend='win32').connect(handle=handle).window(handle=handle)
@staticmethod
def texts(window):
return [item.window_text() for item in window.descendants(control_type="Text")]
def status_detail(self):
for item in self.toolbar.descendants(control_type='Text'):
if item.window_text().startswith(('● ', '○ ')):
element = item.element_info._element
return str(element.GetCurrentPropertyValue(30159) or element.GetCurrentPropertyValue(30013) or '')
return ''
def collapse(self):
self.toolbar.child_window(title="收起面板", control_type="Button").invoke()
self.panel.wait_not("visible", timeout=10)
assert self.toolbar.is_visible()
def expand(self):
self.toolbar.child_window(title="展开面板", control_type="Button").invoke()
self.panel.wait("visible", timeout=10)
self.panel.set_focus()
def exit(self):
try:
self.menu_action("退出工具")
except TimeoutError:
# Closing the toolbar invokes the same explicit request_exit path.
# Closing the feature panel would only collapse it.
win32gui.PostMessage(self.toolbar.handle, 0x10, 0, 0)
self.toolbar.wait_not("exists", timeout=15)