feat: follow connected DX minimize and restore state

This commit is contained in:
阿白叔 committed 2026-10-12 23:23:36 +08:00
1 parent b51bcb0b3e
commit f3b027b494
10 files changed
+475 -2

No files matched your search

@@ -0,0 +1,45 @@
# 跟随 DX 最小化验收(2026-10-12)
工具现在跟随所连接的 DxDesigner 窗口。DX 最小化时隐藏工具栏、面板和打开的更多菜单;DX 恢复时还原此前的展开或收起状态,保留页面与表单输入。隐藏只改变可见性,后台定时器及桥接会话继续运行。
## 实现与范围
原生快照和轻量选择状态增加可选的 `host_view_handle`。UI 验证其桥接 run ID 和工程路径,通过 Win32 GA_ROOTOWNER 找到所属 DX 顶层窗口,并保存 HWND/PID。独立 150 ms 监听器读取 IsIconic,不依赖选择变化或事务完成。切页后原视图关闭也不影响已缓存的顶层绑定;句柄或 PID 失效时不读取其他窗口。
初始 DX 已最小化时,工具延后显示。若此时还没有创建原生窗口句柄,也按隐藏处理。恢复采用 WA_ShowWithoutActivating,不走显式用户点击入口的激活路径;退出时停止监听器。无桥接的独立启动或没有宿主标识的旧桥接文件维持独立工具栏行为,后续匹配的选择状态可补全宿主绑定。
## 自动检查
| 检查 | 结果 | 记录 |
|---|---|---|
| 新行为修改前 | 8 项因行为或监听器缺失而失败 | `build/test-evidence/host-visibility-red.xml` |
| 最小化与恢复、初始隐藏、输入保留、后台定时器、退出、弹出菜单、所属宿主和延后绑定 | 8 passed;1 项焦点检查在 offscreen 跳过 | `build/test-evidence/host-visibility-green.xml` |
| 相关窗口、更新退出、选择、协议及原生 VBS 回归 | 68 passed;同一 offscreen 焦点检查跳过 | `build/test-evidence/host-visibility-targeted.xml` |
| 原生 Windows 焦点检查 | 1 passed,恢复后另一测试窗口保持活动 | `build/test-evidence/host-native-focus.xml` |
| VBScript 请求与选择的宿主标识 | cscript 断言通过,含标识不可用时的零值 | `tests/vbs/test_refdes_export.vbs` |
| 最终便携包 | 16 passed,包含九页入口、中文路径、运行库和 ZIP 校验 | `build/test-evidence/host-visibility-packaged.xml` |
| 独立代码审查 | 无剩余可操作 P1/P2 | `build/test-evidence/host-visibility-review.md` |
offscreen 平台会激活每个显示的窗口,不能用于验证原生焦点,因此该项单独在 Windows 后端执行。上表的检查集有重叠,不将数量相加。
## 最终包实机
独立工程为 `%LOCALAPPDATA%/DxProductivity/acceptance/native-20261010/1GPHY_RTL8211F/1GPHY_RTL8211F.prj`,DX PID 57584、主 HWND 9051710。由更新后的原生菜单打开最终 EXE PID 86508,其视图 HWND 593196 正确解析为该主窗口。
- DX 初始已最小化,启动后工具保持隐藏;恢复 DX 后工具栏和自动位号面板显示,桥接已连接。
- 面板展开时两轮最小化/恢复,工具栏与面板同步隐藏,恢复仍展开。
- 面板收起时两轮最小化/恢复,工具栏隐藏,恢复仅显示工具栏。
- 每轮隐藏期间 `apply-progress.json` 时间继续更新,DX 没有被后台桥接还原;恢复后前台 PID 均未变为工具 PID。
- 最终恢复用户原本的 DX 最小化状态,工具随之隐藏;未写回器件。
证据:`%LOCALAPPDATA%/DxProductivity/acceptance/host-visibility-20261012/host-native.json`,同目录含恢复后的工具栏及面板截图。循环脚本为 `tools/acceptance/host_visibility.py`。
本轮实机使用一个 DX;第二宿主隔离由模拟窗口后端覆盖。尝试强制设置 DX 前台时,Windows 的前台限制拒绝了验收辅助程序,最终用例验证工具恢复后不占用前台;原生 Qt 焦点检查另验证活动窗口保留。
## 发布
- 包目录:`release/一叶知秋_重构版_横向工具栏版`。
- ZIP SHA-256:`5d9bb051690eba512bd1017fee4e2afa8a35f85cd817f709d433fb8990debb55`。
- EXE SHA-256:`d1af32fca413de8a9e857d093c5843414598ab779bcb6e2b805e67d795dae9d6`。
业务功能全量验收见 `toolbar-acceptance-20261011.md`。本次未解决 PON 全工程快照阻塞,亦未测量长会话原生集合保留的内存增长。
@@ -6,6 +6,7 @@
- 点击功能展开对应面板,再点同一功能或“收起面板”收起。面板关闭和最小化也会收起;退出整个工具使用“更多 → 退出工具”。
- 工具栏末尾使用明确的“展开 ▾ / 收起 ▴”按钮;展开内容以无标题栏卡片贴在工具栏下方,不再显示独立应用窗口的标题框。
- 修复“更多”的文字与菜单箭头重叠;正常宽度下两者并排,极窄屏自动保留箭头菜单入口,屏幕恢复后显示文字。
- 工具跟随所属 DxDesigner 窗口:DX 最小化时隐藏工具栏和面板,DX 恢复时还原此前的展开或收起状态,并保留表单输入。隐藏期间选择监听和导出继续运行;恢复工具不会抢走 DX 焦点。
- 收起后工具栏继续显示选择与任务状态;悬停可查看完整位号、工程、图页和状态信息。拖动左侧手柄移动,位置与各页面大小会保存。
- 页面移除固定左导航、重复标题与说明,操作按钮移到对应页面。低频设置折叠为高级选项,并显示当前有效参数摘要。
- PDF 保留三种范围、输出目录、打开目录和保存后自动导出;配色、文字处理与引擎设置可在高级选项中调整。
+5 -2
View File
@@ -126,7 +126,9 @@ Sub DxBridgePublishSelection(runRoot, runId, snapshotId, _
ByRef lastSelection, ByRef pageContext, ByRef pageKeys)
Dim designPath, blockName, sheetName, currentContext, selectedKeys
Dim text, numberJson, ready, newPageKeys
Dim hostViewHandleJson
On Error Resume Next
hostViewHandleJson = DxBridgeHostViewHandleJson()
designPath = DxBridgeDesignPath()
blockName = DxBridgeCurrentBlockName()
sheetName = DxBridgeCurrentSheetName()
@@ -151,12 +153,13 @@ Sub DxBridgePublishSelection(runRoot, runId, snapshotId, _
text = "{""state"":""unavailable"",""run_id"":""" & _
DxToolsJson(runId) & """,""snapshot_id"":""" & _
DxToolsJson(snapshotId) & """,""design_path"":""" & _
DxToolsJson(designPath) & """}"
DxToolsJson(designPath) & """,""host_view_handle"":" & hostViewHandleJson & "}"
If ready Then
text = "{""state"":""ready"",""run_id"":""" & _
DxToolsJson(runId) & """,""snapshot_id"":""" & _
DxToolsJson(snapshotId) & """,""design_path"":""" & _
DxToolsJson(designPath) & """,""active_block_name"":""" & _
DxToolsJson(designPath) & """,""host_view_handle"":" & hostViewHandleJson & _
",""active_block_name"":""" & _
DxToolsJson(blockName) & """,""current_sheet_name"":""" & _
DxToolsJson(sheetName) & """,""current_sheet_number"":" & _
numberJson & ",""selected_keys"":" & selectedKeys & _
@@ -154,6 +154,7 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _
" ""snapshot_id"": """ & DxToolsJson(snapshotId) & """," & vbCrLf & _
" ""design_id"": """ & DxToolsJson(designId) & """," & vbCrLf & _
" ""design_path"": """ & DxToolsJson(designPath) & """," & vbCrLf & _
" ""host_view_handle"": " & DxBridgeHostViewHandleJson() & "," & vbCrLf & _
" ""active_block_name"": """ & _
DxToolsJson(activeBlockName) & """," & vbCrLf & _
" ""current_sheet_number"": " & currentSheetNumberJson & "," & vbCrLf & _
@@ -168,6 +169,17 @@ Function DxRefreshSnapshot(runRoot, runId, objectMap, originalMap, _
DxRefreshSnapshot = True
End Function
Function DxBridgeHostViewHandleJson()
Dim handle
handle = 0
On Error Resume Next
handle = CLng(Application.ActiveViewHandle)
If Err.Number <> 0 Then handle = 0
Err.Clear
On Error GoTo 0
DxBridgeHostViewHandleJson = CStr(handle)
End Function
Function DxBridgeExportAttributes(component)
Dim attribute
Dim text
+2
View File
@@ -24,6 +24,7 @@ from dx_productivity.ui.bom_controller import BomController
from dx_productivity.ui.bom_page import BomPage
from dx_productivity.ui.main_window import MainWindow
from dx_productivity.ui.selection_watcher import SelectionWatcher
from dx_productivity.ui.host_window_watcher import HostWindowWatcher
from dx_productivity.ui.startup_controller import StartupController
from dx_productivity.ui.property_change_controller import PropertyChangeController
from dx_productivity.ui.property_change_page import PropertyChangePage
@@ -321,6 +322,7 @@ def create_main_window(request_path: Path | None = None) -> MainWindow:
if watcher is not None:
watcher.snapshot_reloaded.connect(pdf_export_controller.load_snapshot)
window.selection_watcher = SelectionWatcher(window, request_path)
window.host_window_watcher = HostWindowWatcher(window, request_path)
window.set_active_page(0)
startup_controller = StartupController(_tool_root(), window)
window.startup_controller = startup_controller
@@ -0,0 +1,90 @@
"""Follow only the native DxDesigner window that owns this bridge session."""
from __future__ import annotations
from dataclasses import dataclass
import json
import os
from pathlib import Path
from PySide6.QtCore import QObject, QTimer
@dataclass(frozen=True)
class HostWindow:
handle: int
pid: int
class WindowsHostWindows:
def resolve(self, view_handle: int) -> HostWindow | None:
if os.name != 'nt':
return None
import win32gui
import win32process
try:
# The 32-bit host can publish a signed HWND value.
view_handle &= 0xFFFFFFFF
if not win32gui.IsWindow(view_handle):
return None
handle = win32gui.GetAncestor(view_handle, 3) # GA_ROOTOWNER
if not handle or not win32gui.GetWindowText(handle).startswith('DxDesigner'):
return None
return HostWindow(handle, win32process.GetWindowThreadProcessId(handle)[1])
except win32gui.error:
return None
def is_minimized(self, host: HostWindow) -> bool | None:
import win32gui
import win32process
try:
if (not win32gui.IsWindow(host.handle)
or win32process.GetWindowThreadProcessId(host.handle)[1] != host.pid
or not win32gui.GetWindowText(host.handle).startswith('DxDesigner')):
return None
return bool(win32gui.IsIconic(host.handle))
except win32gui.error:
return None
class HostWindowWatcher(QObject):
def __init__(self, window, request_path: Path, *, backend=None) -> None:
super().__init__(window)
self.window = window
self.backend = backend if backend is not None else WindowsHostWindows()
self.selection_path = request_path.with_name('selection.json')
self.host = self._read_host(request_path)
self.timer = QTimer(self)
self.timer.setInterval(150)
self.timer.timeout.connect(self._check)
self.timer.start()
self._check()
def _read_host(self, path: Path):
try:
data = json.loads(path.read_text(encoding='utf-8-sig'))
except (OSError, ValueError):
return None
snapshot = self.window.refdes_controller.snapshot
if (snapshot is None or not isinstance(data, dict)
or data.get('run_id') != snapshot.run_id
or not isinstance(data.get('design_path'), str)
or os.path.normcase(os.path.normpath(data['design_path']))
!= os.path.normcase(os.path.normpath(snapshot.design_path))):
return None
handle = data.get('host_view_handle')
if type(handle) is not int or handle == 0:
return None
return self.backend.resolve(handle)
def _check(self) -> None:
if self.window._closing:
self.timer.stop()
return
if self.host is None:
self.host = self._read_host(self.selection_path)
if self.host is not None:
minimized = self.backend.is_minimized(self.host)
if minimized is not None:
self.window.set_host_minimized(minimized)
+40
View File
@@ -29,6 +29,9 @@ class MainWindow(QMainWindow):
)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self._closing = False
self._host_minimized = False
self._host_restore_toolbar = False
self._host_restore_panel = False
self._placing = False
self._effective_page_size = None
self._active_page = 0
@@ -93,6 +96,9 @@ class MainWindow(QMainWindow):
def show_toolbar(self) -> None:
if self._closing:
return
if self._host_minimized:
self._host_restore_toolbar = True
return
if not self._toolbar_positioned:
screen = self.toolbar.screen() or QApplication.primaryScreen()
position = self.layout_preferences.position
@@ -108,6 +114,11 @@ class MainWindow(QMainWindow):
def show_panel(self, index: int | None = None) -> None:
if self._closing:
return
if self._host_minimized:
self.set_active_page(self._active_page if index is None else index)
self._host_restore_toolbar = True
self._host_restore_panel = True
return
self.show_toolbar()
self.set_active_page(self._active_page if index is None else index)
self._anchor_panel()
@@ -120,11 +131,40 @@ class MainWindow(QMainWindow):
def hide_panel(self) -> None:
if self._closing:
return
if self._host_minimized:
self._host_restore_panel = False
return
self._remember_size()
self.hide()
self.show_toolbar()
self.toolbar.set_panel_state(self._active_page, False)
def set_host_minimized(self, minimized: bool) -> None:
"""Temporarily hide tool surfaces without changing their working state."""
if self._closing or self._host_minimized == minimized:
return
self._host_minimized = minimized
if minimized:
self._host_restore_toolbar = self.toolbar.isVisible()
self._host_restore_panel = self.isVisible()
self._remember_size()
self.toolbar.more_menu.close()
self.hide()
self.toolbar.hide()
return
if self._host_restore_toolbar:
self.show_toolbar()
if self._host_restore_panel:
# Restore passively; explicit user clicks still use show_panel().
passive = self.testAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)
self._anchor_panel()
self.showNormal()
self._anchor_panel()
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, passive)
self._host_restore_toolbar = False
self._host_restore_panel = False
collapse_to_floating = hide_panel
restore_from_floating = show_panel
+153
View File
@@ -0,0 +1,153 @@
import json
from types import SimpleNamespace
import pytest
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QLineEdit, QWidget
from dx_productivity.ui.main_window import MainWindow
@pytest.mark.parametrize('expanded', (False, True))
def test_host_minimize_hides_both_windows_and_restores_previous_panel(qtbot, tmp_path, expanded):
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
page = QLineEdit('unfinished input')
window.set_page(1, page, '属性批改')
window.show_panel(1) if expanded else window.show_toolbar()
ticks = []
timer = QTimer(window)
timer.timeout.connect(lambda: ticks.append(1))
timer.start(10)
window.set_host_minimized(True)
assert not window.toolbar.isVisible() and not window.isVisible()
qtbot.waitUntil(lambda: len(ticks) >= 2)
window.set_host_minimized(True)
window.set_host_minimized(False)
assert window.toolbar.isVisible()
assert window.isVisible() is expanded
assert page.text() == 'unfinished input'
if expanded:
assert window.pages.currentIndex() == 1
def test_initial_minimized_host_defers_requested_page_until_restore(qtbot, tmp_path):
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.set_host_minimized(True)
window.show_panel(7)
window.show_toolbar()
assert not window.isVisible() and not window.toolbar.isVisible()
window.set_host_minimized(False)
assert window.isVisible() and window.toolbar.isVisible()
assert window.pages.currentIndex() == 7
def test_collapse_during_host_minimize_remains_collapsed_after_restore(qtbot, tmp_path):
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.show_panel(0)
window.set_host_minimized(True)
window.hide_panel()
assert not window.toolbar.isVisible()
window.set_host_minimized(False)
assert window.toolbar.isVisible() and not window.isVisible()
def test_host_restore_does_not_activate_feature_panel(qtbot, qapp, tmp_path):
if qapp.platformName() == 'offscreen':
pytest.skip('Offscreen activates every shown window; focus requires the native window backend')
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.show_panel(0)
window.set_host_minimized(True)
host = QWidget()
qtbot.addWidget(host)
host.show()
host.activateWindow()
qapp.processEvents()
active = qapp.activeWindow()
window.set_host_minimized(False)
qapp.processEvents()
assert window.isVisible() and qapp.activeWindow() is active
def test_explicit_exit_while_host_minimized_cannot_restore_windows(qtbot, tmp_path):
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.show_panel(0)
window.set_host_minimized(True)
window.request_exit()
window.set_host_minimized(False)
assert not window.isVisible() and not window.toolbar.isVisible()
def test_host_minimize_closes_more_popup(qtbot, qapp, tmp_path):
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.show_toolbar()
window.toolbar.more_menu.popup(window.toolbar.more_button.mapToGlobal(window.toolbar.more_button.rect().bottomLeft()))
qapp.processEvents()
assert window.toolbar.more_menu.isVisible()
window.set_host_minimized(True)
assert not window.toolbar.more_menu.isVisible()
assert not window.toolbar.isVisible()
class FakeHostWindows:
def __init__(self):
self.minimized = {100: False, 200: False}
def resolve(self, view_handle):
return view_handle if view_handle in self.minimized else None
def is_minimized(self, handle):
return self.minimized.get(handle)
def test_watcher_follows_exact_bridge_host_even_during_transaction(qtbot, tmp_path):
from dx_productivity.ui.host_window_watcher import HostWindowWatcher
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.refdes_controller = SimpleNamespace(snapshot=SimpleNamespace(run_id='run-1', design_path='C:/demo.prj'), _apply_in_flight=True)
request = tmp_path / 'request.json'
request.write_text(json.dumps({'run_id': 'run-1', 'design_path': 'C:/demo.prj', 'host_view_handle': 100}), encoding='utf-8')
backend = FakeHostWindows()
watcher = HostWindowWatcher(window, request, backend=backend)
window.show_panel(0)
backend.minimized[200] = True
watcher._check()
assert window.toolbar.isVisible() and window.isVisible()
backend.minimized[100] = True
watcher._check()
assert not window.toolbar.isVisible() and not window.isVisible()
backend.minimized[100] = False
watcher._check()
assert window.toolbar.isVisible() and window.isVisible()
window.request_exit()
assert not watcher.timer.isActive()
def test_watcher_can_bind_later_from_selection_without_using_foreign_run(qtbot, tmp_path):
from dx_productivity.ui.host_window_watcher import HostWindowWatcher
window = MainWindow(layout_path=tmp_path / 'layout.json')
qtbot.addWidget(window)
window.refdes_controller = SimpleNamespace(snapshot=SimpleNamespace(run_id='run-1', design_path='C:/demo.prj'))
request = tmp_path / 'request.json'
request.write_text(json.dumps({'run_id': 'run-1', 'design_path': 'C:/demo.prj', 'host_view_handle': 0}), encoding='utf-8')
backend = FakeHostWindows()
backend.minimized[100] = True
watcher = HostWindowWatcher(window, request, backend=backend)
window.show_toolbar()
selection = tmp_path / 'selection.json'
for run_id, design_path in (('other-run', 'C:/demo.prj'), ('run-1', 'C:/other.prj')):
selection.write_text(json.dumps({'run_id': run_id, 'design_path': design_path, 'host_view_handle': 100}), encoding='utf-8')
watcher._check()
assert window.toolbar.isVisible()
selection.write_text(json.dumps({'run_id': 'run-1', 'design_path': 'C:/demo.prj', 'host_view_handle': 100}), encoding='utf-8')
watcher._check()
assert not window.toolbar.isVisible()
+21
View File
@@ -3,6 +3,7 @@ Option Explicit
Const VDM_COMP = 128
Const VDM_NET = 32
Const VD_SELECTED = 1
Const VD_ALL = 0
Const SHORT_NAME = 3
Dim Fso
@@ -22,6 +23,10 @@ Dim RequestText
Dim InitialComponentReleased
Dim RefreshedMap
Dim FreshComponent
Dim LastSelection
Dim PageContext
Dim PageKeys
Dim SelectionText
Class FakeParentBlock
Public Name
@@ -79,6 +84,7 @@ End Class
Class FakeApplicationHost
Public TheComponent
Public ProjectPath
Public ActiveViewHandle
Public Function GetProjectData()
Set GetProjectData = New FakeProjectData
@@ -125,6 +131,8 @@ Call LoadGlobal(Fso.GetAbsolutePathName(Fso.BuildPath( _
ScriptRoot, "..\..\integration\dxdesigner795\BridgeCommon.vbs")))
Call LoadGlobal(Fso.GetAbsolutePathName(Fso.BuildPath( _
ScriptRoot, "..\..\integration\dxdesigner795\core\Snapshot.vbs")))
Call LoadGlobal(Fso.GetAbsolutePathName(Fso.BuildPath( _
ScriptRoot, "..\..\integration\dxdesigner795\core\Mailbox.vbs")))
TempRoot = Fso.BuildPath(Fso.GetSpecialFolder(2), _
"dx-tools-export-" & Replace(CStr(Timer), ".", "-"))
@@ -148,6 +156,7 @@ Component.ComponentName = "R1"
Set Application = New FakeApplicationHost
Set Application.TheComponent = Component
Application.ProjectPath = "C:\Projects\board.prj"
Application.ActiveViewHandle = 12345
Set ActiveView = New FakeActiveView
Set ActiveView.TheComponent = Component
Set ActiveView.Block = New FakeBlock
@@ -171,11 +180,23 @@ Call AssertContains(RequestText, """selected"": true", "selected")
Call AssertContains(RequestText, """current_sheet"": true", "current sheet")
Call AssertContains(RequestText, """x"": ""12.5""", "x coordinate")
Call AssertContains(RequestText, """format_version"": 2", "format version")
Call AssertContains(RequestText, """host_view_handle"": 12345", "host view handle")
Call AssertContains(RequestText, """attributes"": []", "attributes field")
Call AssertContains(RequestText, """nets"": []", "nets field")
Call AssertContains(RequestText, """selected_nets"": []", "selected nets field")
Call AssertContains(RequestText, """locked"": false", "locked field")
LastSelection = ""
PageContext = ""
PageKeys = "[]"
Call DxBridgePublishSelection(RunRoot, RunId, SnapshotId, LastSelection, PageContext, PageKeys)
SelectionText = DxToolsReadUtf8(Fso.BuildPath(RunRoot, "selection.json"))
Call AssertContains(SelectionText, """state"":""ready""", "selection ready")
Call AssertContains(SelectionText, """host_view_handle"":12345", "selection host view handle")
Application.ActiveViewHandle = "unavailable"
Call AssertEqual(DxBridgeHostViewHandleJson(), "0", "unavailable host handle")
Application.ActiveViewHandle = 12345
' A new native enumeration can replace all bridge mappings. Keep the
' previous collection alive until the bridge exits: Dx releases the shared
' query context when an older collection is destroyed.
+106
View File
@@ -0,0 +1,106 @@
"""Check minimize/restore against one explicitly identified acceptance DX."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import shlex
import time
import win32con
import win32gui
import win32process
from dx_productivity.ui.host_window_watcher import WindowsHostWindows
from packaged_menu import tools_running, wait_for
from toolbar_ui import ToolbarUI, TOOLBAR_TITLE, PANEL_TITLE
def main():
parser = argparse.ArgumentParser()
parser.add_argument('executable', type=Path)
parser.add_argument('--host-pid', required=True, type=int)
parser.add_argument('--project', required=True, type=Path)
parser.add_argument('--evidence', required=True, type=Path)
options = parser.parse_args()
exe, project, base = options.executable.resolve(), options.project.resolve(), options.evidence.resolve()
assert 'acceptance' in project.parts
base.mkdir(parents=True, exist_ok=True)
def find_tool():
for process in tools_running():
if process.executable == 'None' or Path(process.executable).resolve() != exe or '--request' not in process.command_line:
continue
args = shlex.split(process.command_line, posix=False)
request = Path(args[args.index('--request') + 1].strip('"'))
data = json.loads(request.read_text(encoding='utf-8-sig'))
if Path(data['design_path']).resolve() == project:
return process, request, data
process, request, data = wait_for(find_tool, 30)
host = WindowsHostWindows().resolve(data['host_view_handle'])
assert host is not None and host.pid == options.host_pid
original_minimized = bool(win32gui.IsIconic(host.handle))
def windows():
result = {}
win32gui.EnumWindows(lambda handle, _: result.update({win32gui.GetWindowText(handle): handle})
if win32process.GetWindowThreadProcessId(handle)[1] == process.pid
and win32gui.GetWindowText(handle) in (TOOLBAR_TITLE, PANEL_TITLE) else None, None)
return result
cases = []
try:
if original_minimized:
# A correctly suppressed initial launch need not create native
# window handles until the first show. Absence also means hidden.
assert all(not win32gui.IsWindowVisible(handle) for handle in windows().values())
cases.append({'case': 'startup-while-minimized', 'tool_hidden': True})
win32gui.ShowWindow(host.handle, win32con.SW_RESTORE)
handles = wait_for(lambda: windows() if len(windows()) == 2 else None, 20)
bar, panel = handles[TOOLBAR_TITLE], handles[PANEL_TITLE]
wait_for(lambda: win32gui.IsWindowVisible(bar) and win32gui.IsWindowVisible(panel), 10)
ui = ToolbarUI(process.pid)
assert '桥接已连接' in ui.texts(ui.panel)
ui.capture(ui.toolbar).save(base / 'restored-toolbar.png')
ui.capture(ui.panel).save(base / 'restored-panel.png')
cases.append({'case': 'initial-restore', 'toolbar_visible': True, 'panel_visible': True})
for expanded in (True, False):
if not expanded:
ui.collapse()
for repeat in range(2):
progress = request.with_name('apply-progress.json')
prior = progress.stat().st_mtime
win32gui.ShowWindow(host.handle, win32con.SW_MINIMIZE)
wait_for(lambda: win32gui.IsIconic(host.handle)
and not win32gui.IsWindowVisible(bar) and not win32gui.IsWindowVisible(panel), 10)
wait_for(lambda: progress.stat().st_mtime > prior, 10)
assert win32gui.IsIconic(host.handle)
win32gui.ShowWindow(host.handle, win32con.SW_RESTORE)
wait_for(lambda: win32gui.IsWindowVisible(bar)
and bool(win32gui.IsWindowVisible(panel)) == expanded, 10)
time.sleep(.4)
foreground = win32gui.GetForegroundWindow()
foreground_pid = win32process.GetWindowThreadProcessId(foreground)[1] if foreground else None
assert foreground_pid != process.pid, 'Tool took foreground focus on host restore'
cases.append({'case': 'cycle', 'expanded': expanded, 'repeat': repeat + 1,
'hidden_during_minimize': True, 'previous_panel_state_restored': True,
'heartbeat_continued': True, 'tool_did_not_take_focus': True,
'foreground_pid_after_restore': foreground_pid})
finally:
if original_minimized:
win32gui.ShowWindow(host.handle, win32con.SW_MINIMIZE)
wait_for(lambda: all(not win32gui.IsWindowVisible(handle) for handle in windows().values()), 10)
result = {'host_pid': host.pid, 'host_hwnd': host.handle, 'tool_pid': process.pid,
'host_view_handle': data['host_view_handle'], 'request': str(request), 'executable': str(exe),
'cases': cases, 'final_dx_minimized': bool(win32gui.IsIconic(host.handle)),
'final_tool_hidden': all(not win32gui.IsWindowVisible(handle) for handle in windows().values()),
'design_values_written': False}
(base / 'host-native.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(result, ensure_ascii=False, indent=2), flush=True)
if __name__ == '__main__':
main()