@reticlehq/computer 0.0.0-stage → 3.11.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.
Files changed (63) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +12 -0
  3. package/README.md +217 -2
  4. package/bin/attach.mjs +330 -0
  5. package/dist/attach.d.ts +105 -0
  6. package/dist/attach.js +234 -0
  7. package/dist/channels.d.ts +42 -0
  8. package/dist/channels.js +46 -0
  9. package/dist/computer-realm.d.ts +54 -0
  10. package/dist/computer-realm.js +487 -0
  11. package/dist/doctor.d.ts +32 -0
  12. package/dist/doctor.js +42 -0
  13. package/dist/driver.d.ts +227 -0
  14. package/dist/driver.js +73 -0
  15. package/dist/effect.d.ts +60 -0
  16. package/dist/effect.js +158 -0
  17. package/dist/files.d.ts +16 -0
  18. package/dist/files.js +40 -0
  19. package/dist/hud/port.d.ts +44 -0
  20. package/dist/hud/port.js +6 -0
  21. package/dist/index.d.ts +34 -0
  22. package/dist/index.js +22 -0
  23. package/dist/lines.d.ts +34 -0
  24. package/dist/lines.js +80 -0
  25. package/dist/mac/from-ax.d.ts +27 -0
  26. package/dist/mac/from-ax.js +275 -0
  27. package/dist/mac/mac-driver.d.ts +42 -0
  28. package/dist/mac/mac-driver.js +355 -0
  29. package/dist/mac/mac-hud.d.ts +10 -0
  30. package/dist/mac/mac-hud.js +142 -0
  31. package/dist/peer/act-effect.d.ts +9 -0
  32. package/dist/peer/act-effect.js +13 -0
  33. package/dist/peer/commands.d.ts +87 -0
  34. package/dist/peer/commands.js +811 -0
  35. package/dist/peer/form.d.ts +62 -0
  36. package/dist/peer/form.js +103 -0
  37. package/dist/peer/link-switch.d.ts +12 -0
  38. package/dist/peer/link-switch.js +38 -0
  39. package/dist/peer/peer.d.ts +43 -0
  40. package/dist/peer/peer.js +216 -0
  41. package/dist/peer/pointer.d.ts +97 -0
  42. package/dist/peer/pointer.js +289 -0
  43. package/dist/peer/scroll.d.ts +12 -0
  44. package/dist/peer/scroll.js +157 -0
  45. package/dist/peer/seen.d.ts +18 -0
  46. package/dist/peer/seen.js +61 -0
  47. package/dist/peer/select.d.ts +27 -0
  48. package/dist/peer/select.js +78 -0
  49. package/dist/peer/window.d.ts +25 -0
  50. package/dist/peer/window.js +111 -0
  51. package/dist/ui-node.d.ts +93 -0
  52. package/dist/ui-node.js +192 -0
  53. package/dist/win/helper-launch.d.ts +10 -0
  54. package/dist/win/helper-launch.js +34 -0
  55. package/native/linux/Dockerfile +12 -0
  56. package/native/linux/reticle-atspi.py +933 -0
  57. package/native/linux/sandbox.mjs +127 -0
  58. package/native/mac/build/reticle-ax +0 -0
  59. package/native/mac/build/reticle-hud +0 -0
  60. package/native/mac/hud.swift +749 -0
  61. package/native/mac/reticle-ax.swift +1786 -0
  62. package/native/win/reticle-uia.ps1 +620 -0
  63. package/package.json +65 -3
@@ -0,0 +1,620 @@
1
+ # reticle-uia: the Windows helper of the computer realm. It reads an application through UI
2
+ # Automation and acts on it, and it answers in the same shape as the macOS helper (reticle-ax):
3
+ # the same commands, the same JSON, and the roles named as macOS names them (AXButton, AXTextField),
4
+ # so the realm reads both with one reader.
5
+ #
6
+ # powershell -NoProfile -ExecutionPolicy Bypass -File reticle-uia.ps1 serve
7
+ #
8
+ # Each line on standard input is one command as a JSON list of words; each answer is one line.
9
+ # apps
10
+ # tree <pid>
11
+ # reach <pid> <path> <role> <name>
12
+ # act <pid> <path> <role> <name> <kind> <value> <budgetMs> <delivery[:quietMs]> [folder...]
13
+ # capture <pid> <file> [screen]
14
+ #
15
+ # Windows PowerShell 5.1 and PowerShell 7 both run it. It needs no install: UI Automation is part
16
+ # of Windows.
17
+ $ErrorActionPreference = 'Stop'
18
+ # WindowsBase holds System.Windows.Point, which the hit test of the reach check takes.
19
+ Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes, WindowsBase, System.Windows.Forms, System.Drawing
20
+ # The classic controls of Windows (an Edit box, a menu bar, a list view) are described to UI
21
+ # Automation by client-side providers in an assembly of their own. Without it they were plain
22
+ # panes with no value and no children: Notepad's text box had no ref in the first Windows run.
23
+ $script:Providers = 'not loaded'
24
+ foreach ($name in @('UIAutomationClientsideProviders', 'UIAutomationClientSideProviders')) {
25
+ try {
26
+ $loaded = [System.Reflection.Assembly]::Load(
27
+ "$name, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
28
+ [System.Windows.Automation.ClientSettings]::RegisterClientSideProviderAssembly($loaded.GetName())
29
+ $script:Providers = "loaded $($loaded.FullName)"
30
+ break
31
+ } catch {
32
+ # ponytail: a Windows without the assembly still reads the controls that describe themselves.
33
+ $script:Providers = "failed: $($_.Exception.Message)"
34
+ }
35
+ }
36
+ Add-Type -TypeDefinition @'
37
+ using System;
38
+ using System.Runtime.InteropServices;
39
+ public static class ReticleWin32 {
40
+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
41
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
42
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
43
+ [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
44
+ [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
45
+ [DllImport("user32.dll")] public static extern void mouse_event(uint flags, uint x, uint y, int data, UIntPtr extra);
46
+ [DllImport("user32.dll")] public static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
47
+ [DllImport("user32.dll")] public static extern bool GetLastInputInfo(ref LASTINPUTINFO info);
48
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessage(IntPtr h, uint msg, IntPtr w, string l);
49
+ [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr h, uint msg, IntPtr w, IntPtr l);
50
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; }
51
+ [StructLayout(LayoutKind.Sequential)] public struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }
52
+ public static uint IdleMs() {
53
+ LASTINPUTINFO i = new LASTINPUTINFO(); i.cbSize = (uint)Marshal.SizeOf(i);
54
+ GetLastInputInfo(ref i); return (uint)Environment.TickCount - i.dwTime;
55
+ }
56
+ }
57
+ '@
58
+
59
+ # Pictures of a window, made small, and what changed between them. In C#: a loop over the pixels
60
+ # in PowerShell takes seconds.
61
+ Add-Type -ReferencedAssemblies System.Drawing -TypeDefinition @'
62
+ using System;
63
+ using System.Collections;
64
+ using System.Drawing;
65
+ using System.Drawing.Drawing2D;
66
+ using System.Drawing.Imaging;
67
+ using System.Runtime.InteropServices;
68
+ public class ReticlePicture { public byte[] Bytes; public int W; public int H; }
69
+ public static class ReticlePixels {
70
+ const int Width = 240; const int Step = 24;
71
+ public static ReticlePicture Shot(int x, int y, int w, int h) {
72
+ if (w <= 0 || h <= 0) return null;
73
+ using (Bitmap full = new Bitmap(w, h)) {
74
+ using (Graphics g = Graphics.FromImage(full)) g.CopyFromScreen(x, y, 0, 0, full.Size);
75
+ int pw = Math.Min(Width, w); int ph = Math.Max(1, h * pw / w);
76
+ using (Bitmap small = new Bitmap(pw, ph, PixelFormat.Format32bppArgb)) {
77
+ using (Graphics g = Graphics.FromImage(small)) {
78
+ g.InterpolationMode = InterpolationMode.Bilinear; g.DrawImage(full, 0, 0, pw, ph);
79
+ }
80
+ BitmapData data = small.LockBits(new Rectangle(0, 0, pw, ph), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
81
+ byte[] bytes = new byte[pw * ph * 4];
82
+ for (int row = 0; row < ph; row++) Marshal.Copy(data.Scan0 + row * data.Stride, bytes, row * pw * 4, pw * 4);
83
+ small.UnlockBits(data);
84
+ ReticlePicture p = new ReticlePicture(); p.Bytes = bytes; p.W = pw; p.H = ph; return p;
85
+ }
86
+ }
87
+ }
88
+ static bool[] Moved(ReticlePicture a, ReticlePicture b) {
89
+ if (a == null || b == null || a.W != b.W || a.H != b.H) return null;
90
+ bool[] moved = new bool[a.W * a.H];
91
+ for (int p = 0; p < moved.Length; p++)
92
+ for (int c = 0; c < 3; c++) if (Math.Abs(a.Bytes[p * 4 + c] - b.Bytes[p * 4 + c]) > Step) moved[p] = true;
93
+ return moved;
94
+ }
95
+ // What moved between the two pictures of each pair moves by itself (a video, a spinner): it is
96
+ // made a little wider, and left out of the change.
97
+ public static Hashtable Change(ReticlePicture earlier, ReticlePicture before, ReticlePicture after, ReticlePicture later,
98
+ double wx, double wy, double ww, double wh) {
99
+ Hashtable answer = new Hashtable();
100
+ bool[] moved = Moved(before, after);
101
+ if (moved == null) { answer["changed"] = 1.0; answer["box"] = new double[] { wx, wy, ww, wh }; return answer; }
102
+ int w = before.W, h = before.H;
103
+ bool[] mask = new bool[w * h];
104
+ foreach (bool[] self in new bool[][] { Moved(earlier, before), Moved(after, later) }) {
105
+ if (self == null) continue;
106
+ for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) {
107
+ if (!self[y * w + x]) continue;
108
+ for (int yy = Math.Max(0, y - 2); yy <= Math.Min(h - 1, y + 2); yy++)
109
+ for (int xx = Math.Max(0, x - 2); xx <= Math.Min(w - 1, x + 2); xx++) mask[yy * w + xx] = true;
110
+ }
111
+ }
112
+ int count = 0, moving = 0, minX = w, minY = h, maxX = -1, maxY = -1;
113
+ for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) {
114
+ int p = y * w + x;
115
+ if (mask[p]) { moving++; continue; }
116
+ if (!moved[p]) continue;
117
+ count++; minX = Math.Min(minX, x); maxX = Math.Max(maxX, x); minY = Math.Min(minY, y); maxY = Math.Max(maxY, y);
118
+ }
119
+ if (moving > 0) answer["moving"] = Math.Round((double)moving / (w * h), 4);
120
+ answer["changed"] = Math.Round((double)count / (w * h), 4);
121
+ if (count > 0) {
122
+ double sx = ww / w, sy = wh / h;
123
+ answer["box"] = new double[] { Math.Round(wx + minX * sx), Math.Round(wy + minY * sy),
124
+ Math.Round((maxX - minX + 1) * sx), Math.Round((maxY - minY + 1) * sy) };
125
+ }
126
+ return answer;
127
+ }
128
+ }
129
+ '@
130
+
131
+ # The keys a pointer action holds: the names the realm sends, as virtual keys. Meta is Control on
132
+ # Windows, as in Key-Words.
133
+ $VkOf = @{ 'shift' = 0x10; 'control' = 0x11; 'ctrl' = 0x11; 'meta' = 0x11; 'alt' = 0x12; 'option' = 0x12 }
134
+
135
+ $AE = [System.Windows.Automation.AutomationElement]
136
+ $Walker = [System.Windows.Automation.TreeWalker]::ControlViewWalker
137
+ $ReadLimit = 20000
138
+ $ShortList = 200
139
+ $QuietMs = 150
140
+
141
+ # UI Automation control types, named as macOS names them.
142
+ $RoleOf = @{
143
+ 'ControlType.Window' = 'AXWindow'; 'ControlType.Button' = 'AXButton'; 'ControlType.SplitButton' = 'AXMenuButton'
144
+ 'ControlType.Edit' = 'AXTextField'; 'ControlType.Document' = 'AXTextArea'; 'ControlType.Text' = 'AXStaticText'
145
+ 'ControlType.CheckBox' = 'AXCheckBox'; 'ControlType.RadioButton' = 'AXRadioButton'; 'ControlType.ComboBox' = 'AXComboBox'
146
+ 'ControlType.List' = 'AXList'; 'ControlType.ListItem' = 'AXRow'; 'ControlType.DataGrid' = 'AXTable'
147
+ 'ControlType.DataItem' = 'AXRow'; 'ControlType.Table' = 'AXTable'; 'ControlType.Tree' = 'AXOutline'
148
+ 'ControlType.TreeItem' = 'AXRow'; 'ControlType.Menu' = 'AXMenu'; 'ControlType.MenuBar' = 'AXMenuBar'
149
+ 'ControlType.MenuItem' = 'AXMenuItem'; 'ControlType.Tab' = 'AXTabGroup'; 'ControlType.TabItem' = 'AXRadioButton'
150
+ 'ControlType.Hyperlink' = 'AXLink'; 'ControlType.Image' = 'AXImage'; 'ControlType.Slider' = 'AXSlider'
151
+ 'ControlType.ScrollBar' = 'AXScrollBar'; 'ControlType.ProgressBar' = 'AXProgressIndicator'
152
+ 'ControlType.ToolBar' = 'AXToolbar'; 'ControlType.Group' = 'AXGroup'; 'ControlType.Pane' = 'AXGroup'
153
+ 'ControlType.Custom' = 'AXGroup'; 'ControlType.StatusBar' = 'AXGroup'; 'ControlType.TitleBar' = 'AXGroup'
154
+ 'ControlType.Header' = 'AXGroup'; 'ControlType.HeaderItem' = 'AXButton'; 'ControlType.Separator' = 'AXSplitter'
155
+ 'ControlType.Spinner' = 'AXIncrementor'; 'ControlType.Calendar' = 'AXGroup'; 'ControlType.ToolTip' = 'AXGroup'
156
+ 'ControlType.Thumb' = 'AXValueIndicator'
157
+ }
158
+
159
+ function Write-Answer($value) {
160
+ [Console]::Out.WriteLine(($value | ConvertTo-Json -Depth 100 -Compress))
161
+ [Console]::Out.Flush()
162
+ }
163
+
164
+ function Get-Pattern($el, $pattern) {
165
+ $found = $null
166
+ if ($el.TryGetCurrentPattern($pattern, [ref]$found)) { return $found }
167
+ return $null
168
+ }
169
+
170
+ # The top windows of a process, in the order the read gives them. A window that is made small is
171
+ # counted and not read: it is not on the screen, as on macOS.
172
+ function Get-Windows([int]$procId) {
173
+ $condition = New-Object System.Windows.Automation.PropertyCondition($AE::ProcessIdProperty, $procId)
174
+ $all = $AE::RootElement.FindAll([System.Windows.Automation.TreeScope]::Children, $condition)
175
+ $shown = @(); $away = 0
176
+ foreach ($w in $all) {
177
+ $state = Get-Pattern $w ([System.Windows.Automation.WindowPattern]::Pattern)
178
+ if ($null -ne $state -and $state.Current.WindowVisualState -eq 'Minimized') { $away += 1; continue }
179
+ $shown += $w
180
+ }
181
+ return @{ shown = $shown; away = $away }
182
+ }
183
+
184
+ function Get-Children($el) {
185
+ $kids = @()
186
+ $child = $Walker.GetFirstChild($el)
187
+ while ($null -ne $child) { $kids += $child; $child = $Walker.GetNextSibling($child) }
188
+ return $kids
189
+ }
190
+
191
+ $script:Budget = $ReadLimit
192
+ function Read-Node($el, [int]$depth, [ref]$unread) {
193
+ try { $c = $el.Current } catch { $unread.Value += 1; return @{ role = ''; children = @() } }
194
+ $role = $RoleOf[$c.ControlType.ProgrammaticName]
195
+ if ($null -eq $role) { $role = 'AXUnknown' }
196
+ $node = [ordered]@{ role = $role }
197
+ # What UI Automation said, for a check that has to see why an element is read as it is.
198
+ if ($env:RETICLE_UIA_DEBUG) {
199
+ $raw = 0; $r = [System.Windows.Automation.TreeWalker]::RawViewWalker.GetFirstChild($el)
200
+ while ($null -ne $r) { $raw += 1; $r = [System.Windows.Automation.TreeWalker]::RawViewWalker.GetNextSibling($r) }
201
+ $node.uia = "$($c.ControlType.ProgrammaticName) $($c.ClassName) kids:$((Get-Children $el).Count) raw:$raw"
202
+ }
203
+ if ($c.Name) { $node.title = $c.Name }
204
+ if ($c.HelpText) { $node.help = $c.HelpText }
205
+ if ($c.AutomationId) { $node.id = $c.AutomationId }
206
+ $node.enabled = $c.IsEnabled
207
+ $node.focused = $c.HasKeyboardFocus
208
+ $r = $c.BoundingRectangle
209
+ if (-not $r.IsEmpty -and -not [double]::IsInfinity($r.X)) { $node.frame = @($r.X, $r.Y, $r.Width, $r.Height) }
210
+ $toggle = Get-Pattern $el ([System.Windows.Automation.TogglePattern]::Pattern)
211
+ $value = Get-Pattern $el ([System.Windows.Automation.ValuePattern]::Pattern)
212
+ $range = Get-Pattern $el ([System.Windows.Automation.RangeValuePattern]::Pattern)
213
+ if ($null -ne $toggle) { $node.value = $(if ($toggle.Current.ToggleState -eq 'On') { '1' } else { '0' }) }
214
+ elseif ($null -ne $value) { $node.value = [string]$value.Current.Value }
215
+ elseif ($null -ne $range) { $node.value = [string]$range.Current.Value }
216
+ elseif (@('AXTextField', 'AXTextArea') -contains $role) {
217
+ # A multi-line Edit box (the text of Notepad) has no value pattern: its text is in the text
218
+ # pattern. Without it the realm read the box as empty after it wrote to it.
219
+ $text = Get-Pattern $el ([System.Windows.Automation.TextPattern]::Pattern)
220
+ if ($null -ne $text) { try { $node.value = [string]$text.DocumentRange.GetText(4000) } catch { } }
221
+ }
222
+ $pick = Get-Pattern $el ([System.Windows.Automation.SelectionItemPattern]::Pattern)
223
+ if ($null -ne $pick -and $pick.Current.IsSelected) { $node.selected = $true }
224
+ $kids = @()
225
+ if ($depth -lt 80) { $kids = Get-Children $el }
226
+ # A long list gives the items on the screen, with their places, and says how many it left out.
227
+ $places = $null
228
+ if ($kids.Count -gt $ShortList -and @('AXList', 'AXTable', 'AXOutline') -contains $role) {
229
+ $places = @(); $shown = @()
230
+ for ($k = 0; $k -lt $kids.Count; $k++) {
231
+ try { if (-not $kids[$k].Current.IsOffscreen) { $places += $k; $shown += $kids[$k] } } catch { }
232
+ }
233
+ $node.notShown = $kids.Count - $shown.Count
234
+ $kids = $shown
235
+ }
236
+ if ($script:Budget -le 0 -and $kids.Count -gt 0) {
237
+ $node.notShown = [int]$node.notShown + $kids.Count
238
+ $node.children = @()
239
+ return $node
240
+ }
241
+ $script:Budget -= $kids.Count
242
+ $children = @()
243
+ for ($k = 0; $k -lt $kids.Count; $k++) {
244
+ $one = Read-Node $kids[$k] ($depth + 1) $unread
245
+ if ($null -ne $places) { $one.i = $places[$k] }
246
+ $children += , $one
247
+ }
248
+ $node.children = $children
249
+ return $node
250
+ }
251
+
252
+ function Read-App([int]$procId) {
253
+ $script:Budget = $ReadLimit
254
+ $unread = 0
255
+ $proc = Get-Process -Id $procId -ErrorAction SilentlyContinue
256
+ if ($null -eq $proc) { return $null }
257
+ $windows = Get-Windows $procId
258
+ $children = @()
259
+ foreach ($w in $windows.shown) { $children += , (Read-Node $w 1 ([ref]$unread)) }
260
+ return @{
261
+ tree = [ordered]@{ role = 'AXApplication'; title = $proc.ProcessName; children = $children; uia = $(if ($env:RETICLE_UIA_DEBUG) { "providers: $script:Providers" } else { $null }) }
262
+ unread = $unread
263
+ windowsNotOnScreen = $windows.away
264
+ }
265
+ }
266
+
267
+ # The element at a path of child places, from the application: the first place is a window.
268
+ function Find-Element([int]$procId, [string]$path) {
269
+ $places = @($path.Split('.') | Where-Object { $_ -ne '' } | ForEach-Object { [int]$_ })
270
+ if ($places.Count -eq 0) { return @{ app = $true } }
271
+ $windows = (Get-Windows $procId).shown
272
+ if ($places[0] -ge $windows.Count) { return $null }
273
+ $el = $windows[$places[0]]
274
+ for ($k = 1; $k -lt $places.Count; $k++) {
275
+ $kids = Get-Children $el
276
+ if ($places[$k] -ge $kids.Count) { return $null }
277
+ $el = $kids[$places[$k]]
278
+ }
279
+ return @{ el = $el }
280
+ }
281
+
282
+ function Name-Of($el) { try { return [string]$el.Current.Name } catch { return '' } }
283
+
284
+ # Can a person click the element: is it the element at its middle, or inside it?
285
+ function Test-Reach($el) {
286
+ $r = $el.Current.BoundingRectangle
287
+ if ($r.IsEmpty) { return @{ reach = 'unknown'; detail = 'the element has no place on the screen' } }
288
+ $point = New-Object System.Windows.Point(($r.X + $r.Width / 2), ($r.Y + $r.Height / 2))
289
+ try { $hit = $AE::FromPoint($point) } catch { return @{ reach = 'unknown'; detail = 'the hit test failed' } }
290
+ $at = $hit
291
+ for ($k = 0; $k -lt 8 -and $null -ne $at; $k++) {
292
+ if ([System.Windows.Automation.Automation]::Compare($at, $el)) { return @{ reach = 'yes' } }
293
+ $at = $Walker.GetParent($at)
294
+ }
295
+ $owner = ''
296
+ try { $owner = (Get-Process -Id $hit.Current.ProcessId).ProcessName } catch { }
297
+ return @{ reach = 'no'; detail = "a $($RoleOf[$hit.Current.ControlType.ProgrammaticName]) of $owner" }
298
+ }
299
+
300
+ function Wait-Quiet([int]$procId, [int]$budgetMs, [int]$quietMs) {
301
+ $started = [DateTime]::UtcNow
302
+ $last = (Read-App $procId | ConvertTo-Json -Depth 100 -Compress)
303
+ $quietSince = [DateTime]::UtcNow
304
+ while (([DateTime]::UtcNow - $started).TotalMilliseconds -lt $budgetMs) {
305
+ Start-Sleep -Milliseconds 50
306
+ $now = (Read-App $procId | ConvertTo-Json -Depth 100 -Compress)
307
+ if ($now -ne $last) { $last = $now; $quietSince = [DateTime]::UtcNow; continue }
308
+ if (([DateTime]::UtcNow - $quietSince).TotalMilliseconds -ge $quietMs) { return $true }
309
+ }
310
+ return $false
311
+ }
312
+
313
+ function Send-Click([int]$x, [int]$y, [int]$times, [bool]$right, [int]$holdMs = 0, [bool]$middle = $false) {
314
+ [ReticleWin32]::SetCursorPos($x, $y) | Out-Null
315
+ $down = $(if ($right) { 0x0008 } elseif ($middle) { 0x0020 } else { 0x0002 })
316
+ $up = $(if ($right) { 0x0010 } elseif ($middle) { 0x0040 } else { 0x0004 })
317
+ for ($k = 0; $k -lt $times; $k++) {
318
+ [ReticleWin32]::mouse_event($down, 0, 0, 0, [UIntPtr]::Zero)
319
+ if ($holdMs -gt 0) { Start-Sleep -Milliseconds $holdMs }
320
+ [ReticleWin32]::mouse_event($up, 0, 0, 0, [UIntPtr]::Zero)
321
+ }
322
+ }
323
+
324
+ # SendKeys words for the key names the realm uses.
325
+ $KeyOf = @{ 'return' = '{ENTER}'; 'enter' = '{ENTER}'; 'escape' = '{ESC}'; 'tab' = '{TAB}'; 'backspace' = '{BACKSPACE}'
326
+ 'delete' = '{DELETE}'; 'arrowup' = '{UP}'; 'arrowdown' = '{DOWN}'; 'arrowleft' = '{LEFT}'; 'arrowright' = '{RIGHT}'
327
+ 'home' = '{HOME}'; 'end' = '{END}'; 'pageup' = '{PGUP}'; 'pagedown' = '{PGDN}'; 'space' = ' ' }
328
+ function Key-Words([string]$value) {
329
+ $parts = $value.Split('+'); $key = $parts[-1]; $mods = ''
330
+ foreach ($m in $parts[0..($parts.Count - 2)]) {
331
+ switch ($m.ToLower()) { 'control' { $mods += '^' } 'meta' { $mods += '^' } 'shift' { $mods += '+' } 'alt' { $mods += '%' } }
332
+ }
333
+ if ($parts.Count -eq 1) { $mods = '' }
334
+ $word = $KeyOf[$key.ToLower()]
335
+ if ($null -eq $word) { $word = $(if ($key.Length -eq 1) { $key } else { "{$($key.ToUpper())}" }) }
336
+ return $mods + $word
337
+ }
338
+
339
+ # The virtual keys of the key names the realm uses, for a key in the background.
340
+ $VkOfKey = @{ 'return' = 0x0D; 'enter' = 0x0D; 'escape' = 0x1B; 'tab' = 0x09; 'backspace' = 0x08; 'delete' = 0x2E
341
+ 'arrowup' = 0x26; 'arrowdown' = 0x28; 'arrowleft' = 0x25; 'arrowright' = 0x27; 'home' = 0x24; 'end' = 0x23
342
+ 'pageup' = 0x21; 'pagedown' = 0x22; 'space' = 0x20 }
343
+ # A key in the background: posted to the window of the control alone, as its own messages. The
344
+ # pointer and the keyboard of the person are not used, and the window does not come to the front.
345
+ # ponytail: one key with no modifier. A modifier is in the state of the keyboard, which a message
346
+ # does not carry; a key with one is not delivered.
347
+ function Send-KeyToWindow($el, [string]$value) {
348
+ $parts = $value.Split('+')
349
+ if ($parts.Count -gt 1) { return $false }
350
+ $name = $parts[0].ToLower()
351
+ $vk = $VkOfKey[$name]
352
+ if ($null -eq $vk -and $name -match '^f([1-9]|1[0-2])$') { $vk = 0x6F + [int]$Matches[1] }
353
+ if ($null -eq $vk -and $name.Length -eq 1) { $vk = [int][char]$name.ToUpper() }
354
+ if ($null -eq $vk) { return $false }
355
+ $at = $el
356
+ while ($null -ne $at -and $at.Current.NativeWindowHandle -eq 0) { $at = $Walker.GetParent($at) }
357
+ if ($null -eq $at) { return $false }
358
+ $handle = [IntPtr]$at.Current.NativeWindowHandle
359
+ [ReticleWin32]::PostMessage($handle, 0x0100, [IntPtr]$vk, [IntPtr]1) | Out-Null
360
+ [ReticleWin32]::PostMessage($handle, 0x0101, [IntPtr]$vk, [IntPtr]0xC0000001L) | Out-Null
361
+ return $true
362
+ }
363
+
364
+ function Invoke-Act($words) {
365
+ $procId = [int]$words[1]; $path = $words[2]; $role = $words[3]; $name = $words[4]; $kind = $words[5]
366
+ $value = $words[6]; $budgetMs = [int]$words[7]; $how = $words[8].Split(':')
367
+ $quiet = $(if ($how.Count -gt 1) { [int]$how[1] } else { $QuietMs })
368
+ $foreground = $how[0] -eq 'foreground'; $direct = $how[0] -eq 'direct'
369
+ if ($null -eq (Get-Process -Id $procId -ErrorAction SilentlyContinue)) { return @{ error = 'app-gone' } }
370
+ $found = Find-Element $procId $path
371
+ if ($null -eq $found) { return @{ refused = 'stale'; detail = 'no element at the path' } }
372
+ $el = $found.el
373
+ if ($null -ne $el) {
374
+ $nowRole = $RoleOf[$el.Current.ControlType.ProgrammaticName]
375
+ if ($nowRole -ne $role -or (Name-Of $el) -ne $name) { return @{ refused = 'stale'; detail = 'a different element is at the path' } }
376
+ if (-not $el.Current.IsEnabled -and $kind -ne 'raise') { return @{ refused = 'disabled' } }
377
+ }
378
+ $pointer = @('click', 'dblclick', 'rightclick', 'hover', 'drag', 'wheel') -contains $kind
379
+ if ($pointer -and -not $foreground) { return @{ refused = 'needs-foreground' } }
380
+ # A pointer value is its points, then the hand: "x,y|mods=shift+alt|hold=300|pixels=1".
381
+ $hand = @{}
382
+ if ($pointer) {
383
+ $parts = "$value".Split('|'); $value = $parts[0]
384
+ foreach ($part in $parts | Select-Object -Skip 1) {
385
+ $pair = $part.Split('=', 2); if ($pair.Count -eq 2) { $hand[$pair[0]] = $pair[1] }
386
+ }
387
+ }
388
+ $mods = @(("$($hand['mods'])").Split('+') | ForEach-Object { $VkOf[$_.ToLower()] } | Where-Object { $null -ne $_ })
389
+ $holdMs = [Math]::Min(10000, [Math]::Max(0, [int]("0$($hand['hold'])")))
390
+ if ($foreground -and [ReticleWin32]::IdleMs() -lt 800) {
391
+ Start-Sleep -Milliseconds 800
392
+ if ([ReticleWin32]::IdleMs() -lt 800) { return @{ refused = 'person-active'; detail = 'the person at the machine is typing or moving the pointer' } }
393
+ }
394
+ $reach = $(if ($null -ne $el) { Test-Reach $el } else { @{ reach = 'yes' } })
395
+ if ($reach.reach -ne 'yes' -and -not $direct -and $kind -ne 'raise' -and $kind -ne 'window') {
396
+ if ($reach.reach -eq 'no') { return @{ refused = 'unreachable'; detail = $reach.detail } }
397
+ return @{ refused = 'reach-unknown'; detail = $reach.detail }
398
+ }
399
+ $before = Read-App $procId
400
+ # A canvas shows its effect only in pixels: two pictures of the window before the action, a
401
+ # moment apart, so what moves by itself is known. Only when the realm asks (a point of a picture,
402
+ # an image, a window): a button shows its effect in its elements.
403
+ $shots = $null
404
+ if ($pointer -and $kind -ne 'hover' -and $hand['pixels'] -eq '1') {
405
+ $top = (Get-Windows $procId).shown
406
+ if ($top.Count -gt 0) {
407
+ $wr = $top[0].Current.BoundingRectangle
408
+ $shots = @{ rect = $wr; earlier = [ReticlePixels]::Shot([int]$wr.X, [int]$wr.Y, [int]$wr.Width, [int]$wr.Height) }
409
+ Start-Sleep -Milliseconds 100
410
+ $shots.before = [ReticlePixels]::Shot([int]$wr.X, [int]$wr.Y, [int]$wr.Width, [int]$wr.Height)
411
+ }
412
+ }
413
+ foreach ($vk in $mods) { [ReticleWin32]::keybd_event([byte]$vk, 0, 0, [UIntPtr]::Zero) }
414
+ $delivered = $true
415
+ $arranged = $null
416
+ try {
417
+ switch ($kind) {
418
+ 'press' {
419
+ $invoke = Get-Pattern $el ([System.Windows.Automation.InvokePattern]::Pattern)
420
+ $toggle = Get-Pattern $el ([System.Windows.Automation.TogglePattern]::Pattern)
421
+ $pick = Get-Pattern $el ([System.Windows.Automation.SelectionItemPattern]::Pattern)
422
+ $expand = Get-Pattern $el ([System.Windows.Automation.ExpandCollapsePattern]::Pattern)
423
+ if ($null -ne $invoke) { $invoke.Invoke() }
424
+ elseif ($null -ne $toggle) { $toggle.Toggle() }
425
+ elseif ($null -ne $pick) { $pick.Select() }
426
+ elseif ($null -ne $expand) { if ($expand.Current.ExpandCollapseState -eq 'Collapsed') { $expand.Expand() } else { $expand.Collapse() } }
427
+ else {
428
+ # The words of a row: the row or the item that holds them is chosen, as a click chooses it.
429
+ $up = $Walker.GetParent($el); $done = $false
430
+ for ($k = 0; $k -lt 4 -and $null -ne $up -and -not $done; $k++) {
431
+ $holder = Get-Pattern $up ([System.Windows.Automation.SelectionItemPattern]::Pattern)
432
+ if ($null -ne $holder) { $holder.Select(); $done = $true }
433
+ $up = $Walker.GetParent($up)
434
+ }
435
+ $delivered = $done
436
+ }
437
+ }
438
+ 'set' {
439
+ $valuePattern = Get-Pattern $el ([System.Windows.Automation.ValuePattern]::Pattern)
440
+ $range = Get-Pattern $el ([System.Windows.Automation.RangeValuePattern]::Pattern)
441
+ $set = $false
442
+ try {
443
+ if ($null -ne $range -and $value -match '^-?[\d.]+$') { $range.SetValue([double]$value); $set = $true }
444
+ elseif ($null -ne $valuePattern) { $valuePattern.SetValue($value); $set = $true }
445
+ } catch {
446
+ $script:LastError = $_.Exception.Message
447
+ }
448
+ # UI Automation refuses a value for a multi-line Edit box (the text of Notepad). The control
449
+ # of Windows takes its text from WM_SETTEXT, also in the background, as it took it before
450
+ # UI Automation existed.
451
+ $handle = $el.Current.NativeWindowHandle
452
+ if (-not $set -and $handle -ne 0) {
453
+ [ReticleWin32]::SendMessage([IntPtr]$handle, 0x000C, [IntPtr]::Zero, $value) | Out-Null
454
+ $set = $true
455
+ }
456
+ $delivered = $set
457
+ }
458
+ 'raise' {
459
+ $proc = Get-Process -Id $procId
460
+ if ($proc.MainWindowHandle -ne [IntPtr]::Zero) { [ReticleWin32]::SetForegroundWindow($proc.MainWindowHandle) | Out-Null }
461
+ if ($null -ne $el) { try { $el.SetFocus() } catch { } }
462
+ }
463
+ { $_ -eq 'type' -or $_ -eq 'key' } {
464
+ $front = [IntPtr]::Zero; [uint32]$owner = 0
465
+ $front = [ReticleWin32]::GetForegroundWindow(); [ReticleWin32]::GetWindowThreadProcessId($front, [ref]$owner) | Out-Null
466
+ if (-not $foreground) {
467
+ # Text in the background goes to a field as its value. A key goes to the window of the control.
468
+ if ($kind -eq 'type') { (Get-Pattern $el ([System.Windows.Automation.ValuePattern]::Pattern)).SetValue($value) }
469
+ else { $delivered = Send-KeyToWindow $el $value }
470
+ } elseif ($owner -ne $procId) { return @{ refused = 'no-keyboard' } }
471
+ elseif ($kind -eq 'type') { [System.Windows.Forms.SendKeys]::SendWait(($value -replace '([+^%~(){}\[\]])', '{$1}')) }
472
+ else { [System.Windows.Forms.SendKeys]::SendWait((Key-Words $value)) }
473
+ }
474
+ { @('click', 'dblclick', 'rightclick', 'hover') -contains $_ } {
475
+ $r = $el.Current.BoundingRectangle
476
+ $xy = $value.Split(',') | Where-Object { $_ -ne '' }
477
+ $x = $(if ($xy.Count -ge 2) { [int][double]$xy[0] } else { [int]($r.X + $r.Width / 2) })
478
+ $y = $(if ($xy.Count -ge 2) { [int][double]$xy[1] } else { [int]($r.Y + $r.Height / 2) })
479
+ if ($kind -eq 'hover') { [ReticleWin32]::SetCursorPos($x, $y) | Out-Null }
480
+ else {
481
+ # "count=3" is a triple-click, "button=middle" the middle button.
482
+ $times = $(if ($kind -eq 'dblclick') { 2 } else { [Math]::Min(3, [Math]::Max(1, [int]("0$($hand['count'])"))) })
483
+ Send-Click $x $y $times ($kind -eq 'rightclick') $holdMs ($hand['button'] -eq 'middle')
484
+ }
485
+ }
486
+ 'drag' {
487
+ # Two numbers: the end, from the middle of the element. Four or more: a path, from its first
488
+ # point. The pointer walks each part in small steps, as a hand moves.
489
+ $n = @("$value".Split(',') | Where-Object { $_ -ne '' } | ForEach-Object { [double]$_ })
490
+ $r = $el.Current.BoundingRectangle
491
+ $way = [System.Collections.ArrayList]::new()
492
+ if ($n.Count -eq 2) { [void]$way.Add(@(($r.X + $r.Width / 2), ($r.Y + $r.Height / 2))) }
493
+ for ($k = 0; $k + 1 -lt $n.Count; $k += 2) { [void]$way.Add(@($n[$k], $n[$k + 1])) }
494
+ if ($way.Count -lt 2) { return @{ error = 'a drag needs an end' } }
495
+ [ReticleWin32]::SetCursorPos([int]$way[0][0], [int]$way[0][1]) | Out-Null
496
+ [ReticleWin32]::mouse_event(0x0002, 0, 0, 0, [UIntPtr]::Zero)
497
+ if ($holdMs -gt 0) { Start-Sleep -Milliseconds $holdMs }
498
+ for ($k = 1; $k -lt $way.Count; $k++) {
499
+ $a = $way[$k - 1]; $b = $way[$k]
500
+ $steps = [Math]::Max(4, [Math]::Min(40, [int]([Math]::Sqrt([Math]::Pow($b[0] - $a[0], 2) + [Math]::Pow($b[1] - $a[1], 2)) / 6)))
501
+ for ($s = 1; $s -le $steps; $s++) {
502
+ [ReticleWin32]::SetCursorPos([int]($a[0] + ($b[0] - $a[0]) * $s / $steps), [int]($a[1] + ($b[1] - $a[1]) * $s / $steps)) | Out-Null
503
+ Start-Sleep -Milliseconds 8
504
+ }
505
+ }
506
+ [ReticleWin32]::mouse_event(0x0004, 0, 0, 0, [UIntPtr]::Zero)
507
+ }
508
+ 'wheel' {
509
+ $n = $value.Split(','); $r = $el.Current.BoundingRectangle
510
+ $x = $(if ($n.Count -ge 3) { [int][double]$n[1] } else { [int]($r.X + $r.Width / 2) })
511
+ $y = $(if ($n.Count -ge 3) { [int][double]$n[2] } else { [int]($r.Y + $r.Height / 2) })
512
+ [ReticleWin32]::SetCursorPos($x, $y) | Out-Null
513
+ if ([double]$n[0] -ne 0) { [ReticleWin32]::mouse_event(0x0800, 0, 0, -120 * [int][Math]::Ceiling([double]$n[0] / 3), [UIntPtr]::Zero) }
514
+ # "across=5" turns the wheel to the side: more than 0 is to the right.
515
+ $across = [int]("0$($hand['across'])".Replace('0-', '-'))
516
+ if ($across -ne 0) { [ReticleWin32]::mouse_event(0x01000, 0, 0, 120 * [Math]::Sign($across) * [int][Math]::Ceiling([Math]::Abs($across) / 3), [UIntPtr]::Zero) }
517
+ }
518
+ 'window' {
519
+ $top = $el
520
+ while ($null -ne $top -and $top.Current.ControlType.ProgrammaticName -ne 'ControlType.Window') { $top = $Walker.GetParent($top) }
521
+ $win = Get-Pattern $top ([System.Windows.Automation.WindowPattern]::Pattern)
522
+ $move = Get-Pattern $top ([System.Windows.Automation.TransformPattern]::Pattern)
523
+ $arranged = @{ top = $top; win = $win }
524
+ switch -Regex ($value) {
525
+ '^minimize$' { $win.SetWindowVisualState('Minimized') }
526
+ '^(zoom|fullscreen)$' { $win.SetWindowVisualState('Maximized') }
527
+ '^restore$' { $win.SetWindowVisualState('Normal') }
528
+ '^(left|right)$' {
529
+ $area = [System.Windows.Forms.Screen]::FromPoint([System.Drawing.Point]::new([int]$top.Current.BoundingRectangle.X, [int]$top.Current.BoundingRectangle.Y)).WorkingArea
530
+ $win.SetWindowVisualState('Normal'); $half = $area.Width / 2
531
+ $move.Move($(if ($value -eq 'left') { $area.X } else { $area.X + $half }), $area.Y); $move.Resize($half, $area.Height)
532
+ }
533
+ '^frame:' { $f = $value.Substring(6).Split(','); $win.SetWindowVisualState('Normal'); $move.Move([double]$f[0], [double]$f[1]); $move.Resize([double]$f[2], [double]$f[3]) }
534
+ }
535
+ }
536
+ default { return @{ error = "unknown-action $kind" } }
537
+ }
538
+ } catch {
539
+ $script:LastError = $_.Exception.Message
540
+ $delivered = $false
541
+ } finally {
542
+ foreach ($vk in $mods) { [ReticleWin32]::keybd_event([byte]$vk, 0, 2, [UIntPtr]::Zero) }
543
+ }
544
+ $settled = Wait-Quiet $procId $budgetMs $quiet
545
+ $after = Read-App $procId
546
+ # The window, read again after an arrangement: the answer of the system to the set is not the
547
+ # proof that it moved. The realm refuses an arrangement with no state.
548
+ $windowState = $null
549
+ if ($null -ne $arranged) {
550
+ $wr = $arranged.top.Current.BoundingRectangle
551
+ $windowState = @{ minimized = ($null -ne $arranged.win -and $arranged.win.Current.WindowVisualState -eq 'Minimized'); fullscreen = $false }
552
+ if (-not $wr.IsEmpty) { $windowState.frame = @($wr.X, $wr.Y, $wr.Width, $wr.Height) }
553
+ }
554
+ # The pixels, each time the realm asked for them: not only when the tree is the same. A press on
555
+ # a window that was not active changes its tree (the focus), and the stroke on the canvas was then
556
+ # not compared. Two pictures after, too, for a motion that started with the action or is slow.
557
+ $pixels = $null
558
+ if ($null -ne $shots -and $null -ne $after) {
559
+ $wr = $shots.rect
560
+ $seen = [ReticlePixels]::Shot([int]$wr.X, [int]$wr.Y, [int]$wr.Width, [int]$wr.Height)
561
+ Start-Sleep -Milliseconds 100
562
+ $later = [ReticlePixels]::Shot([int]$wr.X, [int]$wr.Y, [int]$wr.Width, [int]$wr.Height)
563
+ $pixels = [ReticlePixels]::Change($shots.earlier, $shots.before, $seen, $later, $wr.X, $wr.Y, $wr.Width, $wr.Height)
564
+ }
565
+ if ($null -eq $after) {
566
+ return @{ delivered = $delivered; reachable = $true; settled = $settled; appGone = $true; before = $before.tree; after = @{ role = 'AXApplication'; children = @() }; unreadBefore = $before.unread; unreadAfter = 0 }
567
+ }
568
+ $answer = @{ delivered = $delivered; reachable = ($reach.reach -eq 'yes'); settled = $settled; before = $before.tree; after = $after.tree; unreadBefore = $before.unread; unreadAfter = $after.unread }
569
+ if ($null -ne $pixels) { $answer.pixels = $pixels }
570
+ if ($null -ne $windowState) { $answer.windowState = $windowState }
571
+ if ($env:RETICLE_UIA_DEBUG -and $script:LastError) { $answer.uiaError = $script:LastError }
572
+ return $answer
573
+ }
574
+
575
+ function Invoke-Capture($words) {
576
+ $procId = [int]$words[1]; $file = $words[2]; $screen = $words.Count -gt 3 -and $words[3] -eq 'screen'
577
+ $windows = (Get-Windows $procId).shown
578
+ if ($windows.Count -eq 0) { return @{ ok = $false; reason = 'the application has no window on the screen' } }
579
+ $r = $windows[0].Current.BoundingRectangle
580
+ $area = $(if ($screen) { [System.Windows.Forms.Screen]::FromPoint([System.Drawing.Point]::new([int]$r.X, [int]$r.Y)).Bounds } else { [System.Drawing.Rectangle]::new([int]$r.X, [int]$r.Y, [int]$r.Width, [int]$r.Height) })
581
+ $bitmap = New-Object System.Drawing.Bitmap($area.Width, $area.Height)
582
+ $g = [System.Drawing.Graphics]::FromImage($bitmap)
583
+ $g.CopyFromScreen($area.X, $area.Y, 0, 0, $bitmap.Size)
584
+ $bitmap.Save($file, [System.Drawing.Imaging.ImageFormat]::Png); $g.Dispose(); $bitmap.Dispose()
585
+ $answer = @{ ok = $true; window = @($area.X, $area.Y, $area.Width, $area.Height); scale = 1 }
586
+ if ($screen) { $answer.appWindow = @($r.X, $r.Y, $r.Width, $r.Height) }
587
+ return $answer
588
+ }
589
+
590
+ function Invoke-ReticleCommand($words) {
591
+ switch ($words[0]) {
592
+ 'apps' {
593
+ return @{ apps = @(Get-Process | Where-Object { $_.MainWindowHandle -ne [IntPtr]::Zero } | ForEach-Object {
594
+ @{ name = $(if ($_.MainWindowTitle) { $_.ProcessName } else { $_.ProcessName }); process = $_.ProcessName; pid = $_.Id; regular = $true } }) }
595
+ }
596
+ 'tree' {
597
+ $read = Read-App ([int]$words[1])
598
+ if ($null -eq $read) { return @{ error = 'app-gone' } }
599
+ return $read
600
+ }
601
+ 'reach' {
602
+ $found = Find-Element ([int]$words[1]) $words[2]
603
+ if ($null -eq $found -or $null -eq $found.el) { return @{ refused = 'stale' } }
604
+ return Test-Reach $found.el
605
+ }
606
+ 'act' { return Invoke-Act $words }
607
+ 'capture' { return Invoke-Capture $words }
608
+ default { return @{ error = 'usage' } }
609
+ }
610
+ }
611
+
612
+ if ($args.Count -gt 0 -and $args[0] -eq 'serve') {
613
+ while ($null -ne ($line = [Console]::In.ReadLine())) {
614
+ # Windows PowerShell 5.1 gives a JSON list as one object; the pipe opens it on every version.
615
+ try { Write-Answer (Invoke-ReticleCommand @((ConvertFrom-Json $line) | ForEach-Object { [string]$_ })) }
616
+ catch { Write-Answer @{ error = [string]$_.Exception.Message } }
617
+ }
618
+ } else {
619
+ Write-Answer (Invoke-ReticleCommand $args)
620
+ }