diff --git a/TODO.md b/TODO.md index 58dc650..11c5799 100644 --- a/TODO.md +++ b/TODO.md @@ -284,7 +284,180 @@ - [x] **提醒**:截图与 OCR 可能捕获到屏幕上的敏感内容(实测就截到过一行带 token 的地址)。代码只记录长度与路径、 不记录识别文本,但**截图文件会落在磁盘上**,请自行控制保存目录与保留期限 -#### 下一段(段三,待做) +#### 第十一轮:可见性、拾取展开、搜索面板、页面特征、焦点列、悬浮条配置 + +- [x] **高亮框只在目标真正可见时显示**(定位框 + 拾取预览共用):新增 `WindowVisibility`, + 检查 窗口存在/可见/未最小化/矩形在可见屏幕内,并用 5 个取样点判断**是否被其他窗口遮挡** + (本工具自己的覆盖层不计入遮挡)。最小化或被遮挡时只说明原因,不画框 +- [x] **拾取完成后展开控件树**:以被拾取元素为根读树后展开根与其一层子节点并选中 +- [x] 控件树搜索的「更多」区域**按内容自适应高度**(之前固定 58px 把第二行条件截断) +- [x] 选中控件树节点时,在「控件属性」标题栏显示该控件的**页面特征**(进程/窗口类/标题关键词), + 并新增「复制页面特征」按钮,便于填进悬浮条条件 +- [x] 监控列表「焦点」列 = **该控件当前是否获得焦点**:默认「未读取」,之后每 3 秒轮询**一行** + (后台线程、单飞、可在工具栏关闭自动刷新),Hover 说明"是否获得焦点" +- [x] **悬浮按钮改为可配置的「悬浮条」**(设置 → 悬浮按钮): + - 每条:名称、启用、透明度、**相对锚定窗口的 X/Y**、显示条件(进程 / 窗口类 / 标题关键词 / + **导入监控项 path** = 该控件出现才显示)、要求窗口可见未被遮挡 + - 按钮表格:**按钮名称、点击执行操作(读取列表/定位控件/刷新状态/检查窗口/拾取/截图/OCR/执行命令)、 + 快捷键、点击执行命令、启用** + - 运行时(`FloatingBarManager`):按条件显示、**跟随锚点窗口按相对坐标定位**、窗口消失或被遮挡即隐藏; + 锚点窗口缓存避免每秒重新枚举窗口;导入的 path 每 5 秒在后台复查一次 + - 快捷键用 `RegisterHotKey` 注册(`WM_HOTKEY` 在主窗体 WndProc 处理),冲突会记日志; + 保存时会校验快捷键格式并提示 + - 拖动词条会把**相对位置写回设置**(关闭时保存) +- [x] 新增共享 `WindowMatcher`(分级窗口匹配),定位与悬浮条条件用同一套规则 +- [x] 回归:三来源树、拾取下钻、列表读取三例、设置窗口构造(127 个控件)、布局自检"异常区域 0 个" + +#### 第十二轮:现场 8 条反馈 + +- [x] ① **悬浮条在窗口移动过程中跟随**:拆成两个节拍 —— 120ms 的**跟随节拍**只读 `GetWindowRect` + (内核直接回答,不会卡在目标进程上)并用「锚点窗口矩形 + 相对偏移」重算位置;1 秒的**条件节拍** + 仍负责锚点重发现、遮挡判断与导入 path 检查。拖动悬浮条本身时跟随让位(新增 `IsDragging`), + 松手把相对位置写回设置(`ApplyDraggedOffset` 此前从未被调用,拖动后会被拉回原位) +- [x] ② **选中控件监控列表的一行即定位**:选中行(或同一行的另一格)会在**后台线程**定位该条目, + 定位成功后画高亮框、在控件树里展开祖先并选中该节点。定位由同步改异步(跨进程窗口枚举 + 解析 + 不再卡界面),并用请求序号丢弃被新选中行取代的旧结果;若该条目属于**另一个窗口**, + 会自动读取那个窗口的控件树,读完再选中对应节点 +- [x] ③ **拾取后自动在控件监控列表新增一条(未启用)**,并展开控件树、选中被拾取的节点; + 同一次拾取期间的深层重探不会重复添加 +- [x] ④ **拾取框/定位框跟随、隐藏与遮挡**:新增 `HighlightFollower`,每 120ms 用「控件相对锚点 + 窗口的偏移 + 锚点窗口矩形」重算位置(纯 Win32,不可能被目标进程卡住);UIA/MSAA 的重新解析 + 放到后台线程、约 3 秒一次,只用于修正偏移(滚动/布局变化)。最小化 / 隐藏 / 被遮挡 / 移出屏幕 + 时立即隐藏并说明原因,目标重新可见后自动回来,只有窗口关闭才彻底停止。拾取预览框与定位框都改用 + 它,拾取结束时不再留下一个停在原地的旧框 +- [x] ⑤ 「复制页面特征」移入工具栏的**「杂项 ▾」菜单**(右键同一按钮也打开),工具栏不再被低频按钮占用 +- [x] ⑥ **退出时结束所有命令,以及命令拉起的应用**:新增 `ProcessJob` + (`JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`)——每个命令进程启动后加入该 Job,命令自己拉起的子进程 + 继承 Job;Job 句柄关闭时(正常退出、崩溃被强杀都会关闭)由系统结束整棵树。退出路径另外先按 PID + 走 `taskkill /T /F`(上限 1.5 秒,避免卡住退出),命令超时也从「只杀 cmd.exe」改为结束整棵树 +- [x] ⑦ **控件树搜索栏按内容自适应高度**:搜索行与「更多」区域都允许换行,高度按**当前宽度** + 重新测量(此前只在构造时算一次,那时宽度还未知,所以第二行条件被截断);窄栏下按钮会换行而不是 + 被挤掉。▲/▼ 改为固定 28px(AutoSize 会把它们撑到 75px 的最小按钮宽度,默认宽度下就换行) +- [x] ⑧ **设置窗口放大并按屏幕自适应**(本机 1705x1018 工作区 → 1229x855,原来固定 860x640), + 最小 980x720;命令页列表行占 70%,说明行按内容高度(原来固定 58px 会把整行截断) +- [x] ⑧b **截图里的显示 bug(悬浮按钮页)**:按钮表格被上面的字段压住。原因:该面板里 `Dock=Fill` + 的表格比 `Dock=Top/Bottom` 的字段区更晚加入,于是表格先占满整块区域、字段再画在它上面 —— + 截图里那块"空灰色列表"就是被盖住的表格(表头与前 3 行都在字段后面)。改为**先加表格**、 + 再加底部按钮行与字段区;字段区改为**按内容自适应高度**(固定 190px 会切掉下半部分字段), + 标签与输入框成对成组,换行时不会拆开 +- [x] 本轮验证方式(独立宿主进程,不在仓库内):`LayoutHarness`(布局探针 + 控件监控列表新增 + 跟随测试)、 + `TargetHost`(跨进程锚点窗口)。实测结果: + - ① 锚点移动后 **350ms 内**悬浮条已在新位置(340+14,230+14 → 540+14,320+14);锚点最小化即隐藏,还原后 1 秒内回来 + - ③ 新增后行数 +1、`Enabled=false`、当前选中行不变、启用复选框单元格为 false + - ④ 窗口移动 (260,150) 后框位置完全一致;最小化后隐藏并给出原因;还原后回来 + - ⑥ 命令 `start "" TargetHost.exe 45` 拉起独立应用后 `CommandRunner.Dispose()`(等价于退出), + 该应用进程数 1 → 0 + - ⑦ 展开时 1184 / 684 / 404 三种宽度下"内容底部 = 面板高度"(不再裁切);收起时 717 宽度下为一行 38px + - ⑧b 表格 bounds 从 `{0,0,841,747}`(占满并被遮)变成 `{0,100,841,613}`(3 行 × 5 列全部可见) + - 启动回归:主界面 2048x1298、布局自检"异常区域 0 个"、Debug 与 Release 均已编译 + +#### 第十二轮仍未验证(需要真实目标) + +- [ ] ② 监控列表选中 → 定位 → 展开树:本机没有匹配的目标窗口,只走查了代码路径; + 需要在真实 PACS 上点一条监控项复测(尤其"该条目属于另一个窗口时自动读取那个窗口的树") +- [ ] ④ 遮挡判断在真实场景下的表现(多屏、其它置顶工具、RDP) +- [ ] ⑥ 目标为提权进程、或命令用 `start` 二次派生时的 Job 继承;以及本工具被任务管理器强杀时命令是否同样被结束 +- [ ] ⑦ 高 DPI / 不同系统字体下搜索栏的换行高度是否仍然合适 +- [ ] ⑧ 设置窗口在小屏(1024x768)与多屏下的尺寸与分栏比例 + +### 第十三轮:现场 6 条反馈 + +- [x] ① **悬浮按钮设置的「点击执行操作」显示中文**:该列原来是枚举值列表,单元格显示 `PickControl` + 这类英文名。改为绑定 `FloatingButtonDefinition.DescribeChoices()`(枚举值 + 中文名, + `DisplayMember`/`ValueMember`),界面显示「拾取控件 / 读取选中控件列表 / 定位到控件 / 刷新监控项状态 / + 检查选中窗口 / 窗口截图 / OCR 读取 / 执行命令 /(不执行任何操作)」,写回模型的仍是枚举 +- [x] ② **控件监控列表的只读列也要能复制**:只读单元格双击即复制其文本(可编辑列保持原有编辑行为), + 右键菜单提供「复制单元格文本 / 复制整行(表头 + 内容,制表符分隔)/ 定位到该控件并画框」, + Ctrl+C 按选中区域复制(`ClipboardCopyMode = EnableWithoutHeaderText`), + 鼠标悬停显示完整内容(控件Path 列经常被列宽截断) +- [x] ③ **点击监控列表任何位置都定位并画框**:新增 CellClick 处理 —— 点启用复选框、点只读的控件Path、 + 点别名都会定位该行。此前只在"选中行/格发生变化"时定位,点同一处没反应,操作者要反复点几次才生效。 + 同一格的双事件(SelectionChanged + CellClick)用 300ms 去重,隔一会儿再点同一格仍会重新定位 +- [x] ③b **框的"再点一次隐藏"只对显式操作生效**(定位按钮 / 行头 / 悬浮按钮):点击式定位永远把框显示出来, + 不再出现"点一下反而把框关掉、必须再点一次"的情况 +- [x] ④ **拾取后的 UIA 路径可回读**:拾取时立刻把刚保存的路径**从顶层窗口走一遍**(正是回读用的 + 同一套匹配逻辑),结果写进定义: + - 从顶层窗口命中 → 正常完整路径 + - 只有内层窗口元素能命中(UWP `ApplicationFrameWindow` / 浏览器套壳的内容在另一个窗口里)→ + 置 `UiaPathFromInnerWindow`,回读时按内层窗口定位**不再算容错命中**(以前每次都报 + "第 1 段未匹配…改从内层窗口元素开始"并提示"建议重新添加") + - 两种都走不通 → 添加时明确说明"路径回读校验未通过",不再让操作者以为保存成功 + - 共用 `ControlLocatorService` 的 `WalkPath`/`TryMatchChild`/`CollectNestedWindowStarts`/`SameElement` + (改为 internal),避免生成与回读两套匹配逻辑再次漂移 +- [x] ⑤ **拾取结束后隐藏红框**:拾取确认后不再保留高亮框(上一轮留下的"跟随框"已移除), + 窗口列表/控件树才是拾取后该看的东西 +- [x] ⑥ **拾取后读的是与窗口列表相同的控件树,并在其中展开并选中被拾取节点**: + 此前以被拾取元素为根读树(UWP 列表项只有 2 个节点,而窗口树有 118 个,两边"看起来不一样")。 + 现在一律从**顶层窗口**读(与窗口列表同一条路径),读完按身份在被拾取的祖先链上展开并选中该节点; + 万一窗口树里确实没有它(内层窗口/跨进程视图差异),再自动改为以该控件为根读一次; + MSAA/Win32 拾取的控件会把控件树来源切到同一来源,保证节点在同一棵树里 +- [x] 本轮验证(独立宿主进程,与上一轮同一套夹具): + - ① 设置里三行按钮的操作列显示「读取选中控件列表 / 定位到控件 / 刷新监控项状态」,值仍是枚举 + - ③ 点击只读单元格后状态栏出现「正在定位「control」(点击定位)……」 + - ⑤⑥ 需要在真实目标上点一次拾取复测(本机夹具只覆盖到上面这些) + - 回归:搜索栏高度、设置页布局、悬浮条跟随、退出结束命令树、布局自检"异常区域 0 个"、Debug/Release 均已编译 + +### 第十四轮:现场 14 条反馈 + +- [x] ① **可运行的测试夹具** `tests/uia-fixture`(普通 WinForms 窗口:按钮/文本框/复选框/单选/下拉/ + 两列 ListView/TreeView/DataGridView/三层嵌套容器 + 第二个窗口),已加入 `pacs_win_uia.sln`, + 用 `tests\run-fixture.cmd` 一键构建并启动;`tests/README.md` 里是建议的验收清单 +- [x] ② **低频能力收进「杂项」**:工具栏只留 刷新窗口 / 拾取控件 / 检查选中窗口 / 控件树来源 / + 尝试激活目标无障碍 / 杂项 / 设置;读取选中控件列表、窗口截图、OCR 读取、导出控件树、 + 导出列表 JSON/CSV 与复制页面特征、按 path 定位、绘制所有控件框都在杂项菜单里 +- [x] ③ **控件树筛选界面重做**:条件是 5 列 × 3 行(标题 / 输入框 / 按钮)的 `TableLayoutPanel`, + 标题与输入框同列不再拆行,标红只用于"匹配 0 项" +- [x] ④ **Shift+滚轮横向滚动 + Ctrl+F**:新增 `ShiftWheelScroll`(`IMessageFilter`),按光标下的控件 + 找可横向滚动者(ListView / TreeView 走 WM_HSCROLL,属性区宿主走滚动属性;DataGridView 本来就会); + Ctrl+F 在控件树页跳到控件树搜索框、其它地方跳到窗口列表搜索框 +- [x] ⑤ **拾取与窗口列表显示同一棵树,路径同源** —— 这是"两棵树不一样 / 复制的 path 解析不到"的根因: + `result.Window` 是光标下**最深的 Win32 窗口**(UWP 的 `Windows.UI.Core.CoreWindow`、浏览器渲染窗口), + 以它为根读树,和窗口列表按顶层窗口读出来的树自然不同,路径也差了开头一段。 + 现在拾取后一律用 `GetAncestor(GA_ROOT)` 的**顶层窗口**为根读树,读完整棵后在树里展开并选中被拾取节点 +- [x] ⑥ 同上(拾取与窗口列表的树一致);MSAA/Win32 拾取时控件树来源会自动切到同一来源, + 保证节点在同一棵树里 +- [x] ⑦ **设置窗口居中/记住位置**:首次打开按屏幕自适应并居中,之后恢复上次的位置与大小 + (`Ui.SettingsWindowX/Y/Width/Height`,位置已不在任何屏幕上时回到居中) +- [x] ⑧ **悬浮条:背景透明度与按钮透明度分开**:WinForms 子控件没有自己的 alpha,所以悬浮条改为 + **自绘的层窗口**(`UpdateLayeredWindow` + 32 位 ARGB 位图):背景按「背景透明度」画、按钮按 + 「按钮透明度」画,圆角、悬停/按下状态、提示文字都在自绘里;逐像素透明不可用时退化为整条不透明度 + (仍在画,只是只有一个透明度)。设置里新增「整体透明度 / 背景透明度(0=同上) / 按钮透明度(0=同上)」 +- [x] ⑨ **path 匹配收紧**:控件类型现在是身份的一部分;记了 `AutomationId` 的段必须精确命中 + (不再退化成按名字/序号乱配),同名子元素用记录的序号消歧;每次命中都会把 + 「命中元素:类型 AutomationId 名称 类名 矩形」写进定位步骤和日志, + 定位到别的同名控件时一眼能看出来 +- [x] ⑩ **新增「按 path 定位…」**(杂项):把工具打印的路径粘回来即可定位 —— 先按顶层窗口走, + 再按内层窗口元素起点走(与回读同一套容错),命中后画框并在控件树里选中; + 未命中时明确报出**第几段**没匹配 +- [x] ⑪ 路径往返已修(见 ⑤⑨⑩):工具打印的路径与回读用同一套生成/匹配代码 + (`ControlLocatorBuilder.DescribePathFromTree` 与 `ControlLocatorService.WalkPath`) +- [x] ⑫ **「绘制所有控件框」**(杂项,可勾选):把当前控件树里每个带矩形的节点都画一个细红框 + (新增 `NodeMapOverlayForm`,矩形按"相对锚点窗口的偏移"保存,每 150ms 只读一次 `GetWindowRect`, + 所以拖窗口时整片框跟着走,窗口最小化/被遮挡/关掉即隐藏) +- [x] ⑬ **拾取不再触发目标控件**:新增低级鼠标钩子(`WH_MOUSE_LL`),拾取期间左键由本工具接管并 + **不转发**给任何窗口,钩子里的坐标直接作为拾取确认点(钩子回调只投递消息,不做耗时工作); + 钩子装不上时退化为原来的行为并在日志里说明 +- [x] ⑭ **控件属性显示 path / 页面特征 / 焦点状态**:`UiaElementInfo` 增加三个只读展示字段 + (不序列化),选中控件树节点时按内存里的树现算路径,可直接复制去「按 path 定位」 +- [x] 本轮验证(独立宿主进程夹具,对着 `tests/uia-fixture` 的真窗口跑): + - 路径往返:工具打印 `[Uia] Tab[FixtureTabs] > TabItem:控件 > Pane[...] > Button[FixtureButton]` + → 解析 → 从窗口走回去 → **命中同一个控件**(AutomationId/名称/矩形一致) + - 故意写错:`Tab[NoSuchTabs]` → "第 1 段(Tab[NoSuchTabs])未匹配:没有 AutomationId…"(不再乱命中) + - 控件属性:path / 页面特征(进程=UiaFixture;标题关键词=UIA 测试夹具;窗口类=…)/ 焦点 均有值 + - 绘制所有控件框:39 个节点全部出框,可再次点击取消 + - 悬浮条:逐像素透明生效 —— 背景像素 246(35% 混合,非纯白)、按钮像素为不透明文字像素 + - 拾取不点目标:注入一次真实左键到「测试按钮」,夹具状态仍是"还没有操作。",拾取同时确认到了该按钮 + - 回归:搜索栏高度/设置页布局/悬浮条跟随/退出结束命令树/布局自检"异常区域 0 个"、Debug+Release 均已编译 + +#### 第十四轮未验证 + +- [ ] ④ Ctrl+F 与 Shift+滚轮只做了代码走查,需要手工在 控件树/窗口列表/属性区 试一次 +- [ ] ⑧ 悬浮条自绘在高 DPI / 多屏 / RDP 下的观感;逐像素透明不可用的退化路径(只在装不上层窗口时才走) +- [ ] ⑬ 低级鼠标钩子在被其它钩子(安全软件/输入法)拦截时的表现;以及"拾取期间左键完全被吞掉" + 是否会影响操作者(取消/Esc 立即恢复) +- [ ] ⑤⑥ 需要在真实 PACS/OCS(CEF 套壳、UWP)上确认拾取与窗口列表的树确实一致、路径一次命中 + +#### 下一段(段三剩余,待做) - [ ] 条件评估(窗口条件 + 控件条件)`ConditionEvaluator`,同时供监听规则与悬浮条使用 - [ ] `MonitorRule` + `monitor-rules.json` + 设置里的「监听」页:控件出现/消失/值变化/选中变化/焦点变化 + 单击/双击/右键 → 动作(执行命令 / 读取值 / OCR / 截图 / 显示悬浮条) diff --git a/docs/XPath定位.md b/docs/XPath定位.md new file mode 100644 index 0000000..cdf6d57 --- /dev/null +++ b/docs/XPath定位.md @@ -0,0 +1,459 @@ +# 控件 Path 教程:从第一次定位到稳定规则 + +> 本工具的 Path 是 **XPath 1.0 节点路径**。它只负责“在已经选定的窗口控件树里找到哪个节点”,不会点击、输入或修改目标程序。 +> +> 最重要的原则:**宁可报告“无法唯一确定”,也不要猜一个看起来相似的控件。** + +--- + +## 一、先用 3 分钟完成第一次定位 + +### 1. 取得 Path + +1. 在主界面的“窗口列表”选中目标窗口。 +2. 等待“控件树”读取完成。 +3. 在控件树中选中目标控件。 +4. 在右侧“控件属性”中找到 `ControlPath`。 +5. 复制这个 XPath,或点击“添加当前控件”加入“控件监控列表”。 + +拾取控件也会从**同一个顶层窗口控件树**生成 Path,所以“手动选树节点”和“鼠标拾取”产生的 Path 应当使用同一套规则。 + +### 2. 测试 Path + +在控件监控列表中可以: + +- 选中 `控件Path` 单元格后按 `F2` 直接编辑; +- 双击 Path 打开多行 XPath 编辑器; +- 点击“测试定位”检查当前窗口是否**唯一命中**; +- 点击“定位到”在树中展开并高亮目标; +- 最后点击监控列表的“保存”才会写入 JSON。 + +测试结果有三种: + +| 结果 | 含义 | +|---|---| +| 唯一命中 | 可以保存并用于监控 | +| 0 个命中 | 当前页面没有这个节点,或条件写错 | +| 多个命中 | 条件太宽,必须继续增加约束 | + +### 3. 最小可用示例 + +```xpath +/Window[1] +``` + +表示当前树的顶层窗口。 + +```xpath +/Window[1]//Button[@AutomationId='saveButton'] +``` + +表示窗口内任意层级、`AutomationId` 为 `saveButton` 的按钮。 + +```xpath +/Window[1]//*[@AutomationId='PatientPanel']//Edit[@ClassName='PatientEditor'] +``` + +表示先找到稳定的患者面板,再在面板内部找编辑框。 + +--- + +## 二、你需要先理解的 4 个概念 + +### 1. 窗口条件和控件 Path 是两层定位 + +程序先通过窗口条件找到**哪个顶层窗口**,再用 XPath 找窗口里面的**哪个控件**。 + +窗口条件通常包括: + +- 进程名; +- 窗口类名; +- 标题关键词。 + +已经填写的窗口条件会同时满足,并且必须唯一匹配。窗口标题只用于找窗口,不等同于控件 Path 中的 `@Name`。 + +因此下面两件事是不同的: + +```text +窗口条件:进程=MyPacs;窗口类=PacsMainWindow +控件 Path:/Window[1]//*[@AutomationId='PatientPanel']//Edit[@ClassName='PatientEditor'] +``` + +窗口条件解决“去哪一棵树”;XPath 解决“树里的哪一个节点”。 + +### 2. 控件类型是节点名称 + +常见节点名称包括: + +```text +Window Pane Group Button +Edit Text List ListItem +Tree Tab TabItem CheckBox +ComboBox ScrollBar Custom +``` + +XPath 中的 `Edit`、`Button` 等来自 UIA 控件类型。不同来源也会映射为树节点,例如 MSAA/Win32 节点可能显示为 `Accessible` 或 `Window`。 + +### 3. 属性是节点的特征 + +常用属性: + +| 属性 | 适合用途 | 稳定性提醒 | +|---|---|---| +| `@AutomationId` | 程序给控件的逻辑 ID | 通常最适合长期定位,但目标程序也可能生成动态 ID | +| `@ClassName` | 控件/窗口类名 | 比显示文字稳定,但框架升级可能改变 | +| `@ControlType` | 精确区分控件类型 | 一般与节点名称对应 | +| `@Name` | 按钮文字、标签文字、列表项文字 | 最容易随患者、文件、语言、状态变化 | +| `@Source` | 区分 UIA、MSAA、Win32 | 多来源树不能混为一棵树 | + +例如: + +```xpath +//Button[@AutomationId='saveButton'] +//Edit[@ClassName='PatientEditor'] +//*[@ControlType='ControlType.ListItem'] +//*[@Source='Win32'] +``` + +### 4. 唯一命中比“写得像”更重要 + +这条路径可能看起来合理: + +```xpath +//Button +``` + +但一个页面通常有很多按钮,所以它不能用于监控定位。 + +可以搜索时使用宽路径,但保存或定位必须收窄到唯一节点: + +```xpath +//Button[@ClassName='ActionButton' and contains(@Name,'保存')] +``` + +如果仍然有两个结果,再增加稳定祖先、AutomationId 或同级序号。 + +--- + +## 三、XPath 语法速查 + +### 1. `/`:直接子节点 + +```xpath +/Window[1]/Pane/Button +``` + +只查直接下一层。中间缺一层就匹配不到。 + +### 2. `//`:任意后代节点 + +```xpath +/Window[1]//Button +``` + +查找窗口下面任意深度的按钮。页面有动态布局时,`//` 通常比写死全部中间 Pane 更耐用,但也更容易产生多个结果,需要加条件。 + +### 3. `*`:任意控件类型 + +```xpath +/Window[1]//*[@AutomationId='PatientPanel'] +``` + +适合先用稳定属性找锚点,不确定控件类型时也很有用。 + +### 4. 属性条件 `[@属性='值']` + +```xpath +//Edit[@AutomationId='PatientId'] +//Button[@ClassName='ActionButton'] +``` + +### 5. 多条件 `and` / `or` + +```xpath +//Edit[@ClassName='PatientEditor' and @AutomationId='PatientId'] +//Button[@AutomationId='save' or @AutomationId='submit'] +``` + +长期监控优先使用 `and`,因为它能减少误匹配。 + +### 6. `contains()`:部分匹配 + +```xpath +//Button[contains(@Name,'保存')] +//Text[contains(@Name,'患者编号')] +``` + +适合名称有固定部分、但后面会变化的情况,例如“保存(3)”。 + +注意:`contains()` 可能匹配多个节点,必须测试唯一性。 + +### 7. `starts-with()`:固定前缀 + +```xpath +//Text[starts-with(@Name,'患者编号')] +``` + +如果控件名称是“患者编号:张三”,而“患者编号”稳定,可以使用它。 + +### 8. 序号 `[n]` + +序号从 **1** 开始: + +```xpath +//Button[1] +//Button[2] +(//Button[@AutomationId='same-id'])[2] +``` + +序号表示当前 XPath 结果中的位置,不是永久 ID。页面插入一个同类型控件后,序号可能改变,所以只能作为最后的消歧手段。 + +### 9. 组合条件 + +```xpath +/Window[1]//*[@AutomationId='PatientPanel']//Group[ + .//Text[@AutomationId='PatientIdLabel'] +]//Edit[@ClassName='PatientEditor'] +``` + +这是更稳定的思路:先找业务面板,再找面板内由稳定标签限定的编辑框。 + +### 10. 选择节点集,不要返回值 + +Path 必须返回控件节点集合。下面这些不是可定位 Path: + +```xpath +count(//Button) +string(//Text/@Name) +/Window/@Name +text() +``` + +它们返回数字、字符串、属性或文本,而不是控件节点。 + +--- + +## 四、Name 会变化时,怎样尽量精准定位 + +这是最常见也最容易误定位的场景。 + +### 推荐优先级 + +#### 第一优先:AutomationId + +```xpath +/Window[1]//*[@AutomationId='PatientPanel']//Edit[@AutomationId='PatientId'] +``` + +如果目标程序提供稳定 ID,不要额外把动态 Name 写进条件。 + +#### 第二优先:稳定祖先 + ClassName + 类型 + +```xpath +/Window[1]//*[@AutomationId='PatientPanel']//Edit[@ClassName='PatientEditor'] +``` + +中间布局层可以增加、减少或更换名称,通常不会影响这条路径。 + +#### 第三优先:稳定辅助节点 + +```xpath +/Window[1]//Group[ + .//Text[@AutomationId='PatientIdLabel'] +]//Edit[@ClassName='PatientEditor'] +``` + +辅助节点必须和目标有明确结构关系。不要只在整个窗口中搜索一个相似文字,然后猜最近的控件。 + +#### 第四优先:名称的稳定部分 + +```xpath +//Text[starts-with(@Name,'患者编号')] +//Button[contains(@Name,'保存') and @ClassName='ActionButton'] +``` + +只有名称的一部分稳定时才这样写,并且一定点击“测试定位”确认唯一。 + +#### 第五优先:结构序号 + +```xpath +//*[@AutomationId='PatientPanel']//Edit[2] +``` + +这是最后手段。结构变化、权限变化、页面状态变化都可能让 `[2]` 指向另一个控件。 + +### 自动生成路径的策略 + +当前工具自动生成 Path 时: + +1. 根窗口固定为 `/Window[1]`,不依赖窗口标题; +2. 子节点优先使用 AutomationId; +3. 没有 AutomationId 时使用 ClassName 和控件类型; +4. 没有稳定属性时使用类型和结构序号; +5. 不自动把 Name 写成长期必经条件。 + +这能避免患者姓名、文件名、数量、语言变化直接让路径失效。 + +### 无法保证的情况 + +如果目标程序同时满足以下条件: + +- 没有稳定 AutomationId; +- ClassName 也会变化; +- 中间结构会动态重排; +- 没有稳定辅助标签或业务锚点; +- 控件本身是自绘且不暴露 UIA; + +那么 UIA XPath 没有足够信息证明“这就是同一个业务控件”。此时不应继续堆叠猜测条件,应考虑: + +- 让目标程序提供稳定无障碍 ID; +- 使用官方插件/API; +- 切换 MSAA/Win32 来源; +- 对明确授权的场景使用截图/OCR,并标记为降级结果; +- 页面变化后要求人工重新确认。 + +RuntimeId 和 HWND 适合当前运行中的重新绑定,不适合直接作为跨重启、跨版本的长期配置身份。 + +--- + +## 五、Path 的编辑、测试和保存 + +### 直接编辑 + +在“控件监控列表”中: + +1. 选中 `控件Path` 单元格; +2. 按 `F2` 或直接输入; +3. 输入期间不会自动定位,避免半截 XPath 造成界面跳动; +4. 按 Enter/离开单元格提交; +5. 点击“测试定位”或“定位到”; +6. 点击列表的“保存”写入 JSON。 + +### 多行编辑器 + +双击 Path 会打开“编辑控件 XPath”窗口: + +- 上方显示 XPath 快速说明; +- 中间可以编辑长路径; +- “测试定位”在后台执行,不阻塞窗口; +- 0 个或多个结果会显示错误; +- 非法语法不能保存; +- “取消”不会修改原 Path; +- 右键菜单仍可复制 Path。 + +### 按 path 定位 + +打开“杂项 → 按 path 定位”: + +1. 先选中目标窗口并读取控件树; +2. 粘贴完整 XPath; +3. 点击“定位”; +4. 唯一命中时,工具会在树中选择节点并尝试画框。 + +当前窗口树必须是你复制 Path 时对应的窗口树。Path 不能跨窗口直接使用。 + +--- + +## 六、旧格式为什么不能继续使用 + +以下格式已经停用: + +```text +[Uia] Window:设置 > Custom[PermanentNavigationView] > Button:个性化 +Button[saveButton] +i3/o1 +[Win32] ClassName 0x1234 +``` + +原因是这些格式存在多个问题: + +- 显示文本和真实属性混在一起; +- `:`、`>`、`[` 等字符无法可靠转义; +- 同名节点的序号语义容易不一致; +- 不同来源的路径不能放在同一套解析器里猜测; +- 失败时容易静默回退到另一个控件。 + +旧配置仍可读取并显示,方便手工修正;但旧 Path 不会执行,保存前必须改成 XPath。保存失败时原文件保持不变,不会自动清空或改写旧配置。 + +--- + +## 七、悬浮条中使用 XPath + +在“设置 → 悬浮按钮”中: + +1. 选择或新建悬浮条; +2. 配置进程名、窗口类或标题关键词; +3. 点击“导入监控项 path”; +4. 选择要导入的监控项; +5. 点击“检测显示条件”; +6. 确认悬浮条启用,并至少有一个启用按钮; +7. 点击设置窗口“保存”。 + +导入内容是定位条件的副本。之后修改监控列表中的 XPath,不会自动改变已经导入的悬浮条;请重新导入。 + +下拉框显示的是“窗口标题 / 进程名 / PID / 窗口类”等人类可读信息,但保存的是实际条件值。悬浮条名称只用于显示,不是窗口定位条件。 + +### 不显示时的排查顺序 + +点击“检测显示条件”,按提示处理: + +1. 悬浮条是否启用; +2. 是否有至少一个启用按钮; +3. 是否填写了窗口条件; +4. 已填写的进程、类名、标题是否同时匹配; +5. 是否匹配到多个窗口; +6. 导入 XPath 是否仍然唯一命中; +7. 窗口是否最小化、隐藏或被遮挡; +8. 设置窗口自身是否挡住了目标。 + +--- + +## 八、常见错误速查 + +### “旧路径格式已停用” + +请回到控件树复制新的 `ControlPath`,或者手工改成 XPath。不要给旧格式加一个 `/` 试图伪装成 XPath。 + +### “路径匹配到 0 个控件” + +检查: + +1. 是否选中了正确的顶层窗口; +2. 控件树是否读取完整; +3. 控件类型是否正确; +4. AutomationId/ClassName 是否发生变化; +5. 是否把临时患者姓名或文件名写进了 `@Name`; +6. 页面是否已切换或控件已重建; +7. 是否选错了来源(UIA、MSAA、Win32)。 + +### “匹配到多个控件” + +先增加稳定祖先或属性: + +```xpath +//*[@AutomationId='PatientPanel']//Edit[@ClassName='PatientEditor'] +``` + +仍然多个时,再使用序号: + +```xpath +//*[@AutomationId='PatientPanel']//Edit[@ClassName='PatientEditor'][2] +``` + +### “悬浮条保存后不显示” + +点击“检测显示条件”。通常是按钮没有启用、窗口条件为空/不唯一、导入的 XPath 已失效,或目标窗口被遮挡。 + +### “Path 看起来对,但仍找不到” + +XPath 只在当前读取到的树中计算。CEF、自绘、GPU、权限隔离或未开启无障碍的界面,可能根本没有暴露目标节点。Path 无法凭空创建目标节点。 + +--- + +## 九、设计和安全边界 + +- XPath 是只读定位规则,不会自动点击、输入或修改目标控件。 +- 长期配置不保存 RuntimeId、当前 Value、焦点状态等动态快照字段。 +- 姓名、身份证号、检查结果等敏感内容不应写入调试日志或 Path。 +- 截图/OCR 可能包含患者信息,应使用受控目录、保留期限和授权的本地服务。 +- 能力不足时必须报告“无法确认”,不能把 OCR、相似名称或第一个匹配项伪装成精确控件。 diff --git a/pacs_win_uia.sln b/pacs_win_uia.sln index 3788963..44533a0 100644 --- a/pacs_win_uia.sln +++ b/pacs_win_uia.sln @@ -5,6 +5,8 @@ VisualStudioVersion = 17.0.31903.59 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "pacs_win_uia", "src\pacs_win_uia\pacs_win_uia.csproj", "{C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UiaFixture", "tests\uia-fixture\UiaFixture.csproj", "{3B8C1F52-9E4A-4D27-8C51-2A6F0D4E7A11}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +17,10 @@ Global {C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202}.Debug|Any CPU.Build.0 = Debug|Any CPU {C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202}.Release|Any CPU.ActiveCfg = Release|Any CPU {C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202}.Release|Any CPU.Build.0 = Release|Any CPU + {3B8C1F52-9E4A-4D27-8C51-2A6F0D4E7A11}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3B8C1F52-9E4A-4D27-8C51-2A6F0D4E7A11}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3B8C1F52-9E4A-4D27-8C51-2A6F0D4E7A11}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3B8C1F52-9E4A-4D27-8C51-2A6F0D4E7A11}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/pacs_win_uia/Interop/NativeMethods.cs b/src/pacs_win_uia/Interop/NativeMethods.cs index 299d5d4..70216ec 100644 --- a/src/pacs_win_uia/Interop/NativeMethods.cs +++ b/src/pacs_win_uia/Interop/NativeMethods.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Drawing; using System.Runtime.InteropServices; using System.Text; @@ -154,6 +154,15 @@ namespace pacs_win_uia.Interop [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetWindowRect(IntPtr hWnd, out RECT rect); + [DllImport("gdi32.dll", SetLastError = true)] + internal static extern IntPtr CreateRectRgn(int left, int top, int right, int bottom); + + [DllImport("user32.dll", SetLastError = true)] + internal static extern int GetWindowRgn(IntPtr hWnd, IntPtr region); + + [DllImport("dwmapi.dll", EntryPoint = "DwmGetWindowAttribute")] + internal static extern int DwmGetWindowRectangle(IntPtr hwnd, int attribute, out RECT value, int size); + [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetClientRect(IntPtr hWnd, out RECT rect); @@ -177,6 +186,113 @@ namespace pacs_win_uia.Interop [DllImport("user32.dll", SetLastError = true)] internal static extern short GetAsyncKeyState(int virtualKey); + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern IntPtr SendMessage( + IntPtr hWnd, + int msg, + IntPtr wParam, + IntPtr lParam); + + // ---------------------------------------------------------------- low-level mouse hook + // Used by the picker to keep the confirmation click from reaching the target application. + + internal const int WH_MOUSE_LL = 14; + internal const int WM_LBUTTONDOWN = 0x0201; + internal const int WM_LBUTTONUP = 0x0202; + internal const int WM_RBUTTONDOWN = 0x0204; + internal const int WM_RBUTTONUP = 0x0205; + internal const int WM_MOUSEMOVE = 0x0200; + internal const int WM_MBUTTONDOWN = 0x0207; + internal const int WM_MBUTTONUP = 0x0208; + internal const int WM_MOUSEWHEEL = 0x020A; + internal const int WM_XBUTTONDOWN = 0x020B; + internal const int WM_XBUTTONUP = 0x020C; + internal const int WM_MOUSEHWHEEL = 0x020E; + internal const int WH_KEYBOARD_LL = 13; + internal const int WM_KEYDOWN = 0x0100; + internal const int WM_KEYUP = 0x0101; + internal const int WM_SYSKEYDOWN = 0x0104; + internal const int WM_SYSKEYUP = 0x0105; + + internal delegate IntPtr LowLevelKeyboardProc(int code, IntPtr wParam, IntPtr lParam); + + [StructLayout(LayoutKind.Sequential)] + internal struct KBDLLHOOKSTRUCT + { + public uint VirtualKey; + public uint ScanCode; + public uint Flags; + public uint Time; + public IntPtr ExtraInfo; + } + + [DllImport("user32.dll", SetLastError = true)] + internal static extern IntPtr SetWindowsHookEx(int hookId, LowLevelKeyboardProc callback, IntPtr module, uint threadId); + + internal delegate IntPtr LowLevelMouseProc(int code, IntPtr wParam, IntPtr lParam); + + [StructLayout(LayoutKind.Sequential)] + internal struct MSLLHOOKSTRUCT + { + public POINT Point; + public uint MouseData; + public uint Flags; + public uint Time; + public IntPtr ExtraInfo; + } + + [DllImport("user32.dll", SetLastError = true)] + internal static extern IntPtr SetWindowsHookEx(int hookId, LowLevelMouseProc callback, IntPtr module, uint threadId); + + [DllImport("user32.dll", SetLastError = true)] + internal static extern bool UnhookWindowsHookEx(IntPtr hook); + + [DllImport("user32.dll", SetLastError = true)] + internal static extern IntPtr CallNextHookEx(IntPtr hook, int code, IntPtr wParam, IntPtr lParam); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + internal static extern IntPtr GetModuleHandle(string moduleName); + + // ---------------------------------------------------------------- layered window painting + // The floating bar draws itself so its background and buttons can have separate transparency. + + [StructLayout(LayoutKind.Sequential)] + internal struct SIZE + { + public int Width; + public int Height; + + public SIZE(int width, int height) + { + Width = width; + Height = height; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct BLENDFUNCTION + { + public byte BlendOp; + public byte BlendFlags; + public byte SourceConstantAlpha; + public byte AlphaFormat; + } + + [DllImport("user32.dll", SetLastError = true)] + internal static extern bool UpdateLayeredWindow( + IntPtr hWnd, + IntPtr hdcDst, + ref POINT pptDst, + ref SIZE psize, + IntPtr hdcSrc, + ref POINT pptSrc, + int crKey, + ref BLENDFUNCTION pblend, + int dwFlags); + + [DllImport("user32.dll", SetLastError = true)] + internal static extern IntPtr GetDC(IntPtr hWnd); + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern IntPtr SendMessageTimeout( IntPtr hWnd, diff --git a/src/pacs_win_uia/Models/AppSettings.cs b/src/pacs_win_uia/Models/AppSettings.cs index f5d1abf..cf61e9b 100644 --- a/src/pacs_win_uia/Models/AppSettings.cs +++ b/src/pacs_win_uia/Models/AppSettings.cs @@ -13,6 +13,14 @@ namespace pacs_win_uia.Models public sealed class AppSettings { public const int CurrentVersion = 1; + public const int DefaultRefreshIntervalMs = 300; + public const int MinimumRefreshIntervalMs = 50; + public const int MaximumRefreshIntervalMs = 60000; + + public static int NormalizeRefreshIntervalMs(int value) + { + return Clamp(value, MinimumRefreshIntervalMs, MaximumRefreshIntervalMs, DefaultRefreshIntervalMs); + } public AppSettings() { @@ -113,6 +121,9 @@ namespace pacs_win_uia.Models Ui.TreeMaxDepth = Clamp(Ui.TreeMaxDepth, 1, 32, 12); Ui.TreeMaxNodes = Clamp(Ui.TreeMaxNodes, 50, 50000, 3000); Ui.TreeTimeoutSeconds = Clamp(Ui.TreeTimeoutSeconds, 1, 600, 10); + // DataContract deserialization leaves fields absent in older JSON at zero. + Ui.TreeRefreshIntervalMs = NormalizeRefreshIntervalMs(Ui.TreeRefreshIntervalMs); + FloatingButton.RefreshIntervalMs = NormalizeRefreshIntervalMs(FloatingButton.RefreshIntervalMs); Read.DefaultTimeoutSeconds = Clamp(Read.DefaultTimeoutSeconds, 0, 3600, 10); Ocr.ApplyDefaults(); @@ -167,6 +178,7 @@ namespace pacs_win_uia.Models TreeMaxDepth = 12; TreeMaxNodes = 3000; TreeTimeoutSeconds = 10; + TreeRefreshIntervalMs = AppSettings.DefaultRefreshIntervalMs; } [DataMember(Order = 1)] @@ -188,6 +200,34 @@ namespace pacs_win_uia.Models [DataMember(Order = 5)] [Description("控件树读取超时(秒)。")] public int TreeTimeoutSeconds { get; set; } + + /// + /// Where the settings dialog was last placed. Remembered so it opens where the operator left it; + /// all values are 0 until it has been moved once, and a remembered position that is no longer on + /// any screen is ignored (the monitor may be gone). + /// + [DataMember(Order = 6, EmitDefaultValue = false)] + [Description("设置窗口上次的位置与大小(0 = 还没有记录,首次打开会居中)。")] + public int SettingsWindowX { get; set; } + + [DataMember(Order = 7, EmitDefaultValue = false)] + public int SettingsWindowY { get; set; } + + [DataMember(Order = 8, EmitDefaultValue = false)] + public int SettingsWindowWidth { get; set; } + + [DataMember(Order = 9, EmitDefaultValue = false)] + public int SettingsWindowHeight { get; set; } + + [DataMember(Order = 10)] + [Description("控件树及高亮重解析刷新间隔(毫秒,50-60000,默认300;0按默认值处理)。")] + public int TreeRefreshIntervalMs { get; set; } + + [IgnoreDataMember] + public bool HasSettingsWindowBounds + { + get { return SettingsWindowWidth > 200 && SettingsWindowHeight > 200; } + } } [DataContract] @@ -195,6 +235,7 @@ namespace pacs_win_uia.Models { public FloatingButtonSettings() { + RefreshIntervalMs = AppSettings.DefaultRefreshIntervalMs; Bars = new List(); } @@ -205,6 +246,10 @@ namespace pacs_win_uia.Models [DataMember(Order = 1)] public List Bars { get; set; } + [DataMember(Order = 2)] + [Description("悬浮条跟随、显示条件及导入 path 的刷新间隔(毫秒,50-60000,默认300;0按默认值处理)。")] + public int RefreshIntervalMs { get; set; } + /// One ready-to-use bar so the feature is discoverable. public static List CreateDefaultBars() { diff --git a/src/pacs_win_uia/Models/ControlLocator.cs b/src/pacs_win_uia/Models/ControlLocator.cs index 60dd206..ac07c96 100644 --- a/src/pacs_win_uia/Models/ControlLocator.cs +++ b/src/pacs_win_uia/Models/ControlLocator.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Runtime.Serialization; using System.Text; @@ -10,7 +9,7 @@ namespace pacs_win_uia.Models [DataContract] public enum ControlSourcePreference { - /// Try UIA, then MSAA, then Win32; the first that resolves wins. + /// Choose an available snapshot before evaluating XPath once. [EnumMember] Auto, @@ -24,7 +23,7 @@ namespace pacs_win_uia.Models Win32 } - /// One step of the UIA path, from the top-level window down to the control. + /// Legacy UIA data retained for deserialization/display only, never executed. [DataContract] public sealed class ControlLocatorSegment { @@ -37,7 +36,10 @@ namespace pacs_win_uia.Models [DataMember(Order = 3, EmitDefaultValue = false)] public string AutomationId { get; set; } - /// Ordinal among same-type siblings; the last resort when names are not unique. + [DataMember(Order = 5, EmitDefaultValue = false)] + public string ClassName { get; set; } + + /// ZERO-based ordinal among ALL same-type siblings; -1 means unspecified. [DataMember(Order = 4)] public int Index { get; set; } @@ -53,7 +55,7 @@ namespace pacs_win_uia.Models } } - /// One step of the Win32 path: class name plus ordinal among same-class siblings. + /// Legacy Win32 data retained for deserialization/display only, never executed. [DataContract] public sealed class Win32LocatorSegment { @@ -69,41 +71,9 @@ namespace pacs_win_uia.Models } } - /// Helpers shared by the path builder and the resolver so the two cannot disagree. + /// Legacy display helpers only. These strings must never be executed as locators. public static class ControlLocatorFormat { - /// MSAA path keys are stored relative to the root window ("i3/o1"), not absolute. - public static string StripRoot(string pathKey) - { - if (string.IsNullOrEmpty(pathKey)) - { - return string.Empty; - } - - int slash = pathKey.IndexOf('/'); - return slash < 0 ? string.Empty : pathKey.Substring(slash + 1); - } - - public static IList SplitMsaaPath(string pathKey) - { - var parts = new List(); - string relative = StripRoot(pathKey); - if (string.IsNullOrEmpty(relative)) - { - return parts; - } - - foreach (string part in relative.Split('/')) - { - if (!string.IsNullOrEmpty(part)) - { - parts.Add(part); - } - } - - return parts; - } - public static string DescribeUiaPath(IList segments) { if (segments == null || segments.Count == 0) diff --git a/src/pacs_win_uia/Models/ControlMonitorDefinition.cs b/src/pacs_win_uia/Models/ControlMonitorDefinition.cs index 1b06368..e45be84 100644 --- a/src/pacs_win_uia/Models/ControlMonitorDefinition.cs +++ b/src/pacs_win_uia/Models/ControlMonitorDefinition.cs @@ -19,7 +19,7 @@ namespace pacs_win_uia.Models [DataMember(Order = 1, IsRequired = true)] public string Id { get; set; } - /// Human-readable path from the top-level window down to the control. Display only. + /// Authoritative XPath 1.0 over the selected source snapshot. Legacy text is display-only. [DataMember(Order = 2, IsRequired = false, EmitDefaultValue = false)] public string ControlPath { get; set; } @@ -34,11 +34,11 @@ namespace pacs_win_uia.Models /// UIA runtime id of the control at capture time. It is a hint for re-resolution only: /// runtime ids are not stable across a restart of the target application. /// - [DataMember(Order = 5, IsRequired = false, EmitDefaultValue = false)] + [IgnoreDataMember] public string RuntimeId { get; set; } // ---------------------------------------------------------------- re-resolution locator - // All of these are additive: a file written by an older build simply has them missing. + // Legacy locator fields are retained only for loading/display; resolution uses ControlPath. /// /// Persisted as a readable name ("Auto"/"Uia"/"Msaa"/"Win32") rather than a number: the @@ -49,7 +49,7 @@ namespace pacs_win_uia.Models public string SourceName { get; set; } [IgnoreDataMember] - [Description("回读时优先使用的来源:自动(UIA→MSAA→Win32)/ UIA / MSAA / Win32。")] + [Description("XPath 快照来源:自动先选可用来源(UIA→MSAA→Win32);显式来源不跨来源回退。")] public ControlSourcePreference Source { get { return ParseSourcePreference(SourceName); } @@ -94,15 +94,20 @@ namespace pacs_win_uia.Models public string WindowTitleKeyword { get; set; } [DataMember(Order = 10, IsRequired = false, EmitDefaultValue = false)] - [Description("UIA 层级定位路径:从顶层窗口到控件逐段记录(AutomationId 优先,其次类型+名称,最后同级序号)。")] + [Description("旧 UIA 结构化路径(仅保留显示,不执行;请重新拾取生成 XPath)。")] public List UiaPath { get; set; } [DataMember(Order = 11, IsRequired = false, EmitDefaultValue = false)] - [Description("MSAA 定位路径,形如 i3/o1/i2(i=简单子 ID,o=子对象),相对于顶层窗口。")] + [Description("旧 MSAA 路径(仅保留显示,不执行;请重新拾取生成 XPath)。")] public string MsaaPathKey { get; set; } + /// Legacy flag retained only for deserialization/display, never executed. + [DataMember(Order = 17, IsRequired = false, EmitDefaultValue = false)] + [Description("旧内层窗口标志(不再参与定位或新保存)。")] + public bool UiaPathFromInnerWindow { get; set; } + [DataMember(Order = 12, IsRequired = false, EmitDefaultValue = false)] - [Description("Win32 定位路径:逐级窗口类名 + 同级同类序号。")] + [Description("旧 Win32 结构化路径(仅保留显示,不执行;请重新拾取生成 XPath)。")] public List Win32Path { get; set; } [DataMember(Order = 13, IsRequired = false, EmitDefaultValue = false)] @@ -141,8 +146,8 @@ namespace pacs_win_uia.Models [Description("等待该控件出现的秒数。0 = 使用全局 --timeout。每条独立计时,某个控件等不到不会拖累其他控件。")] public int TimeoutSeconds { get; set; } - [DataMember(Order = 14, IsRequired = false, EmitDefaultValue = false)] - [Description("添加该控件时读到的当前值,供人工核对;回读时以 ValueKey 实时读取的结果为准。")] + [IgnoreDataMember] + [Description("实时读取的值,不写入监控定义 JSON。")] public string Value { get; set; } string IDataErrorInfo.Error diff --git a/src/pacs_win_uia/Models/ControlMonitorRules.cs b/src/pacs_win_uia/Models/ControlMonitorRules.cs index 0ded6ad..74c0220 100644 --- a/src/pacs_win_uia/Models/ControlMonitorRules.cs +++ b/src/pacs_win_uia/Models/ControlMonitorRules.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Text.RegularExpressions; +using pacs_win_uia.Services; namespace pacs_win_uia.Models { @@ -77,7 +78,7 @@ namespace pacs_win_uia.Models case "Id": return ValidateId(definition.Id); case "ControlPath": - return ValidateRequired(definition.ControlPath, "控件 Path", MaxControlPathLength); + return ValidateControlPath(definition.ControlPath); case "RuntimeId": return definition.RuntimeId == null || definition.RuntimeId.Length <= MaxRuntimeIdLength ? null @@ -111,6 +112,17 @@ namespace pacs_win_uia.Models /// Validates the whole list, including rules that span rows. Returns every error found. public static IList ValidateList(IList definitions) + { + return ValidateList(definitions, true); + } + + /// + /// Validates a definition list. Loading uses false so + /// an old or hand-edited path remains available for repair instead of making the whole file + /// unreadable; saving and UI validation use the strict default overload. + /// + public static IList ValidateList( + IList definitions, bool validatePathSyntax) { var errors = new List(); if (definitions == null) @@ -138,7 +150,10 @@ namespace pacs_win_uia.Models foreach (string field in Fields) { - string message = ValidateField(definition, field); + string message = field == "ControlPath" && !validatePathSyntax + ? (definition.ControlPath == null || definition.ControlPath.Length <= MaxControlPathLength + ? null : "控件 Path 过长(上限 " + MaxControlPathLength + " 个字符)。") + : ValidateField(definition, field); if (message != null) { errors.Add(new ControlMonitorValidationError(index, field, message)); @@ -196,6 +211,12 @@ namespace pacs_win_uia.Models return null; } + /// Shared by direct edits, the multiline editor, PropertyGrid and save validation. + public static string ValidateControlPath(string path) + { + return ValidateRequired(path, "控件 Path", MaxControlPathLength) ?? ControlPath.ValidateSyntax(path); + } + private static string ValidateRequired(string value, string label, int maxLength) { if (string.IsNullOrWhiteSpace(value)) diff --git a/src/pacs_win_uia/Models/ControlTreeNode.cs b/src/pacs_win_uia/Models/ControlTreeNode.cs index 9d54e73..1b91bd0 100644 --- a/src/pacs_win_uia/Models/ControlTreeNode.cs +++ b/src/pacs_win_uia/Models/ControlTreeNode.cs @@ -60,6 +60,13 @@ namespace pacs_win_uia.Models [DataMember(Order = 7)] public string ChildrenError { get; set; } + /// Prepared absolute XPath in the current snapshot; not persisted. + [IgnoreDataMember] + public string CanonicalPath { get; internal set; } + + [IgnoreDataMember] + internal ControlTreeNode CanonicalPathRoot { get; set; } + [Browsable(false)] [IgnoreDataMember] public UiaElementInfo UiaElement diff --git a/src/pacs_win_uia/Models/FloatingBarDefinition.cs b/src/pacs_win_uia/Models/FloatingBarDefinition.cs index 134e8e6..40f4d45 100644 --- a/src/pacs_win_uia/Models/FloatingBarDefinition.cs +++ b/src/pacs_win_uia/Models/FloatingBarDefinition.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.Serialization; @@ -6,7 +6,6 @@ using System.Windows.Forms; namespace pacs_win_uia.Models { - /// What clicking a floating button does. [DataContract] public enum FloatingActionKind { @@ -39,6 +38,28 @@ namespace pacs_win_uia.Models RunCommand } + /// + /// One entry of the settings dialog's "点击执行操作" dropdown: the enum value plus its Chinese name. + /// The grid must show the Chinese name while still writing the enum into the model. + /// + public sealed class FloatingActionChoice + { + public FloatingActionChoice(FloatingActionKind value, string display) + { + Value = value; + Display = display; + } + + public FloatingActionKind Value { get; private set; } + + public string Display { get; private set; } + + public override string ToString() + { + return Display; + } + } + [DataContract] public sealed class FloatingButtonDefinition { @@ -47,6 +68,27 @@ namespace pacs_win_uia.Models Enabled = true; } + [OnDeserializing] + private void OnDeserializing(StreamingContext context) + { + // DataContractJsonSerializer does not run constructors. An omitted flag means enabled; + // an explicitly saved false is still applied after this callback. + Enabled = true; + } + + [IgnoreDataMember] + public string ConfigurationError + { + get + { + if (!Enum.IsDefined(typeof(FloatingActionKind), Action) || Action == FloatingActionKind.None) + return "请选择按钮的点击操作(不能为不执行任何操作)。"; + if (Action == FloatingActionKind.RunCommand && string.IsNullOrWhiteSpace(CommandLine)) + return "执行命令按钮的命令行为空。"; + return null; + } + } + [DataMember(Order = 1)] [Description("按钮上显示的名称。")] public string Label { get; set; } @@ -72,6 +114,32 @@ namespace pacs_win_uia.Models return string.IsNullOrEmpty(Label) ? Action.ToString() : Label; } + /// + /// The actions a floating button can run, in the order the settings dialog offers them, each + /// with the Chinese name the operator sees. + /// + public static IList DescribeChoices() + { + var choices = new List(); + foreach (FloatingActionKind kind in new[] + { + FloatingActionKind.PickControl, + FloatingActionKind.ReadList, + FloatingActionKind.LocateControl, + FloatingActionKind.RefreshStates, + FloatingActionKind.InspectWindow, + FloatingActionKind.Screenshot, + FloatingActionKind.OcrRead, + FloatingActionKind.RunCommand, + FloatingActionKind.None + }) + { + choices.Add(new FloatingActionChoice(kind, DescribeAction(kind))); + } + + return choices; + } + public static string DescribeAction(FloatingActionKind kind) { switch (kind) @@ -107,6 +175,11 @@ namespace pacs_win_uia.Models public sealed class FloatingBarDefinition { public FloatingBarDefinition() + { + SetDefaults(); + } + + private void SetDefaults() { Enabled = true; OpacityPercent = 90; @@ -116,6 +189,53 @@ namespace pacs_win_uia.Models Buttons = new List(); } + [OnDeserializing] + private void OnDeserializing(StreamingContext context) + { + SetDefaults(); + } + + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + if (Buttons == null) Buttons = new List(); + } + + [IgnoreDataMember] + public int EnabledButtonCount + { + get + { + int count = 0; + foreach (FloatingButtonDefinition button in Buttons ?? new List()) + if (button != null && button.Enabled) count++; + return count; + } + } + + /// Do not silently turn intentionally disabled buttons back on. + [IgnoreDataMember] + public string ButtonConfigurationError + { + get + { + if (EnabledButtonCount == 0) return "没有启用的按钮;请新增按钮或勾选按钮的启用。"; + foreach (FloatingButtonDefinition button in Buttons) + if (button != null && button.Enabled && button.ConfigurationError != null) + return "按钮「" + button + "」:" + button.ConfigurationError; + return null; + } + } + + /// Importing a condition into an empty bar also gives it a real, editable action. + public bool EnsureButtonForImport() + { + if (Buttons == null) Buttons = new List(); + if (EnabledButtonCount > 0) return false; + Buttons.Add(new FloatingButtonDefinition { Label = "定位控件", Action = FloatingActionKind.LocateControl }); + return true; + } + [DataMember(Order = 1)] public string Name { get; set; } @@ -124,9 +244,34 @@ namespace pacs_win_uia.Models public bool Enabled { get; set; } [DataMember(Order = 3)] - [Description("悬浮条不透明度(20-100)。")] + [Description("悬浮条整体不透明度(20-100)。下面是背景/按钮各自的透明度;留 0 表示沿用这个值。")] public int OpacityPercent { get; set; } + /// + /// The bar is drawn by the tool itself (a layered window), so the background and the buttons can + /// have different transparency. 0 means "not set" and falls back to OpacityPercent — 0% would be + /// invisible anyway. + /// + [DataMember(Order = 10, EmitDefaultValue = false)] + [Description("背景透明度(0-100,留 0 = 用「透明度」)。")] + public int BackgroundOpacityPercent { get; set; } + + [DataMember(Order = 11, EmitDefaultValue = false)] + [Description("按钮(控件)透明度(0-100,留 0 = 用「透明度」)。")] + public int ControlOpacityPercent { get; set; } + + [IgnoreDataMember] + public int EffectiveBackgroundOpacity + { + get { return BackgroundOpacityPercent > 0 ? BackgroundOpacityPercent : Math.Max(1, OpacityPercent); } + } + + [IgnoreDataMember] + public int EffectiveControlOpacity + { + get { return ControlOpacityPercent > 0 ? ControlOpacityPercent : Math.Max(1, OpacityPercent); } + } + [DataMember(Order = 4)] [Description("相对锚定窗口左上角的 X 偏移。")] public int OffsetX { get; set; } @@ -155,17 +300,17 @@ namespace pacs_win_uia.Models [DataMember(Order = 9, EmitDefaultValue = false)] public ControlMonitorDefinition ImportedCondition { get; set; } - [DataMember(Order = 10)] + [DataMember(Order = 12)] [Description("锚定窗口必须可见(未最小化且没有被遮挡)时才显示。")] public bool RequireWindowVisible { get; set; } - [DataMember(Order = 11)] + [DataMember(Order = 13)] public List Buttons { get; set; } public override string ToString() { string name = string.IsNullOrEmpty(Name) ? "(未命名悬浮条)" : Name; - return name + "(" + Buttons.Count + " 个按钮)"; + return name + "(" + (Enabled ? "启用" : "停用") + "," + EnabledButtonCount + " 个启用按钮)"; } /// diff --git a/src/pacs_win_uia/Models/HeadlessReport.cs b/src/pacs_win_uia/Models/HeadlessReport.cs index 058c5d7..10d6884 100644 --- a/src/pacs_win_uia/Models/HeadlessReport.cs +++ b/src/pacs_win_uia/Models/HeadlessReport.cs @@ -33,6 +33,9 @@ namespace pacs_win_uia.Models [DataMember(Order = 6)] public List Items { get; set; } + + [DataMember(Order = 7)] + public bool SkipDisabled { get; set; } } [DataContract] @@ -56,6 +59,8 @@ namespace pacs_win_uia.Models /// Entries left disabled in the config, so deliberately not read. [DataMember(Order = 5)] public int Skipped { get; set; } + + /// Whether disabled definitions were skipped for this report. } [DataContract] diff --git a/src/pacs_win_uia/Models/UiaElementInfo.cs b/src/pacs_win_uia/Models/UiaElementInfo.cs index 94cf902..fc405ef 100644 --- a/src/pacs_win_uia/Models/UiaElementInfo.cs +++ b/src/pacs_win_uia/Models/UiaElementInfo.cs @@ -24,6 +24,31 @@ namespace pacs_win_uia.Models [Browsable(false)] public AutomationElement Element { get; set; } + /// + /// Display-only extras for the 控件属性 grid. They are filled by the tool when the node is shown + /// and are never serialised — the same values are recomputed from the live tree. + /// + [IgnoreDataMember] + [Browsable(true)] + [ReadOnly(true)] + [Description("从顶层窗口到该控件的 UIA 路径(与监控列表保存的路径同格式,可粘进「杂项 → 按 path 定位」验证)。")] + public string ControlPath { get; set; } + + [IgnoreDataMember] + [Browsable(true)] + [ReadOnly(true)] + [Description("页面特征:进程=…;标题关键词=…;窗口类=…(与悬浮条显示条件同一套取值)。")] + public string PageFeatures { get; set; } + + [IgnoreDataMember] + [Browsable(true)] + [ReadOnly(true)] + [Description("该控件当前是否获得键盘焦点(未知 = 本次快照没有读焦点)。")] + public string FocusState + { + get { return HasKeyboardFocus.HasValue ? (HasKeyboardFocus.Value ? "是" : "否") : "未知"; } + } + [DataMember(Order = 1)] [Description("UIA 名称。按钮文字、列表行的文本通常在这里;为空不代表控件没有内容,可能要从 ValuePattern/TextPattern 取。")] public string Name { get; set; } diff --git a/src/pacs_win_uia/Picker/CrosshairPicker.cs b/src/pacs_win_uia/Picker/CrosshairPicker.cs index c84bd02..7d052e9 100644 --- a/src/pacs_win_uia/Picker/CrosshairPicker.cs +++ b/src/pacs_win_uia/Picker/CrosshairPicker.cs @@ -1,9 +1,10 @@ -using System; +using System; using System.Drawing; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using pacs_win_uia.Diagnostics; +using pacs_win_uia.Interop; using pacs_win_uia.Models; using pacs_win_uia.Services; using pacs_win_uia.UI; @@ -20,7 +21,7 @@ namespace pacs_win_uia.Picker private readonly Control _owner; private readonly int _ownProcessId; private readonly TargetProbeService _probeService; - private readonly HighlightOverlayForm _highlight; + private readonly HighlightFollower _highlight; private readonly System.Windows.Forms.Timer _probeWatchdog; private PickerOverlayForm _pickerOverlay; private CancellationTokenSource _operationCancellation; @@ -35,6 +36,10 @@ namespace pacs_win_uia.Picker private bool _pickRequested; private PointPickResult _lastResult; private Task _probeTask; + /// Keeps the confirmation click away from the target application. + private NativeMethods.LowLevelMouseProc _mouseHook; + private IntPtr _mouseHookHandle = IntPtr.Zero; + private bool _pendingClickSwallowed; private DateTime _probeStartedUtc; private DateTime _pickDeadlineUtc; @@ -42,8 +47,12 @@ namespace pacs_win_uia.Picker { _owner = owner ?? throw new ArgumentNullException("owner"); _probeService = probeService ?? throw new ArgumentNullException("probeService"); - _highlight = new HighlightOverlayForm(); _ownProcessId = System.Diagnostics.Process.GetCurrentProcess().Id; + _highlight = new HighlightFollower(_ownProcessId); + _highlight.Hidden += delegate(object sender, HighlightHiddenEventArgs e) + { + AppLog.Debug("拾取预览:" + e.Reason); + }; // Fine-grained enough to honour the pick deadline (1.2 s) without being busy. _probeWatchdog = new System.Windows.Forms.Timer { Interval = 150 }; _probeWatchdog.Tick += ProbeWatchdogOnTick; @@ -66,7 +75,7 @@ namespace pacs_win_uia.Picker } _isPicking = true; - _highlight.HideHighlight(); + _highlight.Hide("拾取开始。"); _hasLastProbePoint = false; _lastNativeWindowHandle = IntPtr.Zero; _hasPendingProbePoint = false; @@ -81,6 +90,7 @@ namespace pacs_win_uia.Picker _pickerOverlay.FormClosed += PickerOverlayOnFormClosed; _pickerOverlay.Show(); _probeWatchdog.Start(); + InstallMouseHook(); AppLog.Info("十字拾取器已启动。"); } @@ -123,7 +133,7 @@ namespace pacs_win_uia.Picker if (!_pickRequested) { _hasPendingProbePoint = false; - _highlight.HideHighlight(); + _highlight.Hide("探测卡住,已收起预览框。"); } } @@ -135,7 +145,7 @@ namespace pacs_win_uia.Picker } AppLog.Info("十字拾取已取消。"); - Stop(false); + Stop(); EventHandler handler = Canceled; if (handler != null) { @@ -207,7 +217,7 @@ namespace pacs_win_uia.Picker task.Exception.Handle(delegate { return true; }); _pickRequested = false; _hasPendingProbePoint = false; - _highlight.HideHighlight(); + _highlight.Hide("预览探测异常。"); return; } if (!task.IsCanceled && !task.IsFaulted) @@ -216,27 +226,19 @@ namespace pacs_win_uia.Picker bool hasHighlight = false; // Bounds is filled from whichever source identified the target, so a target that only - // Win32 or MSAA can see still gets a highlight box. A minimized or covered target gets - // none: a box over a window the operator cannot see only adds noise. + // Win32 or MSAA can see still gets a highlight box. The follower keeps it glued to the + // target window while the mouse is still, and takes it away when the target is + // minimized or covered. if (_lastResult != null && _lastResult.HasBounds) { - Rectangle rect = _lastResult.Bounds.ToRectangle(); IntPtr anchor = _lastResult.Window == null ? IntPtr.Zero : _lastResult.Window.Handle; - string visibilityReason; - if (WindowVisibility.IsVisibleOnScreen(anchor, rect, _ownProcessId, out visibilityReason)) - { - _highlight.ShowHighlight(rect); - hasHighlight = true; - } - else - { - AppLog.Debug("拾取预览:不显示高亮框——" + visibilityReason); - } + _highlight.Show(_lastResult.Bounds.ToRectangle(), anchor, null, "拾取预览"); + hasHighlight = true; } if (!hasHighlight) { - _highlight.HideHighlight(); + _highlight.Hide("没有可高亮的矩形。"); } EventHandler previewHandler = PreviewChanged; @@ -272,13 +274,109 @@ namespace pacs_win_uia.Picker } private void PickerOverlayOnLeftButtonReleased(object sender, EventArgs e) + { + ConfirmPickAt(Cursor.Position); + } + + /// + /// Installs the low-level mouse hook that swallows the left button while picking. The overlay + /// itself is click-through on purpose (the tool has to see the window under the cursor), so + /// without the hook every pick would also press the control being picked — which an operator + /// notices immediately on a button or a menu. + /// + private void InstallMouseHook() + { + if (_mouseHookHandle != IntPtr.Zero || !_isPicking) + { + return; + } + + _mouseHook = MouseHookCallback; + _mouseHookHandle = NativeMethods.SetWindowsHookEx( + NativeMethods.WH_MOUSE_LL, _mouseHook, NativeMethods.GetModuleHandle(null), 0); + if (_mouseHookHandle == IntPtr.Zero) + { + _pendingClickSwallowed = false; + AppLog.Warn("无法安装低级鼠标钩子,拾取时的左键仍会传给目标窗口。Win32 错误码: " + + System.Runtime.InteropServices.Marshal.GetLastWin32Error()); + return; + } + + _pendingClickSwallowed = true; + AppLog.Info("拾取期间左键由本工具接管:不会传给目标窗口,也不会抢焦点。"); + } + + private void UninstallMouseHook() + { + if (_mouseHookHandle == IntPtr.Zero) + { + return; + } + + try + { + NativeMethods.UnhookWindowsHookEx(_mouseHookHandle); + } + catch (Exception ex) + { + AppLog.Debug("卸载鼠标钩子失败:" + ex.GetType().Name); + } + + _mouseHookHandle = IntPtr.Zero; + _mouseHook = null; + } + + /// True when the pick click is taken by the tool instead of the target application. + public bool ClicksAreSwallowed + { + get { return _pendingClickSwallowed; } + } + + private IntPtr MouseHookCallback(int code, IntPtr wParam, IntPtr lParam) + { + if (code < 0 || !_isPicking) + { + return NativeMethods.CallNextHookEx(_mouseHookHandle, code, wParam, lParam); + } + + int message = wParam.ToInt32(); + if (message != NativeMethods.WM_LBUTTONDOWN && message != NativeMethods.WM_LBUTTONUP) + { + return NativeMethods.CallNextHookEx(_mouseHookHandle, code, wParam, lParam); + } + + var data = (NativeMethods.MSLLHOOKSTRUCT)System.Runtime.InteropServices.Marshal.PtrToStructure( + lParam, typeof(NativeMethods.MSLLHOOKSTRUCT)); + if (message == NativeMethods.WM_LBUTTONUP) + { + Point point = new Point(data.Point.X, data.Point.Y); + // Never do real work inside a hook callback (the system kills slow hooks): hand the + // click to the UI queue and swallow the message. + try + { + if (_owner != null && _owner.IsHandleCreated && !_owner.IsDisposed) + { + _owner.BeginInvoke((Action)delegate { ConfirmPickAt(point); }); + } + } + catch (Exception) + { + // The owner is going away; the pick is already over. + } + } + + return new IntPtr(1); + } + + /// Confirms a pick at an explicit point (the hook's coordinates, or the overlay's). + private void ConfirmPickAt(Point screenPoint) { if (!_isPicking) { return; } - _pickPoint = Cursor.Position; + _pickPoint = screenPoint; _lastNativeWindowHandle = _pickerOverlay == null ? IntPtr.Zero : _pickerOverlay.RefreshCurrentWindowHandle(_pickPoint); @@ -312,7 +410,7 @@ namespace pacs_win_uia.Picker AppLog.Warn("拾取确认无效:" + (result == null ? "无探测结果" : result.FailureReason ?? "目标无效")); _pickRequested = false; _hasPendingProbePoint = false; - _highlight.HideHighlight(); + _highlight.Hide("拾取目标无效。"); if (allowRetryWhenInvalid) { EventHandler invalidHandler = PreviewChanged; @@ -324,7 +422,7 @@ namespace pacs_win_uia.Picker return; } - Stop(false); + Stop(); EventHandler failedHandler = Picked; if (failedHandler != null) { @@ -337,7 +435,9 @@ namespace pacs_win_uia.Picker AppLog.Info("拾取确认:HWND=" + result.Window.HwndHex + ";UIA=" + (result.AutomationElement == null ? "无" : result.AutomationElement.ToString())); _pickRequested = false; - Stop(true); + // The picker's own box goes away; the main window draws a followed frame for the picked + // control instead (so the frame keeps tracking the target window). + Stop(); EventHandler handler = Picked; if (handler != null) { @@ -349,14 +449,15 @@ namespace pacs_win_uia.Picker { if (_isPicking) { - Stop(false); + Stop(); } } - private void Stop(bool keepHighlight) + private void Stop() { _isPicking = false; _probeWatchdog.Stop(); + UninstallMouseHook(); _probeSequence++; _hasPendingProbePoint = false; _pickRequested = false; @@ -379,15 +480,13 @@ namespace pacs_win_uia.Picker _pickerOverlay = null; } - if (!keepHighlight) - { - _highlight.HideHighlight(); - } + _highlight.Hide("拾取结束。"); } public void Dispose() { - Stop(false); + Stop(); + UninstallMouseHook(); _probeWatchdog.Tick -= ProbeWatchdogOnTick; _probeWatchdog.Dispose(); _highlight.Dispose(); diff --git a/src/pacs_win_uia/Program.cs b/src/pacs_win_uia/Program.cs index 2849d46..dcfd843 100644 --- a/src/pacs_win_uia/Program.cs +++ b/src/pacs_win_uia/Program.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Json; using System.Text; @@ -37,28 +36,52 @@ namespace pacs_win_uia [STAThread] private static int Main(string[] args) { - AppLog.Init(); - AppLog.Info("pacs_win_uia 启动;只读模式,不注入目标进程。"); - AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; - Application.ThreadException += OnThreadException; - Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); - - if (args != null && args.Length > 0) - { - return RunHeadless(args); - } - try { - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new MainForm()); - return 0; + using (var instance = new SingleInstanceService()) + { + SingleInstanceService.Request request = CreateRequest(args ?? new string[0]); + if (!instance.IsOwner) + { + SingleInstanceService.Response response = instance.Forward(request); + Console.Out.Write(response.StandardOutput); + Console.Error.Write(response.StandardError); + return response.ExitCode; + } + + AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; + // Initialize diagnostics only in the owner. A forwarded request must retain the + // caller's standard streams; request capture never calls Console.SetOut/SetError. + AppLog.Init(); + if (request.Arguments.Length > 0) + { + // A one-shot owner also accepts clients for its lifetime, but has no window. + instance.Start((incoming, stdout, stderr, cancellation) => + ExecuteRequest(incoming, stdout, stderr, cancellation, null)); + return instance.Execute(request, Console.Out, Console.Error); + } + + AppLog.Info("pacs_win_uia 启动;只读模式,不注入目标进程。"); + Application.ThreadException += OnThreadException; + Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + using (var form = new MainForm()) + { + // Create the handle on the UI thread before workers may BeginInvoke. + IntPtr handle = form.Handle; + instance.Start((incoming, stdout, stderr, cancellation) => + ExecuteRequest(incoming, stdout, stderr, cancellation, form)); + Application.Run(form); + } + return 0; + } } catch (Exception ex) { - AppLog.Error("主界面异常退出。", ex); - throw; + Console.Error.WriteLine("启动或转发失败(不会另开实例执行):" + ex.Message); + AppLog.Error("启动或转发失败。", ex); + return 2; } finally { @@ -66,7 +89,92 @@ namespace pacs_win_uia } } - private static int RunHeadless(string[] args) + private static SingleInstanceService.Request CreateRequest(string[] args) + { + var normalized = (string[])args.Clone(); + // Resolve on the launching process: this also preserves drive-relative paths (C:foo) + // and rooted paths (\\foo), without ever changing the owner's process-wide CWD. + for (int index = 0; index < normalized.Length; index++) + { + string arg = normalized[index]; + if (arg == "--help" || arg == "-h" || arg == "/?") break; + if (arg == "--timeout") + { + index++; + } + else if ((arg == "--read-config" || arg == "--output") && index + 1 < normalized.Length && + !normalized[index + 1].StartsWith("--", StringComparison.Ordinal)) + { + if (!string.IsNullOrEmpty(normalized[index + 1])) + { + normalized[index + 1] = Path.GetFullPath(normalized[index + 1]); + } + index++; + } + } + return new SingleInstanceService.Request + { + Arguments = normalized, + DefaultOutputPath = GetDefaultOutputPath() + }; + } + + private static int ExecuteRequest(SingleInstanceService.Request request, TextWriter stdout, + TextWriter stderr, CancellationToken cancellation, Form form) + { + if (request.Arguments.Length > 0) + { + return RunHeadless(request.Arguments, stdout, stderr, request.DefaultOutputPath, cancellation); + } + if (form == null) + { + stderr.WriteLine("已有实例正在执行一次性无界面读取,没有可激活的窗口;请在其退出后重试。"); + return 2; + } + + // BeginInvoke rather than blocking Control.Invoke: closing the window must not strand + // a worker and deadlock service disposal. Only the short activation runs on the UI. + var completion = new System.Threading.Tasks.TaskCompletionSource(); + try + { + form.BeginInvoke(new Action(() => + { + if (completion.Task.IsCompleted) return; + try + { + if (form.IsDisposed || form.Disposing) throw new InvalidOperationException("主窗口正在关闭。"); + if (!form.Visible) form.Show(); + if (form.WindowState == FormWindowState.Minimized) form.WindowState = FormWindowState.Normal; + form.BringToFront(); + form.Activate(); + pacs_win_uia.Interop.NativeMethods.SetForegroundWindow(form.Handle); + completion.TrySetResult(true); + } + catch (Exception ex) + { + completion.TrySetException(ex); + } + })); + if (!completion.Task.Wait(15000, cancellation)) + { + throw new TimeoutException("等待主窗口激活超时。"); + } + completion.Task.GetAwaiter().GetResult(); + return 0; + } + catch (Exception ex) + { + stderr.WriteLine("激活主窗口失败:" + ex.Message); + return 2; + } + finally + { + completion.TrySetCanceled(); + } + } + + private static int RunHeadless(string[] args, TextWriter stdout, TextWriter stderr, + string defaultOutputPath, CancellationToken cancellationToken) { string configPath = null; string outputPath = null; @@ -82,7 +190,7 @@ namespace pacs_win_uia case "--help": case "-h": case "/?": - Console.WriteLine(Usage); + stdout.WriteLine(Usage); return 0; case "--read-config": // The path is optional: without one the config the GUI saved is used. @@ -98,7 +206,7 @@ namespace pacs_win_uia break; case "--read-saved": configPath = GetDefaultConfigPath(); - outputPath = GetDefaultOutputPath(); + outputPath = defaultOutputPath; break; case "--output": if (index + 1 < args.Length && !args[index + 1].StartsWith("--", StringComparison.Ordinal)) @@ -107,14 +215,14 @@ namespace pacs_win_uia } else { - outputPath = GetDefaultOutputPath(); + outputPath = defaultOutputPath; } break; case "--timeout": if (++index >= args.Length || !double.TryParse(args[index], out timeoutSeconds) || timeoutSeconds < 0) { - return UsageError("--timeout 需要一个不小于 0 的秒数。"); + return UsageError(stderr, "--timeout 需要一个不小于 0 的秒数。"); } break; @@ -125,13 +233,13 @@ namespace pacs_win_uia forceOcr = true; break; default: - return UsageError("无法识别的参数:" + arg); + return UsageError(stderr, "无法识别的参数:" + arg); } } if (string.IsNullOrEmpty(configPath)) { - return UsageError("必须指定 --read-config 或 --read-saved。"); + return UsageError(stderr, "必须指定 --read-config 或 --read-saved。"); } string fullConfigPath; @@ -141,18 +249,18 @@ namespace pacs_win_uia } catch (Exception ex) { - return UsageError("配置文件路径无效:" + ex.Message); + return UsageError(stderr, "配置文件路径无效:" + ex.Message); } if (!File.Exists(fullConfigPath)) { - return UsageError("配置文件不存在:" + fullConfigPath); + return UsageError(stderr, "配置文件不存在:" + fullConfigPath); } - Console.Error.WriteLine("配置文件:" + fullConfigPath); + stderr.WriteLine("配置文件:" + fullConfigPath); if (!string.IsNullOrEmpty(outputPath)) { - Console.Error.WriteLine("输出文件:" + Path.GetFullPath(outputPath)); + stderr.WriteLine("输出文件:" + Path.GetFullPath(outputPath)); } // OCR is off unless the settings file switches it on; --ocr forces it for this run. @@ -180,19 +288,20 @@ namespace pacs_win_uia try { var reader = new HeadlessConfigReader(new ControlMonitorStore(fullConfigPath)); - report = reader.Read(fullConfigPath, TimeSpan.FromSeconds(timeoutSeconds), activate, ocr, CancellationToken.None); + report = reader.Read(fullConfigPath, TimeSpan.FromSeconds(timeoutSeconds), activate, ocr, cancellationToken, + settings.Read == null || settings.Read.SkipDisabled); } catch (InvalidDataException ex) { // A malformed config is a usage problem, not a read failure. AppLog.Error("配置文件无效。", ex); - Console.Error.WriteLine("配置文件无效:" + ex.Message); + stderr.WriteLine("配置文件无效:" + ex.Message); return 2; } catch (Exception ex) { AppLog.Error("无界面读取失败。", ex); - Console.Error.WriteLine("无界面读取失败:" + ex.Message); + stderr.WriteLine("无界面读取失败:" + ex.Message); return 2; } @@ -201,7 +310,7 @@ namespace pacs_win_uia string json = SerializeReport(report); if (string.IsNullOrEmpty(outputPath)) { - Console.Out.WriteLine(json); + stdout.WriteLine(json); } else { @@ -214,13 +323,13 @@ namespace pacs_win_uia File.WriteAllText(fullOutput, json, new UTF8Encoding(false)); AppLog.Info("报告已写入:" + fullOutput); - Console.Out.WriteLine("报告已写入:" + fullOutput); + stdout.WriteLine("报告已写入:" + fullOutput); } } catch (Exception ex) { AppLog.Error("写出报告失败。", ex); - Console.Error.WriteLine("写出报告失败:" + ex.Message); + stderr.WriteLine("写出报告失败:" + ex.Message); return 2; } @@ -262,11 +371,11 @@ namespace pacs_win_uia } } - private static int UsageError(string message) + private static int UsageError(TextWriter stderr, string message) { - Console.Error.WriteLine(message); - Console.Error.WriteLine(); - Console.Error.WriteLine(Usage); + stderr.WriteLine(message); + stderr.WriteLine(); + stderr.WriteLine(Usage); AppLog.Error("参数错误:" + message); return 2; } diff --git a/src/pacs_win_uia/Services/CommandRunner.cs b/src/pacs_win_uia/Services/CommandRunner.cs index 645141c..2a4c368 100644 --- a/src/pacs_win_uia/Services/CommandRunner.cs +++ b/src/pacs_win_uia/Services/CommandRunner.cs @@ -54,6 +54,10 @@ namespace pacs_win_uia.Services private readonly object _sync = new object(); private readonly List _continuousTimers = new List(); private readonly HashSet _inFlight = new HashSet(StringComparer.Ordinal); + /// Processes still running, so exit can end them instead of leaving them behind. + private readonly Dictionary _running = new Dictionary(); + /// Kills the whole command tree when this tool goes away, including a crash. + private readonly ProcessJob _job = new ProcessJob(); private bool _disposed; public event EventHandler Output; @@ -244,19 +248,30 @@ namespace pacs_win_uia.Services } result.Started = true; - process.BeginOutputReadLine(); - process.BeginErrorReadLine(); - int timeoutMs = Math.Max(1, command.TimeoutSeconds) * 1000; - if (!process.WaitForExit(timeoutMs)) + // Membership of the job is what makes "退出时连同命令拉起的应用一起结束" true: + // killing cmd.exe alone would leave the application it started running. + _job.TryAssign(process); + TrackRunning(process); + try { - result.TimedOut = true; - TryKill(process); - AppLog.Warn("命令超时(" + command.TimeoutSeconds + " 秒),已结束:" + command.CommandLine); + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + int timeoutMs = Math.Max(1, command.TimeoutSeconds) * 1000; + if (!process.WaitForExit(timeoutMs)) + { + result.TimedOut = true; + KillProcessTree(process, "命令超时"); + AppLog.Warn("命令超时(" + command.TimeoutSeconds + " 秒),已结束:" + command.CommandLine); + } + else + { + process.WaitForExit(); // let the async readers flush + result.ExitCode = process.ExitCode; + } } - else + finally { - process.WaitForExit(); // let the async readers flush - result.ExitCode = process.ExitCode; + UntrackRunning(process); } } } @@ -273,18 +288,103 @@ namespace pacs_win_uia.Services return result; } - private static void TryKill(Process process) + private void TrackRunning(Process process) { + lock (_sync) + { + _running[process.Id] = process; + } + } + + private void UntrackRunning(Process process) + { + lock (_sync) + { + _running.Remove(process.Id); + } + } + + /// + /// Ends a command process *and its children* (a command may have launched an application). + /// taskkill /T walks the tree; a plain Kill would only take down cmd.exe and leave the + /// application running with no way for the operator to see where it came from. + /// + private void KillProcessTree(Process process, string reason) + { + if (process == null) + { + return; + } + + int processId; try { - process.Kill(); + processId = process.Id; + } + catch (Exception) + { + return; // already gone + } + + try + { + var info = new ProcessStartInfo("taskkill", "/PID " + processId + " /T /F") + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + using (Process killer = Process.Start(info)) + { + if (killer != null) + { + // Bounded: exit must not hang waiting for a stuck command. Whatever survives + // this is still killed when the job is closed. + killer.WaitForExit(1500); + } + } + + AppLog.Info("已结束命令进程树(" + reason + "):PID " + processId); } catch (Exception ex) { - AppLog.Warn("结束超时命令失败:" + ex.GetType().Name); + AppLog.Warn("结束命令进程树失败(PID " + processId + "):" + ex.GetType().Name, ex); + try + { + process.Kill(); + } + catch (Exception inner) + { + AppLog.Debug("回退结束进程也失败:" + inner.GetType().Name); + } } } + /// Ends every command that is still running. Called on exit, before the job is closed. + public int KillRunningCommands() + { + List processes; + lock (_sync) + { + processes = new List(_running.Values); + } + + int killed = 0; + foreach (Process process in processes) + { + KillProcessTree(process, "程序退出"); + killed++; + } + + if (killed > 0) + { + AppLog.Info("退出时结束了 " + killed + " 个仍在运行的命令进程树。"); + } + + return killed; + } + private static string ResolveWorkingDirectory(string configured) { if (!string.IsNullOrWhiteSpace(configured) && Directory.Exists(configured)) @@ -332,6 +432,11 @@ namespace pacs_win_uia.Services _disposed = true; StopContinuous(); + // End what is still running now (so a hung command cannot delay the exit), then close the + // job: anything the commands launched themselves — including processes started by a + // command that has already returned — dies with it. + KillRunningCommands(); + _job.Dispose(); } } } diff --git a/src/pacs_win_uia/Services/ControlLocatorBuilder.cs b/src/pacs_win_uia/Services/ControlLocatorBuilder.cs index 393b1bb..4c461da 100644 --- a/src/pacs_win_uia/Services/ControlLocatorBuilder.cs +++ b/src/pacs_win_uia/Services/ControlLocatorBuilder.cs @@ -1,8 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; -using System.Windows.Automation; -using pacs_win_uia.Diagnostics; using pacs_win_uia.Interop; using pacs_win_uia.Models; @@ -25,7 +22,7 @@ namespace pacs_win_uia.Services public List Win32Path { get; set; } - /// Human-readable path (display only). + /// Authoritative absolute XPath for every source. public string DisplayPath { get; set; } public string RuntimeId { get; set; } @@ -36,6 +33,9 @@ namespace pacs_win_uia.Services public bool IsComplete { get; set; } + /// Legacy compatibility flag; new paths always include the actual window root. + public bool UiaPathFromInnerWindow { get; set; } + public string Note { get; set; } } @@ -46,8 +46,6 @@ namespace pacs_win_uia.Services /// public sealed class ControlLocatorBuilder { - private const int MaxSiblingsToScan = 400; - private readonly NativeWindowService _windowService; public ControlLocatorBuilder() @@ -71,7 +69,6 @@ namespace pacs_win_uia.Services return; } - result.ProcessName = window.ProcessName; NativeWindowInfo topLevel = window; IntPtr root = NativeMethods.GetAncestor(window.Handle, NativeMethods.GA_ROOT); if (root != IntPtr.Zero && root != window.Handle) @@ -85,10 +82,7 @@ namespace pacs_win_uia.Services result.WindowClass = topLevel.ClassName; result.WindowTitleKeyword = ShortenTitle(topLevel.Title); - if (string.IsNullOrEmpty(result.ProcessName)) - { - result.ProcessName = topLevel.ProcessName; - } + result.ProcessName = topLevel.ProcessName; } /// @@ -144,300 +138,218 @@ namespace pacs_win_uia.Services return text.Length == 0 ? null : text.ToString(); } + /// Captures the same canonical RawView window tree used by resolution. public ControlLocatorBuildResult BuildFromUia(UiaElementInfo element, NativeWindowInfo window) + { + var failure = new ControlLocatorBuildResult { Source = ControlSourcePreference.Uia, ValueKey = "Name" }; + ApplyWindowFields(failure, window); + if (element == null || element.Element == null || window == null) + { + failure.Note = "没有可用的 UIA 元素或所属窗口。"; + return failure; + } + try + { + IntPtr handle = NativeMethods.GetAncestor(window.Handle, NativeMethods.GA_ROOT); + if (handle == IntPtr.Zero) handle = window.Handle; + ControlTreeResult tree = new ControlTreeService().Read(handle, null, ControlTreeSource.Uia, + new ControlTreeOptions(), System.Threading.CancellationToken.None); + if (tree.Root == null || !tree.Root.ChildrenComplete) + { + failure.Note = "无法从完整窗口树生成路径:" + (tree.Root == null ? tree.Note : tree.Root.ChildrenError); + return failure; + } + element.EnsureRuntimeId(); + ControlTreeNode target = null; + var pending = new Stack(); + pending.Push(tree.Root); + while (pending.Count > 0) + { + ControlTreeNode node = pending.Pop(); + if (node.Uia != null && + (!string.IsNullOrEmpty(element.RuntimeId) && string.Equals(node.Uia.RuntimeId, element.RuntimeId, StringComparison.Ordinal) || + (string.IsNullOrEmpty(element.RuntimeId) || string.IsNullOrEmpty(node.Uia.RuntimeId)) && + ControlLocatorService.SameElement(node.Uia.Element, element.Element))) + { + if (target != null) { failure.Note = "快照中存在多个相同 UIA 身份,无法唯一保存。"; return failure; } + target = node; + } + foreach (ControlTreeNode child in node.Children) pending.Push(child); + } + if (target == null) { failure.Note = "拾取元素不在窗口的 canonical RawView 树中;未虚构或跳过层级。"; return failure; } + element.EnsureRuntimeId(); + target.Uia.RuntimeId = element.RuntimeId; + NativeWindowInfo top = handle == window.Handle ? window : _windowService.Capture(handle); + return BuildFromTree(tree.Root, target, top ?? window); + } + catch (Exception ex) + { + failure.Note = "读取 canonical UIA 树失败:" + ex.Message; + return failure; + } + } + + /// + /// Pure snapshot builder: no UIA, HWND, runtime-id or other cross-process reads. + /// window should be the already-captured top-level window. The root itself is saveable. + /// DisplayPath is authoritative; legacy structured fields are left empty. + /// + public ControlLocatorBuildResult BuildFromTree(ControlTreeNode root, ControlTreeNode node, NativeWindowInfo window) { var result = new ControlLocatorBuildResult { - Source = ControlSourcePreference.Uia, - UiaPath = new List(), - ValueKey = "Name" + Source = node == null ? ControlSourcePreference.Auto : Preference(node.Source), + ProcessName = window == null ? null : window.ProcessName, + WindowClass = window == null ? null : window.ClassName, + WindowTitleKeyword = window == null ? null : ShortenTitle(window.Title) }; - ApplyWindowFields(result, window); - if (element == null || element.Element == null) + if (root == null || node == null) { - result.Note = "没有可用的 UIA 元素。"; + result.Note = "没有可用的控件树节点。"; return result; } - - element.EnsureRuntimeId(); - result.RuntimeId = element.RuntimeId; - - IList segments; - string note; - // Record the path relative to the ROOT window: resolution starts at FromHandle(root HWND), - // so a path recorded relative to a nested window element (UWP CoreWindow, browser renderer) - // would never match. - IntPtr rootHandle = window == null - ? IntPtr.Zero - : NativeMethods.GetAncestor(window.Handle, NativeMethods.GA_ROOT); - bool complete = TryBuildUiaPath(element.Element, rootHandle, out segments, out note); - foreach (ControlLocatorSegment segment in segments) + var chain = new List(); + if (!BuildNodeChain(root, node, chain)) { result.Note = "节点不属于指定窗口树。"; return result; } + switch (node.Source) { - result.UiaPath.Add(segment); + case ControlTreeSource.Msaa: + if (node.Msaa == null) { result.Note = "节点缺少 MSAA 数据。"; return result; } + result.ValueKey = string.IsNullOrEmpty(node.Msaa.Name) ? "accValue" : "accName"; + result.Value = result.ValueKey == "accValue" ? node.Msaa.Value : node.Msaa.Name; + break; + case ControlTreeSource.Win32: + if (node.Window == null) { result.Note = "节点缺少 Win32 数据。"; return result; } + result.ValueKey = "窗口标题"; + result.Value = node.Window.Title; + break; + default: + if (node.Uia == null) { result.Note = "节点缺少 UIA 数据。"; return result; } + result.ValueKey = "Name"; + result.RuntimeId = node.Uia.RuntimeId; + result.Value = node.Uia.Name; + break; } - - result.ValueKey = "Name"; - result.Value = element.Name; - result.DisplayPath = ControlLocatorFormat.DescribeUiaPath(result.UiaPath); - result.IsComplete = complete && result.UiaPath.Count > 0; - if (result.UiaPath.Count == 0) - { - note = "拾取到的就是顶层窗口本身,没有可保存的下级路径;请在该窗口内部选取具体控件。"; - } - - result.Note = note; + ControlPath.PreparePaths(root); + result.DisplayPath = ControlPath.Build(root, node); + string error; + ControlTreeNode selected = ControlPath.SelectUnique(root, result.DisplayPath, out error); + string snapshotError = ControlPath.SnapshotError(root); + result.IsComplete = snapshotError == null && ReferenceEquals(node, selected); + result.Note = snapshotError ?? error; + if (result.IsComplete) result.Note = DescribeStability(chain); return result; } + private static ControlSourcePreference Preference(ControlTreeSource source) + { + switch (source) + { + case ControlTreeSource.Msaa: return ControlSourcePreference.Msaa; + case ControlTreeSource.Win32: return ControlSourcePreference.Win32; + default: return ControlSourcePreference.Uia; + } + } + + private static string DescribeStability(IList chain) + { + int withoutId = 0; + int indexed = 0; + int classes = 0; + for (int i = 1; i < chain.Count; i++) + { + ControlTreeNode node = chain[i]; + bool hasId = node.Source == ControlTreeSource.Uia && node.Uia != null && !string.IsNullOrEmpty(node.Uia.AutomationId); + if (!hasId) + { + withoutId++; + if (node.Source == ControlTreeSource.Uia && node.Uia != null && !string.IsNullOrEmpty(node.Uia.ClassName) || + node.Source == ControlTreeSource.Win32 && node.Window != null && !string.IsNullOrEmpty(node.Window.ClassName)) classes++; + } + string path = node.CanonicalPath; + int bracket = path.LastIndexOf('['); + int ordinal; + if (bracket >= 0 && int.TryParse(path.Substring(bracket + 1, path.Length - bracket - 2), out ordinal)) indexed++; + } + string note = "路径仅保证当前快照唯一,不保证跨版本层级结构稳定;自动路径不使用 Name。"; + if (withoutId > 0) note += " 有 " + withoutId + " 个路径段没有稳定 AutomationId。"; + if (classes > 0) note += " 其中 " + classes + " 段使用类型+ClassName 尽力定位;类名可能动态变化,并非稳定标识。"; + if (indexed > 0) note += " 有 " + indexed + " 段依赖同类型/谓词匹配后的序号;控件增删或重排可能导致定位变化。"; + return note; + } + public ControlLocatorBuildResult BuildFromMsaa(MsaaNodeInfo node, NativeWindowInfo window) { - var result = new ControlLocatorBuildResult + return CaptureAndBuild(ControlTreeSource.Msaa, window, delegate(ControlTreeNode candidate) { - Source = ControlSourcePreference.Msaa, - ValueKey = string.IsNullOrEmpty(node == null ? null : node.Name) ? "accValue" : "accName" - }; - ApplyWindowFields(result, window); - if (node == null) - { - result.Note = "没有可用的 MSAA 节点。"; - return result; - } - - result.MsaaPathKey = ControlLocatorFormat.StripRoot(node.PathKey); - result.Value = string.Equals(result.ValueKey, "accName", StringComparison.Ordinal) ? node.Name : node.Value; - result.DisplayPath = result.MsaaPathKey; - result.IsComplete = !string.IsNullOrEmpty(result.MsaaPathKey); - result.Note = result.IsComplete ? null : "该 MSAA 节点就是窗口本身,没有可保存的下级路径。"; - return result; + return node != null && !string.IsNullOrEmpty(node.PathKey) && candidate.Msaa != null && + string.Equals(candidate.Msaa.PathKey, node.PathKey, StringComparison.Ordinal); + }); } public ControlLocatorBuildResult BuildFromWin32(NativeWindowInfo target, NativeWindowInfo window) { - var result = new ControlLocatorBuildResult + return CaptureAndBuild(ControlTreeSource.Win32, window ?? target, delegate(ControlTreeNode candidate) { - Source = ControlSourcePreference.Win32, - Win32Path = new List(), - ValueKey = "窗口标题" - }; - ApplyWindowFields(result, window); - if (target == null) - { - result.Note = "没有可用的 Win32 窗口。"; - return result; - } - - IntPtr rootHandle = NativeMethods.GetAncestor(target.Handle, NativeMethods.GA_ROOT); - IList segments = BuildWin32Path(rootHandle, target.Handle); - foreach (Win32LocatorSegment segment in segments) - { - result.Win32Path.Add(segment); - } - - result.Value = target.Title; - result.DisplayPath = ControlLocatorFormat.DescribeWin32Path(result.Win32Path); - result.IsComplete = result.Win32Path.Count > 0; - result.Note = result.IsComplete - ? null - : "选中的就是顶层窗口,没有可保存的下级窗口路径;请拾取窗口内部的子窗口。"; - return result; + return target != null && candidate.Window != null && candidate.Window.Handle == target.Handle; + }); } - /// - /// Segments from the top-level window down to the element (the window itself is not a segment, - /// because resolution starts *at* the window). - /// - private static bool TryBuildUiaPath( - AutomationElement element, - IntPtr rootHandle, - out IList segments, - out string note) - { - var collected = new List(); - segments = collected; - note = null; - AutomationElement current = element; - for (int depth = 0; depth < 32 && current != null; depth++) - { - AutomationElement parent; - try - { - parent = TreeWalker.ControlViewWalker.GetParent(current); - } - catch (Exception ex) - { - note = "向上查找父元素失败:" + ex.GetType().Name + ": " + ex.Message; - return false; - } - - if (parent == null) - { - note = "没有找到顶层窗口(元素已脱离树)。"; - return false; - } - - AutomationElement.AutomationElementInformation parentInfo = parent.Current; - bool isRoot = rootHandle != IntPtr.Zero - ? new IntPtr(parentInfo.NativeWindowHandle) == rootHandle - : parentInfo.NativeWindowHandle != 0 && parentInfo.ControlType == ControlType.Window; - if (isRoot) - { - // `current` is a direct child of the root window, and the resolver starts AT the - // root — so this element is a path step. Dropping it shifted every saved path one - // level down and made resolution fail from the window. - collected.Add(BuildSegment(current, parent)); - break; - } - - if (parentInfo.NativeWindowHandle != 0 && parentInfo.ControlType == ControlType.Window && - rootHandle != IntPtr.Zero) - { - AppLog.Warn("构建 UIA 路径:经过了内层窗口元素 0x" - + parentInfo.NativeWindowHandle.ToString("X") + "(不是根窗口),路径仍会包含它。"); - } - - collected.Add(BuildSegment(current, parent)); - current = parent; - } - - collected.Reverse(); - return true; - } - - private static ControlLocatorSegment BuildSegment(AutomationElement element, AutomationElement parent) - { - AutomationElement.AutomationElementInformation info = element.Current; - var segment = new ControlLocatorSegment - { - ControlType = info.ControlType == null ? null : info.ControlType.ProgrammaticName, - Name = info.Name, - AutomationId = info.AutomationId, - Index = -1 - }; - segment.Index = SameTypeOrdinal(parent, element, segment.ControlType); - return segment; - } - - private static int SameTypeOrdinal(AutomationElement parent, AutomationElement target, string controlType) + private ControlLocatorBuildResult CaptureAndBuild(ControlTreeSource source, NativeWindowInfo window, Predicate matches) { + var failure = new ControlLocatorBuildResult { Source = Preference(source) }; + ApplyWindowFields(failure, window); + if (window == null) { failure.Note = "没有可用的所属窗口。"; return failure; } try { - AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(parent); - int ordinal = 0; - int scanned = 0; - while (child != null && scanned < MaxSiblingsToScan) + IntPtr handle = NativeMethods.GetAncestor(window.Handle, NativeMethods.GA_ROOT); + if (handle == IntPtr.Zero) handle = window.Handle; + ControlTreeResult tree = new ControlTreeService().Read(handle, null, source, + new ControlTreeOptions(), System.Threading.CancellationToken.None); + if (tree.Root == null) { failure.Note = "读取窗口树失败:" + tree.Note; return failure; } + ControlTreeNode target = null; + var pending = new Stack(); + pending.Push(tree.Root); + while (pending.Count > 0) { - scanned++; - bool sameType = string.Equals( - child.Current.ControlType == null ? null : child.Current.ControlType.ProgrammaticName, - controlType, - StringComparison.Ordinal); - if (sameType) + ControlTreeNode candidate = pending.Pop(); + if (matches(candidate)) { - if (child == target) - { - return ordinal; - } - - ordinal++; + if (target != null) { failure.Note = "快照中拾取身份不唯一,不能保存。"; return failure; } + target = candidate; } - - child = TreeWalker.ControlViewWalker.GetNextSibling(child); + foreach (ControlTreeNode child in candidate.Children) pending.Push(child); } + if (target == null) { failure.Note = "拾取节点不在所属窗口快照中,未生成替代路径。"; return failure; } + NativeWindowInfo top = handle == window.Handle ? window : _windowService.Capture(handle); + return BuildFromTree(tree.Root, target, top ?? window); } - catch (Exception ex) - { - AppLog.Warn("构建 UIA 路径时统计同级序号失败:" + ex.GetType().Name + ": " + ex.Message); - } - - return -1; + catch (Exception ex) { failure.Note = "读取 " + source + " 窗口树失败:" + ex.Message; return failure; } } - /// Win32 path: each step is the class name plus its ordinal among same-class siblings. - public static IList BuildWin32Path(IntPtr rootHandle, IntPtr targetHandle) + /// Shared in-memory absolute XPath, including the window root. + public static string DescribePathFromTree(ControlTreeNode root, ControlTreeNode node) { - var segments = new List(); - if (rootHandle == IntPtr.Zero || targetHandle == IntPtr.Zero || rootHandle == targetHandle) - { - return segments; - } - - var chain = new List(); - IntPtr current = targetHandle; - for (int depth = 0; depth < 32 && current != IntPtr.Zero && current != rootHandle; depth++) - { - chain.Add(current); - current = NativeMethods.GetAncestor(current, NativeMethods.GA_PARENT); - } - - if (current != rootHandle) - { - return segments; - } - - chain.Reverse(); - foreach (IntPtr handle in chain) - { - IntPtr parent = NativeMethods.GetAncestor(handle, NativeMethods.GA_PARENT); - segments.Add(new Win32LocatorSegment - { - ClassName = ReadClassName(handle), - Index = SameClassOrdinal(parent, handle) - }); - } - - return segments; + return ControlPath.Build(root, node); } - private static int SameClassOrdinal(IntPtr parent, IntPtr target) + private static bool BuildNodeChain(ControlTreeNode root, ControlTreeNode target, IList chain) { - string targetClass = ReadClassName(target); - int ordinal = 0; - var children = new List(); - NativeMethods.EnumChildWindows( - parent, - delegate(IntPtr hWnd, IntPtr lParam) - { - IntPtr childParent = NativeMethods.GetAncestor(hWnd, NativeMethods.GA_PARENT); - if (childParent == parent) - { - children.Add(hWnd); - } + chain.Add(root); + if (ReferenceEquals(root, target)) + { + return true; + } + foreach (ControlTreeNode child in root.Children) + { + if (BuildNodeChain(child, target, chain)) + { return true; - }, - IntPtr.Zero); - - foreach (IntPtr child in children) - { - if (!string.Equals(ReadClassName(child), targetClass, StringComparison.Ordinal)) - { - continue; } - - if (child == target) - { - return ordinal; - } - - ordinal++; } - return 0; - } - - private static string ReadClassName(IntPtr handle) - { - try - { - var builder = new StringBuilder(256); - NativeMethods.GetClassName(handle, builder, builder.Capacity); - return builder.ToString(); - } - catch (Exception ex) - { - AppLog.Warn("读取窗口类名失败:" + ex.GetType().Name); - return string.Empty; - } + chain.RemoveAt(chain.Count - 1); + return false; } /// Titles change (file names, patient counts); a prefix is a stabler keyword. diff --git a/src/pacs_win_uia/Services/ControlLocatorService.cs b/src/pacs_win_uia/Services/ControlLocatorService.cs index 231ce42..b2ea425 100644 --- a/src/pacs_win_uia/Services/ControlLocatorService.cs +++ b/src/pacs_win_uia/Services/ControlLocatorService.cs @@ -1,10 +1,6 @@ using System; using System.Collections.Generic; -using System.Runtime.InteropServices; using System.Windows.Automation; -using Accessibility; -using pacs_win_uia.Diagnostics; -using pacs_win_uia.Interop; using pacs_win_uia.Models; namespace pacs_win_uia.Services @@ -22,9 +18,7 @@ namespace pacs_win_uia.Services public IntPtr WindowHandle { get; set; } /// - /// True when the control was found through a tolerant path (a wide window match, an inner - /// content window, or skipped leading path segments). The position may then be off, so the UI - /// says so instead of silently drawing a frame in the wrong place. + /// True when the window was found through a wide match. Path segments are never skipped. /// public bool UsedFallback { get; set; } @@ -33,13 +27,10 @@ namespace pacs_win_uia.Services /// /// Re-resolves a saved control without any UI. Nothing here depends on a window existing: a saved - /// control is located through 进程名 + 窗口类名 + 标题关键词, then walked down its source-specific - /// path (UIA segments / MSAA child ids / Win32 class+ordinal). + /// control is located through 进程名 + 窗口类名 + 标题关键词, then selected with XPath over a snapshot of the requested source. /// public sealed class ControlLocatorService { - private const int MaxSiblingsToScan = 400; - private readonly NativeWindowService _windowService; private readonly UiAutomationService _uiAutomationService; private readonly MsaaService _msaaService; @@ -77,6 +68,11 @@ namespace pacs_win_uia.Services return IntPtr.Zero; } + error = ControlPath.ValidateSyntax(definition.ControlPath); + if (error != null) return IntPtr.Zero; + steps = steps ?? new List(); + _lastWindowMatchLevel = 0; + if (string.IsNullOrEmpty(definition.ProcessName) && string.IsNullOrEmpty(definition.WindowClass) && string.IsNullOrEmpty(definition.WindowTitleKeyword)) { @@ -110,6 +106,12 @@ namespace pacs_win_uia.Services continue; } + if (candidates.Count > 1) + { + error = "窗口定位匹配到 " + candidates.Count + " 个候选(" + DescribeMatchLevel(level) + + "),要求唯一;请补充窗口标题、类名或进程信息。"; + return IntPtr.Zero; + } best = candidates[0].Handle; bestWindow = candidates[0]; bestLevel = level; @@ -177,7 +179,9 @@ namespace pacs_win_uia.Services // of class/title or refuse. if (!hasProcess) { - return sameClass || sameTitle; + if (!string.IsNullOrEmpty(definition.WindowClass) && !sameClass) return false; + if (!string.IsNullOrEmpty(definition.WindowTitleKeyword) && !sameTitle) return false; + return !string.IsNullOrEmpty(definition.WindowClass) || !string.IsNullOrEmpty(definition.WindowTitleKeyword); } return sameProcess; @@ -201,737 +205,112 @@ namespace pacs_win_uia.Services // ------------------------------------------------------------------ control resolution - /// Resolves the control with the preferred source, falling back to the other two. + /// XPath is authoritative. Explicit sources never fall back to a different tree. public ControlResolution Resolve(ControlMonitorDefinition definition, IntPtr windowHandle, IList steps) { - var order = SourceOrder(definition.Source); - string preferredError = null; - foreach (ControlTreeSource source in order) + if (definition == null) return new ControlResolution { Error = "定义为空。", WindowHandle = windowHandle }; + string syntaxError = ControlPath.ValidateSyntax(definition.ControlPath); + if (syntaxError != null) return new ControlResolution { Error = syntaxError, WindowHandle = windowHandle }; + steps = steps ?? new List(); + ControlTreeSource? source; + switch (definition.Source) { - ControlResolution resolution = TryResolveBySource(definition, windowHandle, source, steps); - if (resolution.Found && _lastWindowMatchLevel > 0 && _lastWindowMatchLevel <= 2) - { - // Matched by title or process alone: the located control may not be the saved one. - resolution.UsedFallback = true; - steps.Add("窗口是按较宽的规则匹配上的(级别 " + _lastWindowMatchLevel + "),定位结果需要人工核对。"); - } - - if (resolution.Found) - { - // The preferred source may legitimately resolve to the window itself (empty path). - // A *fallback* doing that only proves the window exists, not that the requested - // control was found — reporting success there would be misleading. - if (preferredError == null || HasSavedPath(definition, source)) - { - if (preferredError != null) - { - steps.Add(source + " 回退定位成功(该来源保存了完整路径)。"); - } - - return resolution; - } - - steps.Add(source + " 回退只定位到顶层窗口本身(该来源没有保存下级路径),不算命中。"); - if (preferredError == null) - { - preferredError = resolution.Error; - } - - continue; - } - - // The preferred source's reason is the meaningful one; the fallbacks mostly report - // "this source has no saved path". - if (preferredError == null) - { - preferredError = resolution.Error; - } - - if (order.Count > 1) - { - steps.Add(source + " 定位失败:" + (resolution.Error ?? "未知原因")); - } + case ControlSourcePreference.Uia: source = ControlTreeSource.Uia; break; + case ControlSourcePreference.Msaa: source = ControlTreeSource.Msaa; break; + case ControlSourcePreference.Win32: source = ControlTreeSource.Win32; break; + case ControlSourcePreference.Auto: source = null; break; + default: return new ControlResolution { Error = "未知控件来源。", WindowHandle = windowHandle }; } - - return new ControlResolution - { - Found = false, - WindowHandle = windowHandle, - Error = preferredError ?? "该控件在所有来源下都没有定位到。" - }; - } - - /// True when the definition actually saved a path for that source. - private static bool HasSavedPath(ControlMonitorDefinition definition, ControlTreeSource source) - { - switch (source) - { - case ControlTreeSource.Msaa: - return !string.IsNullOrEmpty(definition.MsaaPathKey); - case ControlTreeSource.Win32: - return definition.Win32Path != null && definition.Win32Path.Count > 0; - default: - return definition.UiaPath != null && definition.UiaPath.Count > 0; - } - } - - private static List SourceOrder(ControlSourcePreference preference) - { - var order = new List(); - switch (preference) - { - case ControlSourcePreference.Uia: - order.Add(ControlTreeSource.Uia); - break; - case ControlSourcePreference.Msaa: - order.Add(ControlTreeSource.Msaa); - break; - case ControlSourcePreference.Win32: - order.Add(ControlTreeSource.Win32); - break; - default: - order.Add(ControlTreeSource.Uia); - order.Add(ControlTreeSource.Msaa); - order.Add(ControlTreeSource.Win32); - return order; - } - - // Preferred source first, then the fallbacks, so a config keeps working when only one - // source is unavailable. - foreach (ControlTreeSource candidate in new[] - { - ControlTreeSource.Uia, ControlTreeSource.Msaa, ControlTreeSource.Win32 - }) - { - if (candidate != order[0]) - { - order.Add(candidate); - } - } - - return order; - } - - private ControlResolution TryResolveBySource( - ControlMonitorDefinition definition, - IntPtr windowHandle, - ControlTreeSource source, - IList steps) - { - switch (source) - { - case ControlTreeSource.Msaa: - return ResolveMsaa(definition, windowHandle, steps); - case ControlTreeSource.Win32: - return ResolveWin32(definition, windowHandle, steps); - default: - return ResolveUia(definition, windowHandle, steps); - } - } - - private ControlResolution ResolveUia(ControlMonitorDefinition definition, IntPtr windowHandle, IList steps) - { - if (definition.UiaPath == null || definition.UiaPath.Count == 0) - { - return ResolveWindowItselfUia(windowHandle, steps); - } - - AutomationElement root; try { - root = AutomationElement.FromHandle(windowHandle); + // Auto chooses an available snapshot before XPath evaluation; a failed XPath never + // retries another source where the same structural path might mean another control. + var trees = new ControlTreeService(_uiAutomationService, new MsaaTreeReader(_msaaService), _win32TreeReader); + ControlTreeResult tree = trees.Read(windowHandle, null, source, + new ControlTreeOptions(), System.Threading.CancellationToken.None); + ControlResolution result = ResolveFromTree(definition, tree.Root, windowHandle); + if (result.Found) + { + steps.Add(result.ResolvedSource + " XPath 唯一命中:" + definition.ControlPath); + result.UsedFallback = _lastWindowMatchLevel > 0 && _lastWindowMatchLevel <= 2; + if (result.UsedFallback) steps.Add("窗口按较宽规则匹配,定位结果需要人工核对。"); + } + return result; } catch (Exception ex) { - return new ControlResolution { Error = "无法从 HWND 取得 UIA 根元素:" + ex.Message }; + return new ControlResolution { WindowHandle = windowHandle, Error = "读取控件快照失败:" + ex.Message }; } - - if (root == null) - { - return new ControlResolution { Error = "AutomationElement.FromHandle 返回空。" }; - } - - // First try the saved path starting at the window itself. - string reason; - AutomationElement match = WalkPath(root, definition.UiaPath, out reason); - if (match != null) - { - UiaElementInfo direct = _uiAutomationService.Inspect(match); - steps.Add("UIA 路径 " + definition.UiaPath.Count + " 段全部匹配(从顶层窗口开始),命中 " + direct); - return new ControlResolution - { - Found = true, - ResolvedSource = ControlTreeSource.Uia, - WindowHandle = windowHandle, - Node = new ControlTreeNode { Source = ControlTreeSource.Uia, Uia = direct } - }; - } - - string firstFailure = reason; - - // Some hosts (UWP ApplicationFrameWindow, browser shells) own an inner window element and - // the tree was read from that element, so a saved path can be relative to it. - foreach (AutomationElement start in CollectNestedWindowStarts(root, windowHandle)) - { - string nestedReason; - AutomationElement nestedMatch = WalkPath(start, definition.UiaPath, out nestedReason); - if (nestedMatch == null) - { - continue; - } - - UiaElementInfo info = _uiAutomationService.Inspect(nestedMatch); - steps.Add("从顶层窗口开始匹配失败(" + firstFailure + "),改从内层窗口元素 " - + NativeWindowInfo.FormatHandle((IntPtr)SafeNativeHandle(start)) + " 开始匹配成功。"); - return new ControlResolution - { - Found = true, - UsedFallback = true, - ResolvedSource = ControlTreeSource.Uia, - WindowHandle = windowHandle, - Node = new ControlTreeNode { Source = ControlTreeSource.Uia, Uia = info } - }; - } - - // Last resort: the control tree gained or lost a level (XAML/Chromium trees change between - // versions and page states). Drop up to two leading segments and accept the result only - // when exactly ONE element in the window matches the remaining path. - for (int skip = 1; skip <= MaxSkippedPrefixSegments && skip < definition.UiaPath.Count; skip++) - { - var remaining = new List(); - for (int index = skip; index < definition.UiaPath.Count; index++) - { - remaining.Add(definition.UiaPath[index]); - } - - List candidates = FindSegments(root, remaining[0]); - if (candidates.Count == 0) - { - continue; - } - - var matches = new List(); - foreach (AutomationElement candidate in candidates) - { - var tail = new List(); - for (int index = 1; index < remaining.Count; index++) - { - tail.Add(remaining[index]); - } - - string tailReason; - AutomationElement tailMatch = tail.Count == 0 ? candidate : WalkPath(candidate, tail, out tailReason); - if (tailMatch != null && !matches.Contains(tailMatch)) - { - matches.Add(tailMatch); - } - } - - if (matches.Count != 1) - { - steps.Add(string.Format( - "跳过前 {0} 段后在窗口内找到 {1} 个候选(要求唯一才算命中),放弃该方案。", - skip, matches.Count)); - continue; - } - - UiaElementInfo flexible = _uiAutomationService.Inspect(matches[0]); - steps.Add(string.Format( - "完整路径未命中,但跳过前 {0} 段后在整个窗口内**唯一**匹配到 {1}。" - + "说明控件树层级与保存时不同(程序版本或页面状态变了),建议在界面里重新添加该控件。", - skip, flexible)); - return new ControlResolution - { - Found = true, - UsedFallback = true, - ResolvedSource = ControlTreeSource.Uia, - WindowHandle = windowHandle, - Node = new ControlTreeNode { Source = ControlTreeSource.Uia, Uia = flexible } - }; - } - - return new ControlResolution - { - Error = string.Format("UIA 路径第 1 段起点匹配失败:{0}", firstFailure) - }; - } - - /// Walks a saved UIA path from a start element; returns null with a reason on failure. - private static AutomationElement WalkPath( - AutomationElement start, - IList path, - out string failureReason) - { - failureReason = null; - AutomationElement current = start; - for (int index = 0; index < path.Count; index++) - { - ControlLocatorSegment segment = path[index]; - AutomationElement next; - string reason; - if (!TryMatchChild(current, segment, out next, out reason)) - { - failureReason = string.Format("第 {0} 段({1})未匹配:{2}", index + 1, segment, reason); - return null; - } - - current = next; - } - - return current; - } - - private const int MaxSkippedPrefixSegments = 2; - private const int SegmentSearchDepth = 10; - private const int SegmentSearchNodes = 1500; - private const int MaxSegmentCandidates = 20; - - /// - /// Every element in the window's subtree matching one segment, by AutomationId first (exact) - /// and otherwise by ControlType + Name. Bounded; the ordinal is meaningless in a subtree-wide - /// search, so it is not used here. - /// - private static List FindSegments(AutomationElement root, ControlLocatorSegment segment) - { - var found = new List(); - if (segment == null || (string.IsNullOrEmpty(segment.AutomationId) && string.IsNullOrEmpty(segment.Name))) - { - return found; - } - - try - { - var queue = new Queue>(); - queue.Enqueue(new KeyValuePair(root, 0)); - int visited = 0; - while (queue.Count > 0 && visited < SegmentSearchNodes && found.Count < MaxSegmentCandidates) - { - KeyValuePair item = queue.Dequeue(); - visited++; - if (item.Value >= SegmentSearchDepth) - { - continue; - } - - AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(item.Key); - int scanned = 0; - while (child != null && scanned < MaxSiblingsToScan) - { - scanned++; - try - { - AutomationElement.AutomationElementInformation info = child.Current; - string controlType = info.ControlType == null ? null : info.ControlType.ProgrammaticName; - bool matches = !string.IsNullOrEmpty(segment.AutomationId) - ? string.Equals(info.AutomationId, segment.AutomationId, StringComparison.Ordinal) - : string.Equals(controlType, segment.ControlType, StringComparison.Ordinal) && - string.Equals(info.Name, segment.Name, StringComparison.Ordinal); - if (matches && found.Count < MaxSegmentCandidates) - { - found.Add(child); - } - } - catch (Exception) - { - // Skip an unreadable element; the search continues. - } - - queue.Enqueue(new KeyValuePair(child, item.Value + 1)); - child = TreeWalker.ControlViewWalker.GetNextSibling(child); - } - } - } - catch (Exception ex) - { - AppLog.Warn("在窗口内搜索定位段失败:" + ex.GetType().Name + ": " + ex.Message); - } - - return found; - } - - private const int NestedWindowScanDepth = 4; - private const int NestedWindowScanNodes = 200; - private const int MaxNestedWindowStarts = 4; - - /// - /// Nested window-typed elements with their own HWND, breadth-first and bounded. A UWP app's - /// CoreWindow and a browser's renderer window both qualify. - /// - private static IList CollectNestedWindowStarts(AutomationElement root, IntPtr rootHandle) - { - var starts = new List(); - try - { - var queue = new Queue>(); - queue.Enqueue(new KeyValuePair(root, 0)); - int visited = 0; - while (queue.Count > 0 && visited < NestedWindowScanNodes && starts.Count < MaxNestedWindowStarts) - { - KeyValuePair item = queue.Dequeue(); - visited++; - if (item.Value >= NestedWindowScanDepth) - { - continue; - } - - AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(item.Key); - int scanned = 0; - while (child != null && scanned < MaxSiblingsToScan) - { - scanned++; - try - { - AutomationElement.AutomationElementInformation info = child.Current; - if (info.ControlType == ControlType.Window && - info.NativeWindowHandle != 0 && - new IntPtr(info.NativeWindowHandle) != rootHandle && - starts.Count < MaxNestedWindowStarts) - { - starts.Add(child); - } - } - catch (Exception) - { - // A provider that refuses one child must not abort the scan. - } - - queue.Enqueue(new KeyValuePair(child, item.Value + 1)); - child = TreeWalker.ControlViewWalker.GetNextSibling(child); - } - } - } - catch (Exception ex) - { - AppLog.Warn("收集内层窗口元素失败:" + ex.GetType().Name + ": " + ex.Message); - } - - return starts; - } - - private static long SafeNativeHandle(AutomationElement element) - { - try - { - return element.Current.NativeWindowHandle; - } - catch (Exception) - { - return 0; - } - } - - /// AutomationId first, then type+name, then ordinal — the same order the builder records. - private static bool TryMatchChild(AutomationElement parent, ControlLocatorSegment segment, out AutomationElement match, out string reason) - { - match = null; - reason = null; - var sameType = new List(); - try - { - AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(parent); - int scanned = 0; - while (child != null && scanned < MaxSiblingsToScan) - { - scanned++; - AutomationElement.AutomationElementInformation info = child.Current; - string controlType = info.ControlType == null ? null : info.ControlType.ProgrammaticName; - bool sameControlType = string.Equals(controlType, segment.ControlType, StringComparison.Ordinal); - if (sameControlType) - { - sameType.Add(child); - } - - if (!string.IsNullOrEmpty(segment.AutomationId) && - string.Equals(info.AutomationId, segment.AutomationId, StringComparison.Ordinal)) - { - match = child; - return true; - } - - if (sameControlType && !string.IsNullOrEmpty(segment.Name) && - string.Equals(info.Name, segment.Name, StringComparison.Ordinal)) - { - match = child; - return true; - } - - child = TreeWalker.ControlViewWalker.GetNextSibling(child); - } - - if (scanned >= MaxSiblingsToScan) - { - reason = "同级子元素超过 " + MaxSiblingsToScan + " 个,扫描被截断"; - } - } - catch (Exception ex) - { - reason = "枚举子元素失败:" + ex.GetType().Name + ": " + ex.Message; - return false; - } - - if (segment.Index >= 0 && segment.Index < sameType.Count) - { - match = sameType[segment.Index]; - return true; - } - - reason = reason ?? string.Format("没有匹配的同级元素(同类元素 {0} 个,期望序号 {1})", sameType.Count, segment.Index); - return false; } /// - /// An empty path is not an error: it means "the top-level window itself", which is a valid - /// thing to monitor (its title, class, visibility...). + /// Pure snapshot resolver for ALL sources. Returns the exact selected node with its payload. + /// Old path text/structured fields are never executed, even if ControlPath is missing. /// - private ControlResolution ResolveWindowItselfUia(IntPtr windowHandle, IList steps) + public static ControlResolution ResolveFromTree(ControlMonitorDefinition definition, ControlTreeNode root, IntPtr windowHandle) { - try + var result = new ControlResolution { WindowHandle = windowHandle }; + if (definition == null) { result.Error = "定义为空。"; return result; } + result.Error = ControlPath.ValidateSyntax(definition.ControlPath); + if (result.Error != null) return result; + result.Error = ControlPath.SnapshotError(root); + if (result.Error != null) return result; + result.ResolvedSource = root.Source; + if (definition.Source != ControlSourcePreference.Auto && + !string.Equals(definition.Source.ToString(), root.Source.ToString(), StringComparison.Ordinal)) { - UiaElementInfo info = _uiAutomationService.FromHandle(windowHandle); - steps.Add("没有保存 UIA 下级路径,定位到顶层窗口本身。"); - return new ControlResolution - { - Found = true, - ResolvedSource = ControlTreeSource.Uia, - WindowHandle = windowHandle, - Node = new ControlTreeNode { Source = ControlTreeSource.Uia, Uia = info } - }; + result.Error = "指定来源 " + definition.Source + " 与快照来源 " + root.Source + " 不一致。"; + return result; } - catch (Exception ex) - { - return new ControlResolution { Error = "读取顶层窗口的 UIA 元素失败:" + ex.Message }; - } - } - - private ControlResolution ResolveWindowItselfMsaa(IntPtr windowHandle, IList steps) - { - object accessibleObject; string error; - if (!_msaaService.TryGetRoot(windowHandle, out accessibleObject, out error)) + ControlTreeNode node = ControlPath.SelectUnique(root, definition.ControlPath, out error); + if (node != null && (node.Source == ControlTreeSource.Uia && node.Uia == null || + node.Source == ControlTreeSource.Msaa && node.Msaa == null || + node.Source == ControlTreeSource.Win32 && node.Window == null)) { - return new ControlResolution { Error = "无法取得 MSAA 根对象:" + error }; - } - - var accessible = accessibleObject as IAccessible; - if (accessible == null) - { - return new ControlResolution { Error = "MSAA 根对象不是 IAccessible。" }; + error = "匹配节点缺少 " + node.Source + " 来源的数据。"; + node = null; } + result.Node = node; + result.Found = node != null; + result.Error = error; + if (node != null) result.ResolvedSource = node.Source; + return result; + } + /// + /// RuntimeId is authoritative. Different ids (including lengths) are NEVER rescued by + /// equal names/classes/handles. Without ids only reference identity proves equality. + /// + public static bool SameElement(AutomationElement left, AutomationElement right) + { + if (left == null || right == null) return false; + if (ReferenceEquals(left, right)) return true; try { - MsaaNodeInfo info = _msaaService.ReadSelf(accessible, MsaaNativeMethods.CHILDID_SELF, - "0x" + windowHandle.ToInt64().ToString("X")); - steps.Add("没有保存 MSAA 下级路径,定位到顶层窗口本身。"); - return new ControlResolution + int[] leftId = left.GetRuntimeId(); + int[] rightId = right.GetRuntimeId(); + bool leftHasId = leftId != null && leftId.Length > 0; + bool rightHasId = rightId != null && rightId.Length > 0; + if (leftHasId && rightHasId) { - Found = true, - ResolvedSource = ControlTreeSource.Msaa, - WindowHandle = windowHandle, - Node = new ControlTreeNode { Source = ControlTreeSource.Msaa, Msaa = info } - }; - } - finally - { - try - { - Marshal.ReleaseComObject(accessible); - } - catch (Exception) - { - // Best effort. + if (leftId.Length != rightId.Length) return false; + for (int i = 0; i < leftId.Length; i++) if (leftId[i] != rightId[i]) return false; + return true; } + + // If either side has no id, compare the stable snapshot properties. A provider + // that exposes no RuntimeId cannot be distinguished more precisely by this API. + AutomationElement.AutomationElementInformation a = left.Current; + AutomationElement.AutomationElementInformation b = right.Current; + return string.Equals(a.ControlType == null ? null : a.ControlType.ProgrammaticName, + b.ControlType == null ? null : b.ControlType.ProgrammaticName, StringComparison.Ordinal) && + string.Equals(a.AutomationId, b.AutomationId, StringComparison.Ordinal) && + string.Equals(a.Name, b.Name, StringComparison.Ordinal) && + a.NativeWindowHandle == b.NativeWindowHandle; } + catch (Exception) { return false; } } - private ControlResolution ResolveWindowItselfWin32(IntPtr windowHandle, IList steps) - { - ControlTreeNode root = _win32TreeReader.Read(windowHandle, new ControlTreeOptions(), System.Threading.CancellationToken.None); - if (root == null || root.Window == null) - { - return new ControlResolution { Error = "读取顶层窗口信息失败。" }; - } - - steps.Add("没有保存 Win32 下级路径,定位到顶层窗口本身。"); - return new ControlResolution - { - Found = true, - ResolvedSource = ControlTreeSource.Win32, - WindowHandle = windowHandle, - Node = root - }; - } - - private ControlResolution ResolveMsaa(ControlMonitorDefinition definition, IntPtr windowHandle, IList steps) - { - IList parts = ControlLocatorFormat.SplitMsaaPath(definition.MsaaPathKey); - if (parts.Count == 0) - { - return ResolveWindowItselfMsaa(windowHandle, steps); - } - - object accessibleObject; - string error; - if (!_msaaService.TryGetRoot(windowHandle, out accessibleObject, out error)) - { - return new ControlResolution { Error = "无法取得 MSAA 根对象:" + error }; - } - - var accessible = accessibleObject as IAccessible; - if (accessible == null) - { - return new ControlResolution { Error = "MSAA 根对象不是 IAccessible。" }; - } - - try - { - IAccessible current = accessible; - object currentChildId = MsaaNativeMethods.CHILDID_SELF; - List owned = new List(); - try - { - for (int index = 0; index < parts.Count; index++) - { - string part = parts[index]; - if (part.Length < 2) - { - return new ControlResolution { Error = "MSAA 路径第 " + (index + 1) + " 段格式不正确:" + part }; - } - - int ordinal; - if (!int.TryParse(part.Substring(1), out ordinal)) - { - return new ControlResolution { Error = "MSAA 路径第 " + (index + 1) + " 段不是数字:" + part }; - } - - if (part[0] == 'i') - { - // A simple child id: still read through the same parent object. - currentChildId = ordinal; - continue; - } - - bool complete; - string childError; - IList children = _msaaService.ReadChildren( - current, currentChildId, "walk", ordinal + 1, out complete, out childError); - if (ordinal >= children.Count) - { - return new ControlResolution - { - Error = string.Format("MSAA 路径第 {0} 段({1})越界:该层只有 {2} 个子元素({3})", - index + 1, part, children.Count, childError ?? "无错误信息") - }; - } - - MsaaChild child = children[ordinal]; - if (!child.IsObject || child.Accessible == null) - { - // A simple id in an object slot still resolves through the parent. - currentChildId = child.ChildId; - continue; - } - - owned.Add(child); - current = child.Accessible; - currentChildId = MsaaNativeMethods.CHILDID_SELF; - } - - MsaaNodeInfo node = _msaaService.ReadSelf(current, currentChildId, "0x" + windowHandle.ToInt64().ToString("X")); - steps.Add("MSAA 路径 " + parts.Count + " 段全部匹配,命中 " + node); - return new ControlResolution - { - Found = true, - ResolvedSource = ControlTreeSource.Msaa, - WindowHandle = windowHandle, - Node = new ControlTreeNode { Source = ControlTreeSource.Msaa, Msaa = node } - }; - } - finally - { - foreach (MsaaChild child in owned) - { - child.Release(); - } - } - } - finally - { - try - { - Marshal.ReleaseComObject(accessible); - } - catch (Exception) - { - // Best effort. - } - } - } - - private ControlResolution ResolveWin32(ControlMonitorDefinition definition, IntPtr windowHandle, IList steps) - { - if (definition.Win32Path == null || definition.Win32Path.Count == 0) - { - return ResolveWindowItselfWin32(windowHandle, steps); - } - - ControlTreeNode root = _win32TreeReader.Read(windowHandle, new ControlTreeOptions(), System.Threading.CancellationToken.None); - ControlTreeNode current = root; - for (int index = 0; index < definition.Win32Path.Count; index++) - { - Win32LocatorSegment segment = definition.Win32Path[index]; - ControlTreeNode next = MatchWindowChild(current, segment); - if (next == null) - { - return new ControlResolution - { - Error = string.Format("Win32 路径第 {0} 段({1})未匹配:该层没有对应类名与序号的子窗口(同级 {2} 个)", - index + 1, segment, current == null ? 0 : current.Children.Count) - }; - } - - current = next; - } - - steps.Add("Win32 路径 " + definition.Win32Path.Count + " 段全部匹配,命中 " + (current == null ? "(空)" : current.Describe())); - return new ControlResolution - { - Found = true, - ResolvedSource = ControlTreeSource.Win32, - WindowHandle = current != null && current.Window != null ? current.Window.Handle : windowHandle, - Node = current - }; - } - - private static ControlTreeNode MatchWindowChild(ControlTreeNode parent, Win32LocatorSegment segment) - { - if (parent == null) - { - return null; - } - - int ordinal = 0; - foreach (ControlTreeNode child in parent.Children) - { - if (child.Window == null) - { - continue; - } - - if (!string.Equals(child.Window.ClassName, segment.ClassName, StringComparison.Ordinal)) - { - continue; - } - - if (ordinal == segment.Index) - { - return child; - } - - ordinal++; - } - - return null; - } } } diff --git a/src/pacs_win_uia/Services/ControlMonitorStore.cs b/src/pacs_win_uia/Services/ControlMonitorStore.cs index f99cc0b..c8d8be6 100644 --- a/src/pacs_win_uia/Services/ControlMonitorStore.cs +++ b/src/pacs_win_uia/Services/ControlMonitorStore.cs @@ -100,7 +100,9 @@ namespace pacs_win_uia.Services throw new InvalidDataException("Unsupported control monitor document version; expected version 1."); } - IList errors = ControlMonitorRules.ValidateList(document.Items); + // Keep legacy/invalid path text intact for manual editing. Loading never migrates, + // evaluates, discards or saves a locator; execution and Save require valid XPath. + IList errors = ControlMonitorRules.ValidateList(document.Items, false); if (errors.Count > 0) { throw new InvalidDataException("控件监控定义文件内容无效:" + DescribeErrors(errors)); @@ -134,6 +136,19 @@ namespace pacs_win_uia.Services throw new InvalidDataException("控件监控定义无效:" + DescribeErrors(errors)); } + // Never overwrite an unreadable existing document after a caller caught Load's error. + // An empty UI list must also not silently erase old paths. Repair/re-pick the entries + // and explicitly save XPath, or archive/remove the old file outside this store. + IList existing = Load(); + if (items.Count == 0) + { + foreach (ControlMonitorDefinition definition in existing) + { + if (ControlPath.ValidateSyntax(definition.ControlPath) != null) + throw new InvalidDataException("原文件包含旧格式或无效路径,拒绝用空列表覆盖;请先修正路径或备份原文件。"); + } + } + byte[] data; using (var stream = new MemoryStream()) { @@ -216,52 +231,30 @@ namespace pacs_win_uia.Services { Id = definition.Id, ControlPath = definition.ControlPath, - PageFeatures = definition.PageFeatures, + // Generated page features duplicate the stable window locator. Keep only custom text. + PageFeatures = string.Equals(definition.PageFeatures, + ControlLocatorBuilder.FormatPageFeatures(new ControlLocatorBuildResult + { + ProcessName = definition.ProcessName, + WindowClass = definition.WindowClass, + WindowTitleKeyword = definition.WindowTitleKeyword + }), StringComparison.Ordinal) ? null : definition.PageFeatures, ContentKey = definition.ContentKey, - RuntimeId = definition.RuntimeId, + RuntimeId = null, Source = definition.Source, ProcessName = definition.ProcessName, WindowClass = definition.WindowClass, WindowTitleKeyword = definition.WindowTitleKeyword, - MsaaPathKey = definition.MsaaPathKey, + UiaPath = null, + MsaaPathKey = null, + Win32Path = null, + UiaPathFromInnerWindow = false, ValueKey = definition.ValueKey, - Value = definition.Value, Disabled = definition.Disabled, TimeoutSeconds = definition.TimeoutSeconds }; - if (definition.UiaPath != null) - { - foreach (ControlLocatorSegment segment in definition.UiaPath) - { - if (segment != null) - { - copy.UiaPath.Add(new ControlLocatorSegment - { - ControlType = segment.ControlType, - Name = segment.Name, - AutomationId = segment.AutomationId, - Index = segment.Index - }); - } - } - } - - if (definition.Win32Path != null) - { - foreach (Win32LocatorSegment segment in definition.Win32Path) - { - if (segment != null) - { - copy.Win32Path.Add(new Win32LocatorSegment - { - ClassName = segment.ClassName, - Index = segment.Index - }); - } - } - } - + // New saves have one locator only: ControlPath. Legacy fields are read-only history. return copy; } diff --git a/src/pacs_win_uia/Services/ControlPath.cs b/src/pacs_win_uia/Services/ControlPath.cs new file mode 100644 index 0000000..5ecb293 --- /dev/null +++ b/src/pacs_win_uia/Services/ControlPath.cs @@ -0,0 +1,246 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Xml; +using System.Xml.XPath; +using pacs_win_uia.Models; + +namespace pacs_win_uia.Services +{ + /// + /// XPath 1.0 over a snapshot. XML elements map to the ORIGINAL nodes, including source payloads. + /// The selected window is always /Window[1]; window identity is supplied separately. + /// + public static class ControlPath + { + /// Checks the supported expression prefix, not syntax or uniqueness. + public static bool IsXPath(string text) + { + text = (text ?? string.Empty).Trim(); + return text.StartsWith("/", StringComparison.Ordinal) || + text.StartsWith("./", StringComparison.Ordinal) || + text.StartsWith("(", StringComparison.Ordinal); + } + + /// + /// Returns null for supported node-set XPath syntax, otherwise a Chinese diagnostic. + /// Does not read providers or check matches. Select additionally checks actual node kinds. + /// Legacy display paths/source tags/structured locators are not accepted. + /// + public static string ValidateSyntax(string text) + { + if (string.IsNullOrWhiteSpace(text)) return "路径为空;请填写 XPath,例如 /Window[1]。"; + if (!IsXPath(text)) return "仅支持以 /、//、./ 或括号开头的 XPath 1.0 节点集表达式;旧路径格式已停用,请重新拾取控件。"; + try + { + XPathExpression expression = XPathExpression.Compile(text.Trim()); + if (expression.ReturnType != XPathResultType.NodeSet) + return "XPath 必须返回控件节点集,不能返回字符串、数字或布尔值。"; + // Attributes in predicates are valid; attributes selected as results are not. + // Check this even if evaluation against an empty tree would return no nodes. + int predicates = 0; + char quote = '\0'; + for (int i = 0; i < text.Length; i++) + { + char c = text[i]; + if (quote != '\0') { if (c == quote) quote = '\0'; continue; } + if (c == '\'' || c == '"') { quote = c; continue; } + if (c == '[') { predicates++; continue; } + if (c == ']') { predicates--; continue; } + if (predicates != 0) continue; + if (c == '@') return "XPath 必须选择控件元素,不能选择属性。"; + if (!char.IsLetter(c) && c != '_') continue; + int start = i; + while (i + 1 < text.Length && (char.IsLetterOrDigit(text[i + 1]) || text[i + 1] == '_' || text[i + 1] == '-')) i++; + string token = text.Substring(start, i - start + 1); + int next = i + 1; + while (next < text.Length && char.IsWhiteSpace(text[next])) next++; + if ((token == "attribute" || token == "namespace") && next + 1 < text.Length && text[next] == ':' && text[next + 1] == ':') + return "XPath 必须选择控件元素,不能选择属性或命名空间。"; + if ((token == "text" || token == "comment" || token == "processing-instruction") && next < text.Length && text[next] == '(') + return "XPath 必须选择控件元素,不能选择文本、注释或处理指令。"; + } + return null; + } + catch (XPathException ex) { return "XPath 无效:" + ex.Message; } + catch (ArgumentException ex) { return "XPath 无效:" + ex.Message; } + } + + /// Quotes an XPath 1.0 string, including values containing both kinds of quote. + public static string Quote(string value) + { + value = value ?? string.Empty; + if (value.IndexOf('\'') < 0) return "'" + value + "'"; + if (value.IndexOf('"') < 0) return "\"" + value + "\""; + return "concat('" + value.Replace("'", "',\"'\",'") + "')"; + } + + /// Linear sibling work plus output size. Re-run after modifying the snapshot. + public static void PreparePaths(ControlTreeNode root) + { + if (root == null) return; + root.CanonicalPath = "/Window[1]"; + root.CanonicalPathRoot = root; + var pending = new Stack(); + pending.Push(root); + while (pending.Count > 0) + { + ControlTreeNode parent = pending.Pop(); + var totals = new Dictionary(StringComparer.Ordinal); + var ordinals = new Dictionary(StringComparer.Ordinal); + foreach (ControlTreeNode child in parent.Children) + foreach (string key in IdentityKeys(child)) Increment(totals, key); + foreach (ControlTreeNode child in parent.Children) + { + string step = PreferredStep(child); + foreach (string key in IdentityKeys(child)) Increment(ordinals, key); + if (!HasIdentity(child) || totals[step] > 1) + step += "[" + ordinals[step].ToString(CultureInfo.InvariantCulture) + "]"; + child.CanonicalPath = parent.CanonicalPath + "/" + step; + child.CanonicalPathRoot = root; + pending.Push(child); + } + } + } + + public static string Build(ControlTreeNode root, ControlTreeNode node) + { + if (root == null || node == null) return null; + if (!ReferenceEquals(node.CanonicalPathRoot, root)) PreparePaths(root); + return ReferenceEquals(node.CanonicalPathRoot, root) ? node.CanonicalPath : null; + } + + /// All element matches in document order; errors and zero matches set error. + public static IList Select(ControlTreeNode root, string text, out string error) + { + error = ValidateSyntax(text); + var found = new List(); + if (error != null) return found; + if (root == null) { error = "控件树为空。"; return found; } + try + { + var document = new XmlDocument { XmlResolver = null }; + var mapping = new Dictionary(); + AppendXml(document, root, mapping); + XmlNodeList selected = document.SelectNodes(text.Trim()); + foreach (XmlNode xml in selected) + { + ControlTreeNode node; + if (!mapping.TryGetValue(xml, out node)) + { + error = "XPath 必须选择控件元素,不能选择属性、文本或文档节点。"; + return new List(); + } + found.Add(node); + } + if (found.Count == 0) error = "路径匹配到 0 个控件。"; + } + catch (XPathException ex) { error = "XPath 无效:" + ex.Message; } + catch (ArgumentException ex) { error = "XPath/XML 快照无效:" + ex.Message; } + return found; + } + + public static ControlTreeNode SelectUnique(ControlTreeNode root, string text, out string error) + { + IList nodes = Select(root, text, out error); + if (error != null) return null; + if (nodes.Count == 1) return nodes[0]; + error = "路径匹配到 " + nodes.Count + " 个控件,定位要求唯一;请补充属性或序号。"; + return null; + } + + /// Readers do not all propagate incomplete descendants to the root. + internal static string SnapshotError(ControlTreeNode root) + { + if (root == null) return "控件树为空。"; + var pending = new Stack(); + pending.Push(root); + while (pending.Count > 0) + { + ControlTreeNode node = pending.Pop(); + if (node.Source != root.Source) return "控件树混合了不同来源,不能确认定位唯一性。"; + if (!node.ChildrenComplete) return "控件树不完整,不能确认定位唯一性:" + node.ChildrenError; + foreach (ControlTreeNode child in node.Children) pending.Push(child); + } + return null; + } + + private static string TypeName(ControlTreeNode node) + { + if (node.Source == ControlTreeSource.Win32) return "Window"; + if (node.Source == ControlTreeSource.Msaa) return "Accessible"; + string type = node.Uia == null ? null : node.Uia.ControlType; + return string.IsNullOrEmpty(type) ? "Control" : + type.StartsWith("ControlType.", StringComparison.Ordinal) ? type.Substring(12) : type; + } + + private static string Name(ControlTreeNode node) + { + switch (node.Source) + { + case ControlTreeSource.Msaa: return node.Msaa == null ? null : node.Msaa.Name; + case ControlTreeSource.Win32: return node.Window == null ? null : node.Window.Title; + default: return node.Uia == null ? null : node.Uia.Name; + } + } + + private static string AutomationId(ControlTreeNode node) + { + return node.Source == ControlTreeSource.Uia && node.Uia != null ? node.Uia.AutomationId : null; + } + + private static string ClassName(ControlTreeNode node) + { + if (node.Source == ControlTreeSource.Uia) return node.Uia == null ? null : node.Uia.ClassName; + return node.Source == ControlTreeSource.Win32 && node.Window != null ? node.Window.ClassName : null; + } + + private static bool HasIdentity(ControlTreeNode node) + { + return !string.IsNullOrEmpty(AutomationId(node)) || !string.IsNullOrEmpty(ClassName(node)); + } + + private static void Increment(IDictionary counts, string key) + { + int count; + counts.TryGetValue(key, out count); + counts[key] = count + 1; + } + + // A class predicate must also count siblings which prefer an AutomationId. Bare type + // indices likewise count ALL same-type siblings, including siblings with identities. + private static IEnumerable IdentityKeys(ControlTreeNode node) + { + string type = XmlConvert.EncodeLocalName(TypeName(node)); + yield return type; + if (!string.IsNullOrEmpty(ClassName(node))) yield return type + "[@ClassName=" + Quote(ClassName(node)) + "]"; + if (!string.IsNullOrEmpty(AutomationId(node))) yield return type + "[@AutomationId=" + Quote(AutomationId(node)) + "]"; + } + + private static string PreferredStep(ControlTreeNode node) + { + string step = XmlConvert.EncodeLocalName(TypeName(node)); + if (!string.IsNullOrEmpty(AutomationId(node))) return step + "[@AutomationId=" + Quote(AutomationId(node)) + "]"; + return string.IsNullOrEmpty(ClassName(node)) ? step : step + "[@ClassName=" + Quote(ClassName(node)) + "]"; + } + + private static void AppendXml(XmlNode parent, ControlTreeNode node, IDictionary mapping) + { + XmlDocument document = parent as XmlDocument ?? parent.OwnerDocument; + XmlElement xml = document.CreateElement(parent is XmlDocument ? "Window" : XmlConvert.EncodeLocalName(TypeName(node))); + xml.SetAttribute("Name", Name(node) ?? string.Empty); + xml.SetAttribute("AutomationId", AutomationId(node) ?? string.Empty); + xml.SetAttribute("ClassName", ClassName(node) ?? string.Empty); + xml.SetAttribute("ControlType", node.Source == ControlTreeSource.Uia && node.Uia != null ? node.Uia.ControlType ?? string.Empty : TypeName(node)); + xml.SetAttribute("Source", node.Source.ToString()); + if (node.Source == ControlTreeSource.Msaa && node.Msaa != null) + { + xml.SetAttribute("Role", node.Msaa.RoleText ?? string.Empty); + xml.SetAttribute("Value", node.Msaa.Value ?? string.Empty); + } + parent.AppendChild(xml); + mapping.Add(xml, node); + foreach (ControlTreeNode child in node.Children) AppendXml(xml, child, mapping); + } + } +} diff --git a/src/pacs_win_uia/Services/ControlTreeService.cs b/src/pacs_win_uia/Services/ControlTreeService.cs index c456395..8c3c9d4 100644 --- a/src/pacs_win_uia/Services/ControlTreeService.cs +++ b/src/pacs_win_uia/Services/ControlTreeService.cs @@ -155,10 +155,11 @@ namespace pacs_win_uia.Services }; } + ControlPath.PreparePaths(root); stopwatch.Stop(); int nodeCount = CountNodes(root); bool hasContent = nodeCount > 1; - AppLog.Info(string.Format( + AppLog.Debug(string.Format( "控件树({0}):节点 {1} 个,耗时 {2} ms{3}。", source, nodeCount, @@ -205,7 +206,7 @@ namespace pacs_win_uia.Services // bounded re-read usually picks up the content that has appeared by then. if (uiaRoot == null && LooksLikeChromeOnly(tree)) { - AppLog.Info("控件树只读到窗口边框(" + CountNodes(tree) + " 个节点),稍后重读一次。"); + AppLog.Debug("控件树只读到窗口边框(" + CountNodes(tree) + " 个节点),稍后重读一次。"); Thread.Sleep(ChromeContentRetryDelayMs); UiaTreeNodeInfo retry = _uiAutomationService.ReadTree( handle, options.MaxDepth, options.MaxNodes, options.Timeout, cancellationToken); @@ -218,26 +219,8 @@ namespace pacs_win_uia.Services } } - // The real content can also hang under a nested window element (UWP CoreWindow, renderer - // window). Reading that child is what the operator actually asked for. - if (uiaRoot == null && LooksLikeChromeOnly(tree)) - { - IntPtr contentWindow = _uiAutomationService.FindNestedContentWindow(handle); - if (contentWindow != IntPtr.Zero) - { - UiaTreeNodeInfo inner = _uiAutomationService.ReadTree( - contentWindow, options.MaxDepth, options.MaxNodes, options.Timeout, cancellationToken); - ControlTreeNode innerTree = FromUia(inner); - if (CountNodes(innerTree) > CountNodes(tree)) - { - note = string.Format( - "顶层窗口只暴露了标题栏({0} 个节点);已自动改读内层内容窗口 {1}({2} 个节点)。", - CountNodes(tree), NativeWindowInfo.FormatHandle(contentWindow), CountNodes(innerTree)); - return innerTree; - } - } - } - + // Never replace the requested root with an inner content HWND: doing so invents + // a different absolute hierarchy. A retry above always reads the SAME window. return tree; } diff --git a/src/pacs_win_uia/Services/FloatingBarManager.cs b/src/pacs_win_uia/Services/FloatingBarManager.cs index abf6481..4ba555d 100644 --- a/src/pacs_win_uia/Services/FloatingBarManager.cs +++ b/src/pacs_win_uia/Services/FloatingBarManager.cs @@ -24,26 +24,41 @@ namespace pacs_win_uia.Services public FloatingButtonDefinition Button { get; private set; } } + /// A read-only snapshot, shared by runtime checks and the settings diagnostic. + public sealed class FloatingBarDisplayCheck + { + public bool CanShow { get; internal set; } + public string Reason { get; internal set; } + public IntPtr Anchor { get; internal set; } + public IntPtr ConditionAnchor { get; internal set; } + public string Details { get; internal set; } + + public override string ToString() + { + return (CanShow ? "当前满足显示条件:" : "当前不显示:") + Reason + + (string.IsNullOrEmpty(Details) ? string.Empty : Environment.NewLine + Details); + } + } + /// /// Shows each configured floating bar only while its page/window condition holds, keeps it glued to /// that window with relative offsets, and owns the optional global hotkeys. /// - /// The condition is evaluated on a timer. Enumerating the top-level windows is the expensive part, - /// so the matched window is cached per bar and only re-discovered when it disappears; an imported - /// control path is re-checked on a slower cadence on a background thread. + /// Follow and condition checks use FloatingButton.RefreshIntervalMs (300 ms by default). Window + /// discovery and imported paths run in one background batch, never on the UI thread. A slow batch + /// skips ticks instead of queuing work; its completed results are consumed by the UI timer. /// public sealed class FloatingBarManager : IDisposable { - private const int ConditionRecheckTicks = 5; - private readonly Func _settings; private readonly Control _owner; private readonly EventHandler _actionHandler; - private readonly NativeWindowService _windowService = new NativeWindowService(); private readonly System.Windows.Forms.Timer _timer; private readonly List _bars = new List(); private readonly List _hotkeys = new List(); - private int _tick; + private readonly int _ownProcessId = System.Diagnostics.Process.GetCurrentProcess().Id; + private Task _checkTask; + private int _generation; private bool _disposed; public FloatingBarManager( @@ -54,7 +69,7 @@ namespace pacs_win_uia.Services _settings = settings ?? throw new ArgumentNullException("settings"); _owner = owner ?? throw new ArgumentNullException("owner"); _actionHandler = actionHandler; - _timer = new System.Windows.Forms.Timer { Interval = 1000 }; + _timer = new System.Windows.Forms.Timer { Interval = AppSettings.DefaultRefreshIntervalMs }; _timer.Tick += OnTick; } @@ -63,9 +78,27 @@ namespace pacs_win_uia.Services internal FloatingBarDefinition Definition; internal FloatingToolbarForm Form; internal IntPtr Anchor = IntPtr.Zero; - internal int TicksSinceCheck; - internal bool ControlConditionOk = true; - internal bool ControlCheckInFlight; + internal IntPtr ConditionAnchor; + internal bool ControlConditionOk; + internal bool WasDragging; + internal string LastStatus; + } + + private sealed class BarCheckRequest + { + internal BarRuntime Runtime; + internal IntPtr Anchor; + internal IntPtr ConditionAnchor; + internal int Generation; + } + + private sealed class BarCheckResult + { + internal BarCheckRequest Request; + internal IntPtr Anchor; + internal IntPtr ConditionAnchor; + internal bool ConditionOk; + internal string Reason; } private sealed class HotkeyRegistration @@ -79,6 +112,14 @@ namespace pacs_win_uia.Services /// Rebuilds the bars and hotkeys from the current settings. public void Reload() { + if (_disposed) + { + return; + } + + _timer.Stop(); + Interlocked.Increment(ref _generation); + // Do not clear _checkTask: even across reloads there may be only one blocking UIA batch. foreach (BarRuntime runtime in _bars) { if (runtime.Form != null) @@ -106,7 +147,7 @@ namespace pacs_win_uia.Services continue; } - var runtime = new BarRuntime { Definition = bar }; + var runtime = new BarRuntime { Definition = bar, ControlConditionOk = bar.ImportedCondition == null }; _bars.Add(runtime); foreach (FloatingButtonDefinition button in bar.Buttons ?? new List()) { @@ -143,9 +184,12 @@ namespace pacs_win_uia.Services } } + int interval = GetRefreshIntervalMs(); + _timer.Interval = interval; if (_bars.Count > 0) { - AppLog.Info("悬浮条已加载 " + _bars.Count + " 条,快捷键 " + _hotkeys.Count + " 个。"); + AppLog.Info("悬浮条已加载 " + _bars.Count + " 条,快捷键 " + _hotkeys.Count + + " 个,刷新间隔 " + interval + " ms。"); _timer.Start(); } else @@ -189,6 +233,13 @@ namespace pacs_win_uia.Services _hotkeys.Clear(); } + private int GetRefreshIntervalMs() + { + AppSettings settings = _settings(); + return AppSettings.NormalizeRefreshIntervalMs( + settings == null || settings.FloatingButton == null ? 0 : settings.FloatingButton.RefreshIntervalMs); + } + private void OnTick(object sender, EventArgs e) { if (_disposed || _owner.IsDisposed) @@ -196,7 +247,44 @@ namespace pacs_win_uia.Services return; } - _tick++; + int interval = GetRefreshIntervalMs(); + if (_timer.Interval != interval) + { + _timer.Interval = interval; + } + + // Only the UI thread reads/writes runtime state. A completed batch is a single bounded + // result slot, not a stream of BeginInvoke callbacks if the UI is busy. + if (_checkTask != null && _checkTask.IsCompleted) + { + Task completed = _checkTask; + _checkTask = null; + if (completed.IsFaulted) + { + AppLog.Warn("悬浮条后台检查失败。", completed.Exception); + } + else if (!completed.IsCanceled) + { + foreach (BarCheckResult result in completed.Result) + { + if (result.Request.Generation != _generation) + { + continue; + } + + BarRuntime runtime = result.Request.Runtime; + runtime.Anchor = result.Anchor; + runtime.ConditionAnchor = result.ConditionAnchor; + runtime.ControlConditionOk = result.ConditionOk; + if (!string.Equals(runtime.LastStatus, result.Reason, StringComparison.Ordinal)) + { + runtime.LastStatus = result.Reason; + AppLog.Info("悬浮条「" + runtime.Definition.Name + "」:" + result.Reason); + } + } + } + } + foreach (BarRuntime runtime in _bars) { try @@ -208,123 +296,263 @@ namespace pacs_win_uia.Services AppLog.Warn("更新悬浮条失败(" + runtime.Definition.Name + ")。", ex); } } + + if (_checkTask == null && _bars.Count > 0) + { + var requests = new List(); + foreach (BarRuntime runtime in _bars) + { + requests.Add(new BarCheckRequest + { + Runtime = runtime, + Anchor = runtime.Anchor, + ConditionAnchor = runtime.ConditionAnchor, + Generation = _generation + }); + } + + _checkTask = Task.Factory.StartNew( + delegate { return CheckBars(requests); }, + CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); + } } - private void UpdateBar(BarRuntime runtime) + private void FollowBar(BarRuntime runtime) { - FloatingBarDefinition bar = runtime.Definition; - - // Re-discover the anchor only when the cached one is gone: enumerating windows every tick - // would cost hundreds of milliseconds. - if (runtime.Anchor == IntPtr.Zero || !NativeMethods.IsWindow(runtime.Anchor)) + FloatingToolbarForm form = runtime.Form; + if (form == null || !form.Visible || form.IsDragging) { - runtime.Anchor = FindAnchor(bar); - if (runtime.Anchor == IntPtr.Zero) + // While the operator drags the bar itself, the mouse owns its position. + if (form != null && form.IsDragging) { - Hide(runtime); - return; + runtime.WasDragging = true; } + + return; } - NativeWindowInfo window = _windowService.Capture(runtime.Anchor); - if (window == null) + if (runtime.Anchor == IntPtr.Zero || !NativeMethods.IsWindow(runtime.Anchor)) { - runtime.Anchor = IntPtr.Zero; Hide(runtime); return; } - if (bar.RequireWindowVisible) + // Only when the bar itself asked for "target must be visible": otherwise a later + // configured condition tick could show it again and the two paths would flicker. + if (runtime.Definition.RequireWindowVisible && + (NativeMethods.IsIconic(runtime.Anchor) || !NativeMethods.IsWindowVisible(runtime.Anchor))) { - string reason; - if (!WindowVisibility.IsVisibleOnScreen( - runtime.Anchor, window.WindowBounds.ToRectangle(), - System.Diagnostics.Process.GetCurrentProcess().Id, out reason)) - { - AppLog.Debug("悬浮条 " + bar.Name + " 暂不显示:" + reason); - Hide(runtime); - return; - } + Hide(runtime); + return; } - // An imported control path is the "wait until this control exists" part of the condition. - if (bar.ImportedCondition != null) + NativeMethods.RECT rect; + if (!NativeMethods.GetWindowRect(runtime.Anchor, out rect)) { - runtime.TicksSinceCheck++; - if (!runtime.ControlCheckInFlight && runtime.TicksSinceCheck >= ConditionRecheckTicks) - { - runtime.TicksSinceCheck = 0; - StartControlConditionCheck(runtime); - } - - if (!runtime.ControlConditionOk) - { - Hide(runtime); - return; - } + return; } - Show(runtime, window); + var anchor = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); + if (runtime.WasDragging) + { + // The drop position becomes the new relative offset, otherwise the next follow tick + // would immediately snap the bar back to where it was before the drag. + runtime.WasDragging = false; + form.ApplyDraggedOffset(anchor.Location); + AppLog.Info("悬浮条「" + runtime.Definition.Name + "」相对位置已更新为 " + + runtime.Definition.OffsetX + "," + runtime.Definition.OffsetY + "(退出时保存)。"); + } + + Point target = ComputeLocation(runtime.Definition, form.Size, anchor); + if (form.Location != target) + { + form.Location = target; + } } - private IntPtr FindAnchor(FloatingBarDefinition bar) + private void UpdateBar(BarRuntime runtime) { - IList windows = _windowService.EnumerateTopLevelWindows(false); - WindowMatch match = WindowMatcher.FindBest(windows, bar.ProcessName, bar.WindowClass, bar.WindowTitleKeyword); - if (match == null) + // No Capture/EnumWindows/UIA here: position and visibility use cheap Win32 calls only. + NativeMethods.RECT rect; + if (runtime.Anchor == IntPtr.Zero || !NativeMethods.IsWindow(runtime.Anchor) + || !NativeMethods.GetWindowRect(runtime.Anchor, out rect)) { - return IntPtr.Zero; + runtime.Anchor = IntPtr.Zero; + runtime.ControlConditionOk = false; + Hide(runtime); + return; } - return match.Window.Handle; + if (!runtime.ControlConditionOk) + { + Hide(runtime); + return; + } + + var anchor = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); + string reason; + if (runtime.Definition.RequireWindowVisible && + !WindowVisibility.IsVisibleOnScreen(runtime.Anchor, anchor, _ownProcessId, out reason)) + { + Hide(runtime); + return; + } + + FollowBar(runtime); + Show(runtime, anchor); } - private void StartControlConditionCheck(BarRuntime runtime) + private BarCheckResult[] CheckBars(IList requests) { - runtime.ControlCheckInFlight = true; - ControlMonitorDefinition condition = runtime.Definition.ImportedCondition; - Task.Factory.StartNew( - delegate + // One discovery per batch; all provider work remains off the UI thread. + IList windows = null; + var results = new List(); + foreach (BarCheckRequest request in requests) + { + if (request.Generation != Volatile.Read(ref _generation)) break; + FloatingBarDisplayCheck check = EvaluateDisplay(request.Runtime.Definition, ref windows); + results.Add(new BarCheckResult { - try - { - var locator = new ControlLocatorService(); - var steps = new List(); - string error; - IntPtr handle = locator.FindTargetWindow(condition, steps, out error); - if (handle == IntPtr.Zero) - { - return false; - } - - return locator.Resolve(condition, handle, steps).Found; - } - catch (Exception ex) - { - AppLog.Debug("悬浮条控件条件检查失败:" + ex.GetType().Name + ": " + ex.Message); - return false; - } - }, - CancellationToken.None, - TaskCreationOptions.LongRunning, - TaskScheduler.Default) - .ContinueWith( - delegate(Task completed) - { - runtime.ControlCheckInFlight = false; - if (completed.IsFaulted || completed.IsCanceled) - { - return; - } - - runtime.ControlConditionOk = completed.Result; - }, - CancellationToken.None, - TaskContinuationOptions.None, - TaskScheduler.Default); + Request = request, Anchor = check.Anchor, ConditionAnchor = check.ConditionAnchor, + ConditionOk = check.CanShow, Reason = check.Reason + }); + } + return results.ToArray(); } - private void Show(BarRuntime runtime, NativeWindowInfo window) + /// Run on a worker thread. Never activates windows, invokes buttons or runs commands. + public static FloatingBarDisplayCheck CheckDisplayConditions(FloatingBarDefinition bar) + { + IList windows = null; + return EvaluateDisplay(bar, ref windows); + } + + private static FloatingBarDisplayCheck EvaluateDisplay(FloatingBarDefinition bar, + ref IList windows) + { + var result = new FloatingBarDisplayCheck(); + try + { + if (bar == null) { result.Reason = "未选择悬浮条。"; return result; } + if (!bar.Enabled) { result.Reason = "悬浮条已停用,请勾选启用。"; return result; } + string error = bar.ButtonConfigurationError; + if (error != null) { result.Reason = error; return result; } + ControlMonitorDefinition condition = bar.ImportedCondition; + if (condition != null) + { + error = ControlPath.ValidateSyntax(condition.ControlPath); + if (error != null) + { + result.Reason = "导入的 path 无效,请在监控项中编辑为 XPath 后重新导入:" + error; + return result; + } + } + string process = bar.ProcessName, windowClass = bar.WindowClass, title = bar.WindowTitleKeyword; + if (!HasWindowConditions(process, windowClass, title) && condition != null) + { + process = condition.ProcessName; + windowClass = condition.WindowClass; + title = condition.WindowTitleKeyword; + } + if (!HasWindowConditions(process, windowClass, title)) + { + result.Reason = "缺少锚定窗口条件:至少填写进程名、窗口类或标题之一,或导入含窗口条件的 XPath。"; + return result; + } + if (windows == null) + { + // Hidden/message-only windows are not useful anchors. Keep minimized top-level + // windows in the candidate set so the diagnostic can explain visibility failure. + WindowEnumerationResult enumeration = new NativeWindowService().EnumerateTopLevelWindowsResult(false); + if (!enumeration.Succeeded) { result.Reason = "窗口枚举失败:" + enumeration.Error; return result; } + windows = enumeration.Windows; + } + NativeWindowInfo window = FindConditionWindow(windows, process, windowClass, title, out error); + if (window == null) { result.Reason = "锚定窗口:" + error; return result; } + result.Anchor = window.Handle; + result.Details = "锚定窗口:" + window + ";PID=" + window.ProcessId; + if (bar.RequireWindowVisible && !WindowVisibility.IsVisibleOnScreen(window.Handle, + window.WindowRectangle, System.Diagnostics.Process.GetCurrentProcess().Id, out error)) + { + result.Reason = "锚定窗口可见性不满足:" + error + + " 设置窗口本身也可能遮挡目标;请移开设置窗口后重新检测。"; + return result; + } + if (condition != null) + { + NativeWindowInfo conditionWindow = window; + if (HasWindowConditions(condition.ProcessName, condition.WindowClass, condition.WindowTitleKeyword)) + conditionWindow = FindConditionWindow(windows, condition.ProcessName, + condition.WindowClass, condition.WindowTitleKeyword, out error); + if (conditionWindow == null) { result.Reason = "导入 XPath 的窗口:" + error; return result; } + result.ConditionAnchor = conditionWindow.Handle; + result.Details += Environment.NewLine + "XPath 窗口:" + conditionWindow + + ";PID=" + conditionWindow.ProcessId; + // Monitor.Disabled controls monitor polling, not this imported predicate. + var steps = new List(); + ControlResolution resolution = new ControlLocatorService().Resolve(condition, conditionWindow.Handle, steps); + if (!resolution.Found) + { + result.Reason = "导入 XPath 条件未满足:" + (resolution.Error ?? "未找到唯一控件。"); + result.Details += Environment.NewLine + string.Join(Environment.NewLine, steps.ToArray()); + return result; + } + } + result.CanShow = true; + result.Reason = "窗口" + (condition == null ? "" : "及导入 XPath") + "条件已满足;启用按钮 " + + bar.EnabledButtonCount + " 个。"; + } + catch (Exception ex) + { + result.Reason = "检测失败:" + ex.GetType().Name + ":" + ex.Message; + } + return result; + } + + public static bool HasWindowConditions(string process, string windowClass, string title) + { + return !string.IsNullOrWhiteSpace(process) || !string.IsNullOrWhiteSpace(windowClass) + || !string.IsNullOrWhiteSpace(title); + } + + /// Display predicates are AND conditions, not a best-effort locator fallback. + public static NativeWindowInfo FindConditionWindow(IList windows, string process, + string windowClass, string title, out string error) + { + error = null; + if (!HasWindowConditions(process, windowClass, title)) + { + error = "窗口条件全空。"; + return null; + } + process = NormalizeProcessName(process); + NativeWindowInfo match = null; + int count = 0; + foreach (NativeWindowInfo window in windows ?? new List()) + { + if (window == null || window.IsOwnProcess || !window.IsVisible) continue; + if (!string.IsNullOrEmpty(process) && !string.Equals(process, + NormalizeProcessName(window.ProcessName), StringComparison.OrdinalIgnoreCase)) continue; + if (!string.IsNullOrWhiteSpace(windowClass) && !string.Equals(window.ClassName, windowClass, StringComparison.Ordinal)) continue; + if (!string.IsNullOrWhiteSpace(title) && (window.Title == null + || window.Title.IndexOf(title, StringComparison.OrdinalIgnoreCase) < 0)) continue; + match = window; + count++; + } + if (count == 1) return match; + error = count == 0 ? "没有同时符合已填写条件的窗口(进程=" + process + ";类=" + windowClass + ";标题=" + title + ")。" + : "匹配到 " + count + " 个窗口,不能确定锚点;请补充窗口类/标题条件。"; + return null; + } + + public static string NormalizeProcessName(string process) + { + process = (process ?? string.Empty).Trim(); + return process.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) + ? process.Substring(0, process.Length - 4) : process; + } + + private void Show(BarRuntime runtime, Rectangle anchor) { if (runtime.Form == null) { @@ -332,14 +560,37 @@ namespace pacs_win_uia.Services runtime.Form.ActionInvoked += OnBarActionInvoked; } - Rectangle anchor = window.WindowBounds.ToRectangle(); - Rectangle target = new Rectangle( - anchor.Left + runtime.Definition.OffsetX, - anchor.Top + runtime.Definition.OffsetY, - runtime.Form.Width, - runtime.Form.Height); + if (runtime.Form.IsDragging) + { + runtime.WasDragging = true; + return; + } + + Point target = ComputeLocation(runtime.Definition, runtime.Form.Size, anchor); + if (runtime.Form.Location != target) + { + runtime.Form.Location = target; + } + + if (!runtime.Form.Visible) + { + runtime.Form.Show(); + } + } + + /// + /// Anchor window top-left + the configured relative offsets, clamped so the bar stays inside + /// the working area it belongs to. Used by both the condition tick and the follow tick, so the + /// bar cannot be "correct" in one and jump somewhere else in the other. + /// + private static Point ComputeLocation(FloatingBarDefinition bar, Size size, Rectangle anchor) + { + var target = new Rectangle( + anchor.Left + bar.OffsetX, + anchor.Top + bar.OffsetY, + Math.Max(1, size.Width), + Math.Max(1, size.Height)); - // Keep it on screen even if the offsets would push it off. Rectangle workingArea = Screen.FromRectangle(anchor).WorkingArea; if (target.Right > workingArea.Right) { @@ -361,11 +612,7 @@ namespace pacs_win_uia.Services target.Y = workingArea.Top; } - runtime.Form.Location = target.Location; - if (!runtime.Form.Visible) - { - runtime.Form.Show(); - } + return target.Location; } private void Hide(BarRuntime runtime) @@ -393,7 +640,10 @@ namespace pacs_win_uia.Services foreach (FloatingButtonDefinition button in runtime.Definition.Buttons) { - if (button != null && string.Equals(button.Label, e.Action, StringComparison.Ordinal)) + if (button != null && (ReferenceEquals(button, e.Button) || + (e.Button == null && string.Equals( + string.IsNullOrWhiteSpace(button.Label) ? FloatingButtonDefinition.DescribeAction(button.Action) : button.Label, + e.Action, StringComparison.Ordinal)))) { Invoke(runtime.Definition, button); return; @@ -424,6 +674,7 @@ namespace pacs_win_uia.Services } _disposed = true; + Interlocked.Increment(ref _generation); _timer.Stop(); _timer.Tick -= OnTick; _timer.Dispose(); diff --git a/src/pacs_win_uia/Services/HeadlessConfigReader.cs b/src/pacs_win_uia/Services/HeadlessConfigReader.cs index b4169fd..def3037 100644 --- a/src/pacs_win_uia/Services/HeadlessConfigReader.cs +++ b/src/pacs_win_uia/Services/HeadlessConfigReader.cs @@ -49,12 +49,24 @@ namespace pacs_win_uia.Services bool activate, OcrReadContext ocr, CancellationToken cancellationToken) + { + return Read(configPath, windowTimeout, activate, ocr, cancellationToken, true); + } + + public HeadlessReport Read( + string configPath, + TimeSpan windowTimeout, + bool activate, + OcrReadContext ocr, + CancellationToken cancellationToken, + bool skipDisabled) { var stopwatch = Stopwatch.StartNew(); var report = new HeadlessReport { ReadAtUtc = DateTime.UtcNow, - ConfigPath = configPath + ConfigPath = configPath, + SkipDisabled = skipDisabled }; IList definitions = _store.Load(); @@ -77,9 +89,8 @@ namespace pacs_win_uia.Services foreach (ControlMonitorDefinition definition in definitions) { cancellationToken.ThrowIfCancellationRequested(); - if (!definition.Enabled) + if (!definition.Enabled && skipDisabled) { - // Kept in the config but deliberately not read. report.Summary.Skipped++; AppLog.Info("跳过已停用的条目:" + definition.ContentKey); continue; @@ -103,7 +114,7 @@ namespace pacs_win_uia.Services { report.Summary.Missing++; } - else if (!item.ValueAvailable) + else if (!item.ValueAvailable && !string.IsNullOrWhiteSpace(item.ValueKey)) { report.Summary.ValueUnavailable++; } @@ -181,6 +192,16 @@ namespace pacs_win_uia.Services return item; } + if (string.IsNullOrWhiteSpace(definition.ValueKey)) + { + // Locate-only entries do not request a value (or OCR), so this is not a read failure. + steps.Add("未设置 ValueKey:仅定位,不取值。"); + stopwatch.Stop(); + item.ElapsedMs = stopwatch.ElapsedMilliseconds; + AppLog.Info("条目 " + definition.ContentKey + ":已定位到控件,仅定位不取值。"); + return item; + } + string value; string valueError; if (ControlValueReader.TryRead(resolution.Node, definition.ValueKey, new ListReadOptions(), ocr, out value, out valueError)) diff --git a/src/pacs_win_uia/Services/HighlightFollower.cs b/src/pacs_win_uia/Services/HighlightFollower.cs new file mode 100644 index 0000000..cbb0e49 --- /dev/null +++ b/src/pacs_win_uia/Services/HighlightFollower.cs @@ -0,0 +1,391 @@ +using System; +using System.Drawing; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using pacs_win_uia.Diagnostics; +using pacs_win_uia.Interop; +using pacs_win_uia.Models; +using pacs_win_uia.UI; + +namespace pacs_win_uia.Services +{ + public sealed class HighlightHiddenEventArgs : EventArgs + { + public HighlightHiddenEventArgs(string reason) + { + Reason = reason; + } + + /// Why the box is no longer drawn; shown in the status bar. + public string Reason { get; private set; } + } + + /// + /// Keeps one highlight rectangle glued to a target control, and takes it off screen the moment it + /// would point at nothing. + /// + /// The fast path is pure Win32 on purpose: the offset of the control inside its top-level window + /// is measured once, and every follow tick re-reads only GetWindowRect of that window. That + /// call is answered by the kernel, so it cannot hang on a stuck target — which is what lets the + /// follow run at ~120 ms (a frame that only moved after the operator stopped dragging the target + /// window was the whole complaint). UIA / MSAA / Win32 re-resolution, which *can* block on another + /// process, runs single-flight on a background thread at a configurable cadence and corrects the offset (it + /// catches scrolling and layout changes, not window movement). + /// + public sealed class HighlightFollower : IDisposable + { + private const int FollowIntervalMs = 120; + + private readonly HighlightOverlayForm _overlay; + private readonly System.Windows.Forms.Timer _timer; + private readonly int _ownProcessId; + private Func _reResolve; + private IntPtr _anchor = IntPtr.Zero; + private Rectangle _bounds; + private Size _size; + private int _offsetX; + private int _offsetY; + private string _label; + private int _reResolveIntervalMs = AppSettings.DefaultRefreshIntervalMs; + private DateTime _nextReResolveUtc; + private int _session; + private bool _active; + private bool _shown; + private bool _hiddenReported; + private volatile bool _resolutionInFlight; + private bool _disposed; + + public HighlightFollower(int ownProcessId) + { + _ownProcessId = ownProcessId; + _overlay = new HighlightOverlayForm(); + _timer = new System.Windows.Forms.Timer { Interval = FollowIntervalMs }; + _timer.Tick += OnTimerTick; + } + + /// Raised once when the box stops being drawn because the target disappeared or is covered. + public event EventHandler Hidden; + + /// True while a target is being followed (not necessarily currently visible). + public bool IsTracking + { + get { return _active; } + } + + /// True while the box is actually on screen. + public bool IsVisible + { + get { return _active && _shown && _overlay.Visible; } + } + + public IntPtr AnchorWindow + { + get { return _anchor; } + } + + /// Interval used for potentially blocking UIA/MSAA re-resolution. + public int ReResolveIntervalMs + { + get { return _reResolveIntervalMs; } + } + + /// + /// Sets the background re-resolution cadence. Win32 position following remains at 120 ms; + /// this value only controls the potentially blocking resolver. + /// + public void SetReResolveIntervalMs(int intervalMs) + { + _reResolveIntervalMs = AppSettings.NormalizeRefreshIntervalMs(intervalMs); + _nextReResolveUtc = DateTime.UtcNow.AddMilliseconds(_reResolveIntervalMs); + } + + /// + /// Follows (absolute screen rectangle, as measured now) and + /// keeps it relative to . is + /// optional: it is called on a background thread at ReResolveIntervalMs to correct the offset. + /// + public void Show(Rectangle controlBounds, IntPtr anchorWindow, Func reResolve, string label) + { + if (_disposed) + { + return; + } + + if (controlBounds.Width <= 1 || controlBounds.Height <= 1) + { + Hide("矩形过小(" + controlBounds + "),不画框。"); + return; + } + + _session++; + _active = true; + _shown = false; + _hiddenReported = false; + _anchor = anchorWindow; + _bounds = controlBounds; + _size = controlBounds.Size; + _label = label; + _reResolve = reResolve; + _nextReResolveUtc = DateTime.UtcNow.AddMilliseconds(_reResolveIntervalMs); + UpdateOffset(); + _timer.Start(); + Tick(); + } + + /// Stops following and hides the box. No event: the caller asked. + public void Hide(string reason) + { + StopCore(false); + } + + private void OnTimerTick(object sender, EventArgs e) + { + Tick(); + } + + private void Tick() + { + if (_disposed || !_active) + { + return; + } + + Rectangle rect; + if (_anchor != IntPtr.Zero) + { + if (!NativeMethods.IsWindow(_anchor)) + { + // The target is gone for good: nothing left to follow. + StopAndNotify("目标窗口已关闭,已隐藏高亮框。"); + return; + } + + Rectangle anchorRect; + if (!TryGetWindowRectangle(_anchor, out anchorRect)) + { + StopAndNotify("读不到目标窗口位置,已隐藏高亮框。"); + return; + } + + rect = new Rectangle(anchorRect.Left + _offsetX, anchorRect.Top + _offsetY, _size.Width, _size.Height); + } + else + { + rect = _bounds; + } + + string visibilityReason; + if (!WindowVisibility.IsVisibleOnScreen(_anchor, rect, _ownProcessId, out visibilityReason)) + { + // Minimized, hidden, covered or off-screen: take the box away, but keep tracking so it + // comes back when the operator can see the target again. The reason is reported once. + if (_shown) + { + _shown = false; + _overlay.HideHighlight(); + } + + if (!_hiddenReported) + { + _hiddenReported = true; + Notify(visibilityReason + ":" + (_label ?? "高亮框") + "已隐藏。"); + } + + return; + } + + if (!_shown || _overlay.Bounds != rect) + { + _shown = true; + _hiddenReported = false; + _overlay.ShowHighlight(rect); + } + else + { + _hiddenReported = false; + } + + MaybeReResolve(); + } + + private void MaybeReResolve() + { + if (_reResolve == null || _resolutionInFlight) + { + return; + } + + DateTime now = DateTime.UtcNow; + if (now < _nextReResolveUtc) + { + return; + } + + // Advance the deadline before starting work. The in-flight guard prevents overlap if a + // resolver takes longer than the configured cadence. + _nextReResolveUtc = now.AddMilliseconds(_reResolveIntervalMs); + _resolutionInFlight = true; + int session = _session; + Func resolver = _reResolve; + Task task = Task.Factory.StartNew( + delegate + { + try + { + return resolver(); + } + catch (Exception ex) + { + AppLog.Debug("重新解析高亮框位置失败:" + ex.GetType().Name + ": " + ex.Message); + return (Rectangle?)null; + } + }, + CancellationToken.None, + TaskCreationOptions.None, + TaskScheduler.Default); + + task.ContinueWith( + delegate(Task completed) + { + if (_disposed || completed.IsFaulted || completed.IsCanceled) + { + _resolutionInFlight = false; + return; + } + + Rectangle? result = completed.Result; + try + { + if (_overlay.IsHandleCreated && !_overlay.IsDisposed) + { + _overlay.BeginInvoke((Action)delegate + { + try + { + ApplyReResolved(session, result); + } + finally + { + // Keep the gate closed until the UI consumes the result, including + // across Show/Hide sessions. No queued UI callbacks can accumulate. + _resolutionInFlight = false; + } + }); + return; + } + } + catch (Exception) + { + // The overlay is going away; nothing left to update. + } + + _resolutionInFlight = false; + }, + CancellationToken.None, + TaskContinuationOptions.None, + TaskScheduler.Default); + } + + private void ApplyReResolved(int session, Rectangle? result) + { + if (_disposed || !_active || session != _session) + { + return; + } + + if (!result.HasValue || result.Value.Width <= 1 || result.Value.Height <= 1) + { + StopAndNotify("控件已经取不到矩形(可能已关闭),已隐藏高亮框。"); + return; + } + + _bounds = result.Value; + _size = _bounds.Size; + UpdateOffset(); + Tick(); + } + + /// Measures where the control sits inside the anchor window, once per new rectangle. + private void UpdateOffset() + { + _offsetX = _bounds.Left; + _offsetY = _bounds.Top; + if (_anchor == IntPtr.Zero) + { + return; + } + + Rectangle anchorRect; + if (TryGetWindowRectangle(_anchor, out anchorRect)) + { + _offsetX = _bounds.Left - anchorRect.Left; + _offsetY = _bounds.Top - anchorRect.Top; + } + } + + private static bool TryGetWindowRectangle(IntPtr handle, out Rectangle rectangle) + { + rectangle = Rectangle.Empty; + NativeMethods.RECT native; + if (!NativeMethods.GetWindowRect(handle, out native)) + { + return false; + } + + rectangle = new Rectangle( + native.Left, native.Top, native.Right - native.Left, native.Bottom - native.Top); + return rectangle.Width > 0 && rectangle.Height > 0; + } + + private void StopAndNotify(string reason) + { + StopCore(true, reason); + } + + private void StopCore(bool notify) + { + StopCore(notify, null); + } + + private void StopCore(bool notify, string reason) + { + _timer.Stop(); + _active = false; + _shown = false; + _hiddenReported = false; + _session++; + _anchor = IntPtr.Zero; + _reResolve = null; + _nextReResolveUtc = DateTime.MinValue; + _overlay.HideHighlight(); + if (notify) + { + Notify(reason); + } + } + + private void Notify(string reason) + { + EventHandler handler = Hidden; + if (handler != null) + { + handler(this, new HighlightHiddenEventArgs(reason)); + } + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + _timer.Stop(); + _timer.Tick -= OnTimerTick; + _timer.Dispose(); + _overlay.Dispose(); + } + } +} diff --git a/src/pacs_win_uia/Services/ProcessJob.cs b/src/pacs_win_uia/Services/ProcessJob.cs new file mode 100644 index 0000000..75ddb55 --- /dev/null +++ b/src/pacs_win_uia/Services/ProcessJob.cs @@ -0,0 +1,170 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using pacs_win_uia.Diagnostics; + +namespace pacs_win_uia.Services +{ + /// + /// A Windows job object created with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE. + /// + /// Every process this tool starts is assigned to the job, and children a process creates are + /// inherited into the same job. Closing the job handle — which happens on a normal exit, on + /// , and also when this process is killed (the OS closes the handle) — + /// therefore terminates the command *and everything the command launched*. + /// + /// Killing only the cmd.exe we started would leave a launched application running; the job is + /// what makes "退出时把命令和它拉起的应用一起结束" actually true. Assignment can fail (the + /// process may have already exited, or a legacy parent job may forbid nesting); failures are + /// logged and the caller still has the explicit kill path as a fallback. + /// + public sealed class ProcessJob : IDisposable + { + private const int JobObjectExtendedLimitInformation = 9; + private const uint JobObjectLimitKillOnJobClose = 0x2000; + + private IntPtr _handle; + private bool _disposed; + + public ProcessJob() + { + try + { + _handle = CreateJobObject(IntPtr.Zero, null); + if (_handle == IntPtr.Zero) + { + AppLog.Warn("创建进程 Job 失败,退出时只能按 PID 结束命令(拉起的子进程可能残留)。Win32 错误码: " + + Marshal.GetLastWin32Error()); + return; + } + + var limits = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION(); + limits.BasicLimitInformation.LimitFlags = JobObjectLimitKillOnJobClose; + int size = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION)); + IntPtr buffer = Marshal.AllocHGlobal(size); + try + { + Marshal.StructureToPtr(limits, buffer, false); + if (!SetInformationJobObject(_handle, JobObjectExtendedLimitInformation, buffer, (uint)size)) + { + AppLog.Warn("设置 Job 的「句柄关闭即结束」标志失败,退出时只能按 PID 结束命令。Win32 错误码: " + + Marshal.GetLastWin32Error()); + } + } + finally + { + Marshal.FreeHGlobal(buffer); + } + } + catch (Exception ex) + { + AppLog.Warn("初始化进程 Job 失败:", ex); + if (_handle != IntPtr.Zero) + { + CloseHandle(_handle); + _handle = IntPtr.Zero; + } + } + } + + /// False when the job could not be created; callers must then kill explicitly. + public bool IsAvailable + { + get { return _handle != IntPtr.Zero; } + } + + /// Puts a freshly started process (and, by inheritance, its children) into the job. + public bool TryAssign(Process process) + { + if (_handle == IntPtr.Zero || process == null) + { + return false; + } + + try + { + if (!AssignProcessToJobObject(_handle, process.Handle)) + { + AppLog.Warn("把命令进程(PID " + process.Id + ")加入 Job 失败,它的子进程不会随本工具退出:Win32 错误码 " + + Marshal.GetLastWin32Error()); + return false; + } + + return true; + } + catch (Exception ex) + { + // The process can exit before we get its handle; that is not an error worth failing on. + AppLog.Debug("加入 Job 时进程已不可用:" + ex.GetType().Name + ": " + ex.Message); + return false; + } + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + if (_handle == IntPtr.Zero) + { + return; + } + + // Closing the handle is the kill: every process still in the job is terminated by the OS, + // including processes the commands spawned themselves. + CloseHandle(_handle); + _handle = IntPtr.Zero; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr CreateJobObject(IntPtr securityAttributes, string name); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool SetInformationJobObject(IntPtr job, int informationClass, IntPtr information, uint length); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process); + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool CloseHandle(IntPtr handle); + + [StructLayout(LayoutKind.Sequential)] + private struct JOBOBJECT_BASIC_LIMIT_INFORMATION + { + public long PerProcessUserTimeLimit; + public long PerJobUserTimeLimit; + public uint LimitFlags; + public UIntPtr MinimumWorkingSetSize; + public UIntPtr MaximumWorkingSetSize; + public uint ActiveProcessLimit; + public UIntPtr Affinity; + public uint PriorityClass; + public uint SchedulingClass; + } + + [StructLayout(LayoutKind.Sequential)] + private struct IO_COUNTERS + { + public ulong ReadOperationCount; + public ulong WriteOperationCount; + public ulong OtherOperationCount; + public ulong ReadTransferCount; + public ulong WriteTransferCount; + public ulong OtherTransferCount; + } + + [StructLayout(LayoutKind.Sequential)] + private struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION + { + public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; + public IO_COUNTERS IoInfo; + public UIntPtr ProcessMemoryLimit; + public UIntPtr JobMemoryLimit; + public UIntPtr PeakProcessMemoryUsed; + public UIntPtr PeakJobMemoryUsed; + } + } +} diff --git a/src/pacs_win_uia/Services/SingleInstanceService.cs b/src/pacs_win_uia/Services/SingleInstanceService.cs new file mode 100644 index 0000000..ef8366c --- /dev/null +++ b/src/pacs_win_uia/Services/SingleInstanceService.cs @@ -0,0 +1,441 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.IO.Pipes; +using System.Runtime.InteropServices; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Json; +using System.Security.AccessControl; +using System.Security.Principal; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Win32.SafeHandles; +using pacs_win_uia.Diagnostics; + +namespace pacs_win_uia.Services +{ + /// + /// One owner per Windows user/session, including one-shot headless invocations. + /// Construct and dispose on the same thread (Windows mutex ownership is thread-affine). + /// A non-owner may only forward: it never promotes itself after a connection failure. + /// + internal sealed class SingleInstanceService : IDisposable + { + private const int TransportTimeoutMs = 15000; + private const int MaxRequestBytes = 256 * 1024; + private const int MaxResponseBytes = 64 * 1024 * 1024; + private readonly Mutex _mutex; + private readonly string _pipeName; + private readonly SecurityIdentifier _user; + private readonly int _sessionId; + private readonly CancellationTokenSource _shutdown = new CancellationTokenSource(); + private readonly SemaphoreSlim _readGate = new SemaphoreSlim(1, 1); + private readonly object _clientsLock = new object(); + private readonly List _clients = new List(); + private Task _listener; + private Func _handler; + private bool _disposed; + + public SingleInstanceService() + { + using (WindowsIdentity identity = WindowsIdentity.GetCurrent()) + { + _user = identity.User; + } + if (_user == null) + { + throw new InvalidOperationException("无法确定当前 Windows 用户。"); + } + using (Process process = Process.GetCurrentProcess()) + { + _sessionId = process.SessionId; + } + + _pipeName = "pacs_win_uia.single-instance.v1." + _user.Value + "." + _sessionId; + var security = new MutexSecurity(); + security.SetAccessRuleProtection(true, false); + security.AddAccessRule(new MutexAccessRule(_user, MutexRights.FullControl, AccessControlType.Allow)); + bool created; + _mutex = new Mutex(false, "Local\\" + _pipeName, out created, security); + try + { + IsOwner = _mutex.WaitOne(0); + } + catch (AbandonedMutexException) + { + // The previous process died. This acquisition, not a failed forwarding attempt, + // is the only other way a newly started process may become the owner. + IsOwner = true; + } + } + + public bool IsOwner { get; private set; } + + [DataContract] + public sealed class Request + { + // Explicit path arguments are made absolute by the caller, before crossing processes. + [DataMember(Order = 1, IsRequired = true)] + public string[] Arguments { get; set; } + + // Defaults belong to the launching executable, not necessarily the owner's directory. + [DataMember(Order = 2, IsRequired = true)] + public string DefaultOutputPath { get; set; } + } + + [DataContract] + public sealed class Response + { + [DataMember(Order = 1, IsRequired = true)] + public string StandardOutput { get; set; } + + [DataMember(Order = 2, IsRequired = true)] + public string StandardError { get; set; } + + [DataMember(Order = 3, IsRequired = true)] + public int ExitCode { get; set; } + } + + /// Starts accepting immediately; neither pipe I/O nor handlers run on the UI thread. + public void Start(Func handler) + { + EnsureOwner(); + if (handler == null) throw new ArgumentNullException("handler"); + if (_listener != null) throw new InvalidOperationException("命名管道服务已经启动。"); + _handler = handler; + // Surface initial bind/ACL failures to Main rather than silently leaving a mutex-only owner. + NamedPipeServerStream first = CreateServer(); + _listener = Task.Run(() => AcceptLoopAsync(first)); + } + + /// + /// Also used by the first headless invocation. Serialize reads (including their output files), + /// but do not make an activation request wait for a long-running read. + /// + public int Execute(Request request, TextWriter stdout, TextWriter stderr) + { + EnsureOwner(); + ValidateRequest(request); + if (_handler == null) throw new InvalidOperationException("命名管道服务尚未启动。"); + bool reading = request.Arguments.Length != 0; + bool gateAcquired = false; + try + { + if (reading) + { + _readGate.Wait(_shutdown.Token); + gateAcquired = true; + } + _shutdown.Token.ThrowIfCancellationRequested(); + return _handler(request, stdout, stderr, _shutdown.Token); + } + finally + { + if (gateAcquired) _readGate.Release(); + } + } + + /// + /// Retry only connection establishment during startup. After sending a request, never retry it: + /// losing a reply does not prove that the owner did not already read or write the output file. + /// + public Response Forward(Request request) + { + if (_disposed) throw new ObjectDisposedException(GetType().Name); + if (IsOwner) throw new InvalidOperationException("主实例不能向自身转发请求。"); + ValidateRequest(request); + using (var pipe = new NamedPipeClientStream( + ".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.Identification)) + { + var elapsed = Stopwatch.StartNew(); + while (!pipe.IsConnected) + { + if (!OwnerStillRunning()) + { + throw new IOException("已有实例已退出;本次请求未改为本地执行,请重新启动命令。"); + } + int remaining = TransportTimeoutMs - (int)elapsed.ElapsedMilliseconds; + if (remaining <= 0) + { + throw new TimeoutException("等待已有实例的命名管道超时;本次请求未在本地执行。"); + } + try + { + pipe.Connect(Math.Min(250, remaining)); + } + catch (TimeoutException) + { + // The owner may hold the mutex before its UI/pipe has finished starting. + } + } + + uint serverPid; + if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle, out serverPid) || !IsSameSession(serverPid)) + { + throw new IOException("无法验证已有实例的会话。"); + } + if (request.Arguments.Length == 0) + { + // Transfer this launch's foreground permission before the owner invokes its UI. + AllowSetForegroundWindow(serverPid); + } + + using (var sendTimeout = new CancellationTokenSource(TransportTimeoutMs)) + using (sendTimeout.Token.Register(() => ClosePipe(pipe))) + { + WriteMessageAsync(pipe, request, MaxRequestBytes, sendTimeout.Token).GetAwaiter().GetResult(); + } + // A read may legitimately take longer than the connection timeout. Owner exit closes + // the pipe and produces EOF; there is deliberately no short execution-time deadline. + Response response = ReadMessageAsync(pipe, MaxResponseBytes, CancellationToken.None) + .GetAwaiter().GetResult(); + if (response == null || response.StandardOutput == null || response.StandardError == null) + { + throw new InvalidDataException("已有实例返回了无效响应。"); + } + return response; + } + } + + private bool OwnerStillRunning() + { + bool acquired; + try + { + acquired = _mutex.WaitOne(0); + } + catch (AbandonedMutexException) + { + acquired = true; + } + if (acquired) _mutex.ReleaseMutex(); + return !acquired; + } + + private NamedPipeServerStream CreateServer() + { + var security = new PipeSecurity(); + security.SetAccessRuleProtection(true, false); + security.AddAccessRule(new PipeAccessRule( + new SecurityIdentifier(WellKnownSidType.NetworkSid, null), PipeAccessRights.FullControl, AccessControlType.Deny)); + security.AddAccessRule(new PipeAccessRule(_user, PipeAccessRights.FullControl, AccessControlType.Allow)); + return new NamedPipeServerStream( + _pipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, + PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 4096, 4096, security); + } + + private async Task AcceptLoopAsync(NamedPipeServerStream pipe) + { + try + { + while (!_shutdown.IsCancellationRequested) + { + // Capture this listener, not the loop variable which becomes a connected client. + NamedPipeServerStream waiting = pipe; + using (_shutdown.Token.Register(() => ClosePipe(waiting))) + { + await waiting.WaitForConnectionAsync(_shutdown.Token).ConfigureAwait(false); + } + _shutdown.Token.ThrowIfCancellationRequested(); + NamedPipeServerStream connected = pipe; + Task client = Task.Run(() => HandleClientAsync(connected)); + lock (_clientsLock) + { + _clients.RemoveAll(task => task.IsCompleted); + _clients.Add(client); + } + pipe = null; // The client task now owns this stream. + if (!_shutdown.IsCancellationRequested) pipe = CreateServer(); + } + } + catch (Exception ex) + { + if (!_shutdown.IsCancellationRequested) + { + AppLog.Error("单实例管道服务停止。", ex); + _shutdown.Cancel(); + } + } + finally + { + if (pipe != null) ClosePipe(pipe); + } + } + + private async Task HandleClientAsync(NamedPipeServerStream pipe) + { + using (pipe) + using (_shutdown.Token.Register(() => ClosePipe(pipe))) + { + try + { + uint clientPid; + if (!GetNamedPipeClientProcessId(pipe.SafePipeHandle, out clientPid) || !IsSameSession(clientPid)) + { + throw new IOException("拒绝其他会话的单实例请求。"); + } + Request request; + using (var receiveTimeout = CancellationTokenSource.CreateLinkedTokenSource(_shutdown.Token)) + using (receiveTimeout.Token.Register(() => ClosePipe(pipe))) + { + receiveTimeout.CancelAfter(TransportTimeoutMs); + request = await ReadMessageAsync(pipe, MaxRequestBytes, receiveTimeout.Token) + .ConfigureAwait(false); + } + + Response response; + using (var stdout = new StringWriter()) + using (var stderr = new StringWriter()) + { + int exitCode; + try + { + exitCode = Execute(request, stdout, stderr); + } + catch (OperationCanceledException) + { + stderr.WriteLine("已有实例正在退出,请求已取消。"); + exitCode = 2; + } + catch (Exception ex) + { + stderr.WriteLine("已有实例处理请求失败:" + ex.Message); + AppLog.Error("单实例请求执行失败。", ex); + exitCode = 2; + } + response = new Response + { + StandardOutput = stdout.ToString(), + StandardError = stderr.ToString(), + ExitCode = exitCode + }; + } + + using (var sendTimeout = CancellationTokenSource.CreateLinkedTokenSource(_shutdown.Token)) + using (sendTimeout.Token.Register(() => ClosePipe(pipe))) + { + sendTimeout.CancelAfter(TransportTimeoutMs); + await WriteMessageAsync(pipe, response, MaxResponseBytes, sendTimeout.Token).ConfigureAwait(false); + } + } + catch (Exception ex) + { + // Broken clients and malformed frames must not kill the listener or the UI. + if (!_shutdown.IsCancellationRequested) AppLog.Warn("单实例管道连接结束。", ex); + } + } + } + + private bool IsSameSession(uint processId) + { + try + { + using (Process process = Process.GetProcessById(checked((int)processId))) + { + return process.SessionId == _sessionId; + } + } + catch (ArgumentException) { return false; } + catch (InvalidOperationException) { return false; } + catch (System.ComponentModel.Win32Exception) { return false; } + } + + private static void ValidateRequest(Request request) + { + if (request == null || request.Arguments == null || Array.Exists(request.Arguments, arg => arg == null) || + string.IsNullOrWhiteSpace(request.DefaultOutputPath) || !Path.IsPathRooted(request.DefaultOutputPath)) + { + throw new InvalidDataException("无效的单实例请求。"); + } + } + + private static async Task WriteMessageAsync(Stream pipe, T value, int limit, CancellationToken token) + { + byte[] data; + using (var buffer = new MemoryStream()) + { + new DataContractJsonSerializer(typeof(T)).WriteObject(buffer, value); + if (buffer.Length > limit) throw new InvalidDataException("单实例消息超过大小限制。"); + data = buffer.ToArray(); + } + byte[] length = BitConverter.GetBytes(data.Length); + await pipe.WriteAsync(length, 0, length.Length, token).ConfigureAwait(false); + await pipe.WriteAsync(data, 0, data.Length, token).ConfigureAwait(false); + await pipe.FlushAsync(token).ConfigureAwait(false); + } + + private static async Task ReadMessageAsync(Stream pipe, int limit, CancellationToken token) + { + var header = new byte[4]; + await ReadExactlyAsync(pipe, header, token).ConfigureAwait(false); + int length = BitConverter.ToInt32(header, 0); + if (length <= 0 || length > limit) throw new InvalidDataException("无效的单实例消息长度。"); + var data = new byte[length]; + await ReadExactlyAsync(pipe, data, token).ConfigureAwait(false); + using (var buffer = new MemoryStream(data, false)) + { + return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(buffer); + } + } + + private static async Task ReadExactlyAsync(Stream pipe, byte[] bytes, CancellationToken token) + { + int offset = 0; + while (offset < bytes.Length) + { + int count = await pipe.ReadAsync(bytes, offset, bytes.Length - offset, token).ConfigureAwait(false); + if (count == 0) throw new EndOfStreamException("已有实例的管道已关闭;请求可能已执行,请勿自动重试。"); + offset += count; + } + } + + private void EnsureOwner() + { + if (_disposed) throw new ObjectDisposedException(GetType().Name); + if (!IsOwner) throw new InvalidOperationException("只有主实例可以执行请求。"); + } + + private static void ClosePipe(Stream pipe) + { + try { pipe.Dispose(); } + catch (IOException) { } + catch (ObjectDisposedException) { } + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + try + { + _shutdown.Cancel(); + if (_listener != null) _listener.GetAwaiter().GetResult(); + Task[] clients; + lock (_clientsLock) { clients = _clients.ToArray(); } + // Called after Application.Run has ended, never by a UI Invoke callback. Keep the + // mutex until all actual work stops, even if a third-party provider is slow to return. + Task.WaitAll(clients); + } + finally + { + if (IsOwner) _mutex.ReleaseMutex(); + _mutex.Dispose(); + _readGate.Dispose(); + _shutdown.Dispose(); + } + } + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetNamedPipeServerProcessId(SafePipeHandle pipe, out uint serverProcessId); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GetNamedPipeClientProcessId(SafePipeHandle pipe, out uint clientProcessId); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool AllowSetForegroundWindow(uint processId); + } +} diff --git a/src/pacs_win_uia/Services/TargetProbeService.cs b/src/pacs_win_uia/Services/TargetProbeService.cs index 1e655f8..7f0d96a 100644 --- a/src/pacs_win_uia/Services/TargetProbeService.cs +++ b/src/pacs_win_uia/Services/TargetProbeService.cs @@ -78,12 +78,13 @@ namespace pacs_win_uia.Services + ",矩形=" + (result.Bounds == null ? "(无)" : result.Bounds.ToString())); // --- UIA: walked down from the window the cursor is over ---------------------- - result.AutomationElement = knownWindowHandle == IntPtr.Zero - ? _uiAutomationService.FromPoint(screenPoint) - : _uiAutomationService.FromHandleAtPoint(handle, screenPoint); + IntPtr rootHandle = NativeMethods.GetAncestor(handle, NativeMethods.GA_ROOT); + result.AutomationElement = _uiAutomationService.FromHandleAtPoint( + rootHandle == IntPtr.Zero ? handle : rootHandle, screenPoint); - bool uiaMatchesWindow = result.AutomationElement != null && result.AutomationElement.IsAvailable && - (result.AutomationElement.ProcessId <= 0 || result.AutomationElement.ProcessId == deepest.ProcessId); + // FromHandleAtPoint verifies membership in this window tree; UWP content may be + // provided by a different process than the frame HWND. + bool uiaMatchesWindow = result.AutomationElement != null && result.AutomationElement.IsAvailable; if (result.AutomationElement != null && result.AutomationElement.IsAvailable && !uiaMatchesWindow) { result.FailureReason = "UIA 元素与 Win32 窗口属于不同进程,已拒绝合并为同一目标。"; diff --git a/src/pacs_win_uia/Services/UiAutomationService.cs b/src/pacs_win_uia/Services/UiAutomationService.cs index 6b04835..ad79568 100644 --- a/src/pacs_win_uia/Services/UiAutomationService.cs +++ b/src/pacs_win_uia/Services/UiAutomationService.cs @@ -7,6 +7,7 @@ using System.Threading; using System.Windows.Automation; using pacs_win_uia.Diagnostics; using pacs_win_uia.Models; +using pacs_win_uia.Interop; namespace pacs_win_uia.Services { @@ -42,7 +43,8 @@ namespace pacs_win_uia.Services /// public static CacheRequest CreateSnapshotCache() { - var request = new CacheRequest(); + var request = new CacheRequest { TreeFilter = Automation.RawViewCondition }; + request.Add(AutomationElement.RuntimeIdProperty); request.Add(AutomationElement.NameProperty); request.Add(AutomationElement.AutomationIdProperty); request.Add(AutomationElement.ControlTypeProperty); @@ -104,8 +106,14 @@ namespace pacs_win_uia.Services } } - // RuntimeId is a provider call that cannot be cached; it is filled on demand - // (see UiaElementInfo.EnsureRuntimeId) instead of once per tree node. + // RuntimeIdProperty participates in the same batch cache request. Older providers + // may omit it; leave the id unset in that case, never substitute it for a differing id. + try + { + int[] id = element.GetCachedPropertyValue(AutomationElement.RuntimeIdProperty, true) as int[]; + snapshot.RuntimeId = id == null ? null : string.Join(".", Array.ConvertAll(id, value => value.ToString(System.Globalization.CultureInfo.InvariantCulture))); + } + catch (Exception) { /* Optional identity cache; EnsureRuntimeId remains available. */ } return snapshot; } catch (Exception ex) @@ -164,7 +172,7 @@ namespace pacs_win_uia.Services continue; } - AutomationElementCollection children = item.Key.FindAll(TreeScope.Children, Condition.TrueCondition); + AutomationElementCollection children = item.Key.FindAll(TreeScope.Children, Automation.RawViewCondition); foreach (AutomationElement child in children) { AutomationElement.AutomationElementInformation info = child.Current; @@ -214,78 +222,100 @@ namespace pacs_win_uia.Services public UiaElementInfo FromHandleAtPoint(IntPtr handle, Point point) { - if (handle == IntPtr.Zero) - { - return Failure("HWND 为空。"); - } - + if (handle == IntPtr.Zero) return Failure("HWND 为空。"); try { + IntPtr top = NativeMethods.GetAncestor(handle, NativeMethods.GA_ROOT); + if (top != IntPtr.Zero) handle = top; AutomationElement root = AutomationElement.FromHandle(handle); - var searchState = new PointProbeState(500); - AutomationElement deepest = FindDeepestElementAtPoint(root, point, 0, 8, searchState); - return Inspect(deepest ?? root); + // Real provider hit-testing knows virtual items and Z order. Validate ancestry, + // not PID: a UWP/Chromium child provider may live in another process. + try + { + AutomationElement hit = AutomationElement.FromPoint(new System.Windows.Point(point.X, point.Y)); + if (BelongsToWindow(hit, root, handle)) + { + UiaElementInfo snapshot = Inspect(hit); + if (snapshot.IsAvailable) return snapshot; + } + } + catch (Exception ex) { AppLog.Debug("UIA hit-test 不可用,改用 RawView:" + ex.Message); } + var state = new PointProbeState(3000); + FindDeepestElementAtPoint(root, point, 0, 32, state); + return state.Best == null ? Failure("目标窗口中没有包含该点的 UIA 元素。") : Inspect(state.Best); } - catch (Exception ex) + catch (Exception ex) { return Failure(FormatException(ex)); } + } + + private static bool BelongsToWindow(AutomationElement hit, AutomationElement root, IntPtr handle) + { + AutomationElement current = hit; + for (int depth = 0; current != null && depth < 64; depth++) { - return Failure(FormatException(ex)); + try + { + // Do not use name/class equality to prove ancestry. A UWP/Chromium provider + // may have no RuntimeId and may expose duplicate labels; HWND ancestry is the + // cross-process-safe boundary, while child providers can have HWND=0. + if (ReferenceEquals(current, root) || new IntPtr(current.Current.NativeWindowHandle) == handle) + return true; + current = TreeWalker.RawViewWalker.GetParent(current); + } + catch (Exception) { return false; } } + return false; } private sealed class PointProbeState { - internal PointProbeState(int maximumNodes) - { - Remaining = maximumNodes; - } - + internal PointProbeState(int maximumNodes) { Remaining = maximumNodes; } internal int Remaining { get; private set; } - + internal AutomationElement Best; + internal double BestArea = double.PositiveInfinity; + internal int BestDepth = -1; + private readonly System.Diagnostics.Stopwatch _clock = System.Diagnostics.Stopwatch.StartNew(); internal bool Consume() { - if (Remaining <= 0) - { - return false; - } - + if (Remaining <= 0 || _clock.Elapsed > TimeSpan.FromSeconds(3)) return false; Remaining--; return true; } } - private static AutomationElement FindDeepestElementAtPoint( - AutomationElement element, - Point point, - int depth, - int maxDepth, - PointProbeState state) + private static void FindDeepestElementAtPoint(AutomationElement element, Point point, int depth, + int maxDepth, PointProbeState state) { - if (element == null || depth >= maxDepth || state.Remaining <= 0) - { - return element; - } - - AutomationElement best = element; + if (element == null || !state.Consume()) return; try { - AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(element); - while (child != null && state.Consume()) + System.Windows.Rect bounds = element.Current.BoundingRectangle; + if (!bounds.IsEmpty && bounds.Contains(new System.Windows.Point(point.X, point.Y))) { - System.Windows.Rect bounds = child.Current.BoundingRectangle; - if (!bounds.IsEmpty && bounds.Contains(new System.Windows.Point(point.X, point.Y))) + double area = bounds.Width * bounds.Height; + if (area > 0 && !double.IsInfinity(area) && + (area < state.BestArea || (area == state.BestArea && depth > state.BestDepth))) { - best = FindDeepestElementAtPoint(child, point, depth + 1, maxDepth, state); + state.Best = element; + state.BestArea = area; + state.BestDepth = depth; } - - child = TreeWalker.ControlViewWalker.GetNextSibling(child); } } - catch + catch (Exception) { /* An unreadable/empty container can still expose usable children. */ } + if (depth >= maxDepth) return; + try { - // The root/last usable element remains a valid fallback when a provider rejects a child query. + // Do not prune on container rectangles: raw virtual containers often have none. + AutomationElement child = TreeWalker.RawViewWalker.GetFirstChild(element); + while (child != null && state.Remaining > 0) + { + FindDeepestElementAtPoint(child, point, depth + 1, maxDepth, state); + // The recursive call consumes the child budget. Do not consume again here: + // doing so skipped every other raw child and made fallback hit testing unstable. + child = TreeWalker.RawViewWalker.GetNextSibling(child); + } } - - return best; + catch (Exception) { /* Keep the best actual hit, never an unrelated root fallback. */ } } /// @@ -301,7 +331,7 @@ namespace pacs_win_uia.Services lines.Add(level + ": " + DescribeElement(current, maxChildren)); try { - current = TreeWalker.ControlViewWalker.GetParent(current); + current = TreeWalker.RawViewWalker.GetParent(current); } catch (Exception ex) { @@ -324,7 +354,7 @@ namespace pacs_win_uia.Services try { - AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(element); + AutomationElement child = TreeWalker.RawViewWalker.GetFirstChild(element); int index = 0; while (child != null && index < maxChildren) { @@ -348,12 +378,12 @@ namespace pacs_win_uia.Services lines.Add(" 子元素 " + index + ": " + description); index++; - child = TreeWalker.ControlViewWalker.GetNextSibling(child); + child = TreeWalker.RawViewWalker.GetNextSibling(child); } if (index == 0) { - lines.Add(" 该元素没有暴露任何 ControlView 子元素。"); + lines.Add(" 该元素没有暴露任何 RawView 子元素。"); } } catch (Exception ex) @@ -399,7 +429,7 @@ namespace pacs_win_uia.Services string firstChildType = null; try { - AutomationElement child = TreeWalker.ControlViewWalker.GetFirstChild(element); + AutomationElement child = TreeWalker.RawViewWalker.GetFirstChild(element); while (child != null && childCount < maxChildren) { if (childCount == 0) @@ -410,7 +440,7 @@ namespace pacs_win_uia.Services } childCount++; - child = TreeWalker.ControlViewWalker.GetNextSibling(child); + child = TreeWalker.RawViewWalker.GetNextSibling(child); } } catch (Exception ex) @@ -586,7 +616,7 @@ namespace pacs_win_uia.Services { try { - AutomationElementCollection probe = element.FindAll(TreeScope.Children, Condition.TrueCondition); + AutomationElementCollection probe = element.FindAll(TreeScope.Children, Automation.RawViewCondition); if (probe == null || probe.Count == 0) { return node; @@ -606,11 +636,13 @@ namespace pacs_win_uia.Services try { + // RawViewCondition enumerates RawView children, exactly like RawViewWalker used + // by picking/ancestry helpers. The cache uses RawViewCondition too. // One bulk call per parent instead of one call per child plus one per sibling: with the // snapshot cache attached, every returned child arrives fully populated, so a node // costs the walker nothing at all. Child counts here are per-control, never the whole // desktop (the walk never descends from the root window). - AutomationElementCollection children = element.FindAll(TreeScope.Children, Condition.TrueCondition); + AutomationElementCollection children = element.FindAll(TreeScope.Children, Automation.RawViewCondition); foreach (AutomationElement child in children) { state.ThrowIfStopped(); diff --git a/src/pacs_win_uia/Services/WindowMatcher.cs b/src/pacs_win_uia/Services/WindowMatcher.cs index f3e18e6..c0567ac 100644 --- a/src/pacs_win_uia/Services/WindowMatcher.cs +++ b/src/pacs_win_uia/Services/WindowMatcher.cs @@ -99,8 +99,10 @@ namespace pacs_win_uia.Services default: if (!hasProcess) { - // Without a process name this would match every window: require one real clue. - return sameClass || sameTitle; + // Without a process name, every supplied clue remains mandatory. + if (!string.IsNullOrEmpty(className) && !sameClass) return false; + if (!string.IsNullOrEmpty(titleKeyword) && !sameTitle) return false; + return !string.IsNullOrEmpty(className) || !string.IsNullOrEmpty(titleKeyword); } return sameProcess; diff --git a/src/pacs_win_uia/Services/WindowVisibility.cs b/src/pacs_win_uia/Services/WindowVisibility.cs index 70e78db..8fab514 100644 --- a/src/pacs_win_uia/Services/WindowVisibility.cs +++ b/src/pacs_win_uia/Services/WindowVisibility.cs @@ -1,109 +1,212 @@ using System; +using System.Collections.Generic; using System.Drawing; +using System.Drawing.Drawing2D; using System.Windows.Forms; using pacs_win_uia.Interop; -using pacs_win_uia.Models; namespace pacs_win_uia.Services { - /// - /// "Would the operator actually see a frame drawn here?" A box over a minimized or covered window - /// points at nothing, so both the picker preview and the locate frame ask this first. - /// + /// Screen-coordinate visibility regions. Returned Regions belong to the caller. public static class WindowVisibility { - public static bool IsVisibleOnScreen( - IntPtr topLevelWindow, - Rectangle rect, - int ownProcessId, - out string reason) + public static bool IsForegroundWindow(IntPtr window) + { + IntPtr root = GetRoot(window); + return root != IntPtr.Zero && root == GetRoot(NativeMethods.GetForegroundWindow()); + } + + private static IntPtr GetRoot(IntPtr window) + { + return window == IntPtr.Zero ? IntPtr.Zero : NativeMethods.GetAncestor(window, NativeMethods.GA_ROOT); + } + + /// + /// Enumerates top-level windows in Z order, subtracting every visible window ahead of the + /// target. Only known tool overlays (or explicitly supplied overlay HWNDs) are ignored; + /// sharing our PID is NOT a reason to ignore a window (MainForm/SettingsForm occlude). + /// A GetWindowRgn shape is used when present, otherwise the DWM visible frame/Win32 bounds. + /// Per-pixel alpha/color-key holes of arbitrary layered windows are not available as HRGNs; + /// those windows conservatively occlude their window region. + /// + public static bool TryGetVisibleRegion(IntPtr targetWindow, bool requireForeground, + IEnumerable ignoredOverlayWindows, out Region visibleRegion, out string reason) + { + visibleRegion = null; + reason = null; + IntPtr target = GetRoot(targetWindow); + if (target == IntPtr.Zero || !NativeMethods.IsWindow(target)) + { + reason = "目标窗口已关闭。"; + return false; + } + if (!IsDrawable(target)) + { + reason = "目标窗口已最小化、隐藏或不在当前桌面。"; + return false; + } + if (requireForeground && !IsForegroundWindow(target)) + { + reason = "目标不是前台窗口。"; + return false; + } + + var ignored = ignoredOverlayWindows == null + ? new HashSet() : new HashSet(ignoredOverlayWindows); + Region result = CreateWindowRegion(target); + if (result == null) + { + reason = "无法读取目标窗口区域。"; + return false; + } + try + { + using (var screens = new Region()) + { + screens.MakeEmpty(); + foreach (Screen screen in Screen.AllScreens) screens.Union(screen.Bounds); + result.Intersect(screens); + } + bool reachedTarget = false; + NativeMethods.EnumWindows(delegate(IntPtr window, IntPtr unused) + { + if (window == target) + { + reachedTarget = true; + return false; + } + if (!ignored.Contains(window) && !IsToolOverlay(window) && IsDrawable(window)) + { + using (Region obstruction = CreateWindowRegion(window)) + { + if (obstruction != null) result.Exclude(obstruction); + } + } + return true; + }, IntPtr.Zero); + + // Recheck after enumeration as foreground/minimize can change during native calls. + if (!reachedTarget || !IsDrawable(target) || + (requireForeground && !IsForegroundWindow(target)) || !HasArea(result)) + { + reason = "目标不在前台、已隐藏或可见区域被完全遮挡。"; + return false; + } + visibleRegion = result; + result = null; + return true; + } + finally + { + if (result != null) result.Dispose(); + } + } + + private static bool IsDrawable(IntPtr window) + { + if (!NativeMethods.IsWindowVisible(window) || NativeMethods.IsIconic(window)) return false; + int cloaked; + return NativeMethods.DwmGetWindowAttribute(window, NativeMethods.DWMWA_CLOAKED, + out cloaked, sizeof(int)) != 0 || cloaked == 0; + } + + private static bool IsToolOverlay(IntPtr window) + { + // FromHandle only resolves this process's managed controls. Use exact type names so + // adding this service does not introduce dependencies on every UI implementation. + Control control = Control.FromHandle(window); + if (control == null) return false; + switch (control.GetType().FullName) + { + case "pacs_win_uia.UI.NodeMapOverlayForm": + case "pacs_win_uia.UI.NodeMapActionsForm": + case "pacs_win_uia.UI.HighlightOverlayForm": + case "pacs_win_uia.UI.PickerOverlayForm": + case "pacs_win_uia.UI.FloatingToolbarForm": + return true; + default: + return false; + } + } + + private static Region CreateWindowRegion(IntPtr window) + { + NativeMethods.RECT bounds; + if (!NativeMethods.GetWindowRect(window, out bounds)) return null; + IntPtr nativeRegion = NativeMethods.CreateRectRgn(0, 0, 0, 0); + if (nativeRegion == IntPtr.Zero) + throw new System.ComponentModel.Win32Exception(); + try + { + // ERROR (0) means no explicit window region. NULLREGION (1) is a real empty shape. + if (NativeMethods.GetWindowRgn(window, nativeRegion) != 0) + { + Region region = Region.FromHrgn(nativeRegion); + region.Translate(bounds.Left, bounds.Top); + region.Intersect(bounds.ToRectangle()); + return region; + } + } + finally + { + NativeMethods.DeleteObject(nativeRegion); + } + NativeMethods.RECT frame; + // DWMWA_EXTENDED_FRAME_BOUNDS excludes invisible resize borders on modern Windows. + if (NativeMethods.DwmGetWindowRectangle(window, 9, out frame, 16) == 0 && + frame.Right > frame.Left && frame.Bottom > frame.Top) + return new Region(frame.ToRectangle()); + return new Region(bounds.ToRectangle()); + } + + public static bool HasArea(Region region) + { + using (var identity = new Matrix()) return region.GetRegionScans(identity).Length != 0; + } + + /// + /// Compatibility API for callers which cannot clip their frame: true only when the requested + /// on-screen rectangle is unobstructed. ownProcessId is retained but never exempts main/settings. + /// Unlike the node map, these older callers need not target the foreground window. + /// + public static bool IsVisibleOnScreen(IntPtr topLevelWindow, Rectangle rect, + int ownProcessId, out string reason) { reason = null; - if (rect.Width <= 1 || rect.Height <= 1) + if (rect.Width <= 1 || rect.Height <= 1 || !SystemInformation.VirtualScreen.IntersectsWith(rect)) { - reason = "矩形过小,无法判断可见性。"; + reason = "矩形过小或不在屏幕范围内。"; return false; } - - if (topLevelWindow != IntPtr.Zero) + if (topLevelWindow == IntPtr.Zero) return true; + Region visible; + if (!TryGetVisibleRegion(topLevelWindow, false, null, out visible, out reason)) return false; + using (visible) + using (Region missing = CreateWindowRegion(GetRoot(topLevelWindow))) { - if (!NativeMethods.IsWindow(topLevelWindow)) + if (missing == null) { - reason = "目标窗口已关闭。"; + reason = "无法读取目标窗口区域。"; return false; } - - if (NativeMethods.IsIconic(topLevelWindow)) + // Do not mistake DWM's invisible resize border or off-screen portions for occlusion. + missing.Intersect(rect); + using (var screens = new Region()) { - reason = "目标窗口已最小化,屏幕上没有它的画面。"; + screens.MakeEmpty(); + foreach (Screen screen in Screen.AllScreens) screens.Union(screen.Bounds); + missing.Intersect(screens); + } + if (!HasArea(missing)) + { + reason = "矩形不在目标的可见窗口范围内。"; return false; } - - if (!NativeMethods.IsWindowVisible(topLevelWindow)) - { - reason = "目标窗口当前不可见(已隐藏或未显示)。"; - return false; - } - } - - if (!SystemInformation.VirtualScreen.IntersectsWith(rect)) - { - reason = "矩形不在可见屏幕范围内。"; + missing.Exclude(visible); + if (!HasArea(missing)) return true; + reason = "该区域部分或全部被其他窗口遮挡。"; return false; } - - // Sample a few points: whatever is on top there must belong to the target, otherwise the - // window is covered. Our own windows are ignored (the highlight frame and the picker - // overlay are both ours and sit above everything). - Point[] samples = - { - new Point(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2), - new Point(rect.Left + rect.Width / 4, rect.Top + rect.Height / 4), - new Point(rect.Left + rect.Width * 3 / 4, rect.Top + rect.Height / 4), - new Point(rect.Left + rect.Width / 4, rect.Top + rect.Height * 3 / 4), - new Point(rect.Left + rect.Width * 3 / 4, rect.Top + rect.Height * 3 / 4) - }; - - int checkedPoints = 0; - IntPtr targetRoot = topLevelWindow == IntPtr.Zero - ? IntPtr.Zero - : NativeMethods.GetAncestor(topLevelWindow, NativeMethods.GA_ROOT); - - foreach (Point point in samples) - { - IntPtr under = NativeMethods.WindowFromPoint(point); - if (under == IntPtr.Zero) - { - continue; - } - - uint processId; - NativeMethods.GetWindowThreadProcessId(under, out processId); - if (ownProcessId > 0 && unchecked((int)processId) == ownProcessId) - { - // Our own overlay: it does not count as an obstruction. - continue; - } - - checkedPoints++; - IntPtr underRoot = NativeMethods.GetAncestor(under, NativeMethods.GA_ROOT); - bool sameWindow = topLevelWindow == IntPtr.Zero - || under == topLevelWindow - || (targetRoot != IntPtr.Zero && underRoot == targetRoot); - if (!sameWindow) - { - reason = "该区域被其他窗口遮挡(" + NativeWindowInfo.FormatHandle(under) + "),屏幕上看不到它。"; - return false; - } - } - - if (checkedPoints == 0 && topLevelWindow != IntPtr.Zero) - { - reason = "无法确认该区域是否可见(取样点全部落在本工具窗口上)。"; - return false; - } - - return true; } } } diff --git a/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs b/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs index 3db463a..770e2dc 100644 --- a/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs +++ b/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs @@ -21,6 +21,18 @@ namespace pacs_win_uia.UI IntPtr anchorWindow, bool usedFallback, IList steps) + : this(definition, node, bounds, anchorWindow, usedFallback, steps, true) + { + } + + public ControlLocatedEventArgs( + Models.ControlMonitorDefinition definition, + Models.ControlTreeNode node, + Models.NativeRectangleInfo bounds, + IntPtr anchorWindow, + bool usedFallback, + IList steps, + bool isExplicit) { Definition = definition; Node = node; @@ -28,11 +40,19 @@ namespace pacs_win_uia.UI AnchorWindow = anchorWindow; Steps = steps; UsedFallback = usedFallback; + Explicit = isExplicit; } /// True when the control was located through a tolerant path (position may be off). public bool UsedFallback { get; private set; } + /// + /// True when the operator asked for this directly (定位按钮 / 行头 / 悬浮按钮), false when it + /// is the automatic locate that follows a click in the grid. Only the explicit request toggles + /// the frame off; a click must always show it. + /// + public bool Explicit { get; private set; } + /// Top-level window the control lives in; used to hide the frame when it goes away. public IntPtr AnchorWindow { get; private set; } @@ -75,13 +95,16 @@ namespace pacs_win_uia.UI /// public sealed class ControlMonitorEditorControl : UserControl { + /// One click raises SelectionChanged and CellClick; this dedupes the pair (ms). + private const int AutoLocateDedupeMs = 300; + private const int ColumnEnabled = 0; private const int ColumnPath = 1; - private const int ColumnAlias = 2; - private const int ColumnSource = 3; - private const int ColumnValueKey = 4; - private const int ColumnFocus = 5; - private const int ColumnTimeout = 6; + private const int ColumnSource = 2; + private const int ColumnValueKey = 3; + private const int ColumnFocus = 4; + private const int ColumnTimeout = 5; + private const int ColumnAlias = 6; private readonly ControlMonitorStore _store; private readonly ControlLocatorBuilder _locatorBuilder; @@ -98,12 +121,51 @@ namespace pacs_win_uia.UI private readonly Label _messageLabel; private readonly DataGridViewComboBoxColumn _valueKeyColumn; private ControlTreeNode _currentNode; + private ControlTreeNode _currentTreeRoot; + + public void SetTreeRoot(ControlTreeNode root) + { + _currentTreeRoot = root; + } + + public void SetRefreshInterval(int milliseconds) + { + _stateTimer.Interval = Math.Max(100, Math.Min(60000, milliseconds)); + } private NativeWindowInfo _currentWindow; private bool _dirty; private readonly System.Windows.Forms.Timer _stateTimer; private readonly CheckBox _autoStateCheck; private int _stateCursor; private bool _stateRefreshInFlight; + /// + /// The row/cell the last automatic locate was started for. Clicking another row — or another + /// cell of the same row — is an explicit "show me where this is". + /// + private int _lastAutoLocateRow = -1; + private int _lastAutoLocateColumn = -1; + private int _lastAutoLocateTick; + /// Every locate request gets a number; a slow one that has been superseded is dropped. + private int _locateRequest; + /// True while the grid is being re-bound: no selection event is a user action then. + private bool _loading; + private bool _editingCell; + private bool _pathEditorOpen; + private bool _suppressAutoLocateUntilIdle; + private readonly Dictionary _locatorVersions = + new Dictionary(); + + private sealed class LocatorVersion + { + internal string Path; + internal ControlSourcePreference Source; + internal int Revision; + } + + private bool IsEditing + { + get { return _editingCell || _pathEditorOpen || _grid.IsCurrentCellInEditMode; } + } public ControlMonitorEditorControl() : this(new ControlMonitorStore(), new ControlLocatorBuilder()) @@ -169,7 +231,7 @@ namespace pacs_win_uia.UI { HeaderText = "控件Path", DataPropertyName = "ControlPath", - ReadOnly = true, + ReadOnly = false, AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, FillWeight = 46, MinimumWidth = 150 @@ -253,7 +315,7 @@ namespace pacs_win_uia.UI _refreshStatesButton.Click += delegate { RefreshAllStates(); }; // Clicking the row-header triangle jumps to the control on screen. _grid.RowHeaderMouseClick += delegate { LocateCurrentDefinition(); }; - _grid.SelectionChanged += delegate { RaiseDefinitionSelected(); }; + _grid.SelectionChanged += GridOnSelectionChanged; _stateTimer = new System.Windows.Forms.Timer { Interval = 3000 }; _stateTimer.Tick += StateTimerOnTick; _stateTimer.Start(); @@ -261,7 +323,12 @@ namespace pacs_win_uia.UI _grid.RowsAdded += delegate { MarkDirty(); }; _grid.UserDeletedRow += delegate { MarkDirty(); }; _grid.DataError += GridOnDataError; - _grid.CellEndEdit += delegate { RefreshValidation(); }; + _grid.CellEndEdit += delegate + { + _editingCell = false; + SuppressAutoLocateForCurrentEvent(); + RefreshValidation(); + }; _grid.RowValidated += delegate { RefreshValidation(); }; _grid.CellBeginEdit += GridOnCellBeginEdit; _grid.CellValidating += GridOnCellValidating; @@ -269,13 +336,19 @@ namespace pacs_win_uia.UI { // Commit a checkbox click immediately; without this the toggle is not written to the // object until the user happens to leave the cell. - if (_grid.IsCurrentCellDirty) + if (_grid.IsCurrentCellDirty && _grid.CurrentCell is DataGridViewCheckBoxCell) { _grid.CommitEdit(DataGridViewDataErrorContexts.Commit); } }; _grid.SelectionChanged += delegate { ShowSelectedLocator(); }; - + _grid.CellClick += GridOnCellClick; + _grid.CellDoubleClick += GridOnCellDoubleClick; + _grid.CellToolTipTextNeeded += GridOnCellToolTipNeeded; + _grid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText; + _grid.ContextMenuStrip = BuildGridMenu(); + // LoadFromStore resets the auto-locate bookkeeping: the selection it produces is not a + // user action. LoadFromStore(); } @@ -299,6 +372,23 @@ namespace pacs_win_uia.UI /// Raised when the selected row changes, so the property grid can edit that entry. public event EventHandler DefinitionSelected; + /// Right-click menu: the read-only columns have to be copyable. + private ContextMenuStrip BuildGridMenu() + { + var menu = new ContextMenuStrip(); + var copyCell = new ToolStripMenuItem("复制单元格文本"); + copyCell.Click += delegate { CopyCurrentCell(); }; + var copyRow = new ToolStripMenuItem("复制整行(表头 + 内容,制表符分隔)"); + copyRow.Click += delegate { CopyCurrentRow(); }; + var locate = new ToolStripMenuItem("定位到该控件并画框"); + locate.Click += delegate { LocateCurrentDefinition(); }; + menu.Items.Add(copyCell); + menu.Items.Add(copyRow); + menu.Items.Add(new ToolStripSeparator()); + menu.Items.Add(locate); + return menu; + } + public bool HasUnsavedChanges { get { return _dirty; } @@ -322,8 +412,8 @@ namespace pacs_win_uia.UI { try { - _bindingSource.EndEdit(); _grid.EndEdit(); + _bindingSource.EndEdit(); } catch (Exception ex) { @@ -334,7 +424,22 @@ namespace pacs_win_uia.UI public void LoadFromStore() { CommitEdits(); + _loading = true; + try + { + LoadFromStoreCore(); + } + finally + { + _loading = false; + _lastAutoLocateRow = _bindingSource.Position; + _lastAutoLocateColumn = -1; + _locateRequest++; + } + } + private void LoadFromStoreCore() + { List loaded; try { @@ -352,9 +457,11 @@ namespace pacs_win_uia.UI try { _definitions.Clear(); + _locatorVersions.Clear(); foreach (ControlMonitorDefinition definition in loaded) { _definitions.Add(definition); + TrackLocator(definition); } } finally @@ -371,6 +478,11 @@ namespace pacs_win_uia.UI } _bindingSource.ResetBindings(false); + // Loading is not a user selection: it must not fire a locate, and any locate still in + // flight belongs to the row list that has just been replaced. + _lastAutoLocateRow = _bindingSource.Position; + _lastAutoLocateColumn = -1; + _locateRequest++; _dirty = false; AppLog.Info("已加载 " + _definitions.Count + " 条控件监控定义:" + _store.FilePath); RefreshValidation(); @@ -379,17 +491,41 @@ namespace pacs_win_uia.UI private void AddCurrentControl() { + string message; + if (AddCurrentNode(true, out message) == null) + { + Report(message, null); + return; + } + + Report(message, null); + } + + /// + /// Snapshots the current node as a monitor entry and appends it. + /// + /// is false for the automatic entry the picker creates: the control + /// is recorded (with its locator) so the operator only has to tick 启用, but nothing reads it + /// until they do and save. + /// + public ControlMonitorDefinition AddCurrentNode(bool enabled, out string message) + { + message = null; ControlTreeNode node = _currentNode; if (node == null) { - Report("请先拾取或选中一个控件。", null); - return; + message = "请先拾取或选中一个控件。"; + return null; } ControlLocatorBuildResult locator; try { - if (node.Source == ControlTreeSource.Msaa) + if (_currentTreeRoot != null) + { + locator = _locatorBuilder.BuildFromTree(_currentTreeRoot, node, _currentWindow); + } + else if (node.Source == ControlTreeSource.Msaa) { locator = _locatorBuilder.BuildFromMsaa(node.Msaa, _currentWindow); } @@ -406,14 +542,12 @@ namespace pacs_win_uia.UI { AppLog.Error("生成控件定位信息失败。", ex); Report("生成控件定位信息失败:" + ex.Message, ex); - return; + return null; } var definition = new ControlMonitorDefinition { - ControlPath = string.IsNullOrEmpty(locator.DisplayPath) - ? "(" + node.Source + ":窗口本身)" - : "[" + node.Source + "] " + locator.DisplayPath, + ControlPath = locator.DisplayPath, Source = locator.Source, ProcessName = locator.ProcessName, WindowClass = locator.WindowClass, @@ -424,7 +558,9 @@ namespace pacs_win_uia.UI Value = locator.Value, FocusState = "未读取", PageFeatures = BuildPageFeatures(locator), - ContentKey = SuggestContentKey(node) + ContentKey = SuggestContentKey(node), + Enabled = enabled, + UiaPathFromInnerWindow = locator.UiaPathFromInnerWindow }; if (locator.UiaPath != null) { @@ -437,14 +573,27 @@ namespace pacs_win_uia.UI } CommitEdits(); + TrackLocator(definition); _definitions.Add(definition); - _bindingSource.Position = _definitions.Count - 1; + if (enabled) + { + // Only the manual action moves the selection; the picker's automatic entry must not + // yank the grid away from whatever row the operator was working on. + _bindingSource.Position = _definitions.Count - 1; + _lastAutoLocateRow = _bindingSource.Position; + _lastAutoLocateColumn = -1; + } + MarkDirty(); RefreshValidation(); ShowSelectedLocator(); - Report(locator.IsComplete - ? "已添加当前控件(" + locator.Source + ",属性 " + locator.ValueKey + "),请确认后保存。" - : "已添加当前控件,但定位路径不完整:" + (locator.Note ?? "未知原因"), null); + message = locator.IsComplete + ? "已添加当前控件(" + locator.Source + ",属性 " + locator.ValueKey + "," + + (enabled ? "已启用" : "未启用") + "),请确认后保存。" + + (string.IsNullOrEmpty(locator.Note) ? string.Empty : " " + locator.Note) + : "已添加当前控件(" + (enabled ? "已启用" : "未启用") + "),但定位路径不完整:" + + (locator.Note ?? "未知原因"); + return definition; } /// The page feature suggestion is exactly the window identification that gets saved. @@ -490,6 +639,8 @@ namespace pacs_win_uia.UI } ControlMonitorDefinition removed = _definitions[index]; + if (removed != null) _locatorVersions.Remove(removed); + _locateRequest++; _definitions.RemoveAt(index); MarkDirty(); RefreshValidation(); @@ -549,6 +700,8 @@ namespace pacs_win_uia.UI /// Offers the keys that make sense for the row's source, while still allowing any text. private void GridOnCellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { + _editingCell = true; + _locateRequest++; // A click-to-locate started before F2/double-click must not interrupt editing. if (e.ColumnIndex != ColumnValueKey) { return; @@ -604,77 +757,484 @@ namespace pacs_win_uia.UI private void OnCellValueChanged(object sender, DataGridViewCellEventArgs e) { + if (_loading || e.RowIndex < 0) return; MarkDirty(); - if (e.ColumnIndex == ColumnEnabled || e.ColumnIndex == ColumnSource || - e.ColumnIndex == ColumnValueKey || e.ColumnIndex == ColumnTimeout) + if (e.ColumnIndex == ColumnPath || e.ColumnIndex == ColumnSource) + { + var definition = _grid.Rows[e.RowIndex].DataBoundItem as ControlMonitorDefinition; + NotifyDefinitionChanged(definition); + } + else if (e.ColumnIndex == ColumnEnabled || e.ColumnIndex == ColumnValueKey || + e.ColumnIndex == ColumnTimeout) { RefreshValidation(); } } + private LocatorVersion TrackLocator(ControlMonitorDefinition definition) + { + if (definition == null) return null; + LocatorVersion version; + if (!_locatorVersions.TryGetValue(definition, out version)) + { + version = new LocatorVersion { Path = definition.ControlPath, Source = definition.Source }; + _locatorVersions.Add(definition, version); + } + return version; + } + + /// Call after PropertyGrid edits too; setters accept unfinished text for repair. + public void NotifyDefinitionChanged(ControlMonitorDefinition definition) + { + if (definition == null || !_definitions.Contains(definition)) return; + LocatorVersion version = TrackLocator(definition); + if (!string.Equals(version.Path, definition.ControlPath, StringComparison.Ordinal) || + version.Source != definition.Source) + { + version.Path = definition.ControlPath; + version.Source = definition.Source; + version.Revision++; + _locateRequest++; + definition.FocusState = "未读取(路径已更改)"; + SetRowError(definition, null); + } + MarkDirty(); + RefreshValidation(); + _grid.Invalidate(); + } + + private bool IsCurrentLocator(ControlMonitorDefinition definition, + ControlMonitorDefinition snapshot, int revision) + { + LocatorVersion version; + return definition != null && _definitions.Contains(definition) && + _locatorVersions.TryGetValue(definition, out version) && version.Revision == revision && + string.Equals(definition.ControlPath, snapshot.ControlPath, StringComparison.Ordinal) && + definition.Source == snapshot.Source; + } + + private void SuppressAutoLocateForCurrentEvent() + { + _suppressAutoLocateUntilIdle = true; + if (IsHandleCreated && !IsDisposed) + BeginInvoke((Action)delegate { _suppressAutoLocateUntilIdle = false; }); + else + _suppressAutoLocateUntilIdle = false; + } + + /// What one locate attempt produced, carried from the worker thread back to the UI. + private sealed class LocateOutcome + { + internal bool Found; + internal string Error; + internal ControlResolution Resolution; + internal string Focus; + internal IList Steps; + internal long ElapsedMs; + internal bool Explicit; + } + + /// + /// Selecting a row is the everyday way of asking "where is this control?": it locates the + /// entry, so the owner can expand the control tree to it and draw the frame. Cell edits inside + /// the same row do not re-trigger it. + /// + private void GridOnSelectionChanged(object sender, EventArgs e) + { + RaiseDefinitionSelected(); + if (_loading) + { + return; + } + + RequestAutoLocate(); + } + + /// + /// Non-editing clicks locate the row; path clicks are reserved for editing (F2/double-click). + /// + private void GridOnCellClick(object sender, DataGridViewCellEventArgs e) + { + if (_loading || e.RowIndex < 0) + { + return; + } + + RequestAutoLocate(); + } + + /// + /// One click raises SelectionChanged *and* CellClick; the second one must not start a second + /// resolution, but clicking the same cell again later must locate again. + /// + private void RequestAutoLocate() + { + if (_loading || IsEditing || _suppressAutoLocateUntilIdle || + (_grid.CurrentCell != null && _grid.CurrentCell.ColumnIndex == ColumnPath)) return; + int position = _bindingSource.Position; + if (position < 0 || position >= _definitions.Count) + { + return; + } + + DataGridViewCell cell = _grid.CurrentCell; + int column = cell == null ? -1 : cell.ColumnIndex; + int now = Environment.TickCount; + if (position == _lastAutoLocateRow && column == _lastAutoLocateColumn && + unchecked(now - _lastAutoLocateTick) < AutoLocateDedupeMs) + { + return; + } + + _lastAutoLocateRow = position; + _lastAutoLocateColumn = column; + _lastAutoLocateTick = now; + StartLocate(SelectedDefinition(), false, "点击定位"); + } + + /// Copies the current cell's text: read-only cells have to be readable somehow. + private void CopyCurrentCell() + { + DataGridViewCell cell = _grid.CurrentCell; + string text = cell == null || cell.Value == null ? null : Convert.ToString(cell.Value); + if (string.IsNullOrEmpty(text)) + { + Report("当前单元格没有可复制的内容。", null); + return; + } + + SetClipboard(text, "已复制单元格内容:" + text); + } + + /// Copies the selected row as tab-separated text (usable in Excel). + private void CopyCurrentRow() + { + int index = _bindingSource.Position; + if (index < 0 || index >= _grid.Rows.Count) + { + Report("请先选中要复制的行。", null); + return; + } + + var builder = new StringBuilder(); + DataGridViewRow row = _grid.Rows[index]; + var headers = new StringBuilder(); + for (int column = 0; column < _grid.Columns.Count; column++) + { + object value = row.Cells[column].Value; + string text = value is bool + ? ((bool)value ? "是" : "否") + : (value == null ? string.Empty : Convert.ToString(value)); + if (column > 0) + { + builder.Append('\t'); + headers.Append('\t'); + } + + builder.Append(text); + headers.Append(_grid.Columns[column].HeaderText); + } + + SetClipboard(headers.ToString() + Environment.NewLine + builder.ToString(), + "已复制该行(表头 + 内容):" + Environment.NewLine + builder); + } + + private void SetClipboard(string text, string report) + { + try + { + Clipboard.SetText(text); + Report(report, null); + } + catch (Exception ex) + { + AppLog.Warn("复制到剪贴板失败。", ex); + Report("复制失败:" + ex.Message, ex); + } + } + + /// Long values (the control path) are cut off by the column width; show them in full. + private void GridOnCellToolTipNeeded(object sender, DataGridViewCellToolTipTextNeededEventArgs e) + { + if (e.RowIndex < 0 || e.ColumnIndex < 0) + { + return; + } + + object value = _grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; + string text = value == null ? null : Convert.ToString(value); + if (!string.IsNullOrEmpty(text)) + { + e.ToolTipText = text; + } + } + + private void GridOnCellDoubleClick(object sender, DataGridViewCellEventArgs e) + { + if (e.RowIndex < 0 || e.ColumnIndex < 0) + { + return; + } + + if (e.ColumnIndex == ColumnPath) + { + EditControlPath(_grid.Rows[e.RowIndex].DataBoundItem as ControlMonitorDefinition); + return; + } + + // Other read-only columns retain their copy shortcut. + if (!_grid.Columns[e.ColumnIndex].ReadOnly) + { + return; + } + + CopyCurrentCell(); + } + + private void EditControlPath(ControlMonitorDefinition definition) + { + if (definition == null || _pathEditorOpen) return; + _pathEditorOpen = true; + _locateRequest++; + try + { + CommitEdits(); + ControlMonitorDefinition template = Snapshot(definition); + using (var editor = new ControlPathEditorForm(definition.ControlPath, delegate(string path) + { + // A separate snapshot for each test: never mutate the live row on the worker. + ControlMonitorDefinition candidate = Snapshot(template); + candidate.ControlPath = path; + var locator = new ControlLocatorService(); + var steps = new List(); + string error; + IntPtr window = locator.FindTargetWindow(candidate, steps, out error); + if (window == IntPtr.Zero) return error ?? "没有找到目标窗口。"; + ControlResolution resolution = locator.Resolve(candidate, window, steps); + return resolution.Found ? null : resolution.Error ?? "控件未唯一定位。"; + })) + { + if (editor.ShowDialog(this) != DialogResult.OK) return; + definition.ControlPath = editor.PathText; + NotifyDefinitionChanged(definition); + _bindingSource.ResetCurrentItem(); + Report("控件 XPath 已更新,请保存监控列表。", null); + } + } + finally + { + _pathEditorOpen = false; + SuppressAutoLocateForCurrentEvent(); + } + } + /// /// Resolves the selected entry and asks the owner to highlight it on screen. Also records the /// focus state, which is exactly what the 焦点 column shows. + /// + /// The resolution walks other processes (window enumeration, UIA/MSAA reads) and can take + /// seconds on a busy PACS client, so it runs on a worker thread; the result is applied on the + /// UI thread and dropped if another row has been selected meanwhile. /// public void LocateCurrentDefinition() { CommitEdits(); - ControlMonitorDefinition definition = SelectedDefinition(); + StartLocate(SelectedDefinition(), true, "定位到控件"); + } + + /// + /// True for 定位按钮 / 行头 / 悬浮按钮: only those toggle the frame off when the same entry is + /// asked for twice. A click in the grid always shows the frame. + /// + private void StartLocate(ControlMonitorDefinition definition, bool isExplicit, string trigger) + { if (definition == null) { Report("请先选中要定位的监控条目。", null); return; } - TimeSpan timeout = definition.TimeoutSeconds > 0 - ? TimeSpan.FromSeconds(definition.TimeoutSeconds) - : TimeSpan.FromSeconds(5); - var steps = new List(); - var stopwatch = System.Diagnostics.Stopwatch.StartNew(); - string error; - IntPtr window = _locatorService.FindTargetWindow(definition, steps, out error); - if (window == IntPtr.Zero) + int request = ++_locateRequest; + string syntaxError = ControlMonitorRules.ValidateControlPath(definition.ControlPath); + if (syntaxError != null) { - MarkRowError(definition, error ?? "没有找到目标窗口。"); - Report("定位失败:" + error, null); + MarkRowError(definition, syntaxError); + Report("定位失败:" + syntaxError, null); + return; + } + int revision = TrackLocator(definition).Revision; + ControlMonitorDefinition snapshot = Snapshot(definition); + string name = definition.ContentKey; + Report("正在定位「" + name + "」(" + trigger + ")……", null); + + Task.Factory.StartNew( + delegate + { + var stopwatch = System.Diagnostics.Stopwatch.StartNew(); + var steps = new List(); + var outcome = new LocateOutcome { Steps = steps, Explicit = isExplicit }; + try + { + var locator = new ControlLocatorService(); + string error; + IntPtr window = locator.FindTargetWindow(snapshot, steps, out error); + if (window == IntPtr.Zero) + { + outcome.Error = error ?? "没有找到目标窗口。"; + return outcome; + } + + ControlResolution resolution = locator.Resolve(snapshot, window, steps); + if (!resolution.Found) + { + outcome.Error = resolution.Error ?? "控件未定位到。"; + return outcome; + } + + outcome.Found = true; + outcome.Resolution = resolution; + string focus; + string focusError; + if (ControlValueReader.TryRead( + resolution.Node, ControlValueKeys.Focused, new ListReadOptions(), out focus, out focusError)) + { + outcome.Focus = focus; + } + else + { + outcome.Focus = "(读不到)"; + steps.Add("焦点状态:" + focusError); + } + + return outcome; + } + catch (Exception ex) + { + outcome.Error = ex.GetType().Name + ": " + ex.Message; + AppLog.Debug("定位控件失败:" + outcome.Error); + return outcome; + } + finally + { + stopwatch.Stop(); + outcome.ElapsedMs = stopwatch.ElapsedMilliseconds; + } + }, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default) + .ContinueWith( + delegate(Task completed) + { + if (completed.IsFaulted || completed.IsCanceled) + { + return; + } + + try + { + if (IsHandleCreated && !IsDisposed) + { + BeginInvoke((Action)delegate + { + ApplyLocateResult(request, definition, snapshot, revision, completed.Result); + }); + } + } + catch (Exception) + { + // The control is going away. + } + }, + CancellationToken.None, + TaskContinuationOptions.None, + TaskScheduler.Default); + } + + /// A copy of the locator fields: the operator may edit or delete the row while the read runs. + private static ControlMonitorDefinition Snapshot(ControlMonitorDefinition definition) + { + var snapshot = new ControlMonitorDefinition + { + Id = definition.Id, + ControlPath = definition.ControlPath, + Source = definition.Source, + ProcessName = definition.ProcessName, + WindowClass = definition.WindowClass, + WindowTitleKeyword = definition.WindowTitleKeyword, + MsaaPathKey = definition.MsaaPathKey, + RuntimeId = definition.RuntimeId, + ValueKey = definition.ValueKey, + UiaPathFromInnerWindow = definition.UiaPathFromInnerWindow, + TimeoutSeconds = definition.TimeoutSeconds + }; + if (definition.UiaPath != null) + { + foreach (ControlLocatorSegment segment in definition.UiaPath) + { + snapshot.UiaPath.Add(segment == null ? null : new ControlLocatorSegment + { + ControlType = segment.ControlType, + Name = segment.Name, + AutomationId = segment.AutomationId, + ClassName = segment.ClassName, + Index = segment.Index + }); + } + } + + if (definition.Win32Path != null) + { + foreach (Win32LocatorSegment segment in definition.Win32Path) + { + snapshot.Win32Path.Add(segment == null ? null : new Win32LocatorSegment + { + ClassName = segment.ClassName, + Index = segment.Index + }); + } + } + + return snapshot; + } + + private void ApplyLocateResult(int request, ControlMonitorDefinition definition, + ControlMonitorDefinition snapshot, int revision, LocateOutcome outcome) + { + if (IsDisposed || IsEditing || outcome == null || request != _locateRequest || + !ReferenceEquals(SelectedDefinition(), definition) || + !IsCurrentLocator(definition, snapshot, revision)) + { + // Includes edits of the same row (even A -> B -> A), deletion and reloading. return; } - ControlResolution resolution = _locatorService.Resolve(definition, window, steps); - if (!resolution.Found) + if (!outcome.Found) { - MarkRowError(definition, resolution.Error ?? "控件未定位到。"); - Report("定位失败:" + resolution.Error, null); + definition.FocusState = "(未找到)"; + MarkRowError(definition, outcome.Error ?? "控件未定位到。"); + _grid.Refresh(); + Report("定位失败:" + (outcome.Error ?? "控件未定位到。"), null); return; } - string focus; - string focusError; - if (ControlValueReader.TryRead(resolution.Node, ControlValueKeys.Focused, new ListReadOptions(), out focus, out focusError)) - { - definition.FocusState = focus; - } - else - { - definition.FocusState = "(读不到)"; - steps.Add("焦点状态:" + focusError); - } - + definition.FocusState = outcome.Focus; + SetRowError(definition, null); _grid.Refresh(); - stopwatch.Stop(); AppLog.Info(string.Format("定位到控件:{0};来源 {1};焦点 {2};耗时 {3} ms;步骤:{4}", - definition.ContentKey, resolution.ResolvedSource, definition.FocusState, - stopwatch.ElapsedMilliseconds, string.Join(" / ", steps.ToArray()))); + definition.ContentKey, outcome.Resolution.ResolvedSource, definition.FocusState, + outcome.ElapsedMs, string.Join(" / ", new List(outcome.Steps).ToArray()))); EventHandler handler = ControlLocated; if (handler != null) { - handler(this, new ControlLocatedEventArgs(definition, resolution.Node, - BoundsOf(resolution.Node), resolution.WindowHandle, resolution.UsedFallback, steps)); + handler(this, new ControlLocatedEventArgs(definition, outcome.Resolution.Node, + BoundsOf(outcome.Resolution.Node), outcome.Resolution.WindowHandle, + outcome.Resolution.UsedFallback, outcome.Steps, outcome.Explicit)); } Report(string.Format("已定位到「{0}」({1}),焦点:{2}", - definition.ContentKey, resolution.ResolvedSource, definition.FocusState), null); + definition.ContentKey, outcome.Resolution.ResolvedSource, definition.FocusState), null); } /// @@ -762,7 +1322,7 @@ namespace pacs_win_uia.UI /// private void StateTimerOnTick(object sender, EventArgs e) { - if (IsDisposed || _stateRefreshInFlight || !_autoStateCheck.Checked || _definitions.Count == 0) + if (IsDisposed || IsEditing || _stateRefreshInFlight || !_autoStateCheck.Checked || _definitions.Count == 0) { return; } @@ -785,27 +1345,8 @@ namespace pacs_win_uia.UI private void RefreshFocusStateAsync(int index, ControlMonitorDefinition definition) { _stateRefreshInFlight = true; - // Copy the locator fields: the operator may edit the row while the read is in flight. - var snapshot = new ControlMonitorDefinition - { - Id = definition.Id, - ControlPath = definition.ControlPath, - Source = definition.Source, - ProcessName = definition.ProcessName, - WindowClass = definition.WindowClass, - WindowTitleKeyword = definition.WindowTitleKeyword, - MsaaPathKey = definition.MsaaPathKey, - ValueKey = definition.ValueKey - }; - if (definition.UiaPath != null) - { - snapshot.UiaPath.AddRange(definition.UiaPath); - } - - if (definition.Win32Path != null) - { - snapshot.Win32Path.AddRange(definition.Win32Path); - } + int revision = TrackLocator(definition).Revision; + ControlMonitorDefinition snapshot = Snapshot(definition); Task.Factory.StartNew( delegate @@ -858,18 +1399,14 @@ namespace pacs_win_uia.UI { BeginInvoke((Action)delegate { - if (IsDisposed || index >= _definitions.Count) + if (IsDisposed || IsEditing || index >= _definitions.Count || + !ReferenceEquals(_definitions[index], definition) || + !IsCurrentLocator(definition, snapshot, revision)) { return; } - ControlMonitorDefinition target = _definitions[index]; - if (target == null || !ReferenceEquals(target.Id, definition.Id)) - { - return; - } - - target.FocusState = completed.Result; + definition.FocusState = completed.Result; _grid.Refresh(); }); } diff --git a/src/pacs_win_uia/UI/ControlPathEditorForm.cs b/src/pacs_win_uia/UI/ControlPathEditorForm.cs new file mode 100644 index 0000000..e10cb0b --- /dev/null +++ b/src/pacs_win_uia/UI/ControlPathEditorForm.cs @@ -0,0 +1,141 @@ +using System; +using System.Drawing; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using pacs_win_uia.Models; + +namespace pacs_win_uia.UI +{ + /// Edits plain XPath text; optional resolution runs off the UI thread on a snapshot. + public sealed class ControlPathEditorForm : Form + { + internal const string XPathHelp = + "XPath 1.0:/ 从所选窗口根开始,/ 子级,// 后代,* 任意控件,[1] 同级序号(从 1 开始)。\r\n" + + "示例:/Window//Button[@Name='确定'] 或 //*[@AutomationId='saveButton']\r\n" + + "属性:@Name、@AutomationId、@ClassName、@Source;可用 and、or、contains(@Name,'文本')。\r\n" + + "UIA / MSAA / Win32 均使用 XPath;不要加 [Uia] 等前缀或旧的 > 分隔路径。\r\n" + + "定位必须唯一匹配控件元素;0 个、多个匹配或属性/文本结果均报错。"; + + private readonly TextBox _path; + private readonly Label _status; + private readonly Button _testButton; + private readonly Func _testLocate; + private int _textRevision; + private bool _testing; + + /// Optional worker callback; returns null for one match, or an error. + public ControlPathEditorForm(string initialPath, Func testLocate) + { + Text = "编辑控件 XPath"; + StartPosition = FormStartPosition.CenterParent; + MinimumSize = new Size(640, 410); + Size = new Size(850, 500); + ShowInTaskbar = false; + _testLocate = testLocate; + + var help = new TextBox + { + Dock = DockStyle.Top, + Height = 116, + Multiline = true, + ReadOnly = true, + BorderStyle = BorderStyle.None, + BackColor = SystemColors.Control, + ScrollBars = ScrollBars.Vertical, + Text = XPathHelp + }; + _path = new TextBox + { + Dock = DockStyle.Fill, + Multiline = true, + AcceptsReturn = true, + ScrollBars = ScrollBars.Both, + WordWrap = false, + Text = initialPath ?? string.Empty + }; + _status = new Label + { + Dock = DockStyle.Bottom, + Height = 56, + Padding = new Padding(6), + AutoEllipsis = true + }; + var buttons = new FlowLayoutPanel + { + Dock = DockStyle.Bottom, + Height = 44, + FlowDirection = FlowDirection.RightToLeft, + Padding = new Padding(6) + }; + var cancel = new Button { Text = "取消", AutoSize = true, DialogResult = DialogResult.Cancel }; + var save = new Button { Text = "保存", AutoSize = true }; + save.Click += delegate + { + if (!ValidatePath()) return; + DialogResult = DialogResult.OK; + Close(); + }; + _testButton = new Button { Text = "测试定位", AutoSize = true, Enabled = testLocate != null }; + _testButton.Click += TestLocateOnClick; + buttons.Controls.Add(cancel); + buttons.Controls.Add(save); + buttons.Controls.Add(_testButton); + Controls.Add(_path); + Controls.Add(_status); + Controls.Add(help); + Controls.Add(buttons); + CancelButton = cancel; + // Enter remains a newline in the multiline editor; save is an explicit button action. + _path.TextChanged += delegate + { + _textRevision++; + ValidatePath(); + }; + ValidatePath(); + } + + public string PathText { get { return _path.Text; } } + + private bool ValidatePath() + { + string error = ControlMonitorRules.ValidateControlPath(_path.Text); + ShowStatus(error ?? "语法有效。保存仅更新当前行;写入配置文件仍需点击列表的“保存”。", error != null); + return error == null; + } + + private void ShowStatus(string text, bool error) + { + _status.ForeColor = error ? Color.Firebrick : Color.DarkSlateGray; + _status.Text = text; + } + + private async void TestLocateOnClick(object sender, EventArgs e) + { + if (_testing || _testLocate == null || !ValidatePath()) return; + int revision = _textRevision; + string path = _path.Text; + _testing = true; + _testButton.Enabled = false; + ShowStatus("正在后台测试唯一匹配……可继续编辑或取消。", false); + try + { + string error = await Task.Factory.StartNew( + () => _testLocate(path), CancellationToken.None, + TaskCreationOptions.LongRunning, TaskScheduler.Default); + if (!IsDisposed && revision == _textRevision) + ShowStatus(error ?? "定位成功:唯一匹配 1 个控件。", error != null); + } + catch (Exception ex) + { + if (!IsDisposed && revision == _textRevision) + ShowStatus("测试定位失败:" + ex.Message, true); + } + finally + { + _testing = false; + if (!IsDisposed) _testButton.Enabled = true; + } + } + } +} diff --git a/src/pacs_win_uia/UI/ControlTreeReconciler.cs b/src/pacs_win_uia/UI/ControlTreeReconciler.cs new file mode 100644 index 0000000..96ef5e7 --- /dev/null +++ b/src/pacs_win_uia/UI/ControlTreeReconciler.cs @@ -0,0 +1,240 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using pacs_win_uia.Models; + +namespace pacs_win_uia.UI +{ + /// Reuses native tree items across snapshots. Identity never depends on display text/path. + internal sealed class ControlTreeReconciler : IDisposable + { + internal sealed class Item + { + internal ControlTreeNode Model; + internal string Text; + internal bool Match; + internal Color ForeColor; + internal readonly List Children = new List(); + internal TreeNode Node; + } + + private readonly TreeView _tree; + private Font _matchFont; + private Font _baseFont; + + internal ControlTreeReconciler(TreeView tree) { _tree = tree; } + + // Strong identities can move between parents. Process scoping prevents cross-process reuse. + internal static string Identity(ControlTreeNode node) + { + if (node == null) return null; + if (node.Source == ControlTreeSource.Uia && node.Uia != null) + { + var u = node.Uia; + if (u.ProcessId > 0 && !string.IsNullOrEmpty(u.RuntimeId)) + return "uia:" + u.ProcessId + ":" + u.RuntimeId; + // A provider can expose several elements with the same HWND. Treat it only as + // a parent-scoped fallback, not a globally unique UIA identity. + } + if (node.Source == ControlTreeSource.Win32 && node.Window != null && node.Window.Handle != IntPtr.Zero) + return "win:" + node.Window.ProcessId + ":" + node.Window.Handle.ToInt64(); + if (node.Source == ControlTreeSource.Msaa && node.Msaa != null && !string.IsNullOrEmpty(node.Msaa.PathKey)) + return "msaa:" + node.Msaa.PathKey; + return null; + } + + private static string Part(string text) { return (text ?? string.Empty).Length + ":" + text; } + + // Only matched within the same retained parent, in occurrence order. Without provider IDs, + // indistinguishable siblings cannot reliably be tracked through arbitrary reordering. + private static string Fallback(ControlTreeNode node) + { + if (node == null) return "incomplete"; + if (node.Uia != null) + { + var u = node.Uia; + return "uia:" + u.ProcessId + ":" + u.NativeWindowHandle + ":" + + Part(u.AutomationId) + Part(u.ClassName) + Part(u.ControlType); + } + if (node.Msaa != null) + return "msaa:" + node.Msaa.WindowHandle + ":" + node.Msaa.ChildId + ":" + node.Msaa.RoleId; + return node.Source.ToString(); + } + + internal void Apply(Item root, IList matches) + { + var oldNodes = new List(); + Collect(_tree.Nodes, oldNodes); + var strong = new Dictionary(StringComparer.Ordinal); + var duplicate = new HashSet(StringComparer.Ordinal); + foreach (TreeNode node in oldNodes) + { + string key = Identity(node.Tag as ControlTreeNode); + if (key == null) continue; + if (strong.ContainsKey(key)) duplicate.Add(key); + else strong.Add(key, node); + } + foreach (string key in duplicate) strong.Remove(key); + var desiredCounts = new Dictionary(StringComparer.Ordinal); + CountIdentities(root, desiredCounts); + var used = new HashSet(); + // Reserve strong matches first: fallback nodes must not steal an item needed elsewhere. + Reserve(root, strong, desiredCounts, used); + if (root != null) Bind(root, _tree.Nodes, used); + + var selection = Ancestors(_tree.SelectedNode); + var top = Ancestors(_tree.TopNode); + var expanded = new HashSet(); + foreach (TreeNode node in oldNodes) if (node.IsExpanded) expanded.Add(node); + int horizontal = _tree.IsHandleCreated ? GetScrollPos(_tree.Handle, 0) : 0; + bool structural = false; + bool changed = false; + Font retiredFont = null; + if (_matchFont == null || !Equals(_baseFont, _tree.Font)) + { + retiredFont = _matchFont; + _baseFont = _tree.Font; + _matchFont = new Font(_baseFont, FontStyle.Bold); + } + Action beginStructure = delegate + { + if (structural) return; + _tree.BeginUpdate(); + structural = true; + }; + try + { + matches.Clear(); + if (root != null) Place(root, _tree.Nodes, 0, matches, beginStructure, ref changed); + // Prune only after moves: an obsolete parent may still contain a retained descendant. + foreach (TreeNode node in oldNodes) + { + if (used.Contains(node) || node.TreeView != _tree) continue; + beginStructure(); + node.Remove(); + } + if (structural) + { + foreach (TreeNode node in expanded) + if (node.TreeView == _tree && !node.IsExpanded) node.Expand(); + TreeNode selected = FirstAttached(selection); + if (_tree.SelectedNode != selected) _tree.SelectedNode = selected; + if (oldNodes.Count == 0 && root != null) root.Node.Expand(); + } + } + finally + { + if (structural) _tree.EndUpdate(); + if (retiredFont != null) retiredFont.Dispose(); + } + // EndUpdate can recalculate the scrollbar and move the viewport. Restore afterwards. + if (structural || changed) + { + TreeNode first = FirstAttached(top); + if (first != null && _tree.TopNode != first) _tree.TopNode = first; + if (_tree.IsHandleCreated && GetScrollPos(_tree.Handle, 0) != horizontal) + { + SetScrollPos(_tree.Handle, 0, horizontal, true); + SendMessage(_tree.Handle, 0x114, new IntPtr((horizontal << 16) | 4), IntPtr.Zero); + } + } + } + + private static void CountIdentities(Item item, Dictionary counts) + { + if (item == null) return; + string key = Identity(item.Model); + if (key != null) { int count; counts.TryGetValue(key, out count); counts[key] = count + 1; } + foreach (Item child in item.Children) CountIdentities(child, counts); + } + + private static void Reserve(Item item, Dictionary old, Dictionary counts, HashSet used) + { + if (item == null) return; + string key = Identity(item.Model); + item.Node = null; + TreeNode node; + if (key != null && counts[key] == 1 && old.TryGetValue(key, out node)) + { + item.Node = node; + used.Add(node); + } + foreach (Item child in item.Children) Reserve(child, old, counts, used); + } + + private static void Bind(Item item, TreeNodeCollection siblings, HashSet used) + { + if (item.Node == null) + { + string identity = Identity(item.Model); + string fallback = Fallback(item.Model); + foreach (TreeNode node in siblings) + { + if (used.Contains(node)) continue; + var old = node.Tag as ControlTreeNode; + string oldIdentity = Identity(old); + // If both snapshots supply IDs, never override a mismatch with a weaker hint. + if (identity != null && oldIdentity != null ? identity != oldIdentity : fallback != Fallback(old)) continue; + // Loading placeholders are not incomplete-child items. + if (item.Model == null && !node.Text.StartsWith("[读取不完整] ", StringComparison.Ordinal)) continue; + item.Node = node; + used.Add(node); + break; + } + if (item.Node == null) { item.Node = new TreeNode(); used.Add(item.Node); } + } + foreach (Item child in item.Children) Bind(child, item.Node.Nodes, used); + } + + private void Place(Item item, TreeNodeCollection siblings, int index, IList matches, Action beginStructure, ref bool changed) + { + TreeNode node = item.Node; + if (index >= siblings.Count || siblings[index] != node) + { + beginStructure(); + node.Remove(); + siblings.Insert(index, node); + } + node.Tag = item.Model; // Always use the latest snapshot, even if nothing visual changed. + if (node.Text != item.Text) { node.Text = item.Text; changed = true; } + Font font = item.Match ? _matchFont : null; + if (!ReferenceEquals(node.NodeFont, font)) { node.NodeFont = font; changed = true; } + if (node.ForeColor != item.ForeColor) { node.ForeColor = item.ForeColor; changed = true; } + for (int i = 0; i < item.Children.Count; i++) + Place(item.Children[i], node.Nodes, i, matches, beginStructure, ref changed); + if (item.Match) matches.Add(node); + } + + private static void Collect(TreeNodeCollection nodes, List result) + { + foreach (TreeNode node in nodes) { result.Add(node); Collect(node.Nodes, result); } + } + + private static List Ancestors(TreeNode node) + { + var result = new List(); + for (; node != null; node = node.Parent) result.Add(node); + return result; + } + + private TreeNode FirstAttached(List nodes) + { + foreach (TreeNode node in nodes) if (node.TreeView == _tree) return node; + return null; + } + + public void Dispose() + { + if (_matchFont != null) { _matchFont.Dispose(); _matchFont = null; } + } + + [DllImport("user32.dll")] + private static extern int GetScrollPos(IntPtr window, int bar); + [DllImport("user32.dll")] + private static extern int SetScrollPos(IntPtr window, int bar, int position, bool redraw); + [DllImport("user32.dll")] + private static extern IntPtr SendMessage(IntPtr window, int message, IntPtr wParam, IntPtr lParam); + } +} diff --git a/src/pacs_win_uia/UI/ControlTreeSearchPanel.cs b/src/pacs_win_uia/UI/ControlTreeSearchPanel.cs index ac253f0..88888b5 100644 --- a/src/pacs_win_uia/UI/ControlTreeSearchPanel.cs +++ b/src/pacs_win_uia/UI/ControlTreeSearchPanel.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Drawing; using System.Windows.Forms; using pacs_win_uia.Models; @@ -115,6 +115,8 @@ namespace pacs_win_uia.UI private readonly Button _more; private readonly Label _countLabel; private readonly Panel _advanced; + private readonly FlowLayoutPanel _bar; + private readonly TableLayoutPanel _grid; private readonly TextBox _nameBox; private readonly TextBox _pathBox; private readonly TextBox _automationIdBox; @@ -124,29 +126,39 @@ namespace pacs_win_uia.UI private readonly Button _apply; private readonly Button _clear; private bool _advancedVisible; + private int _measuredWidth = -1; + private int _barHeight = 28; + private int _advancedHeight = 58; + private int _loggedWidth = -1; + private bool _loggedAdvanced; public ControlTreeSearchPanel() { Height = 28; - var bar = new FlowLayoutPanel + // WrapContents on both rows: at a narrow width the buttons and the 更多 fields have to flow + // onto another line, and the panel height then follows the content instead of clipping it. + _bar = new FlowLayoutPanel { Dock = DockStyle.Top, Height = 28, - WrapContents = false, + WrapContents = true, FlowDirection = FlowDirection.LeftToRight }; + FlowLayoutPanel bar = _bar; bar.Controls.Add(new Label { Text = "搜索", AutoSize = true, Padding = new Padding(2, 6, 0, 0) }); - _anyBox = new TextBox { Width = 180 }; + // Compact controls on purpose: this row has to stay on one line in the default layout, and + // the ▲/▼ buttons only carry a symbol (AutoSize made them jump to the 75 px minimum width). + _anyBox = new TextBox { Width = 150 }; _anyBox.TextChanged += delegate { RaiseSearchChanged(); }; bar.Controls.Add(_anyBox); _onlyMatches = new CheckBox { Text = "仅显示匹配", AutoSize = true, Padding = new Padding(4, 6, 0, 0) }; _onlyMatches.CheckedChanged += delegate { RaiseSearchChanged(); }; bar.Controls.Add(_onlyMatches); - _previous = new Button { Text = "▲", AutoSize = true }; + _previous = new Button { Text = "▲", AutoSize = false, Width = 28, Height = 24 }; _previous.Click += delegate { RaiseNavigate(-1); }; - _next = new Button { Text = "▼", AutoSize = true }; + _next = new Button { Text = "▼", AutoSize = false, Width = 28, Height = 24 }; _next.Click += delegate { RaiseNavigate(1); }; bar.Controls.Add(_previous); bar.Controls.Add(_next); @@ -156,37 +168,114 @@ namespace pacs_win_uia.UI _more.Click += delegate { ToggleAdvanced(); }; bar.Controls.Add(_more); + // A real grid instead of a wrapping flow row: the caption and its box stay in one column, + // so nothing splits mid-pair and the fields line up (they were ragged before). _advanced = new Panel { Dock = DockStyle.Top, Height = 58, Visible = false }; - var grid = new FlowLayoutPanel + _grid = new TableLayoutPanel { Dock = DockStyle.Fill, - WrapContents = true, - FlowDirection = FlowDirection.LeftToRight, - Padding = new Padding(0, 2, 0, 0) + ColumnCount = 5, + RowCount = 3, + Padding = new Padding(2, 2, 2, 2) }; - _nameBox = AddField(grid, "名称"); - _pathBox = AddField(grid, "路径"); - _automationIdBox = AddField(grid, "AutomationId"); - _classBox = AddField(grid, "类名"); - _typeBox = AddField(grid, "类型"); - _onlyFocused = new CheckBox { Text = "仅焦点元素", AutoSize = true, Padding = new Padding(4, 6, 0, 0) }; + for (int index = 0; index < 5; index++) + { + _grid.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 20F)); + _grid.RowStyles.Add(new RowStyle(SizeType.AutoSize)); + } + + _grid.RowStyles.Clear(); + _grid.RowStyles.Add(new RowStyle(SizeType.AutoSize)); // 标题 + _grid.RowStyles.Add(new RowStyle(SizeType.Absolute, 26)); // 输入框 + _grid.RowStyles.Add(new RowStyle(SizeType.Absolute, 32)); // 按钮行 + + TableLayoutPanel grid = _grid; + _nameBox = AddField(grid, "名称", 0); + _pathBox = AddField(grid, "路径", 1); + _automationIdBox = AddField(grid, "AutomationId", 2); + _classBox = AddField(grid, "类名", 3); + _typeBox = AddField(grid, "类型", 4); + + var actions = new FlowLayoutPanel { Dock = DockStyle.Fill, WrapContents = false }; + _onlyFocused = new CheckBox { Text = "仅焦点元素", AutoSize = true, Padding = new Padding(4, 8, 0, 0) }; _onlyFocused.CheckedChanged += delegate { RaiseSearchChanged(); }; - grid.Controls.Add(_onlyFocused); + actions.Controls.Add(_onlyFocused); _apply = new Button { Text = "应用", AutoSize = true }; _apply.Click += delegate { RaiseSearchChanged(); }; - grid.Controls.Add(_apply); + actions.Controls.Add(_apply); _clear = new Button { Text = "清除", AutoSize = true }; _clear.Click += delegate { ClearAll(); }; - grid.Controls.Add(_clear); + actions.Controls.Add(_clear); + grid.Controls.Add(actions, 0, 2); + grid.SetColumnSpan(actions, 5); _advanced.Controls.Add(grid); Controls.Add(_advanced); Controls.Add(bar); - // Size the advanced area to its content: a fixed height clipped the second row of fields. - grid.PerformLayout(); - int wanted = grid.PreferredSize.Height + 6; - _advanced.Height = Math.Max(58, wanted); + // Both heights are measured for the current width (see UpdateHeights): a height computed + // once, before the panel had a width, clipped the second row of fields. + UpdateHeights(); + } + + protected override void OnSizeChanged(EventArgs e) + { + base.OnSizeChanged(e); + if (Width != _measuredWidth) + { + UpdateHeights(); + } + } + + /// + /// Sizes the two rows (and the whole panel) to the content at the *current* width. Both rows + /// wrap, so the required height depends on how wide this panel ended up being. + /// + private void UpdateHeights() + { + _measuredWidth = Width; + if (Width <= 0 || _bar == null || _grid == null || _advanced == null) + { + // Still in the constructor: Height is assigned before the rows exist. + return; + } + + _barHeight = MeasureWrappedHeight(_bar, Width, 28); + _advancedHeight = MeasureWrappedHeight(_grid, Width, 58); + if (_bar.Height != _barHeight) + { + _bar.Height = _barHeight; + } + + if (_advanced.Height != _advancedHeight) + { + _advanced.Height = _advancedHeight; + } + + int wanted = _barHeight + (_advancedVisible ? _advancedHeight : 0); + if (Height != wanted) + { + Height = wanted; + } + + if (_loggedWidth != Width || _loggedAdvanced != _advancedVisible) + { + _loggedWidth = Width; + _loggedAdvanced = _advancedVisible; + Diagnostics.AppLog.Debug("控件树搜索栏:宽 " + Width + " → 高 " + wanted + + "(搜索行 " + _barHeight + " / 更多 " + (_advancedVisible ? _advancedHeight.ToString() : "收起") + ")"); + } + } + + private static int MeasureWrappedHeight(Control panel, int width, int minimum) + { + if (panel == null) + { + return minimum; + } + + Size preferred = panel.GetPreferredSize(new Size(Math.Max(80, width - 4), 0)); + return Math.Max(minimum, preferred.Height + 4); } /// Fires when the criteria change; the owner re-applies filtering. @@ -217,6 +306,13 @@ namespace pacs_win_uia.UI get { return _onlyMatches.Checked; } } + /// Ctrl+F support: put the caret in the search box. + public void FocusSearchBox() + { + _anyBox.Focus(); + _anyBox.SelectAll(); + } + public void SetMatchCount(int count) { _countLabel.Text = count == 0 ? "匹配 0 项" : "匹配 " + count + " 项"; @@ -229,12 +325,18 @@ namespace pacs_win_uia.UI _next.Enabled = enabled; } - private TextBox AddField(FlowLayoutPanel parent, string label) + private TextBox AddField(TableLayoutPanel parent, string label, int column) { - parent.Controls.Add(new Label { Text = label, AutoSize = true, Padding = new Padding(6, 6, 0, 0) }); - var box = new TextBox { Width = 110 }; + parent.Controls.Add(new Label + { + Text = label, + AutoSize = true, + Padding = new Padding(2, 4, 0, 0), + TextAlign = ContentAlignment.MiddleLeft + }, column, 0); + var box = new TextBox { Dock = DockStyle.Fill }; box.TextChanged += delegate { /* applied by 应用 / Enter to avoid re-filtering per key */ }; - parent.Controls.Add(box); + parent.Controls.Add(box, column, 1); return box; } @@ -242,7 +344,7 @@ namespace pacs_win_uia.UI { _advancedVisible = !_advancedVisible; _advanced.Visible = _advancedVisible; - Height = _advancedVisible ? _advanced.Height + 28 : 28; + UpdateHeights(); _more.Text = _advancedVisible ? "收起" : "更多…"; RaiseSearchChanged(); } diff --git a/src/pacs_win_uia/UI/FloatingToolbarForm.cs b/src/pacs_win_uia/UI/FloatingToolbarForm.cs index 9776cce..599e4e7 100644 --- a/src/pacs_win_uia/UI/FloatingToolbarForm.cs +++ b/src/pacs_win_uia/UI/FloatingToolbarForm.cs @@ -1,7 +1,11 @@ -using System; +using System; using System.Collections.Generic; using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Text; +using System.Runtime.InteropServices; using System.Windows.Forms; +using pacs_win_uia.Diagnostics; using pacs_win_uia.Interop; using pacs_win_uia.Models; @@ -14,7 +18,16 @@ namespace pacs_win_uia.UI Action = action; } - /// Label of the clicked button. + public FloatingActionEventArgs(FloatingButtonDefinition button, string action) + { + Button = button; + Action = action; + } + + /// Stable configured button instance, avoiding duplicate-label dispatch. + public FloatingButtonDefinition Button { get; private set; } + + /// Display label of the clicked button. public string Action { get; private set; } } @@ -23,8 +36,10 @@ namespace pacs_win_uia.UI /// PACS window without stealing its keyboard. This is the "方案 B" from the requirements — an /// independent operation bar instead of injecting into the target's context menu. /// - /// Showing/hiding and positioning are driven by FloatingBarManager from the configured condition - /// and the relative offsets. + /// The bar draws itself: the background and the buttons have separate transparency, which WinForms + /// child controls cannot express (a child control has no alpha of its own). The window is layered + /// and rendered through UpdateLayeredWindow, which is also what gives the rounded corners. Showing, + /// hiding and positioning are driven by FloatingBarManager from the configured condition. /// public sealed class FloatingToolbarForm : Form { @@ -41,9 +56,30 @@ namespace pacs_win_uia.UI FloatingActionKind.RunCommand }; + private const int EdgePadding = 6; + private const int ButtonPaddingX = 10; + private const int ButtonPaddingY = 5; + private const int ButtonGap = 4; + private const byte SolidAlpha = 255; + private readonly FloatingBarDefinition _bar; + private readonly List _buttons = new List(); + private readonly ToolTip _tooltip = new ToolTip(); private Point _dragOffset; private bool _dragging; + private int _hoverIndex = -1; + private int _pressedIndex = -1; + private bool _layered; + private bool _layeredFailed; + private string _shownTooltip; + + private sealed class ButtonLayout + { + internal FloatingButtonDefinition Definition; + internal Rectangle Bounds; + internal string Label; + internal string Tooltip; + } public FloatingToolbarForm(FloatingBarDefinition bar) { @@ -52,69 +88,38 @@ namespace pacs_win_uia.UI ShowInTaskbar = false; StartPosition = FormStartPosition.Manual; TopMost = true; - BackColor = Color.FromArgb(245, 245, 245); - Padding = new Padding(4); DoubleBuffered = true; - Opacity = Math.Max(0.2D, Math.Min(1.0D, _bar.OpacityPercent / 100.0D)); - - var panel = new FlowLayoutPanel - { - Dock = DockStyle.Fill, - AutoSize = true, - AutoSizeMode = AutoSizeMode.GrowAndShrink, - WrapContents = false, - FlowDirection = FlowDirection.LeftToRight - }; - - foreach (FloatingButtonDefinition button in _bar.Buttons ?? new List()) - { - if (button == null || !button.Enabled) - { - continue; - } - - string label = string.IsNullOrWhiteSpace(button.Label) - ? FloatingButtonDefinition.DescribeAction(button.Action) - : button.Label; - var control = new Button - { - Text = label, - AutoSize = true, - FlatStyle = FlatStyle.System, - Margin = new Padding(2) - }; - string tooltip = FloatingButtonDefinition.DescribeAction(button.Action); - if (!string.IsNullOrWhiteSpace(button.Shortcut)) - { - tooltip += "(快捷键 " + button.Shortcut + ")"; - } - - if (!string.IsNullOrWhiteSpace(button.CommandLine)) - { - tooltip += Environment.NewLine + button.CommandLine; - } - - new ToolTip().SetToolTip(control, tooltip); - string captured = button.Label; - control.Click += delegate { Raise(captured); }; - panel.Controls.Add(control); - } - - Controls.Add(panel); - AutoSize = true; - AutoSizeMode = AutoSizeMode.GrowAndShrink; - - // Drag the bar by its background; the buttons still receive their own clicks. - panel.MouseDown += OnDragStart; - panel.MouseMove += OnDragMove; - panel.MouseUp += OnDragEnd; - MouseDown += OnDragStart; - MouseMove += OnDragMove; - MouseUp += OnDragEnd; + Font = SystemFonts.DefaultFont; + BuildLayout(); + ClientSize = MeasureBar(); } public event EventHandler ActionInvoked; + /// + /// True when the bar is rendered with per-pixel alpha (background and buttons can differ). + /// False means the window fell back to a single window opacity. + /// + public bool UsesPerPixelAlpha + { + get { return _layered; } + } + + /// The definition the bar was built from (the settings dialog reads the live one). + public FloatingBarDefinition Definition + { + get { return _bar; } + } + + /// + /// True while the operator is dragging the bar. The manager keeps its "follow the anchor + /// window" ticks off the bar during a drag, otherwise the two would fight over the position. + /// + public bool IsDragging + { + get { return _dragging; } + } + /// The offsets the operator dragged the bar to, relative to the anchor window. public void ApplyDraggedOffset(Point anchorTopLeft) { @@ -133,47 +138,447 @@ namespace pacs_win_uia.UI { CreateParams parameters = base.CreateParams; parameters.ExStyle |= NativeMethods.WS_EX_TOOLWINDOW | NativeMethods.WS_EX_NOACTIVATE; + // Per-pixel alpha: the background and the buttons carry their own transparency. + parameters.ExStyle |= NativeMethods.WS_EX_LAYERED; return parameters; } } - private void OnDragStart(object sender, MouseEventArgs e) + // ------------------------------------------------------------------ layout + + private void BuildLayout() { + _buttons.Clear(); + foreach (FloatingButtonDefinition button in _bar.Buttons ?? new List()) + { + if (button == null || !button.Enabled) + { + continue; + } + + string label = string.IsNullOrWhiteSpace(button.Label) + ? FloatingButtonDefinition.DescribeAction(button.Action) + : button.Label; + string tooltip = FloatingButtonDefinition.DescribeAction(button.Action); + if (!string.IsNullOrWhiteSpace(button.Shortcut)) + { + tooltip += "(快捷键 " + button.Shortcut + ")"; + } + + if (!string.IsNullOrWhiteSpace(button.CommandLine)) + { + tooltip += Environment.NewLine + button.CommandLine; + } + + _buttons.Add(new ButtonLayout { Definition = button, Label = label, Tooltip = tooltip }); + } + } + + private Size MeasureBar() + { + int width = EdgePadding * 2; + int height = EdgePadding * 2 + TextRenderer.MeasureText("测", Font).Height + ButtonPaddingY * 2; + foreach (ButtonLayout button in _buttons) + { + Size text = TextRenderer.MeasureText(button.Label, Font); + button.Bounds = new Rectangle( + width, EdgePadding, text.Width + ButtonPaddingX * 2, height - EdgePadding * 2); + width += button.Bounds.Width + ButtonGap; + } + + if (_buttons.Count > 0) + { + width -= ButtonGap; + } + + return new Size(Math.Max(width, 24), Math.Max(height, 24)); + } + + // ------------------------------------------------------------------ rendering + + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + Render(); + } + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + if (IsHandleCreated) + { + Render(); + } + } + + protected override void OnPaintBackground(PaintEventArgs e) + { + // The window surface comes from UpdateLayeredWindow; normal painting would only flicker. + if (!_layeredFailed) + { + return; + } + + base.OnPaintBackground(e); + } + + protected override void OnPaint(PaintEventArgs e) + { + // Only the degraded path paints normally; the layered path renders into a bitmap instead. + if (!_layeredFailed) + { + return; + } + + DrawBar(e.Graphics, false); + } + + protected override void WndProc(ref Message message) + { + const int WM_ERASEBKGND = 0x0014; + const int WM_NCHITTEST = 0x0084; + const int HTCLIENT = 1; + const int HTTRANSPARENT = -1; + if (message.Msg == WM_ERASEBKGND) + { + message.Result = new IntPtr(1); + return; + } + + if (message.Msg == WM_NCHITTEST) + { + // The rounded corners are empty space: let clicks through instead of swallowing them. + int x = unchecked((short)(long)message.LParam); + int y = unchecked((short)((long)message.LParam >> 16)); + Point client = PointToClient(new Point(x, y)); + message.Result = new IntPtr(IsInsideShape(client.X, client.Y) ? HTCLIENT : HTTRANSPARENT); + return; + } + + base.WndProc(ref message); + } + + private bool IsInsideShape(int x, int y) + { + var shape = new Rectangle(0, 0, Width, Height); + return shape.Contains(x, y); + } + + /// + /// Draws the whole bar into an ARGB bitmap and hands it to the window. Called on every visual + /// change (hover, press, resize) — the bar is a few hundred pixels, so redrawing is free. + /// + public void Render() + { + if (!IsHandleCreated || Width <= 0 || Height <= 0) + { + return; + } + + if (_layeredFailed) + { + // Degraded mode: the window itself is translucent, so the drawing is fully opaque. + Invalidate(); + return; + } + + using (var bitmap = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)) + using (Graphics graphics = Graphics.FromImage(bitmap)) + { + DrawBar(graphics, true); + ApplyBitmap(bitmap, ToAlpha(_bar.EffectiveBackgroundOpacity)); + } + } + + /// + /// Draws the bar. false is the degraded path: the same shapes, + /// fully opaque, with the whole window carrying the transparency. + /// + private void DrawBar(Graphics graphics, bool perPixelAlpha) + { + int backgroundAlpha = perPixelAlpha ? ToAlpha(_bar.EffectiveBackgroundOpacity) : SolidAlpha; + int controlAlpha = perPixelAlpha ? ToAlpha(_bar.EffectiveControlOpacity) : SolidAlpha; + graphics.SmoothingMode = SmoothingMode.AntiAlias; + graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; + if (perPixelAlpha) + { + graphics.Clear(Color.Transparent); + } + + Color face = SystemColors.Control; + using (var background = new SolidBrush(Color.FromArgb(backgroundAlpha, face))) + using (var border = new Pen(Color.FromArgb(backgroundAlpha, 120, 120, 120))) + { + Rectangle shape = new Rectangle(0, 0, Width - 1, Height - 1); + using (GraphicsPath path = RoundedRect(shape, 6)) + { + graphics.FillPath(background, path); + graphics.DrawPath(border, path); + } + } + + for (int index = 0; index < _buttons.Count; index++) + { + ButtonLayout button = _buttons[index]; + Color buttonFace = index == _pressedIndex + ? Color.FromArgb(200, 210, 225) + : (index == _hoverIndex ? Color.FromArgb(232, 240, 250) : Color.White); + using (var fill = new SolidBrush(Color.FromArgb(controlAlpha, buttonFace))) + using (var buttonBorder = new Pen(Color.FromArgb(controlAlpha, 150, 150, 150))) + using (GraphicsPath path = RoundedRect(button.Bounds, 4)) + { + graphics.FillPath(fill, path); + graphics.DrawPath(buttonBorder, path); + } + + TextRenderer.DrawText( + graphics, + button.Label, + Font, + button.Bounds, + Color.FromArgb(controlAlpha, SystemColors.ControlText), + TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPrefix); + } + + } + + /// + /// Hands the bitmap to the window. If per-pixel alpha is unavailable the bar degrades to a + /// whole-window opacity (still drawn by the tool, just one alpha for everything). + /// + private void ApplyBitmap(Bitmap bitmap, int backgroundAlpha) + { + IntPtr screenDc = IntPtr.Zero; + IntPtr memoryDc = IntPtr.Zero; + IntPtr hBitmap = IntPtr.Zero; + IntPtr previous = IntPtr.Zero; + try + { + screenDc = NativeMethods.GetDC(IntPtr.Zero); + memoryDc = NativeMethods.CreateCompatibleDC(screenDc); + hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); + previous = NativeMethods.SelectObject(memoryDc, hBitmap); + var destination = new NativeMethods.POINT(Left, Top); + var source = new NativeMethods.POINT(0, 0); + var size = new NativeMethods.SIZE(Width, Height); + var blend = new NativeMethods.BLENDFUNCTION + { + BlendOp = 0, + BlendFlags = 0, + SourceConstantAlpha = SolidAlpha, + AlphaFormat = 1 + }; + + if (NativeMethods.UpdateLayeredWindow( + Handle, screenDc, ref destination, ref size, memoryDc, ref source, 0, ref blend, 2)) + { + _layered = true; + if (_layeredFailed) + { + AppLog.Info("悬浮条已切回逐像素透明(背景与按钮可分别设置)。"); + _layeredFailed = false; + } + + return; + } + + if (!_layeredFailed) + { + _layeredFailed = true; + AppLog.Warn("悬浮条逐像素透明不可用,退化为整条不透明度。Win32 错误码: " + + Marshal.GetLastWin32Error()); + } + + // Degraded path: one alpha for the whole window, painted with normal GDI. + _layered = false; + if (Opacity != backgroundAlpha / 255.0D) + { + Opacity = Math.Max(0.05D, backgroundAlpha / 255.0D); + } + + Invalidate(); + } + catch (Exception ex) + { + AppLog.Warn("绘制悬浮条失败:" + ex.GetType().Name + ": " + ex.Message); + } + finally + { + if (previous != IntPtr.Zero) + { + NativeMethods.SelectObject(memoryDc, previous); + } + + if (hBitmap != IntPtr.Zero) + { + NativeMethods.DeleteObject(hBitmap); + } + + if (memoryDc != IntPtr.Zero) + { + NativeMethods.DeleteDC(memoryDc); + } + + if (screenDc != IntPtr.Zero) + { + NativeMethods.ReleaseDC(IntPtr.Zero, screenDc); + } + } + } + + private static int ToAlpha(int percent) + { + int clamped = Math.Max(1, Math.Min(100, percent)); + return clamped * 255 / 100; + } + + private static GraphicsPath RoundedRect(Rectangle bounds, int radius) + { + var path = new GraphicsPath(); + int diameter = Math.Max(2, radius * 2); + if (bounds.Width <= diameter || bounds.Height <= diameter) + { + path.AddRectangle(bounds); + return path; + } + + path.AddArc(bounds.Left, bounds.Top, diameter, diameter, 180, 90); + path.AddArc(bounds.Right - diameter, bounds.Top, diameter, diameter, 270, 90); + path.AddArc(bounds.Right - diameter, bounds.Bottom - diameter, diameter, diameter, 0, 90); + path.AddArc(bounds.Left, bounds.Bottom - diameter, diameter, diameter, 90, 90); + path.CloseFigure(); + return path; + } + + // ------------------------------------------------------------------ input + + private int HitTest(Point client) + { + for (int index = 0; index < _buttons.Count; index++) + { + if (_buttons[index].Bounds.Contains(client)) + { + return index; + } + } + + return -1; + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); if (e.Button != MouseButtons.Left) { return; } - _dragging = true; - _dragOffset = new Point(e.X, e.Y); + _pressedIndex = HitTest(e.Location); + if (_pressedIndex < 0) + { + _dragging = true; + _dragOffset = e.Location; + } + + Render(); } - private void OnDragMove(object sender, MouseEventArgs e) + protected override void OnMouseMove(MouseEventArgs e) { - if (!_dragging) + base.OnMouseMove(e); + if (_dragging) + { + Point screenPoint = PointToScreen(e.Location); + Location = new Point(screenPoint.X - _dragOffset.X, screenPoint.Y - _dragOffset.Y); + return; + } + + int hover = HitTest(e.Location); + if (hover != _hoverIndex) + { + _hoverIndex = hover; + Render(); + UpdateTooltip(hover); + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + if (e.Button != MouseButtons.Left) { return; } - Point screenPoint = ((Control)sender).PointToScreen(new Point(e.X, e.Y)); - Location = new Point(screenPoint.X - _dragOffset.X, screenPoint.Y - _dragOffset.Y); - } - - private void OnDragEnd(object sender, MouseEventArgs e) - { - if (_dragging) + int released = HitTest(e.Location); + bool wasPressed = _pressedIndex >= 0 && _pressedIndex == released; + _pressedIndex = -1; + _dragging = false; + Render(); + if (!wasPressed) { - _dragging = false; + return; } - } - private void Raise(string action) - { + string label = _buttons[released].Label; EventHandler handler = ActionInvoked; if (handler != null) { - handler(this, new FloatingActionEventArgs(action)); + handler(this, new FloatingActionEventArgs(_buttons[released].Definition, label)); } } + + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + if (_hoverIndex >= 0) + { + _hoverIndex = -1; + Render(); + } + + _tooltip.Hide(this); + _shownTooltip = null; + } + + protected override void OnMouseCaptureChanged(EventArgs e) + { + base.OnMouseCaptureChanged(e); + if (!Capture && _pressedIndex >= 0) + { + _pressedIndex = -1; + Render(); + } + } + + private void UpdateTooltip(int index) + { + if (index < 0) + { + _tooltip.Hide(this); + _shownTooltip = null; + return; + } + + string text = _buttons[index].Tooltip; + if (string.IsNullOrEmpty(text) || text == _shownTooltip) + { + return; + } + + _shownTooltip = text; + Rectangle bounds = _buttons[index].Bounds; + _tooltip.Show(text, this, new Point(bounds.Left, bounds.Bottom + 4), 8000); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _tooltip.Dispose(); + } + + base.Dispose(disposing); + } } } diff --git a/src/pacs_win_uia/UI/MainForm.cs b/src/pacs_win_uia/UI/MainForm.cs index f05dde9..ecf446a 100644 --- a/src/pacs_win_uia/UI/MainForm.cs +++ b/src/pacs_win_uia/UI/MainForm.cs @@ -55,9 +55,9 @@ namespace pacs_win_uia private readonly TextBox _statusText; private readonly Button _refreshButton; private readonly Button _inspectButton; - private readonly Button _exportButton; - private readonly Button _readListButton; - private readonly Button _exportListButton; + private readonly ToolStripMenuItem _exportTreeItem; + private readonly ToolStripMenuItem _readListItem; + private readonly ToolStripMenuItem _exportListItem; private readonly Button _pickButton; private readonly ComboBox _treeSourceCombo; private readonly Label _windowListCaption; @@ -66,20 +66,32 @@ namespace pacs_win_uia private readonly ControlTreeSearchPanel _treeSearchPanel; private readonly Label _listResultHint; private readonly Button _settingsButton; - private readonly Button _screenshotButton; - private readonly Button _ocrButton; - private readonly Button _copyFeaturesButton; + private readonly ToolStripMenuItem _screenshotItem; + private readonly ToolStripMenuItem _ocrItem; + private readonly Button _miscButton; + private readonly ContextMenuStrip _miscMenu; + private readonly ShiftWheelScroll _shiftWheel = new ShiftWheelScroll(); + private readonly ScrollHostPanel _propertyHost; + private readonly ToolStripMenuItem _copyFeaturesItem; + private readonly ToolStripMenuItem _locateByPathItem; + private readonly ToolStripMenuItem _nodeMapItem; private readonly ScreenshotService _screenshotService; private OcrReadContext _ocrContext; private ControlTreeNode _currentNode; private readonly Services.AppSettingsStore _settingsStore; private readonly Services.CommandRunner _commandRunner; - private readonly HighlightOverlayForm _locateHighlight; - private readonly System.Windows.Forms.Timer _locateWatchTimer; + private readonly HighlightFollower _locateFollower; + private readonly NodeMapOverlayForm _nodeMapOverlay; + private readonly ControlLocatorService _locatorService = new ControlLocatorService(); private ControlMonitorDefinition _locatedDefinition; private ControlTreeNode _locatedNode; + /// Node to select once the tree of its own window has been read (see ApplyTree). + private ControlTreeNode _pendingTreeSelection; + /// Falls back to a tree rooted at the picked element when the window tree lacks it. + private int _autoAddedPickSession = -1; + /// True while the tree source is switched programmatically (no re-read of the old root). + private bool _suppressTreeSourceEvents; private bool _expandPickedTree; - private IntPtr _locatedAnchor = IntPtr.Zero; private AppSettings _settings; private FloatingBarManager _floatingBars; private readonly List _treeMatches = new List(); @@ -91,6 +103,14 @@ namespace pacs_win_uia private readonly CrosshairPicker _picker; private readonly System.Windows.Forms.Timer _autoInspectTimer; private readonly System.Windows.Forms.Timer _treeReadTimer; + private readonly System.Windows.Forms.Timer _liveTreeTimer; + private bool _liveTreeReadInFlight; + private bool _restoringTreeState; + private ControlTreeReconciler _treeReconciler; + private bool _autoAddPendingPick; + private HashSet _pathSearchMatches; + private DateTime _lastLiveTreeUtc; + private DateTime _liveTreeStartedUtc; private DateTime _treeReadStartedUtc; private string _treeReadLabel; private bool _splittersInitialized; @@ -149,6 +169,13 @@ namespace pacs_win_uia _autoInspectTimer.Tick += AutoInspectTimerOnTick; _treeReadTimer = new System.Windows.Forms.Timer { Interval = 500 }; _treeReadTimer.Tick += TreeReadTimerOnTick; + _liveTreeTimer = new System.Windows.Forms.Timer { Interval = _settings.Ui.TreeRefreshIntervalMs }; + _liveTreeTimer.Tick += LiveTreeTimerOnTick; + _liveTreeTimer.Start(); + + KeyPreview = true; + KeyDown += MainFormOnKeyDown; + Application.AddMessageFilter(_shiftWheel); Text = "PACS Windows UI Automation Inspector - 第一/二阶段"; StartPosition = FormStartPosition.CenterScreen; @@ -166,9 +193,9 @@ namespace pacs_win_uia _refreshButton = new Button { Text = "刷新窗口", AutoSize = true }; _pickButton = new Button { Text = "拾取控件", AutoSize = true, Enabled = true }; _inspectButton = new Button { Text = "检查选中窗口", AutoSize = true, Enabled = false }; - _readListButton = new Button { Text = "读取选中控件列表", AutoSize = true, Enabled = false }; - _exportButton = new Button { Text = "导出控件树", AutoSize = true, Enabled = false }; - _exportListButton = new Button { Text = "导出列表 JSON/CSV", AutoSize = true, Enabled = false }; + _readListItem = new ToolStripMenuItem("读取选中控件列表") { Enabled = false }; + _exportTreeItem = new ToolStripMenuItem("导出控件树") { Enabled = false }; + _exportListItem = new ToolStripMenuItem("导出列表 JSON/CSV") { Enabled = false }; _treeSourceCombo = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, @@ -189,9 +216,18 @@ namespace pacs_win_uia Enabled = false }; _settingsButton = new Button { Text = "设置", AutoSize = true }; - _screenshotButton = new Button { Text = "窗口截图", AutoSize = true, Enabled = false }; - _ocrButton = new Button { Text = "OCR 读取", AutoSize = true, Enabled = false }; - _copyFeaturesButton = new Button { Text = "复制页面特征", AutoSize = true, Enabled = false }; + _screenshotItem = new ToolStripMenuItem("窗口截图") { Enabled = false }; + _ocrItem = new ToolStripMenuItem("OCR 读取") { Enabled = false }; + // 复制页面特征 is used once in a while — it lives in a 杂项 menu instead of taking a + // permanent slot in an already crowded toolbar. + _miscButton = new Button { Text = "杂项 ▾", AutoSize = true }; + _miscMenu = new ContextMenuStrip(); + _copyFeaturesItem = new ToolStripMenuItem("复制页面特征(进程 / 窗口类 / 标题关键词)") + { + Enabled = false + }; + _locateByPathItem = new ToolStripMenuItem("按 path 定位…"); + _nodeMapItem = new ToolStripMenuItem("绘制所有控件框") { CheckOnClick = true }; _screenshotService = new ScreenshotService(); _pickerPreviewLabel = new Label { @@ -210,15 +246,10 @@ namespace pacs_win_uia toolbar.Controls.Add(_refreshButton); toolbar.Controls.Add(_pickButton); toolbar.Controls.Add(_inspectButton); - toolbar.Controls.Add(_readListButton); - toolbar.Controls.Add(_exportButton); - toolbar.Controls.Add(_exportListButton); toolbar.Controls.Add(new Label { Text = "控件树来源:", AutoSize = true, Padding = new Padding(10, 7, 0, 0) }); toolbar.Controls.Add(_treeSourceCombo); toolbar.Controls.Add(_activateButton); - toolbar.Controls.Add(_screenshotButton); - toolbar.Controls.Add(_ocrButton); - toolbar.Controls.Add(_copyFeaturesButton); + toolbar.Controls.Add(_miscButton); toolbar.Controls.Add(_settingsButton); toolbar.Controls.Add(_pickerPreviewLabel); toolbar.Controls.Add(limitationLabel); @@ -248,6 +279,7 @@ namespace pacs_win_uia _windowList.Columns.Add("最小化", 70); _controlTree = new TreeView { Dock = DockStyle.Fill, HideSelection = false }; + _controlTree.Disposed += delegate { if (_treeReconciler != null) _treeReconciler.Dispose(); }; _listResultGrid = new DataGridView { Dock = DockStyle.Fill, @@ -278,12 +310,31 @@ namespace pacs_win_uia _resultTabs.TabPages.Add(_listResultTab); _propertyGrid = new PropertyGrid { Dock = DockStyle.Fill, HelpVisible = true, ToolbarVisible = false }; _monitorEditor = new ControlMonitorEditorControl(); + _propertyGrid.PropertyValueChanged += delegate + { + _monitorEditor.NotifyDefinitionChanged(_propertyGrid.SelectedObject as ControlMonitorDefinition); + }; + _monitorEditor.SetRefreshInterval(_settings.Ui.TreeRefreshIntervalMs); _monitorEditor.StatusChanged += MonitorEditorOnStatusChanged; _monitorEditor.ControlLocated += MonitorEditorOnControlLocated; _monitorEditor.DefinitionSelected += MonitorEditorOnDefinitionSelected; - _locateHighlight = new HighlightOverlayForm(); - _locateWatchTimer = new System.Windows.Forms.Timer { Interval = 1000 }; - _locateWatchTimer.Tick += LocateWatchTimerOnTick; + _locateFollower = new HighlightFollower(Process.GetCurrentProcess().Id); + _locateFollower.SetReResolveIntervalMs(_settings.Ui.TreeRefreshIntervalMs); + _locateFollower.Hidden += LocateFollowerOnHidden; + _nodeMapOverlay = new NodeMapOverlayForm { RefreshIntervalMs = _settings.Ui.TreeRefreshIntervalMs }; + _nodeMapOverlay.MapExited += delegate { _nodeMapItem.Checked = false; }; + _nodeMapOverlay.NodeSelected += delegate(object sender, NodeMapSelectionEventArgs e) + { + var node = e.Node as ControlTreeNode; + if (node == null) return; + SelectTreeNodeFor(node); + try + { + if (!string.IsNullOrEmpty(e.Path)) Clipboard.SetText(e.Path); + SetStatus("已复制该框的 path:" + e.Path + "(滚轮可切换重叠节点)", null); + } + catch (Exception ex) { SetStatus("复制 path 失败。", ex); } + }; _statusText = new TextBox { Dock = DockStyle.Bottom, @@ -312,6 +363,7 @@ namespace pacs_win_uia var propertyHost = new ScrollHostPanel { Dock = DockStyle.Fill, MinimumContentWidth = 360 }; propertyHost.Content = _propertyGrid; + _propertyHost = propertyHost; _propertyCaption = CreateCaption("控件属性 —— 选中控件树的节点、或选中下面监控列表的一行,都在这里查看/编辑"); var propertyPanel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(6) }; propertyPanel.Controls.Add(propertyHost); @@ -359,10 +411,18 @@ namespace pacs_win_uia _refreshButton.Click += delegate { RefreshWindows(); }; _pickButton.Click += delegate { StartPicker(); }; _inspectButton.Click += delegate { InspectSelectedWindow(); }; - _readListButton.Click += delegate { ReadSelectedList(); }; - _exportButton.Click += delegate { ExportCurrentTree(); }; - _exportListButton.Click += delegate { ExportLastListResult(); }; - _treeSourceCombo.SelectedIndexChanged += delegate { RereadCurrentTree("来源已切换"); }; + _readListItem.Click += delegate { ReadSelectedList(); }; + _exportTreeItem.Click += delegate { ExportCurrentTree(); }; + _exportListItem.Click += delegate { ExportLastListResult(); }; + _treeSourceCombo.SelectedIndexChanged += delegate + { + if (_suppressTreeSourceEvents) + { + return; + } + + RereadCurrentTree("来源已切换"); + }; _treeSearchPanel.SearchChanged += delegate { RebuildTreeView(); }; _treeSearchPanel.NavigateRequested += delegate(object sender, FloatingActionEventArgs e) { @@ -374,9 +434,29 @@ namespace pacs_win_uia }; _activateButton.Click += delegate { ActivateTargetAccessibility(); }; _settingsButton.Click += delegate { ShowSettings(); }; - _screenshotButton.Click += delegate { CaptureCurrentWindow(); }; - _ocrButton.Click += delegate { ReadCurrentByOcr(); }; - _copyFeaturesButton.Click += delegate { CopyCurrentPageFeatures(); }; + _screenshotItem.Click += delegate { CaptureCurrentWindow(); }; + _ocrItem.Click += delegate { ReadCurrentByOcr(); }; + _copyFeaturesItem.Click += delegate { CopyCurrentPageFeatures(); }; + _locateByPathItem.Click += delegate { LocateByPath(); }; + _nodeMapItem.Click += delegate { ToggleNodeMap(); }; + _miscMenu.Items.Add(_copyFeaturesItem); + _miscMenu.Items.Add(_locateByPathItem); + _miscMenu.Items.Add(_nodeMapItem); + _miscMenu.Items.Add(new ToolStripSeparator()); + // 低频但必须留着的能力:工具栏只放常用的,其余进这里。 + _miscMenu.Items.Add(_readListItem); + _miscMenu.Items.Add(_screenshotItem); + _miscMenu.Items.Add(_ocrItem); + _miscMenu.Items.Add(new ToolStripSeparator()); + _miscMenu.Items.Add(_exportTreeItem); + _miscMenu.Items.Add(_exportListItem); + // Also assigned as the button's context menu so a right-click opens it, and so the menu is + // discoverable from the button itself. + _miscButton.ContextMenuStrip = _miscMenu; + _miscButton.Click += delegate + { + _miscMenu.Show(_miscButton, new Point(0, _miscButton.Height)); + }; _windowSearchBox.TextChanged += delegate { ApplyWindowFilter(); }; _windowList.SelectedIndexChanged += WindowListOnSelectedIndexChanged; _controlTree.AfterSelect += ControlTreeOnAfterSelect; @@ -517,7 +597,10 @@ namespace pacs_win_uia _settings = _settingsStore.Load(); _ocrContext = OcrReadContext.Create(_settings.Ocr); _floatingBars.Reload(); - _commandRunner.RunStartCommands(_settings); + _liveTreeTimer.Interval = _settings.Ui.TreeRefreshIntervalMs; + _nodeMapOverlay.RefreshIntervalMs = _settings.Ui.TreeRefreshIntervalMs; + _locateFollower.SetReResolveIntervalMs(_settings.Ui.TreeRefreshIntervalMs); + _monitorEditor.SetRefreshInterval(_settings.Ui.TreeRefreshIntervalMs); SetStatus("设置已保存并生效:" + _settingsStore.FilePath, null); } @@ -1080,7 +1163,7 @@ namespace pacs_win_uia _pickButton.Enabled = !_picker.IsPicking; if (!hasSelection) { - ClearInspectionState(); + if (!_suppressSelectionEvents) ClearInspectionState(); return; } @@ -1149,19 +1232,29 @@ namespace pacs_win_uia private void ClearInspectionState() { + _treeReadTimer.Stop(); + _treeReadStartedUtc = default(DateTime); + _autoInspectTimer.Stop(); CancelInspection(); _inspectionSequence++; _currentTree = null; + _currentTreeRoot = null; + _treeRootHandle = IntPtr.Zero; + _treeUiaRoot = null; + _monitorEditor.SetTreeRoot(null); _currentElement = null; _inspectedWindow = null; _lastListResult = null; CancelListRead(); ClearListResultGrid(); _controlTree.Nodes.Clear(); + _nodeMapOverlay.HideMap(); + _nodeMapItem.Checked = false; + _pendingTreeSelection = null; _propertyGrid.SelectedObject = null; - _exportButton.Enabled = false; - _exportListButton.Enabled = false; - _readListButton.Enabled = false; + _exportTreeItem.Enabled = false; + _exportListItem.Enabled = false; + _readListItem.Enabled = false; _monitorEditor.SetCurrentNode(null, null); ShowNodeProperties(null); } @@ -1280,7 +1373,8 @@ namespace pacs_win_uia return null; } - if (result.AutomationElement != null && result.AutomationElement.IsAvailable) + if (result.AutomationElement != null && result.AutomationElement.IsAvailable && + !(result.Msaa != null && result.AutomationElement.ControlType == "ControlType.Window")) { return new ControlTreeNode { Source = ControlTreeSource.Uia, Uia = result.AutomationElement }; } @@ -1298,54 +1392,60 @@ namespace pacs_win_uia return null; } - private void ApplyPickResult(PointPickResult result) + /// + /// A control picked from MSAA or Win32 can only be found in that source's tree, so the tree is + /// read from the same source as the pick. UIA picks stay on 自动, where the reader can still + /// fall back to a source that has content. + /// + private void EnsureTreeSourceFor(ControlTreeNode node) { - _currentElement = result.AutomationElement; - _inspectedWindow = result.Window; - _propertyGrid.SelectedObject = result.AutomationElement ?? (object)result.Window; - _monitorEditor.SetCurrentNode(BuildPickedNode(result), _inspectedWindow); - ShowNodeProperties(_currentTreeRoot); - _readListButton.Enabled = _currentElement != null && _currentElement.IsAvailable; - - // Show the picked window in the list for context; this must not replace the picked - // element's tree with a whole-window tree. - RefreshWindows(); - if (result.Window != null) + if (node == null) { - SelectWindowItem(result.Window); - } - - if (result.IsWindowOnlyPick) - { - SetStatus("只拾取到窗口「" + (result.Window == null ? "(未知)" : result.Window.ToString()) - + "」:UIA 只返回窗口本身、MSAA 在该窗口上也没有命中内部对象," - + "窗口区域已高亮,但光标下的具体控件无法确定。" - + "可试试切换控件树来源,或点「尝试激活目标无障碍」。", null); - } - - if (_currentElement != null && _currentElement.IsAvailable && _currentElement.Element != null) - { - AutomationElement root = _currentElement.Element; - _expandPickedTree = true; - if (!result.IsWindowOnlyPick) - { - SetStatus("已拾取 UIA 元素:" + _currentElement + ";正在读取控件树……", null); - } - - BeginTreeRead( - result.Window == null ? IntPtr.Zero : result.Window.Handle, - root, - result.Window, - "被拾取控件 " + _currentElement); return; } - SetStatus("已拾取窗口,但 UIA 元素不可用:" + (result.FailureReason ?? "未知原因"), null); - if (result.Window != null) + int wanted = node.Source == ControlTreeSource.Uia ? 1 : node.Source == ControlTreeSource.Msaa ? 2 : 3; + if (_treeSourceCombo.SelectedIndex == wanted) { - // Still show the window's tree so the window is not a dead end. - BeginTreeRead(result.Window.Handle, null, result.Window, result.Window.ToString()); + return; } + + _suppressTreeSourceEvents = true; + try + { + _treeSourceCombo.SelectedIndex = wanted; + } + finally + { + _suppressTreeSourceEvents = false; + } + + SetStatus("拾取的是 " + node.Source + " 来源的控件,控件树来源已切到 " + node.Source + + ",这样节点一定在同一棵树里。", null); + } + + private void ApplyPickResult(PointPickResult result) + { + ControlTreeNode pickedNode = BuildPickedNode(result); + if (result.Window == null || pickedNode == null) + { + SetStatus("未能确定拾取控件:" + result.FailureReason, null); + return; + } + IntPtr rootHandle = NativeMethods.GetAncestor(result.Window.Handle, NativeMethods.GA_ROOT); + if (rootHandle == IntPtr.Zero) rootHandle = result.Window.Handle; + NativeWindowInfo rootWindow = _windowService.Capture(rootHandle) ?? result.Window; + _currentElement = pickedNode.Uia; + _inspectedWindow = rootWindow; + _locateFollower.Hide("拾取完成,已隐藏高亮框。"); + _autoAddPendingPick = _autoAddedPickSession != _pickSession; + RefreshWindows(); + SelectWindowItem(rootWindow); + _expandPickedTree = result.IsWindowOnlyPick; + _pendingTreeSelection = pickedNode; + EnsureTreeSourceFor(pickedNode); + SetStatus("正在从顶层窗口读取统一控件树,确认拾取身份后新增未启用的监控项。", null); + BeginTreeRead(rootHandle, null, rootWindow, "被拾取控件 " + pickedNode); } /// @@ -1461,9 +1561,9 @@ namespace pacs_win_uia IntPtr handle = window.Handle; _inspectButton.Enabled = false; - _exportButton.Enabled = false; - _exportListButton.Enabled = false; - _readListButton.Enabled = false; + _exportTreeItem.Enabled = false; + _exportListItem.Enabled = false; + _readListItem.Enabled = false; _lastListResult = null; CancelListRead(); SetStatus("正在读取 UIA 控件树……", null); @@ -1498,8 +1598,11 @@ namespace pacs_win_uia CancellationToken token = _inspectionCancellation.Token; int sequence = ++_inspectionSequence; ControlTreeSource? source = GetSelectedTreeSource(); + bool changedWindow = _treeRootHandle != handle; _treeRootHandle = handle; - _treeUiaRoot = uiaRoot; + _treeUiaRoot = null; + _nodeMapOverlay.HideMap(); + if (changedWindow) _nodeMapItem.Checked = false; _treeWindow = window; _currentTreeSource = source; _currentTreeRoot = null; @@ -1614,6 +1717,65 @@ namespace pacs_win_uia TaskScheduler.Default); } + private void LiveTreeTimerOnTick(object sender, EventArgs e) + { + if (IsDisposed || _shutdown.IsCancellationRequested || _picker.IsPicking || + _treeReadTimer.Enabled || _liveTreeReadInFlight || _treeRootHandle == IntPtr.Zero) + { + return; + } + + if (!NativeMethods.IsWindow(_treeRootHandle)) + { + ClearInspectionState(); + return; + } + + _liveTreeReadInFlight = true; + _liveTreeStartedUtc = DateTime.UtcNow; + int sequence = _inspectionSequence; + IntPtr handle = _treeRootHandle; + ControlTreeSource? source = GetSelectedTreeSource(); + var options = new ControlTreeOptions + { + MaxDepth = _settings.Ui.TreeMaxDepth, + MaxNodes = _settings.Ui.TreeMaxNodes, + Timeout = TimeSpan.FromSeconds(_settings.Ui.TreeTimeoutSeconds) + }; + CancellationToken token = _shutdown.Token; + Task.Factory.StartNew(() => _controlTreeService.Read(handle, null, source, options, token), + CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default) + .ContinueWith(task => + { + Exception error = task.IsFaulted ? task.Exception.GetBaseException() : null; + try + { + if (!IsDisposed && IsHandleCreated) + { + BeginInvoke((Action)delegate + { + _liveTreeReadInFlight = false; + if (IsDisposed || sequence != _inspectionSequence || handle != _treeRootHandle) + return; + if (error != null || task.IsCanceled || task.Result == null) + { + _nodeMapOverlay.HideMap(); + return; + } + + ControlTreeResult result = task.Result; + _currentTree = _currentTreeRoot = result.Root; + _monitorEditor.SetTreeRoot(_currentTreeRoot); + ReconcileTreeView(false); + _lastLiveTreeUtc = DateTime.UtcNow; + if (_nodeMapItem.Checked) ShowNodeMap(); + }); + } + } + catch (InvalidOperationException) { } + }, TaskScheduler.Default); + } + /// Selected tree source; null means auto. private ControlTreeSource? GetSelectedTreeSource() { @@ -1687,6 +1849,7 @@ namespace pacs_win_uia _inspectedWindow = inspectedWindow; _currentTreeRoot = result == null ? null : result.Root; _currentTree = _currentTreeRoot; + _monitorEditor.SetTreeRoot(_currentTreeRoot); LogTreeResult(result, label); RebuildTreeView(); @@ -1697,6 +1860,7 @@ namespace pacs_win_uia if (_controlTree.Nodes.Count > 0) { _controlTree.Nodes[0].Expand(); + if (_controlTree.SelectedNode == null) _controlTree.SelectedNode = _controlTree.Nodes[0]; if (expandDeep) { // A picked control is what the operator is looking at: show its children too. @@ -1710,15 +1874,22 @@ namespace pacs_win_uia } } - _exportButton.Enabled = _currentTreeRoot != null; - _exportListButton.Enabled = _lastListResult != null; + _exportTreeItem.Enabled = _currentTreeRoot != null; + _exportListItem.Enabled = _lastListResult != null; _activateButton.Enabled = _treeRootHandle != IntPtr.Zero; _currentElement = _currentTreeRoot == null ? null : _currentTreeRoot.Uia; - _readListButton.Enabled = _currentElement != null && _currentElement.IsAvailable && + _readListItem.Enabled = _currentElement != null && _currentElement.IsAvailable && _currentElement.Element != null && !_picker.IsPicking; _propertyGrid.SelectedObject = SelectedObjectFor(_currentTreeRoot); _monitorEditor.SetCurrentNode(_currentTreeRoot, _inspectedWindow); ShowNodeProperties(_currentTreeRoot); + // A locate that had to read the tree of another window selects its node only now. + ApplyPendingTreeSelection(); + if (_nodeMapItem.Checked) + { + // The frames belong to the tree that was just replaced. + ShowNodeMap(); + } string source = result == null ? "(无)" : result.UsedSource.ToString(); string note = result == null ? null : result.Note; @@ -1850,6 +2021,9 @@ namespace pacs_win_uia if (element != null) { element.EnsureRuntimeId(); + // 控件属性 里直接给出 path / 页面特征 / 焦点,省得来回切换去找。 + element.ControlPath = DescribeNodePath(node); + element.PageFeatures = ControlLocatorBuilder.DescribePageFeatures(node.Window ?? _inspectedWindow); } _currentNode = node; @@ -1858,9 +2032,9 @@ namespace pacs_win_uia _currentNode = node; _propertyGrid.SelectedObject = SelectedObjectFor(node); _propertyGrid.Refresh(); - _screenshotButton.Enabled = node != null; - _ocrButton.Enabled = node != null; - _copyFeaturesButton.Enabled = node != null; + _screenshotItem.Enabled = node != null; + _ocrItem.Enabled = node != null; + _copyFeaturesItem.Enabled = node != null; } /// The selected node's page features (process/class/title keyword), shown above the grid. @@ -1878,6 +2052,169 @@ namespace pacs_win_uia : "控件属性 —— 页面特征:" + features + "(可复制到悬浮按钮的显示条件)"; } + // ------------------------------------------------------------------ path / node map + + /// + /// Pastes a path (the format the tool prints anywhere) and locates it in the current window. + /// This is the "why does my path not resolve" tool: it reports the first segment that fails and + /// what was actually matched, instead of silently highlighting a same-named control elsewhere. + /// + private void LocateByPath() + { + if (_treeRootHandle == IntPtr.Zero) + { + SetStatus("还没有根窗口:先在窗口列表里选中一个窗口,或拾取一个控件,再按 path 定位。", null); + return; + } + + string initial = DescribeNodePath(_currentNode); + string windowText = _treeWindow == null + ? NativeWindowInfo.FormatHandle(_treeRootHandle) + : _treeWindow.ToString(); + string path; + using (var dialog = new PathLocateForm(initial, windowText)) + { + if (dialog.ShowDialog(this) != DialogResult.OK) + { + return; + } + + path = dialog.PathText; + } + + string error; + IList matches = ControlPath.Select(_currentTreeRoot, path, out error); + if (error != null || matches.Count != 1) + { + SetStatus(error ?? ("path 匹配 " + matches.Count + " 个节点,需要唯一命中;请补充属性或序号。"), null); + return; + } + ControlTreeNode node = matches[0]; + SelectTreeNodeFor(node); + if (node.Uia != null) ShowFrameFor(node.Uia, _treeRootHandle, "path 定位"); + SetStatus("path 已唯一匹配当前窗口树:" + node.CanonicalPath, null); + } + + /// Draws the follower frame for a UIA element (used by 按 path 定位). + private void ShowFrameFor(UiaElementInfo element, IntPtr anchor, string label) + { + if (element == null || element.BoundingRectangle == null || !element.BoundingRectangle.IsValid) + { + SetStatus("控件没有可用的屏幕矩形,无法画框。", null); + return; + } + + Rectangle rect = element.BoundingRectangle.ToRectangle(); + string reason; + if (!WindowVisibility.IsVisibleOnScreen(anchor, rect, Process.GetCurrentProcess().Id, out reason)) + { + SetStatus("控件位置读到了,但暂时不画框:" + reason, null); + return; + } + + _locatedDefinition = null; + _locatedNode = new ControlTreeNode { Source = ControlTreeSource.Uia, Uia = element }; + _locateFollower.Show(rect, anchor, BuildBoundsResolver(null, _locatedNode), label); + } + + /// + /// Turns on/off a frame around every control of the current tree. Rectangles come from the tree + /// already in memory, so this costs nothing on the target application. + /// + private void ToggleNodeMap() + { + if (!_nodeMapItem.Checked) + { + _nodeMapOverlay.HideMap(); + SetStatus("已隐藏所有控件的框。", null); + return; + } + + ShowNodeMap(); + } + + private void ShowNodeMap() + { + if (_currentTreeRoot == null || _treeRootHandle == IntPtr.Zero) + { + _nodeMapItem.Checked = false; + SetStatus("先选中窗口或拾取控件,让控件树有内容,再绘制所有控件框。", null); + return; + } + + var rects = new List(); + CollectNodeBounds(_currentTreeRoot, rects); + if (rects.Count == 0) + { + _nodeMapItem.Checked = false; + SetStatus("当前控件树里没有带有效矩形的节点(该来源可能不提供坐标)。", null); + return; + } + + IntPtr anchor = NativeMethods.GetAncestor(_treeRootHandle, NativeMethods.GA_ROOT); + if (anchor == IntPtr.Zero) + { + anchor = _treeRootHandle; + } + + if (_nodeMapOverlay.IsShown) + _nodeMapOverlay.SetItems(rects); + else + { + _nodeMapOverlay.ShowMapItems(anchor, rects); + SetStatus("已开启实时控件框:仅在目标前台显示,遮挡区域不绘制;右侧可点击框复制 path 或退出。", null); + } + } + + private static void CollectNodeBounds(ControlTreeNode node, IList target) + { + if (node == null) + { + return; + } + + NativeRectangleInfo bounds = null; + if (node.Uia != null && node.Uia.BoundingRectangle != null && node.Uia.BoundingRectangle.IsValid) + { + bounds = node.Uia.BoundingRectangle; + } + else if (node.Msaa != null && node.Msaa.Location != null && node.Msaa.Location.IsValid) + { + bounds = node.Msaa.Location; + } + else if (node.Window != null && node.Window.WindowBounds != null && node.Window.WindowBounds.IsValid) + { + bounds = node.Window.WindowBounds; + } + + if (bounds != null && !(node.Uia != null && node.Uia.IsOffscreen == true) && + !(node.Window != null && !node.Window.IsVisible)) + { + target.Add(new NodeMapItem(bounds.ToRectangle(), node, node.CanonicalPath)); + } + + foreach (ControlTreeNode child in node.Children) + { + CollectNodeBounds(child, target); + } + } + + /// + /// The path text of a node, in the same format the resolver reads. Built from the tree already in + /// memory (no cross-process calls), so it can be shown in the property grid and copied into + /// 「按 path 定位」 to check a saved path. + /// + private string DescribeNodePath(ControlTreeNode node) + { + if (node == null) + { + return null; + } + + // Same code the resolver walks, so what is shown here can be pasted back into 按 path 定位. + return ControlLocatorBuilder.DescribePathFromTree(_currentTreeRoot, node); + } + /// Copies the selected node's page features for pasting into a floating-bar condition. private void CopyCurrentPageFeatures() { @@ -1906,6 +2243,74 @@ namespace pacs_win_uia } /// Object shown in the property grid for a node, per source. + private void SyncSelectedTreeProperties(ControlTreeNode node) + { + if (node == null || _propertyGrid.ContainsFocus || _propertyGrid.SelectedObject is ControlMonitorDefinition) + return; + object displayed = _propertyGrid.SelectedObject; + object latest = SelectedObjectFor(node); + if (displayed == null || latest == null || displayed.GetType() != latest.GetType()) return; + bool changed = false; + if (displayed is UiaElementInfo oldUia && latest is UiaElementInfo newUia) + { + changed |= CopyIfDifferent(() => oldUia.Name, value => oldUia.Name = value, newUia.Name); + changed |= CopyIfDifferent(() => oldUia.AutomationId, value => oldUia.AutomationId = value, newUia.AutomationId); + changed |= CopyIfDifferent(() => oldUia.ControlType, value => oldUia.ControlType = value, newUia.ControlType); + changed |= CopyIfDifferent(() => oldUia.ClassName, value => oldUia.ClassName = value, newUia.ClassName); + changed |= CopyIfDifferent(() => oldUia.FrameworkId, value => oldUia.FrameworkId = value, newUia.FrameworkId); + changed |= CopyIfDifferent(() => oldUia.NativeWindowHandle, value => oldUia.NativeWindowHandle = value, newUia.NativeWindowHandle); + changed |= CopyIfDifferent(() => oldUia.ProcessId, value => oldUia.ProcessId = value, newUia.ProcessId); + changed |= CopyIfDifferent(() => oldUia.IsEnabled, value => oldUia.IsEnabled = value, newUia.IsEnabled); + changed |= CopyIfDifferent(() => oldUia.IsOffscreen, value => oldUia.IsOffscreen = value, newUia.IsOffscreen); + changed |= CopyRectangleIfDifferent(() => oldUia.BoundingRectangle, value => oldUia.BoundingRectangle = value, newUia.BoundingRectangle); + changed |= CopyIfDifferent(() => oldUia.HasKeyboardFocus, value => oldUia.HasKeyboardFocus = value, newUia.HasKeyboardFocus); + changed |= CopyIfDifferent(() => oldUia.IsKeyboardFocusable, value => oldUia.IsKeyboardFocusable = value, newUia.IsKeyboardFocusable); + changed |= CopyIfDifferent(() => oldUia.ControlPath, value => oldUia.ControlPath = value, newUia.ControlPath); + changed |= CopyIfDifferent(() => oldUia.PageFeatures, value => oldUia.PageFeatures = value, newUia.PageFeatures); + } + else if (displayed is MsaaNodeInfo oldMsaa && latest is MsaaNodeInfo newMsaa) + { + changed |= CopyIfDifferent(() => oldMsaa.Name, value => oldMsaa.Name = value, newMsaa.Name); + changed |= CopyIfDifferent(() => oldMsaa.Value, value => oldMsaa.Value = value, newMsaa.Value); + changed |= CopyIfDifferent(() => oldMsaa.RoleText, value => oldMsaa.RoleText = value, newMsaa.RoleText); + changed |= CopyIfDifferent(() => oldMsaa.StateText, value => oldMsaa.StateText = value, newMsaa.StateText); + changed |= CopyRectangleIfDifferent(() => oldMsaa.Location, value => oldMsaa.Location = value, newMsaa.Location); + changed |= CopyIfDifferent(() => oldMsaa.Error, value => oldMsaa.Error = value, newMsaa.Error); + } + else if (displayed is NativeWindowInfo oldWindow && latest is NativeWindowInfo newWindow) + { + changed |= CopyIfDifferent(() => oldWindow.Title, value => oldWindow.Title = value, newWindow.Title); + changed |= CopyIfDifferent(() => oldWindow.ClassName, value => oldWindow.ClassName = value, newWindow.ClassName); + changed |= CopyIfDifferent(() => oldWindow.IsVisible, value => oldWindow.IsVisible = value, newWindow.IsVisible); + changed |= CopyIfDifferent(() => oldWindow.IsMinimized, value => oldWindow.IsMinimized = value, newWindow.IsMinimized); + changed |= CopyRectangleIfDifferent(() => oldWindow.WindowBounds, value => oldWindow.WindowBounds = value, newWindow.WindowBounds); + changed |= CopyRectangleIfDifferent(() => oldWindow.ClientBounds, value => oldWindow.ClientBounds = value, newWindow.ClientBounds); + } + if (changed) _propertyGrid.Refresh(); + } + + private static bool CopyRectangleIfDifferent(Func read, Action write, NativeRectangleInfo value) + { + NativeRectangleInfo old = read(); + bool same = old == null && value == null; + if (!same && old != null && value != null) + { + same = old.Left == value.Left && old.Top == value.Top && old.Right == value.Right && + old.Bottom == value.Bottom && old.IsValid == value.IsValid; + } + if (same) return false; + write(value); + return true; + } + + private static bool CopyIfDifferent(Func read, Action write, T value) + { + T old = read(); + if (Equals(old, value)) return false; + write(value); + return true; + } + private static object SelectedObjectFor(ControlTreeNode node) { if (node == null) @@ -1958,83 +2363,106 @@ namespace pacs_win_uia /// private void RebuildTreeView() { + ReconcileTreeView(true); + } + + private void ReconcileTreeView(bool searchChanged) + { + TreeNode previousSelection = _controlTree.SelectedNode; + // The grid intentionally remains a user-selected snapshot during live reads. Rebinding + // every 300 ms destroys property expansion/edit state (including monitor edits). + bool showingTreeProperties = _propertyGrid.SelectedObject is UiaElementInfo || + _propertyGrid.SelectedObject is MsaaNodeInfo || + (_currentNode != null && _propertyGrid.SelectedObject is NativeWindowInfo); TreeSearchCriteria criteria = _treeSearchPanel.Criteria; + _pathSearchMatches = null; + string query = IsPathQuery(criteria.Path) ? criteria.Path : IsPathQuery(criteria.Any) ? criteria.Any : null; + if (query != null && _currentTreeRoot != null) + { + string error; + _pathSearchMatches = new HashSet(ControlPath.Select(_currentTreeRoot, query, out error)); + if (error != null) SetStatus("路径搜索:" + error, null); + if (IsPathQuery(criteria.Path)) criteria.Path = null; + if (IsPathQuery(criteria.Any)) criteria.Any = null; + } bool filter = _treeSearchPanel.OnlyMatches; - _treeMatches.Clear(); - _controlTree.BeginUpdate(); + ControlTreeReconciler.Item root = BuildTreeItem(_currentTreeRoot, criteria, filter); + if (_treeReconciler == null) _treeReconciler = new ControlTreeReconciler(_controlTree); + _restoringTreeState = true; try { - _controlTree.Nodes.Clear(); - if (_currentTreeRoot != null) - { - TreeNode root = BuildTreeNode(_currentTreeRoot, string.Empty, criteria, filter); - if (root != null) - { - _controlTree.Nodes.Add(root); - root.Expand(); - } - } + _treeReconciler.Apply(root, _treeMatches); } finally { - _controlTree.EndUpdate(); + _restoringTreeState = false; } _treeSearchPanel.SetMatchCount(_treeMatches.Count); _treeSearchPanel.SetNavigationEnabled(_treeMatches.Count > 0); - if (!criteria.IsEmpty) + { + var selected = _controlTree.SelectedNode == null ? null : _controlTree.SelectedNode.Tag as ControlTreeNode; + _currentNode = selected; + _currentElement = selected == null ? null : selected.Uia; + _monitorEditor.SetCurrentNode(selected, _inspectedWindow); + _readListItem.Enabled = _currentElement != null && _currentElement.IsAvailable && + _currentElement.Element != null && !_picker.IsPicking; + _screenshotItem.Enabled = _ocrItem.Enabled = _copyFeaturesItem.Enabled = selected != null; + // A disappeared/filtered selection must not leave an actionable stale snapshot. + // Monitor definitions are never replaced, even when selection moves during a tick. + if (showingTreeProperties && previousSelection == _controlTree.SelectedNode) + { + SyncSelectedTreeProperties(selected); + } + else if (showingTreeProperties && previousSelection != _controlTree.SelectedNode) + { + if (searchChanged) ShowNodeProperties(selected); + else + { + _propertyGrid.SelectedObject = null; + UpdatePropertyCaption(selected); + } + } + } + if (searchChanged && !criteria.IsEmpty) { AppLog.Info("控件树搜索:匹配 " + _treeMatches.Count + " 项" + (filter ? "(仅显示匹配)" : "(全部显示,匹配项高亮)")); } } - private TreeNode BuildTreeNode(ControlTreeNode node, string parentPath, TreeSearchCriteria criteria, bool filter) + private static bool IsPathQuery(string text) { - if (node == null) - { - return null; - } + return ControlPath.IsXPath(text); + } - string text = node.Describe(); - string path = string.IsNullOrEmpty(parentPath) ? text : parentPath + " > " + text; + private ControlTreeReconciler.Item BuildTreeItem(ControlTreeNode node, TreeSearchCriteria criteria, bool filter) + { + if (node == null) return null; + string path = node.CanonicalPath ?? DescribeNodePath(node); bool focused = node.Uia != null && node.Uia.HasKeyboardFocus.HasValue && node.Uia.HasKeyboardFocus.Value; - bool selfMatches = criteria.Matches(node, path, focused); - - var treeNode = new TreeNode(text) { Tag = node }; - int before = _treeMatches.Count; + bool selfMatches = criteria.Matches(node, path, focused) && + (_pathSearchMatches == null || _pathSearchMatches.Contains(node)); + var item = new ControlTreeReconciler.Item + { + Model = node, + Text = node.Describe(), + Match = selfMatches, + ForeColor = node.Source == ControlTreeSource.Win32 && node.Window != null && !node.Window.IsVisible + ? Color.Gray : _controlTree.ForeColor + }; foreach (ControlTreeNode child in node.Children) { - TreeNode childNode = BuildTreeNode(child, path, criteria, filter); - if (childNode != null) - { - treeNode.Nodes.Add(childNode); - } + ControlTreeReconciler.Item childItem = BuildTreeItem(child, criteria, filter); + if (childItem != null) item.Children.Add(childItem); } - - bool descendantMatches = _treeMatches.Count > before; - if (selfMatches) - { - _treeMatches.Add(treeNode); - // Bold, not coloured: the operator asked for colours to stay in the window list. - treeNode.NodeFont = new Font(_controlTree.Font, FontStyle.Bold); - } - + if (!selfMatches && filter && item.Children.Count == 0) return null; if (!node.ChildrenComplete) - { - treeNode.Nodes.Add(new TreeNode("[读取不完整] " + (node.ChildrenError ?? "未知原因"))); - } - - if (node.Source == ControlTreeSource.Win32 && node.Window != null && !node.Window.IsVisible) - { - treeNode.ForeColor = Color.Gray; - } - - if (selfMatches || descendantMatches || criteria.IsEmpty || !filter) - { - return treeNode; - } - - return null; + item.Children.Add(new ControlTreeReconciler.Item + { + Text = "[读取不完整] " + (node.ChildrenError ?? "未知原因"), + ForeColor = _controlTree.ForeColor + }); + return item; } /// Moves the selection to the next/previous search hit, wrapping around. @@ -2065,17 +2493,13 @@ namespace pacs_win_uia _controlTree.SelectedNode = target; } - private TreeNode CreateTreeNode(ControlTreeNode node) - { - return BuildTreeNode(node, string.Empty, new TreeSearchCriteria(), false); - } - private void ControlTreeOnAfterSelect(object sender, TreeViewEventArgs e) { + if (_restoringTreeState) return; CancelListRead(); _lastListResult = null; ClearListResultGrid(); - _exportListButton.Enabled = false; + _exportListItem.Enabled = false; var node = e.Node == null ? null : e.Node.Tag as ControlTreeNode; _currentElement = node == null ? null : node.Uia; @@ -2085,11 +2509,11 @@ namespace pacs_win_uia if (_currentElement != null && _currentElement.IsAvailable && _currentElement.Element != null) { - _readListButton.Enabled = !_picker.IsPicking; + _readListItem.Enabled = !_picker.IsPicking; return; } - _readListButton.Enabled = false; + _readListItem.Enabled = false; if (node != null && node.Source != ControlTreeSource.Uia) { SetStatus("当前节点来自 " + node.Source @@ -2123,7 +2547,7 @@ namespace pacs_win_uia AutomationElement element = _currentElement.Element; _lastListReadElement = _currentElement.ControlType + " / " + _currentElement.Name + " / RuntimeId=" + _currentElement.RuntimeId; - _readListButton.Enabled = false; + _readListItem.Enabled = false; SetStatus("正在读取标准 UIA 列表模式……", null); AppLog.Info("开始读取列表:" + _lastListReadElement); @@ -2177,7 +2601,7 @@ namespace pacs_win_uia return; } - _readListButton.Enabled = true; + _readListItem.Enabled = true; if (completed.IsCanceled) { SetStatus("列表读取已取消。", null); @@ -2189,7 +2613,7 @@ namespace pacs_win_uia else { _lastListResult = completed.Result; - _exportListButton.Enabled = _lastListResult != null; + _exportListItem.Enabled = _lastListResult != null; AppLog.Info("列表读取耗时 " + stopwatch.ElapsedMilliseconds + " ms。"); ApplyListResult(completed.Result); if (_lastListResult != null && @@ -2548,7 +2972,10 @@ namespace pacs_win_uia _propertyGrid.SelectedObject = e.Definition; _propertyGrid.Refresh(); - if (_locatedDefinition == e.Definition && _locateHighlight.Visible) + // Toggling off is for the deliberate asks (定位按钮 / 行头 / 悬浮按钮). A click in the + // monitor grid must always end with the frame on screen, otherwise the operator ends up + // clicking repeatedly wondering why nothing happens. + if (e.Explicit && _locatedDefinition == e.Definition && _locateFollower.IsTracking) { HideLocateFrame("已隐藏高亮框。"); return; @@ -2561,16 +2988,185 @@ namespace pacs_win_uia return; } - _locateHighlight.ShowHighlight(e.Bounds.ToRectangle()); _locatedDefinition = e.Definition; - _locatedAnchor = e.AnchorWindow; _locatedNode = e.Node; - _locateWatchTimer.Start(); - SelectTreeNodeFor(e.Node); + _locateFollower.Show( + e.Bounds.ToRectangle(), + e.AnchorWindow, + BuildBoundsResolver(e.Definition, e.Node), + "定位框"); SetStatus(e.UsedFallback ? "已高亮该控件(" + e.Bounds + "),但这次是用容错规则定位的,框的位置可能不准:" + "建议在界面里重新添加该控件;再点一次行头可隐藏。" : "已在屏幕上高亮该控件(" + e.Bounds + ");再点一次行头可隐藏。", null); + // Selecting the node may find the tree belongs to another window, in which case that + // window's tree is read and this message is replaced by the more specific one. + SelectTreeNodeFor(e.Node); + EnsureTreeShows(e); + } + + /// + /// The locate frame has to survive the target window being closed, minimized or covered, and it + /// has to follow the window while it is dragged. All of that lives in the follower; this is + /// only the reporting and the bookkeeping. + /// + private void LocateFollowerOnHidden(object sender, HighlightHiddenEventArgs e) + { + _locatedDefinition = null; + _locatedNode = null; + SetStatus(e.Reason, null); + } + + /// + /// Corrects the frame's offset every few seconds, on a background thread. UIA and MSAA + /// re-resolution can block inside another process, so it must never run on the UI thread; + /// Win32 rectangles are read directly. + /// + private Func BuildBoundsResolver(ControlMonitorDefinition definition, ControlTreeNode node) + { + UiaElementInfo element = node == null ? null : node.Uia; + if (element != null && element.Element != null) + { + AutomationElement automationElement = element.Element; + return delegate + { + System.Windows.Rect rect = automationElement.Current.BoundingRectangle; + if (rect.IsEmpty || double.IsInfinity(rect.Left) || double.IsInfinity(rect.Top)) + { + return (Rectangle?)null; + } + + return new Rectangle( + (int)Math.Round(rect.Left), (int)Math.Round(rect.Top), + (int)Math.Round(rect.Width), (int)Math.Round(rect.Height)); + }; + } + + if (node != null && node.Window != null && node.Window.Handle != IntPtr.Zero) + { + IntPtr handle = node.Window.Handle; + return delegate + { + NativeMethods.RECT rect; + if (!NativeMethods.GetWindowRect(handle, out rect)) + { + return (Rectangle?)null; + } + + return new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); + }; + } + + if (definition == null) + { + return null; + } + + // MSAA (and any locator that only has a path) has to be resolved again from its saved + // locator; that is the slowest path, which is why the follower runs it rarely. + return delegate + { + var steps = new List(); + string error; + IntPtr window = _locatorService.FindTargetWindow(definition, steps, out error); + if (window == IntPtr.Zero) + { + return (Rectangle?)null; + } + + ControlResolution resolution = _locatorService.Resolve(definition, window, steps); + if (!resolution.Found || resolution.Node == null) + { + return (Rectangle?)null; + } + + return BoundsOfNode(resolution.Node); + }; + } + + private static Rectangle? BoundsOfNode(ControlTreeNode node) + { + NativeRectangleInfo bounds = null; + if (node.Uia != null && node.Uia.BoundingRectangle != null && node.Uia.BoundingRectangle.IsValid) + { + bounds = node.Uia.BoundingRectangle; + } + else if (node.Msaa != null && node.Msaa.Location != null && node.Msaa.Location.IsValid) + { + bounds = node.Msaa.Location; + } + else if (node.Window != null && node.Window.WindowBounds != null && node.Window.WindowBounds.IsValid) + { + bounds = node.Window.WindowBounds; + } + + return bounds == null ? (Rectangle?)null : bounds.ToRectangle(); + } + + /// + /// A located monitor entry may live in a window whose tree is not the one on screen. Selecting + /// a row has to end with the control visible in the tree, so the tree of its own window is read + /// and the node selected when the read completes. + /// + private void EnsureTreeShows(ControlLocatedEventArgs e) + { + if (e.Node == null || e.AnchorWindow == IntPtr.Zero) + { + return; + } + + if (FindTreeNode(_controlTree.Nodes, e.Node) != null) + { + return; + } + + if (e.AnchorWindow == _treeRootHandle) + { + // Same window, different source/content: re-reading would not help. + return; + } + + NativeWindowInfo window = _windowService.Capture(e.AnchorWindow); + if (window == null) + { + return; + } + + _pendingTreeSelection = e.Node; + SetStatus("该控件属于另一个窗口(" + window + "),正在读取它的控件树……", null); + BeginTreeRead(e.AnchorWindow, null, window, "定位监控项"); + } + + /// + /// Selects the node that was waiting for its tree (a picked control, or a located monitor entry + /// whose window had to be read). When the freshly read tree does not contain it, the tree is + /// read once more rooted at the picked element — the fallback that keeps "拾取后一定能在控件树里 + /// 找到它" true for controls that only exist in an inner window's view. + /// + private void ApplyPendingTreeSelection() + { + ControlTreeNode pending = _pendingTreeSelection; + if (pending == null) + { + return; + } + + _pendingTreeSelection = null; + if (SelectTreeNodeFor(pending)) + { + if (_autoAddPendingPick) + { + _autoAddPendingPick = false; + _autoAddedPickSession = _pickSession; + string added; + _monitorEditor.AddCurrentNode(false, out added); + AppLog.Info(added); + } + return; + } + + _autoAddPendingPick = false; + SetStatus("当前窗口树中没有拾取到的节点(控件已变化或读取被截断)。不会改用另一棵子树或保存猜测路径;请提高读取限制后重试。", null); } /// @@ -2606,78 +3202,10 @@ namespace pacs_win_uia return true; } - /// Keeps the frame glued to a UIA control while the window moves or scrolls. - private void RefreshLocatedFrameBounds() - { - UiaElementInfo element = _locatedNode == null ? null : _locatedNode.Uia; - if (element == null || element.Element == null) - { - return; - } - - try - { - System.Windows.Rect rect = element.Element.Current.BoundingRectangle; - if (rect.IsEmpty || double.IsInfinity(rect.Left) || double.IsInfinity(rect.Top)) - { - HideLocateFrame("控件已不可见,已隐藏高亮框。"); - return; - } - - var bounds = new NativeRectangleInfo( - (int)Math.Round(rect.Left), (int)Math.Round(rect.Top), - (int)Math.Round(rect.Right), (int)Math.Round(rect.Bottom)); - if (!bounds.IsValid) - { - return; - } - - if (_locateHighlight.Bounds != bounds.ToRectangle()) - { - _locateHighlight.ShowHighlight(bounds.ToRectangle()); - } - } - catch (Exception) - { - HideLocateFrame("控件已失效,已隐藏高亮框。"); - } - } - - /// Hides the frame when the target window is gone or minimized, so nothing stale is left behind. - private void LocateWatchTimerOnTick(object sender, EventArgs e) - { - if (!_locateHighlight.Visible) - { - _locateWatchTimer.Stop(); - return; - } - - if (_locatedAnchor == IntPtr.Zero) - { - return; - } - - if (!NativeMethods.IsWindow(_locatedAnchor)) - { - HideLocateFrame("目标窗口已关闭,已隐藏高亮框。"); - return; - } - - if (NativeMethods.IsIconic(_locatedAnchor)) - { - HideLocateFrame("目标窗口已最小化,已隐藏高亮框。"); - return; - } - - RefreshLocatedFrameBounds(); - } - private void HideLocateFrame(string reason) { - _locateHighlight.HideHighlight(); - _locateWatchTimer.Stop(); + _locateFollower.Hide(reason); _locatedDefinition = null; - _locatedAnchor = IntPtr.Zero; _locatedNode = null; if (!string.IsNullOrEmpty(reason)) { @@ -2685,30 +3213,35 @@ namespace pacs_win_uia } } - /// Finds the tree node for a resolved control and selects it (expanding its ancestors). - private void SelectTreeNodeFor(ControlTreeNode target) + /// + /// Finds the tree node for a resolved control, expands its ancestors and selects it. + /// + /// False when the current tree has no node for it (the caller may read another tree). + private bool SelectTreeNodeFor(ControlTreeNode target) { if (target == null) { - return; + return false; } if (_currentTreeRoot == null) { - SetStatus("已在屏幕上高亮该控件;当前没有控件树,先选中它的窗口再试可以看到节点联动。", null); - return; + SetStatus("当前没有控件树,先选中它的窗口再试可以看到节点联动。", null); + return false; } TreeNode found = FindTreeNode(_controlTree.Nodes, target); if (found == null) { - AppLog.Info("定位到控件,但当前控件树里没有对应节点(来源或窗口不同)。"); - SetStatus("已在屏幕上高亮该控件;但当前控件树是其它窗口/来源的,没有对应节点。", null); - return; + AppLog.Info("控件树里没有对应节点(来源或窗口不同)。"); + SetStatus("当前控件树是其它窗口/来源的,没有对应节点。", null); + return false; } found.EnsureVisible(); _controlTree.SelectedNode = found; + _resultTabs.SelectedTab = _controlTreeTab; + return true; } private static TreeNode FindTreeNode(TreeNodeCollection nodes, ControlTreeNode target) @@ -2747,10 +3280,15 @@ namespace pacs_win_uia case ControlTreeSource.Win32: return left.Window != null && right.Window != null && left.Window.Handle == right.Window.Handle; default: - return left.Uia != null && right.Uia != null && - string.Equals(left.Uia.ControlType, right.Uia.ControlType, StringComparison.Ordinal) && - string.Equals(left.Uia.AutomationId, right.Uia.AutomationId, StringComparison.Ordinal) && - string.Equals(left.Uia.Name, right.Uia.Name, StringComparison.Ordinal); + if (ReferenceEquals(left, right)) return true; + if (left.Uia == null || right.Uia == null) return false; + if (!string.IsNullOrEmpty(left.Uia.RuntimeId) && !string.IsNullOrEmpty(right.Uia.RuntimeId)) + return string.Equals(left.Uia.RuntimeId, right.Uia.RuntimeId, StringComparison.Ordinal); + if (!string.IsNullOrEmpty(left.CanonicalPath) && !string.IsNullOrEmpty(right.CanonicalPath)) + return left.Uia.ProcessId == right.Uia.ProcessId && + string.Equals(left.CanonicalPath, right.CanonicalPath, StringComparison.Ordinal); + return left.Uia.Element != null && right.Uia.Element != null && + ControlLocatorService.SameElement(left.Uia.Element, right.Uia.Element); } } @@ -2771,6 +3309,48 @@ namespace pacs_win_uia SetStatus(e.Message, e.Exception); } + /// + /// Ctrl+F jumps to the search box that belongs to where the operator is: the tree search while + /// working in the tree tab, the window search everywhere else. Esc-like "get me out" is not + /// needed: Tab moves on normally. + /// + private void MainFormOnKeyDown(object sender, KeyEventArgs e) + { + if (!e.Control || e.KeyCode != Keys.F) + { + return; + } + + bool inTree = IsWithin(_controlTreeTab, ActiveControl); + if (inTree) + { + _resultTabs.SelectedTab = _controlTreeTab; + _treeSearchPanel.FocusSearchBox(); + } + else + { + _windowSearchBox.Focus(); + _windowSearchBox.SelectAll(); + } + + e.Handled = true; + e.SuppressKeyPress = true; + SetStatus(inTree ? "已跳到控件树搜索框。" : "已跳到窗口列表搜索框(Ctrl+F 在控件树页时跳到控件树搜索)。", null); + } + + private static bool IsWithin(Control ancestor, Control control) + { + for (Control current = control; current != null; current = current.Parent) + { + if (ReferenceEquals(current, ancestor)) + { + return true; + } + } + + return false; + } + private void SetStatus(string message, Exception exception) { string detail = exception == null ? string.Empty : Environment.NewLine + exception.GetType().Name + ": " + exception.Message; @@ -2812,6 +3392,8 @@ namespace pacs_win_uia AppLog.Error("退出钩子执行失败。", ex); } + _liveTreeTimer.Stop(); + _liveTreeTimer.Dispose(); _autoInspectTimer.Stop(); _treeReadTimer.Stop(); _treeReadTimer.Tick -= TreeReadTimerOnTick; @@ -2823,10 +3405,12 @@ namespace pacs_win_uia _shutdown.Cancel(); _picker.Dispose(); _activationService.Dispose(); - _locateWatchTimer.Stop(); - _locateWatchTimer.Tick -= LocateWatchTimerOnTick; - _locateWatchTimer.Dispose(); - _locateHighlight.Dispose(); + _locateFollower.Hidden -= LocateFollowerOnHidden; + _locateFollower.Dispose(); + _nodeMapOverlay.Dispose(); + Application.RemoveMessageFilter(_shiftWheel); + KeyDown -= MainFormOnKeyDown; + _miscMenu.Dispose(); _autoInspectTimer.Tick -= AutoInspectTimerOnTick; _autoInspectTimer.Dispose(); _shutdown.Dispose(); diff --git a/src/pacs_win_uia/UI/NodeMapOverlayForm.cs b/src/pacs_win_uia/UI/NodeMapOverlayForm.cs new file mode 100644 index 0000000..7849042 --- /dev/null +++ b/src/pacs_win_uia/UI/NodeMapOverlayForm.cs @@ -0,0 +1,632 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using pacs_win_uia.Interop; +using pacs_win_uia.Services; + +namespace pacs_win_uia.UI +{ + /// An immutable tree-refresh snapshot; Bounds are screen coordinates, Node is caller-owned. + public class NodeMapItem + { + public NodeMapItem(Rectangle bounds, object node = null, string path = null) + { + Bounds = bounds; + Node = node; + Path = path; + } + public Rectangle Bounds { get; private set; } + public object Node { get; private set; } + public string Path { get; private set; } + } + + /// Preferred integration name: one node, its path, and its screen rectangle. + public sealed class NodeMapEntry : NodeMapItem + { + public NodeMapEntry(Rectangle bounds, object node = null, string path = null) + : base(bounds, node, path) { } + + public NodeMapEntry(object node, string path, Rectangle bounds) + : base(bounds, node, path) { } + } + + public sealed class NodeMapSelectionEventArgs : EventArgs + { + internal NodeMapSelectionEventArgs(int index, NodeMapItem item, Point point) + { + Index = index; + Item = item; + ScreenPoint = point; + } + /// Index in the supplied list, including any skipped null/empty items. + public int Index { get; private set; } + public NodeMapItem Item { get; private set; } + public object Node { get { return Item.Node; } } + public string Path { get { return Item.Path; } } + public Point ScreenPoint { get; private set; } + } + + /// + /// Click-through, nonactivating map. Call ShowMapItems/SetItems on the UI thread after each tree + /// refresh; only window geometry is polled here, never UIA. Minimizing/backgrounding suspends + /// rendering without losing the snapshot. Closing the target ends the map. + /// + public sealed class NodeMapOverlayForm : Form + { + private sealed class Entry + { + internal int Index; + internal NodeMapItem Item; + internal Rectangle Offset; + } + + private readonly Timer _timer; + private readonly NodeMapActionsForm _actions; + private readonly List _entries = new List(); + private readonly List _candidates = new List(); + private readonly NativeMethods.LowLevelMouseProc _mouseProc; + private readonly NativeMethods.LowLevelKeyboardProc _keyboardProc; + private IntPtr _mouseHook, _keyboardHook, _anchor; + private Rectangle _anchorBounds; + private bool _shown, _selectionMode, _disposing, _escapeSuppressed; + private int _suppressedButtons, _candidateIndex, _version; + private Entry _pressedEntry; + private int _pressedVersion; + private Point _candidatePoint; + private bool _hasCandidatePoint; + + public NodeMapOverlayForm() + { + FormBorderStyle = FormBorderStyle.None; + ShowInTaskbar = false; + StartPosition = FormStartPosition.Manual; + AutoScaleMode = AutoScaleMode.None; + TopMost = true; + BackColor = Color.Magenta; + TransparencyKey = Color.Magenta; + DoubleBuffered = true; + _mouseProc = MouseHookCallback; + _keyboardProc = KeyboardHookCallback; + _timer = new Timer { Interval = 300 }; + _timer.Tick += OnTimerTick; + _actions = new NodeMapActionsForm(); + _actions.ToggleSelection += delegate { SetSelectionMode(!_selectionMode); }; + _actions.ExitMap += delegate + { + HideMap(); + EventHandler handler = MapExited; + if (handler != null) handler(this, EventArgs.Empty); + }; + } + + public event EventHandler NodeSelected; + /// Preferred event name for MainForm integration; aliases NodeSelected. + public event EventHandler NodePicked + { + add { NodeSelected += value; } + remove { NodeSelected -= value; } + } + public event EventHandler SelectionModeChanged; + public event EventHandler MapExited; + + /// Requested map state (also true while temporarily hidden). Visible is actual visibility. + public bool IsShown { get { return _shown; } } + public bool IsSelectionMode { get { return _selectionMode; } } + public int RectangleCount { get { return _entries.Count; } } + public int RefreshIntervalMs + { + get { return _timer.Interval; } + set + { + if (value < 1) throw new ArgumentOutOfRangeException("value"); + _timer.Interval = value; + } + } + + protected override bool ShowWithoutActivation { get { return true; } } + protected override CreateParams CreateParams + { + get + { + CreateParams parameters = base.CreateParams; + parameters.ExStyle |= NativeMethods.WS_EX_TOOLWINDOW | NativeMethods.WS_EX_NOACTIVATE | + NativeMethods.WS_EX_TRANSPARENT; + return parameters; + } + } + protected override void WndProc(ref Message message) + { + if (message.Msg == NativeMethods.WM_NCHITTEST) + { + message.Result = new IntPtr(NativeMethods.HTTRANSPARENT); + return; + } + if (message.Msg == NativeMethods.WM_MOUSEACTIVATE) + { + message.Result = new IntPtr(NativeMethods.MA_NOACTIVATE); + return; + } + base.WndProc(ref message); + } + + /// Legacy API. Selection events still return the original rectangle-list index. + public void ShowMap(IntPtr anchorWindow, IList screenRectangles) + { + List items = null; + if (screenRectangles != null) + { + items = new List(screenRectangles.Count); + foreach (Rectangle rectangle in screenRectangles) items.Add(new NodeMapItem(rectangle)); + } + ShowMapItems(anchorWindow, items); + } + + /// Preferred entry API. NodeMapEntry derives from NodeMapItem. + public void ShowMap(IntPtr anchorWindow, IList entries) + { + if (entries == null) + { + ShowMapItems(anchorWindow, null); + return; + } + var items = new List(entries.Count); + foreach (NodeMapEntry entry in entries) items.Add(entry); + ShowMapItems(anchorWindow, items); + } + + /// Starts/replaces the map, but never shows it until the target is foreground and visible. + public void ShowMapItems(IntPtr anchorWindow, IList items) + { + if (IsDisposed) throw new ObjectDisposedException(GetType().Name); + IntPtr root = anchorWindow == IntPtr.Zero ? IntPtr.Zero : + NativeMethods.GetAncestor(anchorWindow, NativeMethods.GA_ROOT); + Rectangle bounds; + if (items == null || root == IntPtr.Zero || !TryGetWindowRectangle(root, out bounds)) + { + HideMap(); + return; + } + if (_anchor != root) SetSelectionMode(false); + _anchor = root; + ReplaceItems(items, bounds); + _shown = true; + _timer.Start(); + RefreshMap(); + } + + /// + /// Supplies a new screen-coordinate snapshot without starting a stopped map. Empty lists keep + /// the map session alive, so a later tree refresh can restore its frames. UI thread only. + /// + public void SetItems(IList items) + { + Rectangle bounds; + if (!_shown || !TryGetWindowRectangle(_anchor, out bounds)) return; + ReplaceItems(items, bounds); + RefreshMap(); + } + + private void ReplaceItems(IList items, Rectangle bounds) + { + _version++; + _pressedEntry = null; + _entries.Clear(); + if (items != null) + { + for (int index = 0; index < items.Count; index++) + { + NodeMapItem item = items[index]; + if (item == null || item.Bounds.Width <= 1 || item.Bounds.Height <= 1) continue; + Rectangle offset = item.Bounds; + offset.Offset(-bounds.Left, -bounds.Top); + _entries.Add(new Entry { Index = index, Item = item, Offset = offset }); + } + } + ClearCandidates(); + } + + public void HideMap() + { + _shown = false; + _version++; + _anchor = IntPtr.Zero; + _entries.Clear(); + SetSelectionMode(false); + HideSurfaces(); + _timer.Stop(); + } + + /// Enables hooks only while selecting. On failure, leaves normal click-through mode. + public void SetSelectionMode(bool enabled) + { + enabled = enabled && _shown && Visible && WindowVisibility.IsForegroundWindow(_anchor); + if (enabled == _selectionMode) return; + if (enabled) + { + IntPtr module = NativeMethods.GetModuleHandle(null); + if (_mouseHook == IntPtr.Zero) + _mouseHook = NativeMethods.SetWindowsHookEx(NativeMethods.WH_MOUSE_LL, _mouseProc, module, 0); + if (_keyboardHook == IntPtr.Zero) + _keyboardHook = NativeMethods.SetWindowsHookEx(NativeMethods.WH_KEYBOARD_LL, _keyboardProc, module, 0); + if (_mouseHook == IntPtr.Zero || _keyboardHook == IntPtr.Zero) + { + int error = Marshal.GetLastWin32Error(); + ReleaseHooks(true); + throw new Win32Exception(error, "无法安装选取钩子;未进入选取模式。"); + } + } + _selectionMode = enabled; + _pressedEntry = null; + ClearCandidates(); + _actions.SetSelectionMode(enabled); + if (!enabled) ReleaseHooks(false); + Invalidate(); + EventHandler handler = SelectionModeChanged; + if (handler != null && !_disposing) handler(this, EventArgs.Empty); + } + + private void OnTimerTick(object sender, EventArgs e) { RefreshMap(); } + + /// Immediately recomputes geometry/occlusion. No tree traversal or UIA reads. + public void RefreshMap() + { + if (!_shown || _disposing) return; + if (!NativeMethods.IsWindow(_anchor)) + { + HideMap(); + EventHandler handler = MapExited; + if (handler != null) handler(this, EventArgs.Empty); + return; + } + Region visible; + string reason; + Rectangle bounds; + if (!TryGetWindowRectangle(_anchor, out bounds) || + !WindowVisibility.TryGetVisibleRegion(_anchor, true, null, out visible, out reason)) + { + SetSelectionMode(false); + HideSurfaces(); + return; + } + using (visible) + { + _anchorBounds = bounds; + Bounds = bounds; + _actions.PositionBeside(bounds); + // A clamped action panel may overlap the target at the monitor's right edge. + visible.Exclude(_actions.Bounds); + Region local = visible.Clone(); + local.Translate(-bounds.Left, -bounds.Top); + ReplaceRegion(local); + if (!WindowVisibility.IsForegroundWindow(_anchor)) + { + SetSelectionMode(false); + HideSurfaces(); + return; + } + if (!Visible) Show(); + if (!_actions.Visible) _actions.Show(); + if (_selectionMode) + { + NativeMethods.POINT point; + if (NativeMethods.GetCursorPos(out point)) UpdateCandidates(point.ToDrawingPoint(), false); + } + Invalidate(); + } + } + + private void ReplaceRegion(Region region) + { + Region previous = Region; + Region = region; + if (previous != null && !ReferenceEquals(previous, region)) previous.Dispose(); + } + + private void HideSurfaces() + { + Hide(); + _actions.Hide(); + ReplaceRegion(null); + ClearCandidates(); + } + + private bool CanIntercept(Point point) + { + if (!_selectionMode || !Visible || !WindowVisibility.IsForegroundWindow(_anchor) || + (_actions.Visible && _actions.Bounds.Contains(point))) return false; + // Fresh clipping at click/wheel time prevents stale timer data from swallowing input to + // a newly appeared popup or to the tool's own main/settings windows. + Region visible; + string reason; + if (!WindowVisibility.TryGetVisibleRegion(_anchor, true, null, out visible, out reason)) return false; + using (visible) return visible.IsVisible(point); + } + + private void ClearCandidates() + { + _candidates.Clear(); + _candidateIndex = 0; + _hasCandidatePoint = false; + _actions.SetCandidate(0, 0, null); + } + + private void UpdateCandidates(Point point, bool cycle, int direction = 1) + { + Rectangle bounds; + if (!TryGetWindowRectangle(_anchor, out bounds)) return; + Point local = new Point(point.X - bounds.Left, point.Y - bounds.Top); + var hits = new List(); + foreach (Entry entry in _entries) + if (entry.Offset.Contains(local)) hits.Add(entry); + hits.Sort(delegate(Entry left, Entry right) + { + int size = ((long)left.Offset.Width * left.Offset.Height).CompareTo((long)right.Offset.Width * right.Offset.Height); + return size != 0 ? size : left.Index.CompareTo(right.Index); + }); + bool same = _hasCandidatePoint && Math.Abs((long)point.X - _candidatePoint.X) <= 3 && + Math.Abs((long)point.Y - _candidatePoint.Y) <= 3 && hits.Count == _candidates.Count; + for (int i = 0; same && i < hits.Count; i++) same = hits[i] == _candidates[i]; + if (!same) _candidateIndex = 0; + _candidates.Clear(); + _candidates.AddRange(hits); + _candidatePoint = point; + _hasCandidatePoint = true; + if (cycle && hits.Count > 0) + _candidateIndex = (_candidateIndex + direction % hits.Count + hits.Count) % hits.Count; + Entry selected = CurrentCandidate; + _actions.SetCandidate(selected == null ? 0 : _candidateIndex + 1, hits.Count, + selected == null ? null : selected.Item.Path); + Invalidate(); + } + + private Entry CurrentCandidate + { + get { return _candidates.Count == 0 ? null : _candidates[_candidateIndex]; } + } + + private static int ButtonMask(int message, uint data, out bool down, out bool up) + { + down = message == NativeMethods.WM_LBUTTONDOWN || message == NativeMethods.WM_RBUTTONDOWN || + message == NativeMethods.WM_MBUTTONDOWN || message == NativeMethods.WM_XBUTTONDOWN; + up = message == NativeMethods.WM_LBUTTONUP || message == NativeMethods.WM_RBUTTONUP || + message == NativeMethods.WM_MBUTTONUP || message == NativeMethods.WM_XBUTTONUP; + if (!down && !up) return 0; + if (message == NativeMethods.WM_LBUTTONDOWN || message == NativeMethods.WM_LBUTTONUP) return 1; + if (message == NativeMethods.WM_RBUTTONDOWN || message == NativeMethods.WM_RBUTTONUP) return 2; + if (message == NativeMethods.WM_MBUTTONDOWN || message == NativeMethods.WM_MBUTTONUP) return 4; + return (data >> 16) == 1 ? 8 : 16; + } + + private IntPtr MouseHookCallback(int code, IntPtr wParam, IntPtr lParam) + { + if (code < 0) return NativeMethods.CallNextHookEx(_mouseHook, code, wParam, lParam); + try + { + int message = wParam.ToInt32(); + var data = (NativeMethods.MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(NativeMethods.MSLLHOOKSTRUCT)); + Point point = data.Point.ToDrawingPoint(); + bool down, up; + int mask = ButtonMask(message, data.MouseData, out down, out up); + // Match a swallowed down even if the pointer was dragged outside, the map hidden, + // or Escape pressed. Unhook after this release, never leak an orphan mouse-up. + if (up && (_suppressedButtons & mask) != 0) + { + _suppressedButtons &= ~mask; + Entry picked = _pressedEntry; + _pressedEntry = null; + if (mask == 1 && picked != null && _pressedVersion == _version && CanIntercept(point)) + { + int version = _version; + var args = new NodeMapSelectionEventArgs(picked.Index, picked.Item, point); + Post(delegate + { + if (_selectionMode && version == _version) + { + EventHandler handler = NodeSelected; + if (handler != null) handler(this, args); + } + }); + } + if (!_selectionMode) ReleaseHooks(false); + return new IntPtr(1); + } + if (!_selectionMode) return NativeMethods.CallNextHookEx(_mouseHook, code, wParam, lParam); + if (message == NativeMethods.WM_MOUSEMOVE) + { + // Hover uses the latest rendered region. Click/wheel always revalidate natively. + Point local = new Point(point.X - _anchorBounds.Left, point.Y - _anchorBounds.Top); + if (Visible && Region != null && Region.IsVisible(local) && WindowVisibility.IsForegroundWindow(_anchor)) + UpdateCandidates(point, false); + else if (_candidates.Count != 0) { ClearCandidates(); Invalidate(); } + } + bool wheel = message == NativeMethods.WM_MOUSEWHEEL || message == NativeMethods.WM_MOUSEHWHEEL; + if ((down || wheel) && CanIntercept(point)) + { + if (down) _suppressedButtons |= mask; + UpdateCandidates(point, wheel, (short)(data.MouseData >> 16) < 0 ? 1 : -1); + if (mask == 1 && down) + { + _pressedEntry = CurrentCandidate; + _pressedVersion = _version; + } + // All buttons/wheel in the visible target are swallowed in selection mode, + // including blank areas, to avoid changing the very UI being inspected. + return new IntPtr(1); + } + } + catch + { + // Never unwind a managed exception through the native hook callback. + Post(delegate { SetSelectionMode(false); }); + } + return NativeMethods.CallNextHookEx(_mouseHook, code, wParam, lParam); + } + + private IntPtr KeyboardHookCallback(int code, IntPtr wParam, IntPtr lParam) + { + if (code >= 0) + { + var data = (NativeMethods.KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(NativeMethods.KBDLLHOOKSTRUCT)); + if (data.VirtualKey == NativeMethods.VK_ESCAPE) + { + int message = wParam.ToInt32(); + bool up = message == NativeMethods.WM_KEYUP || message == NativeMethods.WM_SYSKEYUP; + if (_escapeSuppressed || (_selectionMode && WindowVisibility.IsForegroundWindow(_anchor))) + { + _escapeSuppressed = !up; + if (!up) Post(delegate { SetSelectionMode(false); }); + else if (!_selectionMode) ReleaseHooks(false); + return new IntPtr(1); + } + } + } + return NativeMethods.CallNextHookEx(_keyboardHook, code, wParam, lParam); + } + + private void Post(Action action) + { + if (_disposing || IsDisposed || !IsHandleCreated) return; + try { BeginInvoke(action); } + catch (InvalidOperationException) { } + } + + private void ReleaseHooks(bool force) + { + if (_mouseHook != IntPtr.Zero && (force || _suppressedButtons == 0)) + { + NativeMethods.UnhookWindowsHookEx(_mouseHook); + _mouseHook = IntPtr.Zero; + } + if (_keyboardHook != IntPtr.Zero && (force || !_escapeSuppressed)) + { + NativeMethods.UnhookWindowsHookEx(_keyboardHook); + _keyboardHook = IntPtr.Zero; + } + if (force) { _suppressedButtons = 0; _escapeSuppressed = false; } + } + + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + if (!_shown || Region == null || !WindowVisibility.IsForegroundWindow(_anchor)) return; + e.Graphics.SmoothingMode = SmoothingMode.None; + e.Graphics.SetClip(Region, CombineMode.Intersect); + using (var pen = new Pen(Color.Red, 1.6F)) + foreach (Entry entry in _entries) e.Graphics.DrawRectangle(pen, entry.Offset); + Entry selected = CurrentCandidate; + if (_selectionMode && selected != null) + using (var pen = new Pen(Color.DodgerBlue, 3F)) e.Graphics.DrawRectangle(pen, selected.Offset); + } + + private static bool TryGetWindowRectangle(IntPtr window, out Rectangle rectangle) + { + NativeMethods.RECT native; + rectangle = Rectangle.Empty; + if (window == IntPtr.Zero || !NativeMethods.GetWindowRect(window, out native)) return false; + rectangle = native.ToRectangle(); + return rectangle.Width > 0 && rectangle.Height > 0; + } + + protected override void Dispose(bool disposing) + { + if (disposing && !_disposing) + { + _disposing = true; + _selectionMode = false; + _shown = false; + ReleaseHooks(true); + _timer.Stop(); + _timer.Tick -= OnTimerTick; + _timer.Dispose(); + _actions.Dispose(); + ReplaceRegion(null); + _entries.Clear(); + _candidates.Clear(); + NodeSelected = null; + SelectionModeChanged = null; + MapExited = null; + } + base.Dispose(disposing); + } + } + + // Kept in the already compiled overlay source so integration requires no csproj changes. + internal sealed class NodeMapActionsForm : Form + { + private readonly Button _select; + private readonly Label _candidate; + internal event EventHandler ToggleSelection; + internal event EventHandler ExitMap; + + internal NodeMapActionsForm() + { + FormBorderStyle = FormBorderStyle.None; + ShowInTaskbar = false; + StartPosition = FormStartPosition.Manual; + AutoScaleMode = AutoScaleMode.None; + TopMost = true; + ClientSize = new Size(170, 112); + BackColor = SystemColors.Control; + _select = new Button { Text = "点击框获取path", Bounds = new Rectangle(5, 5, 160, 32), TabStop = false }; + var exit = new Button { Text = "退出绘制", Bounds = new Rectangle(5, 41, 160, 30), TabStop = false }; + _candidate = new Label { Bounds = new Rectangle(5, 76, 160, 32), AutoEllipsis = true, Text = "选取后滚轮切换重叠节点" }; + _select.Click += delegate + { + try + { + EventHandler handler = ToggleSelection; + if (handler != null) handler(this, EventArgs.Empty); + } + catch (Win32Exception) { _candidate.Text = "钩子安装失败,未进入选取"; } + }; + exit.Click += delegate { EventHandler handler = ExitMap; if (handler != null) handler(this, EventArgs.Empty); }; + Controls.Add(_select); + Controls.Add(exit); + Controls.Add(_candidate); + } + protected override bool ShowWithoutActivation { get { return true; } } + protected override CreateParams CreateParams + { + get + { + CreateParams parameters = base.CreateParams; + parameters.ExStyle |= NativeMethods.WS_EX_TOOLWINDOW | NativeMethods.WS_EX_NOACTIVATE; + return parameters; + } + } + protected override void WndProc(ref Message message) + { + if (message.Msg == NativeMethods.WM_MOUSEACTIVATE) + { + message.Result = new IntPtr(NativeMethods.MA_NOACTIVATE); + return; + } + base.WndProc(ref message); + } + internal void PositionBeside(Rectangle target) + { + Rectangle area = Screen.FromRectangle(target).WorkingArea; + // Prefer outside-right; for a maximized window use its inside-right edge. + int x = target.Right + 6; + if ((long)x + Width > area.Right) x = Math.Min(target.Right, area.Right) - Width - 6; + x = Math.Max(area.Left, Math.Min(x, area.Right - Width)); + int y = Math.Max(area.Top, Math.Min(target.Top + 8, area.Bottom - Height)); + Location = new Point(x, y); + } + internal void SetSelectionMode(bool enabled) + { + _select.Text = enabled ? "选取中(Esc退出)" : "点击框获取path"; + _select.BackColor = enabled ? Color.LightSkyBlue : SystemColors.Control; + } + internal void SetCandidate(int index, int count, string path) + { + string text = count == 0 ? "选取后滚轮切换重叠节点" : + "候选 " + index + "/" + count + " · 滚轮切换\r\n" + (path ?? "点击返回节点索引"); + if (_candidate.Text != text) _candidate.Text = text; + } + } +} diff --git a/src/pacs_win_uia/UI/PathLocateForm.cs b/src/pacs_win_uia/UI/PathLocateForm.cs new file mode 100644 index 0000000..1aed47b --- /dev/null +++ b/src/pacs_win_uia/UI/PathLocateForm.cs @@ -0,0 +1,103 @@ +using System; +using System.Drawing; +using System.Windows.Forms; +using pacs_win_uia.Models; + +namespace pacs_win_uia.UI +{ + /// + /// Paste a control path and locate it. The path text is exactly what the tool prints (the tree, the + /// property grid's 控件Path, the monitor list's 控件Path), so a path copied from anywhere in the tool + /// can be pasted back here to check that it still resolves. + /// + public sealed class PathLocateForm : Form + { + private readonly TextBox _path; + + public PathLocateForm(string initialPath, string windowDescription) + { + Text = "按 path 定位"; + StartPosition = FormStartPosition.CenterParent; + MinimumSize = new Size(640, 380); + Size = new Size(850, 450); + ShowInTaskbar = false; + + var caption = new Label + { + Dock = DockStyle.Top, + Height = 46, + Padding = new Padding(8, 6, 8, 0), + ForeColor = Color.DarkSlateGray, + Text = "粘贴 XPath(必须唯一匹配一个控件;不支持旧格式路径)。" + + Environment.NewLine + + "定位窗口:" + (string.IsNullOrEmpty(windowDescription) ? "(还没有根窗口,请先选中窗口或拾取控件)" : windowDescription) + }; + var help = new TextBox + { + Dock = DockStyle.Top, + Height = 110, + Multiline = true, + ReadOnly = true, + BorderStyle = BorderStyle.None, + BackColor = SystemColors.Control, + ScrollBars = ScrollBars.Vertical, + Text = ControlPathEditorForm.XPathHelp + }; + var errorLabel = new Label + { + Dock = DockStyle.Bottom, + Height = 46, + ForeColor = Color.Firebrick, + Padding = new Padding(6), + AutoEllipsis = true + }; + + _path = new TextBox + { + Dock = DockStyle.Fill, + Multiline = true, + ScrollBars = ScrollBars.Vertical, + WordWrap = true, + Text = initialPath ?? string.Empty + }; + + var buttons = new FlowLayoutPanel + { + Dock = DockStyle.Bottom, + Height = 44, + FlowDirection = FlowDirection.RightToLeft, + Padding = new Padding(6) + }; + var cancel = new Button { Text = "取消", AutoSize = true, DialogResult = DialogResult.Cancel }; + var locate = new Button { Text = "定位", AutoSize = true }; + locate.Click += delegate + { + string error = ControlMonitorRules.ValidateControlPath(_path.Text); + errorLabel.Text = error ?? string.Empty; + if (error != null) return; + DialogResult = DialogResult.OK; + Close(); + }; + _path.TextChanged += delegate { errorLabel.Text = string.Empty; }; + var clear = new Button { Text = "清空", AutoSize = true }; + clear.Click += delegate { _path.Text = string.Empty; }; + buttons.Controls.Add(cancel); + buttons.Controls.Add(locate); + buttons.Controls.Add(clear); + + Controls.Add(_path); + Controls.Add(errorLabel); + Controls.Add(help); + Controls.Add(caption); + Controls.Add(buttons); + AcceptButton = locate; + CancelButton = cancel; + } + + /// The pasted path text. + public string PathText + { + get { return _path.Text; } + } + } +} diff --git a/src/pacs_win_uia/UI/SettingsForm.cs b/src/pacs_win_uia/UI/SettingsForm.cs index a32c4e9..0e2b703 100644 --- a/src/pacs_win_uia/UI/SettingsForm.cs +++ b/src/pacs_win_uia/UI/SettingsForm.cs @@ -1,10 +1,12 @@ -using System; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Reflection; +using System.Runtime.Serialization.Json; +using System.Threading.Tasks; using System.Windows.Forms; using pacs_win_uia.Diagnostics; using pacs_win_uia.Models; @@ -42,17 +44,29 @@ namespace pacs_win_uia.UI private TextBox _barName; private CheckBox _barEnabled; private NumericUpDown _barOpacity; + private NumericUpDown _barBackgroundOpacity; + private NumericUpDown _barControlOpacity; private NumericUpDown _barOffsetX; private NumericUpDown _barOffsetY; - private TextBox _barProcess; - private TextBox _barClass; - private TextBox _barTitle; + private ComboBox _barProcess; + private ComboBox _barClass; + private ComboBox _barTitle; + private Button _refreshWindowSuggestions; + private Button _checkBarConditions; + private Label _windowSuggestionStatus; + private TextBox _barCheckStatus; + private IList _suggestedWindows = new List(); + private int _barEditVersion; + private bool _refreshingSuggestions; + private bool _checkingConditions; private CheckBox _barRequireVisible; private Label _barConditionLabel; private bool _suppressBarEvents; private NumericUpDown _treeDepth; private NumericUpDown _treeNodes; private NumericUpDown _treeTimeout; + private NumericUpDown _treeRefreshInterval; + private NumericUpDown _floatingRefreshInterval; private NumericUpDown _readTimeout; private CheckBox _skipDisabled; @@ -75,8 +89,10 @@ namespace pacs_win_uia.UI Text = "设置 - PACS Windows UI Automation Inspector"; StartPosition = FormStartPosition.CenterParent; - MinimumSize = new Size(720, 560); - Size = new Size(860, 640); + MinimumSize = new Size(980, 720); + // 860x640 clipped every list: a trigger with a few commands could not be seen whole. The + // size is fitted to the screen in OnLoad (see ApplyScreenFitting). + Size = new Size(1200, 900); ShowInTaskbar = false; var tabs = new TabControl { Dock = DockStyle.Fill }; @@ -115,6 +131,8 @@ namespace pacs_win_uia.UI Controls.Add(tabs); Controls.Add(_outputBox); Controls.Add(buttons); + // The dialog remembers where the operator put it; persisted when the tool saves settings. + FormClosing += delegate { RememberBounds(); }; if (_runner != null) { @@ -130,8 +148,85 @@ namespace pacs_win_uia.UI protected override void OnLoad(EventArgs e) { base.OnLoad(e); + // Size first (remembered size, or fitted to the screen), then the splitters: their distances + // are relative to the real width. + ApplyRememberedBounds(); ApplySplitter(_commandSplit, 0.38D, 240, 320); ApplySplitter(_barSplit, 0.30D, 200, 380); + RefreshWindowSuggestionsAsync(); + } + + /// + /// Opens where the operator left it. The first time (or when the remembered place is no longer + /// on any screen, e.g. a monitor was removed) the dialog is centred on the screen it belongs to. + /// + private void ApplyRememberedBounds() + { + Rectangle screen = Screen.FromControl(this).WorkingArea; + if (_settings.Ui.HasSettingsWindowBounds) + { + var remembered = new Rectangle( + _settings.Ui.SettingsWindowX, _settings.Ui.SettingsWindowY, + _settings.Ui.SettingsWindowWidth, _settings.Ui.SettingsWindowHeight); + if (Screen.AllScreens.Length > 0 && IntersectsAnyScreen(remembered)) + { + StartPosition = FormStartPosition.Manual; + Bounds = remembered; + AppLog.Info("设置窗口恢复上次位置:" + remembered); + return; + } + + AppLog.Info("设置窗口上次位置已不在任何屏幕上,改为居中。"); + } + + ApplyScreenFitting(); + StartPosition = FormStartPosition.Manual; + Location = new Point( + screen.Left + Math.Max(0, (screen.Width - Width) / 2), + screen.Top + Math.Max(0, (screen.Height - Height) / 2)); + } + + private static bool IntersectsAnyScreen(Rectangle bounds) + { + foreach (Screen screen in Screen.AllScreens) + { + if (screen.WorkingArea.IntersectsWith(bounds)) + { + return true; + } + } + + return false; + } + + /// Remembers the size and place so the next open lands where the operator put it. + private void RememberBounds() + { + if (WindowState != FormWindowState.Normal) + { + return; + } + + _settings.Ui.SettingsWindowX = Bounds.X; + _settings.Ui.SettingsWindowY = Bounds.Y; + _settings.Ui.SettingsWindowWidth = Bounds.Width; + _settings.Ui.SettingsWindowHeight = Bounds.Height; + } + + /// + /// Fits the dialog to the screen. The old fixed 860x640 was smaller than the 命令 page needs: + /// a trigger's command list showed only its first line. + /// + private void ApplyScreenFitting() + { + Rectangle workingArea = Screen.FromControl(this).WorkingArea; + int width = Math.Min( + workingArea.Width - 60, Math.Max(MinimumSize.Width, (int)(workingArea.Width * 0.72D))); + int height = Math.Min( + workingArea.Height - 60, Math.Max(MinimumSize.Height, (int)(workingArea.Height * 0.84D))); + Size = new Size(width, height); + AppLog.Info("设置窗口尺寸:" + width + "x" + height + "(屏幕工作区 " + + workingArea.Width + "x" + workingArea.Height + ")"); } private static void ApplySplitter(SplitContainer split, double ratio, int minimum1, int minimum2) @@ -184,12 +279,14 @@ namespace pacs_win_uia.UI Name = bar.Name, Enabled = bar.Enabled, OpacityPercent = bar.OpacityPercent, + BackgroundOpacityPercent = bar.BackgroundOpacityPercent, + ControlOpacityPercent = bar.ControlOpacityPercent, OffsetX = bar.OffsetX, OffsetY = bar.OffsetY, ProcessName = bar.ProcessName, WindowClass = bar.WindowClass, WindowTitleKeyword = bar.WindowTitleKeyword, - ImportedCondition = bar.ImportedCondition, + ImportedCondition = CopyCondition(bar.ImportedCondition), RequireWindowVisible = bar.RequireWindowVisible }; foreach (FloatingButtonDefinition button in bar.Buttons ?? new List()) @@ -356,6 +453,9 @@ namespace pacs_win_uia.UI _treeDepth = AddNumber(panel, "控件树最大深度(1-32):", _settings.Ui.TreeMaxDepth, 1, 32); _treeNodes = AddNumber(panel, "控件树最大节点数(50-50000):", _settings.Ui.TreeMaxNodes, 50, 50000); _treeTimeout = AddNumber(panel, "控件树读取超时(秒):", _settings.Ui.TreeTimeoutSeconds, 1, 600); + _treeRefreshInterval = AddNumber(panel, "控件树/高亮重解析刷新间隔(毫秒,默认300):", + _settings.Ui.TreeRefreshIntervalMs, AppSettings.MinimumRefreshIntervalMs, AppSettings.MaximumRefreshIntervalMs); + panel.AutoScroll = true; _readTimeout = AddNumber(panel, "无界面读取默认等待超时(秒,0=不等待):", _settings.Read.DefaultTimeoutSeconds, 0, 3600); _skipDisabled = new CheckBox { @@ -406,10 +506,13 @@ namespace pacs_win_uia.UI split.Panel1.Controls.Add(left); var right = new Panel { Dock = DockStyle.Fill }; + // Dock=Top with AutoSize: the field rows decide their own height (a fixed 190 px cut off + // the lower fields, which then had to share the grid's area). var details = new FlowLayoutPanel { Dock = DockStyle.Top, - Height = 190, + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink, WrapContents = true, FlowDirection = FlowDirection.LeftToRight, Padding = new Padding(2) @@ -418,14 +521,28 @@ namespace pacs_win_uia.UI _barEnabled = new CheckBox { Text = "启用", AutoSize = true, Padding = new Padding(8, 6, 0, 0) }; _barEnabled.CheckedChanged += delegate { ApplyBarDetails(); }; details.Controls.Add(_barEnabled); - _barOpacity = AddBarNumber(details, "透明度", 20, 100); + _barOpacity = AddBarNumber(details, "整体透明度", 20, 100); + _barBackgroundOpacity = AddBarNumber(details, "背景透明度(0=同上)", 0, 100); + _barControlOpacity = AddBarNumber(details, "按钮透明度(0=同上)", 0, 100); _barOffsetX = AddBarNumber(details, "相对X", -4000, 4000); _barOffsetY = AddBarNumber(details, "相对Y", -4000, 4000); - details.Controls.Add(new Label { Text = "显示条件(留空表示不限制)", AutoSize = true, Width = 640, Padding = new Padding(0, 8, 0, 0) }); - _barProcess = AddBarField(details, "进程名", 130); - _barClass = AddBarField(details, "窗口类", 150); - _barTitle = AddBarField(details, "标题关键词", 150); + var conditionHint = new Label + { + Text = "锚定窗口:填写的条件需同时满足;至少填写一项。可手输或下拉选择(仅保存实际值)。", + AutoSize = true, MaximumSize = new Size(600, 0), Padding = new Padding(0, 8, 0, 0) + }; + details.Controls.Add(conditionHint); + details.SetFlowBreak(conditionHint, true); + _barProcess = AddBarSuggestionField(details, "进程名", 180, 0); + _barClass = AddBarSuggestionField(details, "窗口类", 180, 1); + _barTitle = AddBarSuggestionField(details, "标题关键词", 220, 2); + _refreshWindowSuggestions = new Button { Text = "刷新窗口建议", AutoSize = true }; + _refreshWindowSuggestions.Click += delegate { RefreshWindowSuggestionsAsync(); }; + details.Controls.Add(_refreshWindowSuggestions); + _windowSuggestionStatus = new Label { AutoSize = true, MaximumSize = new Size(600, 0) }; + details.Controls.Add(_windowSuggestionStatus); + details.SetFlowBreak(_windowSuggestionStatus, true); _barRequireVisible = new CheckBox { Text = "窗口可见且未被遮挡时才显示", @@ -445,6 +562,7 @@ namespace pacs_win_uia.UI if (bar != null) { bar.ImportedCondition = null; + InvalidateBarCheck(); RefreshBarConditionLabel(); } }; @@ -455,8 +573,25 @@ namespace pacs_win_uia.UI ForeColor = Color.DarkSlateGray, Padding = new Padding(0, 6, 0, 0) }; + _barConditionLabel.MaximumSize = new Size(620, 0); details.Controls.Add(_barConditionLabel); - right.Controls.Add(details); + details.SetFlowBreak(_barConditionLabel, true); + _checkBarConditions = new Button { Text = "检测显示条件(只读)", AutoSize = true }; + _checkBarConditions.Click += delegate { CheckBarConditionsAsync(); }; + details.Controls.Add(_checkBarConditions); + var diagnosticHint = new Label + { + Text = "后台检测,不执行命令或改变目标。保存后才生效;设置窗口也可能遮挡目标。", + AutoSize = true, MaximumSize = new Size(500, 0) + }; + details.Controls.Add(diagnosticHint); + details.SetFlowBreak(diagnosticHint, true); + _barCheckStatus = new TextBox + { + ReadOnly = true, Multiline = true, ScrollBars = ScrollBars.Vertical, + Width = 620, Height = 62, Text = "尚未检测当前显示条件。" + }; + details.Controls.Add(_barCheckStatus); var buttonRow = new FlowLayoutPanel { Dock = DockStyle.Bottom, Height = 34, WrapContents = false }; var addButton = new Button { Text = "新增按钮", AutoSize = true }; @@ -483,18 +618,20 @@ namespace pacs_win_uia.UI }; _buttonGrid.Columns.Add(new DataGridViewCheckBoxColumn { HeaderText = "启用", DataPropertyName = "Enabled", FillWeight = 8 }); _buttonGrid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "按钮名称", DataPropertyName = "Label", FillWeight = 22 }); + // Bound instead of a list of enum values: the cell must show the Chinese name of the action + // while still writing the enum into the model (a plain Items list would print "PickControl"). var actionColumn = new DataGridViewComboBoxColumn { HeaderText = "点击执行操作", DataPropertyName = "Action", - FillWeight = 26, - FlatStyle = FlatStyle.Flat + FillWeight = 30, + FlatStyle = FlatStyle.Flat, + DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox, + DisplayStyleForCurrentCellOnly = true, + DataSource = FloatingButtonDefinition.DescribeChoices(), + DisplayMember = "Display", + ValueMember = "Value" }; - foreach (FloatingActionKind kind in FloatingToolbarForm.KnownActions) - { - actionColumn.Items.Add(kind); - } - _buttonGrid.Columns.Add(actionColumn); _buttonGrid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "快捷键", DataPropertyName = "Shortcut", FillWeight = 14 }); _buttonGrid.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "点击执行命令", DataPropertyName = "CommandLine", FillWeight = 30 }); @@ -502,31 +639,268 @@ namespace pacs_win_uia.UI { e.Cancel = true; }; + _buttonGrid.CurrentCellDirtyStateChanged += delegate + { + if (_buttonGrid.IsCurrentCellDirty) + _buttonGrid.CommitEdit(DataGridViewDataErrorContexts.Commit); + }; + _buttonGrid.CellValueChanged += delegate + { + InvalidateBarCheck(); + RefreshBarConditionLabel(); + }; + // Add order matters for docking: the Fill control comes first, the edge-docked ones after + // it — the other way round the grid was docked across the whole panel and painted over the + // fields above it, which is exactly the "empty grey list" the operator saw. + // Keep a visible button editor even on small screens; the richer condition form scrolls + // independently instead of growing over the grid and making it look empty. + var detailViewport = new Panel { Dock = DockStyle.Top, Height = 360, AutoScroll = true }; + detailViewport.Controls.Add(details); + detailViewport.SizeChanged += delegate + { + int width = Math.Max(240, detailViewport.ClientSize.Width - SystemInformation.VerticalScrollBarWidth - 12); + details.Width = width; + _barCheckStatus.Width = Math.Max(220, width - 12); + _barConditionLabel.MaximumSize = new Size(width - 12, 0); + conditionHint.MaximumSize = new Size(width - 12, 0); + _windowSuggestionStatus.MaximumSize = new Size(width - 12, 0); + }; right.Controls.Add(_buttonGrid); right.Controls.Add(buttonRow); + right.Controls.Add(detailViewport); split.Panel2.Controls.Add(right); + var refreshPanel = new FlowLayoutPanel + { + Dock = DockStyle.Top, + AutoSize = true, + WrapContents = false, + Padding = new Padding(6) + }; + _floatingRefreshInterval = AddNumber(refreshPanel, + "所有悬浮条跟随/显示条件刷新间隔(毫秒,默认300):", + _settings.FloatingButton.RefreshIntervalMs, + AppSettings.MinimumRefreshIntervalMs, AppSettings.MaximumRefreshIntervalMs); page.Controls.Add(split); + page.Controls.Add(refreshPanel); RefreshBarList(); return page; } + /// + /// One label + input pair. The pair is wrapped in its own flow panel so that a wrapping row + /// cannot leave the caption at the end of one line and its input at the start of the next. + /// + private static FlowLayoutPanel AddBarGroup(Control parent) + { + var group = new FlowLayoutPanel + { + AutoSize = true, + AutoSizeMode = AutoSizeMode.GrowAndShrink, + WrapContents = false, + FlowDirection = FlowDirection.LeftToRight, + Margin = new Padding(0) + }; + parent.Controls.Add(group); + return group; + } + private TextBox AddBarField(Control parent, string label, int width) { - parent.Controls.Add(new Label { Text = label, AutoSize = true, Padding = new Padding(6, 6, 0, 0) }); + FlowLayoutPanel group = AddBarGroup(parent); + group.Controls.Add(new Label { Text = label, AutoSize = true, Padding = new Padding(6, 8, 0, 0) }); var box = new TextBox { Width = width }; box.TextChanged += delegate { ApplyBarDetails(); }; - parent.Controls.Add(box); + group.Controls.Add(box); return box; } + private sealed class WindowSuggestion + { + internal NativeWindowInfo Window; + internal string Value; + public override string ToString() + { + return Value + " — " + (string.IsNullOrEmpty(Window.Title) ? "(无标题)" : Window.Title) + + " | " + Window.ProcessName + " / PID " + Window.ProcessId + " | " + Window.ClassName + + (Window.IsMinimized ? " [最小化]" : !Window.IsVisible ? " [隐藏]" : ""); + } + } + + private ComboBox AddBarSuggestionField(Control parent, string label, int width, int field) + { + FlowLayoutPanel group = AddBarGroup(parent); + group.Controls.Add(new Label { Text = label, AutoSize = true, Padding = new Padding(6, 8, 0, 0) }); + var box = new ComboBox + { + Width = width, DropDownStyle = ComboBoxStyle.DropDown, + DropDownWidth = 780, IntegralHeight = false, MaxDropDownItems = 14 + }; + box.TextChanged += delegate + { + if (_suppressBarEvents) return; + ApplyBarDetails(); + }; + box.SelectionChangeCommitted += delegate + { + var suggestion = box.SelectedItem as WindowSuggestion; + if (suggestion == null) return; + _suppressBarEvents = true; + try + { + box.SelectedIndex = -1; + box.Text = suggestion.Value; + // A choice supplies useful defaults only for blank fields. Typed conditions win. + if (field == 0) + { + if (string.IsNullOrWhiteSpace(_barClass.Text)) _barClass.Text = suggestion.Window.ClassName; + if (string.IsNullOrWhiteSpace(_barTitle.Text)) _barTitle.Text = suggestion.Window.Title; + } + } + finally { _suppressBarEvents = false; } + ApplyBarDetails(); + if (field == 0) RebuildWindowSuggestions(false); + }; + group.Controls.Add(box); + return box; + } + + private static string SuggestionValue(ComboBox box) + { + var selected = box.SelectedItem as WindowSuggestion; + // Text may be a user's edit even if WinForms still has a SelectedItem. + return selected != null && string.Equals(box.Text, selected.ToString(), StringComparison.Ordinal) + ? selected.Value : box.Text; + } + + private async void RefreshWindowSuggestionsAsync() + { + if (_refreshingSuggestions || IsDisposed) return; + _refreshingSuggestions = true; + _refreshWindowSuggestions.Enabled = false; + _windowSuggestionStatus.Text = "正在后台读取窗口建议…(不修改已填写的条件)"; + try + { + WindowEnumerationResult result = await Task.Run( + () => new NativeWindowService().EnumerateTopLevelWindowsResult(false)); + if (IsDisposed || Disposing) return; + _suggestedWindows = result.Windows; + RebuildWindowSuggestions(true); + _windowSuggestionStatus.Text = result.Succeeded + ? "已刷新 " + result.Windows.Count + " 个窗口;进程选择联动类/标题建议,已有输入不会覆盖。" + : "窗口建议读取失败:" + result.Error; + } + catch (Exception ex) + { + if (!IsDisposed && !Disposing) _windowSuggestionStatus.Text = "读取建议失败:" + ex.Message; + } + finally + { + _refreshingSuggestions = false; + if (!IsDisposed && !Disposing) _refreshWindowSuggestions.Enabled = true; + } + } + + private void RebuildWindowSuggestions(bool includeProcess) + { + if (_barProcess == null || _barClass == null || _barTitle == null) return; + bool previous = _suppressBarEvents; + _suppressBarEvents = true; + try + { + if (includeProcess) FillWindowSuggestions(_barProcess, 0, null); + string process = FloatingBarManager.NormalizeProcessName(SuggestionValue(_barProcess)); + FillWindowSuggestions(_barClass, 1, process); + FillWindowSuggestions(_barTitle, 2, process); + } + finally { _suppressBarEvents = previous; } + } + + private void FillWindowSuggestions(ComboBox box, int field, string process) + { + string text = SuggestionValue(box); + box.BeginUpdate(); + try + { + box.Items.Clear(); + foreach (NativeWindowInfo window in _suggestedWindows) + { + if (!string.IsNullOrEmpty(process) && !string.Equals(process, + FloatingBarManager.NormalizeProcessName(window.ProcessName), StringComparison.OrdinalIgnoreCase)) continue; + string value = field == 0 ? window.ProcessName : field == 1 ? window.ClassName : window.Title; + if (string.IsNullOrEmpty(value)) continue; + box.Items.Add(new WindowSuggestion { Window = window, Value = value }); + } + box.SelectedIndex = -1; + box.Text = text; + } + finally { box.EndUpdate(); } + } + + private void InvalidateBarCheck() + { + _barEditVersion++; + if (_barCheckStatus != null) + _barCheckStatus.Text = "配置已修改或已切换悬浮条,请重新检测。名称仅用于显示,不是按钮或定位条件。"; + } + + private async void CheckBarConditionsAsync() + { + if (_checkingConditions) return; + _buttonGrid.EndEdit(); + ApplyBarDetails(); + FloatingBarDefinition bar = SelectedBar(); + if (bar == null) return; + FloatingBarDefinition snapshot = CopyBars(new[] { bar })[0]; + int version = _barEditVersion; + _checkingConditions = true; + _checkBarConditions.Enabled = false; + _barCheckStatus.Text = "正在后台检测当前草稿(只读,不执行操作)…"; + try + { + Task check = Task.Run(() => FloatingBarManager.CheckDisplayConditions(snapshot)); + if (await Task.WhenAny(check, Task.Delay(10000)) != check) + { + if (!IsDisposed && !Disposing && version == _barEditVersion) + _barCheckStatus.Text = "检测超过10秒,目标提供者可能无响应;未判定显示成功。等待本次后台调用结束,不会排队重复调用。"; + } + FloatingBarDisplayCheck result = await check; + if (IsDisposed || Disposing || version != _barEditVersion || !ReferenceEquals(bar, SelectedBar())) return; + _barCheckStatus.Text = DateTime.Now.ToString("HH:mm:ss") + " " + result + + Environment.NewLine + "这是当前时刻的检测结果;保存后才应用配置。"; + } + catch (Exception ex) + { + if (!IsDisposed && !Disposing && version == _barEditVersion) + _barCheckStatus.Text = "检测失败:" + ex.Message; + } + finally + { + _checkingConditions = false; + if (!IsDisposed && !Disposing) _checkBarConditions.Enabled = true; + } + } + + private static ControlMonitorDefinition CopyCondition(ControlMonitorDefinition source) + { + if (source == null) return null; + var serializer = new DataContractJsonSerializer(typeof(ControlMonitorDefinition)); + using (var stream = new MemoryStream()) + { + serializer.WriteObject(stream, source); + stream.Position = 0; + return (ControlMonitorDefinition)serializer.ReadObject(stream); + } + } + private NumericUpDown AddBarNumber(Control parent, string label, int minimum, int maximum) { - parent.Controls.Add(new Label { Text = label, AutoSize = true, Padding = new Padding(6, 6, 0, 0) }); + FlowLayoutPanel group = AddBarGroup(parent); + group.Controls.Add(new Label { Text = label, AutoSize = true, Padding = new Padding(6, 8, 0, 0) }); var box = new NumericUpDown { Minimum = minimum, Maximum = maximum, Width = 70 }; box.ValueChanged += delegate { ApplyBarDetails(); }; - parent.Controls.Add(box); + group.Controls.Add(box); return box; } @@ -587,11 +961,15 @@ namespace pacs_win_uia.UI private void LoadSelectedBar() { + if (_suppressBarEvents) return; + InvalidateBarCheck(); FloatingBarDefinition bar = SelectedBar(); _buttonGrid.Enabled = bar != null; if (bar == null) { _buttonGrid.DataSource = null; + _currentButtons = null; + RefreshBarConditionLabel(); return; } @@ -601,6 +979,10 @@ namespace pacs_win_uia.UI _barName.Text = bar.Name; _barEnabled.Checked = bar.Enabled; _barOpacity.Value = Math.Max(_barOpacity.Minimum, Math.Min(_barOpacity.Maximum, bar.OpacityPercent)); + _barBackgroundOpacity.Value = Math.Max(_barBackgroundOpacity.Minimum, + Math.Min(_barBackgroundOpacity.Maximum, bar.BackgroundOpacityPercent)); + _barControlOpacity.Value = Math.Max(_barControlOpacity.Minimum, + Math.Min(_barControlOpacity.Maximum, bar.ControlOpacityPercent)); _barOffsetX.Value = Math.Max(_barOffsetX.Minimum, Math.Min(_barOffsetX.Maximum, bar.OffsetX)); _barOffsetY.Value = Math.Max(_barOffsetY.Minimum, Math.Min(_barOffsetY.Maximum, bar.OffsetY)); _barProcess.Text = bar.ProcessName; @@ -615,6 +997,7 @@ namespace pacs_win_uia.UI _currentButtons = new BindingList(bar.Buttons); _buttonGrid.DataSource = _currentButtons; + RebuildWindowSuggestions(true); RefreshBarConditionLabel(); } @@ -634,16 +1017,27 @@ namespace pacs_win_uia.UI bar.Name = _barName.Text; bar.Enabled = _barEnabled.Checked; bar.OpacityPercent = (int)_barOpacity.Value; + bar.BackgroundOpacityPercent = (int)_barBackgroundOpacity.Value; + bar.ControlOpacityPercent = (int)_barControlOpacity.Value; bar.OffsetX = (int)_barOffsetX.Value; bar.OffsetY = (int)_barOffsetY.Value; - bar.ProcessName = _barProcess.Text; - bar.WindowClass = _barClass.Text; - bar.WindowTitleKeyword = _barTitle.Text; + bar.ProcessName = SuggestionValue(_barProcess); + bar.WindowClass = SuggestionValue(_barClass); + bar.WindowTitleKeyword = SuggestionValue(_barTitle); bar.RequireWindowVisible = _barRequireVisible.Checked; - int index = _barList.SelectedIndex; - _barList.Items[index] = bar; - _barList.SelectedIndex = index; + // Replacing the selected list item raises SelectedIndexChanged on WinForms. Do not + // rebind the grid/reset editors (and lose an in-progress edit) while refreshing its label. + _suppressBarEvents = true; + try + { + int index = _barList.SelectedIndex; + _barList.Items[index] = bar; + _barList.SelectedIndex = index; + } + finally { _suppressBarEvents = false; } + InvalidateBarCheck(); + RefreshBarConditionLabel(); } private void AddFloatingButton() @@ -660,6 +1054,7 @@ namespace pacs_win_uia.UI Action = FloatingActionKind.LocateControl }); _currentButtons.ResetBindings(); + ApplyBarDetails(); } private void RemoveFloatingButton() @@ -673,6 +1068,7 @@ namespace pacs_win_uia.UI if (index >= 0 && index < _currentButtons.Count) { _currentButtons.RemoveAt(index); + ApplyBarDetails(); } } @@ -734,21 +1130,25 @@ namespace pacs_win_uia.UI return; } - bar.ImportedCondition = selected; - if (string.IsNullOrEmpty(bar.ProcessName)) + string pathError = ControlPath.ValidateSyntax(selected.ControlPath); + if (pathError != null) + { + MessageBox.Show(this, "不能导入:" + pathError + + "\r\n请先在监控项中重新拾取或编辑为 XPath(不支持旧格式)。", "导入 XPath", + MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + bar.ImportedCondition = CopyCondition(selected); + // Derive a complete anchor only when none was supplied. Mixing a hand-entered + // process with another monitor's class/title silently creates impossible conditions. + if (!FloatingBarManager.HasWindowConditions(bar.ProcessName, bar.WindowClass, bar.WindowTitleKeyword)) { bar.ProcessName = selected.ProcessName; - } - - if (string.IsNullOrEmpty(bar.WindowClass)) - { bar.WindowClass = selected.WindowClass; - } - - if (string.IsNullOrEmpty(bar.WindowTitleKeyword)) - { bar.WindowTitleKeyword = selected.WindowTitleKeyword; } + bool addedButton = bar.EnsureButtonForImport(); + _currentButtons.ResetBindings(); _suppressBarEvents = true; try @@ -763,31 +1163,55 @@ namespace pacs_win_uia.UI } ApplyBarDetails(); + RebuildWindowSuggestions(true); RefreshBarConditionLabel(); + _barCheckStatus.Text = "已导入 XPath 的独立副本(监控项停用状态不影响此条件)。" + + (addedButton ? "已添加启用的「定位控件」按钮,可在下表修改操作。" : "按钮配置保留。") + + "请点击检测显示条件;导入不会自动启用已停用的悬浮条。"; } } private void RefreshBarConditionLabel() { + if (_barConditionLabel == null) return; FloatingBarDefinition bar = SelectedBar(); - if (bar == null || bar.ImportedCondition == null) + if (bar == null) { - _barConditionLabel.Text = "显示条件:仅按上面的页面/窗口条件"; + _barConditionLabel.Text = "请先新增或选择悬浮条。"; return; } - - _barConditionLabel.Text = "已导入监控项 path:「" + bar.ImportedCondition.ContentKey - + "」——该控件出现时才显示这条悬浮条"; + string error = bar.ButtonConfigurationError; + string status = (bar.Enabled ? "悬浮条启用" : "悬浮条已停用,不显示") + + ";启用按钮 " + bar.EnabledButtonCount + " 个。"; + if (error != null) status += " " + error; + ControlMonitorDefinition condition = bar.ImportedCondition; + if (condition == null) status += "\r\n无导入 XPath,仅检测锚定窗口条件。"; + else + { + status += "\r\n已导入 XPath 副本「" + condition.ContentKey + "」;控件唯一存在才显示。" + + "条件窗口:" + (condition.ProcessName ?? "*") + " / " + (condition.WindowClass ?? "*") + + " / " + (condition.WindowTitleKeyword ?? "*") + "。"; + string pathError = ControlPath.ValidateSyntax(condition.ControlPath); + if (pathError != null) status += "\r\n无效 XPath,需重新导入:" + pathError; + } + if (!FloatingBarManager.HasWindowConditions(bar.ProcessName, bar.WindowClass, bar.WindowTitleKeyword)) + status += condition == null ? "\r\n缺少锚定窗口条件,不会显示。" : "\r\n锚定窗口沿用导入条件的窗口信息。"; + _barConditionLabel.ForeColor = !bar.Enabled || error != null ? Color.Firebrick : Color.DarkSlateGray; + _barConditionLabel.Text = status; } private TabPage BuildCommandPage() { var page = new TabPage("命令"); var layout = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 1, RowCount = 4 }; - layout.RowStyles.Add(new RowStyle(SizeType.Percent, 62)); + layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); + // The list gets the room: a trigger with several commands has to be readable without + // scrolling, which is why the page sizes itself to the screen. + layout.RowStyles.Add(new RowStyle(SizeType.Percent, 70)); layout.RowStyles.Add(new RowStyle(SizeType.Absolute, 36)); - layout.RowStyles.Add(new RowStyle(SizeType.Absolute, 58)); - layout.RowStyles.Add(new RowStyle(SizeType.Percent, 38)); + // The hint row sizes to its text: at a fixed 58 px it was cut off in the middle of a line. + layout.RowStyles.Add(new RowStyle(SizeType.AutoSize)); + layout.RowStyles.Add(new RowStyle(SizeType.Percent, 30)); // ---- left: execution moments; right: commands of the selected moment var split = new SplitContainer { Dock = DockStyle.Fill, Orientation = Orientation.Vertical }; @@ -876,7 +1300,9 @@ namespace pacs_win_uia.UI layout.Controls.Add(new Label { Text = "命令通过 cmd.exe /c 以当前用户身份执行;输出进控制台日志。" - + "默认只读、不注入目标进程、不提权。不要把患者信息写进命令行。", + + "默认只读、不注入目标进程、不提权。不要把患者信息写进命令行。" + + "本工具退出时会结束仍在运行的命令,以及这些命令拉起的应用。", + Dock = DockStyle.Fill, AutoSize = true, ForeColor = Color.DarkSlateGray }); @@ -1184,11 +1610,34 @@ namespace pacs_win_uia.UI private void Save() { + // Commit the current cell before taking the settings snapshot or validating it. + if (!_buttonGrid.EndEdit() || !_commandGrid.EndEdit()) return; + ApplyBarDetails(); + foreach (FloatingBarDefinition bar in _bars) + { + if (!bar.Enabled) continue; // Deliberately inactive drafts may be saved for later. + string error = bar.ButtonConfigurationError; + if (error == null && bar.ImportedCondition != null) + error = ControlPath.ValidateSyntax(bar.ImportedCondition.ControlPath); + if (error == null && !FloatingBarManager.HasWindowConditions(bar.ProcessName, bar.WindowClass, bar.WindowTitleKeyword) + && (bar.ImportedCondition == null || !FloatingBarManager.HasWindowConditions( + bar.ImportedCondition.ProcessName, bar.ImportedCondition.WindowClass, bar.ImportedCondition.WindowTitleKeyword))) + error = "缺少锚定窗口条件,请选择窗口或填写至少一项条件。"; + if (error != null) + { + _barList.SelectedItem = bar; + MessageBox.Show(this, "悬浮条「" + bar.Name + "」不能启用:" + error + + "\r\n请修正,或取消悬浮条的启用后保存草稿。", "设置", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + } _settings.Ui.AutoReadTreeOnSelect = _autoReadTree.Checked; _settings.Ui.HighlightForegroundWindow = _highlightForeground.Checked; _settings.Ui.TreeMaxDepth = (int)_treeDepth.Value; _settings.Ui.TreeMaxNodes = (int)_treeNodes.Value; _settings.Ui.TreeTimeoutSeconds = (int)_treeTimeout.Value; + _settings.Ui.TreeRefreshIntervalMs = (int)_treeRefreshInterval.Value; + _settings.FloatingButton.RefreshIntervalMs = (int)_floatingRefreshInterval.Value; _settings.Read.DefaultTimeoutSeconds = (int)_readTimeout.Value; _settings.Read.SkipDisabled = _skipDisabled.Checked; diff --git a/src/pacs_win_uia/UI/ShiftWheelScroll.cs b/src/pacs_win_uia/UI/ShiftWheelScroll.cs new file mode 100644 index 0000000..d777bfa --- /dev/null +++ b/src/pacs_win_uia/UI/ShiftWheelScroll.cs @@ -0,0 +1,123 @@ +using System; +using System.Drawing; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using pacs_win_uia.Interop; + +namespace pacs_win_uia.UI +{ + /// + /// Shift + mouse wheel scrolls horizontally, anywhere in the tool: the wheel message is looked up + /// by the window under the cursor, so it works over the window list, the tree, the property area + /// and the grids without every control having to implement it. DataGridView already does this + /// itself, so those are left alone. + /// + public sealed class ShiftWheelScroll : IMessageFilter + { + private const int WM_MOUSEWHEEL = 0x020A; + private const int WM_HSCROLL = 0x0114; + private const int SB_LINELEFT = 0; + private const int SB_LINERIGHT = 1; + + private const int LinesPerNotch = 3; + + public bool PreFilterMessage(ref Message message) + { + if (message.Msg != WM_MOUSEWHEEL) + { + return false; + } + + if ((Control.ModifierKeys & Keys.Shift) != Keys.Shift) + { + return false; + } + + int delta = (short)((long)message.WParam >> 16); + if (delta == 0) + { + return false; + } + + // WM_MOUSEWHEEL carries screen coordinates in the low/high words of lParam. + long value = message.LParam.ToInt64(); + var screenPoint = new Point((short)(value & 0xFFFF), (short)((value >> 16) & 0xFFFF)); + Control target = Control.FromChildHandle(NativeMethods.WindowFromPoint(screenPoint)); + if (target == null) + { + return false; + } + + Control scrollable = FindScrollable(target, out bool native); + if (scrollable == null) + { + return false; + } + + int lines = Math.Max(1, Math.Abs(delta) / 120) * LinesPerNotch; + int direction = delta > 0 ? -lines : lines; + if (native) + { + int command = direction < 0 ? SB_LINELEFT : SB_LINERIGHT; + for (int step = 0; step < lines; step++) + { + NativeMethods.SendMessage(scrollable.Handle, WM_HSCROLL, new IntPtr(command), IntPtr.Zero); + } + } + else + { + ScrollableControl panel = scrollable as ScrollableControl; + if (panel == null) + { + return false; + } + + int wanted = panel.HorizontalScroll.Value + direction * 8; + wanted = Math.Max(panel.HorizontalScroll.Minimum, Math.Min(panel.HorizontalScroll.Maximum, wanted)); + try + { + panel.HorizontalScroll.Value = wanted; + } + catch (ArgumentOutOfRangeException) + { + return false; + } + + panel.PerformLayout(); + } + + return true; + } + + /// + /// Walks up from the control under the cursor to one that can scroll sideways. Controls with a + /// native scrollbar need WM_HSCROLL; a scrollable panel uses its scroll properties. + /// + private static Control FindScrollable(Control control, out bool native) + { + native = false; + for (Control current = control; current != null; current = current.Parent) + { + var grid = current as DataGridView; + if (grid != null) + { + // DataGridView handles Shift+wheel itself. + return null; + } + + if (current is ListView || current is TreeView) + { + native = true; + return current; + } + + if (current is ScrollableControl && ((ScrollableControl)current).AutoScroll) + { + return current; + } + } + + return null; + } + } +} diff --git a/src/pacs_win_uia/pacs_win_uia.csproj b/src/pacs_win_uia/pacs_win_uia.csproj index 7053f4a..0093098 100644 --- a/src/pacs_win_uia/pacs_win_uia.csproj +++ b/src/pacs_win_uia/pacs_win_uia.csproj @@ -75,10 +75,14 @@ + + + + @@ -102,7 +106,12 @@ + + + + + diff --git a/src/pacs_win_uia/settings.json b/src/pacs_win_uia/settings.json index 3eb2f98..1e40ffe 100644 --- a/src/pacs_win_uia/settings.json +++ b/src/pacs_win_uia/settings.json @@ -5,9 +5,11 @@ "HighlightForegroundWindow": true, "TreeMaxDepth": 12, "TreeMaxNodes": 3000, - "TreeTimeoutSeconds": 10 + "TreeTimeoutSeconds": 10, + "TreeRefreshIntervalMs": 300 }, "FloatingButton": { + "RefreshIntervalMs": 300, "Enabled": false, "OpacityPercent": 90, "X": 60, diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..6ba25fb --- /dev/null +++ b/tests/README.md @@ -0,0 +1,61 @@ +# tests —— 可运行的测试夹具 + +真实 PACS/OCS 客户端要么不暴露 UIA(CEF 套壳),要么树太大没法人工核对。 +这里放一个**普通 WinForms 窗口**,控件类型、名称、层级都是已知的,用来验证本工具的读取链路。 + +## 运行 + +```bat +tests\run-fixture.cmd :: Debug(默认) +tests\run-fixture.cmd Release :: Release +``` + +脚本会先用 `dotnet msbuild`(没有 dotnet 时用 `msbuild`)构建 `tests/uia-fixture`, +然后启动 `UiaFixture.exe`。也可以直接在 Rider / VS 里打开 `pacs_win_uia.sln` 单独运行这个项目。 + +## 窗口内容 + +| 窗口 | 内容 | +| --- | --- | +| `UIA 测试夹具` | 「控件」页:按钮、文本框、复选框、单选、下拉、两列 ListView、TreeView、状态标签;「表格」页:5 行 × 3 列 DataGridView;「嵌套」页:三层嵌套容器里的 ListBox | +| `UIA 测试夹具 - 第二个窗口` | 一个按钮(测试"选哪个窗口"、窗口列表分组与匹配) | + +两个窗口的**标题与类名都固定**,所以保存的监控条目、悬浮条显示条件可以长期复用。 + +## 建议的验证清单 + +1. **控件树**:选中 `UIA 测试夹具` → 期望读到 Button/Edit/CheckBox/ComboBox/List/Tree 等节点, + 「控件属性」里能看到控件Path、页面特征、焦点状态。 +2. **拾取**:拾取「测试按钮」,期望拾取后控件树**以顶层窗口为根**展开并选中该按钮 + (与窗口列表选中同一窗口得到的树一致),高亮框在拾取结束后消失。 +2. **列表读取**:选中 DataGridView → 期望 5 行 × 3 列;ListView 走 MSAA/Win32 也应能读到行。 +3. **path 往返**:在控件树里选中任意节点 → 复制「控件属性 → 控件Path」→ 杂项 →「按 path 定位…」→ 粘贴 → 定位, + 期望命中同一个控件并在树上选中(这是"复制的 path 能不能用"的回归测试)。 +4. **按 path 定位(故意写错)**:把路径中间一段改成不存在的名字,期望明确报出**第几段**没匹配, + 而不是高亮到名字相同的另一个控件。 +5. **监控列表**:添加一条指向「FixtureButton」的条目 → 点击该行立即出现红框、控件树展开到它; + 点击标题、文本框、复选框那几行同样要有反应(点击任何位置都定位)。 +6. **绘制所有控件框**:杂项 →「绘制所有控件框」,期望窗口里每个控件都套上一个细红框, + 拖动/最小化目标窗口时框跟随/隐藏。 +7. **命令与退出**:设置里加一条 `启动` 命令 `start "" notepad.exe`(测试用),退出工具后期望该进程被结束。 +8. **拾取不触发目标**:拾取夹具窗口里的「测试按钮」时,期望按钮**不会被按下**(状态标签不变化, + 见「控件」页右下角的状态文字),也不会抢走焦点。 + +> 注意:夹具只是测试目标,不要在里面放真实患者数据。 + +## 路径与持久化回归测试 + +`regression/RegressionTests.csproj` 是独立的 net48 console 测试工程。它引用主项目,在纯内存 `ControlTreeNode` 快照上覆盖 XPath、重复身份、转义、全节点 roundtrip、唯一性与不完整树;验证所有祖先 Name 改变后生成路径仍有效、稳定祖先锚定,以及 MSAA/Win32 来源不丢失。旧格式测试现在要求明确拒绝执行,旧文件仅保留用于人工编辑;保存前必须修正为 XPath。另验证动态字段不持久化、缺失刷新间隔默认300ms、悬浮条缺省启用值和显式停用值的区别,以及悬浮条窗口条件的严格匹配。测试不访问自身 UIA 或真实业务窗口。 + +新一轮界面验收: +- 静置控件树不应不断清空/重绘;更改目标控件文字只更新该节点;展开状态、选中和滚动保持。 +- 双击监控 Path 打开多行编辑器;取消不改变配置,非法 XPath 不允许提交;编辑过程中不自动跳去定位。 +- 悬浮条进程/类名/标题可以输入和下拉选择;导入 XPath 后使用“检测显示条件”核对不显示原因。 +- Name 变化的定位方案见 `docs/XPath定位.md`。 + +在仓库根目录执行: + +```bat +dotnet msbuild tests\regression\RegressionTests.csproj -t:Build -p:Configuration=Debug -v:minimal +tests\regression\bin\Debug\RegressionTests.exe +``` diff --git a/tests/regression/FloatingConditionsTests.cs b/tests/regression/FloatingConditionsTests.cs new file mode 100644 index 0000000..f186cae --- /dev/null +++ b/tests/regression/FloatingConditionsTests.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using pacs_win_uia.Models; +using pacs_win_uia.Services; + +namespace PacsWinUia.RegressionTests +{ + internal static class FloatingConditionsTests + { + public static void Register(IList> tests) + { + tests.Add(new KeyValuePair("Floating conditions require all supplied clues and unique window", WindowConditions)); + tests.Add(new KeyValuePair("Floating display explains missing configuration before provider calls", InvalidConfiguration)); + } + + private static void WindowConditions() + { + var first = new NativeWindowInfo(new IntPtr(1)) { ProcessName = "fixture", ClassName = "Host", Title = "测试窗口 A", IsVisible = true }; + var second = new NativeWindowInfo(new IntPtr(2)) { ProcessName = "fixture", ClassName = "Host", Title = "测试窗口 B", IsVisible = true }; + var windows = new List { first, second }; + string error; + Check.Same(first, FloatingBarManager.FindConditionWindow(windows, "Fixture.exe", "Host", "窗口 A", out error), "Friendly .exe process input not normalized"); + Check.Equal(null, error, "Exact match error"); + Check.Equal(null, FloatingBarManager.FindConditionWindow(windows, "fixture", "Host", "不存在", out error), "Wrong title fell back to process"); + Check.True(!string.IsNullOrEmpty(error), "Missing title diagnostic"); + Check.Equal(null, FloatingBarManager.FindConditionWindow(windows, "fixture", null, null, out error), "Ambiguous windows silently chose first"); + Check.True(!string.IsNullOrEmpty(error), "Ambiguity diagnostic"); + Check.Equal(null, FloatingBarManager.FindConditionWindow(windows, null, null, null, out error), "Empty clues matched a window"); + Check.Equal(null, FloatingBarManager.FindConditionWindow(windows, null, "Host", "wrong", out error), "Class OR title bug returned"); + } + + private static void InvalidConfiguration() + { + var bar = new FloatingBarDefinition { Enabled = false }; + var result = FloatingBarManager.CheckDisplayConditions(bar); + Check.True(!result.CanShow && !string.IsNullOrWhiteSpace(result.Reason), "Disabled bar lacks reason"); + bar.Enabled = true; + result = FloatingBarManager.CheckDisplayConditions(bar); + Check.True(!result.CanShow && !string.IsNullOrWhiteSpace(result.Reason), "Empty buttons lack reason"); + bar.Buttons.Add(new FloatingButtonDefinition { Enabled = true, Label = "测试", Action = FloatingActionKind.PickControl }); + result = FloatingBarManager.CheckDisplayConditions(bar); + Check.True(!result.CanShow && !string.IsNullOrWhiteSpace(result.Reason), "No anchor lacks reason"); + bar.ImportedCondition = new ControlMonitorDefinition { ControlPath = TreeFixture.MenuLegacy, ProcessName = "fixture" }; + result = FloatingBarManager.CheckDisplayConditions(bar); + Check.True(!result.CanShow && result.Reason.IndexOf("path", StringComparison.OrdinalIgnoreCase) >= 0, "Old imported path lacks diagnostic"); + } + } +} diff --git a/tests/regression/PathTests.cs b/tests/regression/PathTests.cs new file mode 100644 index 0000000..bc97b45 --- /dev/null +++ b/tests/regression/PathTests.cs @@ -0,0 +1,204 @@ +using System; +using System.Collections.Generic; +using pacs_win_uia.Models; +using pacs_win_uia.Services; + +namespace PacsWinUia.RegressionTests +{ + internal static class PathTests + { + public static void Register(IList> tests) + { + tests.Add(new KeyValuePair("XPath attributes, contains, axes and positional predicates", XPathQueries)); + tests.Add(new KeyValuePair("All nodes roundtrip with duplicate IDs and structural indices", AllNodesRoundtrip)); + tests.Add(new KeyValuePair("Generated paths survive names changing on every ancestor", ChangingNames)); + tests.Add(new KeyValuePair("Class-qualified paths and stable ancestor anchors", ClassAndAnchor)); + tests.Add(new KeyValuePair("XPath quoting for both quotes, slash and Chinese", Escaping)); + tests.Add(new KeyValuePair("Old display and structured paths are not executed", RejectLegacy)); + tests.Add(new KeyValuePair("Invalid, scalar and attribute XPath rejected", RejectedPaths)); + tests.Add(new KeyValuePair("Ambiguity never resolves to an arbitrary first node", AmbiguousPaths)); + tests.Add(new KeyValuePair("Changed XPath is authoritative over stale locator hints", AuthoritativeXPath)); + tests.Add(new KeyValuePair("Root, outsider and incomplete snapshot handling", RootAndIncomplete)); + tests.Add(new KeyValuePair("XPath resolution preserves MSAA and Win32 payloads", OtherSources)); + } + + private static void XPathQueries() + { + var f = new TreeFixture(); + Check.Matches(f.Root, "/Window[1]", f.Root); + Check.Matches(f.Root, "//ListItem[@Name='个性化']", f.MenuItem); + Check.Matches(f.Root, "//*[@AutomationId='PermanentNavigationView']", f.Navigation); + Check.Matches(f.Root, "//Button[@ClassName='SecondaryButton']", f.SecondDuplicate); + Check.Matches(f.Root, "//Button[contains(@Name,'重') and @AutomationId='same-id']", f.FirstDuplicate, f.SecondDuplicate); + Check.Matches(f.Root, "//Button[@Name='重复'][2]", f.SecondDuplicate); + Check.Matches(f.Root, "(//Button[@AutomationId='same-id'])[1]", f.FirstDuplicate); + Check.Matches(f.Root, "//Group[@AutomationId='Duplicates']/Button[3]", f.SecondDuplicate); + Check.Matches(f.Root, "//Group[@AutomationId='PermanentNavigationViewBreadcrumbBar']/Button/Text", f.BreadcrumbText); + Check.Matches(f.Root, "//Group[@AutomationId='MenuItemsHost']/ListItem[1]", f.MenuItem); + Check.Rejected(f.Root, "//Button[@Name='重复'][0]"); + Check.Rejected(f.Root, "/Window/ListItem[@Name='个性化']"); + } + + private static void AllNodesRoundtrip() + { + var f = new TreeFixture(); + var builder = new ControlLocatorBuilder(); + var window = new NativeWindowInfo(IntPtr.Zero) { ProcessName = "fixture", ClassName = "RootClass", Title = "设置" }; + ControlPath.PreparePaths(f.Root); + var unique = new HashSet(StringComparer.Ordinal); + foreach (ControlTreeNode node in TreeFixture.All(f.Root)) + { + string path = ControlPath.Build(f.Root, node); + Check.True(path.StartsWith("/Window[1]", StringComparison.Ordinal), "Root must not depend on window title"); + Check.True(path.IndexOf("@Name", StringComparison.Ordinal) < 0, "Generated path depends on a mutable Name"); + Check.True(unique.Add(path), "Two nodes share a path: " + path); + Check.Matches(f.Root, path, node); + ControlLocatorBuildResult built = builder.BuildFromTree(f.Root, node, window); + Check.True(built.IsComplete, "Builder incomplete: " + built.Note); + Check.Equal(path, built.DisplayPath, "Builder path differs"); + var resolved = ControlLocatorService.ResolveFromTree(new ControlMonitorDefinition { ControlPath = path, Source = ControlSourcePreference.Uia }, f.Root, IntPtr.Zero); + Check.True(resolved.Found, "Resolver failed: " + resolved.Error); + Check.Same(node, resolved.Node, "Resolver must return original node"); + } + Check.True(f.FirstDuplicate.CanonicalPath.EndsWith("Button[@AutomationId='same-id'][1]", StringComparison.Ordinal), "Duplicate ID first ordinal"); + Check.True(f.SecondDuplicate.CanonicalPath.EndsWith("Button[@AutomationId='same-id'][2]", StringComparison.Ordinal), "Duplicate ID second ordinal"); + } + + private static void ChangingNames() + { + var f = new TreeFixture(); + var original = new Dictionary(); + ControlPath.PreparePaths(f.Root); + foreach (ControlTreeNode node in TreeFixture.All(f.Root)) original.Add(node, node.CanonicalPath); + foreach (ControlTreeNode node in TreeFixture.All(f.Root)) node.Uia.Name = "动态患者/状态 '变化' \"中文\""; + ControlPath.PreparePaths(f.Root); + foreach (var item in original) + { + Check.Equal(item.Value, item.Key.CanonicalPath, "Name change invalidated path"); + Check.Matches(f.Root, item.Value, item.Key); + } + Check.Rejected(f.Root, "//ListItem[@Name='个性化']"); + } + + private static void ClassAndAnchor() + { + var root = TreeFixture.Node("Window", "患者 A"); + var page = TreeFixture.Add(root, TreeFixture.Node("Pane", "页码1", "stable-page")); + var target = TreeFixture.Add(page, TreeFixture.Node("Edit", "数量1", null, "PatientEditor")); + string path = ControlPath.Build(root, target); + Check.True(path.IndexOf("@ClassName='PatientEditor'", StringComparison.Ordinal) >= 0, "Class fallback absent"); + root.Uia.Name = "患者 B"; + page.Uia.Name = "页码2"; + target.Uia.Name = "数量2"; + Check.Matches(root, path, target); + // A descendant anchor survives insertion of a layout-only ancestor. + page.Children.Clear(); + TreeFixture.Add(TreeFixture.Add(page, TreeFixture.Node("Group", "新布局")), target); + Check.Matches(root, "//*[@AutomationId='stable-page']//Edit[@ClassName='PatientEditor']", target); + Check.Rejected(root, path); + // Structure alone is not a semantic identity; duplicate candidates must remain ambiguous. + TreeFixture.Add(page, TreeFixture.Node("Edit", "相同类型", null, "PatientEditor")); + string error; + Check.Equal(null, ControlPath.SelectUnique(root, + "//*[@AutomationId='stable-page']//Edit[@ClassName='PatientEditor']", out error), "Anchor ambiguity guessed a node"); + Check.True(!string.IsNullOrEmpty(error), "Ambiguity missing reason"); + } + + private static void Escaping() + { + var f = new TreeFixture(); + Check.Matches(f.Root, "//Text[@Name=" + ControlPath.Quote(f.EscapedName.Uia.Name) + "]", f.EscapedName); + Check.Matches(f.Root, "//Edit[@AutomationId=" + ControlPath.Quote(f.EscapedId.Uia.AutomationId) + + " and @ClassName=" + ControlPath.Quote(f.EscapedId.Uia.ClassName) + "]", f.EscapedId); + Check.Matches(f.Root, ControlPath.Build(f.Root, f.EscapedId), f.EscapedId); + } + + private static void RejectLegacy() + { + var f = new TreeFixture(); + foreach (string path in new[] { TreeFixture.BreadcrumbLegacy, TreeFixture.MenuLegacy, + "[Uia] /Window[1]", "Group[Duplicates] > Button#2", "[MSAA] i3/o1", "[Win32] Class 0x123" }) + { + Check.Rejected(f.Root, path); + var result = ControlLocatorService.ResolveFromTree(new ControlMonitorDefinition { ControlPath = path }, f.Root, IntPtr.Zero); + Check.True(!result.Found && !string.IsNullOrEmpty(result.Error), "Legacy resolver unexpectedly succeeded"); + } + var structured = new ControlMonitorDefinition + { + ControlPath = "", + UiaPath = new List { new ControlLocatorSegment { ControlType = "ControlType.Custom", AutomationId = "PermanentNavigationView" } } + }; + Check.True(!ControlLocatorService.ResolveFromTree(structured, f.Root, IntPtr.Zero).Found, "Structured old path must not execute"); + } + + private static void RejectedPaths() + { + var f = new TreeFixture(); + foreach (string path in new[] { "//Button[@AutomationId='missing']", "//Button[", "/Window/@Name", "/", "", " ", "count(//Button)", "(1 + 1)", "true()" }) + Check.Rejected(f.Root, path); + Check.Rejected(null, "/Window"); + Check.Equal(null, ControlPath.ValidateSyntax("//Edit[@ClassName='PatientEditor']"), "Valid syntax"); + Check.True(ControlPath.ValidateSyntax("//Edit[") != null, "Broken syntax accepted"); + Check.True(ControlPath.ValidateSyntax(TreeFixture.MenuLegacy) != null, "Legacy syntax accepted"); + } + + private static void AmbiguousPaths() + { + var f = new TreeFixture(); + string path = "//Button[@AutomationId='same-id']"; + Check.Matches(f.Root, path, f.FirstDuplicate, f.SecondDuplicate); + string error; + Check.Equal(null, ControlPath.SelectUnique(f.Root, path, out error), "Must not take first match"); + Check.True(!string.IsNullOrWhiteSpace(error), "Ambiguity lacks reason"); + Check.True(!ControlLocatorService.ResolveFromTree(new ControlMonitorDefinition { ControlPath = path }, f.Root, IntPtr.Zero).Found, "Resolver guessed ambiguity"); + } + + private static void AuthoritativeXPath() + { + var f = new TreeFixture(); + var definition = new ControlMonitorDefinition + { + ControlPath = ControlPath.Build(f.Root, f.MenuItem), RuntimeId = "stale-runtime", + UiaPath = new List { new ControlLocatorSegment { ControlType = "ControlType.Text", Name = "个性化" } } + }; + Check.Same(f.MenuItem, ControlLocatorService.ResolveFromTree(definition, f.Root, IntPtr.Zero).Node, "Old hint overrode XPath"); + definition.ControlPath = "//ListItem[@Name='不存在']"; + Check.True(!ControlLocatorService.ResolveFromTree(definition, f.Root, IntPtr.Zero).Found, "Missing XPath fell back"); + definition.ControlPath = ControlPath.Build(f.Root, f.BreadcrumbText); + Check.Same(f.BreadcrumbText, ControlLocatorService.ResolveFromTree(definition, f.Root, IntPtr.Zero).Node, "Edited XPath ignored"); + } + + private static void RootAndIncomplete() + { + var f = new TreeFixture(); + Check.Equal("/Window[1]", ControlPath.Build(f.Root, f.Root), "Root path"); + Check.True(new ControlLocatorBuilder().BuildFromTree(f.Root, f.Root, null).IsComplete, "Root cannot save"); + var outsider = TreeFixture.Node("Button", "外部"); + Check.Equal(null, ControlPath.Build(f.Root, outsider), "Outsider got a path"); + string path = ControlPath.Build(f.Root, f.MenuItem); + f.Root.ChildrenComplete = false; + f.Root.ChildrenError = "fixture truncated"; + Check.True(!new ControlLocatorBuilder().BuildFromTree(f.Root, f.MenuItem, null).IsComplete, "Incomplete builder claimed success"); + Check.True(!ControlLocatorService.ResolveFromTree(new ControlMonitorDefinition { ControlPath = path }, f.Root, IntPtr.Zero).Found, "Incomplete resolution claimed uniqueness"); + } + + private static void OtherSources() + { + var win = new ControlTreeNode { Source = ControlTreeSource.Win32, Window = new NativeWindowInfo(IntPtr.Zero) { ClassName = "Host", Title = "动态标题" } }; + var child = new ControlTreeNode { Source = ControlTreeSource.Win32, Window = new NativeWindowInfo(IntPtr.Zero) { ClassName = "Edit", Title = "动态输入" } }; + win.Children.Add(child); + string path = ControlPath.Build(win, child); + Check.Matches(win, path, child); + var result = ControlLocatorService.ResolveFromTree(new ControlMonitorDefinition { Source = ControlSourcePreference.Win32, ControlPath = path }, win, IntPtr.Zero); + Check.True(result.Found && result.ResolvedSource == ControlTreeSource.Win32, "Win32 XPath source lost"); + Check.Same(child, result.Node, "Win32 payload lost"); + var msaa = new ControlTreeNode { Source = ControlTreeSource.Msaa, Msaa = new MsaaNodeInfo { Name = "动态根" } }; + var item = new ControlTreeNode { Source = ControlTreeSource.Msaa, Msaa = new MsaaNodeInfo { Name = "动态项" } }; + msaa.Children.Add(item); + path = ControlPath.Build(msaa, item); + result = ControlLocatorService.ResolveFromTree(new ControlMonitorDefinition { Source = ControlSourcePreference.Msaa, ControlPath = path }, msaa, IntPtr.Zero); + Check.True(result.Found && result.ResolvedSource == ControlTreeSource.Msaa, "MSAA XPath source lost"); + Check.Same(item, result.Node, "MSAA payload lost"); + } + } +} diff --git a/tests/regression/PersistenceTests.cs b/tests/regression/PersistenceTests.cs new file mode 100644 index 0000000..af87a06 --- /dev/null +++ b/tests/regression/PersistenceTests.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using pacs_win_uia.Models; +using pacs_win_uia.Services; + +namespace PacsWinUia.RegressionTests +{ + internal static class PersistenceTests + { + public static void Register(IList> tests) + { + tests.Add(new KeyValuePair("Store saves XPath without dynamic UIA fields and copies flags", StoreXPath)); + tests.Add(new KeyValuePair("Store reads legacy UiaPath definitions", StoreLegacy)); + tests.Add(new KeyValuePair("Settings missing refresh interval defaults to 300", SettingsDefault)); + tests.Add(new KeyValuePair("Floating JSON missing defaults differs from explicit disabled", FloatingDefaults)); + } + + private static void StoreXPath() + { + using (var directory = new TemporaryDirectory()) + { + string path = directory.File("control-monitors.json"); + var definition = new ControlMonitorDefinition + { + Id = "11111111-1111-1111-1111-111111111111", + ControlPath = "/Window[@Name='设置']/Button[@Name='保存']", + ContentKey = "xpath_save", + SourceName = "Uia", + RuntimeId = "dynamic-runtime-id", + Value = "live-value-must-not-persist", + UiaPathFromInnerWindow = true, + Disabled = true, + UiaPath = new List + { + new ControlLocatorSegment { ControlType = "ControlType.Button", Name = "stale legacy", Index = 4 } + }, + ProcessName = "fixture", + WindowClass = "RootClass", + WindowTitleKeyword = "设置" + }; + new ControlMonitorStore(path).Save(new[] { definition }); + string json = File.ReadAllText(path, Encoding.UTF8); + Check.True(json.IndexOf("dynamic-runtime-id", StringComparison.Ordinal) < 0, "RuntimeId leaked into JSON"); + Check.True(json.IndexOf("live-value-must-not-persist", StringComparison.Ordinal) < 0, "Value leaked into JSON"); + Check.True(json.IndexOf("\"UiaPath\":", StringComparison.Ordinal) < 0, "UiaPath must not be persisted with XPath"); + Check.True(json.IndexOf("UiaPathFromInnerWindow", StringComparison.Ordinal) < 0, "Obsolete inner-window flag persisted"); + Check.True(json.IndexOf("Disabled", StringComparison.Ordinal) >= 0, "Disabled flag missing"); + IList loaded = new ControlMonitorStore(path).Load(); + Check.Equal(1, loaded.Count, "Saved definition count"); + Check.Equal(definition.ControlPath, loaded[0].ControlPath, "XPath roundtrip"); + Check.True(loaded[0].Disabled && !loaded[0].Enabled, "Disabled flag roundtrip"); + Check.True(!loaded[0].UiaPathFromInnerWindow, "Obsolete inner-window flag survived XPath save"); + Check.Equal(null, loaded[0].RuntimeId, "RuntimeId must remain runtime-only"); + Check.Equal(null, loaded[0].Value, "Value must remain runtime-only"); + Check.True(loaded[0].UiaPath == null || loaded[0].UiaPath.Count == 0, "XPath must not restore stale UiaPath"); + } + } + + private static void StoreLegacy() + { + using (var directory = new TemporaryDirectory()) + { + string path = directory.File("legacy.json"); + string json = "{\"Version\":1,\"Items\":[{" + + "\"Id\":\"22222222-2222-2222-2222-222222222222\"," + + "\"ControlPath\":\"[Uia] Window:设置 > Button:保存\"," + + "\"ContentKey\":\"legacy_save\"," + + "\"Source\":\"Uia\",\"UiaPathFromInnerWindow\":true,\"Disabled\":true," + + "\"UiaPath\":[{\"ControlType\":\"ControlType.Window\",\"Name\":\"设置\",\"Index\":0}," + + "{\"ControlType\":\"ControlType.Button\",\"Name\":\"保存\",\"Index\":0}]" + + "}]}"; + File.WriteAllText(path, json, new UTF8Encoding(false)); + IList loaded = new ControlMonitorStore(path).Load(); + Check.Equal(1, loaded.Count, "Legacy definition count"); + ControlMonitorDefinition definition = loaded[0]; + Check.Equal("[Uia] Window:设置 > Button:保存", definition.ControlPath, "Legacy display path"); + Check.True(definition.Disabled && !definition.Enabled, "Legacy disabled flag"); + Check.True(ControlMonitorRules.ValidateField(definition, "ControlPath") != null, "Old path needs an editable validation error"); + bool rejected = false; + try { new ControlMonitorStore(path).Save(loaded); } + catch (InvalidDataException) { rejected = true; } + Check.True(rejected, "Saving old path silently succeeded"); + Check.Equal(json, File.ReadAllText(path, Encoding.UTF8), "Failed save overwrote old file"); + definition.ControlPath = "/Window[1]//Button[@AutomationId='save']"; + new ControlMonitorStore(path).Save(loaded); + Check.Equal(definition.ControlPath, new ControlMonitorStore(path).Load()[0].ControlPath, "Corrected XPath did not persist"); + } + } + + private static void FloatingDefaults() + { + using (var directory = new TemporaryDirectory()) + { + string preferred = directory.File("floating-defaults.json"); + File.WriteAllText(preferred, + "{\"Version\":1,\"FloatingButton\":{\"Bars\":[{\"Name\":\"missing-defaults\",\"Buttons\":[{\"Label\":\"test\"}]},{\"Name\":\"disabled\",\"Enabled\":false,\"Buttons\":[{\"Label\":\"off\",\"Enabled\":false}]}]}}", + new UTF8Encoding(false)); + AppSettings settings = new AppSettingsStore(preferred, directory.File("fallback.json")).Load(); + Check.Equal(2, settings.FloatingButton.Bars.Count, "JSON bars disappeared"); + FloatingBarDefinition first = settings.FloatingButton.Bars[0]; + Check.True(first.Enabled && first.RequireWindowVisible, "Missing bar defaults were not initialized"); + Check.True(first.Buttons[0].Enabled, "Missing button enabled default"); + Check.True(!settings.FloatingButton.Bars[1].Enabled && !settings.FloatingButton.Bars[1].Buttons[0].Enabled, + "Explicit disabled flags must not be overridden"); + new AppSettingsStore(preferred, directory.File("fallback.json")).Save(settings); + Check.True(!new AppSettingsStore(preferred, directory.File("fallback.json")).Load().FloatingButton.Bars[1].Enabled, + "Disabled bar changed after roundtrip"); + } + } + + private static void SettingsDefault() + { + using (var directory = new TemporaryDirectory()) + { + string preferred = directory.File("settings.json"); + string fallback = directory.File("fallback-settings.json"); + File.WriteAllText(preferred, "{\"Version\":1,\"Ui\":{\"TreeMaxDepth\":12}}", new UTF8Encoding(false)); + AppSettings settings = new AppSettingsStore(preferred, fallback).Load(); + Check.Equal(AppSettings.DefaultRefreshIntervalMs, settings.Ui.TreeRefreshIntervalMs, "Missing Ui refresh interval"); + Check.True(settings.FloatingButton != null, "Missing FloatingButton section default"); + Check.Equal(AppSettings.DefaultRefreshIntervalMs, settings.FloatingButton.RefreshIntervalMs, "Missing floating refresh interval"); + Check.True(settings.Commands != null && settings.Ocr != null && settings.Read != null && settings.Screenshot != null, + "Missing settings sections were not restored"); + } + } + } +} diff --git a/tests/regression/Program.cs b/tests/regression/Program.cs new file mode 100644 index 0000000..86ef584 --- /dev/null +++ b/tests/regression/Program.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using pacs_win_uia.Models; +using pacs_win_uia.Services; + +namespace PacsWinUia.RegressionTests +{ + internal static class Program + { + [STAThread] + private static int Main() + { + Console.OutputEncoding = new UTF8Encoding(false); + var tests = new List>(); + PathTests.Register(tests); + PersistenceTests.Register(tests); + TreeRefreshTests.Register(tests); + FloatingConditionsTests.Register(tests); + int passed = 0; + foreach (var test in tests) + { + try + { + test.Value(); + passed++; + Console.WriteLine("PASS " + test.Key); + } + catch (Exception exception) + { + Console.WriteLine("FAIL " + test.Key); + Console.WriteLine(exception); + } + } + Console.WriteLine("RESULT total={0} passed={1} failed={2}", tests.Count, passed, tests.Count - passed); + return passed == tests.Count ? 0 : 1; + } + } + + internal static class Check + { + public static void True(bool condition, string message) + { + if (!condition) throw new InvalidOperationException(message); + } + + public static void Equal(T expected, T actual, string message) + { + True(EqualityComparer.Default.Equals(expected, actual), + message + "; expected=" + expected + "; actual=" + actual); + } + + public static void Same(object expected, object actual, string message) + { + True(ReferenceEquals(expected, actual), message + "; node reference mismatch"); + } + + public static void Matches(ControlTreeNode root, string path, params ControlTreeNode[] expected) + { + string error; + IList actual = ControlPath.Select(root, path, out error); + Equal(null, error, "Select error: " + path); + Equal(expected.Length, actual.Count, "Select count: " + path); + for (int i = 0; i < expected.Length; i++) Same(expected[i], actual[i], "Select order: " + path); + if (expected.Length == 1) + { + Same(expected[0], ControlPath.SelectUnique(root, path, out error), "SelectUnique: " + path); + Equal(null, error, "SelectUnique error: " + path); + } + } + + public static void Rejected(ControlTreeNode root, string path) + { + string error; + Equal(0, ControlPath.Select(root, path, out error).Count, "Rejected path returned nodes: " + path); + True(!string.IsNullOrWhiteSpace(error), "Rejected path lacks error: " + path); + Equal(null, ControlPath.SelectUnique(root, path, out error), "Rejected path uniquely resolved: " + path); + True(!string.IsNullOrWhiteSpace(error), "Rejected unique path lacks error: " + path); + } + } + + internal sealed class TemporaryDirectory : IDisposable + { + public TemporaryDirectory() + { + DirectoryPath = Path.Combine(Path.GetTempPath(), "pacs-win-uia-regression-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(DirectoryPath); + } + + public string DirectoryPath { get; private set; } + public string File(string name) { return Path.Combine(DirectoryPath, name); } + public void Dispose() { Directory.Delete(DirectoryPath, true); } + } + + // Every node is an in-memory snapshot: no AutomationElement, HWND lookup, GUI or provider calls. + internal sealed class TreeFixture + { + public const string BreadcrumbLegacy = "[Uia] Custom[PermanentNavigationView] > Group[PermanentNavigationViewBreadcrumbBar] > Button:个性化 > Text:个性化"; + public const string MenuLegacy = "[Uia] Window:设置 > Custom[PermanentNavigationView] > Window[PaneRoot] > Pane[MenuItemsScrollViewer] > Group[MenuItemsHost] > ListItem:个性化"; + public readonly ControlTreeNode Root; + public readonly ControlTreeNode Navigation; + public readonly ControlTreeNode BreadcrumbText; + public readonly ControlTreeNode MenuItem; + public readonly ControlTreeNode Duplicates; + public readonly ControlTreeNode FirstDuplicate; + public readonly ControlTreeNode SecondDuplicate; + public readonly ControlTreeNode NameWithId; + public readonly ControlTreeNode NameWithoutId; + public readonly ControlTreeNode Nameless; + public readonly ControlTreeNode EscapedName; + public readonly ControlTreeNode EscapedId; + + public TreeFixture() + { + Root = Node("Window", "设置", null, "RootClass"); + Navigation = Add(Root, Node("Custom", null, "PermanentNavigationView")); + var breadcrumb = Add(Navigation, Node("Group", null, "PermanentNavigationViewBreadcrumbBar")); + BreadcrumbText = Add(Add(breadcrumb, Node("Button", "个性化")), Node("Text", "个性化")); + var paneRoot = Add(Navigation, Node("Window", null, "PaneRoot")); + var scroll = Add(paneRoot, Node("Pane", null, "MenuItemsScrollViewer")); + var host = Add(scroll, Node("Group", null, "MenuItemsHost")); + MenuItem = Add(host, Node("ListItem", "个性化")); + Add(host, Node("ListItem", "系统")); + Duplicates = Add(Root, Node("Group", null, "Duplicates")); + FirstDuplicate = Add(Duplicates, Node("Button", "重复", "same-id", "PrimaryButton")); + Add(Duplicates, Node("Text", "同级异类型")); + Add(Duplicates, Node("Button", "其他", "other-id", "OtherButton")); + SecondDuplicate = Add(Duplicates, Node("Button", "重复", "same-id", "SecondaryButton")); + NameWithId = Add(Duplicates, Node("Button", "混合名称", "has-id")); + NameWithoutId = Add(Duplicates, Node("Button", "混合名称")); + Nameless = Add(Duplicates, Node("Button")); + Add(Duplicates, Node("Button")); + EscapedName = Add(Root, Node("Text", "中文 '单引号' \"双引号\" /斜杠 > 大于 & < [括号]")); + EscapedId = Add(Root, Node("Edit", "输入", "id'\"/ > 中文 & <", "class'\"/ > 中文 & <")); + } + + public static ControlTreeNode Node(string type, string name = null, string id = null, string className = null) + { + return new ControlTreeNode + { + Source = ControlTreeSource.Uia, + Uia = new UiaElementInfo { ControlType = "ControlType." + type, Name = name, AutomationId = id, ClassName = className } + }; + } + + public static ControlTreeNode Add(ControlTreeNode parent, ControlTreeNode child) + { + parent.Children.Add(child); + return child; + } + + public static IEnumerable All(ControlTreeNode root) + { + yield return root; + foreach (ControlTreeNode child in root.Children) + foreach (ControlTreeNode descendant in All(child)) yield return descendant; + } + } +} diff --git a/tests/regression/RegressionTests.csproj b/tests/regression/RegressionTests.csproj new file mode 100644 index 0000000..61d899a --- /dev/null +++ b/tests/regression/RegressionTests.csproj @@ -0,0 +1,39 @@ + + + + Debug + AnyCPU + {734FCA9D-3071-48D1-91DF-C2A07B329512} + Exe + PacsWinUia.RegressionTests + RegressionTests + v4.8 + bin\$(Configuration)\ + 7.3 + false + true + + + + + + + + + + + + {C74B0B3A-0FB4-47CB-9AE8-DC7E0D993202} + pacs_win_uia + + + + + + + + + ControlTreeReconciler.cs + + + diff --git a/tests/regression/TreeRefreshTests.cs b/tests/regression/TreeRefreshTests.cs new file mode 100644 index 0000000..f87ec33 --- /dev/null +++ b/tests/regression/TreeRefreshTests.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Windows.Forms; +using pacs_win_uia.Models; +using pacs_win_uia.UI; + +namespace PacsWinUia.RegressionTests +{ + internal static class TreeRefreshTests + { + public static void Register(IList> tests) + { + tests.Add(new KeyValuePair("Tree refresh retains native items when unchanged or renamed", RetainsItems)); + tests.Add(new KeyValuePair("Tree refresh applies only insert, remove and move differences", StructuralChanges)); + tests.Add(new KeyValuePair("Tree fallback identity ignores mutable Name", FallbackIdentity)); + } + + private static ControlTreeReconciler.Item Item(string runtime, string name) + { + return new ControlTreeReconciler.Item + { + Model = new ControlTreeNode { Source = ControlTreeSource.Uia, + Uia = new UiaElementInfo { ProcessId = 12345, RuntimeId = runtime, + ControlType = "ControlType.Button", Name = name, ClassName = "StableClass" } }, + Text = name, + ForeColor = System.Drawing.Color.Empty + }; + } + + private static void RetainsItems() + { + using (var tree = new TreeView()) + using (var update = new ControlTreeReconciler(tree)) + { + tree.CreateControl(); + var matches = new List(); + var root = Item("1", "root"); + root.Children.Add(Item("2", "before")); + update.Apply(root, matches); + TreeNode parent = tree.Nodes[0], child = parent.Nodes[0]; + parent.Expand(); + tree.SelectedNode = child; + IntPtr handle = child.Handle; + for (int i = 0; i < 40; i++) + { + var fresh = Item("1", "root"); + fresh.Children.Add(Item("2", i < 20 ? "before" : "after")); + fresh.Children[0].Match = i >= 30; + update.Apply(fresh, matches); + Check.Same(parent, tree.Nodes[0], "Root was rebuilt"); + Check.Same(child, parent.Nodes[0], "Renamed item was rebuilt"); + Check.Equal(handle, child.Handle, "Native item handle changed"); + Check.Same(child, tree.SelectedNode, "Selection changed"); + Check.True(parent.IsExpanded, "Parent collapsed"); + Check.Same(fresh.Children[0].Model, child.Tag, "Tag not rebound to fresh snapshot"); + } + Check.Equal("after", child.Text, "Updated text missing"); + Check.Equal(1, matches.Count, "Search matches not updated"); + } + } + + private static void StructuralChanges() + { + using (var tree = new TreeView()) + using (var update = new ControlTreeReconciler(tree)) + { + tree.CreateControl(); + var matches = new List(); + var root = Item("1", "root"); + root.Children.Add(Item("2", "A")); + root.Children.Add(Item("3", "B")); + root.Children.Add(Item("4", "C")); + update.Apply(root, matches); + TreeNode original = tree.Nodes[0], a = original.Nodes[0], b = original.Nodes[1], c = original.Nodes[2]; + original.Expand(); + tree.SelectedNode = b; + var fresh = Item("1", "root"); + fresh.Children.Add(Item("4", "C")); + fresh.Children.Add(Item("5", "inserted")); + fresh.Children.Add(Item("3", "B renamed")); + update.Apply(fresh, matches); + Check.Same(original, tree.Nodes[0], "Root rebuilt on structural change"); + Check.Same(c, original.Nodes[0], "Moved C lost identity"); + Check.Same(b, original.Nodes[2], "Retained B lost identity"); + Check.Equal(3, original.Nodes.Count, "Insert/delete count"); + Check.True(a.TreeView == null, "Deleted A retained"); + Check.Same(b, tree.SelectedNode, "Selection lost after sibling reorder"); + Check.True(original.IsExpanded, "Expansion lost after reorder"); + var moved = Item("1", "root"); + var newParent = Item("6", "new parent"); + newParent.Children.Add(Item("3", "B moved")); + moved.Children.Add(newParent); + update.Apply(moved, matches); + Check.Same(b, original.Nodes[0].Nodes[0], "Reparented item lost identity"); + Check.Same(b, tree.SelectedNode, "Selection lost after reparenting"); + } + } + + private static void FallbackIdentity() + { + using (var tree = new TreeView()) + using (var update = new ControlTreeReconciler(tree)) + { + var matches = new List(); + var root = Item(null, "old name"); + root.Children.Add(Item(null, "old child name")); + update.Apply(root, matches); + TreeNode parent = tree.Nodes[0], child = parent.Nodes[0]; + var fresh = Item(null, "new name"); + fresh.Children.Add(Item(null, "new child name")); + update.Apply(fresh, matches); + Check.Same(parent, tree.Nodes[0], "Fallback root depends on Name"); + Check.Same(child, parent.Nodes[0], "Fallback child depends on Name"); + } + } + } +} diff --git a/tests/run-fixture.cmd b/tests/run-fixture.cmd new file mode 100644 index 0000000..4524e41 --- /dev/null +++ b/tests/run-fixture.cmd @@ -0,0 +1,22 @@ +@echo off +rem 构建并启动 UIA 测试夹具(一个普通的 WinForms 窗口,用来验证控件树/拾取/列表读取)。 +rem 需要 .NET Framework 4.8(Windows 自带)与 dotnet SDK 或 MSBuild。 +setlocal +set HERE=%~dp0 +set PROJECT=%HERE%uia-fixture\UiaFixture.csproj +set CONFIG=%1 +if "%CONFIG%"=="" set CONFIG=Debug + +where dotnet >nul 2>nul +if %ERRORLEVEL%==0 ( + dotnet msbuild "%PROJECT%" -p:Configuration=%CONFIG% -v:m -nologo +) else ( + msbuild "%PROJECT%" -p:Configuration=%CONFIG% -v:m -nologo +) +if not %ERRORLEVEL%==0 ( + echo 构建失败。 + exit /b %ERRORLEVEL% +) + +start "" "%HERE%uia-fixture\bin\%CONFIG%\UiaFixture.exe" +endlocal diff --git a/tests/uia-fixture/FixtureForm.cs b/tests/uia-fixture/FixtureForm.cs new file mode 100644 index 0000000..dbaf275 --- /dev/null +++ b/tests/uia-fixture/FixtureForm.cs @@ -0,0 +1,215 @@ +using System; +using System.Drawing; +using System.Windows.Forms; + +namespace UiaFixture +{ + /// + /// A deliberately ordinary window for exercising the tool: every kind of control the tool has to + /// read (button, text box, checkbox, combo, radio, tree, list, grid, tabs) in one window, with + /// stable names and AutomationIds so a saved path keeps resolving. + /// + /// This exists because the PACS/OCS clients either expose nothing (CEF shells) or expose a large + /// tree nobody wants to hand-verify against; here the expected answer is known. + /// + /// Run it, then in the tool: 刷新窗口 → select "UIA 测试夹具" → 检查选中窗口. The window title and + /// class stay the same between runs, so saved monitor entries and floating-bar conditions can be + /// built against it. + /// + public sealed class FixtureForm : Form + { + private readonly Label _status; + private readonly TextBox _input; + private readonly CheckBox _check; + private readonly ComboBox _combo; + private readonly TreeView _tree; + private readonly ListView _list; + private readonly DataGridView _grid; + + public FixtureForm() + { + Text = "UIA 测试夹具"; + Name = "FixtureForm"; + StartPosition = FormStartPosition.Manual; + Location = new Point(60, 60); + Size = new Size(760, 620); + MinimumSize = new Size(600, 480); + + var tabs = new TabControl { Dock = DockStyle.Fill, Name = "FixtureTabs" }; + + // ---- page 1: the everyday controls + var page = new TabPage("控件") { Name = "ControlsPage" }; + var panel = new Panel { Dock = DockStyle.Fill, Padding = new Padding(10) }; + + var button = new Button + { + Text = "测试按钮", + Name = "FixtureButton", + AutoSize = true, + Location = new Point(12, 12) + }; + button.Click += delegate { SetStatus("按钮被点击:" + DateTime.Now.ToString("HH:mm:ss")); }; + + _input = new TextBox + { + Name = "FixtureTextBox", + Text = "可编辑文本", + Location = new Point(140, 14), + Width = 220 + }; + _input.TextChanged += delegate { SetStatus("文本框内容已改为:" + _input.Text); }; + + _check = new CheckBox + { + Text = "启用选项", + Name = "FixtureCheckBox", + Location = new Point(12, 50), + AutoSize = true + }; + _check.CheckedChanged += delegate { SetStatus("复选框:" + (_check.Checked ? "选中" : "未选中")); }; + + var radioA = new RadioButton { Text = "选项 A", Name = "FixtureRadioA", Location = new Point(140, 50), AutoSize = true, Checked = true }; + var radioB = new RadioButton { Text = "选项 B", Name = "FixtureRadioB", Location = new Point(240, 50), AutoSize = true }; + radioA.CheckedChanged += delegate { SetStatus("单选:A"); }; + radioB.CheckedChanged += delegate { SetStatus("单选:B"); }; + + _combo = new ComboBox + { + Name = "FixtureComboBox", + DropDownStyle = ComboBoxStyle.DropDownList, + Location = new Point(12, 80), + Width = 200 + }; + _combo.Items.AddRange(new object[] { "第一项", "第二项", "第三项" }); + _combo.SelectedIndex = 0; + _combo.SelectedIndexChanged += delegate { SetStatus("下拉选择:" + _combo.SelectedItem); }; + + var listLabel = new Label { Text = "列表(两列)", AutoSize = true, Location = new Point(12, 116) }; + _list = new ListView + { + Name = "FixtureListView", + View = View.Details, + FullRowSelect = true, + Location = new Point(12, 138), + Size = new Size(320, 150) + }; + _list.Columns.Add("姓名", 120); + _list.Columns.Add("编号", 100); + for (int index = 1; index <= 3; index++) + { + _list.Items.Add(new ListViewItem(new[] { "项目 " + index, "ID" + index })); + } + + _tree = new TreeView + { + Name = "FixtureTreeView", + Location = new Point(348, 138), + Size = new Size(360, 150) + }; + TreeNode root = _tree.Nodes.Add("根节点"); + root.Nodes.Add("子节点 1"); + root.Nodes.Add("子节点 2"); + root.ExpandAll(); + + _status = new Label + { + Name = "FixtureStatusLabel", + Text = "还没有操作。", + AutoSize = false, + Height = 22, + Location = new Point(12, 296), + Width = 700, + ForeColor = Color.DarkSlateGray + }; + + panel.Controls.Add(button); + panel.Controls.Add(_input); + panel.Controls.Add(_check); + panel.Controls.Add(radioA); + panel.Controls.Add(radioB); + panel.Controls.Add(_combo); + panel.Controls.Add(listLabel); + panel.Controls.Add(_list); + panel.Controls.Add(_tree); + panel.Controls.Add(_status); + page.Controls.Add(panel); + + // ---- page 2: a grid, for the list reader + var gridPage = new TabPage("表格") { Name = "GridPage" }; + _grid = new DataGridView + { + Name = "FixtureDataGrid", + Dock = DockStyle.Fill, + AllowUserToAddRows = false, + ReadOnly = true, + AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill + }; + _grid.Columns.Add("序号", "序号"); + _grid.Columns.Add("内容", "内容"); + _grid.Columns.Add("状态", "状态"); + for (int index = 1; index <= 5; index++) + { + _grid.Rows.Add(index.ToString(), "第 " + index + " 行内容", index % 2 == 0 ? "已完成" : "待处理"); + } + + gridPage.Controls.Add(_grid); + + // ---- page 3: a nested container, for "the list is inside the picked element" + var nestedPage = new TabPage("嵌套") { Name = "NestedPage" }; + var outer = new Panel { Dock = DockStyle.Fill, Padding = new Padding(8), Name = "NestedOuter" }; + var middle = new Panel { Dock = DockStyle.Fill, Padding = new Padding(8), Name = "NestedMiddle", BackColor = Color.WhiteSmoke }; + var innerList = new ListBox { Dock = DockStyle.Fill, Name = "NestedListBox" }; + for (int index = 1; index <= 4; index++) + { + innerList.Items.Add("嵌套列表项 " + index); + } + + middle.Controls.Add(innerList); + outer.Controls.Add(middle); + nestedPage.Controls.Add(outer); + + tabs.TabPages.Add(page); + tabs.TabPages.Add(gridPage); + tabs.TabPages.Add(nestedPage); + Controls.Add(tabs); + + // A second top-level window so "which window" itself can be tested. + var secondary = new Form + { + Text = "UIA 测试夹具 - 第二个窗口", + Name = "FixtureSecondWindow", + Owner = this, + StartPosition = FormStartPosition.Manual, + Location = new Point(840, 60), + Size = new Size(360, 220) + }; + var secondaryButton = new Button + { + Text = "第二个窗口的按钮", + Name = "FixtureSecondButton", + Location = new Point(20, 24), + AutoSize = true + }; + secondaryButton.Click += delegate { SetStatus("第二个窗口的按钮被点击。"); }; + secondary.Controls.Add(secondaryButton); + secondary.Shown += delegate { secondary.Location = new Point(Location.X + Width + 20, Location.Y); }; + AddOwnedForm(secondary); + } + + private void SetStatus(string text) + { + _status.Text = DateTime.Now.ToString("HH:mm:ss") + " " + text; + } + } + + internal static class Program + { + [STAThread] + private static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new FixtureForm()); + } + } +} diff --git a/tests/uia-fixture/UiaFixture.csproj b/tests/uia-fixture/UiaFixture.csproj new file mode 100644 index 0000000..a965a18 --- /dev/null +++ b/tests/uia-fixture/UiaFixture.csproj @@ -0,0 +1,23 @@ + + + + Debug + AnyCPU + WinExe + UiaFixture + UiaFixture + v4.8 + bin\$(Configuration)\ + 7.3 + + + + + + + + + + + +