diff --git a/.superpowers/sdd/2026-10-11-horizontal-toolbar-and-compact-panels/task-shell-report.md b/.superpowers/sdd/2026-10-11-horizontal-toolbar-and-compact-panels/task-shell-report.md deleted file mode 100644 index 7e5ae04..0000000 --- a/.superpowers/sdd/2026-10-11-horizontal-toolbar-and-compact-panels/task-shell-report.md +++ /dev/null @@ -1,32 +0,0 @@ -# Toolbar shell and shared state report - -Implemented approved tasks 1 and 2 in the horizontal-toolbar worktree. - -## Delivered behavior - -- A persistent 772×44 logical-pixel toolbar replaces the leaf entry. Seven primary functions retain their existing page indices and full accessible names. History, settings, refresh, theme, and exit are available from More. At narrow widths display/check/network/BOM overflow in that order; Start, refdes, attributes, PDF and status retain priority. -- Standalone CLI launch shows the toolbar; `--feature` shows the existing corresponding page. Clicking the same active function hides its panel. Expand restores the last page. Close and minimize hide the panel; explicit exit stops owned timers, shuts down business workers and closes both windows. Startup registration protects actual exit and update installation. -- RefDes preview/apply controls and signals now live on RefDesPage. MainWindow's apply_button/preview_button references refer to those local controls for existing integration callers; there are no global visible apply/preview buttons. -- Central project/bridge/selection/operation setters synchronize the panel and toolbar. Fixed status width and elision prevent selection changes from resizing the toolbar. Tooltip includes project, page, complete selected references and operation. A shared lifecycle timer observes existing controllers' task flags, including PDF threads, without changing controllers or creating another bridge session. -- Lightweight selection watcher keeps running while hidden. Pause, disconnected state, missing previously valid channel and project changes stop presenting old references as current. Selection resumes through the same existing controllers and preserves pending edits and PDF inputs. -- UI placement and per-page dimensions are independently validated and atomically saved to `%LOCALAPPDATA%/DxProductivity/ui-layout.json`. Panel anchoring chooses below/above, accounts for native frames, and clamps to available bounds. Dragging is restricted to the handle and moves an open panel with the toolbar. Screen changes reapply bounds. -- Added CollapsibleSection for subsequent page work: content_layout, set_summary(), set_expanded(), is_expanded, expanded_changed. Removed floating_button.py and old sidebar widgets. Existing business controllers, CLI feature IDs and bridge sessions are preserved. -- UI tests explicitly call request_exit at teardown because ordinary close is intentionally a hide operation; this prevents workers remaining alive during Qt cleanup. - -## Verification - -Before implementation, test_horizontal_toolbar.py failed 2/2 with missing show_toolbar(), proving the new behavior tests exercised the unimplemented contract. - -Consolidated targeted shell suite: **48 passed in 71.24 seconds**. Command used supplied Python, worktree src PYTHONPATH, PYTHONUTF8=1 and QT_QPA_PLATFORM=offscreen: - -`python -m pytest tests/ui/test_horizontal_toolbar.py tests/ui/test_main_window.py tests/ui/test_compact_floating_window.py tests/ui/test_live_selection.py tests/ui/test_layout_preferences.py tests/ui/test_update_launch.py tests/ui/test_snapshot_refresh.py tests/ui/test_inspection_controller.py -q` - -After final snapshot-status initialization and monitor-change hookups, the affected main-window/live-selection/snapshot/update/toolbar suite was rerun: **29 passed in 34.86 seconds**. Accessibility enumeration was then broadened from icon buttons to all toolbar buttons and its targeted test passed. `git diff --check` passed. - -Coverage includes seven button routes and More routes, repeated toggles, inputs/timer retention, minimization, drag-only handle, native-frame screen clamping, per-page persistence, malformed JSON, negative monitor coordinates, single/multi/empty selection, hidden-panel pause/recovery/project change, unchanged watcher/page instances, passive focus retention, in-flight operation status, menu registration guards, and update handoff shutdown. - -Screenshot `toolbar-shell.png` beside this report was generated and visually reviewed; it shows all seven functions and selected CE18 in a single readable row, with grip and expand icons rendered correctly. - -## Remaining acceptance boundary - -This is the shell stage. Existing pages retain their current content layout except the required local RefDes action row; subsequent page tasks must remove redundant headings and reduce their own parameter-area heights. Native host operations, multiple physical displays and Windows 100%/125%/150% DPI were not performed by this worker; root owns those acceptance checks. Synthetic negative coordinates, offscreen native-frame bounds, passive focus, and screen-change connections are covered here. No user DxDesigner process or project was touched. Packaging and acceptance scripts modified by root were excluded from this worker's commit. diff --git a/docs/user/PDF_export.md b/docs/user/PDF_export.md index 7096e35..ede31ba 100644 --- a/docs/user/PDF_export.md +++ b/docs/user/PDF_export.md @@ -2,6 +2,8 @@ 在 DxDesigner 的“Dx 效率工具”菜单中打开“PDF 导出”,工具会按当前桥接工程执行导出。 +也可点击悬浮工具栏的 PDF 按钮展开面板。面板常驻显示范围、输出目录、保存后自动导出与操作按钮;配色、文字处理和引擎路径放在“高级选项”中,当前有效取值会显示为摘要。 + 范围有三种: - **整工程**:导出当前工程中的全部原理图页。 diff --git a/docs/user/一叶知秋_重构版_更新说明.md b/docs/user/一叶知秋_重构版_更新说明.md index b68d63d..be6fa0c 100644 --- a/docs/user/一叶知秋_重构版_更新说明.md +++ b/docs/user/一叶知秋_重构版_更新说明.md @@ -1,18 +1,19 @@ # 一叶知秋_重构版 更新说明 +## 横向工具栏与功能面板 + +- 工具以一排置顶工具栏常驻,提供 Start、位号、属性、显示、检查、网络、BOM 和 PDF;历史、设置、刷新、主题及退出放在“更多”中。 +- 点击功能展开对应面板,再点同一功能或“收起面板”收起。面板关闭和最小化也会收起;退出整个工具使用“更多 → 退出工具”。 +- 收起后工具栏继续显示选择与任务状态;悬停可查看完整位号、工程、图页和状态信息。拖动左侧手柄移动,位置与各页面大小会保存。 +- 页面移除固定左导航、重复标题与说明,操作按钮移到对应页面。低频设置折叠为高级选项,并显示当前有效参数摘要。 +- PDF 保留三种范围、输出目录、打开目录和保存后自动导出;配色、文字处理与引擎设置可在高级选项中调整。 + ## 中文 PDF 与实时选择 - 修复 GBK 中文被按西文输出造成的乱码;默认采用中文兼容模式,嵌入字体及 Unicode 映射,保留图形和颜色。可选西文兼容或原生字体,手动和自动导出共用文字设置。 - DxDesigner 的单选、多选、取消选择及切页会实时同步;底部显示当前选中数量和位号。位号、属性、可见性、BOM 的选中范围同步更新,PDF 的当前页随宿主切页更新。 - 选择同步保留仍选中器件的新属性输入及 PDF 表单;应用或恢复进行时暂缓更新,操作结束后读取最新选择。无法识别的新增器件会自动请求完整快照。 -## 紧凑窗口与悬浮入口 - -- 左侧 PDF 导出移到设置上方。 -- 默认窗口缩小为 960 × 600,可缩到 860 × 540;字体、导航和控件间距同步收紧,规则区和表格支持滚动。 -- 点击右上角“收起为悬浮窗”或窗口最小化,会显示置顶的叶子悬浮入口。拖动入口可移动,点击可恢复当前页面、窗口位置和输入内容;收起期间桥接及后台任务继续运行。 -- 右键悬浮入口可打开或退出工具;主窗口关闭按钮用于退出。 - ## PDF 配色与输出目录 - PDF 默认采用 mentor_PDF_output 的工程参考配色,也可选择原生配色;手动导出与保存后自动导出使用同一设置。 diff --git a/tools/acceptance/compact_window.py b/tools/acceptance/compact_window.py index f25fe40..3d2a3bf 100644 --- a/tools/acceptance/compact_window.py +++ b/tools/acceptance/compact_window.py @@ -1,27 +1,21 @@ -"""Check the packaged floating UI on an already-connected DxDesigner run.""" -from __future__ import annotations - +"""Inspect the horizontal toolbar on a connected acceptance run.""" import argparse import ctypes import json import os from pathlib import Path import shlex -import time - -import win32gui import win32api -import win32process -from pywinauto import Application +import win32gui from pywinauto import mouse - from packaged_menu import tools_running, wait_for - +from toolbar_ui import PRIMARY_FEATURES, ToolbarUI def main(): parser = argparse.ArgumentParser() parser.add_argument("executable", type=Path) parser.add_argument("--leave-collapsed", action="store_true") + parser.add_argument("--evidence", type=Path) options = parser.parse_args() executable = options.executable.resolve() tool = wait_for(lambda: next((p for p in tools_running() if @@ -29,94 +23,58 @@ def main(): args = shlex.split(tool.command_line, posix=False) request = Path(args[args.index("--request") + 1].strip('"')) snapshot = json.loads(request.read_text(encoding="utf-8-sig")) - app = Application(backend="uia").connect(process=tool.pid, timeout=15) - - def floating(): - handles = [] - def inspect(handle, _): - if (win32process.GetWindowThreadProcessId(handle)[1] == tool.pid - and win32gui.GetWindowText(handle) == "一叶知秋悬浮入口" - and win32gui.IsWindowVisible(handle)): - handles.append(handle) - win32gui.EnumWindows(inspect, None) - return handles[0] if handles else None - - collapsed_handle = floating() - if collapsed_handle: - app.window(handle=collapsed_handle).wrapper_object().invoke() - window = app.window(title="一叶知秋_重构版") - window.wait("visible", timeout=15) - main_handle = window.handle - nav = window.descendants(control_type="ListItem") - assert [item.window_text() for item in nav][-2:] == ["PDF 导出", "设置"] - next(item for item in nav if item.window_text() == "PDF 导出").select() - assert [item.window_text() for item in nav if item.is_selected()] == ["PDF 导出"] - assert "桥接已连接" in [item.window_text() for item in window.descendants(control_type="Text")] - bounds = win32gui.GetClientRect(main_handle) - dpi = ctypes.windll.user32.GetDpiForWindow(main_handle) - assert abs(bounds[2] - 960 * dpi / 96) <= 2, (bounds, dpi) - assert abs(bounds[3] - 600 * dpi / 96) <= 2, (bounds, dpi) - progress = request.parent / "apply-progress.json" - + ui = ToolbarUI(tool.pid) + evidence = options.evidence or Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/acceptance/toolbar-20261011" + evidence.mkdir(parents=True, exist_ok=True) + handle = ui.toolbar.handle + dpi = ctypes.windll.user32.GetDpiForWindow(handle) + bounds = win32gui.GetClientRect(handle) + assert bounds[3] * 96 / dpi <= 46, (bounds, dpi) + assert win32gui.GetWindowLong(handle, -20) & 0x8 + buttons = [button.rectangle() for button in ui.toolbar.descendants(control_type="Button")] + assert len({(rect.top, rect.bottom) for rect in buttons}) == 1, buttons + ui.toolbar.capture_as_image().save(str(evidence / "toolbar.png")) + if ui.panel.exists(timeout=0.2) and ui.panel.is_visible(): + ui.collapse() + pages = [] + for name in (*PRIMARY_FEATURES, "操作历史", "设置"): + ui.feature(name) + panel_bounds = win32gui.GetClientRect(ui.panel.handle) + panel_dpi = ctypes.windll.user32.GetDpiForWindow(ui.panel.handle) + assert panel_bounds[2] * 96 / panel_dpi <= 800, (name, panel_bounds) + assert panel_bounds[3] * 96 / panel_dpi <= 520, (name, panel_bounds) + ui.panel.capture_as_image().save(str(evidence / f"page-{len(pages)}.png")) + pages.append({"page": name, "client_rect": panel_bounds, "dpi": panel_dpi}) + ui.collapse() + progress = request.with_name("apply-progress.json") before = progress.stat().st_mtime_ns - window.child_window(title="收起为悬浮窗", control_type="Button").invoke() - handle = wait_for(floating) - assert not win32gui.IsWindowVisible(main_handle) - assert win32gui.GetWindowLong(handle, -20) & 0x8 # WS_EX_TOPMOST wait_for(lambda: progress.stat().st_mtime_ns > before, 15) first = win32gui.GetWindowRect(handle) - - # Qt derives global mouse coordinates from the actual Windows pointer. - # Exercise a real drag on the verified, topmost floating button, then - # restore the pointer. SendMessage alone cannot verify this gesture. - width, height = win32gui.GetClientRect(handle)[2:] - x, y = width // 2, height // 2 + grip = ui.toolbar.child_window(title="拖动工具栏", control_type="Text").rectangle() pointer = win32gui.GetCursorPos() - start = (first[0] + x, first[1] + y) - finish = (start[0] - 30, start[1] - 20) + start = ((grip.left + grip.right) // 2, (grip.top + grip.bottom) // 2) try: mouse.press(coords=start) - mouse.move(coords=finish) - mouse.release(coords=finish) + mouse.move(coords=(start[0] - 30, start[1] - 20)) + mouse.release(coords=(start[0] - 30, start[1] - 20)) finally: mouse.release(coords=win32gui.GetCursorPos()) win32api.SetCursorPos(pointer) moved = wait_for(lambda: win32gui.GetWindowRect(handle) if win32gui.GetWindowRect(handle) != first else None) - assert not win32gui.IsWindowVisible(main_handle) - app.window(handle=handle).wrapper_object().invoke() - window.wait("visible", timeout=15) - assert not floating() - assert [item.window_text() for item in window.descendants(control_type="ListItem") if item.is_selected()] == ["PDF 导出"] - - old_snapshot = snapshot["snapshot_id"] - window.child_window(title="刷新设计快照", control_type="Button").invoke() - def refreshed(): - try: - data = json.loads(request.read_text(encoding="utf-8-sig")) - return data if data["snapshot_id"] != old_snapshot else None - except (OSError, ValueError): - return None - fresh = wait_for(refreshed, 15) - assert fresh["design_path"] == snapshot["design_path"] - window.minimize() - handle = wait_for(floating) - assert not win32gui.IsWindowVisible(main_handle) - app.window(handle=handle).wrapper_object().invoke() - window.wait("visible", timeout=15) + assert not ui.panel.is_visible() + ui.feature("PDF 导出") + ui.panel.minimize() + wait_for(lambda: not ui.panel.is_visible()) + ui.expand() + assert "PDF 导出" in ui.texts(ui.panel) if options.leave_collapsed: - window.child_window(title="收起为悬浮窗", control_type="Button").invoke() - wait_for(floating) + ui.collapse() result = {"executable": str(executable), "pid": tool.pid, "request": str(request), - "project": snapshot["design_path"], "dpi": dpi, "client_rect": bounds, - "pdf_above_settings": True, "floating_heartbeat_updated": True, - "drag_before": first, "drag_after": moved, "restore_kept_pdf_page": True, - "fresh_snapshot": fresh["snapshot_id"], "native_minimize_restored": True, - "left_collapsed": options.leave_collapsed} - evidence = Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/acceptance/compact-floating-20261011" - evidence.mkdir(parents=True, exist_ok=True) + "project": snapshot["design_path"], "dpi": dpi, "toolbar_client_rect": bounds, + "pages": pages, "heartbeat_updated": True, "drag_before": first, + "drag_after": moved, "minimize_restored": True, "left_collapsed": options.leave_collapsed} (evidence / "native-ui.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") - print("PASS COMPACT NATIVE FLOATING UI", json.dumps(result, ensure_ascii=False), flush=True) - + print("PASS NATIVE HORIZONTAL TOOLBAR", json.dumps(result, ensure_ascii=False), flush=True) if __name__ == "__main__": main() diff --git a/tools/acceptance/live_selection.py b/tools/acceptance/live_selection.py index d64c2f9..a76a7d9 100644 --- a/tools/acceptance/live_selection.py +++ b/tools/acceptance/live_selection.py @@ -16,6 +16,7 @@ from pywinauto import Application from dx_productivity.bridge.startup_assets import generate_startup_assets, vbscript_string from packaged_menu import tools_running, wait_for +from toolbar_ui import ToolbarUI def main(): @@ -56,8 +57,9 @@ Next request = Path(args[args.index('--request') + 1].strip('"')) initial = json.loads(request.read_text(encoding='utf-8-sig')) selection = request.with_name('selection.json') - ui = Application(backend='uia').connect(process=tool.pid, timeout=15) - window = ui.window(title='一叶知秋_重构版') + live_ui = ToolbarUI(tool.pid) + ui = live_ui.app + window = live_ui.panel window.wait('visible', timeout=15) main_handle = window.handle refs = {'uid:' + c['stable_uid'].casefold(): c['refdes'] for c in initial['components'] if c['stable_uid']} @@ -71,7 +73,7 @@ Next except (OSError, ValueError, KeyError): return None def displayed(expected): - texts = [x.window_text() for x in window.descendants(control_type='Text')] + texts = live_ui.texts(window) + live_ui.texts(live_ui.toolbar) matches = [text for text in texts if text.startswith(f'已选 {len(expected)} 个')] return matches[0] if matches and all(ref in matches[0] for ref in expected[:4]) else None @@ -107,12 +109,12 @@ ActiveView.Refresh select(['CE17'], 'single-capacitor') select(['LE03'], 'single-inductor') select(['CE17', 'LE03'], 'multiple') - window.child_window(title='属性批改', control_type='ListItem').select() + live_ui.feature('属性批改') rows = [x.window_text() for x in window.descendants(control_type='Text')] assert any(text.startswith('已选 2 个') and 'CE17' in text and 'LE03' in text for text in rows) select([], 'deselected') - window.child_window(title='自动位号', control_type='ListItem').select() - window.child_window(title='收起为悬浮窗', control_type='Button').invoke() + live_ui.feature('自动位号') + live_ui.collapse() wait_for(lambda: not win32gui.IsWindowVisible(main_handle)) script = base / 'collapsed-select.vbs' native_name = next(component['stable_uid'] for component in initial['components'] if component['refdes'] == 'CE17') @@ -122,17 +124,20 @@ ActiveView.Refresh handles = [] def inspect(handle, _): if (win32process.GetWindowThreadProcessId(handle)[1] == tool.pid - and win32gui.GetWindowText(handle) == '一叶知秋悬浮入口' + and win32gui.GetWindowText(handle) == '一叶知秋悬浮工具栏' and win32gui.IsWindowVisible(handle)): handles.append(handle) win32gui.EnumWindows(inspect, None) assert len(handles) == 1 - ui.window(handle=handles[0]).wrapper_object().invoke() + toolbar_label = wait_for(lambda: next((text for text in live_ui.texts(live_ui.toolbar) + if 'CE17' in text), None), 10) + live_ui.expand() window.wait('visible', timeout=15) wait_for(lambda: displayed(['CE17']), 10) - evidence.append({'case': 'collapsed-selection', 'selected': ['CE17'], 'restored_selection_current': True}) + evidence.append({'case': 'collapsed-selection', 'selected': ['CE17'], + 'toolbar_label': toolbar_label, 'restored_selection_current': True}) finally: - win32gui.PostMessage(main_handle, 0x10, 0, 0) + live_ui.exit() assert native_call.wait(timeout=15) == 0 log.close() report = {'executable': str(exe), 'project': str(project), 'pid': tool.pid, diff --git a/tools/acceptance/packaged_menu.py b/tools/acceptance/packaged_menu.py index 85856d1..122c6a2 100644 --- a/tools/acceptance/packaged_menu.py +++ b/tools/acceptance/packaged_menu.py @@ -61,10 +61,22 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("executable", type=Path) parser.add_argument("--features") + parser.add_argument("--project", type=Path) + parser.add_argument("--host-pid", type=int) + parser.add_argument("--evidence", type=Path) + parser.add_argument("--menu-script", type=Path) options = parser.parse_args() + global PROJECT, HOST_PID, BASE + if options.project: + PROJECT = options.project.resolve() + if options.host_pid: + HOST_PID = options.host_pid + if options.evidence: + BASE = options.evidence.resolve() + BASE.mkdir(parents=True, exist_ok=True) root = options.executable.resolve().parent helper = Path(__file__).with_name("run_dx_script.py") - install = Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/startup-refactored/MenuAdd.vbs" + install = options.menu_script or Path(os.environ["LOCALAPPDATA"]) / "DxProductivity/startup-refactored/MenuAdd.vbs" subprocess.run([sys.executable, str(helper), "--project", str(PROJECT), str(install)], timeout=30, check=True) cases = [(1, "refdes", "自动位号"), (2, "property-change", "属性批改"), (3, "property-visibility", "属性显示"), (4, "inspection", "设计检查"), @@ -109,15 +121,15 @@ Next if p.pid not in before and "--request" in p.command_line and Path(p.executable).resolve() == options.executable.resolve(): return p tool = wait_for(new_tool) - app = Application(backend="uia").connect(process=tool.pid, timeout=15) - window = app.window(title="一叶知秋_重构版") + from toolbar_ui import ToolbarUI + toolbar_ui = ToolbarUI(tool.pid) + window = toolbar_ui.panel window.wait("visible", timeout=15) texts = [x.window_text() for x in window.descendants(control_type="Text")] - selected = [x.window_text() for x in window.descendants(control_type="ListItem") if x.is_selected()] - assert selected == [expected], (feature, selected) + assert expected in texts, (feature, texts) assert "桥接已连接" in texts and PROJECT.name in texts, texts - results.append({"feature": feature, "pid": tool.pid, "selected_page": selected[0], "bridge": "connected", "project": PROJECT.name, "executable": tool.executable}) - window.close() + results.append({"feature": feature, "pid": tool.pid, "selected_page": expected, "bridge": "connected", "project": PROJECT.name, "executable": tool.executable}) + toolbar_ui.exit() elif feature == "compatibility": def close_completion(): probe = BASE.parent.parent / "compatibility.json" diff --git a/tools/acceptance/render_toolbar.py b/tools/acceptance/render_toolbar.py new file mode 100644 index 0000000..62f3195 --- /dev/null +++ b/tools/acceptance/render_toolbar.py @@ -0,0 +1,48 @@ +"""Render every page at a chosen Qt scale using an isolated UI profile.""" +import argparse +import json +import os +from pathlib import Path + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--request', type=Path) + parser.add_argument('--evidence', required=True, type=Path) + options = parser.parse_args() + evidence = options.evidence.resolve() + evidence.mkdir(parents=True, exist_ok=True) + os.environ['LOCALAPPDATA'] = str(evidence / 'profile') + from PySide6.QtWidgets import QAbstractButton + from dx_productivity.ui.app import create_application, create_main_window + app = create_application([]) + window = create_main_window(options.request) + report = {'scale': os.environ.get('QT_SCALE_FACTOR', '1'), 'pages': []} + try: + window.show_toolbar() + app.processEvents() + window.toolbar.grab().save(str(evidence / 'toolbar.png')) + report['toolbar_size'] = [window.toolbar.width(), window.toolbar.height()] + for index, name in enumerate(window.navigation_items()): + window.show_panel(index) + app.processEvents() + app.processEvents() + outside = [] + for button in window.pages.currentWidget().findChildren(QAbstractButton): + if button.isVisibleTo(window): + point = button.mapTo(window, button.rect().bottomRight()) + if not window.rect().contains(point): + outside.append(button.text()) + window.grab().save(str(evidence / f'page-{index}.png')) + report['pages'].append({'name': name, 'size': [window.width(), window.height()], + 'outside_buttons': outside}) + assert not any(page['outside_buttons'] for page in report['pages']), report + finally: + window.request_exit() + app.processEvents() + (evidence / 'render.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8') + print(json.dumps(report, ensure_ascii=False)) + + +if __name__ == '__main__': + main() diff --git a/tools/acceptance/toolbar_ui.py b/tools/acceptance/toolbar_ui.py new file mode 100644 index 0000000..442fe69 --- /dev/null +++ b/tools/acceptance/toolbar_ui.py @@ -0,0 +1,51 @@ +"""UI Automation helpers scoped to one toolbar process.""" +from pywinauto import Application +from packaged_menu import wait_for + +TOOLBAR_TITLE = "一叶知秋悬浮工具栏" +PANEL_TITLE = "一叶知秋_重构版" +PRIMARY_FEATURES = ("自动位号", "属性批改", "属性显示", "设计检查", "网络工具", "BOM 工具", "PDF 导出") + +class ToolbarUI: + def __init__(self, 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 menu_action(self, name): + more = next(button for button in self.toolbar.descendants(control_type="Button") + if button.window_text() in ("更多", "更多功能")) + more.invoke() + def find_action(): + for window in self.app.windows(): + for item in window.descendants(control_type="MenuItem"): + if item.window_text() == name: + return item + wait_for(find_action, 5).invoke() + + def feature(self, name): + button = self.toolbar.child_window(title=name, control_type="Button") + if button.exists(timeout=0.2) and button.is_visible(): + button.invoke() + else: + self.menu_action(name) + self.panel.wait("visible", timeout=15) + assert name in self.texts(self.panel) + + @staticmethod + def texts(window): + return [item.window_text() for item in window.descendants(control_type="Text")] + + 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) + + def exit(self): + self.menu_action("退出工具") + self.toolbar.wait_not("exists", timeout=15)