@copylee/dsh-computer-use 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -9
- package/helper/Capture.cs +682 -0
- package/helper/Input.cs +500 -0
- package/helper/Native.cs +136 -0
- package/helper/Overlay.cs +1685 -0
- package/helper/Program.cs +244 -0
- package/helper/Uia.cs +882 -0
- package/helper/Windows.cs +761 -0
- package/lib/client.js +191 -114
- package/lib/index.js +940 -368
- package/lib/types/access.d.ts +7 -0
- package/lib/types/cdp.d.ts +14 -3
- package/lib/types/client/select.d.ts +1 -1
- package/lib/types/computer.d.ts +25 -5
- package/lib/types/diagnostics.d.ts +3 -0
- package/lib/types/helper-client.d.ts +5 -2
- package/lib/types/index.d.ts +4 -1
- package/lib/types/lease.d.ts +30 -0
- package/lib/types/overlay.d.ts +26 -2
- package/lib/types/ui-diff.d.ts +28 -0
- package/package.json +3 -2
- package/helper/CuHelper.cs +0 -4414
package/helper/Uia.cs
ADDED
|
@@ -0,0 +1,882 @@
|
|
|
1
|
+
// UI Automation tree reading, text extraction, Set-of-Marks rendering, password guard, and semantic actions (C# 5).
|
|
2
|
+
|
|
3
|
+
using System;
|
|
4
|
+
using System.Collections;
|
|
5
|
+
using System.Collections.Generic;
|
|
6
|
+
using System.Diagnostics;
|
|
7
|
+
using System.Drawing;
|
|
8
|
+
using System.Drawing.Drawing2D;
|
|
9
|
+
using System.Drawing.Imaging;
|
|
10
|
+
using System.Drawing.Text;
|
|
11
|
+
using System.IO;
|
|
12
|
+
using System.Reflection;
|
|
13
|
+
using System.Runtime.InteropServices;
|
|
14
|
+
using System.Text;
|
|
15
|
+
using System.Threading;
|
|
16
|
+
using System.Web.Script.Serialization;
|
|
17
|
+
using System.Windows.Automation;
|
|
18
|
+
using System.Windows.Forms;
|
|
19
|
+
using Microsoft.Win32;
|
|
20
|
+
|
|
21
|
+
namespace DshComputerUse
|
|
22
|
+
{
|
|
23
|
+
internal static class Uia
|
|
24
|
+
{
|
|
25
|
+
static readonly ControlType[] Interactive = {
|
|
26
|
+
ControlType.Button, ControlType.Edit, ControlType.Hyperlink, ControlType.MenuItem, ControlType.ListItem,
|
|
27
|
+
ControlType.TabItem, ControlType.CheckBox, ControlType.RadioButton, ControlType.ComboBox, ControlType.TreeItem,
|
|
28
|
+
ControlType.DataItem, ControlType.SplitButton, ControlType.Slider, ControlType.Spinner, ControlType.Document,
|
|
29
|
+
ControlType.MenuBar, ControlType.Menu, ControlType.ScrollBar, ControlType.Group };
|
|
30
|
+
|
|
31
|
+
// Wake the renderer, but keep collecting the window too: browser tabs,
|
|
32
|
+
// toolbars and the address bar are outside the renderer's subtree.
|
|
33
|
+
static IntPtr ChromiumRoot(IntPtr hwnd)
|
|
34
|
+
{
|
|
35
|
+
try
|
|
36
|
+
{
|
|
37
|
+
var cls = new StringBuilder(256);
|
|
38
|
+
Native.GetClassName(hwnd, cls, cls.Capacity);
|
|
39
|
+
if (!cls.ToString().StartsWith("Chrome_WidgetWin", StringComparison.Ordinal)) return hwnd;
|
|
40
|
+
IntPtr render = IntPtr.Zero;
|
|
41
|
+
while ((render = Native.FindWindowEx(hwnd, render, "Chrome_RenderWidgetHostHWND", null)) != IntPtr.Zero)
|
|
42
|
+
if (Native.IsWindowVisible(render)) return render;
|
|
43
|
+
return hwnd;
|
|
44
|
+
}
|
|
45
|
+
catch { return hwnd; }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
static bool IsEditorClass(string cls)
|
|
49
|
+
{
|
|
50
|
+
if (string.IsNullOrEmpty(cls)) return false;
|
|
51
|
+
string[] marks = { "ProseMirror", "tiptap", "CodeMirror", "monaco-editor", "ql-editor" };
|
|
52
|
+
foreach (var mark in marks)
|
|
53
|
+
if (cls.IndexOf(mark, StringComparison.OrdinalIgnoreCase) >= 0) return true;
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Chromium builds its accessibility tree lazily. A standard AT request
|
|
58
|
+
// (WM_GETOBJECT/OBJID_CLIENT) wakes it; without this, apps such as
|
|
59
|
+
// VS Code expose only a few nodes even though the render host exists.
|
|
60
|
+
static void WakeAccessibility(IntPtr hwnd)
|
|
61
|
+
{
|
|
62
|
+
try
|
|
63
|
+
{
|
|
64
|
+
IntPtr result;
|
|
65
|
+
Native.SendMessageTimeout(hwnd, 0x003D /* WM_GETOBJECT */, IntPtr.Zero,
|
|
66
|
+
new IntPtr(-4) /* OBJID_CLIENT */, 0x0002 /* SMTO_ABORTIFHUNG */, 1000, out result);
|
|
67
|
+
}
|
|
68
|
+
catch { }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// A broken provider may never return. Bound background queries rather
|
|
72
|
+
// than creating an unbounded number of stuck threads on repeated reads.
|
|
73
|
+
static readonly SemaphoreSlim WindowCollectors = new SemaphoreSlim(4, 4);
|
|
74
|
+
|
|
75
|
+
static bool SameWindow(IntPtr hwnd, uint expectedPid)
|
|
76
|
+
{
|
|
77
|
+
uint pid;
|
|
78
|
+
return expectedPid != 0 && Native.GetWindowThreadProcessId(hwnd, out pid) != 0 && pid == expectedPid;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
static bool IsActionWindow(IntPtr hwnd, uint pid, Native.POINT point)
|
|
82
|
+
{
|
|
83
|
+
if (!SameWindow(hwnd, pid) || Native.GetForegroundWindow() != hwnd) return false;
|
|
84
|
+
var hit = Windows.At(point.X, point.Y);
|
|
85
|
+
return hit.ContainsKey("hwnd") && Convert.ToInt64(hit["hwnd"]) == hwnd.ToInt64();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
public static object Act(Dictionary<string, object> r)
|
|
89
|
+
{
|
|
90
|
+
var hwnd = new IntPtr(Convert.ToInt64(r["hwnd"]));
|
|
91
|
+
uint pid = Convert.ToUInt32(r["pid"]);
|
|
92
|
+
var point = new Native.POINT(Args.Int(r, "x", 0), Args.Int(r, "y", 0));
|
|
93
|
+
string runtimeId = Args.Str(r, "runtimeId", "");
|
|
94
|
+
string action = Args.Str(r, "action", "");
|
|
95
|
+
var result = new Dictionary<string, object> { { "performed", false } };
|
|
96
|
+
if (runtimeId.Length == 0 || !IsActionWindow(hwnd, pid, point))
|
|
97
|
+
throw new Exception("The named target window changed");
|
|
98
|
+
|
|
99
|
+
// FromPoint is scoped to the visible hit. Ancestors are searched only
|
|
100
|
+
// for the exact listed element; no action is attempted on a substitute.
|
|
101
|
+
var hit = AutomationElement.FromPoint(new System.Windows.Point(point.X, point.Y));
|
|
102
|
+
AutomationElement target = null;
|
|
103
|
+
for (var el = hit; el != null; el = TreeWalker.ControlViewWalker.GetParent(el))
|
|
104
|
+
{
|
|
105
|
+
if (String.Join(",", el.GetRuntimeId()) == runtimeId) { target = el; break; }
|
|
106
|
+
if (el.Current.ControlType == ControlType.Window) break;
|
|
107
|
+
}
|
|
108
|
+
// Some providers stop the hit test at a host pane. The caller can
|
|
109
|
+
// re-resolve the control and verify its window before a pointer click.
|
|
110
|
+
if (target == null) return result;
|
|
111
|
+
if (target.Current.IsOffscreen) throw new Exception("The named target is offscreen");
|
|
112
|
+
if (!target.Current.IsEnabled)
|
|
113
|
+
throw new Exception("The named target is disabled");
|
|
114
|
+
object pattern = null;
|
|
115
|
+
if (action == "invoke" && !target.TryGetCurrentPattern(InvokePattern.Pattern, out pattern)) return result;
|
|
116
|
+
if (action == "focus" && !target.Current.IsKeyboardFocusable) return result;
|
|
117
|
+
if (action != "invoke" && action != "focus") return result;
|
|
118
|
+
if (!IsActionWindow(hwnd, pid, point))
|
|
119
|
+
throw new Exception("The named target window changed");
|
|
120
|
+
|
|
121
|
+
// A provider error after dispatch is indeterminate. Let it surface
|
|
122
|
+
// rather than claiming the host can safely click again.
|
|
123
|
+
if (action == "invoke") ((InvokePattern)pattern).Invoke();
|
|
124
|
+
else
|
|
125
|
+
{
|
|
126
|
+
target.SetFocus();
|
|
127
|
+
for (int i = 0; i < 10 && !target.Current.HasKeyboardFocus; i++) Thread.Sleep(25);
|
|
128
|
+
if (!target.Current.HasKeyboardFocus) throw new Exception("Could not verify focus on the named control");
|
|
129
|
+
}
|
|
130
|
+
result["performed"] = true;
|
|
131
|
+
return result;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
static bool BrowserChrome(AutomationElement element)
|
|
135
|
+
{
|
|
136
|
+
// Page content can supply arbitrary UIA names and IDs.
|
|
137
|
+
for (var parent = TreeWalker.ControlViewWalker.GetParent(element); parent != null; parent = TreeWalker.ControlViewWalker.GetParent(parent))
|
|
138
|
+
{
|
|
139
|
+
if (parent.Current.ControlType == ControlType.Document) return false;
|
|
140
|
+
if (parent.Current.ControlType == ControlType.Window) return true;
|
|
141
|
+
}
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
static bool BrowserContentFocused()
|
|
146
|
+
{
|
|
147
|
+
for (var el = AutomationElement.FocusedElement; el != null; el = TreeWalker.ControlViewWalker.GetParent(el))
|
|
148
|
+
{
|
|
149
|
+
if (el.Current.ControlType == ControlType.Document) return true;
|
|
150
|
+
if (el.Current.ControlType == ControlType.Window) return false;
|
|
151
|
+
}
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
public static object OpenBrowserTab(Dictionary<string, object> r)
|
|
156
|
+
{
|
|
157
|
+
var hwnd = new IntPtr(Convert.ToInt64(r["hwnd"]));
|
|
158
|
+
uint pid = Convert.ToUInt32(r["pid"]);
|
|
159
|
+
string expected = Args.Str(r, "tab", "");
|
|
160
|
+
Uri url;
|
|
161
|
+
if (!Uri.TryCreate(Args.Str(r, "url", ""), UriKind.Absolute, out url) || (url.Scheme != "http" && url.Scheme != "https"))
|
|
162
|
+
throw new Exception("Expected an HTTP(S) URL");
|
|
163
|
+
Func<bool> current = delegate { return SameWindow(hwnd, pid) && Native.GetForegroundWindow() == hwnd; };
|
|
164
|
+
Func<Dictionary<string, object>> read = delegate { return BrowserTab(r) as Dictionary<string, object>; };
|
|
165
|
+
var initial = new Dictionary<string, object>(r) { { "listTabs", true } };
|
|
166
|
+
var before = current() ? BrowserTab(initial) as Dictionary<string, object> : null;
|
|
167
|
+
object tabIds;
|
|
168
|
+
if (expected.Length == 0 || before == null || Args.Str(before, "tab", "") != expected || !current())
|
|
169
|
+
throw new Exception("The browser window or active tab changed before opening a new tab");
|
|
170
|
+
if (!before.TryGetValue("tabs", out tabIds) || !(tabIds is List<string>))
|
|
171
|
+
throw new Exception("Could not verify the browser's existing tabs");
|
|
172
|
+
var existing = new HashSet<string>((List<string>)tabIds);
|
|
173
|
+
if (!existing.Contains(expected)) throw new Exception("The active browser tab could not be verified");
|
|
174
|
+
|
|
175
|
+
Input.Keys(new Dictionary<string, object> { { "combos", new[] { new[] { 0x11, 0x54 } } } });
|
|
176
|
+
var clock = Stopwatch.StartNew();
|
|
177
|
+
string created = "";
|
|
178
|
+
while (clock.ElapsedMilliseconds < 2400 && current())
|
|
179
|
+
{
|
|
180
|
+
var fresh = read();
|
|
181
|
+
if (fresh != null && !existing.Contains(Args.Str(fresh, "tab", ""))
|
|
182
|
+
&& Args.Str(fresh, "url", "unavailable") == "")
|
|
183
|
+
{
|
|
184
|
+
created = Args.Str(fresh, "tab", "");
|
|
185
|
+
if (created.Length > 0) break;
|
|
186
|
+
}
|
|
187
|
+
Thread.Sleep(65);
|
|
188
|
+
}
|
|
189
|
+
if (created.Length == 0 || !current())
|
|
190
|
+
throw new Exception("Could not confirm a new blank tab in the original browser window");
|
|
191
|
+
Input.Keys(new Dictionary<string, object> { { "combos", new[] { new[] { 0x11, 0x4C } } } });
|
|
192
|
+
clock.Restart();
|
|
193
|
+
bool addressReady = false;
|
|
194
|
+
while (clock.ElapsedMilliseconds < 1200 && current())
|
|
195
|
+
{
|
|
196
|
+
var blank = read();
|
|
197
|
+
if (blank != null)
|
|
198
|
+
{
|
|
199
|
+
if (Args.Str(blank, "tab", "") != created || Args.Str(blank, "url", "unavailable") != "") break;
|
|
200
|
+
if (Args.Bool(blank, "addressFocused", false)) { addressReady = true; break; }
|
|
201
|
+
}
|
|
202
|
+
Thread.Sleep(65);
|
|
203
|
+
}
|
|
204
|
+
if (!addressReady || !current()) throw new Exception("Could not verify focus in the new tab's address bar");
|
|
205
|
+
Input.Paste(url.AbsoluteUri, true, 120);
|
|
206
|
+
clock.Restart();
|
|
207
|
+
while (clock.ElapsedMilliseconds < 1200 && current())
|
|
208
|
+
{
|
|
209
|
+
var address = read();
|
|
210
|
+
if (address != null)
|
|
211
|
+
{
|
|
212
|
+
if (Args.Str(address, "tab", "") != created || !Args.Bool(address, "addressFocused", false)) break;
|
|
213
|
+
if (Args.Str(address, "url", "") == url.AbsoluteUri && current())
|
|
214
|
+
{
|
|
215
|
+
Input.Keys(new Dictionary<string, object> { { "combos", new[] { new[] { 0x0D } } } });
|
|
216
|
+
return new Dictionary<string, object> { { "tab", created } };
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
Thread.Sleep(65);
|
|
220
|
+
}
|
|
221
|
+
throw new Exception("Could not verify the new tab's address before navigation");
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
public static object BrowserTab(Dictionary<string, object> r)
|
|
225
|
+
{
|
|
226
|
+
IntPtr hwnd = new IntPtr(Convert.ToInt64(r["hwnd"]));
|
|
227
|
+
uint pid = Convert.ToUInt32(r["pid"]);
|
|
228
|
+
string select = Args.Str(r, "select", "");
|
|
229
|
+
if (!SameWindow(hwnd, pid) || !WindowCollectors.Wait(0)) return null;
|
|
230
|
+
var clock = Stopwatch.StartNew();
|
|
231
|
+
Dictionary<string, object> result = null;
|
|
232
|
+
var worker = new Thread(delegate ()
|
|
233
|
+
{
|
|
234
|
+
try
|
|
235
|
+
{
|
|
236
|
+
var root = AutomationElement.FromHandle(hwnd);
|
|
237
|
+
var controls = root.FindAll(TreeScope.Descendants, new OrCondition(
|
|
238
|
+
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit),
|
|
239
|
+
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TabItem)));
|
|
240
|
+
var state = new Dictionary<string, object>();
|
|
241
|
+
var tabs = Args.Bool(r, "listTabs", false) ? new List<string>() : null;
|
|
242
|
+
foreach (AutomationElement el in controls)
|
|
243
|
+
{
|
|
244
|
+
if (el.Current.IsOffscreen && (tabs == null || el.Current.ControlType != ControlType.TabItem)) continue;
|
|
245
|
+
object pattern;
|
|
246
|
+
if (el.Current.ControlType == ControlType.Edit)
|
|
247
|
+
{
|
|
248
|
+
string id = el.Current.AutomationId;
|
|
249
|
+
string name = el.Current.Name;
|
|
250
|
+
if (id != "view_1012" && id != "urlbar-input" && name != "Address and search bar" && name != "地址和搜索栏") continue;
|
|
251
|
+
if (BrowserChrome(el) && el.TryGetCurrentPattern(ValuePattern.Pattern, out pattern))
|
|
252
|
+
{
|
|
253
|
+
state["url"] = ((ValuePattern)pattern).Current.Value;
|
|
254
|
+
state["addressFocused"] = el.Current.HasKeyboardFocus;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
else if (el.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pattern) && BrowserChrome(el))
|
|
258
|
+
{
|
|
259
|
+
var tab = (SelectionItemPattern)pattern;
|
|
260
|
+
string id = String.Join(",", el.GetRuntimeId());
|
|
261
|
+
if (tabs != null) tabs.Add(id);
|
|
262
|
+
if (select.Length > 0 && id == select)
|
|
263
|
+
{
|
|
264
|
+
if (clock.ElapsedMilliseconds < 1200 && SameWindow(hwnd, pid) && Native.GetForegroundWindow() == hwnd)
|
|
265
|
+
{
|
|
266
|
+
if (!tab.Current.IsSelected) tab.Select();
|
|
267
|
+
state["selected"] = true;
|
|
268
|
+
}
|
|
269
|
+
break;
|
|
270
|
+
}
|
|
271
|
+
if (tab.Current.IsSelected) state["tab"] = id;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (tabs != null) state["tabs"] = tabs;
|
|
275
|
+
if (Args.Bool(r, "details", false) && Native.GetForegroundWindow() == hwnd)
|
|
276
|
+
{
|
|
277
|
+
var render = ChromiumRoot(hwnd);
|
|
278
|
+
Native.RECT rect;
|
|
279
|
+
if (render != hwnd && Native.GetWindowRect(render, out rect) && rect.Right > rect.Left && rect.Bottom > rect.Top)
|
|
280
|
+
state["content"] = new Dictionary<string, object> {
|
|
281
|
+
{ "x", rect.Left }, { "y", rect.Top }, { "width", rect.Right - rect.Left }, { "height", rect.Bottom - rect.Top },
|
|
282
|
+
};
|
|
283
|
+
state["contentFocused"] = BrowserContentFocused();
|
|
284
|
+
}
|
|
285
|
+
result = state;
|
|
286
|
+
}
|
|
287
|
+
catch (Exception) { }
|
|
288
|
+
finally { WindowCollectors.Release(); }
|
|
289
|
+
});
|
|
290
|
+
worker.IsBackground = true;
|
|
291
|
+
worker.SetApartmentState(ApartmentState.MTA);
|
|
292
|
+
worker.Start();
|
|
293
|
+
return worker.Join(1250) ? result : null;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
static List<object> CollectWindow(IntPtr hwnd, int max, bool includeText)
|
|
297
|
+
{
|
|
298
|
+
IntPtr render = ChromiumRoot(hwnd);
|
|
299
|
+
if (render == hwnd) return Collect(hwnd, max, includeText);
|
|
300
|
+
WakeAccessibility(render);
|
|
301
|
+
List<object> window = null;
|
|
302
|
+
Exception windowError = null;
|
|
303
|
+
Thread windowWorker = null;
|
|
304
|
+
if (WindowCollectors.Wait(0))
|
|
305
|
+
{
|
|
306
|
+
windowWorker = new Thread(delegate ()
|
|
307
|
+
{
|
|
308
|
+
try { window = Collect(hwnd, max, includeText); }
|
|
309
|
+
catch (Exception ex) { windowError = ex; }
|
|
310
|
+
finally { WindowCollectors.Release(); }
|
|
311
|
+
});
|
|
312
|
+
windowWorker.IsBackground = true;
|
|
313
|
+
windowWorker.SetApartmentState(ApartmentState.MTA);
|
|
314
|
+
windowWorker.Start();
|
|
315
|
+
}
|
|
316
|
+
// Electron can take >16s at the top level while its renderer takes
|
|
317
|
+
// <1s. Read independently; a slow/failed window must not lose DOM controls.
|
|
318
|
+
List<object> content = null;
|
|
319
|
+
Exception contentError = null;
|
|
320
|
+
try { content = Collect(render, max, includeText); }
|
|
321
|
+
catch (Exception ex) { contentError = ex; }
|
|
322
|
+
bool windowReady = windowWorker != null && windowWorker.Join(1000);
|
|
323
|
+
var result = windowReady && window != null ? window : new List<object>();
|
|
324
|
+
if (content == null && result.Count == 0 && contentError != null)
|
|
325
|
+
throw windowReady && windowError != null ? windowError : contentError;
|
|
326
|
+
if (content != null && result.Count < max)
|
|
327
|
+
{
|
|
328
|
+
foreach (Dictionary<string, object> extra in content)
|
|
329
|
+
{
|
|
330
|
+
bool duplicate = false;
|
|
331
|
+
foreach (Dictionary<string, object> item in result)
|
|
332
|
+
if (Equals(item["role"], extra["role"]) && Equals(item["name"], extra["name"])
|
|
333
|
+
&& Equals(item["x"], extra["x"]) && Equals(item["y"], extra["y"])
|
|
334
|
+
&& Equals(item["width"], extra["width"]) && Equals(item["height"], extra["height"]))
|
|
335
|
+
{ duplicate = true; break; }
|
|
336
|
+
if (!duplicate) result.Add(extra);
|
|
337
|
+
if (result.Count >= max) break;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return result;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
public static object Elements(Dictionary<string, object> r)
|
|
344
|
+
{
|
|
345
|
+
IntPtr hwnd = Args.Has(r, "hwnd") ? new IntPtr(Convert.ToInt64(r["hwnd"])) : Native.GetForegroundWindow();
|
|
346
|
+
int max = Args.Int(r, "maxNodes", 150);
|
|
347
|
+
bool all = Args.Bool(r, "includeText", false);
|
|
348
|
+
bool popups = Args.Bool(r, "popups", false);
|
|
349
|
+
bool popupsOnly = Args.Bool(r, "popupsOnly", false);
|
|
350
|
+
List<object> result = null; Exception error = null;
|
|
351
|
+
var worker = new Thread(delegate ()
|
|
352
|
+
{
|
|
353
|
+
try
|
|
354
|
+
{
|
|
355
|
+
if (popupsOnly) result = new List<object>();
|
|
356
|
+
else
|
|
357
|
+
{
|
|
358
|
+
result = CollectWindow(hwnd, max, all);
|
|
359
|
+
if (result.Count < 4) { Thread.Sleep(400); result = CollectWindow(hwnd, max, all); } // Chromium builds its tree lazily
|
|
360
|
+
foreach (Dictionary<string, object> item in result) item["windowHwnd"] = hwnd.ToInt64();
|
|
361
|
+
}
|
|
362
|
+
// An open menu or flyout is a window of its own, not a descendant of the one it belongs to.
|
|
363
|
+
if (popups || popupsOnly) foreach (var extra in Popups(hwnd))
|
|
364
|
+
{
|
|
365
|
+
if (result.Count >= max) break;
|
|
366
|
+
try
|
|
367
|
+
{
|
|
368
|
+
var popup = CollectWindow(extra, max - result.Count, all);
|
|
369
|
+
foreach (Dictionary<string, object> item in popup) item["windowHwnd"] = extra.ToInt64();
|
|
370
|
+
result.AddRange(popup);
|
|
371
|
+
}
|
|
372
|
+
catch (Exception) { }
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
catch (Exception ex) { error = ex; }
|
|
376
|
+
});
|
|
377
|
+
worker.IsBackground = true;
|
|
378
|
+
worker.SetApartmentState(ApartmentState.MTA);
|
|
379
|
+
worker.Start();
|
|
380
|
+
if (!worker.Join(Args.Int(r, "timeoutMs", 8000))) throw new Exception("UI Automation timed out on this window");
|
|
381
|
+
if (error != null) throw error;
|
|
382
|
+
var d = Windows.Describe(hwnd);
|
|
383
|
+
d["elements"] = result;
|
|
384
|
+
return d;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/// <summary>Other visible top-level windows of the same process: menus, flyouts, dropdown lists.</summary>
|
|
388
|
+
static List<IntPtr> Popups(IntPtr hwnd)
|
|
389
|
+
{
|
|
390
|
+
var list = new List<IntPtr>();
|
|
391
|
+
uint owner; Native.GetWindowThreadProcessId(hwnd, out owner);
|
|
392
|
+
Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data)
|
|
393
|
+
{
|
|
394
|
+
if (h == hwnd || !Native.IsWindowVisible(h) || Native.IsIconic(h)) return true;
|
|
395
|
+
uint pid; Native.GetWindowThreadProcessId(h, out pid);
|
|
396
|
+
if (pid == owner && list.Count < 6) list.Add(h);
|
|
397
|
+
return true;
|
|
398
|
+
};
|
|
399
|
+
Native.EnumWindows(cb, IntPtr.Zero);
|
|
400
|
+
GC.KeepAlive(cb);
|
|
401
|
+
return list;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/// <summary>
|
|
405
|
+
/// What a window says, as text: the document or edit control's own text
|
|
406
|
+
/// when it offers one, else its value, else the visible labels in order.
|
|
407
|
+
/// </summary>
|
|
408
|
+
public static object Text(Dictionary<string, object> r)
|
|
409
|
+
{
|
|
410
|
+
IntPtr hwnd = Args.Has(r, "hwnd") ? new IntPtr(Convert.ToInt64(r["hwnd"])) : Native.GetForegroundWindow();
|
|
411
|
+
int tail = Math.Max(200, Math.Min(20000, Args.Int(r, "tail", 4000)));
|
|
412
|
+
string text = ""; string source = "none"; Exception error = null;
|
|
413
|
+
var worker = new Thread(delegate ()
|
|
414
|
+
{
|
|
415
|
+
try { text = Read(hwnd, out source); }
|
|
416
|
+
catch (Exception ex) { error = ex; }
|
|
417
|
+
});
|
|
418
|
+
worker.IsBackground = true;
|
|
419
|
+
worker.SetApartmentState(ApartmentState.MTA);
|
|
420
|
+
worker.Start();
|
|
421
|
+
if (!worker.Join(Args.Int(r, "timeoutMs", 8000))) throw new Exception("UI Automation timed out on this window");
|
|
422
|
+
if (error != null) throw error;
|
|
423
|
+
var d = Windows.Describe(hwnd);
|
|
424
|
+
d["length"] = text.Length;
|
|
425
|
+
d["truncated"] = text.Length > tail;
|
|
426
|
+
d["text"] = text.Length > tail ? text.Substring(text.Length - tail) : text;
|
|
427
|
+
d["source"] = source;
|
|
428
|
+
return d;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const int ReadLimit = 200000;
|
|
432
|
+
|
|
433
|
+
static string Read(IntPtr hwnd, out string source)
|
|
434
|
+
{
|
|
435
|
+
var root = AutomationElement.FromHandle(hwnd);
|
|
436
|
+
var visible = new PropertyCondition(AutomationElement.IsOffscreenProperty, false);
|
|
437
|
+
|
|
438
|
+
// 1. The largest element with a text pattern: an editor's document, a browser's page.
|
|
439
|
+
var withText = root.FindAll(TreeScope.Subtree, new AndCondition(visible, new PropertyCondition(AutomationElement.IsTextPatternAvailableProperty, true)));
|
|
440
|
+
string best = ""; double bestArea = -1;
|
|
441
|
+
int looked = 0;
|
|
442
|
+
foreach (AutomationElement el in withText)
|
|
443
|
+
{
|
|
444
|
+
if (++looked > 40) break;
|
|
445
|
+
try
|
|
446
|
+
{
|
|
447
|
+
var rect = el.Current.BoundingRectangle;
|
|
448
|
+
double area = rect.IsEmpty ? 0 : rect.Width * rect.Height;
|
|
449
|
+
if (area <= bestArea) continue;
|
|
450
|
+
object pattern;
|
|
451
|
+
if (!el.TryGetCurrentPattern(TextPattern.Pattern, out pattern)) continue;
|
|
452
|
+
string got = ((TextPattern)pattern).DocumentRange.GetText(ReadLimit);
|
|
453
|
+
if (got == null || got.Trim().Length == 0) continue;
|
|
454
|
+
best = got; bestArea = area;
|
|
455
|
+
}
|
|
456
|
+
catch (Exception) { }
|
|
457
|
+
}
|
|
458
|
+
if (best.Length > 0) { source = "text"; return best; }
|
|
459
|
+
|
|
460
|
+
// 2. The longest value of an edit or document control.
|
|
461
|
+
var withValue = root.FindAll(TreeScope.Subtree, new AndCondition(visible, new PropertyCondition(AutomationElement.IsValuePatternAvailableProperty, true)));
|
|
462
|
+
looked = 0;
|
|
463
|
+
foreach (AutomationElement el in withValue)
|
|
464
|
+
{
|
|
465
|
+
if (++looked > 200) break;
|
|
466
|
+
try
|
|
467
|
+
{
|
|
468
|
+
if (IsPasswordElement(el)) continue;
|
|
469
|
+
object pattern;
|
|
470
|
+
if (!el.TryGetCurrentPattern(ValuePattern.Pattern, out pattern)) continue;
|
|
471
|
+
string got = ((ValuePattern)pattern).Current.Value;
|
|
472
|
+
if (got != null && got.Length > best.Length) best = got;
|
|
473
|
+
}
|
|
474
|
+
catch (Exception) { }
|
|
475
|
+
}
|
|
476
|
+
if (best.Trim().Length > 0) { source = "value"; return best.Length > ReadLimit ? best.Substring(best.Length - ReadLimit) : best; }
|
|
477
|
+
|
|
478
|
+
// 3. Whatever labels are showing, in tree (reading) order.
|
|
479
|
+
var cache = new CacheRequest();
|
|
480
|
+
cache.Add(AutomationElement.NameProperty);
|
|
481
|
+
cache.AutomationElementMode = AutomationElementMode.None;
|
|
482
|
+
cache.TreeScope = TreeScope.Element;
|
|
483
|
+
AutomationElementCollection labels;
|
|
484
|
+
using (cache.Activate()) { labels = root.FindAll(TreeScope.Descendants, visible); }
|
|
485
|
+
var sb = new StringBuilder();
|
|
486
|
+
string last = null;
|
|
487
|
+
foreach (AutomationElement el in labels)
|
|
488
|
+
{
|
|
489
|
+
string name = el.GetCachedPropertyValue(AutomationElement.NameProperty) as string;
|
|
490
|
+
if (string.IsNullOrEmpty(name) || name == last) continue;
|
|
491
|
+
last = name;
|
|
492
|
+
sb.Append(name).Append('\n');
|
|
493
|
+
if (sb.Length > ReadLimit) break;
|
|
494
|
+
}
|
|
495
|
+
source = sb.Length > 0 ? "labels" : "none";
|
|
496
|
+
return sb.ToString();
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
static bool IsWin32PasswordHwnd(IntPtr h)
|
|
500
|
+
{
|
|
501
|
+
if (h == IntPtr.Zero || !Native.IsWindow(h)) return false;
|
|
502
|
+
var cls = new StringBuilder(64);
|
|
503
|
+
Native.GetClassName(h, cls, cls.Capacity);
|
|
504
|
+
string c = cls.ToString();
|
|
505
|
+
if (c.IndexOf("Edit", StringComparison.OrdinalIgnoreCase) < 0 && c.IndexOf("RichEdit", StringComparison.OrdinalIgnoreCase) < 0)
|
|
506
|
+
return false;
|
|
507
|
+
int style = Native.GetWindowLong(h, -16); // GWL_STYLE
|
|
508
|
+
return (style & 0x0020) != 0; // ES_PASSWORD
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
static bool IsPasswordElement(AutomationElement el)
|
|
512
|
+
{
|
|
513
|
+
if (el == null) return false;
|
|
514
|
+
try
|
|
515
|
+
{
|
|
516
|
+
if (el.Current.IsPassword) return true;
|
|
517
|
+
int nh = el.Current.NativeWindowHandle;
|
|
518
|
+
if (nh != 0 && IsWin32PasswordHwnd(new IntPtr(nh))) return true;
|
|
519
|
+
}
|
|
520
|
+
catch (Exception) { }
|
|
521
|
+
return false;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** Check whether keyboard focus is currently inside a password input (UIA IsPassword or Win32 ES_PASSWORD). */
|
|
525
|
+
public static object PasswordFocus()
|
|
526
|
+
{
|
|
527
|
+
bool isPwd = false;
|
|
528
|
+
string reason = "";
|
|
529
|
+
string name = "";
|
|
530
|
+
try
|
|
531
|
+
{
|
|
532
|
+
IntPtr fg = Native.GetForegroundWindow();
|
|
533
|
+
if (fg != IntPtr.Zero)
|
|
534
|
+
{
|
|
535
|
+
uint pid;
|
|
536
|
+
uint tid = Native.GetWindowThreadProcessId(fg, out pid);
|
|
537
|
+
var gti = new Native.GUITHREADINFO();
|
|
538
|
+
gti.cbSize = Marshal.SizeOf(typeof(Native.GUITHREADINFO));
|
|
539
|
+
if (Native.GetGUIThreadInfo(tid, ref gti) && gti.hwndFocus != IntPtr.Zero && IsWin32PasswordHwnd(gti.hwndFocus))
|
|
540
|
+
{
|
|
541
|
+
isPwd = true;
|
|
542
|
+
reason = "win32_es_password";
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
catch (Exception) { }
|
|
547
|
+
if (!isPwd)
|
|
548
|
+
{
|
|
549
|
+
var worker = new Thread(delegate ()
|
|
550
|
+
{
|
|
551
|
+
try
|
|
552
|
+
{
|
|
553
|
+
var focused = AutomationElement.FocusedElement;
|
|
554
|
+
if (focused != null && IsPasswordElement(focused))
|
|
555
|
+
{
|
|
556
|
+
isPwd = true;
|
|
557
|
+
reason = "uia_is_password";
|
|
558
|
+
name = focused.Current.Name ?? "";
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
catch (Exception) { }
|
|
562
|
+
});
|
|
563
|
+
worker.IsBackground = true;
|
|
564
|
+
worker.SetApartmentState(ApartmentState.MTA);
|
|
565
|
+
worker.Start();
|
|
566
|
+
worker.Join(500);
|
|
567
|
+
}
|
|
568
|
+
var d = new Dictionary<string, object>();
|
|
569
|
+
d["password"] = isPwd;
|
|
570
|
+
d["reason"] = reason;
|
|
571
|
+
d["name"] = name;
|
|
572
|
+
return d;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** Lightweight bounded lookup of the UIA control at physical point (x, y) for user-takeover feedback. */
|
|
576
|
+
public static void DescribeAtPoint(int x, int y, out string role, out string name, out bool isPassword)
|
|
577
|
+
{
|
|
578
|
+
string r = "", n = "";
|
|
579
|
+
bool pwd = false;
|
|
580
|
+
var worker = new Thread(delegate ()
|
|
581
|
+
{
|
|
582
|
+
try
|
|
583
|
+
{
|
|
584
|
+
var el = AutomationElement.FromPoint(new System.Windows.Point(x, y));
|
|
585
|
+
if (el == null) return;
|
|
586
|
+
pwd = IsPasswordElement(el);
|
|
587
|
+
var ct = el.Current.ControlType;
|
|
588
|
+
r = pwd ? "PasswordField" : (ct != null ? ct.ProgrammaticName.Replace("ControlType.", "") : "");
|
|
589
|
+
string raw = pwd ? "" : (el.Current.Name ?? "").Trim();
|
|
590
|
+
n = raw.Length > 60 ? raw.Substring(0, 60) + "…" : raw;
|
|
591
|
+
}
|
|
592
|
+
catch (Exception) { }
|
|
593
|
+
});
|
|
594
|
+
worker.IsBackground = true;
|
|
595
|
+
worker.SetApartmentState(ApartmentState.MTA);
|
|
596
|
+
worker.Start();
|
|
597
|
+
worker.Join(260);
|
|
598
|
+
role = r; name = n; isPassword = pwd;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** Lightweight bounded lookup of the focused UIA control for privacy-safe typing feedback. */
|
|
602
|
+
public static void DescribeFocused(out string role, out string name, out bool isPassword)
|
|
603
|
+
{
|
|
604
|
+
string r = "", n = "";
|
|
605
|
+
bool pwd = false;
|
|
606
|
+
var worker = new Thread(delegate ()
|
|
607
|
+
{
|
|
608
|
+
try
|
|
609
|
+
{
|
|
610
|
+
var el = AutomationElement.FocusedElement;
|
|
611
|
+
if (el == null) return;
|
|
612
|
+
pwd = IsPasswordElement(el);
|
|
613
|
+
var ct = el.Current.ControlType;
|
|
614
|
+
r = pwd ? "PasswordField" : (ct != null ? ct.ProgrammaticName.Replace("ControlType.", "") : "");
|
|
615
|
+
string raw = pwd ? "" : (el.Current.Name ?? "").Trim();
|
|
616
|
+
n = raw.Length > 60 ? raw.Substring(0, 60) + "…" : raw;
|
|
617
|
+
}
|
|
618
|
+
catch (Exception) { }
|
|
619
|
+
});
|
|
620
|
+
worker.IsBackground = true;
|
|
621
|
+
worker.SetApartmentState(ApartmentState.MTA);
|
|
622
|
+
worker.Start();
|
|
623
|
+
worker.Join(240);
|
|
624
|
+
role = r; name = n; isPassword = pwd;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* Try to invoke/toggle/select an enabled native UIA control directly under
|
|
629
|
+
* physical point (x, y) without moving the physical cursor or stealing focus.
|
|
630
|
+
*/
|
|
631
|
+
public static object ClickAtPoint(Dictionary<string, object> r)
|
|
632
|
+
{
|
|
633
|
+
int x = Args.Int(r, "x", 0);
|
|
634
|
+
int y = Args.Int(r, "y", 0);
|
|
635
|
+
long expectedHwnd = Args.Has(r, "hwnd") ? Convert.ToInt64(r["hwnd"]) : 0;
|
|
636
|
+
bool ok = false;
|
|
637
|
+
bool dispatched = false;
|
|
638
|
+
string mechanism = "";
|
|
639
|
+
string role = "";
|
|
640
|
+
string name = "";
|
|
641
|
+
string err = "";
|
|
642
|
+
var worker = new Thread(delegate ()
|
|
643
|
+
{
|
|
644
|
+
try
|
|
645
|
+
{
|
|
646
|
+
var el = AutomationElement.FromPoint(new System.Windows.Point(x, y));
|
|
647
|
+
if (el == null) return;
|
|
648
|
+
if (!el.Current.IsEnabled || IsPasswordElement(el)) return;
|
|
649
|
+
var ct = el.Current.ControlType;
|
|
650
|
+
// Only intercept clearly semantic, single-click invocable controls;
|
|
651
|
+
// never intercept Edit/Document/Pane/Custom/Group where cursor placement matters.
|
|
652
|
+
bool allowed = ct == ControlType.Button || ct == ControlType.CheckBox || ct == ControlType.RadioButton
|
|
653
|
+
|| ct == ControlType.MenuItem || ct == ControlType.TabItem || ct == ControlType.Hyperlink;
|
|
654
|
+
if (!allowed) return;
|
|
655
|
+
if (expectedHwnd != 0)
|
|
656
|
+
{
|
|
657
|
+
int nh = el.Current.NativeWindowHandle;
|
|
658
|
+
IntPtr root = nh != 0 ? Native.GetAncestor(new IntPtr(nh), 2) : IntPtr.Zero;
|
|
659
|
+
if (root != IntPtr.Zero && root.ToInt64() != expectedHwnd) return;
|
|
660
|
+
}
|
|
661
|
+
role = ct.ProgrammaticName.Replace("ControlType.", "");
|
|
662
|
+
name = el.Current.Name ?? "";
|
|
663
|
+
object pat;
|
|
664
|
+
if (el.TryGetCurrentPattern(InvokePattern.Pattern, out pat))
|
|
665
|
+
{
|
|
666
|
+
dispatched = true;
|
|
667
|
+
mechanism = "invoke";
|
|
668
|
+
((InvokePattern)pat).Invoke();
|
|
669
|
+
ok = true;
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
if (el.TryGetCurrentPattern(TogglePattern.Pattern, out pat))
|
|
673
|
+
{
|
|
674
|
+
dispatched = true;
|
|
675
|
+
mechanism = "toggle";
|
|
676
|
+
((TogglePattern)pat).Toggle();
|
|
677
|
+
ok = true;
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
if (el.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pat))
|
|
681
|
+
{
|
|
682
|
+
dispatched = true;
|
|
683
|
+
mechanism = "select";
|
|
684
|
+
((SelectionItemPattern)pat).Select();
|
|
685
|
+
ok = true;
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
catch (Exception e) { err = e.Message ?? "uia_error"; }
|
|
690
|
+
});
|
|
691
|
+
worker.IsBackground = true;
|
|
692
|
+
worker.SetApartmentState(ApartmentState.MTA);
|
|
693
|
+
worker.Start();
|
|
694
|
+
bool joined = worker.Join(900);
|
|
695
|
+
var d = new Dictionary<string, object>();
|
|
696
|
+
d["ok"] = ok;
|
|
697
|
+
d["mechanism"] = mechanism;
|
|
698
|
+
d["role"] = role;
|
|
699
|
+
d["name"] = name;
|
|
700
|
+
// Tri-state guarantee: if Invoke/Toggle/Select was dispatched and then timed out or threw,
|
|
701
|
+
// report uncertain=true so the caller does NOT fall back to a duplicate physical click.
|
|
702
|
+
if (!ok && dispatched && (!joined || err.Length > 0))
|
|
703
|
+
{
|
|
704
|
+
d["uncertain"] = true;
|
|
705
|
+
d["reason"] = !joined ? "uia_invoke_timeout" : err;
|
|
706
|
+
}
|
|
707
|
+
return d;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/**
|
|
711
|
+
* Set-of-Marks annotated screenshot: capture the display, draw crisp numbered
|
|
712
|
+
* badges [1..N] over interactive UIA controls of the target window, and return
|
|
713
|
+
* both the JPEG image and the indexed element list.
|
|
714
|
+
*/
|
|
715
|
+
public static object Marks(Dictionary<string, object> r)
|
|
716
|
+
{
|
|
717
|
+
int sx = Args.Int(r, "x", 0), sy = Args.Int(r, "y", 0);
|
|
718
|
+
int sw = Args.Int(r, "width", 0), sh = Args.Int(r, "height", 0);
|
|
719
|
+
int outW = Args.Int(r, "outWidth", sw), outH = Args.Int(r, "outHeight", sh);
|
|
720
|
+
int quality = Math.Max(30, Math.Min(100, Args.Int(r, "quality", 75)));
|
|
721
|
+
if (sw <= 0 || sh <= 0) throw new Exception("marks needs display width and height");
|
|
722
|
+
var ui = Elements(r) as Dictionary<string, object>;
|
|
723
|
+
var rawElements = ui != null && ui.ContainsKey("elements") ? ui["elements"] as List<object> : new List<object>();
|
|
724
|
+
if (rawElements == null) rawElements = new List<object>();
|
|
725
|
+
|
|
726
|
+
string via;
|
|
727
|
+
using (var rawBmp = Screen2.Grab(sx, sy, sw, sh, out via))
|
|
728
|
+
using (var canvas = new Bitmap(outW, outH, PixelFormat.Format24bppRgb))
|
|
729
|
+
using (var g = Graphics.FromImage(canvas))
|
|
730
|
+
{
|
|
731
|
+
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
|
|
732
|
+
g.SmoothingMode = SmoothingMode.AntiAlias;
|
|
733
|
+
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
|
|
734
|
+
g.DrawImage(rawBmp, 0, 0, outW, outH);
|
|
735
|
+
|
|
736
|
+
double scaleX = (double)outW / sw;
|
|
737
|
+
double scaleY = (double)outH / sh;
|
|
738
|
+
var placed = new List<RectangleF>();
|
|
739
|
+
using (var font = new Font("Microsoft YaHei UI", 10.5f, FontStyle.Bold, GraphicsUnit.Pixel))
|
|
740
|
+
using (var fmt = new StringFormat(StringFormat.GenericTypographic))
|
|
741
|
+
using (var bgBrush = new SolidBrush(Color.FromArgb(228, 217, 119, 87)))
|
|
742
|
+
using (var borderPen = new Pen(Color.FromArgb(245, 255, 255, 255), 1.3f))
|
|
743
|
+
using (var boxPen = new Pen(Color.FromArgb(140, 217, 119, 87), 1.1f))
|
|
744
|
+
{
|
|
745
|
+
fmt.FormatFlags |= StringFormatFlags.NoWrap;
|
|
746
|
+
int drawn = 0;
|
|
747
|
+
for (int i = 0; i < rawElements.Count && drawn < 120; i++)
|
|
748
|
+
{
|
|
749
|
+
var el = rawElements[i] as Dictionary<string, object>;
|
|
750
|
+
if (el == null) continue;
|
|
751
|
+
int ex = Convert.ToInt32(el["x"]), ey = Convert.ToInt32(el["y"]);
|
|
752
|
+
int ew = Convert.ToInt32(el["width"]), eh = Convert.ToInt32(el["height"]);
|
|
753
|
+
float rx = (float)((ex - sx) * scaleX);
|
|
754
|
+
float ry = (float)((ey - sy) * scaleY);
|
|
755
|
+
float rw = (float)(ew * scaleX);
|
|
756
|
+
float rh = (float)(eh * scaleY);
|
|
757
|
+
if (rx + rw < 0 || ry + rh < 0 || rx >= outW || ry >= outH) continue;
|
|
758
|
+
if (rw < 4 || rh < 4) continue;
|
|
759
|
+
el["mark"] = i + 1;
|
|
760
|
+
drawn++;
|
|
761
|
+
if (rw <= outW * 0.85f && rh <= outH * 0.85f)
|
|
762
|
+
g.DrawRectangle(boxPen, rx, ry, rw, rh);
|
|
763
|
+
string tag = (i + 1).ToString();
|
|
764
|
+
SizeF ts = g.MeasureString(tag, font, 1000, fmt);
|
|
765
|
+
float bw = Math.Max(16f, ts.Width + 6f);
|
|
766
|
+
float bh = Math.Max(15f, ts.Height + 2f);
|
|
767
|
+
float bx = Math.Max(1f, Math.Min(outW - bw - 1f, rx));
|
|
768
|
+
float by = Math.Max(1f, Math.Min(outH - bh - 1f, ry - bh * 0.35f));
|
|
769
|
+
var badge = new RectangleF(bx, by, bw, bh);
|
|
770
|
+
for (int attempt = 0; attempt < 3; attempt++)
|
|
771
|
+
{
|
|
772
|
+
bool overlap = false;
|
|
773
|
+
for (int j = 0; j < placed.Count; j++)
|
|
774
|
+
if (placed[j].IntersectsWith(badge)) { overlap = true; break; }
|
|
775
|
+
if (!overlap) break;
|
|
776
|
+
badge.X = Math.Min(outW - bw - 1f, badge.X + bw + 2f);
|
|
777
|
+
}
|
|
778
|
+
placed.Add(badge);
|
|
779
|
+
g.FillRectangle(bgBrush, badge);
|
|
780
|
+
g.DrawRectangle(borderPen, badge.X, badge.Y, badge.Width, badge.Height);
|
|
781
|
+
g.DrawString(tag, font, Brushes.White, badge.X + (badge.Width - ts.Width) / 2f, badge.Y + (badge.Height - ts.Height) / 2f - 0.5f, fmt);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
using (var ms = new MemoryStream())
|
|
786
|
+
{
|
|
787
|
+
ImageCodecInfo jpeg = null;
|
|
788
|
+
foreach (var c in ImageCodecInfo.GetImageEncoders()) if (c.MimeType == "image/jpeg") { jpeg = c; break; }
|
|
789
|
+
if (jpeg != null)
|
|
790
|
+
{
|
|
791
|
+
using (var ep = new EncoderParameters(1))
|
|
792
|
+
{
|
|
793
|
+
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
|
|
794
|
+
canvas.Save(ms, jpeg, ep);
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
else canvas.Save(ms, ImageFormat.Jpeg);
|
|
798
|
+
|
|
799
|
+
var outDict = new Dictionary<string, object>();
|
|
800
|
+
if (ui != null) foreach (var kv in ui) outDict[kv.Key] = kv.Value;
|
|
801
|
+
outDict["data"] = Convert.ToBase64String(ms.ToArray());
|
|
802
|
+
outDict["width"] = outW;
|
|
803
|
+
outDict["height"] = outH;
|
|
804
|
+
outDict["via"] = via;
|
|
805
|
+
return outDict;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
static List<object> Collect(IntPtr hwnd, int max, bool includeText)
|
|
811
|
+
{
|
|
812
|
+
var root = AutomationElement.FromHandle(hwnd);
|
|
813
|
+
var types = new List<Condition>();
|
|
814
|
+
foreach (var t in Interactive) types.Add(new PropertyCondition(AutomationElement.ControlTypeProperty, t));
|
|
815
|
+
if (includeText) types.Add(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text));
|
|
816
|
+
var cond = new AndCondition(new PropertyCondition(AutomationElement.IsOffscreenProperty, false), new OrCondition(types.ToArray()));
|
|
817
|
+
var cache = new CacheRequest();
|
|
818
|
+
cache.Add(AutomationElement.NameProperty);
|
|
819
|
+
cache.Add(AutomationElement.ControlTypeProperty);
|
|
820
|
+
cache.Add(AutomationElement.BoundingRectangleProperty);
|
|
821
|
+
cache.Add(AutomationElement.IsEnabledProperty);
|
|
822
|
+
cache.Add(AutomationElement.AutomationIdProperty);
|
|
823
|
+
cache.Add(AutomationElement.RuntimeIdProperty);
|
|
824
|
+
cache.Add(AutomationElement.ClassNameProperty);
|
|
825
|
+
cache.Add(AutomationElement.IsKeyboardFocusableProperty);
|
|
826
|
+
cache.Add(AutomationElement.IsPasswordProperty);
|
|
827
|
+
cache.Add(AutomationElement.NativeWindowHandleProperty);
|
|
828
|
+
cache.Add(ValuePattern.ValueProperty);
|
|
829
|
+
cache.Add(TogglePattern.ToggleStateProperty);
|
|
830
|
+
cache.AutomationElementMode = AutomationElementMode.None;
|
|
831
|
+
cache.TreeScope = TreeScope.Element;
|
|
832
|
+
AutomationElementCollection found;
|
|
833
|
+
using (cache.Activate()) { found = root.FindAll(TreeScope.Descendants, cond); }
|
|
834
|
+
var list = new List<object>();
|
|
835
|
+
foreach (AutomationElement el in found)
|
|
836
|
+
{
|
|
837
|
+
if (list.Count >= max) break;
|
|
838
|
+
var rect = (System.Windows.Rect)el.GetCachedPropertyValue(AutomationElement.BoundingRectangleProperty);
|
|
839
|
+
if (rect.IsEmpty || rect.Width < 2 || rect.Height < 2) continue;
|
|
840
|
+
var type = (ControlType)el.GetCachedPropertyValue(AutomationElement.ControlTypeProperty);
|
|
841
|
+
string name = (el.GetCachedPropertyValue(AutomationElement.NameProperty) as string) ?? "";
|
|
842
|
+
string cls = (el.GetCachedPropertyValue(AutomationElement.ClassNameProperty) as string) ?? "";
|
|
843
|
+
// Web 编辑器的 contenteditable 常是 Group(ProseMirror/tiptap 等),
|
|
844
|
+
// 不是 Edit;保留这类 Group,其余 Group 跳过,避免淹没按钮。
|
|
845
|
+
if (type == ControlType.Group && !IsEditorClass(cls)) continue;
|
|
846
|
+
bool isPwd = false;
|
|
847
|
+
try
|
|
848
|
+
{
|
|
849
|
+
object pwdProp = el.GetCachedPropertyValue(AutomationElement.IsPasswordProperty, true);
|
|
850
|
+
if (pwdProp is bool && (bool)pwdProp) isPwd = true;
|
|
851
|
+
if (!isPwd)
|
|
852
|
+
{
|
|
853
|
+
object nhProp = el.GetCachedPropertyValue(AutomationElement.NativeWindowHandleProperty, true);
|
|
854
|
+
if (nhProp is int && (int)nhProp != 0 && IsWin32PasswordHwnd(new IntPtr((int)nhProp))) isPwd = true;
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
catch (Exception) { }
|
|
858
|
+
var d = new Dictionary<string, object>();
|
|
859
|
+
d["role"] = type == ControlType.Group ? "Edit" : type.ProgrammaticName.Replace("ControlType.", "");
|
|
860
|
+
if (type == ControlType.Group) d["editable"] = true;
|
|
861
|
+
if (isPwd) d["password"] = true;
|
|
862
|
+
d["name"] = name.Length > 120 ? name.Substring(0, 120) + "…" : name;
|
|
863
|
+
string aid = (el.GetCachedPropertyValue(AutomationElement.AutomationIdProperty) as string) ?? "";
|
|
864
|
+
if (aid.Length > 0) d["automationId"] = aid;
|
|
865
|
+
var runtimeId = el.GetCachedPropertyValue(AutomationElement.RuntimeIdProperty, true) as int[];
|
|
866
|
+
if (runtimeId != null && runtimeId.Length > 0) d["runtimeId"] = String.Join(",", runtimeId);
|
|
867
|
+
d["focusable"] = (bool)el.GetCachedPropertyValue(AutomationElement.IsKeyboardFocusableProperty);
|
|
868
|
+
object value = el.GetCachedPropertyValue(ValuePattern.ValueProperty, true);
|
|
869
|
+
if (isPwd) { d["value"] = "[password]"; }
|
|
870
|
+
else if (value is string && ((string)value).Length > 0) { var v = (string)value; d["value"] = v.Length > 120 ? v.Substring(0, 120) + "…" : v; }
|
|
871
|
+
object toggle = el.GetCachedPropertyValue(TogglePattern.ToggleStateProperty, true);
|
|
872
|
+
if (toggle is ToggleState) d["checked"] = (ToggleState)toggle == ToggleState.On;
|
|
873
|
+
if (!(bool)el.GetCachedPropertyValue(AutomationElement.IsEnabledProperty)) d["disabled"] = true;
|
|
874
|
+
if (type == ControlType.Document && name.Length == 0 && !d.ContainsKey("value")) continue;
|
|
875
|
+
d["x"] = (int)rect.X; d["y"] = (int)rect.Y; d["width"] = (int)rect.Width; d["height"] = (int)rect.Height;
|
|
876
|
+
list.Add(d);
|
|
877
|
+
}
|
|
878
|
+
return list;
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
}
|