dsh-codex-style-computer-use 2.3.1 → 2.3.3

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.
@@ -28,10 +28,15 @@ using System.Runtime.InteropServices;
28
28
  using System.Runtime.InteropServices.WindowsRuntime; // AsBuffer: byte[] -> WinRT IBuffer
29
29
  using System.Text;
30
30
  using System.Threading;
31
+ using System.Threading.Tasks;
31
32
  using System.Web.Script.Serialization;
32
33
  using System.Windows.Automation;
34
+ using System.Windows.Automation.Text;
33
35
  using System.Windows.Forms; // Clipboard (watch out: bare Point stays our own struct)
34
36
  // Inbox OCR (zero external dependencies): the union Windows.winmd ships in lib/core/winmd.
37
+ using Windows.Graphics.Capture;
38
+ using Windows.Graphics.DirectX;
39
+ using Windows.Graphics.DirectX.Direct3D11;
35
40
  using Windows.Media.Ocr;
36
41
  using Windows.Graphics.Imaging;
37
42
 
@@ -323,6 +328,10 @@ namespace DshComputerUse.Worker
323
328
  uint pid;
324
329
  public long Target { get { lock (sync) { return hwnd; } } }
325
330
  public void Reset() { lock (sync) { hwnd = 0; pid = 0; } }
331
+ public bool Confirms(long target, uint process)
332
+ {
333
+ lock (sync) { return target != 0 && process != 0 && hwnd == target && pid == process; }
334
+ }
326
335
  public void Confirm(long target, uint process)
327
336
  {
328
337
  lock (sync) { hwnd = target; pid = process; }
@@ -492,6 +501,8 @@ namespace DshComputerUse.Worker
492
501
  // GW_OWNER=4: a modal dialog's owner is the window that opened it (SameInputFamily).
493
502
  [DllImport("user32.dll")]
494
503
  public static extern IntPtr GetWindow(IntPtr hWnd, uint cmd);
504
+ [DllImport("user32.dll")]
505
+ public static extern IntPtr GetLastActivePopup(IntPtr hWnd);
495
506
  // ---- caret evidence: where WOULD the next character go? ----
496
507
  // GUITHREADINFO reports the caret for the FOREGROUND THREAD without AttachThreadInput, and
497
508
  // works in apps where UIA has no TextPattern (Word's document, many Win32 editors).
@@ -3409,6 +3420,127 @@ namespace DshComputerUse.Worker
3409
3420
  }
3410
3421
  }
3411
3422
 
3423
+ // An HWND capture session owns its frames, D3D device and CPU copies only for this request.
3424
+ sealed class WindowFrames : IDisposable
3425
+ {
3426
+ [ComImport, Guid("3628E81B-3CAC-4C60-B7F4-23CE0E0C3356"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
3427
+ interface IItemInterop {
3428
+ [PreserveSig] int CreateForWindow(IntPtr hwnd, ref Guid iid, out IntPtr item);
3429
+ [PreserveSig] int CreateForMonitor(IntPtr monitor, ref Guid iid, out IntPtr item);
3430
+ }
3431
+ [DllImport("d3d11.dll")]
3432
+ static extern int D3D11CreateDevice(IntPtr adapter, int driver, IntPtr software, uint flags,
3433
+ IntPtr levels, uint count, uint sdk, out IntPtr device, out int feature, out IntPtr context);
3434
+ [DllImport("d3d11.dll")]
3435
+ static extern int CreateDirect3D11DeviceFromDXGIDevice(IntPtr dxgi, out IntPtr device);
3436
+ [DllImport("dwmapi.dll")]
3437
+ static extern int DwmGetWindowAttribute(IntPtr hwnd, int attribute, out RECT bounds, int size);
3438
+
3439
+ IDirect3DDevice device;
3440
+ Direct3D11CaptureFramePool pool;
3441
+ GraphicsCaptureSession session;
3442
+ GraphicsCaptureItem item;
3443
+ readonly int width, height;
3444
+ public readonly RECT Bounds, WindowBounds;
3445
+ public byte[] Pixels { get; private set; }
3446
+ public long CapturedAt { get; private set; }
3447
+ byte[] signature;
3448
+
3449
+ static IDirect3DDevice CreateDevice()
3450
+ {
3451
+ IntPtr native = IntPtr.Zero, context = IntPtr.Zero, dxgi = IntPtr.Zero, projected = IntPtr.Zero;
3452
+ try {
3453
+ int level;
3454
+ int hr = D3D11CreateDevice(IntPtr.Zero, 1, IntPtr.Zero, 32, IntPtr.Zero, 0, 7, out native, out level, out context);
3455
+ if (hr < 0) Marshal.ThrowExceptionForHR(D3D11CreateDevice(IntPtr.Zero, 5, IntPtr.Zero, 32, IntPtr.Zero, 0, 7, out native, out level, out context));
3456
+ Guid iid = new Guid("54EC77FA-1377-44E6-8C32-88FD5F44C84C");
3457
+ Marshal.ThrowExceptionForHR(Marshal.QueryInterface(native, ref iid, out dxgi));
3458
+ Marshal.ThrowExceptionForHR(CreateDirect3D11DeviceFromDXGIDevice(dxgi, out projected));
3459
+ return (IDirect3DDevice)Marshal.GetObjectForIUnknown(projected);
3460
+ } finally {
3461
+ foreach (IntPtr p in new IntPtr[] { projected, dxgi, context, native }) if (p != IntPtr.Zero) Marshal.Release(p);
3462
+ }
3463
+ }
3464
+
3465
+ public WindowFrames(IntPtr hwnd, RECT window)
3466
+ {
3467
+ try {
3468
+ if (!GraphicsCaptureSession.IsSupported()) throw new NotSupportedException("Windows Graphics Capture is unavailable");
3469
+ var factory = (IItemInterop)WindowsRuntimeMarshal.GetActivationFactory(typeof(GraphicsCaptureItem));
3470
+ Guid iid = new Guid("79C3F95B-31F7-4EC2-A464-632EF5D30760");
3471
+ IntPtr ptr;
3472
+ Marshal.ThrowExceptionForHR(factory.CreateForWindow(hwnd, ref iid, out ptr));
3473
+ try { item = (GraphicsCaptureItem)Marshal.GetObjectForIUnknown(ptr); }
3474
+ finally { Marshal.Release(ptr); }
3475
+ WindowBounds = window;
3476
+ width = item.Size.Width; height = item.Size.Height;
3477
+ RECT dwm;
3478
+ if (DwmGetWindowAttribute(hwnd, 9, out dwm, Marshal.SizeOf(typeof(RECT))) == 0 &&
3479
+ dwm.Right - dwm.Left == width && dwm.Bottom - dwm.Top == height) Bounds = dwm;
3480
+ else if (window.Right - window.Left == width && window.Bottom - window.Top == height) Bounds = window;
3481
+ else throw new Exception("capture surface and window bounds differ; observe again after resizing");
3482
+ device = CreateDevice();
3483
+ pool = Direct3D11CaptureFramePool.CreateFreeThreaded(device, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, item.Size);
3484
+ session = pool.CreateCaptureSession(item);
3485
+ if (Windows.Foundation.Metadata.ApiInformation.IsPropertyPresent("Windows.Graphics.Capture.GraphicsCaptureSession", "IsCursorCaptureEnabled"))
3486
+ session.IsCursorCaptureEnabled = false;
3487
+ session.StartCapture();
3488
+ } catch { Dispose(); throw; }
3489
+ }
3490
+
3491
+ public byte[] Sample()
3492
+ {
3493
+ var timer = Stopwatch.StartNew();
3494
+ Direct3D11CaptureFrame frame;
3495
+ while ((frame = pool.TryGetNextFrame()) == null) {
3496
+ if (Pixels != null) return signature; // this session already delivered the current surface
3497
+ if (timer.ElapsedMilliseconds >= 900) throw new TimeoutException("window produced no capture frame");
3498
+ Thread.Sleep(8);
3499
+ }
3500
+ using (frame) {
3501
+ if (frame.ContentSize.Width != width || frame.ContentSize.Height != height) throw new Exception("window resized during capture");
3502
+ var copy = SoftwareBitmap.CreateCopyFromSurfaceAsync(frame.Surface, BitmapAlphaMode.Ignore);
3503
+ var task = copy.AsTask();
3504
+ if (!task.Wait(900)) {
3505
+ copy.Cancel();
3506
+ task.ContinueWith(t => { if (t.Status == System.Threading.Tasks.TaskStatus.RanToCompletion) t.Result.Dispose(); else if (t.IsFaulted) GC.KeepAlive(t.Exception); });
3507
+ throw new TimeoutException("timed out reading window pixels");
3508
+ }
3509
+ using (var bitmap = task.Result) {
3510
+ if (bitmap.PixelWidth != width || bitmap.PixelHeight != height) throw new Exception("surface size changed");
3511
+ if (Pixels == null) Pixels = new byte[checked(width * height * 4)];
3512
+ bitmap.CopyToBuffer(Pixels.AsBuffer());
3513
+ }
3514
+ CapturedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
3515
+ // RGB samples detect small color-only updates that a global mean can miss.
3516
+ byte[] next = new byte[((width + 3) / 4) * ((height + 3) / 4) * 3]; int n = 0;
3517
+ for (int y = 0; y < height; y += 4)
3518
+ for (int x = 0; x < width; x += 4) {
3519
+ int offset = (y * width + x) * 4;
3520
+ next[n++] = Pixels[offset]; next[n++] = Pixels[offset + 1]; next[n++] = Pixels[offset + 2];
3521
+ }
3522
+ signature = next;
3523
+ }
3524
+ return signature;
3525
+ }
3526
+
3527
+ public byte[] Signature { get { return signature; } }
3528
+
3529
+ public Bitmap ToBitmap()
3530
+ {
3531
+ Bitmap target = new Bitmap(width, height, PixelFormat.Format32bppRgb);
3532
+ var lockBits = target.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);
3533
+ try { Marshal.Copy(Pixels, 0, lockBits.Scan0, Pixels.Length); }
3534
+ finally { target.UnlockBits(lockBits); }
3535
+ return target;
3536
+ }
3537
+ public void Dispose()
3538
+ {
3539
+ try { if (session != null) session.Dispose(); }
3540
+ finally { try { if (pool != null) pool.Dispose(); } finally { if (device != null) device.Dispose(); } }
3541
+ }
3542
+ }
3543
+
3412
3544
  static class Program
3413
3545
  {
3414
3546
  public const int ProtocolVersion = 2;
@@ -3548,16 +3680,21 @@ namespace DshComputerUse.Worker
3548
3680
  }
3549
3681
 
3550
3682
  static IDisposable GuardReceiver(IntPtr expected, uint pid, bool keyboard)
3683
+ {
3684
+ return GuardWindowReceiver(expected, pid, keyboard, false);
3685
+ }
3686
+
3687
+ static IDisposable GuardWindowReceiver(IntPtr expected, uint pid, bool keyboard, bool exactWindow)
3551
3688
  {
3552
3689
  return new ReceiverScope(delegate {
3553
- IntPtr actual = keyboard ? InputForeground() : InputPointReceiver();
3690
+ IntPtr actual = exactWindow ? GetAncestor(Native.GetForegroundWindow(), 2) : keyboard ? InputForeground() : InputPointReceiver();
3554
3691
  string problem = InputReceiverProblem(expected.ToInt64(), pid, InputWindowExists(expected), InputWindowPid(expected), actual.ToInt64());
3555
3692
  if (problem != null)
3556
3693
  {
3557
3694
  // Same-family foreground for KEYBOARD only: the dialog is where the keystrokes
3558
3695
  // belong, so accept it and follow it. Mouse/point receivers keep the strict
3559
3696
  // check — a click must land on the pixel's real owner, never be retargeted.
3560
- if (keyboard && SameInputFamily(expected, TopLevel(actual))) { SetSticky(TopLevel(actual)); return; }
3697
+ if (!exactWindow && keyboard && SameInputFamily(expected, TopLevel(actual))) { SetSticky(TopLevel(actual)); return; }
3561
3698
  throw InputInterrupted("INPUT_TARGET_CHANGED", problem + ". Remaining input was refused; inspect any partial effect before retrying.");
3562
3699
  }
3563
3700
  });
@@ -4359,7 +4496,8 @@ namespace DshComputerUse.Worker
4359
4496
  static string _ocrLanguage;
4360
4497
  static Dictionary<string, object> Ocr(Dictionary<string, object> a)
4361
4498
  {
4362
- ValidateKickoffCapture(a);
4499
+ IntPtr window = new IntPtr(GetI(a, "hwnd", 0));
4500
+ ValidateCaptureTarget(a, window);
4363
4501
  if (_ocrEngine == null)
4364
4502
  {
4365
4503
  _ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages();
@@ -4369,6 +4507,7 @@ namespace DshComputerUse.Worker
4369
4507
  throw new Exception("OCR_UNAVAILABLE: no OCR recognizer language is installed on this machine. " +
4370
4508
  "Install one (Settings > Time & language > Language > add a language with 'Text recognition') " +
4371
4509
  "or read regions with computer_shot instead.");
4510
+ if (window != IntPtr.Zero) return WindowOcr(a, window);
4372
4511
  int vx = Native.GetSystemMetrics(Native.SM_XVIRTUALSCREEN);
4373
4512
  int vy = Native.GetSystemMetrics(Native.SM_YVIRTUALSCREEN);
4374
4513
  int vw = Native.GetSystemMetrics(Native.SM_CXVIRTUALSCREEN);
@@ -4378,7 +4517,7 @@ namespace DshComputerUse.Worker
4378
4517
  if (GetB(a, "clamp", true))
4379
4518
  {
4380
4519
  int x2 = Math.Max(x, vx), y2 = Math.Max(y, vy);
4381
- int x3 = Math.Min(x + w, vx + vw), y3 = Math.Min(y + h, vy + vh);
4520
+ int x3 = (int)Math.Min((long)x + w, (long)vx + vw), y3 = (int)Math.Min((long)y + h, (long)vy + vh);
4382
4521
  if (x3 <= x2 || y3 <= y2) throw new Exception("region outside virtual desktop");
4383
4522
  x = x2; y = y2; w = x3 - x2; h = y3 - y2;
4384
4523
  }
@@ -4410,9 +4549,75 @@ namespace DshComputerUse.Worker
4410
4549
  if (mem != IntPtr.Zero) Native.DeleteDC(mem);
4411
4550
  if (screen != IntPtr.Zero) Native.ReleaseDC(IntPtr.Zero, screen);
4412
4551
  }
4413
- SoftwareBitmap bitmap = SoftwareBitmap.CreateCopyFromBuffer(
4414
- WindowsRuntimeBufferExtensions.AsBuffer(bgra), BitmapPixelFormat.Bgra8, w, h);
4415
- OcrResult result = _ocrEngine.RecognizeAsync(bitmap).AsTask().GetAwaiter().GetResult();
4552
+ return RecognizePixels(bgra, x, y, w, h, GetI(a, "scale", 0));
4553
+ }
4554
+
4555
+ static Dictionary<string, object> WindowOcr(Dictionary<string, object> args, IntPtr window)
4556
+ {
4557
+ RECT bounds;
4558
+ string geometry = ScreenshotGeometry(window, out bounds);
4559
+ if (geometry == null) throw new Exception("OCR_TARGET_UNAVAILABLE: window closed or minimized");
4560
+ using (var frames = new WindowFrames(window, bounds)) {
4561
+ RECT r = frames.Bounds;
4562
+ int x = GetI(args, "x", r.Left), y = GetI(args, "y", r.Top);
4563
+ int w = GetI(args, "width", r.Right - r.Left), h = GetI(args, "height", r.Bottom - r.Top);
4564
+ int[] requested = { x, y, w, h };
4565
+ int left = Math.Max(x, r.Left), top = Math.Max(y, r.Top);
4566
+ long right = Math.Min((long)x + w, r.Right), bottom = Math.Min((long)y + h, r.Bottom);
4567
+ if (w <= 0 || h <= 0 || right <= left || bottom <= top)
4568
+ throw new Exception("OCR region outside window surface " + String.Join(",", new int[] { r.Left, r.Top, r.Right-r.Left, r.Bottom-r.Top }));
4569
+ x = left; y = top; w = (int)(right-left); h = (int)(bottom-top);
4570
+ if ((long)w*h > 16L*1024*1024) throw new Exception("OCR region exceeds 16M pixels; crop tighter");
4571
+ frames.Sample();
4572
+ byte[] pixels = frames.Pixels;
4573
+ if (x != r.Left || y != r.Top || w != r.Right-r.Left || h != r.Bottom-r.Top) {
4574
+ pixels = new byte[checked(w*h*4)];
4575
+ for (int i = 0; i < h; i++) Buffer.BlockCopy(frames.Pixels,
4576
+ ((y-r.Top+i)*(r.Right-r.Left)+x-r.Left)*4, pixels, i*w*4, w*4);
4577
+ }
4578
+ var result = RecognizePixels(pixels, x, y, w, h, GetI(args, "scale", 0));
4579
+ ValidateCaptureTarget(args, window);
4580
+ if (ScreenshotGeometry(window, out bounds) != geometry) throw new Exception("OCR_TARGET_CHANGED: observe this window again");
4581
+ if (requested[0] != x || requested[1] != y || requested[2] != w || requested[3] != h)
4582
+ result["requestedRegion"] = requested;
4583
+ result["hwnd"] = window.ToInt64(); result["captureBackend"] = "windows-graphics-capture";
4584
+ return result;
4585
+ }
4586
+ }
4587
+
4588
+ static byte[] EnlargeOcrPixels(byte[] pixels, int width, int height)
4589
+ {
4590
+ // Preserve GDI screen captures whose unused alpha byte may be zero.
4591
+ var pin = GCHandle.Alloc(pixels, GCHandleType.Pinned);
4592
+ try {
4593
+ using (var source = new Bitmap(width, height, width*4, PixelFormat.Format32bppRgb, pin.AddrOfPinnedObject()))
4594
+ using (var target = new Bitmap(width*2, height*2, PixelFormat.Format32bppArgb)) {
4595
+ using (var g = Graphics.FromImage(target)) {
4596
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
4597
+ g.PixelOffsetMode = PixelOffsetMode.Half;
4598
+ g.DrawImage(source, new Rectangle(0, 0, target.Width, target.Height));
4599
+ }
4600
+ var bits = target.LockBits(new Rectangle(0, 0, target.Width, target.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
4601
+ try {
4602
+ byte[] data = new byte[target.Width*target.Height*4];
4603
+ Marshal.Copy(bits.Scan0, data, 0, data.Length);
4604
+ return data;
4605
+ } finally { target.UnlockBits(bits); }
4606
+ }
4607
+ } finally { pin.Free(); }
4608
+ }
4609
+
4610
+ static Dictionary<string, object> RecognizePixels(byte[] bgra, int x, int y, int w, int h, int requestedScale)
4611
+ {
4612
+ bool fits = (long)w*h <= 1024*1024 && Math.Max(w,h)*2L <= OcrEngine.MaxImageDimension;
4613
+ if (requestedScale < 0 || requestedScale > 2 || (requestedScale == 2 && !fits))
4614
+ throw new Exception("OCR scale 2 requires a crop within 1M pixels and the Windows OCR dimension limit");
4615
+ int scale = requestedScale == 0 ? (fits ? 2 : 1) : requestedScale;
4616
+ if (scale == 2) bgra = EnlargeOcrPixels(bgra, w, h);
4617
+ OcrResult result;
4618
+ using (SoftwareBitmap bitmap = SoftwareBitmap.CreateCopyFromBuffer(
4619
+ WindowsRuntimeBufferExtensions.AsBuffer(bgra), BitmapPixelFormat.Bgra8, w*scale, h*scale))
4620
+ result = _ocrEngine.RecognizeAsync(bitmap).AsTask().GetAwaiter().GetResult();
4416
4621
  List<object> lines = new List<object>();
4417
4622
  StringBuilder joined = new StringBuilder();
4418
4623
  foreach (OcrLine line in result.Lines)
@@ -4420,99 +4625,359 @@ namespace DshComputerUse.Worker
4420
4625
  List<object> words = new List<object>();
4421
4626
  foreach (OcrWord word in line.Words)
4422
4627
  {
4423
- words.Add(Dict("text", word.Text,
4424
- "x", x + (int)word.BoundingRect.X, "y", y + (int)word.BoundingRect.Y,
4425
- "w", (int)word.BoundingRect.Width, "h", (int)word.BoundingRect.Height));
4628
+ var box = word.BoundingRect;
4629
+ int left = (int)(box.X/scale), top = (int)(box.Y/scale);
4630
+ words.Add(Dict("text", word.Text, "x", x+left, "y", y+top,
4631
+ "w", (int)Math.Ceiling((box.X+box.Width)/scale)-left,
4632
+ "h", (int)Math.Ceiling((box.Y+box.Height)/scale)-top));
4426
4633
  }
4427
4634
  lines.Add(Dict("text", line.Text, "words", words));
4428
4635
  if (joined.Length > 0) joined.Append('\n');
4429
4636
  joined.Append(line.Text);
4430
4637
  }
4431
- return Dict("lines", lines, "text", joined.ToString(), "language", _ocrLanguage,
4638
+ return Dict("lines", lines, "text", joined.ToString(), "language", _ocrLanguage, "scale", scale,
4432
4639
  "region", new int[] { x, y, w, h });
4433
4640
  }
4434
4641
 
4642
+ [DllImport("user32.dll")]
4643
+ static extern IntPtr GetAncestor(IntPtr window, uint flags);
4644
+
4645
+ static string ScreenshotGeometry(IntPtr window, out RECT bounds)
4646
+ {
4647
+ bounds = new RECT();
4648
+ if (!Native.IsWindowVisible(window) || Native.IsIconic(window) || !Native.GetWindowRect(window, out bounds) ||
4649
+ bounds.Right <= bounds.Left || bounds.Bottom <= bounds.Top) return null;
4650
+ uint dpi = 0;
4651
+ try { dpi = Native.GetDpiForWindow(window); } catch (EntryPointNotFoundException) { }
4652
+ return String.Join(",", new object[] { window.ToInt64(), PidOf(window), bounds.Left, bounds.Top,
4653
+ bounds.Right, bounds.Bottom, dpi, Native.GetSystemMetrics(Native.SM_XVIRTUALSCREEN),
4654
+ Native.GetSystemMetrics(Native.SM_YVIRTUALSCREEN), Native.GetSystemMetrics(Native.SM_CXVIRTUALSCREEN),
4655
+ Native.GetSystemMetrics(Native.SM_CYVIRTUALSCREEN) });
4656
+ }
4657
+
4658
+ sealed class ClickControl
4659
+ {
4660
+ public System.Windows.Rect Rect;
4661
+ public string RuntimeId, Name, Id;
4662
+ public int Role;
4663
+ public static ClickControl Read(AutomationElement e)
4664
+ {
4665
+ var c = e.Cached;
4666
+ var type = c.ControlType;
4667
+ if (type != ControlType.Button && type != ControlType.Hyperlink && type != ControlType.CheckBox &&
4668
+ type != ControlType.RadioButton && type != ControlType.MenuItem && type != ControlType.TabItem &&
4669
+ type != ControlType.ListItem && type != ControlType.ComboBox) return null;
4670
+ var ids = e.GetRuntimeId(); var rect = c.BoundingRectangle;
4671
+ if (!c.IsEnabled || c.IsOffscreen || ids == null || ids.Length == 0 || rect.IsEmpty || rect.Width <= 0 || rect.Height <= 0) return null;
4672
+ return new ClickControl { Rect = rect, Role = type.Id, Name = c.Name, Id = c.AutomationId,
4673
+ RuntimeId = String.Join(".", ids) };
4674
+ }
4675
+ public bool Same(ClickControl other)
4676
+ {
4677
+ return other != null && RuntimeId == other.RuntimeId && Id == other.Id && Role == other.Role &&
4678
+ Name == other.Name && Rect == other.Rect;
4679
+ }
4680
+ }
4681
+ // A slow UIA provider must not hold the screenshot worker. At most one provider scan
4682
+ // is outstanding. Pixel evidence remains available if there is no usable control.
4683
+ static int witnessProviderBusy;
4684
+ static Task<T> StartWitnessRead<T>(Func<T> query) where T : class
4685
+ {
4686
+ if (Interlocked.CompareExchange(ref witnessProviderBusy, 1, 0) != 0) return null;
4687
+ return Task.Run(delegate {
4688
+ try { return query(); } catch { return null; }
4689
+ finally { Interlocked.Exchange(ref witnessProviderBusy, 0); }
4690
+ });
4691
+ }
4692
+ static CacheRequest WitnessCache()
4693
+ {
4694
+ var cache = UiSelectorCache(); cache.Add(AutomationElement.BoundingRectangleProperty);
4695
+ cache.Add(AutomationElement.IsEnabledProperty); cache.Add(AutomationElement.IsOffscreenProperty); return cache;
4696
+ }
4697
+ static List<ClickControl> ReadClickControls(IntPtr window)
4698
+ {
4699
+ var result = new List<ClickControl>(); var cache = WitnessCache();
4700
+ var root = AutomationElement.FromHandle(window);
4701
+ UiWalkBounded(root, 5, 72, 73, new UiReadBudget(120, UiClockMs),
4702
+ delegate(AutomationElement e) {
4703
+ if (e != root) try { var c = ClickControl.Read(e); if (c != null) result.Add(c); } catch (ElementNotAvailableException) { }
4704
+ return false;
4705
+ }, delegate(AutomationElement e) { return TreeWalker.ControlViewWalker.GetFirstChild(e, cache); },
4706
+ delegate(AutomationElement e) { return TreeWalker.ControlViewWalker.GetNextSibling(e, cache); });
4707
+ return result;
4708
+ }
4709
+ static ClickControl ControlAt(int x, int y)
4710
+ {
4711
+ var cache = WitnessCache();
4712
+ using (cache.Activate()) {
4713
+ var e = AutomationElement.FromPoint(new System.Windows.Point(x, y));
4714
+ for (int depth = 0; e != null && depth < 5; depth++) {
4715
+ var c = ClickControl.Read(e); if (c != null) return c;
4716
+ e = TreeWalker.ControlViewWalker.GetParent(e, cache);
4717
+ }
4718
+ }
4719
+ return null;
4720
+ }
4721
+
4722
+ sealed class ClickWitness
4723
+ {
4724
+ public string Id, Geometry;
4725
+ public RECT Bounds;
4726
+ public byte[] Pixels, InitialPixels; // cursor-free RGB, one sample every four physical pixels
4727
+ public int Bytes { get { return Pixels.Length + (InitialPixels == null ? 0 : InitialPixels.Length); } }
4728
+ public List<ClickControl> Controls;
4729
+ }
4730
+ static readonly Queue<ClickWitness> clickWitnesses = new Queue<ClickWitness>();
4731
+ static int witnessBytes;
4732
+ static string RememberClickWitness(string geometry, RECT bounds, byte[] pixels, List<ClickControl> controls, byte[] initial)
4733
+ {
4734
+ const int limit = 16 * 1024 * 1024;
4735
+ var id = Guid.NewGuid().ToString("N");
4736
+ var shot = new ClickWitness { Id = id, Geometry = geometry, Bounds = bounds, Pixels = pixels, Controls = controls };
4737
+ if (controls != null && controls.Count != 0 && !Object.ReferenceEquals(initial,pixels) && !initial.SequenceEqual(pixels))
4738
+ shot.InitialPixels = initial;
4739
+ while (clickWitnesses.Count > 0 && (clickWitnesses.Count >= 12 || witnessBytes + shot.Bytes > limit))
4740
+ witnessBytes -= clickWitnesses.Dequeue().Bytes;
4741
+ if (shot.Bytes <= limit) {
4742
+ clickWitnesses.Enqueue(shot); witnessBytes += shot.Bytes; return id;
4743
+ }
4744
+ return null;
4745
+ }
4746
+ static bool SameClickPatch(ClickWitness shot, byte[] current, int x, int y)
4747
+ {
4748
+ if (current == null || current.Length != shot.Pixels.Length) return false;
4749
+ int width = shot.Bounds.Right - shot.Bounds.Left, height = shot.Bounds.Bottom - shot.Bounds.Top;
4750
+ int columns = (width + 3) / 4, changed = 0;
4751
+ x -= shot.Bounds.Left; y -= shot.Bounds.Top;
4752
+ if (x < 0 || y < 0 || x >= width || y >= height) return false;
4753
+ for (int row = Math.Max(0, y - 18) / 4; row <= Math.Min(height - 1, y + 18) / 4; row++)
4754
+ for (int col = Math.Max(0, x - 32) / 4; col <= Math.Min(width - 1, x + 32) / 4; col++) {
4755
+ int i = 3 * (row * columns + col);
4756
+ if (Math.Abs(shot.Pixels[i] - current[i]) > 12 || Math.Abs(shot.Pixels[i+1] - current[i+1]) > 12 ||
4757
+ Math.Abs(shot.Pixels[i+2] - current[i+2]) > 12) if (++changed >= 3) return false;
4758
+ }
4759
+ return true;
4760
+ }
4761
+ static string CheckClickWitness(Dictionary<string, object> args, int x, int y)
4762
+ {
4763
+ string id = GetS(args, "shotWitness", null);
4764
+ if (id == null) return null;
4765
+ IntPtr hwnd = new IntPtr(GetI(args, "expectHwnd", 0)); RECT bounds;
4766
+ var shot = clickWitnesses.FirstOrDefault(w => w.Id == id);
4767
+ if (shot != null && ScreenshotGeometry(hwnd, out bounds) == shot.Geometry) {
4768
+ var oldControl = shot.Controls == null ? null : shot.Controls.Where(c => c.Rect.Contains(x, y))
4769
+ .OrderBy(c => c.Rect.Width * c.Rect.Height).FirstOrDefault();
4770
+ var query = StartWitnessRead(delegate { return new ClickControl[] { ControlAt(x, y) }; });
4771
+ bool ready = query != null && query.Wait(250) && query.Result != null;
4772
+ var current = ready ? query.Result[0] : null;
4773
+ if (oldControl != null) {
4774
+ if (ready && oldControl.Same(current) &&
4775
+ (shot.InitialPixels == null || SameClickPatch(shot, shot.InitialPixels, x, y))) return "uia";
4776
+ } else if (ready && current == null) {
4777
+ try {
4778
+ using (var frames = new WindowFrames(hwnd, bounds))
4779
+ if (frames.Bounds.Left == shot.Bounds.Left && frames.Bounds.Top == shot.Bounds.Top &&
4780
+ frames.Bounds.Right == shot.Bounds.Right && frames.Bounds.Bottom == shot.Bounds.Bottom &&
4781
+ SameClickPatch(shot, frames.Sample(), x, y)) return "pixels";
4782
+ } catch { /* unavailable pixels cannot authorize the old click */ }
4783
+ }
4784
+ }
4785
+ throw InputInterrupted("STALE_SCREENSHOT", "Click target changed or its observation expired. Inspect this window again.");
4786
+ }
4787
+
4788
+ static void CheckScreenshotPoint(Dictionary<string, object> a, int x, int y)
4789
+ {
4790
+ string expected = GetS(a, "shotGeometry", null);
4791
+ if (expected == null && !GetB(a, "strictHwnd", false)) return;
4792
+ IntPtr window = new IntPtr(GetI(a, "expectHwnd", 0));
4793
+ RECT bounds;
4794
+ POINT point; point.X = x; point.Y = y;
4795
+ if ((expected != null && ScreenshotGeometry(window, out bounds) != expected) || !Native.IsWindowEnabled(window) ||
4796
+ GetAncestor(Native.WindowFromPoint(point), 2) != window ||
4797
+ GetAncestor(Native.GetForegroundWindow(), 2) != window)
4798
+ throw InputInterrupted(expected != null ? "STALE_SCREENSHOT" : "INPUT_TARGET_CHANGED",
4799
+ "The window moved, changed focus, or the point is covered. Observe the named window again.");
4800
+ }
4801
+
4802
+ // Only a matching settled observation, with the same input tick and geometry, earns
4803
+ // the short repeat window. A change during either path starts a full quiet interval.
4804
+ static string lastCaptureKey;
4805
+ static byte[] lastCaptureSample;
4806
+ static uint lastCaptureInput;
4807
+ static readonly Stopwatch CaptureClock = Stopwatch.StartNew();
4808
+ static long lastSettledAt;
4809
+ static bool WaitForCapture(Dictionary<string, object> args, string key, Func<byte[]> sample,
4810
+ out int elapsed, out double difference)
4811
+ {
4812
+ string mode = GetS(args, "wait", "auto");
4813
+ int cap = Math.Max(1, GetI(args, "waitCapMs", mode == "auto" ? 2500 : 10000));
4814
+ int quiet = Math.Max(1, GetI(args, "stableMs", mode == "auto" ? 450 : 700));
4815
+ var timer = Stopwatch.StartNew();
4816
+ uint input = Native.LastInputTick();
4817
+ byte[] previous = sample();
4818
+ bool repeat = mode == "auto" && !args.ContainsKey("stableMs") && key == lastCaptureKey &&
4819
+ CaptureClock.ElapsedMilliseconds - lastSettledAt < 12000 && input == lastCaptureInput &&
4820
+ previous != null && lastCaptureSample != null && previous.SequenceEqual(lastCaptureSample);
4821
+ lastCaptureKey = null; lastCaptureSample = null;
4822
+ long quietSince = timer.ElapsedMilliseconds;
4823
+ int required = repeat ? Math.Min(205, quiet) : quiet;
4824
+ difference = 0;
4825
+ do {
4826
+ long remaining = cap - timer.ElapsedMilliseconds;
4827
+ if (remaining <= 0) break;
4828
+ Thread.Sleep((int)Math.Min(45, Math.Min(remaining, Math.Max(1, required - (timer.ElapsedMilliseconds - quietSince)))));
4829
+ byte[] current = sample();
4830
+ uint tick = Native.LastInputTick();
4831
+ difference = Object.ReferenceEquals(current, previous) && current != null ? 0 : SigDiffPct(previous, current, 4);
4832
+ if (difference > 0 || input != tick) { quietSince = timer.ElapsedMilliseconds; required = quiet; input = tick; }
4833
+ previous = current;
4834
+ if (current != null && timer.ElapsedMilliseconds - quietSince >= required) {
4835
+ lastCaptureKey = key; lastCaptureSample = current; lastCaptureInput = tick;
4836
+ lastSettledAt = CaptureClock.ElapsedMilliseconds; elapsed = (int)timer.ElapsedMilliseconds; return true;
4837
+ }
4838
+ } while (timer.ElapsedMilliseconds < cap);
4839
+ elapsed = (int)timer.ElapsedMilliseconds; return false;
4840
+ }
4841
+
4842
+ static void ValidateCaptureTarget(Dictionary<string, object> args, IntPtr hwnd)
4843
+ {
4844
+ // WGC reads exactly this surface even if the confirmed app is behind another window.
4845
+ if (hwnd != IntPtr.Zero && _kickoffFocus.Confirms(hwnd.ToInt64(), PidOf(hwnd)) && Native.IsWindow(hwnd) &&
4846
+ (!IsHostWindow(hwnd) || HostDrivingAllowed())) return;
4847
+ IntPtr owner = new IntPtr(_kickoffFocus.Target);
4848
+ if (hwnd != IntPtr.Zero && owner != IntPtr.Zero && hwnd != owner && _kickoffFocus.Confirms(owner.ToInt64(), PidOf(owner)) &&
4849
+ (!IsHostWindow(owner) || HostDrivingAllowed()) && FeedbackSurface(owner) == hwnd) return;
4850
+ ValidateKickoffCapture(args);
4851
+ if (hwnd != IntPtr.Zero && GetB(args, "__kickoff", true) && Panic.CycleLit && !Panic.Stopped &&
4852
+ !Panic.Exited && hwnd != TopLevel(Native.GetForegroundWindow()))
4853
+ throw new Exception("KICKOFF-FOCUS-REQUIRED: select this window before observing its background surface");
4854
+ }
4855
+
4435
4856
  static Dictionary<string, object> Capture(Dictionary<string, object> a)
4436
4857
  {
4437
- ValidateKickoffCapture(a); // before even the pixel-stability sampler
4858
+ IntPtr shotWindow = new IntPtr(GetI(a, "shotWindow", 0));
4859
+ ValidateCaptureTarget(a, shotWindow);
4438
4860
  int vx = Native.GetSystemMetrics(Native.SM_XVIRTUALSCREEN);
4439
4861
  int vy = Native.GetSystemMetrics(Native.SM_YVIRTUALSCREEN);
4440
4862
  int vw = Native.GetSystemMetrics(Native.SM_CXVIRTUALSCREEN);
4441
4863
  int vh = Native.GetSystemMetrics(Native.SM_CYVIRTUALSCREEN);
4442
4864
  int x = GetI(a, "x", vx), y = GetI(a, "y", vy);
4443
4865
  int w = GetI(a, "width", vw), h = GetI(a, "height", vh);
4444
- if (GetB(a, "clamp", true))
4866
+ string geometry = null;
4867
+ if (shotWindow != IntPtr.Zero)
4868
+ {
4869
+ RECT bounds;
4870
+ geometry = ScreenshotGeometry(shotWindow, out bounds);
4871
+ if (geometry == null) throw new Exception("SCREENSHOT_WINDOW_UNAVAILABLE: select a visible window");
4872
+ x = bounds.Left; y = bounds.Top;
4873
+ w = bounds.Right - x; h = bounds.Bottom - y;
4874
+ }
4875
+ if (shotWindow == IntPtr.Zero && GetB(a, "clamp", true))
4445
4876
  {
4446
4877
  int x2 = Math.Max(x, vx), y2 = Math.Max(y, vy);
4447
- int x3 = Math.Min(x + w, vx + vw), y3 = Math.Min(y + h, vy + vh);
4878
+ int x3 = (int)Math.Min((long)x + w, (long)vx + vw), y3 = (int)Math.Min((long)y + h, (long)vy + vh);
4448
4879
  if (x3 <= x2 || y3 <= y2) throw new Exception("region outside virtual desktop");
4449
4880
  x = x2; y = y2; w = x3 - x2; h = y3 - y2;
4450
4881
  }
4451
4882
  bool withCursor = GetB(a, "cursor", false);
4452
4883
 
4453
- // Timing redundancy (user-requested): PRIMARY = wait for pixel stability, so a
4454
- // slow network never yields a half-rendered screenshot. FALLBACK = a hard cap;
4455
- // if the screen still will not settle we shoot anyway and report settled:false,
4456
- // so the caller knows to distrust the image instead of stalling the whole task.
4457
4884
  string waitMode = GetS(a, "wait", "auto");
4458
- bool settled = true;
4459
- int settleMs = 0;
4885
+ bool settled = true, cursorDrawn = false;
4886
+ int settleMs = 0, cursorFlags = 0, cursorAtX = 0, cursorAtY = 0;
4460
4887
  double settleDiff = 0;
4461
- int settleEstimate = 0;
4462
- if (waitMode != "none")
4463
- {
4464
- int cap = GetI(a, "waitCapMs", waitMode == "auto" ? 2500 : 10000);
4465
- int stabMs = GetI(a, "stableMs", waitMode == "auto" ? 450 : 700);
4466
- settled = SettleWait(cap, stabMs, 220, 8, GetD(a, "diffPct", 0.30),
4467
- out settleMs, out settleDiff, out settleEstimate);
4468
- }
4469
-
4470
- ValidateKickoffCapture(a); // focus may have changed while the page was settling
4471
- IntPtr screen = Native.GetDC(IntPtr.Zero);
4472
- IntPtr mem = Native.CreateCompatibleDC(screen);
4473
- Native.BITMAPINFO bmi = new Native.BITMAPINFO();
4474
- bmi.bmiHeader.biSize = (uint)Marshal.SizeOf(typeof(Native.BITMAPINFOHEADER));
4475
- bmi.bmiHeader.biWidth = w; bmi.bmiHeader.biHeight = -h;
4476
- bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32;
4477
- bmi.bmiHeader.biCompression = 0;
4478
- IntPtr bits;
4479
- IntPtr dib = Native.CreateDIBSection(screen, ref bmi, 0, out bits, IntPtr.Zero, 0);
4480
- IntPtr old = Native.SelectObject(mem, dib);
4481
- // SRCCOPY | CAPTUREBLT so layered windows are included
4482
- Native.BitBlt(mem, 0, 0, w, h, screen, x, y, 0x00CC0020 | 0x40000000);
4483
- long capturedAt = NowMs();
4484
- bool cursorDrawn = false;
4485
- int cursorFlags = 0, cursorAtX = 0, cursorAtY = 0;
4486
- if (withCursor)
4487
- {
4488
- CURSORINFO ci = new CURSORINFO();
4489
- ci.cbSize = (uint)Marshal.SizeOf(typeof(CURSORINFO));
4490
- if (Native.GetCursorInfo(ref ci))
4888
+ long capturedAt;
4889
+ bool foregroundAtCapture = shotWindow != IntPtr.Zero && GetAncestor(Native.GetForegroundWindow(), 2) == shotWindow;
4890
+ string witness = null;
4891
+ Bitmap managed;
4892
+ if (shotWindow != IntPtr.Zero) {
4893
+ RECT bounds;
4894
+ if (ScreenshotGeometry(shotWindow, out bounds) != geometry) throw new Exception("STALE_SCREENSHOT: window changed before capture");
4895
+ try {
4896
+ bool keepWitness = foregroundAtCapture && GetB(a, "clickWitness", false);
4897
+ using (var frames = new WindowFrames(shotWindow, bounds)) {
4898
+ byte[] firstPixels = keepWitness ? frames.Sample() : null;
4899
+ var controls = keepWitness ? StartWitnessRead(delegate { return ReadClickControls(shotWindow); }) : null;
4900
+ if (waitMode == "none") { if (!keepWitness) frames.Sample(); }
4901
+ else settled = WaitForCapture(a, geometry, frames.Sample, out settleMs, out settleDiff);
4902
+ x = frames.Bounds.Left; y = frames.Bounds.Top;
4903
+ w = frames.Bounds.Right - x; h = frames.Bounds.Bottom - y;
4904
+ managed = frames.ToBitmap(); capturedAt = frames.CapturedAt;
4905
+ if (keepWitness && settled) {
4906
+ byte[] captured = frames.Signature;
4907
+ var matched = controls != null && controls.Wait(120) ? controls.Result : null;
4908
+ witness = RememberClickWitness(geometry, frames.Bounds, captured, matched, firstPixels);
4909
+ }
4910
+ }
4911
+ } catch (Exception ex) {
4912
+ throw new Exception("CAPTURE_UNAVAILABLE: Windows.Graphics.Capture could not read this window: " + ex.GetBaseException().Message);
4913
+ }
4914
+ if (withCursor) {
4915
+ CURSORINFO ci = new CURSORINFO(); ci.cbSize = (uint)Marshal.SizeOf(typeof(CURSORINFO));
4916
+ if (Native.GetCursorInfo(ref ci)) {
4917
+ cursorFlags = (int)ci.flags; cursorAtX = ci.ptScreenPos.X; cursorAtY = ci.ptScreenPos.Y;
4918
+ if ((ci.flags & Native.CURSOR_SHOWING) != 0 && GetAncestor(Native.WindowFromPoint(ci.ptScreenPos), 2) == shotWindow) {
4919
+ using (Graphics graphics = Graphics.FromImage(managed)) {
4920
+ IntPtr dc = graphics.GetHdc();
4921
+ try { cursorDrawn = Native.DrawIconEx(dc, cursorAtX - x, cursorAtY - y, ci.hCursor, 0, 0, 0, IntPtr.Zero, Native.DI_NORMAL); }
4922
+ finally { graphics.ReleaseHdc(dc); }
4923
+ }
4924
+ }
4925
+ }
4926
+ }
4927
+ } else {
4928
+ if (waitMode != "none")
4929
+ settled = WaitForCapture(a, String.Join(",", new int[] { x, y, w, h }),
4930
+ delegate { return CaptureRegionSamples(x, y, w, h, 8); }, out settleMs, out settleDiff);
4931
+ ValidateKickoffCapture(a);
4932
+ IntPtr screen = Native.GetDC(IntPtr.Zero);
4933
+ IntPtr mem = Native.CreateCompatibleDC(screen);
4934
+ Native.BITMAPINFO bmi = new Native.BITMAPINFO();
4935
+ bmi.bmiHeader.biSize = (uint)Marshal.SizeOf(typeof(Native.BITMAPINFOHEADER));
4936
+ bmi.bmiHeader.biWidth = w; bmi.bmiHeader.biHeight = -h;
4937
+ bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32;
4938
+ bmi.bmiHeader.biCompression = 0;
4939
+ IntPtr bits;
4940
+ IntPtr dib = Native.CreateDIBSection(screen, ref bmi, 0, out bits, IntPtr.Zero, 0);
4941
+ IntPtr old = Native.SelectObject(mem, dib);
4942
+ // SRCCOPY | CAPTUREBLT so layered windows are included
4943
+ Native.BitBlt(mem, 0, 0, w, h, screen, x, y, 0x00CC0020 | 0x40000000);
4944
+ capturedAt = NowMs();
4945
+ if (withCursor)
4491
4946
  {
4492
- cursorFlags = (int)ci.flags; cursorAtX = ci.ptScreenPos.X; cursorAtY = ci.ptScreenPos.Y;
4493
- if ((ci.flags & Native.CURSOR_SHOWING) != 0)
4947
+ CURSORINFO ci = new CURSORINFO();
4948
+ ci.cbSize = (uint)Marshal.SizeOf(typeof(CURSORINFO));
4949
+ if (Native.GetCursorInfo(ref ci))
4494
4950
  {
4495
- // Draw straight into the DC that already owns the DIB. The first
4496
- // version created a second DC and SelectObject'd the SAME bitmap into
4497
- // it — GDI forbids a bitmap living in two DCs at once, that SelectObject
4498
- // failed silently, and DrawIconEx painted into memG's default 1x1
4499
- // monochrome bitmap. Result: cursorDrawn=true with no arrow in the image.
4500
- cursorDrawn = Native.DrawIconEx(mem, ci.ptScreenPos.X - x, ci.ptScreenPos.Y - y, ci.hCursor, 0, 0, 0, IntPtr.Zero, Native.DI_NORMAL);
4951
+ cursorFlags = (int)ci.flags; cursorAtX = ci.ptScreenPos.X; cursorAtY = ci.ptScreenPos.Y;
4952
+ if ((ci.flags & Native.CURSOR_SHOWING) != 0)
4953
+ {
4954
+ // Draw straight into the DC that already owns the DIB. The first
4955
+ // version created a second DC and SelectObject'd the SAME bitmap into
4956
+ // it — GDI forbids a bitmap living in two DCs at once, that SelectObject
4957
+ // failed silently, and DrawIconEx painted into memG's default 1x1
4958
+ // monochrome bitmap. Result: cursorDrawn=true with no arrow in the image.
4959
+ cursorDrawn = Native.DrawIconEx(mem, ci.ptScreenPos.X - x, ci.ptScreenPos.Y - y, ci.hCursor, 0, 0, 0, IntPtr.Zero, Native.DI_NORMAL);
4960
+ }
4501
4961
  }
4502
4962
  }
4963
+ // copy DIB pixels into a managed bitmap BEFORE freeing the DIB —
4964
+ // a Bitmap that wraps DIB memory must never outlive the DIB
4965
+ Bitmap wrap = new Bitmap(w, h, 4 * w, PixelFormat.Format32bppRgb, bits);
4966
+ managed = new Bitmap(w, h);
4967
+ using (Graphics cg = Graphics.FromImage(managed))
4968
+ {
4969
+ cg.DrawImage(wrap, 0, 0, w, h);
4970
+ }
4971
+ wrap.Dispose();
4972
+ Native.SelectObject(mem, old);
4973
+ Native.DeleteObject(dib); Native.DeleteDC(mem); Native.ReleaseDC(IntPtr.Zero, screen);
4503
4974
  }
4504
- // copy DIB pixels into a managed bitmap BEFORE freeing the DIB —
4505
- // a Bitmap that wraps DIB memory must never outlive the DIB
4506
- Bitmap wrap = new Bitmap(w, h, 4 * w, PixelFormat.Format32bppRgb, bits);
4507
- Bitmap managed = new Bitmap(w, h);
4508
- using (Graphics cg = Graphics.FromImage(managed))
4509
- {
4510
- cg.DrawImage(wrap, 0, 0, w, h);
4975
+ try {
4976
+ ValidateCaptureTarget(a, shotWindow);
4977
+ RECT after;
4978
+ if (geometry != null && ScreenshotGeometry(shotWindow, out after) != geometry)
4979
+ throw new Exception("STALE_SCREENSHOT: window geometry changed during capture; capture again");
4511
4980
  }
4512
- wrap.Dispose();
4513
- Native.SelectObject(mem, old);
4514
- Native.DeleteObject(dib); Native.DeleteDC(mem); Native.ReleaseDC(IntPtr.Zero, screen);
4515
- try { ValidateKickoffCapture(a); }
4516
4981
  catch { managed.Dispose(); throw; } // discard pixels if focus changed during capture
4517
4982
  Bitmap bmp = managed;
4518
4983
 
@@ -4555,6 +5020,12 @@ namespace DshComputerUse.Worker
4555
5020
  "capturedAt", capturedAt,
4556
5021
  "cursor", PtDict(cp2.X, cp2.Y),
4557
5022
  "ts", NowMs());
5023
+ res["captureBackend"] = shotWindow == IntPtr.Zero ? "desktop-bitblt" : "windows-graphics-capture";
5024
+ if (geometry != null) {
5025
+ res["hwnd"] = shotWindow.ToInt64();
5026
+ if (witness != null) res["shotWitness"] = witness;
5027
+ if ((!GetB(a, "clickWitness", false) || witness != null) && foregroundAtCapture && GetAncestor(Native.GetForegroundWindow(), 2) == shotWindow) res["shotGeometry"] = geometry;
5028
+ }
4558
5029
  if (withCursor)
4559
5030
  {
4560
5031
  // Diagnostics for the visual-calibration contract: the pointer must be
@@ -4570,7 +5041,7 @@ namespace DshComputerUse.Worker
4570
5041
  ? "pointer burned into the image at cursorInImage"
4571
5042
  : ((cursorFlags & 1) == 0
4572
5043
  ? "pointer was HIDDEN (CURSOR_SHOWING=0) at capture time"
4573
- : "DrawIconEx refused; pointer not burned in");
5044
+ : "pointer outside the captured target or unavailable for drawing");
4574
5045
  }
4575
5046
  if (waitMode != "none")
4576
5047
  {
@@ -4578,8 +5049,7 @@ namespace DshComputerUse.Worker
4578
5049
  res["settleMs"] = settleMs;
4579
5050
  res["settleDiffPct"] = Math.Round(settleDiff, 3);
4580
5051
  if (!settled)
4581
- res["settleNote"] = "page never went quiet within the cap — this image may be a partial render; ~" +
4582
- settleEstimate + "ms more might have finished it (or re-shoot with wait:\"stable\")";
5052
+ res["settleNote"] = "The observed surface did not remain quiet before the deadline. Inspect again.";
4583
5053
  }
4584
5054
  // Tell the human a capture just happened: a yellow border flashes around the
4585
5055
  // captured rectangle. Deliberately fired AFTER the pixels are grabbed, so the
@@ -4772,7 +5242,7 @@ namespace DshComputerUse.Worker
4772
5242
  Native.GetCursorPos(out p);
4773
5243
  }
4774
5244
  CheckHumanInput();
4775
- return Dict("x", p.X, "y", p.Y, "positionCorrections", _positionCorrections, "cursor", CursorSnapshot());
5245
+ return Dict("x", p.X, "y", p.Y, "positionCorrections", _positionCorrections, "cursor", CursorSnapshot(), "actionHwnd", TopLevel(Native.WindowFromPoint(p)).ToInt64());
4776
5246
  }
4777
5247
 
4778
5248
  static Rectangle ClickSampleRegion(int x, int y, Rectangle desktop)
@@ -4838,6 +5308,8 @@ namespace DshComputerUse.Worker
4838
5308
 
4839
5309
  static Dictionary<string, object> Click(Dictionary<string, object> a)
4840
5310
  {
5311
+ CheckScreenshotPoint(a, GetI(a, "x", 0), GetI(a, "y", 0));
5312
+ CheckClickWitness(a, GetI(a, "x", 0), GetI(a, "y", 0));
4841
5313
  Rectangle sampleRegion = VerificationSampleRegion(a, GetI(a, "x", 0), GetI(a, "y", 0), new Rectangle(
4842
5314
  Native.GetSystemMetrics(Native.SM_XVIRTUALSCREEN), Native.GetSystemMetrics(Native.SM_YVIRTUALSCREEN),
4843
5315
  Native.GetSystemMetrics(Native.SM_CXVIRTUALSCREEN), Native.GetSystemMetrics(Native.SM_CYVIRTUALSCREEN)));
@@ -5007,14 +5479,28 @@ namespace DshComputerUse.Worker
5007
5479
  if (tx != int.MinValue) HostGuardPoint(tx, ty, "click");
5008
5480
  if (under == IntPtr.Zero) under = InputPointReceiver();
5009
5481
 
5482
+ string checkedTarget = null;
5010
5483
  uint down = Native.MOUSEEVENTF_LEFTDOWN, up = Native.MOUSEEVENTF_LEFTUP;
5011
5484
  if (btn == "right") { down = Native.MOUSEEVENTF_RIGHTDOWN; up = Native.MOUSEEVENTF_RIGHTUP; }
5012
5485
  else if (btn == "middle") { down = Native.MOUSEEVENTF_MIDDLEDOWN; up = Native.MOUSEEVENTF_MIDDLEUP; }
5486
+ CheckScreenshotPoint(a, tx, ty);
5013
5487
  using (GuardReceiver(under, InputWindowPid(under), false)) {
5014
- for (int i = 0; i < clicks; i++) {
5015
- SendMouse(down, 0, 0, 0); Thread.Sleep(30); SendMouse(up, 0, 0, 0);
5016
- if (i < clicks - 1) Thread.Sleep(gap);
5017
- }
5488
+ var modifiers = new List<ushort>();
5489
+ if (GetB(a, "ctrl", false)) modifiers.Add(0x11);
5490
+ if (GetB(a, "shift", false)) modifiers.Add(0x10);
5491
+ KeyboardChord.Run(modifiers, SendKey, ReleaseKeyForCleanup,
5492
+ delegate(ushort vk) { return (Native.GetAsyncKeyState(vk) & 0x8000) != 0; },
5493
+ delegate {
5494
+ for (int i = 0; i < clicks; i++) {
5495
+ if (i == 0) checkedTarget = CheckClickWitness(a, tx, ty);
5496
+ CheckHumanInput();
5497
+ CheckScreenshotPoint(a, tx, ty);
5498
+ SendMouse(down, 0, 0, 0);
5499
+ WaitForKeyHold(GetI(a, "holdMs", 30));
5500
+ SendMouse(up, 0, 0, 0);
5501
+ if (i < clicks - 1) Thread.Sleep(gap);
5502
+ }
5503
+ });
5018
5504
  }
5019
5505
  EndActuationForReadback();
5020
5506
  byte[] after = null;
@@ -5028,6 +5514,8 @@ namespace DshComputerUse.Worker
5028
5514
  CheckHumanInput();
5029
5515
  Dictionary<string, object> clickOut = Dict("x", fp.X, "y", fp.Y, "positionCorrections", _positionCorrections, "focus", clickFocus);
5030
5516
  if (_lastRefocus != null) clickOut["refocused"] = _lastRefocus;
5517
+ if (checkedTarget != null) clickOut["targetCheck"] = checkedTarget;
5518
+ if (under != IntPtr.Zero) clickOut["actionHwnd"] = TopLevel(under).ToInt64();
5031
5519
  if (coveredBy != null) clickOut["coveredBy"] = coveredBy;
5032
5520
  if (under != IntPtr.Zero)
5033
5521
  clickOut["receiver"] = Short(WinTitleOf(under), 40) + " (pid " + PidOf(under) + ")";
@@ -5089,6 +5577,8 @@ namespace DshComputerUse.Worker
5089
5577
  int tx = GetI(a, "toX", int.MinValue), ty = GetI(a, "toY", int.MinValue);
5090
5578
  if (fx == int.MinValue || fy == int.MinValue || tx == int.MinValue || ty == int.MinValue)
5091
5579
  throw new Exception("fromX,fromY,toX,toY required");
5580
+ CheckScreenshotPoint(a, fx, fy);
5581
+ CheckScreenshotPoint(a, tx, ty);
5092
5582
  // both ends are input destinations - the button goes down under (fx,fy) and comes up
5093
5583
  // under (tx,ty) - so either one can be the host window
5094
5584
  HostGuardPoint(fx, fy, "drag");
@@ -5111,6 +5601,8 @@ namespace DshComputerUse.Worker
5111
5601
  IntPtr startWindow = CheckDragStart(a, startPoint.X, startPoint.Y);
5112
5602
  Dictionary<string, object> startCursor = CursorSnapshot();
5113
5603
  Dictionary<string, object> cursorCheck = CheckDragCursor(GetS(a, "expectCursor", ""), startCursor);
5604
+ CheckScreenshotPoint(a, fx, fy);
5605
+ CheckScreenshotPoint(a, tx, ty);
5114
5606
  using (GuardReceiver(startWindow, InputWindowPid(startWindow), false))
5115
5607
  SendMouse(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0);
5116
5608
  Thread.Sleep(80);
@@ -5148,6 +5640,8 @@ namespace DshComputerUse.Worker
5148
5640
 
5149
5641
  static Dictionary<string, object> Scroll(Dictionary<string, object> a)
5150
5642
  {
5643
+ int x = GetI(a, "x", 0), y = GetI(a, "y", 0);
5644
+ CheckScreenshotPoint(a, x, y);
5151
5645
  string dir = GetS(a, "direction", "down");
5152
5646
  int lines = Math.Max(1, Math.Min(30, GetI(a, "lines", 3)));
5153
5647
  uint flag = (dir == "left" || dir == "right") ? Native.MOUSEEVENTF_HWHEEL : Native.MOUSEEVENTF_WHEEL;
@@ -5163,12 +5657,13 @@ namespace DshComputerUse.Worker
5163
5657
  throw InputInterrupted("INPUT_TARGET_CHANGED", "Scroll receiver differs from the observed target. No wheel input was sent.");
5164
5658
  using (GuardReceiver(scrollTarget, InputWindowPid(scrollTarget), false)) {
5165
5659
  for (int i = 0; i < lines; i++) {
5660
+ CheckScreenshotPoint(a, x, y);
5166
5661
  SendMouse(flag, 0, 0, unchecked((uint)(sign * (int)Native.WHEEL_DELTA)));
5167
5662
  Thread.Sleep(25);
5168
5663
  }
5169
5664
  }
5170
5665
  POINT p; Native.GetCursorPos(out p);
5171
- return PtDict(p.X, p.Y);
5666
+ return Dict("x", p.X, "y", p.Y, "actionHwnd", TopLevel(scrollTarget).ToInt64());
5172
5667
  }
5173
5668
 
5174
5669
  // Physical ownership is checked before focus or input, for every action.
@@ -5201,7 +5696,8 @@ namespace DshComputerUse.Worker
5201
5696
  if (op == "click" || op == "move" || op == "drag" || op == "scroll" ||
5202
5697
  op == "key" || op == "type" || op == "selectRange" || op == "shiftClick" || op == "uiaAct")
5203
5698
  {
5204
- _lastRefocus = EnsureTargetForeground();
5699
+ _lastRefocus = GetB(a, "strictHwnd", false) || GetS(a, "shotGeometry", null) != null
5700
+ ? null : EnsureTargetForeground();
5205
5701
  }
5206
5702
  // Validation and focus readback do not own input. The first real mutation
5207
5703
  // or SendInput opens the actual scope and its deep-blue cue.
@@ -5409,7 +5905,12 @@ namespace DshComputerUse.Worker
5409
5905
  /// window look "changed".
5410
5906
  static byte[] FrameSignatureRect(int rx, int ry, int rw, int rh, int step)
5411
5907
  {
5412
- if (rw <= 16 || rh <= 16) return null;
5908
+ return rw <= 16 || rh <= 16 ? null : CaptureRegionSamples(rx, ry, rw, rh, step);
5909
+ }
5910
+
5911
+ static byte[] CaptureRegionSamples(int rx, int ry, int rw, int rh, int step)
5912
+ {
5913
+ if (rw <= 0 || rh <= 0) return null;
5413
5914
  IntPtr screen = Native.GetDC(IntPtr.Zero);
5414
5915
  IntPtr mem = Native.CreateCompatibleDC(screen);
5415
5916
  Native.BITMAPINFO bmi = new Native.BITMAPINFO();
@@ -5488,13 +5989,6 @@ namespace DshComputerUse.Worker
5488
5989
  /// FALLBACK (so a slow or never-quiet page can never stall the loop): a hard cap;
5489
5990
  /// when it trips we also extrapolate how much longer the screen *would* have needed,
5490
5991
  /// so the caller can decide to re-shoot instead of guessing blindly.
5491
- static bool SettleWait(int capMs, int stableMs, int pollMs, int step, double diffPct,
5492
- out int waitedMs, out double lastDiff, out int estimateMs)
5493
- {
5494
- return SettleSampleWait(capMs, stableMs, pollMs, diffPct, delegate { return FrameSignature(step); },
5495
- out waitedMs, out lastDiff, out estimateMs);
5496
- }
5497
-
5498
5992
  static bool SettleSampleWait(int capMs, int stableMs, int pollMs, double diffPct, Func<byte[]> sample,
5499
5993
  out int waitedMs, out double lastDiff, out int estimateMs)
5500
5994
  {
@@ -5538,35 +6032,37 @@ namespace DshComputerUse.Worker
5538
6032
 
5539
6033
  // Explicit window scope excludes unrelated desktop animation without loosening the
5540
6034
  // change threshold. A moved/minimized/replaced window invalidates the observation.
5541
- static Func<byte[]> WaitSampler(Dictionary<string, object> a, int step, out object scope,
6035
+ static WindowFrames OpenWaitSurface(Dictionary<string, object> args)
6036
+ {
6037
+ IntPtr h = new IntPtr(GetI(args, "hwnd", 0));
6038
+ if (h == IntPtr.Zero) return null;
6039
+ ValidateCaptureTarget(args, h);
6040
+ RECT r;
6041
+ if (ScreenshotGeometry(h, out r) == null) throw new Exception("WAIT_TARGET_UNAVAILABLE: window closed or minimized");
6042
+ return new WindowFrames(h, r);
6043
+ }
6044
+ static Func<byte[]> WaitSampler(Dictionary<string, object> a, WindowFrames frames, int step, out object scope,
5542
6045
  out int rx, out int ry, out int rw, out int rh)
5543
6046
  {
5544
- if (!a.ContainsKey("hwnd") || GetI(a, "hwnd", 0) == 0)
5545
- {
5546
- rx = Native.GetSystemMetrics(Native.SM_XVIRTUALSCREEN);
5547
- ry = Native.GetSystemMetrics(Native.SM_YVIRTUALSCREEN);
5548
- rw = Native.GetSystemMetrics(Native.SM_CXVIRTUALSCREEN);
5549
- rh = Native.GetSystemMetrics(Native.SM_CYVIRTUALSCREEN);
6047
+ if (frames == null) {
6048
+ rx = Native.GetSystemMetrics(Native.SM_XVIRTUALSCREEN); ry = Native.GetSystemMetrics(Native.SM_YVIRTUALSCREEN);
6049
+ rw = Native.GetSystemMetrics(Native.SM_CXVIRTUALSCREEN); rh = Native.GetSystemMetrics(Native.SM_CYVIRTUALSCREEN);
5550
6050
  scope = Dict("kind", "virtual-desktop", "region", Dict("x", rx, "y", ry, "width", rw, "height", rh));
5551
6051
  return delegate { return FrameSignature(step); };
5552
6052
  }
5553
- IntPtr h = new IntPtr(GetI(a, "hwnd", 0));
5554
- if (!Native.IsWindow(h) || Native.IsIconic(h))
5555
- throw new Exception("WAIT_TARGET_UNAVAILABLE: window is closed or minimized; restore/requery first");
5556
- RECT original; Native.GetWindowRect(h, out original);
5557
- uint pid = PidOf(h);
5558
- Rectangle virtualRect = SystemInformation.VirtualScreen;
5559
- Rectangle visible = Rectangle.Intersect(virtualRect, Rectangle.FromLTRB(original.Left, original.Top, original.Right, original.Bottom));
5560
- if (visible.Width <= 16 || visible.Height <= 16)
5561
- throw new Exception("WAIT_TARGET_UNAVAILABLE: window has no usable visible screen region");
5562
- rx = visible.X; ry = visible.Y; rw = visible.Width; rh = visible.Height;
5563
- scope = Dict("kind", "window", "hwnd", h.ToInt64(), "region", Dict("x", rx, "y", ry, "width", rw, "height", rh));
6053
+ IntPtr h = new IntPtr(GetI(a, "hwnd", 0)); RECT rect;
6054
+ string geometry = ScreenshotGeometry(h, out rect);
6055
+ if (geometry == null || rect.Left != frames.WindowBounds.Left || rect.Top != frames.WindowBounds.Top ||
6056
+ rect.Right != frames.WindowBounds.Right || rect.Bottom != frames.WindowBounds.Bottom)
6057
+ throw new Exception("WAIT_TARGET_CHANGED: window moved while opening capture");
6058
+ rx = frames.Bounds.Left; ry = frames.Bounds.Top; rw = frames.Bounds.Right-rx; rh = frames.Bounds.Bottom-ry;
6059
+ scope = Dict("kind", "window", "hwnd", h.ToInt64(), "captureBackend", "windows-graphics-capture",
6060
+ "region", Dict("x", rx, "y", ry, "width", rw, "height", rh));
5564
6061
  return delegate {
5565
- RECT current;
5566
- if (!Native.IsWindow(h) || Native.IsIconic(h) || PidOf(h) != pid || !Native.GetWindowRect(h, out current) ||
5567
- current.Left != original.Left || current.Top != original.Top || current.Right != original.Right || current.Bottom != original.Bottom)
6062
+ ValidateCaptureTarget(a, h);
6063
+ if (geometry == null || ScreenshotGeometry(h, out rect) != geometry)
5568
6064
  throw new Exception("WAIT_TARGET_CHANGED: window identity or bounds changed during sampling; requery before waiting again");
5569
- return FrameSignatureRect(visible.X, visible.Y, visible.Width, visible.Height, step);
6065
+ return frames.Sample();
5570
6066
  };
5571
6067
  }
5572
6068
 
@@ -5574,6 +6070,9 @@ namespace DshComputerUse.Worker
5574
6070
  /// threshold — "where did it change", not just "did it" (test report 2026-11-04: a
5575
6071
  /// 0.344% diff cannot distinguish a sent message from a blinking caret without this).
5576
6072
  static int[] SigDiffBounds(byte[] a, byte[] b, int threshold, int cols, int step, int rx, int ry)
6073
+ { return SampleDiffBounds(a, b, threshold, cols, step, rx, ry, 1); }
6074
+
6075
+ static int[] SampleDiffBounds(byte[] a, byte[] b, int threshold, int cols, int step, int rx, int ry, int channels)
5577
6076
  {
5578
6077
  if (a == null || b == null || a.Length != b.Length || cols <= 0) return null;
5579
6078
  int minX = -1, minY = -1, maxX = -1, maxY = -1;
@@ -5582,7 +6081,7 @@ namespace DshComputerUse.Worker
5582
6081
  int d = a[i] - b[i];
5583
6082
  if (d < 0) d = -d;
5584
6083
  if (d <= threshold) continue;
5585
- int c = i % cols, r = i / cols;
6084
+ int cell = i / channels, c = cell % cols, r = cell / cols;
5586
6085
  if (minX < 0 || c < minX) minX = c;
5587
6086
  if (c > maxX) maxX = c;
5588
6087
  if (minY < 0 || r < minY) minY = r;
@@ -5594,6 +6093,11 @@ namespace DshComputerUse.Worker
5594
6093
  }
5595
6094
 
5596
6095
  static Dictionary<string, object> WaitStable(Dictionary<string, object> a)
6096
+ {
6097
+ using (var frames = OpenWaitSurface(a)) return WaitStable(a, frames);
6098
+ }
6099
+
6100
+ static Dictionary<string, object> WaitStable(Dictionary<string, object> a, WindowFrames frames)
5597
6101
  {
5598
6102
  int capMs = Math.Max(400, GetI(a, "timeoutMs", 8000));
5599
6103
  int stableMs = Math.Max(150, GetI(a, "stableMs", 600));
@@ -5602,9 +6106,26 @@ namespace DshComputerUse.Worker
5602
6106
  double diffPct = GetD(a, "diffPct", 0.30);
5603
6107
  int waited, estimate; double lastDiff;
5604
6108
  int rx, ry, rw, rh;
5605
- object scope; Func<byte[]> sample = WaitSampler(a, step, out scope, out rx, out ry, out rw, out rh);
6109
+ if (frames != null) step = 4;
6110
+ object scope; Func<byte[]> sample = WaitSampler(a, frames, step, out scope, out rx, out ry, out rw, out rh);
6111
+ bool smallContinuous = true;
6112
+ int pairs = 0;
6113
+ if (frames != null) {
6114
+ var read = sample; byte[] previous = null;
6115
+ sample = delegate {
6116
+ var pixels = read();
6117
+ if (previous != null && smallContinuous) {
6118
+ double delta = SigDiffPct(previous, pixels, 8);
6119
+ smallContinuous = delta > 0 && delta < 1; pairs++;
6120
+ }
6121
+ previous = pixels; return pixels;
6122
+ };
6123
+ }
5606
6124
  bool ok = SettleSampleWait(capMs, stableMs, pollMs, diffPct, sample, out waited, out lastDiff, out estimate);
5607
- if (!ok)
6125
+ if (!ok && frames != null && waited >= 2400 && pairs >= 6 && smallContinuous)
6126
+ return Dict("stable", true, "waitedMs", waited, "lastDiffPct", Math.Round(lastDiff, 3),
6127
+ "scope", scope, "estimateMs", 0, "caretSteady", true, "note", "small continuous differences consistent with a blinking caret");
6128
+ if (!ok && frames == null)
5608
6129
  {
5609
6130
  // CARET / BLINK DETECTION (test report 2026-11-04): a blinking caret is a ~1-2 Hz
5610
6131
  // periodic sub-percent change that never settles — Notepad burned the full 8 s cap
@@ -5636,13 +6157,19 @@ namespace DshComputerUse.Worker
5636
6157
  }
5637
6158
 
5638
6159
  static Dictionary<string, object> WaitChange(Dictionary<string, object> a)
6160
+ {
6161
+ using (var frames = OpenWaitSurface(a)) return WaitChange(a, frames);
6162
+ }
6163
+
6164
+ static Dictionary<string, object> WaitChange(Dictionary<string, object> a, WindowFrames frames)
5639
6165
  {
5640
6166
  int timeoutMs = Math.Max(300, GetI(a, "timeoutMs", 6000));
5641
6167
  int pollMs = Math.Max(100, GetI(a, "pollMs", 220));
5642
6168
  int step = Math.Max(4, Math.Min(64, GetI(a, "step", 8)));
5643
6169
  double diffPct = GetD(a, "diffPct", 0.30);
5644
6170
  int rx, ry, rw, rh;
5645
- object scope; Func<byte[]> sample = WaitSampler(a, step, out scope, out rx, out ry, out rw, out rh);
6171
+ if (frames != null) step = 4;
6172
+ object scope; Func<byte[]> sample = WaitSampler(a, frames, step, out scope, out rx, out ry, out rw, out rh);
5646
6173
  byte[] first = sample();
5647
6174
  long t0 = NowMs();
5648
6175
  int samples = 0;
@@ -5657,10 +6184,14 @@ namespace DshComputerUse.Worker
5657
6184
  {
5658
6185
  // WHERE it changed (test report 2026-11-04): 0.344% cannot tell a sent
5659
6186
  // message from a caret blink; the bounding box can — input area vs caret.
5660
- int[] bounds = SigDiffBounds(first, cur, 8, cols, step, rx, ry);
6187
+ int[] bounds = SampleDiffBounds(first, cur, 8, cols, step, rx, ry, frames == null ? 1 : 3);
5661
6188
  Dictionary<string, object> hit = Dict("changed", true, "afterMs", NowMs() - t0,
5662
6189
  "diffPct", Math.Round(d, 3), "samples", samples, "scope", scope);
5663
- if (bounds != null) hit["changeBounds"] = Dict("x", bounds[0], "y", bounds[1], "width", bounds[2], "height", bounds[3]);
6190
+ if (bounds != null && frames != null) {
6191
+ bounds[2] = Math.Min(bounds[2], rx + rw - bounds[0]);
6192
+ bounds[3] = Math.Min(bounds[3], ry + rh - bounds[1]);
6193
+ }
6194
+ if (bounds != null) hit["changeBounds"] = Dict("x", bounds[0], "y", bounds[1], "width", bounds[2], "height", bounds[3]);
5664
6195
  return hit;
5665
6196
  }
5666
6197
  }
@@ -5830,6 +6361,7 @@ namespace DshComputerUse.Worker
5830
6361
  d["caps"] = 0x14; d["capslock"] = 0x14; d["apps"] = 0x5D;
5831
6362
  d["prtsc"] = 0x2C; d["printscreen"] = 0x2C; d["numlock"] = 0x90;
5832
6363
  d["plus"] = 0xBB; d["minus"] = 0xBD; d["comma"] = 0xBC; d["period"] = 0xBE;
6364
+ for (int i = 0; i <= 9; i++) d["numpad" + i] = (ushort)(0x60 + i);
5833
6365
  for (int i = 1; i <= 24; i++) d["f" + i] = (ushort)(0x6F + i);
5834
6366
  return d;
5835
6367
  }
@@ -5854,8 +6386,13 @@ namespace DshComputerUse.Worker
5854
6386
  foreach (string raw in combo.Split('+')) {
5855
6387
  string key = raw.Trim().ToLowerInvariant();
5856
6388
  if (key.Length == 0) throw new Exception("key combo contains an empty token; use plus for the + key");
6389
+ if ((key.StartsWith("kp_") || key.StartsWith("numpad_")) && key.Length == key.IndexOf('_') + 2 &&
6390
+ key[key.Length - 1] >= '0' && key[key.Length - 1] <= '9')
6391
+ key = "numpad" + key[key.Length - 1];
5857
6392
  switch (key) {
5858
- case "control": key = "ctrl"; break;
6393
+ case "shift_l": key = "shift"; break;
6394
+ case "alt_l": key = "alt"; break;
6395
+ case "control_l": case "control": key = "ctrl"; break;
5859
6396
  case "lwin": case "windows": case "meta": key = "win"; break;
5860
6397
  case "return": key = "enter"; break;
5861
6398
  case "escape": key = "esc"; break;
@@ -5914,6 +6451,11 @@ namespace DshComputerUse.Worker
5914
6451
  }
5915
6452
 
5916
6453
  static Dictionary<string, object> Key(Dictionary<string, object> a)
6454
+ {
6455
+ return KeyWithExpectedFocus(a, null);
6456
+ }
6457
+
6458
+ static Dictionary<string, object> KeyWithExpectedFocus(Dictionary<string, object> a, AutomationElement expectedField)
5917
6459
  {
5918
6460
  if (_receiverCheck != null) _receiverCheck(); // nested paste may not silently repair a stolen receiver
5919
6461
  string combo = GetS(a, "combo", null);
@@ -5935,7 +6477,7 @@ namespace DshComputerUse.Worker
5935
6477
  List<ushort> vks = new List<ushort>();
5936
6478
  foreach (string k in keys) { ushort vk = VkOf(k); if (!vks.Contains(vk)) vks.Add(vk); }
5937
6479
  bool windowManagement = WindowManagementChord.IsExact(combo);
5938
- using (GuardReceiver(new IntPtr(Convert.ToInt64(focus["hwnd"])), Convert.ToUInt32(focus["pid"]), true))
6480
+ using (GuardWindowReceiver(new IntPtr(Convert.ToInt64(focus["hwnd"])), Convert.ToUInt32(focus["pid"]), true, GetB(a, "strictHwnd", false)))
5939
6481
  {
5940
6482
  if (windowManagement)
5941
6483
  WindowManagementChord.Run(vks, SendKey, ReleaseKeyForCleanup,
@@ -5943,7 +6485,10 @@ namespace DshComputerUse.Worker
5943
6485
  delegate { WaitForKeyHold(Math.Max(20, GetI(a, "holdMs", 60))); },
5944
6486
  delegate { WaitForKeyHold(0); }, InvalidateKeyboardTarget);
5945
6487
  else
5946
- KeyboardChord.Run(vks, SendKey, ReleaseKeyForCleanup,
6488
+ KeyboardChord.Run(vks, delegate(ushort vk, bool up) {
6489
+ if (!up) RequireExpectedFocus(expectedField);
6490
+ SendKey(vk, up);
6491
+ }, ReleaseKeyForCleanup,
5947
6492
  delegate(ushort vk) { return (Native.GetAsyncKeyState(vk) & 0x8000) != 0; },
5948
6493
  delegate { WaitForKeyHold(Math.Max(20, GetI(a, "holdMs", 60))); });
5949
6494
  }
@@ -5974,9 +6519,16 @@ namespace DshComputerUse.Worker
5974
6519
  HostGuardNamed(a, "type");
5975
6520
  Dictionary<string, object> focus = FocusReport(a, true);
5976
6521
  HostGuardForeground("type"); // same rule as `key`: the foreground window is the victim
5977
- using (GuardReceiver(new IntPtr(Convert.ToInt64(focus["hwnd"])), Convert.ToUInt32(focus["pid"]), true)) {
6522
+ using (GuardWindowReceiver(new IntPtr(Convert.ToInt64(focus["hwnd"])), Convert.ToUInt32(focus["pid"]), true, GetB(a, "strictHwnd", false))) {
5978
6523
  // ...and whether whatever owns the focus can hold text at all. Typing into a control
5979
6524
  // with no editable pattern is silently discarded, or interpreted as shortcuts.
6525
+ string expectedToken = GetS(a, "expectTarget", null);
6526
+ AutomationElement expectedField = null;
6527
+ if (expectedToken != null) {
6528
+ string resolved; int scanned;
6529
+ expectedField = ResolveUiTarget(GetUiTarget(expectedToken), false, 6, 120, out resolved, out scanned);
6530
+ RequireExpectedFocus(expectedField);
6531
+ }
5980
6532
  string typeWarn = null;
5981
6533
  bool nonEditableButton = false;
5982
6534
  try
@@ -6003,6 +6555,8 @@ namespace DshComputerUse.Worker
6003
6555
  string mode = GetS(a, "mode", "unicode");
6004
6556
  if (mode == "paste")
6005
6557
  {
6558
+ var pasteKeys = Dict("combo", "ctrl+v", "holdMs", 40, "indicatorMs", 800);
6559
+ if (GetB(a, "strictHwnd", false)) { pasteKeys["strictHwnd"] = true; pasteKeys["expectHwnd"] = a["expectHwnd"]; }
6006
6560
  bool keep = GetB(a, "restoreClipboard", false);
6007
6561
  string restore = "not-requested";
6008
6562
  if (keep)
@@ -6021,7 +6575,7 @@ namespace DshComputerUse.Worker
6021
6575
  MarkMutation();
6022
6576
  Clipboard.SetDataObject(text, true);
6023
6577
  Thread.Sleep(60);
6024
- Key(Dict("combo", "ctrl+v", "holdMs", 40, "indicatorMs", 800));
6578
+ KeyWithExpectedFocus(pasteKeys, expectedField);
6025
6579
  Dictionary<string, object> downgraded = Dict("mode", "paste", "chars", text.Length, "focus", focus,
6026
6580
  "clipboardRestore", "skipped-unpreservable-clipboard");
6027
6581
  downgraded["clipboardWarning"] = "The previous clipboard could not be preserved (private or oversized formats) and was overwritten by this paste. Restore it manually if it mattered.";
@@ -6035,7 +6589,7 @@ namespace DshComputerUse.Worker
6035
6589
  Thread.Sleep(60);
6036
6590
  if (!lease.StillOwned())
6037
6591
  throw NotDispatched("CLIPBOARD_CHANGED", "CLIPBOARD_CHANGED: clipboard changed before paste; no paste keystrokes sent.");
6038
- Key(Dict("combo", "ctrl+v", "holdMs", 40, "indicatorMs", 800));
6592
+ KeyWithExpectedFocus(pasteKeys, expectedField);
6039
6593
  }
6040
6594
  catch (Exception error) { inputError = error; throw; }
6041
6595
  finally
@@ -6053,7 +6607,7 @@ namespace DshComputerUse.Worker
6053
6607
  MarkMutation();
6054
6608
  Clipboard.SetDataObject(text, true);
6055
6609
  Thread.Sleep(60);
6056
- Key(Dict("combo", "ctrl+v", "holdMs", 40, "indicatorMs", 800));
6610
+ KeyWithExpectedFocus(pasteKeys, expectedField);
6057
6611
  }
6058
6612
  Dictionary<string, object> pr = Dict("mode", "paste", "chars", text.Length, "focus", focus,
6059
6613
  "clipboardRestore", restore);
@@ -6067,6 +6621,7 @@ namespace DshComputerUse.Worker
6067
6621
  foreach (char ch in text)
6068
6622
  {
6069
6623
  if (ch == '\r') continue;
6624
+ RequireExpectedFocus(expectedField);
6070
6625
  if (ch == '\n') { SendKey(0x0D, false); SendKey(0x0D, true); Thread.Sleep(15); continue; }
6071
6626
  INPUT down = new INPUT();
6072
6627
  down.type = Native.INPUT_KEYBOARD;
@@ -6091,6 +6646,16 @@ namespace DshComputerUse.Worker
6091
6646
  return AddFocusReadback(tr, a, focus);
6092
6647
  }
6093
6648
  }
6649
+ static void RequireExpectedFocus(AutomationElement expected)
6650
+ {
6651
+ if (expected == null) return;
6652
+ try {
6653
+ var actual = AutomationElement.FocusedElement;
6654
+ if (actual != null && Automation.Compare(actual, expected)) return;
6655
+ } catch (ElementNotAvailableException) { }
6656
+ throw InputInterrupted("INPUT_FIELD_CHANGED", "The expected field no longer has focus; inspect the field before continuing.");
6657
+ }
6658
+
6094
6659
  static Dictionary<string, object> AddFocusReadback(Dictionary<string, object> result, Dictionary<string, object> args, Dictionary<string, object> before)
6095
6660
  {
6096
6661
  var after = FocusReport(args, false);
@@ -6234,8 +6799,85 @@ namespace DshComputerUse.Worker
6234
6799
  "minimized", Native.IsIconic(h));
6235
6800
  }
6236
6801
 
6802
+ static Dictionary<string, object> WindowOnDisplay(IntPtr hwnd)
6803
+ {
6804
+ var window = WinDict(hwnd);
6805
+ var screen = Screen.FromHandle(hwnd);
6806
+ var work = screen.WorkingArea;
6807
+ window["display"] = screen.DeviceName;
6808
+ window["workArea"] = Dict("x", work.X, "y", work.Y, "width", work.Width, "height", work.Height);
6809
+ return window;
6810
+ }
6811
+
6812
+ [StructLayout(LayoutKind.Sequential)]
6813
+ struct COMBOBOXINFO
6814
+ {
6815
+ public int cbSize; public RECT item, button; public uint buttonState;
6816
+ public IntPtr combo, edit, list;
6817
+ }
6818
+ [DllImport("user32.dll")] static extern bool GetComboBoxInfo(IntPtr combo, ref COMBOBOXINFO info);
6819
+
6820
+ static IntPtr FeedbackSurface(IntPtr owner)
6821
+ {
6822
+ IntPtr foreground = TopLevel(Native.GetForegroundWindow());
6823
+ IntPtr active = owner;
6824
+ if (IsEnabledOwnedPopup(owner, foreground)) active = foreground;
6825
+ else if (!Native.IsWindowEnabled(owner)) {
6826
+ var modal = Native.GetLastActivePopup(owner);
6827
+ if (IsEnabledOwnedPopup(owner, modal)) active = modal;
6828
+ }
6829
+ if (active != foreground) return active;
6830
+ uint pid; uint tid = Native.GetWindowThreadProcessId(active, out pid);
6831
+ var gui = new Native.GUITHREADINFO(); gui.cbSize = Marshal.SizeOf(typeof(Native.GUITHREADINFO));
6832
+ if (tid == 0 || !Native.GetGUIThreadInfo(tid, ref gui)) return active;
6833
+ if (gui.hwndMenuOwner != IntPtr.Zero && TopLevel(gui.hwndMenuOwner) == active) {
6834
+ IntPtr menu = IntPtr.Zero;
6835
+ Native.EnumWindows(delegate(IntPtr h, IntPtr unused) {
6836
+ uint process;
6837
+ if (Native.IsWindowVisible(h) && ClassOf(h) == "#32768" && Native.GetWindowThreadProcessId(h, out process) == tid) {
6838
+ menu = h; return false;
6839
+ }
6840
+ return true;
6841
+ }, IntPtr.Zero);
6842
+ if (menu != IntPtr.Zero) return menu;
6843
+ }
6844
+ for (IntPtr h = gui.hwndFocus; h != IntPtr.Zero && h != active && TopLevel(h) == active; h = Native.GetParent(h)) {
6845
+ var combo = new COMBOBOXINFO(); combo.cbSize = Marshal.SizeOf(typeof(COMBOBOXINFO));
6846
+ if (GetComboBoxInfo(h, ref combo) && combo.combo == h && Native.IsWindowVisible(combo.list)) return combo.list;
6847
+ }
6848
+ return active;
6849
+ }
6850
+
6851
+ static Dictionary<string, object> WindowDetails(IntPtr hwnd)
6852
+ {
6853
+ RECT r;
6854
+ if (!Native.IsWindow(hwnd) || !Native.GetWindowRect(hwnd, out r)) throw new Exception("WINDOW_UNAVAILABLE: observe windows again");
6855
+ var popups = new List<object>();
6856
+ Native.EnumWindows(delegate(IntPtr h, IntPtr unused) {
6857
+ if (IsEnabledOwnedPopup(hwnd, h)) popups.Add(WindowOnDisplay(h));
6858
+ return true;
6859
+ }, IntPtr.Zero);
6860
+ var samples = new List<object>();
6861
+ if (Native.IsWindowVisible(hwnd) && !Native.IsIconic(hwnd)) {
6862
+ foreach (int fx in new int[] { 1, 2, 3 }) foreach (int fy in new int[] { 1, 2, 3 }) {
6863
+ POINT p; p.X = r.Left + (r.Right-r.Left)*fx/4; p.Y = r.Top + (r.Bottom-r.Top)*fy/4;
6864
+ var hit = GetAncestor(Native.WindowFromPoint(p), 2);
6865
+ samples.Add(Dict("x", p.X, "y", p.Y, "receiver", hit.ToInt64(), "target", hit == hwnd));
6866
+ }
6867
+ }
6868
+ return Dict("window", WindowOnDisplay(hwnd), "ownedPopups", popups, "hitSamples", samples);
6869
+ }
6870
+
6237
6871
  static Dictionary<string, object> Windows(Dictionary<string, object> a)
6238
6872
  {
6873
+ if (a.ContainsKey("feedbackHwnd")) {
6874
+ IntPtr owner = TopLevel(new IntPtr(GetI(a, "feedbackHwnd", 0)));
6875
+ if (!Native.IsWindow(owner)) throw new Exception("WINDOW_UNAVAILABLE: feedback target closed");
6876
+ IntPtr target = FeedbackSurface(owner);
6877
+ return Dict("owner", owner.ToInt64(), "ownerTitle", WinTitleOf(owner), "target", WinDict(target), "popup", target != owner);
6878
+ }
6879
+ if (a.ContainsKey("inspectHwnd")) return WindowDetails(new IntPtr(GetI(a, "inspectHwnd", 0)));
6880
+ if (a.ContainsKey("appQuery")) return FindRegisteredApps(GetS(a, "appQuery", ""));
6239
6881
  uint self = (uint)System.Diagnostics.Process.GetCurrentProcess().Id;
6240
6882
  List<object> list = new List<object>();
6241
6883
  Native.EnumWindows(delegate(IntPtr h, IntPtr l)
@@ -6255,6 +6897,79 @@ namespace DshComputerUse.Worker
6255
6897
  "cooperation", Panic.CooperationState(), "indicator", IndicatorSnapshot());
6256
6898
  }
6257
6899
 
6900
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode)]
6901
+ static extern int GetApplicationUserModelId(IntPtr process, ref uint length, StringBuilder id);
6902
+
6903
+ static string ProcessAppId(uint pid)
6904
+ {
6905
+ IntPtr process = Native.OpenProcess(Native.PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
6906
+ if (process == IntPtr.Zero) return null;
6907
+ try {
6908
+ uint length = 512;
6909
+ var id = new StringBuilder((int)length);
6910
+ return GetApplicationUserModelId(process, ref length, id) == 0 ? id.ToString() : null;
6911
+ } catch (EntryPointNotFoundException) { return null; }
6912
+ finally { Native.CloseHandle(process); }
6913
+ }
6914
+
6915
+ static object ShellRead(object target, string member, params object[] args)
6916
+ {
6917
+ return target.GetType().InvokeMember(member, System.Reflection.BindingFlags.GetProperty |
6918
+ System.Reflection.BindingFlags.InvokeMethod, null, target, args);
6919
+ }
6920
+
6921
+ static void ReleaseShell(object obj)
6922
+ {
6923
+ if (obj != null && Marshal.IsComObject(obj)) Marshal.ReleaseComObject(obj);
6924
+ }
6925
+
6926
+ static Dictionary<string, object> FindRegisteredApps(string query)
6927
+ {
6928
+ query = query.Trim();
6929
+ if (query.Length < 1 || query.Length > 120) throw new Exception("appQuery requires 1 to 120 characters");
6930
+ var matches = new List<Dictionary<string, object>>();
6931
+ object shell = null, folder = null, items = null;
6932
+ bool truncated = false;
6933
+ try {
6934
+ shell = Activator.CreateInstance(System.Type.GetTypeFromProgID("Shell.Application", true));
6935
+ folder = ShellRead(shell, "NameSpace", "shell:AppsFolder");
6936
+ items = ShellRead(folder, "Items");
6937
+ int count = Convert.ToInt32(ShellRead(items, "Count"));
6938
+ for (int i = 0; i < count; i++) {
6939
+ object item = ShellRead(items, "Item", i);
6940
+ try {
6941
+ string name = Convert.ToString(ShellRead(item, "Name"));
6942
+ string id = Convert.ToString(ShellRead(item, "Path"));
6943
+ if (name.IndexOf(query, StringComparison.OrdinalIgnoreCase) < 0 && id.IndexOf(query, StringComparison.OrdinalIgnoreCase) < 0) continue;
6944
+ if (matches.Count >= 30) { truncated = true; break; }
6945
+ string target = Convert.ToString(ShellRead(item, "ExtendedProperty", "System.Link.TargetParsingPath"));
6946
+ matches.Add(Dict("name", name, "appId", id, "executable", target, "windows", new List<object>()));
6947
+ } finally { ReleaseShell(item); }
6948
+ }
6949
+ } finally { ReleaseShell(items); ReleaseShell(folder); ReleaseShell(shell); }
6950
+ var identities = new Dictionary<uint, string[]>();
6951
+ if (matches.Count > 0) Native.EnumWindows(delegate(IntPtr h, IntPtr unused) {
6952
+ if (!Native.IsWindowVisible(h)) return true;
6953
+ uint pid = PidOf(h);
6954
+ string[] identity;
6955
+ if (!identities.TryGetValue(pid, out identity)) {
6956
+ identity = new string[] { ProcessAppId(pid), ProcessImagePath(pid) };
6957
+ identities.Add(pid, identity);
6958
+ }
6959
+ foreach (var app in matches) {
6960
+ string via = null;
6961
+ if (!String.IsNullOrEmpty(identity[0])) {
6962
+ if (String.Equals(identity[0], (string)app["appId"], StringComparison.OrdinalIgnoreCase)) via = "appId";
6963
+ } else if (!String.IsNullOrEmpty(identity[1]) && String.Equals(identity[1], (string)app["executable"], StringComparison.OrdinalIgnoreCase)) via = "executable";
6964
+ if (via == null) continue;
6965
+ var window = WinDict(h); window["matchBy"] = via;
6966
+ ((List<object>)app["windows"]).Add(window);
6967
+ }
6968
+ return true;
6969
+ }, IntPtr.Zero);
6970
+ return Dict("apps", matches, "truncated", truncated, "source", "shell:AppsFolder", "windowScope", "visible top-level windows");
6971
+ }
6972
+
6258
6973
  static string IndicatorStateName(int want)
6259
6974
  {
6260
6975
  switch (want) {
@@ -6326,6 +7041,17 @@ namespace DshComputerUse.Worker
6326
7041
  throw new Exception(msg.ToString());
6327
7042
  }
6328
7043
 
7044
+ static bool IsEnabledOwnedPopup(IntPtr owner, IntPtr popup)
7045
+ {
7046
+ if (popup == IntPtr.Zero || popup == owner || !Native.IsWindowVisible(popup) || !Native.IsWindowEnabled(popup)) return false;
7047
+ IntPtr h = popup;
7048
+ for (int depth = 0; depth < 32 && h != IntPtr.Zero; depth++) {
7049
+ h = Native.GetWindow(h, 4); // GW_OWNER
7050
+ if (h == owner) return true;
7051
+ }
7052
+ return false;
7053
+ }
7054
+
6329
7055
  static Dictionary<string, object> Activate(Dictionary<string, object> a)
6330
7056
  {
6331
7057
  IntPtr h = FindHwnd(a);
@@ -6334,7 +7060,16 @@ namespace DshComputerUse.Worker
6334
7060
  AgentActing(a, "activate");
6335
7061
  // The whole ladder now lives in RefocusWindow (shared with the keyboard focus
6336
7062
  // guard, which must re-assert the same window before typing).
6337
- string how = RefocusWindow(h, GetB(a, "clickFallback", true));
7063
+ IntPtr receiver = h;
7064
+ if (!Native.IsWindowEnabled(h)) {
7065
+ receiver = Native.GetForegroundWindow();
7066
+ if (!IsEnabledOwnedPopup(h, receiver)) receiver = Native.GetLastActivePopup(h);
7067
+ if (!IsEnabledOwnedPopup(h, receiver)) receiver = Native.GetWindow(h, 6); // GW_ENABLEDPOPUP
7068
+ if (!IsEnabledOwnedPopup(h, receiver))
7069
+ return Dict("activated", false, "hwnd", h.ToInt64(), "hint", "Window is disabled. Observe its current dialog before activating.");
7070
+ HostGuard(receiver, "activate");
7071
+ }
7072
+ string how = RefocusWindow(receiver, GetB(a, "clickFallback", true));
6338
7073
  uint confirmedPid = 0;
6339
7074
  long modalOf = 0;
6340
7075
  IntPtr foreground = Native.GetForegroundWindow();
@@ -6343,7 +7078,8 @@ namespace DshComputerUse.Worker
6343
7078
  // refused while the app was literally waiting for an answer.
6344
7079
  IntPtr dialog = (foreground != IntPtr.Zero && foreground != h && SameInputFamily(h, foreground)) ? foreground : IntPtr.Zero;
6345
7080
  IntPtr confirmed = dialog != IntPtr.Zero ? dialog : h;
6346
- if (how == null || !Native.IsWindow(h) || (confirmedPid = PidOf(confirmed)) == 0 || !IsForeground(confirmed)) how = "failed";
7081
+ if (how == null || !Native.IsWindow(h) || (receiver != h && (confirmed != receiver || !IsEnabledOwnedPopup(h, confirmed))) ||
7082
+ (confirmedPid = PidOf(confirmed)) == 0 || !IsForeground(confirmed)) how = "failed";
6347
7083
  else
6348
7084
  {
6349
7085
  if (dialog != IntPtr.Zero) modalOf = h.ToInt64();
@@ -7280,13 +8016,16 @@ namespace DshComputerUse.Worker
7280
8016
 
7281
8017
  string repaired = null;
7282
8018
  IntPtr fg = Native.GetForegroundWindow();
7283
- if (refocus && want != IntPtr.Zero && TopLevel(fg) != want)
8019
+ bool exact = GetB(a, "strictHwnd", false) || GetS(a, "shotGeometry", null) != null;
8020
+ if (refocus && exact && (!Native.IsWindowEnabled(want) || want != GetAncestor(fg, 2)))
8021
+ throw InputInterrupted("INPUT_TARGET_CHANGED", "The explicitly named window is no longer foreground. Observe the receiver again.");
8022
+ if (refocus && !exact && want != IntPtr.Zero && TopLevel(fg) != want)
7284
8023
  {
7285
8024
  repaired = RefocusWindow(want, true);
7286
8025
  Thread.Sleep(50);
7287
8026
  fg = Native.GetForegroundWindow();
7288
8027
  }
7289
- IntPtr root = TopLevel(fg);
8028
+ IntPtr root = exact ? GetAncestor(fg, 2) : TopLevel(fg);
7290
8029
  if (refocus)
7291
8030
  {
7292
8031
  string mismatch = KickoffFocus.InputProblem(want.ToInt64(),
@@ -7442,6 +8181,26 @@ namespace DshComputerUse.Worker
7442
8181
  case "move":
7443
8182
  {
7444
8183
  RECT cur; Native.GetWindowRect(h, out cur);
8184
+ if (a.ContainsKey("workHwnd")) {
8185
+ var anchor = new IntPtr(GetI(a, "workHwnd", 0));
8186
+ if (!Native.IsWindowVisible(anchor) || Native.IsIconic(anchor) || Native.IsIconic(h) || IsZoomed(h))
8187
+ throw new Exception("WORK_AREA_UNAVAILABLE: observe a visible work window and a restored target");
8188
+ var screen = Screen.FromHandle(anchor);
8189
+ var area = screen.WorkingArea;
8190
+ Rectangle actual = Rectangle.FromLTRB(cur.Left, cur.Top, cur.Right, cur.Bottom);
8191
+ bool moved = !area.Contains(actual);
8192
+ if (moved) {
8193
+ int width = Math.Min(area.Width, actual.Width), height = Math.Min(area.Height, actual.Height);
8194
+ int x = area.Left + (area.Width - width)/2, y = area.Top + (area.Height - height)/2;
8195
+ if (!Native.SetWindowPos(h, IntPtr.Zero, x, y, width, height, 0x0004 | 0x0010))
8196
+ throw new Exception("WINDOW_PLACEMENT_FAILED: inspect the current window rectangle");
8197
+ Thread.Sleep(140);
8198
+ }
8199
+ RECT after;
8200
+ if (!Native.GetWindowRect(h, out after)) throw new Exception("WINDOW_UNAVAILABLE: moved window disappeared");
8201
+ bool contained = area.Contains(Rectangle.FromLTRB(after.Left, after.Top, after.Right, after.Bottom));
8202
+ return Dict("done", "move", "ok", contained, "moved", moved, "contained", contained, "display", screen.DeviceName, "rect", RectDict(after));
8203
+ }
7445
8204
  int mx = GetI(a, "x", cur.Left), my = GetI(a, "y", cur.Top);
7446
8205
  int mw = GetI(a, "width", cur.Right - cur.Left), mh = GetI(a, "height", cur.Bottom - cur.Top);
7447
8206
  if (Native.IsIconic(h)) Native.ShowWindow(h, Native.SW_RESTORE);
@@ -7457,6 +8216,9 @@ namespace DshComputerUse.Worker
7457
8216
  return Dict("done", op);
7458
8217
  }
7459
8218
 
8219
+ [DllImport("user32.dll")]
8220
+ static extern bool IsZoomed(IntPtr hwnd);
8221
+
7460
8222
  // ---------- UIA ----------
7461
8223
  static void AddUiGeometry(Dictionary<string, object> d, System.Windows.Rect? bounds,
7462
8224
  bool? offscreen, Rectangle virtualScreen)
@@ -7684,8 +8446,53 @@ namespace DshComputerUse.Worker
7684
8446
  return d;
7685
8447
  }
7686
8448
 
8449
+ static Dictionary<string, object> FocusedText(IntPtr hwnd)
8450
+ {
8451
+ if (hwnd == IntPtr.Zero || GetAncestor(Native.GetForegroundWindow(), 2) != hwnd)
8452
+ throw new Exception("FOCUS_CHANGED: name the current foreground window");
8453
+ AutomationElement focus = AutomationElement.FocusedElement;
8454
+ AutomationElement root = AutomationElement.FromHandle(hwnd);
8455
+ AutomationElement ancestor = focus;
8456
+ for (int i = 0; i < 48 && ancestor != null && !Automation.Compare(ancestor, root); i++)
8457
+ ancestor = TreeWalker.RawViewWalker.GetParent(ancestor);
8458
+ if (ancestor == null || !Automation.Compare(ancestor, root))
8459
+ throw new Exception("FOCUS_CHANGED: the focused control is outside the named window");
8460
+ object password = focus.GetCurrentPropertyValue(AutomationElement.IsPasswordProperty, true);
8461
+ if (!(password is bool) || (bool)password) return Dict("hwnd", hwnd.ToInt64(), "textStatus", "protected-or-unknown");
8462
+ const int max = 2048;
8463
+ var result = Dict("hwnd", hwnd.ToInt64(), "id", focus.Current.AutomationId, "role", focus.Current.ControlType.ProgrammaticName,
8464
+ "selectionStatus", "unavailable", "textStatus", "unavailable");
8465
+ object pattern;
8466
+ string value = null;
8467
+ if (focus.TryGetCurrentPattern(TextPattern.Pattern, out pattern)) {
8468
+ var text = (TextPattern)pattern;
8469
+ value = text.DocumentRange.GetText(max + 1);
8470
+ if (text.SupportedTextSelection != SupportedTextSelection.None) {
8471
+ var ranges = text.GetSelection();
8472
+ var selections = new List<string>();
8473
+ bool truncated = ranges.Length > 8;
8474
+ foreach (var range in ranges.Take(8)) {
8475
+ string part = range.GetText(max + 1);
8476
+ truncated |= part.Length > max;
8477
+ selections.Add(part.Substring(0, Math.Min(max, part.Length)));
8478
+ }
8479
+ result["selections"] = selections;
8480
+ result["selectionStatus"] = truncated ? "truncated" : "read";
8481
+ }
8482
+ } else if (focus.TryGetCurrentPattern(ValuePattern.Pattern, out pattern)) value = ((ValuePattern)pattern).Current.Value;
8483
+ if (value != null) {
8484
+ result["value"] = value.Substring(0, Math.Min(value.Length, max));
8485
+ result["textStatus"] = value.Length > max ? "truncated" : "read";
8486
+ }
8487
+ var current = AutomationElement.FocusedElement;
8488
+ if (GetAncestor(Native.GetForegroundWindow(), 2) != hwnd || current == null || !Automation.Compare(current, focus))
8489
+ throw new Exception("FOCUS_CHANGED: capture the focused field again");
8490
+ return result;
8491
+ }
8492
+
7687
8493
  static Dictionary<string, object> Uia(Dictionary<string, object> a)
7688
8494
  {
8495
+ if (GetB(a, "focused", false)) return FocusedText(new IntPtr(GetI(a, "hwnd", 0)));
7689
8496
  IntPtr root = FindHwnd(a);
7690
8497
  int maxDepth = Math.Max(1, Math.Min(24, GetI(a, "depth", 6)));
7691
8498
  int maxNodes = Math.Max(10, Math.Min(1200, GetI(a, "maxNodes", 120)));
@@ -7925,6 +8732,30 @@ namespace DshComputerUse.Worker
7925
8732
  return matches;
7926
8733
  }
7927
8734
 
8735
+ static TextPatternRange SelectExactText(TextPattern pattern, string value, string prefix, string suffix)
8736
+ {
8737
+ if (String.IsNullOrEmpty(value)) throw new Exception("selectText requires nonempty text in value");
8738
+ if (pattern.SupportedTextSelection == SupportedTextSelection.None)
8739
+ throw new Exception("Text selection is unavailable on this control.");
8740
+ var document = pattern.DocumentRange;
8741
+ string needle = prefix + value + suffix;
8742
+ var match = document.FindText(needle, false, false);
8743
+ if (match == null) throw new Exception("TEXT_NOT_FOUND: no matching passage in this control");
8744
+ var rest = document.Clone();
8745
+ rest.MoveEndpointByRange(TextPatternRangeEndpoint.Start, match, TextPatternRangeEndpoint.Start);
8746
+ if (rest.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 1) != 1 ||
8747
+ rest.FindText(needle, false, false) != null)
8748
+ throw new Exception("AMBIGUOUS_TEXT: supply more adjacent prefix or suffix text");
8749
+ if (prefix.Length > 0)
8750
+ match.MoveEndpointByRange(TextPatternRangeEndpoint.Start, match.FindText(prefix, false, false), TextPatternRangeEndpoint.End);
8751
+ if (suffix.Length > 0)
8752
+ match.MoveEndpointByRange(TextPatternRangeEndpoint.End, match.FindText(suffix, true, false), TextPatternRangeEndpoint.Start);
8753
+ if (match.GetText(value.Length + 1) != value) throw new Exception("TEXT_CHANGED: query the passage again");
8754
+ MarkMutation();
8755
+ match.Select();
8756
+ return match;
8757
+ }
8758
+
7928
8759
  static Dictionary<string, object> UiaAct(Dictionary<string, object> a)
7929
8760
  {
7930
8761
  string action = GetS(a, "action", "invoke");
@@ -7983,6 +8814,8 @@ namespace DshComputerUse.Worker
7983
8814
 
7984
8815
  object pat = null;
7985
8816
  string via = null;
8817
+ TextPatternRange selectedRange = null;
8818
+ double beforeScrollPercent = 0;
7986
8819
  switch (action)
7987
8820
  {
7988
8821
  case "invoke":
@@ -7991,6 +8824,22 @@ namespace DshComputerUse.Worker
7991
8824
  case "select":
7992
8825
  if (found.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pat)) { MarkMutation(); ((SelectionItemPattern)pat).Select(); via = "SelectionItemPattern"; }
7993
8826
  break;
8827
+ case "addToSelection":
8828
+ case "removeFromSelection":
8829
+ if (found.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pat)) {
8830
+ var item = (SelectionItemPattern)pat;
8831
+ MarkMutation();
8832
+ if (action == "addToSelection") item.AddToSelection(); else item.RemoveFromSelection();
8833
+ via = "SelectionItemPattern." + action;
8834
+ }
8835
+ break;
8836
+ case "selectText":
8837
+ if (found.Current.IsPassword) throw new Exception("selectText is unavailable on password controls");
8838
+ if (found.TryGetCurrentPattern(TextPattern.Pattern, out pat)) {
8839
+ selectedRange = SelectExactText((TextPattern)pat, GetS(a, "value", ""), GetS(a, "prefix", "") ?? "", GetS(a, "suffix", "") ?? "");
8840
+ via = "TextPattern.Select";
8841
+ }
8842
+ break;
7994
8843
  case "expand":
7995
8844
  if (found.TryGetCurrentPattern(ExpandCollapsePattern.Pattern, out pat)) { MarkMutation(); ((ExpandCollapsePattern)pat).Expand(); via = "ExpandCollapsePattern.Expand"; }
7996
8845
  break;
@@ -8004,6 +8853,15 @@ namespace DshComputerUse.Worker
8004
8853
  {
8005
8854
  string val = GetS(a, "value", "");
8006
8855
  if (found.TryGetCurrentPattern(ValuePattern.Pattern, out pat)) { MarkMutation(); ((ValuePattern)pat).SetValue(val); via = "ValuePattern"; }
8856
+ else if (found.TryGetCurrentPattern(RangeValuePattern.Pattern, out pat)) {
8857
+ var range = (RangeValuePattern)pat;
8858
+ double number;
8859
+ if (!Double.TryParse(val, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out number) ||
8860
+ Double.IsNaN(number) || Double.IsInfinity(number) || number < range.Current.Minimum || number > range.Current.Maximum)
8861
+ throw new Exception("RANGE_VALUE_INVALID: supply a finite value within the control's range");
8862
+ if (range.Current.IsReadOnly) throw new Exception("RANGE_VALUE_READ_ONLY");
8863
+ MarkMutation(); range.SetValue(number); via = "RangeValuePattern";
8864
+ }
8007
8865
  break;
8008
8866
  }
8009
8867
  case "focus":
@@ -8011,8 +8869,22 @@ namespace DshComputerUse.Worker
8011
8869
  case "scrollIntoView":
8012
8870
  if (found.TryGetCurrentPattern(ScrollItemPattern.Pattern, out pat)) { MarkMutation(); ((ScrollItemPattern)pat).ScrollIntoView(); via = "ScrollItemPattern"; }
8013
8871
  break;
8872
+ case "scroll":
8873
+ if (found.TryGetCurrentPattern(ScrollPattern.Pattern, out pat)) {
8874
+ var scroll = (ScrollPattern)pat;
8875
+ string direction = GetS(a, "value", "");
8876
+ bool horizontal = direction == "left" || direction == "right";
8877
+ if (!horizontal && direction != "up" && direction != "down") throw new Exception("scroll value must be up, down, left or right");
8878
+ if (horizontal ? !scroll.Current.HorizontallyScrollable : !scroll.Current.VerticallyScrollable)
8879
+ throw new Exception("SCROLL_AXIS_UNAVAILABLE: select a scrollable container for this axis");
8880
+ var amount = direction == "up" || direction == "left" ? ScrollAmount.LargeDecrement : ScrollAmount.LargeIncrement;
8881
+ beforeScrollPercent = horizontal ? scroll.Current.HorizontalScrollPercent : scroll.Current.VerticalScrollPercent;
8882
+ MarkMutation(); scroll.Scroll(horizontal ? amount : ScrollAmount.NoAmount, horizontal ? ScrollAmount.NoAmount : amount);
8883
+ via = "ScrollPattern";
8884
+ }
8885
+ break;
8014
8886
  default:
8015
- throw new Exception("action must be invoke|select|expand|collapse|toggle|setValue|focus|scrollIntoView");
8887
+ throw new Exception("action must be invoke|select|addToSelection|removeFromSelection|selectText|expand|collapse|toggle|setValue|focus|scrollIntoView");
8016
8888
  }
8017
8889
  EndActuationForReadback();
8018
8890
  if (via == null)
@@ -8020,6 +8892,20 @@ namespace DshComputerUse.Worker
8020
8892
 
8021
8893
  Thread.Sleep(GetI(a, "settleMs", 120));
8022
8894
  Dictionary<string, object> res = Dict("action", action, "via", via, "element", ElemDict(found), "scanned", seen);
8895
+ try {
8896
+ if (via == "ScrollPattern") {
8897
+ var scroll = ((ScrollPattern)pat).Current;
8898
+ string direction = GetS(a, "value", "");
8899
+ res["beforePercent"] = beforeScrollPercent;
8900
+ res["afterPercent"] = direction == "left" || direction == "right" ? scroll.HorizontalScrollPercent : scroll.VerticalScrollPercent;
8901
+ } else if (selectedRange != null) {
8902
+ var selected = ((TextPattern)pat).GetSelection();
8903
+ res["selectionVerified"] = selected.Length == 1 && selected[0].Compare(selectedRange);
8904
+ } else if (via == "RangeValuePattern") res["rangeValue"] = ((RangeValuePattern)pat).Current.Value;
8905
+ else if (action == "addToSelection" || action == "removeFromSelection")
8906
+ res["isSelected"] = ((SelectionItemPattern)pat).Current.IsSelected;
8907
+ } catch (InvalidOperationException) { res["readbackUnavailable"] = true; }
8908
+ catch (System.Runtime.InteropServices.COMException) { res["readbackUnavailable"] = true; }
8023
8909
  if (observed != null) res["resolution"] = Dict("target", token, "mode", resolution, "rebound", resolution != "runtime-id");
8024
8910
  if (skipped.Count > 0) res["skippedEarlierMatches"] = skipped;
8025
8911
  return res;
@@ -8250,6 +9136,7 @@ namespace DshComputerUse.Worker
8250
9136
  // Compatibility entry point: no coordinate/frequency/quietMs override can
8251
9137
  // disable the event-driven handoff. Plain Esc and the screen corner are ordinary UI.
8252
9138
  CheckHumanInput();
9139
+ lastCaptureKey = null; lastCaptureSample = null;
8253
9140
  Panic.AgentActed();
8254
9141
  }
8255
9142