dsh-codex-style-computer-use 2.3.0 → 2.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/README.zh.md +1 -0
- package/lib/argument-recovery.js +50 -0
- package/lib/core/bin/dsh-computer-use-worker.exe +0 -0
- package/lib/core/bin/dsh-computer-use-worker.exe.json +2 -2
- package/lib/core/index.js +18 -2
- package/lib/core/worker.cs +972 -121
- package/lib/image-output.js +24 -66
- package/lib/index.js +3 -0
- package/lib/key-command.js +3 -3
- package/lib/tools.js +253 -82
- package/mcp/src/tools.js +5 -2
- package/package.json +2 -2
- package/scripts/check-behavior.mjs +2 -1
- package/skills/computer-use/SKILL.md +30 -2
- package/skills/computer-use/scripts/inspect-borrow.py +113 -0
package/lib/core/worker.cs
CHANGED
|
@@ -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
|
-
|
|
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);
|
|
@@ -4410,9 +4549,41 @@ 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
|
-
|
|
4414
|
-
|
|
4415
|
-
|
|
4552
|
+
return RecognizePixels(bgra, x, y, w, h);
|
|
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
|
+
if (w <= 0 || h <= 0 || x < r.Left || y < r.Top || (long)x+w > r.Right || (long)y+h > r.Bottom ||
|
|
4565
|
+
(long)w*h > 16L*1024*1024) throw new Exception("OCR region must fit inside the window surface and within 16M pixels");
|
|
4566
|
+
frames.Sample();
|
|
4567
|
+
byte[] pixels = frames.Pixels;
|
|
4568
|
+
if (x != r.Left || y != r.Top || w != r.Right-r.Left || h != r.Bottom-r.Top) {
|
|
4569
|
+
pixels = new byte[checked(w*h*4)];
|
|
4570
|
+
for (int i = 0; i < h; i++) Buffer.BlockCopy(frames.Pixels,
|
|
4571
|
+
((y-r.Top+i)*(r.Right-r.Left)+x-r.Left)*4, pixels, i*w*4, w*4);
|
|
4572
|
+
}
|
|
4573
|
+
var result = RecognizePixels(pixels, x, y, w, h);
|
|
4574
|
+
ValidateCaptureTarget(args, window);
|
|
4575
|
+
if (ScreenshotGeometry(window, out bounds) != geometry) throw new Exception("OCR_TARGET_CHANGED: observe this window again");
|
|
4576
|
+
result["hwnd"] = window.ToInt64(); result["captureBackend"] = "windows-graphics-capture";
|
|
4577
|
+
return result;
|
|
4578
|
+
}
|
|
4579
|
+
}
|
|
4580
|
+
|
|
4581
|
+
static Dictionary<string, object> RecognizePixels(byte[] bgra, int x, int y, int w, int h)
|
|
4582
|
+
{
|
|
4583
|
+
OcrResult result;
|
|
4584
|
+
using (SoftwareBitmap bitmap = SoftwareBitmap.CreateCopyFromBuffer(
|
|
4585
|
+
WindowsRuntimeBufferExtensions.AsBuffer(bgra), BitmapPixelFormat.Bgra8, w, h))
|
|
4586
|
+
result = _ocrEngine.RecognizeAsync(bitmap).AsTask().GetAwaiter().GetResult();
|
|
4416
4587
|
List<object> lines = new List<object>();
|
|
4417
4588
|
StringBuilder joined = new StringBuilder();
|
|
4418
4589
|
foreach (OcrLine line in result.Lines)
|
|
@@ -4432,16 +4603,240 @@ namespace DshComputerUse.Worker
|
|
|
4432
4603
|
"region", new int[] { x, y, w, h });
|
|
4433
4604
|
}
|
|
4434
4605
|
|
|
4606
|
+
[DllImport("user32.dll")]
|
|
4607
|
+
static extern IntPtr GetAncestor(IntPtr window, uint flags);
|
|
4608
|
+
|
|
4609
|
+
static string ScreenshotGeometry(IntPtr window, out RECT bounds)
|
|
4610
|
+
{
|
|
4611
|
+
bounds = new RECT();
|
|
4612
|
+
if (!Native.IsWindowVisible(window) || Native.IsIconic(window) || !Native.GetWindowRect(window, out bounds) ||
|
|
4613
|
+
bounds.Right <= bounds.Left || bounds.Bottom <= bounds.Top) return null;
|
|
4614
|
+
uint dpi = 0;
|
|
4615
|
+
try { dpi = Native.GetDpiForWindow(window); } catch (EntryPointNotFoundException) { }
|
|
4616
|
+
return String.Join(",", new object[] { window.ToInt64(), PidOf(window), bounds.Left, bounds.Top,
|
|
4617
|
+
bounds.Right, bounds.Bottom, dpi, Native.GetSystemMetrics(Native.SM_XVIRTUALSCREEN),
|
|
4618
|
+
Native.GetSystemMetrics(Native.SM_YVIRTUALSCREEN), Native.GetSystemMetrics(Native.SM_CXVIRTUALSCREEN),
|
|
4619
|
+
Native.GetSystemMetrics(Native.SM_CYVIRTUALSCREEN) });
|
|
4620
|
+
}
|
|
4621
|
+
|
|
4622
|
+
sealed class ClickControl
|
|
4623
|
+
{
|
|
4624
|
+
public System.Windows.Rect Rect;
|
|
4625
|
+
public string RuntimeId, Name, Id;
|
|
4626
|
+
public int Role;
|
|
4627
|
+
public static ClickControl Read(AutomationElement e)
|
|
4628
|
+
{
|
|
4629
|
+
var c = e.Cached;
|
|
4630
|
+
var type = c.ControlType;
|
|
4631
|
+
if (type != ControlType.Button && type != ControlType.Hyperlink && type != ControlType.CheckBox &&
|
|
4632
|
+
type != ControlType.RadioButton && type != ControlType.MenuItem && type != ControlType.TabItem &&
|
|
4633
|
+
type != ControlType.ListItem && type != ControlType.ComboBox) return null;
|
|
4634
|
+
var ids = e.GetRuntimeId(); var rect = c.BoundingRectangle;
|
|
4635
|
+
if (!c.IsEnabled || c.IsOffscreen || ids == null || ids.Length == 0 || rect.IsEmpty || rect.Width <= 0 || rect.Height <= 0) return null;
|
|
4636
|
+
return new ClickControl { Rect = rect, Role = type.Id, Name = c.Name, Id = c.AutomationId,
|
|
4637
|
+
RuntimeId = String.Join(".", ids) };
|
|
4638
|
+
}
|
|
4639
|
+
public bool Same(ClickControl other)
|
|
4640
|
+
{
|
|
4641
|
+
return other != null && RuntimeId == other.RuntimeId && Id == other.Id && Role == other.Role &&
|
|
4642
|
+
Name == other.Name && Rect == other.Rect;
|
|
4643
|
+
}
|
|
4644
|
+
}
|
|
4645
|
+
// A slow UIA provider must not hold the screenshot worker. At most one provider scan
|
|
4646
|
+
// is outstanding. Pixel evidence remains available if there is no usable control.
|
|
4647
|
+
static int witnessProviderBusy;
|
|
4648
|
+
static Task<T> StartWitnessRead<T>(Func<T> query) where T : class
|
|
4649
|
+
{
|
|
4650
|
+
if (Interlocked.CompareExchange(ref witnessProviderBusy, 1, 0) != 0) return null;
|
|
4651
|
+
return Task.Run(delegate {
|
|
4652
|
+
try { return query(); } catch { return null; }
|
|
4653
|
+
finally { Interlocked.Exchange(ref witnessProviderBusy, 0); }
|
|
4654
|
+
});
|
|
4655
|
+
}
|
|
4656
|
+
static CacheRequest WitnessCache()
|
|
4657
|
+
{
|
|
4658
|
+
var cache = UiSelectorCache(); cache.Add(AutomationElement.BoundingRectangleProperty);
|
|
4659
|
+
cache.Add(AutomationElement.IsEnabledProperty); cache.Add(AutomationElement.IsOffscreenProperty); return cache;
|
|
4660
|
+
}
|
|
4661
|
+
static List<ClickControl> ReadClickControls(IntPtr window)
|
|
4662
|
+
{
|
|
4663
|
+
var result = new List<ClickControl>(); var cache = WitnessCache();
|
|
4664
|
+
var root = AutomationElement.FromHandle(window);
|
|
4665
|
+
UiWalkBounded(root, 5, 72, 73, new UiReadBudget(120, UiClockMs),
|
|
4666
|
+
delegate(AutomationElement e) {
|
|
4667
|
+
if (e != root) try { var c = ClickControl.Read(e); if (c != null) result.Add(c); } catch (ElementNotAvailableException) { }
|
|
4668
|
+
return false;
|
|
4669
|
+
}, delegate(AutomationElement e) { return TreeWalker.ControlViewWalker.GetFirstChild(e, cache); },
|
|
4670
|
+
delegate(AutomationElement e) { return TreeWalker.ControlViewWalker.GetNextSibling(e, cache); });
|
|
4671
|
+
return result;
|
|
4672
|
+
}
|
|
4673
|
+
static ClickControl ControlAt(int x, int y)
|
|
4674
|
+
{
|
|
4675
|
+
var cache = WitnessCache();
|
|
4676
|
+
using (cache.Activate()) {
|
|
4677
|
+
var e = AutomationElement.FromPoint(new System.Windows.Point(x, y));
|
|
4678
|
+
for (int depth = 0; e != null && depth < 5; depth++) {
|
|
4679
|
+
var c = ClickControl.Read(e); if (c != null) return c;
|
|
4680
|
+
e = TreeWalker.ControlViewWalker.GetParent(e, cache);
|
|
4681
|
+
}
|
|
4682
|
+
}
|
|
4683
|
+
return null;
|
|
4684
|
+
}
|
|
4685
|
+
|
|
4686
|
+
sealed class ClickWitness
|
|
4687
|
+
{
|
|
4688
|
+
public string Id, Geometry;
|
|
4689
|
+
public RECT Bounds;
|
|
4690
|
+
public byte[] Pixels, InitialPixels; // cursor-free RGB, one sample every four physical pixels
|
|
4691
|
+
public int Bytes { get { return Pixels.Length + (InitialPixels == null ? 0 : InitialPixels.Length); } }
|
|
4692
|
+
public List<ClickControl> Controls;
|
|
4693
|
+
}
|
|
4694
|
+
static readonly Queue<ClickWitness> clickWitnesses = new Queue<ClickWitness>();
|
|
4695
|
+
static int witnessBytes;
|
|
4696
|
+
static string RememberClickWitness(string geometry, RECT bounds, byte[] pixels, List<ClickControl> controls, byte[] initial)
|
|
4697
|
+
{
|
|
4698
|
+
const int limit = 16 * 1024 * 1024;
|
|
4699
|
+
var id = Guid.NewGuid().ToString("N");
|
|
4700
|
+
var shot = new ClickWitness { Id = id, Geometry = geometry, Bounds = bounds, Pixels = pixels, Controls = controls };
|
|
4701
|
+
if (controls != null && controls.Count != 0 && !Object.ReferenceEquals(initial,pixels) && !initial.SequenceEqual(pixels))
|
|
4702
|
+
shot.InitialPixels = initial;
|
|
4703
|
+
while (clickWitnesses.Count > 0 && (clickWitnesses.Count >= 12 || witnessBytes + shot.Bytes > limit))
|
|
4704
|
+
witnessBytes -= clickWitnesses.Dequeue().Bytes;
|
|
4705
|
+
if (shot.Bytes <= limit) {
|
|
4706
|
+
clickWitnesses.Enqueue(shot); witnessBytes += shot.Bytes; return id;
|
|
4707
|
+
}
|
|
4708
|
+
return null;
|
|
4709
|
+
}
|
|
4710
|
+
static bool SameClickPatch(ClickWitness shot, byte[] current, int x, int y)
|
|
4711
|
+
{
|
|
4712
|
+
if (current == null || current.Length != shot.Pixels.Length) return false;
|
|
4713
|
+
int width = shot.Bounds.Right - shot.Bounds.Left, height = shot.Bounds.Bottom - shot.Bounds.Top;
|
|
4714
|
+
int columns = (width + 3) / 4, changed = 0;
|
|
4715
|
+
x -= shot.Bounds.Left; y -= shot.Bounds.Top;
|
|
4716
|
+
if (x < 0 || y < 0 || x >= width || y >= height) return false;
|
|
4717
|
+
for (int row = Math.Max(0, y - 18) / 4; row <= Math.Min(height - 1, y + 18) / 4; row++)
|
|
4718
|
+
for (int col = Math.Max(0, x - 32) / 4; col <= Math.Min(width - 1, x + 32) / 4; col++) {
|
|
4719
|
+
int i = 3 * (row * columns + col);
|
|
4720
|
+
if (Math.Abs(shot.Pixels[i] - current[i]) > 12 || Math.Abs(shot.Pixels[i+1] - current[i+1]) > 12 ||
|
|
4721
|
+
Math.Abs(shot.Pixels[i+2] - current[i+2]) > 12) if (++changed >= 3) return false;
|
|
4722
|
+
}
|
|
4723
|
+
return true;
|
|
4724
|
+
}
|
|
4725
|
+
static string CheckClickWitness(Dictionary<string, object> args, int x, int y)
|
|
4726
|
+
{
|
|
4727
|
+
string id = GetS(args, "shotWitness", null);
|
|
4728
|
+
if (id == null) return null;
|
|
4729
|
+
IntPtr hwnd = new IntPtr(GetI(args, "expectHwnd", 0)); RECT bounds;
|
|
4730
|
+
var shot = clickWitnesses.FirstOrDefault(w => w.Id == id);
|
|
4731
|
+
if (shot != null && ScreenshotGeometry(hwnd, out bounds) == shot.Geometry) {
|
|
4732
|
+
var oldControl = shot.Controls == null ? null : shot.Controls.Where(c => c.Rect.Contains(x, y))
|
|
4733
|
+
.OrderBy(c => c.Rect.Width * c.Rect.Height).FirstOrDefault();
|
|
4734
|
+
var query = StartWitnessRead(delegate { return new ClickControl[] { ControlAt(x, y) }; });
|
|
4735
|
+
bool ready = query != null && query.Wait(250) && query.Result != null;
|
|
4736
|
+
var current = ready ? query.Result[0] : null;
|
|
4737
|
+
if (oldControl != null) {
|
|
4738
|
+
if (ready && oldControl.Same(current) &&
|
|
4739
|
+
(shot.InitialPixels == null || SameClickPatch(shot, shot.InitialPixels, x, y))) return "uia";
|
|
4740
|
+
} else if (ready && current == null) {
|
|
4741
|
+
try {
|
|
4742
|
+
using (var frames = new WindowFrames(hwnd, bounds))
|
|
4743
|
+
if (frames.Bounds.Left == shot.Bounds.Left && frames.Bounds.Top == shot.Bounds.Top &&
|
|
4744
|
+
frames.Bounds.Right == shot.Bounds.Right && frames.Bounds.Bottom == shot.Bounds.Bottom &&
|
|
4745
|
+
SameClickPatch(shot, frames.Sample(), x, y)) return "pixels";
|
|
4746
|
+
} catch { /* unavailable pixels cannot authorize the old click */ }
|
|
4747
|
+
}
|
|
4748
|
+
}
|
|
4749
|
+
throw InputInterrupted("STALE_SCREENSHOT", "Click target changed or its observation expired. Inspect this window again.");
|
|
4750
|
+
}
|
|
4751
|
+
|
|
4752
|
+
static void CheckScreenshotPoint(Dictionary<string, object> a, int x, int y)
|
|
4753
|
+
{
|
|
4754
|
+
string expected = GetS(a, "shotGeometry", null);
|
|
4755
|
+
if (expected == null && !GetB(a, "strictHwnd", false)) return;
|
|
4756
|
+
IntPtr window = new IntPtr(GetI(a, "expectHwnd", 0));
|
|
4757
|
+
RECT bounds;
|
|
4758
|
+
POINT point; point.X = x; point.Y = y;
|
|
4759
|
+
if ((expected != null && ScreenshotGeometry(window, out bounds) != expected) || !Native.IsWindowEnabled(window) ||
|
|
4760
|
+
GetAncestor(Native.WindowFromPoint(point), 2) != window ||
|
|
4761
|
+
GetAncestor(Native.GetForegroundWindow(), 2) != window)
|
|
4762
|
+
throw InputInterrupted(expected != null ? "STALE_SCREENSHOT" : "INPUT_TARGET_CHANGED",
|
|
4763
|
+
"The window moved, changed focus, or the point is covered. Observe the named window again.");
|
|
4764
|
+
}
|
|
4765
|
+
|
|
4766
|
+
// Only a matching settled observation, with the same input tick and geometry, earns
|
|
4767
|
+
// the short repeat window. A change during either path starts a full quiet interval.
|
|
4768
|
+
static string lastCaptureKey;
|
|
4769
|
+
static byte[] lastCaptureSample;
|
|
4770
|
+
static uint lastCaptureInput;
|
|
4771
|
+
static readonly Stopwatch CaptureClock = Stopwatch.StartNew();
|
|
4772
|
+
static long lastSettledAt;
|
|
4773
|
+
static bool WaitForCapture(Dictionary<string, object> args, string key, Func<byte[]> sample,
|
|
4774
|
+
out int elapsed, out double difference)
|
|
4775
|
+
{
|
|
4776
|
+
string mode = GetS(args, "wait", "auto");
|
|
4777
|
+
int cap = Math.Max(1, GetI(args, "waitCapMs", mode == "auto" ? 2500 : 10000));
|
|
4778
|
+
int quiet = Math.Max(1, GetI(args, "stableMs", mode == "auto" ? 450 : 700));
|
|
4779
|
+
var timer = Stopwatch.StartNew();
|
|
4780
|
+
uint input = Native.LastInputTick();
|
|
4781
|
+
byte[] previous = sample();
|
|
4782
|
+
bool repeat = mode == "auto" && !args.ContainsKey("stableMs") && key == lastCaptureKey &&
|
|
4783
|
+
CaptureClock.ElapsedMilliseconds - lastSettledAt < 12000 && input == lastCaptureInput &&
|
|
4784
|
+
previous != null && lastCaptureSample != null && previous.SequenceEqual(lastCaptureSample);
|
|
4785
|
+
lastCaptureKey = null; lastCaptureSample = null;
|
|
4786
|
+
long quietSince = timer.ElapsedMilliseconds;
|
|
4787
|
+
int required = repeat ? Math.Min(205, quiet) : quiet;
|
|
4788
|
+
difference = 0;
|
|
4789
|
+
do {
|
|
4790
|
+
long remaining = cap - timer.ElapsedMilliseconds;
|
|
4791
|
+
if (remaining <= 0) break;
|
|
4792
|
+
Thread.Sleep((int)Math.Min(45, Math.Min(remaining, Math.Max(1, required - (timer.ElapsedMilliseconds - quietSince)))));
|
|
4793
|
+
byte[] current = sample();
|
|
4794
|
+
uint tick = Native.LastInputTick();
|
|
4795
|
+
difference = Object.ReferenceEquals(current, previous) && current != null ? 0 : SigDiffPct(previous, current, 4);
|
|
4796
|
+
if (difference > 0 || input != tick) { quietSince = timer.ElapsedMilliseconds; required = quiet; input = tick; }
|
|
4797
|
+
previous = current;
|
|
4798
|
+
if (current != null && timer.ElapsedMilliseconds - quietSince >= required) {
|
|
4799
|
+
lastCaptureKey = key; lastCaptureSample = current; lastCaptureInput = tick;
|
|
4800
|
+
lastSettledAt = CaptureClock.ElapsedMilliseconds; elapsed = (int)timer.ElapsedMilliseconds; return true;
|
|
4801
|
+
}
|
|
4802
|
+
} while (timer.ElapsedMilliseconds < cap);
|
|
4803
|
+
elapsed = (int)timer.ElapsedMilliseconds; return false;
|
|
4804
|
+
}
|
|
4805
|
+
|
|
4806
|
+
static void ValidateCaptureTarget(Dictionary<string, object> args, IntPtr hwnd)
|
|
4807
|
+
{
|
|
4808
|
+
// WGC reads exactly this surface even if the confirmed app is behind another window.
|
|
4809
|
+
if (hwnd != IntPtr.Zero && _kickoffFocus.Confirms(hwnd.ToInt64(), PidOf(hwnd)) && Native.IsWindow(hwnd) &&
|
|
4810
|
+
(!IsHostWindow(hwnd) || HostDrivingAllowed())) return;
|
|
4811
|
+
IntPtr owner = new IntPtr(_kickoffFocus.Target);
|
|
4812
|
+
if (hwnd != IntPtr.Zero && owner != IntPtr.Zero && hwnd != owner && _kickoffFocus.Confirms(owner.ToInt64(), PidOf(owner)) &&
|
|
4813
|
+
(!IsHostWindow(owner) || HostDrivingAllowed()) && FeedbackSurface(owner) == hwnd) return;
|
|
4814
|
+
ValidateKickoffCapture(args);
|
|
4815
|
+
if (hwnd != IntPtr.Zero && GetB(args, "__kickoff", true) && Panic.CycleLit && !Panic.Stopped &&
|
|
4816
|
+
!Panic.Exited && hwnd != TopLevel(Native.GetForegroundWindow()))
|
|
4817
|
+
throw new Exception("KICKOFF-FOCUS-REQUIRED: select this window before observing its background surface");
|
|
4818
|
+
}
|
|
4819
|
+
|
|
4435
4820
|
static Dictionary<string, object> Capture(Dictionary<string, object> a)
|
|
4436
4821
|
{
|
|
4437
|
-
|
|
4822
|
+
IntPtr shotWindow = new IntPtr(GetI(a, "shotWindow", 0));
|
|
4823
|
+
ValidateCaptureTarget(a, shotWindow);
|
|
4438
4824
|
int vx = Native.GetSystemMetrics(Native.SM_XVIRTUALSCREEN);
|
|
4439
4825
|
int vy = Native.GetSystemMetrics(Native.SM_YVIRTUALSCREEN);
|
|
4440
4826
|
int vw = Native.GetSystemMetrics(Native.SM_CXVIRTUALSCREEN);
|
|
4441
4827
|
int vh = Native.GetSystemMetrics(Native.SM_CYVIRTUALSCREEN);
|
|
4442
4828
|
int x = GetI(a, "x", vx), y = GetI(a, "y", vy);
|
|
4443
4829
|
int w = GetI(a, "width", vw), h = GetI(a, "height", vh);
|
|
4444
|
-
|
|
4830
|
+
string geometry = null;
|
|
4831
|
+
if (shotWindow != IntPtr.Zero)
|
|
4832
|
+
{
|
|
4833
|
+
RECT bounds;
|
|
4834
|
+
geometry = ScreenshotGeometry(shotWindow, out bounds);
|
|
4835
|
+
if (geometry == null) throw new Exception("SCREENSHOT_WINDOW_UNAVAILABLE: select a visible window");
|
|
4836
|
+
x = bounds.Left; y = bounds.Top;
|
|
4837
|
+
w = bounds.Right - x; h = bounds.Bottom - y;
|
|
4838
|
+
}
|
|
4839
|
+
if (shotWindow == IntPtr.Zero && GetB(a, "clamp", true))
|
|
4445
4840
|
{
|
|
4446
4841
|
int x2 = Math.Max(x, vx), y2 = Math.Max(y, vy);
|
|
4447
4842
|
int x3 = Math.Min(x + w, vx + vw), y3 = Math.Min(y + h, vy + vh);
|
|
@@ -4450,69 +4845,103 @@ namespace DshComputerUse.Worker
|
|
|
4450
4845
|
}
|
|
4451
4846
|
bool withCursor = GetB(a, "cursor", false);
|
|
4452
4847
|
|
|
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
4848
|
string waitMode = GetS(a, "wait", "auto");
|
|
4458
|
-
bool settled = true;
|
|
4459
|
-
int settleMs = 0;
|
|
4849
|
+
bool settled = true, cursorDrawn = false;
|
|
4850
|
+
int settleMs = 0, cursorFlags = 0, cursorAtX = 0, cursorAtY = 0;
|
|
4460
4851
|
double settleDiff = 0;
|
|
4461
|
-
|
|
4462
|
-
|
|
4463
|
-
|
|
4464
|
-
|
|
4465
|
-
|
|
4466
|
-
|
|
4467
|
-
|
|
4468
|
-
|
|
4469
|
-
|
|
4470
|
-
|
|
4471
|
-
|
|
4472
|
-
|
|
4473
|
-
|
|
4474
|
-
|
|
4475
|
-
|
|
4476
|
-
|
|
4477
|
-
|
|
4478
|
-
|
|
4479
|
-
|
|
4480
|
-
|
|
4481
|
-
|
|
4482
|
-
|
|
4483
|
-
|
|
4484
|
-
|
|
4485
|
-
|
|
4486
|
-
|
|
4487
|
-
|
|
4488
|
-
|
|
4489
|
-
|
|
4490
|
-
|
|
4852
|
+
long capturedAt;
|
|
4853
|
+
bool foregroundAtCapture = shotWindow != IntPtr.Zero && GetAncestor(Native.GetForegroundWindow(), 2) == shotWindow;
|
|
4854
|
+
string witness = null;
|
|
4855
|
+
Bitmap managed;
|
|
4856
|
+
if (shotWindow != IntPtr.Zero) {
|
|
4857
|
+
RECT bounds;
|
|
4858
|
+
if (ScreenshotGeometry(shotWindow, out bounds) != geometry) throw new Exception("STALE_SCREENSHOT: window changed before capture");
|
|
4859
|
+
try {
|
|
4860
|
+
bool keepWitness = foregroundAtCapture && GetB(a, "clickWitness", false);
|
|
4861
|
+
using (var frames = new WindowFrames(shotWindow, bounds)) {
|
|
4862
|
+
byte[] firstPixels = keepWitness ? frames.Sample() : null;
|
|
4863
|
+
var controls = keepWitness ? StartWitnessRead(delegate { return ReadClickControls(shotWindow); }) : null;
|
|
4864
|
+
if (waitMode == "none") { if (!keepWitness) frames.Sample(); }
|
|
4865
|
+
else settled = WaitForCapture(a, geometry, frames.Sample, out settleMs, out settleDiff);
|
|
4866
|
+
x = frames.Bounds.Left; y = frames.Bounds.Top;
|
|
4867
|
+
w = frames.Bounds.Right - x; h = frames.Bounds.Bottom - y;
|
|
4868
|
+
managed = frames.ToBitmap(); capturedAt = frames.CapturedAt;
|
|
4869
|
+
if (keepWitness && settled) {
|
|
4870
|
+
byte[] captured = frames.Signature;
|
|
4871
|
+
var matched = controls != null && controls.Wait(120) ? controls.Result : null;
|
|
4872
|
+
witness = RememberClickWitness(geometry, frames.Bounds, captured, matched, firstPixels);
|
|
4873
|
+
}
|
|
4874
|
+
}
|
|
4875
|
+
} catch (Exception ex) {
|
|
4876
|
+
throw new Exception("CAPTURE_UNAVAILABLE: Windows.Graphics.Capture could not read this window: " + ex.GetBaseException().Message);
|
|
4877
|
+
}
|
|
4878
|
+
if (withCursor) {
|
|
4879
|
+
CURSORINFO ci = new CURSORINFO(); ci.cbSize = (uint)Marshal.SizeOf(typeof(CURSORINFO));
|
|
4880
|
+
if (Native.GetCursorInfo(ref ci)) {
|
|
4881
|
+
cursorFlags = (int)ci.flags; cursorAtX = ci.ptScreenPos.X; cursorAtY = ci.ptScreenPos.Y;
|
|
4882
|
+
if ((ci.flags & Native.CURSOR_SHOWING) != 0 && GetAncestor(Native.WindowFromPoint(ci.ptScreenPos), 2) == shotWindow) {
|
|
4883
|
+
using (Graphics graphics = Graphics.FromImage(managed)) {
|
|
4884
|
+
IntPtr dc = graphics.GetHdc();
|
|
4885
|
+
try { cursorDrawn = Native.DrawIconEx(dc, cursorAtX - x, cursorAtY - y, ci.hCursor, 0, 0, 0, IntPtr.Zero, Native.DI_NORMAL); }
|
|
4886
|
+
finally { graphics.ReleaseHdc(dc); }
|
|
4887
|
+
}
|
|
4888
|
+
}
|
|
4889
|
+
}
|
|
4890
|
+
}
|
|
4891
|
+
} else {
|
|
4892
|
+
if (waitMode != "none")
|
|
4893
|
+
settled = WaitForCapture(a, String.Join(",", new int[] { x, y, w, h }),
|
|
4894
|
+
delegate { return CaptureRegionSamples(x, y, w, h, 8); }, out settleMs, out settleDiff);
|
|
4895
|
+
ValidateKickoffCapture(a);
|
|
4896
|
+
IntPtr screen = Native.GetDC(IntPtr.Zero);
|
|
4897
|
+
IntPtr mem = Native.CreateCompatibleDC(screen);
|
|
4898
|
+
Native.BITMAPINFO bmi = new Native.BITMAPINFO();
|
|
4899
|
+
bmi.bmiHeader.biSize = (uint)Marshal.SizeOf(typeof(Native.BITMAPINFOHEADER));
|
|
4900
|
+
bmi.bmiHeader.biWidth = w; bmi.bmiHeader.biHeight = -h;
|
|
4901
|
+
bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32;
|
|
4902
|
+
bmi.bmiHeader.biCompression = 0;
|
|
4903
|
+
IntPtr bits;
|
|
4904
|
+
IntPtr dib = Native.CreateDIBSection(screen, ref bmi, 0, out bits, IntPtr.Zero, 0);
|
|
4905
|
+
IntPtr old = Native.SelectObject(mem, dib);
|
|
4906
|
+
// SRCCOPY | CAPTUREBLT so layered windows are included
|
|
4907
|
+
Native.BitBlt(mem, 0, 0, w, h, screen, x, y, 0x00CC0020 | 0x40000000);
|
|
4908
|
+
capturedAt = NowMs();
|
|
4909
|
+
if (withCursor)
|
|
4491
4910
|
{
|
|
4492
|
-
|
|
4493
|
-
|
|
4911
|
+
CURSORINFO ci = new CURSORINFO();
|
|
4912
|
+
ci.cbSize = (uint)Marshal.SizeOf(typeof(CURSORINFO));
|
|
4913
|
+
if (Native.GetCursorInfo(ref ci))
|
|
4494
4914
|
{
|
|
4495
|
-
|
|
4496
|
-
|
|
4497
|
-
|
|
4498
|
-
|
|
4499
|
-
|
|
4500
|
-
|
|
4915
|
+
cursorFlags = (int)ci.flags; cursorAtX = ci.ptScreenPos.X; cursorAtY = ci.ptScreenPos.Y;
|
|
4916
|
+
if ((ci.flags & Native.CURSOR_SHOWING) != 0)
|
|
4917
|
+
{
|
|
4918
|
+
// Draw straight into the DC that already owns the DIB. The first
|
|
4919
|
+
// version created a second DC and SelectObject'd the SAME bitmap into
|
|
4920
|
+
// it — GDI forbids a bitmap living in two DCs at once, that SelectObject
|
|
4921
|
+
// failed silently, and DrawIconEx painted into memG's default 1x1
|
|
4922
|
+
// monochrome bitmap. Result: cursorDrawn=true with no arrow in the image.
|
|
4923
|
+
cursorDrawn = Native.DrawIconEx(mem, ci.ptScreenPos.X - x, ci.ptScreenPos.Y - y, ci.hCursor, 0, 0, 0, IntPtr.Zero, Native.DI_NORMAL);
|
|
4924
|
+
}
|
|
4501
4925
|
}
|
|
4502
4926
|
}
|
|
4927
|
+
// copy DIB pixels into a managed bitmap BEFORE freeing the DIB —
|
|
4928
|
+
// a Bitmap that wraps DIB memory must never outlive the DIB
|
|
4929
|
+
Bitmap wrap = new Bitmap(w, h, 4 * w, PixelFormat.Format32bppRgb, bits);
|
|
4930
|
+
managed = new Bitmap(w, h);
|
|
4931
|
+
using (Graphics cg = Graphics.FromImage(managed))
|
|
4932
|
+
{
|
|
4933
|
+
cg.DrawImage(wrap, 0, 0, w, h);
|
|
4934
|
+
}
|
|
4935
|
+
wrap.Dispose();
|
|
4936
|
+
Native.SelectObject(mem, old);
|
|
4937
|
+
Native.DeleteObject(dib); Native.DeleteDC(mem); Native.ReleaseDC(IntPtr.Zero, screen);
|
|
4503
4938
|
}
|
|
4504
|
-
|
|
4505
|
-
|
|
4506
|
-
|
|
4507
|
-
|
|
4508
|
-
|
|
4509
|
-
{
|
|
4510
|
-
cg.DrawImage(wrap, 0, 0, w, h);
|
|
4939
|
+
try {
|
|
4940
|
+
ValidateCaptureTarget(a, shotWindow);
|
|
4941
|
+
RECT after;
|
|
4942
|
+
if (geometry != null && ScreenshotGeometry(shotWindow, out after) != geometry)
|
|
4943
|
+
throw new Exception("STALE_SCREENSHOT: window geometry changed during capture; capture again");
|
|
4511
4944
|
}
|
|
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
4945
|
catch { managed.Dispose(); throw; } // discard pixels if focus changed during capture
|
|
4517
4946
|
Bitmap bmp = managed;
|
|
4518
4947
|
|
|
@@ -4555,6 +4984,12 @@ namespace DshComputerUse.Worker
|
|
|
4555
4984
|
"capturedAt", capturedAt,
|
|
4556
4985
|
"cursor", PtDict(cp2.X, cp2.Y),
|
|
4557
4986
|
"ts", NowMs());
|
|
4987
|
+
res["captureBackend"] = shotWindow == IntPtr.Zero ? "desktop-bitblt" : "windows-graphics-capture";
|
|
4988
|
+
if (geometry != null) {
|
|
4989
|
+
res["hwnd"] = shotWindow.ToInt64();
|
|
4990
|
+
if (witness != null) res["shotWitness"] = witness;
|
|
4991
|
+
if ((!GetB(a, "clickWitness", false) || witness != null) && foregroundAtCapture && GetAncestor(Native.GetForegroundWindow(), 2) == shotWindow) res["shotGeometry"] = geometry;
|
|
4992
|
+
}
|
|
4558
4993
|
if (withCursor)
|
|
4559
4994
|
{
|
|
4560
4995
|
// Diagnostics for the visual-calibration contract: the pointer must be
|
|
@@ -4570,7 +5005,7 @@ namespace DshComputerUse.Worker
|
|
|
4570
5005
|
? "pointer burned into the image at cursorInImage"
|
|
4571
5006
|
: ((cursorFlags & 1) == 0
|
|
4572
5007
|
? "pointer was HIDDEN (CURSOR_SHOWING=0) at capture time"
|
|
4573
|
-
: "
|
|
5008
|
+
: "pointer outside the captured target or unavailable for drawing");
|
|
4574
5009
|
}
|
|
4575
5010
|
if (waitMode != "none")
|
|
4576
5011
|
{
|
|
@@ -4578,8 +5013,7 @@ namespace DshComputerUse.Worker
|
|
|
4578
5013
|
res["settleMs"] = settleMs;
|
|
4579
5014
|
res["settleDiffPct"] = Math.Round(settleDiff, 3);
|
|
4580
5015
|
if (!settled)
|
|
4581
|
-
res["settleNote"] = "
|
|
4582
|
-
settleEstimate + "ms more might have finished it (or re-shoot with wait:\"stable\")";
|
|
5016
|
+
res["settleNote"] = "The observed surface did not remain quiet before the deadline. Inspect again.";
|
|
4583
5017
|
}
|
|
4584
5018
|
// Tell the human a capture just happened: a yellow border flashes around the
|
|
4585
5019
|
// captured rectangle. Deliberately fired AFTER the pixels are grabbed, so the
|
|
@@ -4772,7 +5206,7 @@ namespace DshComputerUse.Worker
|
|
|
4772
5206
|
Native.GetCursorPos(out p);
|
|
4773
5207
|
}
|
|
4774
5208
|
CheckHumanInput();
|
|
4775
|
-
return Dict("x", p.X, "y", p.Y, "positionCorrections", _positionCorrections, "cursor", CursorSnapshot());
|
|
5209
|
+
return Dict("x", p.X, "y", p.Y, "positionCorrections", _positionCorrections, "cursor", CursorSnapshot(), "actionHwnd", TopLevel(Native.WindowFromPoint(p)).ToInt64());
|
|
4776
5210
|
}
|
|
4777
5211
|
|
|
4778
5212
|
static Rectangle ClickSampleRegion(int x, int y, Rectangle desktop)
|
|
@@ -4838,6 +5272,8 @@ namespace DshComputerUse.Worker
|
|
|
4838
5272
|
|
|
4839
5273
|
static Dictionary<string, object> Click(Dictionary<string, object> a)
|
|
4840
5274
|
{
|
|
5275
|
+
CheckScreenshotPoint(a, GetI(a, "x", 0), GetI(a, "y", 0));
|
|
5276
|
+
CheckClickWitness(a, GetI(a, "x", 0), GetI(a, "y", 0));
|
|
4841
5277
|
Rectangle sampleRegion = VerificationSampleRegion(a, GetI(a, "x", 0), GetI(a, "y", 0), new Rectangle(
|
|
4842
5278
|
Native.GetSystemMetrics(Native.SM_XVIRTUALSCREEN), Native.GetSystemMetrics(Native.SM_YVIRTUALSCREEN),
|
|
4843
5279
|
Native.GetSystemMetrics(Native.SM_CXVIRTUALSCREEN), Native.GetSystemMetrics(Native.SM_CYVIRTUALSCREEN)));
|
|
@@ -5007,14 +5443,28 @@ namespace DshComputerUse.Worker
|
|
|
5007
5443
|
if (tx != int.MinValue) HostGuardPoint(tx, ty, "click");
|
|
5008
5444
|
if (under == IntPtr.Zero) under = InputPointReceiver();
|
|
5009
5445
|
|
|
5446
|
+
string checkedTarget = null;
|
|
5010
5447
|
uint down = Native.MOUSEEVENTF_LEFTDOWN, up = Native.MOUSEEVENTF_LEFTUP;
|
|
5011
5448
|
if (btn == "right") { down = Native.MOUSEEVENTF_RIGHTDOWN; up = Native.MOUSEEVENTF_RIGHTUP; }
|
|
5012
5449
|
else if (btn == "middle") { down = Native.MOUSEEVENTF_MIDDLEDOWN; up = Native.MOUSEEVENTF_MIDDLEUP; }
|
|
5450
|
+
CheckScreenshotPoint(a, tx, ty);
|
|
5013
5451
|
using (GuardReceiver(under, InputWindowPid(under), false)) {
|
|
5014
|
-
|
|
5015
|
-
|
|
5016
|
-
|
|
5017
|
-
|
|
5452
|
+
var modifiers = new List<ushort>();
|
|
5453
|
+
if (GetB(a, "ctrl", false)) modifiers.Add(0x11);
|
|
5454
|
+
if (GetB(a, "shift", false)) modifiers.Add(0x10);
|
|
5455
|
+
KeyboardChord.Run(modifiers, SendKey, ReleaseKeyForCleanup,
|
|
5456
|
+
delegate(ushort vk) { return (Native.GetAsyncKeyState(vk) & 0x8000) != 0; },
|
|
5457
|
+
delegate {
|
|
5458
|
+
for (int i = 0; i < clicks; i++) {
|
|
5459
|
+
if (i == 0) checkedTarget = CheckClickWitness(a, tx, ty);
|
|
5460
|
+
CheckHumanInput();
|
|
5461
|
+
CheckScreenshotPoint(a, tx, ty);
|
|
5462
|
+
SendMouse(down, 0, 0, 0);
|
|
5463
|
+
WaitForKeyHold(GetI(a, "holdMs", 30));
|
|
5464
|
+
SendMouse(up, 0, 0, 0);
|
|
5465
|
+
if (i < clicks - 1) Thread.Sleep(gap);
|
|
5466
|
+
}
|
|
5467
|
+
});
|
|
5018
5468
|
}
|
|
5019
5469
|
EndActuationForReadback();
|
|
5020
5470
|
byte[] after = null;
|
|
@@ -5028,6 +5478,8 @@ namespace DshComputerUse.Worker
|
|
|
5028
5478
|
CheckHumanInput();
|
|
5029
5479
|
Dictionary<string, object> clickOut = Dict("x", fp.X, "y", fp.Y, "positionCorrections", _positionCorrections, "focus", clickFocus);
|
|
5030
5480
|
if (_lastRefocus != null) clickOut["refocused"] = _lastRefocus;
|
|
5481
|
+
if (checkedTarget != null) clickOut["targetCheck"] = checkedTarget;
|
|
5482
|
+
if (under != IntPtr.Zero) clickOut["actionHwnd"] = TopLevel(under).ToInt64();
|
|
5031
5483
|
if (coveredBy != null) clickOut["coveredBy"] = coveredBy;
|
|
5032
5484
|
if (under != IntPtr.Zero)
|
|
5033
5485
|
clickOut["receiver"] = Short(WinTitleOf(under), 40) + " (pid " + PidOf(under) + ")";
|
|
@@ -5089,6 +5541,8 @@ namespace DshComputerUse.Worker
|
|
|
5089
5541
|
int tx = GetI(a, "toX", int.MinValue), ty = GetI(a, "toY", int.MinValue);
|
|
5090
5542
|
if (fx == int.MinValue || fy == int.MinValue || tx == int.MinValue || ty == int.MinValue)
|
|
5091
5543
|
throw new Exception("fromX,fromY,toX,toY required");
|
|
5544
|
+
CheckScreenshotPoint(a, fx, fy);
|
|
5545
|
+
CheckScreenshotPoint(a, tx, ty);
|
|
5092
5546
|
// both ends are input destinations - the button goes down under (fx,fy) and comes up
|
|
5093
5547
|
// under (tx,ty) - so either one can be the host window
|
|
5094
5548
|
HostGuardPoint(fx, fy, "drag");
|
|
@@ -5111,6 +5565,8 @@ namespace DshComputerUse.Worker
|
|
|
5111
5565
|
IntPtr startWindow = CheckDragStart(a, startPoint.X, startPoint.Y);
|
|
5112
5566
|
Dictionary<string, object> startCursor = CursorSnapshot();
|
|
5113
5567
|
Dictionary<string, object> cursorCheck = CheckDragCursor(GetS(a, "expectCursor", ""), startCursor);
|
|
5568
|
+
CheckScreenshotPoint(a, fx, fy);
|
|
5569
|
+
CheckScreenshotPoint(a, tx, ty);
|
|
5114
5570
|
using (GuardReceiver(startWindow, InputWindowPid(startWindow), false))
|
|
5115
5571
|
SendMouse(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0);
|
|
5116
5572
|
Thread.Sleep(80);
|
|
@@ -5148,6 +5604,8 @@ namespace DshComputerUse.Worker
|
|
|
5148
5604
|
|
|
5149
5605
|
static Dictionary<string, object> Scroll(Dictionary<string, object> a)
|
|
5150
5606
|
{
|
|
5607
|
+
int x = GetI(a, "x", 0), y = GetI(a, "y", 0);
|
|
5608
|
+
CheckScreenshotPoint(a, x, y);
|
|
5151
5609
|
string dir = GetS(a, "direction", "down");
|
|
5152
5610
|
int lines = Math.Max(1, Math.Min(30, GetI(a, "lines", 3)));
|
|
5153
5611
|
uint flag = (dir == "left" || dir == "right") ? Native.MOUSEEVENTF_HWHEEL : Native.MOUSEEVENTF_WHEEL;
|
|
@@ -5163,12 +5621,13 @@ namespace DshComputerUse.Worker
|
|
|
5163
5621
|
throw InputInterrupted("INPUT_TARGET_CHANGED", "Scroll receiver differs from the observed target. No wheel input was sent.");
|
|
5164
5622
|
using (GuardReceiver(scrollTarget, InputWindowPid(scrollTarget), false)) {
|
|
5165
5623
|
for (int i = 0; i < lines; i++) {
|
|
5624
|
+
CheckScreenshotPoint(a, x, y);
|
|
5166
5625
|
SendMouse(flag, 0, 0, unchecked((uint)(sign * (int)Native.WHEEL_DELTA)));
|
|
5167
5626
|
Thread.Sleep(25);
|
|
5168
5627
|
}
|
|
5169
5628
|
}
|
|
5170
5629
|
POINT p; Native.GetCursorPos(out p);
|
|
5171
|
-
return
|
|
5630
|
+
return Dict("x", p.X, "y", p.Y, "actionHwnd", TopLevel(scrollTarget).ToInt64());
|
|
5172
5631
|
}
|
|
5173
5632
|
|
|
5174
5633
|
// Physical ownership is checked before focus or input, for every action.
|
|
@@ -5201,7 +5660,8 @@ namespace DshComputerUse.Worker
|
|
|
5201
5660
|
if (op == "click" || op == "move" || op == "drag" || op == "scroll" ||
|
|
5202
5661
|
op == "key" || op == "type" || op == "selectRange" || op == "shiftClick" || op == "uiaAct")
|
|
5203
5662
|
{
|
|
5204
|
-
_lastRefocus =
|
|
5663
|
+
_lastRefocus = GetB(a, "strictHwnd", false) || GetS(a, "shotGeometry", null) != null
|
|
5664
|
+
? null : EnsureTargetForeground();
|
|
5205
5665
|
}
|
|
5206
5666
|
// Validation and focus readback do not own input. The first real mutation
|
|
5207
5667
|
// or SendInput opens the actual scope and its deep-blue cue.
|
|
@@ -5409,7 +5869,12 @@ namespace DshComputerUse.Worker
|
|
|
5409
5869
|
/// window look "changed".
|
|
5410
5870
|
static byte[] FrameSignatureRect(int rx, int ry, int rw, int rh, int step)
|
|
5411
5871
|
{
|
|
5412
|
-
|
|
5872
|
+
return rw <= 16 || rh <= 16 ? null : CaptureRegionSamples(rx, ry, rw, rh, step);
|
|
5873
|
+
}
|
|
5874
|
+
|
|
5875
|
+
static byte[] CaptureRegionSamples(int rx, int ry, int rw, int rh, int step)
|
|
5876
|
+
{
|
|
5877
|
+
if (rw <= 0 || rh <= 0) return null;
|
|
5413
5878
|
IntPtr screen = Native.GetDC(IntPtr.Zero);
|
|
5414
5879
|
IntPtr mem = Native.CreateCompatibleDC(screen);
|
|
5415
5880
|
Native.BITMAPINFO bmi = new Native.BITMAPINFO();
|
|
@@ -5488,13 +5953,6 @@ namespace DshComputerUse.Worker
|
|
|
5488
5953
|
/// FALLBACK (so a slow or never-quiet page can never stall the loop): a hard cap;
|
|
5489
5954
|
/// when it trips we also extrapolate how much longer the screen *would* have needed,
|
|
5490
5955
|
/// 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
5956
|
static bool SettleSampleWait(int capMs, int stableMs, int pollMs, double diffPct, Func<byte[]> sample,
|
|
5499
5957
|
out int waitedMs, out double lastDiff, out int estimateMs)
|
|
5500
5958
|
{
|
|
@@ -5538,35 +5996,37 @@ namespace DshComputerUse.Worker
|
|
|
5538
5996
|
|
|
5539
5997
|
// Explicit window scope excludes unrelated desktop animation without loosening the
|
|
5540
5998
|
// change threshold. A moved/minimized/replaced window invalidates the observation.
|
|
5541
|
-
static
|
|
5999
|
+
static WindowFrames OpenWaitSurface(Dictionary<string, object> args)
|
|
6000
|
+
{
|
|
6001
|
+
IntPtr h = new IntPtr(GetI(args, "hwnd", 0));
|
|
6002
|
+
if (h == IntPtr.Zero) return null;
|
|
6003
|
+
ValidateCaptureTarget(args, h);
|
|
6004
|
+
RECT r;
|
|
6005
|
+
if (ScreenshotGeometry(h, out r) == null) throw new Exception("WAIT_TARGET_UNAVAILABLE: window closed or minimized");
|
|
6006
|
+
return new WindowFrames(h, r);
|
|
6007
|
+
}
|
|
6008
|
+
static Func<byte[]> WaitSampler(Dictionary<string, object> a, WindowFrames frames, int step, out object scope,
|
|
5542
6009
|
out int rx, out int ry, out int rw, out int rh)
|
|
5543
6010
|
{
|
|
5544
|
-
if (
|
|
5545
|
-
|
|
5546
|
-
|
|
5547
|
-
ry = Native.GetSystemMetrics(Native.SM_YVIRTUALSCREEN);
|
|
5548
|
-
rw = Native.GetSystemMetrics(Native.SM_CXVIRTUALSCREEN);
|
|
5549
|
-
rh = Native.GetSystemMetrics(Native.SM_CYVIRTUALSCREEN);
|
|
6011
|
+
if (frames == null) {
|
|
6012
|
+
rx = Native.GetSystemMetrics(Native.SM_XVIRTUALSCREEN); ry = Native.GetSystemMetrics(Native.SM_YVIRTUALSCREEN);
|
|
6013
|
+
rw = Native.GetSystemMetrics(Native.SM_CXVIRTUALSCREEN); rh = Native.GetSystemMetrics(Native.SM_CYVIRTUALSCREEN);
|
|
5550
6014
|
scope = Dict("kind", "virtual-desktop", "region", Dict("x", rx, "y", ry, "width", rw, "height", rh));
|
|
5551
6015
|
return delegate { return FrameSignature(step); };
|
|
5552
6016
|
}
|
|
5553
|
-
IntPtr h = new IntPtr(GetI(a, "hwnd", 0));
|
|
5554
|
-
|
|
5555
|
-
|
|
5556
|
-
|
|
5557
|
-
|
|
5558
|
-
|
|
5559
|
-
|
|
5560
|
-
|
|
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));
|
|
6017
|
+
IntPtr h = new IntPtr(GetI(a, "hwnd", 0)); RECT rect;
|
|
6018
|
+
string geometry = ScreenshotGeometry(h, out rect);
|
|
6019
|
+
if (geometry == null || rect.Left != frames.WindowBounds.Left || rect.Top != frames.WindowBounds.Top ||
|
|
6020
|
+
rect.Right != frames.WindowBounds.Right || rect.Bottom != frames.WindowBounds.Bottom)
|
|
6021
|
+
throw new Exception("WAIT_TARGET_CHANGED: window moved while opening capture");
|
|
6022
|
+
rx = frames.Bounds.Left; ry = frames.Bounds.Top; rw = frames.Bounds.Right-rx; rh = frames.Bounds.Bottom-ry;
|
|
6023
|
+
scope = Dict("kind", "window", "hwnd", h.ToInt64(), "captureBackend", "windows-graphics-capture",
|
|
6024
|
+
"region", Dict("x", rx, "y", ry, "width", rw, "height", rh));
|
|
5564
6025
|
return delegate {
|
|
5565
|
-
|
|
5566
|
-
if (
|
|
5567
|
-
current.Left != original.Left || current.Top != original.Top || current.Right != original.Right || current.Bottom != original.Bottom)
|
|
6026
|
+
ValidateCaptureTarget(a, h);
|
|
6027
|
+
if (geometry == null || ScreenshotGeometry(h, out rect) != geometry)
|
|
5568
6028
|
throw new Exception("WAIT_TARGET_CHANGED: window identity or bounds changed during sampling; requery before waiting again");
|
|
5569
|
-
return
|
|
6029
|
+
return frames.Sample();
|
|
5570
6030
|
};
|
|
5571
6031
|
}
|
|
5572
6032
|
|
|
@@ -5574,6 +6034,9 @@ namespace DshComputerUse.Worker
|
|
|
5574
6034
|
/// threshold — "where did it change", not just "did it" (test report 2026-11-04: a
|
|
5575
6035
|
/// 0.344% diff cannot distinguish a sent message from a blinking caret without this).
|
|
5576
6036
|
static int[] SigDiffBounds(byte[] a, byte[] b, int threshold, int cols, int step, int rx, int ry)
|
|
6037
|
+
{ return SampleDiffBounds(a, b, threshold, cols, step, rx, ry, 1); }
|
|
6038
|
+
|
|
6039
|
+
static int[] SampleDiffBounds(byte[] a, byte[] b, int threshold, int cols, int step, int rx, int ry, int channels)
|
|
5577
6040
|
{
|
|
5578
6041
|
if (a == null || b == null || a.Length != b.Length || cols <= 0) return null;
|
|
5579
6042
|
int minX = -1, minY = -1, maxX = -1, maxY = -1;
|
|
@@ -5582,7 +6045,7 @@ namespace DshComputerUse.Worker
|
|
|
5582
6045
|
int d = a[i] - b[i];
|
|
5583
6046
|
if (d < 0) d = -d;
|
|
5584
6047
|
if (d <= threshold) continue;
|
|
5585
|
-
int
|
|
6048
|
+
int cell = i / channels, c = cell % cols, r = cell / cols;
|
|
5586
6049
|
if (minX < 0 || c < minX) minX = c;
|
|
5587
6050
|
if (c > maxX) maxX = c;
|
|
5588
6051
|
if (minY < 0 || r < minY) minY = r;
|
|
@@ -5594,6 +6057,11 @@ namespace DshComputerUse.Worker
|
|
|
5594
6057
|
}
|
|
5595
6058
|
|
|
5596
6059
|
static Dictionary<string, object> WaitStable(Dictionary<string, object> a)
|
|
6060
|
+
{
|
|
6061
|
+
using (var frames = OpenWaitSurface(a)) return WaitStable(a, frames);
|
|
6062
|
+
}
|
|
6063
|
+
|
|
6064
|
+
static Dictionary<string, object> WaitStable(Dictionary<string, object> a, WindowFrames frames)
|
|
5597
6065
|
{
|
|
5598
6066
|
int capMs = Math.Max(400, GetI(a, "timeoutMs", 8000));
|
|
5599
6067
|
int stableMs = Math.Max(150, GetI(a, "stableMs", 600));
|
|
@@ -5602,9 +6070,26 @@ namespace DshComputerUse.Worker
|
|
|
5602
6070
|
double diffPct = GetD(a, "diffPct", 0.30);
|
|
5603
6071
|
int waited, estimate; double lastDiff;
|
|
5604
6072
|
int rx, ry, rw, rh;
|
|
5605
|
-
|
|
6073
|
+
if (frames != null) step = 4;
|
|
6074
|
+
object scope; Func<byte[]> sample = WaitSampler(a, frames, step, out scope, out rx, out ry, out rw, out rh);
|
|
6075
|
+
bool smallContinuous = true;
|
|
6076
|
+
int pairs = 0;
|
|
6077
|
+
if (frames != null) {
|
|
6078
|
+
var read = sample; byte[] previous = null;
|
|
6079
|
+
sample = delegate {
|
|
6080
|
+
var pixels = read();
|
|
6081
|
+
if (previous != null && smallContinuous) {
|
|
6082
|
+
double delta = SigDiffPct(previous, pixels, 8);
|
|
6083
|
+
smallContinuous = delta > 0 && delta < 1; pairs++;
|
|
6084
|
+
}
|
|
6085
|
+
previous = pixels; return pixels;
|
|
6086
|
+
};
|
|
6087
|
+
}
|
|
5606
6088
|
bool ok = SettleSampleWait(capMs, stableMs, pollMs, diffPct, sample, out waited, out lastDiff, out estimate);
|
|
5607
|
-
if (!ok)
|
|
6089
|
+
if (!ok && frames != null && waited >= 2400 && pairs >= 6 && smallContinuous)
|
|
6090
|
+
return Dict("stable", true, "waitedMs", waited, "lastDiffPct", Math.Round(lastDiff, 3),
|
|
6091
|
+
"scope", scope, "estimateMs", 0, "caretSteady", true, "note", "small continuous differences consistent with a blinking caret");
|
|
6092
|
+
if (!ok && frames == null)
|
|
5608
6093
|
{
|
|
5609
6094
|
// CARET / BLINK DETECTION (test report 2026-11-04): a blinking caret is a ~1-2 Hz
|
|
5610
6095
|
// periodic sub-percent change that never settles — Notepad burned the full 8 s cap
|
|
@@ -5636,13 +6121,19 @@ namespace DshComputerUse.Worker
|
|
|
5636
6121
|
}
|
|
5637
6122
|
|
|
5638
6123
|
static Dictionary<string, object> WaitChange(Dictionary<string, object> a)
|
|
6124
|
+
{
|
|
6125
|
+
using (var frames = OpenWaitSurface(a)) return WaitChange(a, frames);
|
|
6126
|
+
}
|
|
6127
|
+
|
|
6128
|
+
static Dictionary<string, object> WaitChange(Dictionary<string, object> a, WindowFrames frames)
|
|
5639
6129
|
{
|
|
5640
6130
|
int timeoutMs = Math.Max(300, GetI(a, "timeoutMs", 6000));
|
|
5641
6131
|
int pollMs = Math.Max(100, GetI(a, "pollMs", 220));
|
|
5642
6132
|
int step = Math.Max(4, Math.Min(64, GetI(a, "step", 8)));
|
|
5643
6133
|
double diffPct = GetD(a, "diffPct", 0.30);
|
|
5644
6134
|
int rx, ry, rw, rh;
|
|
5645
|
-
|
|
6135
|
+
if (frames != null) step = 4;
|
|
6136
|
+
object scope; Func<byte[]> sample = WaitSampler(a, frames, step, out scope, out rx, out ry, out rw, out rh);
|
|
5646
6137
|
byte[] first = sample();
|
|
5647
6138
|
long t0 = NowMs();
|
|
5648
6139
|
int samples = 0;
|
|
@@ -5657,10 +6148,14 @@ namespace DshComputerUse.Worker
|
|
|
5657
6148
|
{
|
|
5658
6149
|
// WHERE it changed (test report 2026-11-04): 0.344% cannot tell a sent
|
|
5659
6150
|
// message from a caret blink; the bounding box can — input area vs caret.
|
|
5660
|
-
int[] bounds =
|
|
6151
|
+
int[] bounds = SampleDiffBounds(first, cur, 8, cols, step, rx, ry, frames == null ? 1 : 3);
|
|
5661
6152
|
Dictionary<string, object> hit = Dict("changed", true, "afterMs", NowMs() - t0,
|
|
5662
6153
|
"diffPct", Math.Round(d, 3), "samples", samples, "scope", scope);
|
|
5663
|
-
if (bounds != null
|
|
6154
|
+
if (bounds != null && frames != null) {
|
|
6155
|
+
bounds[2] = Math.Min(bounds[2], rx + rw - bounds[0]);
|
|
6156
|
+
bounds[3] = Math.Min(bounds[3], ry + rh - bounds[1]);
|
|
6157
|
+
}
|
|
6158
|
+
if (bounds != null) hit["changeBounds"] = Dict("x", bounds[0], "y", bounds[1], "width", bounds[2], "height", bounds[3]);
|
|
5664
6159
|
return hit;
|
|
5665
6160
|
}
|
|
5666
6161
|
}
|
|
@@ -5830,6 +6325,7 @@ namespace DshComputerUse.Worker
|
|
|
5830
6325
|
d["caps"] = 0x14; d["capslock"] = 0x14; d["apps"] = 0x5D;
|
|
5831
6326
|
d["prtsc"] = 0x2C; d["printscreen"] = 0x2C; d["numlock"] = 0x90;
|
|
5832
6327
|
d["plus"] = 0xBB; d["minus"] = 0xBD; d["comma"] = 0xBC; d["period"] = 0xBE;
|
|
6328
|
+
for (int i = 0; i <= 9; i++) d["numpad" + i] = (ushort)(0x60 + i);
|
|
5833
6329
|
for (int i = 1; i <= 24; i++) d["f" + i] = (ushort)(0x6F + i);
|
|
5834
6330
|
return d;
|
|
5835
6331
|
}
|
|
@@ -5854,8 +6350,13 @@ namespace DshComputerUse.Worker
|
|
|
5854
6350
|
foreach (string raw in combo.Split('+')) {
|
|
5855
6351
|
string key = raw.Trim().ToLowerInvariant();
|
|
5856
6352
|
if (key.Length == 0) throw new Exception("key combo contains an empty token; use plus for the + key");
|
|
6353
|
+
if ((key.StartsWith("kp_") || key.StartsWith("numpad_")) && key.Length == key.IndexOf('_') + 2 &&
|
|
6354
|
+
key[key.Length - 1] >= '0' && key[key.Length - 1] <= '9')
|
|
6355
|
+
key = "numpad" + key[key.Length - 1];
|
|
5857
6356
|
switch (key) {
|
|
5858
|
-
case "
|
|
6357
|
+
case "shift_l": key = "shift"; break;
|
|
6358
|
+
case "alt_l": key = "alt"; break;
|
|
6359
|
+
case "control_l": case "control": key = "ctrl"; break;
|
|
5859
6360
|
case "lwin": case "windows": case "meta": key = "win"; break;
|
|
5860
6361
|
case "return": key = "enter"; break;
|
|
5861
6362
|
case "escape": key = "esc"; break;
|
|
@@ -5914,6 +6415,11 @@ namespace DshComputerUse.Worker
|
|
|
5914
6415
|
}
|
|
5915
6416
|
|
|
5916
6417
|
static Dictionary<string, object> Key(Dictionary<string, object> a)
|
|
6418
|
+
{
|
|
6419
|
+
return KeyWithExpectedFocus(a, null);
|
|
6420
|
+
}
|
|
6421
|
+
|
|
6422
|
+
static Dictionary<string, object> KeyWithExpectedFocus(Dictionary<string, object> a, AutomationElement expectedField)
|
|
5917
6423
|
{
|
|
5918
6424
|
if (_receiverCheck != null) _receiverCheck(); // nested paste may not silently repair a stolen receiver
|
|
5919
6425
|
string combo = GetS(a, "combo", null);
|
|
@@ -5935,7 +6441,7 @@ namespace DshComputerUse.Worker
|
|
|
5935
6441
|
List<ushort> vks = new List<ushort>();
|
|
5936
6442
|
foreach (string k in keys) { ushort vk = VkOf(k); if (!vks.Contains(vk)) vks.Add(vk); }
|
|
5937
6443
|
bool windowManagement = WindowManagementChord.IsExact(combo);
|
|
5938
|
-
using (
|
|
6444
|
+
using (GuardWindowReceiver(new IntPtr(Convert.ToInt64(focus["hwnd"])), Convert.ToUInt32(focus["pid"]), true, GetB(a, "strictHwnd", false)))
|
|
5939
6445
|
{
|
|
5940
6446
|
if (windowManagement)
|
|
5941
6447
|
WindowManagementChord.Run(vks, SendKey, ReleaseKeyForCleanup,
|
|
@@ -5943,7 +6449,10 @@ namespace DshComputerUse.Worker
|
|
|
5943
6449
|
delegate { WaitForKeyHold(Math.Max(20, GetI(a, "holdMs", 60))); },
|
|
5944
6450
|
delegate { WaitForKeyHold(0); }, InvalidateKeyboardTarget);
|
|
5945
6451
|
else
|
|
5946
|
-
KeyboardChord.Run(vks,
|
|
6452
|
+
KeyboardChord.Run(vks, delegate(ushort vk, bool up) {
|
|
6453
|
+
if (!up) RequireExpectedFocus(expectedField);
|
|
6454
|
+
SendKey(vk, up);
|
|
6455
|
+
}, ReleaseKeyForCleanup,
|
|
5947
6456
|
delegate(ushort vk) { return (Native.GetAsyncKeyState(vk) & 0x8000) != 0; },
|
|
5948
6457
|
delegate { WaitForKeyHold(Math.Max(20, GetI(a, "holdMs", 60))); });
|
|
5949
6458
|
}
|
|
@@ -5974,9 +6483,16 @@ namespace DshComputerUse.Worker
|
|
|
5974
6483
|
HostGuardNamed(a, "type");
|
|
5975
6484
|
Dictionary<string, object> focus = FocusReport(a, true);
|
|
5976
6485
|
HostGuardForeground("type"); // same rule as `key`: the foreground window is the victim
|
|
5977
|
-
using (
|
|
6486
|
+
using (GuardWindowReceiver(new IntPtr(Convert.ToInt64(focus["hwnd"])), Convert.ToUInt32(focus["pid"]), true, GetB(a, "strictHwnd", false))) {
|
|
5978
6487
|
// ...and whether whatever owns the focus can hold text at all. Typing into a control
|
|
5979
6488
|
// with no editable pattern is silently discarded, or interpreted as shortcuts.
|
|
6489
|
+
string expectedToken = GetS(a, "expectTarget", null);
|
|
6490
|
+
AutomationElement expectedField = null;
|
|
6491
|
+
if (expectedToken != null) {
|
|
6492
|
+
string resolved; int scanned;
|
|
6493
|
+
expectedField = ResolveUiTarget(GetUiTarget(expectedToken), false, 6, 120, out resolved, out scanned);
|
|
6494
|
+
RequireExpectedFocus(expectedField);
|
|
6495
|
+
}
|
|
5980
6496
|
string typeWarn = null;
|
|
5981
6497
|
bool nonEditableButton = false;
|
|
5982
6498
|
try
|
|
@@ -6003,6 +6519,8 @@ namespace DshComputerUse.Worker
|
|
|
6003
6519
|
string mode = GetS(a, "mode", "unicode");
|
|
6004
6520
|
if (mode == "paste")
|
|
6005
6521
|
{
|
|
6522
|
+
var pasteKeys = Dict("combo", "ctrl+v", "holdMs", 40, "indicatorMs", 800);
|
|
6523
|
+
if (GetB(a, "strictHwnd", false)) { pasteKeys["strictHwnd"] = true; pasteKeys["expectHwnd"] = a["expectHwnd"]; }
|
|
6006
6524
|
bool keep = GetB(a, "restoreClipboard", false);
|
|
6007
6525
|
string restore = "not-requested";
|
|
6008
6526
|
if (keep)
|
|
@@ -6021,7 +6539,7 @@ namespace DshComputerUse.Worker
|
|
|
6021
6539
|
MarkMutation();
|
|
6022
6540
|
Clipboard.SetDataObject(text, true);
|
|
6023
6541
|
Thread.Sleep(60);
|
|
6024
|
-
|
|
6542
|
+
KeyWithExpectedFocus(pasteKeys, expectedField);
|
|
6025
6543
|
Dictionary<string, object> downgraded = Dict("mode", "paste", "chars", text.Length, "focus", focus,
|
|
6026
6544
|
"clipboardRestore", "skipped-unpreservable-clipboard");
|
|
6027
6545
|
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 +6553,7 @@ namespace DshComputerUse.Worker
|
|
|
6035
6553
|
Thread.Sleep(60);
|
|
6036
6554
|
if (!lease.StillOwned())
|
|
6037
6555
|
throw NotDispatched("CLIPBOARD_CHANGED", "CLIPBOARD_CHANGED: clipboard changed before paste; no paste keystrokes sent.");
|
|
6038
|
-
|
|
6556
|
+
KeyWithExpectedFocus(pasteKeys, expectedField);
|
|
6039
6557
|
}
|
|
6040
6558
|
catch (Exception error) { inputError = error; throw; }
|
|
6041
6559
|
finally
|
|
@@ -6053,7 +6571,7 @@ namespace DshComputerUse.Worker
|
|
|
6053
6571
|
MarkMutation();
|
|
6054
6572
|
Clipboard.SetDataObject(text, true);
|
|
6055
6573
|
Thread.Sleep(60);
|
|
6056
|
-
|
|
6574
|
+
KeyWithExpectedFocus(pasteKeys, expectedField);
|
|
6057
6575
|
}
|
|
6058
6576
|
Dictionary<string, object> pr = Dict("mode", "paste", "chars", text.Length, "focus", focus,
|
|
6059
6577
|
"clipboardRestore", restore);
|
|
@@ -6067,6 +6585,7 @@ namespace DshComputerUse.Worker
|
|
|
6067
6585
|
foreach (char ch in text)
|
|
6068
6586
|
{
|
|
6069
6587
|
if (ch == '\r') continue;
|
|
6588
|
+
RequireExpectedFocus(expectedField);
|
|
6070
6589
|
if (ch == '\n') { SendKey(0x0D, false); SendKey(0x0D, true); Thread.Sleep(15); continue; }
|
|
6071
6590
|
INPUT down = new INPUT();
|
|
6072
6591
|
down.type = Native.INPUT_KEYBOARD;
|
|
@@ -6091,6 +6610,16 @@ namespace DshComputerUse.Worker
|
|
|
6091
6610
|
return AddFocusReadback(tr, a, focus);
|
|
6092
6611
|
}
|
|
6093
6612
|
}
|
|
6613
|
+
static void RequireExpectedFocus(AutomationElement expected)
|
|
6614
|
+
{
|
|
6615
|
+
if (expected == null) return;
|
|
6616
|
+
try {
|
|
6617
|
+
var actual = AutomationElement.FocusedElement;
|
|
6618
|
+
if (actual != null && Automation.Compare(actual, expected)) return;
|
|
6619
|
+
} catch (ElementNotAvailableException) { }
|
|
6620
|
+
throw InputInterrupted("INPUT_FIELD_CHANGED", "The expected field no longer has focus; inspect the field before continuing.");
|
|
6621
|
+
}
|
|
6622
|
+
|
|
6094
6623
|
static Dictionary<string, object> AddFocusReadback(Dictionary<string, object> result, Dictionary<string, object> args, Dictionary<string, object> before)
|
|
6095
6624
|
{
|
|
6096
6625
|
var after = FocusReport(args, false);
|
|
@@ -6234,8 +6763,85 @@ namespace DshComputerUse.Worker
|
|
|
6234
6763
|
"minimized", Native.IsIconic(h));
|
|
6235
6764
|
}
|
|
6236
6765
|
|
|
6766
|
+
static Dictionary<string, object> WindowOnDisplay(IntPtr hwnd)
|
|
6767
|
+
{
|
|
6768
|
+
var window = WinDict(hwnd);
|
|
6769
|
+
var screen = Screen.FromHandle(hwnd);
|
|
6770
|
+
var work = screen.WorkingArea;
|
|
6771
|
+
window["display"] = screen.DeviceName;
|
|
6772
|
+
window["workArea"] = Dict("x", work.X, "y", work.Y, "width", work.Width, "height", work.Height);
|
|
6773
|
+
return window;
|
|
6774
|
+
}
|
|
6775
|
+
|
|
6776
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
6777
|
+
struct COMBOBOXINFO
|
|
6778
|
+
{
|
|
6779
|
+
public int cbSize; public RECT item, button; public uint buttonState;
|
|
6780
|
+
public IntPtr combo, edit, list;
|
|
6781
|
+
}
|
|
6782
|
+
[DllImport("user32.dll")] static extern bool GetComboBoxInfo(IntPtr combo, ref COMBOBOXINFO info);
|
|
6783
|
+
|
|
6784
|
+
static IntPtr FeedbackSurface(IntPtr owner)
|
|
6785
|
+
{
|
|
6786
|
+
IntPtr foreground = TopLevel(Native.GetForegroundWindow());
|
|
6787
|
+
IntPtr active = owner;
|
|
6788
|
+
if (IsEnabledOwnedPopup(owner, foreground)) active = foreground;
|
|
6789
|
+
else if (!Native.IsWindowEnabled(owner)) {
|
|
6790
|
+
var modal = Native.GetLastActivePopup(owner);
|
|
6791
|
+
if (IsEnabledOwnedPopup(owner, modal)) active = modal;
|
|
6792
|
+
}
|
|
6793
|
+
if (active != foreground) return active;
|
|
6794
|
+
uint pid; uint tid = Native.GetWindowThreadProcessId(active, out pid);
|
|
6795
|
+
var gui = new Native.GUITHREADINFO(); gui.cbSize = Marshal.SizeOf(typeof(Native.GUITHREADINFO));
|
|
6796
|
+
if (tid == 0 || !Native.GetGUIThreadInfo(tid, ref gui)) return active;
|
|
6797
|
+
if (gui.hwndMenuOwner != IntPtr.Zero && TopLevel(gui.hwndMenuOwner) == active) {
|
|
6798
|
+
IntPtr menu = IntPtr.Zero;
|
|
6799
|
+
Native.EnumWindows(delegate(IntPtr h, IntPtr unused) {
|
|
6800
|
+
uint process;
|
|
6801
|
+
if (Native.IsWindowVisible(h) && ClassOf(h) == "#32768" && Native.GetWindowThreadProcessId(h, out process) == tid) {
|
|
6802
|
+
menu = h; return false;
|
|
6803
|
+
}
|
|
6804
|
+
return true;
|
|
6805
|
+
}, IntPtr.Zero);
|
|
6806
|
+
if (menu != IntPtr.Zero) return menu;
|
|
6807
|
+
}
|
|
6808
|
+
for (IntPtr h = gui.hwndFocus; h != IntPtr.Zero && h != active && TopLevel(h) == active; h = Native.GetParent(h)) {
|
|
6809
|
+
var combo = new COMBOBOXINFO(); combo.cbSize = Marshal.SizeOf(typeof(COMBOBOXINFO));
|
|
6810
|
+
if (GetComboBoxInfo(h, ref combo) && combo.combo == h && Native.IsWindowVisible(combo.list)) return combo.list;
|
|
6811
|
+
}
|
|
6812
|
+
return active;
|
|
6813
|
+
}
|
|
6814
|
+
|
|
6815
|
+
static Dictionary<string, object> WindowDetails(IntPtr hwnd)
|
|
6816
|
+
{
|
|
6817
|
+
RECT r;
|
|
6818
|
+
if (!Native.IsWindow(hwnd) || !Native.GetWindowRect(hwnd, out r)) throw new Exception("WINDOW_UNAVAILABLE: observe windows again");
|
|
6819
|
+
var popups = new List<object>();
|
|
6820
|
+
Native.EnumWindows(delegate(IntPtr h, IntPtr unused) {
|
|
6821
|
+
if (IsEnabledOwnedPopup(hwnd, h)) popups.Add(WindowOnDisplay(h));
|
|
6822
|
+
return true;
|
|
6823
|
+
}, IntPtr.Zero);
|
|
6824
|
+
var samples = new List<object>();
|
|
6825
|
+
if (Native.IsWindowVisible(hwnd) && !Native.IsIconic(hwnd)) {
|
|
6826
|
+
foreach (int fx in new int[] { 1, 2, 3 }) foreach (int fy in new int[] { 1, 2, 3 }) {
|
|
6827
|
+
POINT p; p.X = r.Left + (r.Right-r.Left)*fx/4; p.Y = r.Top + (r.Bottom-r.Top)*fy/4;
|
|
6828
|
+
var hit = GetAncestor(Native.WindowFromPoint(p), 2);
|
|
6829
|
+
samples.Add(Dict("x", p.X, "y", p.Y, "receiver", hit.ToInt64(), "target", hit == hwnd));
|
|
6830
|
+
}
|
|
6831
|
+
}
|
|
6832
|
+
return Dict("window", WindowOnDisplay(hwnd), "ownedPopups", popups, "hitSamples", samples);
|
|
6833
|
+
}
|
|
6834
|
+
|
|
6237
6835
|
static Dictionary<string, object> Windows(Dictionary<string, object> a)
|
|
6238
6836
|
{
|
|
6837
|
+
if (a.ContainsKey("feedbackHwnd")) {
|
|
6838
|
+
IntPtr owner = TopLevel(new IntPtr(GetI(a, "feedbackHwnd", 0)));
|
|
6839
|
+
if (!Native.IsWindow(owner)) throw new Exception("WINDOW_UNAVAILABLE: feedback target closed");
|
|
6840
|
+
IntPtr target = FeedbackSurface(owner);
|
|
6841
|
+
return Dict("owner", owner.ToInt64(), "ownerTitle", WinTitleOf(owner), "target", WinDict(target), "popup", target != owner);
|
|
6842
|
+
}
|
|
6843
|
+
if (a.ContainsKey("inspectHwnd")) return WindowDetails(new IntPtr(GetI(a, "inspectHwnd", 0)));
|
|
6844
|
+
if (a.ContainsKey("appQuery")) return FindRegisteredApps(GetS(a, "appQuery", ""));
|
|
6239
6845
|
uint self = (uint)System.Diagnostics.Process.GetCurrentProcess().Id;
|
|
6240
6846
|
List<object> list = new List<object>();
|
|
6241
6847
|
Native.EnumWindows(delegate(IntPtr h, IntPtr l)
|
|
@@ -6255,6 +6861,79 @@ namespace DshComputerUse.Worker
|
|
|
6255
6861
|
"cooperation", Panic.CooperationState(), "indicator", IndicatorSnapshot());
|
|
6256
6862
|
}
|
|
6257
6863
|
|
|
6864
|
+
[DllImport("kernel32.dll", CharSet=CharSet.Unicode)]
|
|
6865
|
+
static extern int GetApplicationUserModelId(IntPtr process, ref uint length, StringBuilder id);
|
|
6866
|
+
|
|
6867
|
+
static string ProcessAppId(uint pid)
|
|
6868
|
+
{
|
|
6869
|
+
IntPtr process = Native.OpenProcess(Native.PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
|
|
6870
|
+
if (process == IntPtr.Zero) return null;
|
|
6871
|
+
try {
|
|
6872
|
+
uint length = 512;
|
|
6873
|
+
var id = new StringBuilder((int)length);
|
|
6874
|
+
return GetApplicationUserModelId(process, ref length, id) == 0 ? id.ToString() : null;
|
|
6875
|
+
} catch (EntryPointNotFoundException) { return null; }
|
|
6876
|
+
finally { Native.CloseHandle(process); }
|
|
6877
|
+
}
|
|
6878
|
+
|
|
6879
|
+
static object ShellRead(object target, string member, params object[] args)
|
|
6880
|
+
{
|
|
6881
|
+
return target.GetType().InvokeMember(member, System.Reflection.BindingFlags.GetProperty |
|
|
6882
|
+
System.Reflection.BindingFlags.InvokeMethod, null, target, args);
|
|
6883
|
+
}
|
|
6884
|
+
|
|
6885
|
+
static void ReleaseShell(object obj)
|
|
6886
|
+
{
|
|
6887
|
+
if (obj != null && Marshal.IsComObject(obj)) Marshal.ReleaseComObject(obj);
|
|
6888
|
+
}
|
|
6889
|
+
|
|
6890
|
+
static Dictionary<string, object> FindRegisteredApps(string query)
|
|
6891
|
+
{
|
|
6892
|
+
query = query.Trim();
|
|
6893
|
+
if (query.Length < 1 || query.Length > 120) throw new Exception("appQuery requires 1 to 120 characters");
|
|
6894
|
+
var matches = new List<Dictionary<string, object>>();
|
|
6895
|
+
object shell = null, folder = null, items = null;
|
|
6896
|
+
bool truncated = false;
|
|
6897
|
+
try {
|
|
6898
|
+
shell = Activator.CreateInstance(System.Type.GetTypeFromProgID("Shell.Application", true));
|
|
6899
|
+
folder = ShellRead(shell, "NameSpace", "shell:AppsFolder");
|
|
6900
|
+
items = ShellRead(folder, "Items");
|
|
6901
|
+
int count = Convert.ToInt32(ShellRead(items, "Count"));
|
|
6902
|
+
for (int i = 0; i < count; i++) {
|
|
6903
|
+
object item = ShellRead(items, "Item", i);
|
|
6904
|
+
try {
|
|
6905
|
+
string name = Convert.ToString(ShellRead(item, "Name"));
|
|
6906
|
+
string id = Convert.ToString(ShellRead(item, "Path"));
|
|
6907
|
+
if (name.IndexOf(query, StringComparison.OrdinalIgnoreCase) < 0 && id.IndexOf(query, StringComparison.OrdinalIgnoreCase) < 0) continue;
|
|
6908
|
+
if (matches.Count >= 30) { truncated = true; break; }
|
|
6909
|
+
string target = Convert.ToString(ShellRead(item, "ExtendedProperty", "System.Link.TargetParsingPath"));
|
|
6910
|
+
matches.Add(Dict("name", name, "appId", id, "executable", target, "windows", new List<object>()));
|
|
6911
|
+
} finally { ReleaseShell(item); }
|
|
6912
|
+
}
|
|
6913
|
+
} finally { ReleaseShell(items); ReleaseShell(folder); ReleaseShell(shell); }
|
|
6914
|
+
var identities = new Dictionary<uint, string[]>();
|
|
6915
|
+
if (matches.Count > 0) Native.EnumWindows(delegate(IntPtr h, IntPtr unused) {
|
|
6916
|
+
if (!Native.IsWindowVisible(h)) return true;
|
|
6917
|
+
uint pid = PidOf(h);
|
|
6918
|
+
string[] identity;
|
|
6919
|
+
if (!identities.TryGetValue(pid, out identity)) {
|
|
6920
|
+
identity = new string[] { ProcessAppId(pid), ProcessImagePath(pid) };
|
|
6921
|
+
identities.Add(pid, identity);
|
|
6922
|
+
}
|
|
6923
|
+
foreach (var app in matches) {
|
|
6924
|
+
string via = null;
|
|
6925
|
+
if (!String.IsNullOrEmpty(identity[0])) {
|
|
6926
|
+
if (String.Equals(identity[0], (string)app["appId"], StringComparison.OrdinalIgnoreCase)) via = "appId";
|
|
6927
|
+
} else if (!String.IsNullOrEmpty(identity[1]) && String.Equals(identity[1], (string)app["executable"], StringComparison.OrdinalIgnoreCase)) via = "executable";
|
|
6928
|
+
if (via == null) continue;
|
|
6929
|
+
var window = WinDict(h); window["matchBy"] = via;
|
|
6930
|
+
((List<object>)app["windows"]).Add(window);
|
|
6931
|
+
}
|
|
6932
|
+
return true;
|
|
6933
|
+
}, IntPtr.Zero);
|
|
6934
|
+
return Dict("apps", matches, "truncated", truncated, "source", "shell:AppsFolder", "windowScope", "visible top-level windows");
|
|
6935
|
+
}
|
|
6936
|
+
|
|
6258
6937
|
static string IndicatorStateName(int want)
|
|
6259
6938
|
{
|
|
6260
6939
|
switch (want) {
|
|
@@ -6326,6 +7005,17 @@ namespace DshComputerUse.Worker
|
|
|
6326
7005
|
throw new Exception(msg.ToString());
|
|
6327
7006
|
}
|
|
6328
7007
|
|
|
7008
|
+
static bool IsEnabledOwnedPopup(IntPtr owner, IntPtr popup)
|
|
7009
|
+
{
|
|
7010
|
+
if (popup == IntPtr.Zero || popup == owner || !Native.IsWindowVisible(popup) || !Native.IsWindowEnabled(popup)) return false;
|
|
7011
|
+
IntPtr h = popup;
|
|
7012
|
+
for (int depth = 0; depth < 32 && h != IntPtr.Zero; depth++) {
|
|
7013
|
+
h = Native.GetWindow(h, 4); // GW_OWNER
|
|
7014
|
+
if (h == owner) return true;
|
|
7015
|
+
}
|
|
7016
|
+
return false;
|
|
7017
|
+
}
|
|
7018
|
+
|
|
6329
7019
|
static Dictionary<string, object> Activate(Dictionary<string, object> a)
|
|
6330
7020
|
{
|
|
6331
7021
|
IntPtr h = FindHwnd(a);
|
|
@@ -6334,7 +7024,16 @@ namespace DshComputerUse.Worker
|
|
|
6334
7024
|
AgentActing(a, "activate");
|
|
6335
7025
|
// The whole ladder now lives in RefocusWindow (shared with the keyboard focus
|
|
6336
7026
|
// guard, which must re-assert the same window before typing).
|
|
6337
|
-
|
|
7027
|
+
IntPtr receiver = h;
|
|
7028
|
+
if (!Native.IsWindowEnabled(h)) {
|
|
7029
|
+
receiver = Native.GetForegroundWindow();
|
|
7030
|
+
if (!IsEnabledOwnedPopup(h, receiver)) receiver = Native.GetLastActivePopup(h);
|
|
7031
|
+
if (!IsEnabledOwnedPopup(h, receiver)) receiver = Native.GetWindow(h, 6); // GW_ENABLEDPOPUP
|
|
7032
|
+
if (!IsEnabledOwnedPopup(h, receiver))
|
|
7033
|
+
return Dict("activated", false, "hwnd", h.ToInt64(), "hint", "Window is disabled. Observe its current dialog before activating.");
|
|
7034
|
+
HostGuard(receiver, "activate");
|
|
7035
|
+
}
|
|
7036
|
+
string how = RefocusWindow(receiver, GetB(a, "clickFallback", true));
|
|
6338
7037
|
uint confirmedPid = 0;
|
|
6339
7038
|
long modalOf = 0;
|
|
6340
7039
|
IntPtr foreground = Native.GetForegroundWindow();
|
|
@@ -6343,7 +7042,8 @@ namespace DshComputerUse.Worker
|
|
|
6343
7042
|
// refused while the app was literally waiting for an answer.
|
|
6344
7043
|
IntPtr dialog = (foreground != IntPtr.Zero && foreground != h && SameInputFamily(h, foreground)) ? foreground : IntPtr.Zero;
|
|
6345
7044
|
IntPtr confirmed = dialog != IntPtr.Zero ? dialog : h;
|
|
6346
|
-
if (how == null || !Native.IsWindow(h) || (
|
|
7045
|
+
if (how == null || !Native.IsWindow(h) || (receiver != h && (confirmed != receiver || !IsEnabledOwnedPopup(h, confirmed))) ||
|
|
7046
|
+
(confirmedPid = PidOf(confirmed)) == 0 || !IsForeground(confirmed)) how = "failed";
|
|
6347
7047
|
else
|
|
6348
7048
|
{
|
|
6349
7049
|
if (dialog != IntPtr.Zero) modalOf = h.ToInt64();
|
|
@@ -7280,13 +7980,16 @@ namespace DshComputerUse.Worker
|
|
|
7280
7980
|
|
|
7281
7981
|
string repaired = null;
|
|
7282
7982
|
IntPtr fg = Native.GetForegroundWindow();
|
|
7283
|
-
|
|
7983
|
+
bool exact = GetB(a, "strictHwnd", false) || GetS(a, "shotGeometry", null) != null;
|
|
7984
|
+
if (refocus && exact && (!Native.IsWindowEnabled(want) || want != GetAncestor(fg, 2)))
|
|
7985
|
+
throw InputInterrupted("INPUT_TARGET_CHANGED", "The explicitly named window is no longer foreground. Observe the receiver again.");
|
|
7986
|
+
if (refocus && !exact && want != IntPtr.Zero && TopLevel(fg) != want)
|
|
7284
7987
|
{
|
|
7285
7988
|
repaired = RefocusWindow(want, true);
|
|
7286
7989
|
Thread.Sleep(50);
|
|
7287
7990
|
fg = Native.GetForegroundWindow();
|
|
7288
7991
|
}
|
|
7289
|
-
IntPtr root = TopLevel(fg);
|
|
7992
|
+
IntPtr root = exact ? GetAncestor(fg, 2) : TopLevel(fg);
|
|
7290
7993
|
if (refocus)
|
|
7291
7994
|
{
|
|
7292
7995
|
string mismatch = KickoffFocus.InputProblem(want.ToInt64(),
|
|
@@ -7442,6 +8145,26 @@ namespace DshComputerUse.Worker
|
|
|
7442
8145
|
case "move":
|
|
7443
8146
|
{
|
|
7444
8147
|
RECT cur; Native.GetWindowRect(h, out cur);
|
|
8148
|
+
if (a.ContainsKey("workHwnd")) {
|
|
8149
|
+
var anchor = new IntPtr(GetI(a, "workHwnd", 0));
|
|
8150
|
+
if (!Native.IsWindowVisible(anchor) || Native.IsIconic(anchor) || Native.IsIconic(h) || IsZoomed(h))
|
|
8151
|
+
throw new Exception("WORK_AREA_UNAVAILABLE: observe a visible work window and a restored target");
|
|
8152
|
+
var screen = Screen.FromHandle(anchor);
|
|
8153
|
+
var area = screen.WorkingArea;
|
|
8154
|
+
Rectangle actual = Rectangle.FromLTRB(cur.Left, cur.Top, cur.Right, cur.Bottom);
|
|
8155
|
+
bool moved = !area.Contains(actual);
|
|
8156
|
+
if (moved) {
|
|
8157
|
+
int width = Math.Min(area.Width, actual.Width), height = Math.Min(area.Height, actual.Height);
|
|
8158
|
+
int x = area.Left + (area.Width - width)/2, y = area.Top + (area.Height - height)/2;
|
|
8159
|
+
if (!Native.SetWindowPos(h, IntPtr.Zero, x, y, width, height, 0x0004 | 0x0010))
|
|
8160
|
+
throw new Exception("WINDOW_PLACEMENT_FAILED: inspect the current window rectangle");
|
|
8161
|
+
Thread.Sleep(140);
|
|
8162
|
+
}
|
|
8163
|
+
RECT after;
|
|
8164
|
+
if (!Native.GetWindowRect(h, out after)) throw new Exception("WINDOW_UNAVAILABLE: moved window disappeared");
|
|
8165
|
+
bool contained = area.Contains(Rectangle.FromLTRB(after.Left, after.Top, after.Right, after.Bottom));
|
|
8166
|
+
return Dict("done", "move", "ok", contained, "moved", moved, "contained", contained, "display", screen.DeviceName, "rect", RectDict(after));
|
|
8167
|
+
}
|
|
7445
8168
|
int mx = GetI(a, "x", cur.Left), my = GetI(a, "y", cur.Top);
|
|
7446
8169
|
int mw = GetI(a, "width", cur.Right - cur.Left), mh = GetI(a, "height", cur.Bottom - cur.Top);
|
|
7447
8170
|
if (Native.IsIconic(h)) Native.ShowWindow(h, Native.SW_RESTORE);
|
|
@@ -7457,6 +8180,9 @@ namespace DshComputerUse.Worker
|
|
|
7457
8180
|
return Dict("done", op);
|
|
7458
8181
|
}
|
|
7459
8182
|
|
|
8183
|
+
[DllImport("user32.dll")]
|
|
8184
|
+
static extern bool IsZoomed(IntPtr hwnd);
|
|
8185
|
+
|
|
7460
8186
|
// ---------- UIA ----------
|
|
7461
8187
|
static void AddUiGeometry(Dictionary<string, object> d, System.Windows.Rect? bounds,
|
|
7462
8188
|
bool? offscreen, Rectangle virtualScreen)
|
|
@@ -7684,8 +8410,53 @@ namespace DshComputerUse.Worker
|
|
|
7684
8410
|
return d;
|
|
7685
8411
|
}
|
|
7686
8412
|
|
|
8413
|
+
static Dictionary<string, object> FocusedText(IntPtr hwnd)
|
|
8414
|
+
{
|
|
8415
|
+
if (hwnd == IntPtr.Zero || GetAncestor(Native.GetForegroundWindow(), 2) != hwnd)
|
|
8416
|
+
throw new Exception("FOCUS_CHANGED: name the current foreground window");
|
|
8417
|
+
AutomationElement focus = AutomationElement.FocusedElement;
|
|
8418
|
+
AutomationElement root = AutomationElement.FromHandle(hwnd);
|
|
8419
|
+
AutomationElement ancestor = focus;
|
|
8420
|
+
for (int i = 0; i < 48 && ancestor != null && !Automation.Compare(ancestor, root); i++)
|
|
8421
|
+
ancestor = TreeWalker.RawViewWalker.GetParent(ancestor);
|
|
8422
|
+
if (ancestor == null || !Automation.Compare(ancestor, root))
|
|
8423
|
+
throw new Exception("FOCUS_CHANGED: the focused control is outside the named window");
|
|
8424
|
+
object password = focus.GetCurrentPropertyValue(AutomationElement.IsPasswordProperty, true);
|
|
8425
|
+
if (!(password is bool) || (bool)password) return Dict("hwnd", hwnd.ToInt64(), "textStatus", "protected-or-unknown");
|
|
8426
|
+
const int max = 2048;
|
|
8427
|
+
var result = Dict("hwnd", hwnd.ToInt64(), "id", focus.Current.AutomationId, "role", focus.Current.ControlType.ProgrammaticName,
|
|
8428
|
+
"selectionStatus", "unavailable", "textStatus", "unavailable");
|
|
8429
|
+
object pattern;
|
|
8430
|
+
string value = null;
|
|
8431
|
+
if (focus.TryGetCurrentPattern(TextPattern.Pattern, out pattern)) {
|
|
8432
|
+
var text = (TextPattern)pattern;
|
|
8433
|
+
value = text.DocumentRange.GetText(max + 1);
|
|
8434
|
+
if (text.SupportedTextSelection != SupportedTextSelection.None) {
|
|
8435
|
+
var ranges = text.GetSelection();
|
|
8436
|
+
var selections = new List<string>();
|
|
8437
|
+
bool truncated = ranges.Length > 8;
|
|
8438
|
+
foreach (var range in ranges.Take(8)) {
|
|
8439
|
+
string part = range.GetText(max + 1);
|
|
8440
|
+
truncated |= part.Length > max;
|
|
8441
|
+
selections.Add(part.Substring(0, Math.Min(max, part.Length)));
|
|
8442
|
+
}
|
|
8443
|
+
result["selections"] = selections;
|
|
8444
|
+
result["selectionStatus"] = truncated ? "truncated" : "read";
|
|
8445
|
+
}
|
|
8446
|
+
} else if (focus.TryGetCurrentPattern(ValuePattern.Pattern, out pattern)) value = ((ValuePattern)pattern).Current.Value;
|
|
8447
|
+
if (value != null) {
|
|
8448
|
+
result["value"] = value.Substring(0, Math.Min(value.Length, max));
|
|
8449
|
+
result["textStatus"] = value.Length > max ? "truncated" : "read";
|
|
8450
|
+
}
|
|
8451
|
+
var current = AutomationElement.FocusedElement;
|
|
8452
|
+
if (GetAncestor(Native.GetForegroundWindow(), 2) != hwnd || current == null || !Automation.Compare(current, focus))
|
|
8453
|
+
throw new Exception("FOCUS_CHANGED: capture the focused field again");
|
|
8454
|
+
return result;
|
|
8455
|
+
}
|
|
8456
|
+
|
|
7687
8457
|
static Dictionary<string, object> Uia(Dictionary<string, object> a)
|
|
7688
8458
|
{
|
|
8459
|
+
if (GetB(a, "focused", false)) return FocusedText(new IntPtr(GetI(a, "hwnd", 0)));
|
|
7689
8460
|
IntPtr root = FindHwnd(a);
|
|
7690
8461
|
int maxDepth = Math.Max(1, Math.Min(24, GetI(a, "depth", 6)));
|
|
7691
8462
|
int maxNodes = Math.Max(10, Math.Min(1200, GetI(a, "maxNodes", 120)));
|
|
@@ -7925,6 +8696,30 @@ namespace DshComputerUse.Worker
|
|
|
7925
8696
|
return matches;
|
|
7926
8697
|
}
|
|
7927
8698
|
|
|
8699
|
+
static TextPatternRange SelectExactText(TextPattern pattern, string value, string prefix, string suffix)
|
|
8700
|
+
{
|
|
8701
|
+
if (String.IsNullOrEmpty(value)) throw new Exception("selectText requires nonempty text in value");
|
|
8702
|
+
if (pattern.SupportedTextSelection == SupportedTextSelection.None)
|
|
8703
|
+
throw new Exception("Text selection is unavailable on this control.");
|
|
8704
|
+
var document = pattern.DocumentRange;
|
|
8705
|
+
string needle = prefix + value + suffix;
|
|
8706
|
+
var match = document.FindText(needle, false, false);
|
|
8707
|
+
if (match == null) throw new Exception("TEXT_NOT_FOUND: no matching passage in this control");
|
|
8708
|
+
var rest = document.Clone();
|
|
8709
|
+
rest.MoveEndpointByRange(TextPatternRangeEndpoint.Start, match, TextPatternRangeEndpoint.Start);
|
|
8710
|
+
if (rest.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 1) != 1 ||
|
|
8711
|
+
rest.FindText(needle, false, false) != null)
|
|
8712
|
+
throw new Exception("AMBIGUOUS_TEXT: supply more adjacent prefix or suffix text");
|
|
8713
|
+
if (prefix.Length > 0)
|
|
8714
|
+
match.MoveEndpointByRange(TextPatternRangeEndpoint.Start, match.FindText(prefix, false, false), TextPatternRangeEndpoint.End);
|
|
8715
|
+
if (suffix.Length > 0)
|
|
8716
|
+
match.MoveEndpointByRange(TextPatternRangeEndpoint.End, match.FindText(suffix, true, false), TextPatternRangeEndpoint.Start);
|
|
8717
|
+
if (match.GetText(value.Length + 1) != value) throw new Exception("TEXT_CHANGED: query the passage again");
|
|
8718
|
+
MarkMutation();
|
|
8719
|
+
match.Select();
|
|
8720
|
+
return match;
|
|
8721
|
+
}
|
|
8722
|
+
|
|
7928
8723
|
static Dictionary<string, object> UiaAct(Dictionary<string, object> a)
|
|
7929
8724
|
{
|
|
7930
8725
|
string action = GetS(a, "action", "invoke");
|
|
@@ -7983,6 +8778,8 @@ namespace DshComputerUse.Worker
|
|
|
7983
8778
|
|
|
7984
8779
|
object pat = null;
|
|
7985
8780
|
string via = null;
|
|
8781
|
+
TextPatternRange selectedRange = null;
|
|
8782
|
+
double beforeScrollPercent = 0;
|
|
7986
8783
|
switch (action)
|
|
7987
8784
|
{
|
|
7988
8785
|
case "invoke":
|
|
@@ -7991,6 +8788,22 @@ namespace DshComputerUse.Worker
|
|
|
7991
8788
|
case "select":
|
|
7992
8789
|
if (found.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pat)) { MarkMutation(); ((SelectionItemPattern)pat).Select(); via = "SelectionItemPattern"; }
|
|
7993
8790
|
break;
|
|
8791
|
+
case "addToSelection":
|
|
8792
|
+
case "removeFromSelection":
|
|
8793
|
+
if (found.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pat)) {
|
|
8794
|
+
var item = (SelectionItemPattern)pat;
|
|
8795
|
+
MarkMutation();
|
|
8796
|
+
if (action == "addToSelection") item.AddToSelection(); else item.RemoveFromSelection();
|
|
8797
|
+
via = "SelectionItemPattern." + action;
|
|
8798
|
+
}
|
|
8799
|
+
break;
|
|
8800
|
+
case "selectText":
|
|
8801
|
+
if (found.Current.IsPassword) throw new Exception("selectText is unavailable on password controls");
|
|
8802
|
+
if (found.TryGetCurrentPattern(TextPattern.Pattern, out pat)) {
|
|
8803
|
+
selectedRange = SelectExactText((TextPattern)pat, GetS(a, "value", ""), GetS(a, "prefix", "") ?? "", GetS(a, "suffix", "") ?? "");
|
|
8804
|
+
via = "TextPattern.Select";
|
|
8805
|
+
}
|
|
8806
|
+
break;
|
|
7994
8807
|
case "expand":
|
|
7995
8808
|
if (found.TryGetCurrentPattern(ExpandCollapsePattern.Pattern, out pat)) { MarkMutation(); ((ExpandCollapsePattern)pat).Expand(); via = "ExpandCollapsePattern.Expand"; }
|
|
7996
8809
|
break;
|
|
@@ -8004,6 +8817,15 @@ namespace DshComputerUse.Worker
|
|
|
8004
8817
|
{
|
|
8005
8818
|
string val = GetS(a, "value", "");
|
|
8006
8819
|
if (found.TryGetCurrentPattern(ValuePattern.Pattern, out pat)) { MarkMutation(); ((ValuePattern)pat).SetValue(val); via = "ValuePattern"; }
|
|
8820
|
+
else if (found.TryGetCurrentPattern(RangeValuePattern.Pattern, out pat)) {
|
|
8821
|
+
var range = (RangeValuePattern)pat;
|
|
8822
|
+
double number;
|
|
8823
|
+
if (!Double.TryParse(val, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out number) ||
|
|
8824
|
+
Double.IsNaN(number) || Double.IsInfinity(number) || number < range.Current.Minimum || number > range.Current.Maximum)
|
|
8825
|
+
throw new Exception("RANGE_VALUE_INVALID: supply a finite value within the control's range");
|
|
8826
|
+
if (range.Current.IsReadOnly) throw new Exception("RANGE_VALUE_READ_ONLY");
|
|
8827
|
+
MarkMutation(); range.SetValue(number); via = "RangeValuePattern";
|
|
8828
|
+
}
|
|
8007
8829
|
break;
|
|
8008
8830
|
}
|
|
8009
8831
|
case "focus":
|
|
@@ -8011,8 +8833,22 @@ namespace DshComputerUse.Worker
|
|
|
8011
8833
|
case "scrollIntoView":
|
|
8012
8834
|
if (found.TryGetCurrentPattern(ScrollItemPattern.Pattern, out pat)) { MarkMutation(); ((ScrollItemPattern)pat).ScrollIntoView(); via = "ScrollItemPattern"; }
|
|
8013
8835
|
break;
|
|
8836
|
+
case "scroll":
|
|
8837
|
+
if (found.TryGetCurrentPattern(ScrollPattern.Pattern, out pat)) {
|
|
8838
|
+
var scroll = (ScrollPattern)pat;
|
|
8839
|
+
string direction = GetS(a, "value", "");
|
|
8840
|
+
bool horizontal = direction == "left" || direction == "right";
|
|
8841
|
+
if (!horizontal && direction != "up" && direction != "down") throw new Exception("scroll value must be up, down, left or right");
|
|
8842
|
+
if (horizontal ? !scroll.Current.HorizontallyScrollable : !scroll.Current.VerticallyScrollable)
|
|
8843
|
+
throw new Exception("SCROLL_AXIS_UNAVAILABLE: select a scrollable container for this axis");
|
|
8844
|
+
var amount = direction == "up" || direction == "left" ? ScrollAmount.LargeDecrement : ScrollAmount.LargeIncrement;
|
|
8845
|
+
beforeScrollPercent = horizontal ? scroll.Current.HorizontalScrollPercent : scroll.Current.VerticalScrollPercent;
|
|
8846
|
+
MarkMutation(); scroll.Scroll(horizontal ? amount : ScrollAmount.NoAmount, horizontal ? ScrollAmount.NoAmount : amount);
|
|
8847
|
+
via = "ScrollPattern";
|
|
8848
|
+
}
|
|
8849
|
+
break;
|
|
8014
8850
|
default:
|
|
8015
|
-
throw new Exception("action must be invoke|select|expand|collapse|toggle|setValue|focus|scrollIntoView");
|
|
8851
|
+
throw new Exception("action must be invoke|select|addToSelection|removeFromSelection|selectText|expand|collapse|toggle|setValue|focus|scrollIntoView");
|
|
8016
8852
|
}
|
|
8017
8853
|
EndActuationForReadback();
|
|
8018
8854
|
if (via == null)
|
|
@@ -8020,6 +8856,20 @@ namespace DshComputerUse.Worker
|
|
|
8020
8856
|
|
|
8021
8857
|
Thread.Sleep(GetI(a, "settleMs", 120));
|
|
8022
8858
|
Dictionary<string, object> res = Dict("action", action, "via", via, "element", ElemDict(found), "scanned", seen);
|
|
8859
|
+
try {
|
|
8860
|
+
if (via == "ScrollPattern") {
|
|
8861
|
+
var scroll = ((ScrollPattern)pat).Current;
|
|
8862
|
+
string direction = GetS(a, "value", "");
|
|
8863
|
+
res["beforePercent"] = beforeScrollPercent;
|
|
8864
|
+
res["afterPercent"] = direction == "left" || direction == "right" ? scroll.HorizontalScrollPercent : scroll.VerticalScrollPercent;
|
|
8865
|
+
} else if (selectedRange != null) {
|
|
8866
|
+
var selected = ((TextPattern)pat).GetSelection();
|
|
8867
|
+
res["selectionVerified"] = selected.Length == 1 && selected[0].Compare(selectedRange);
|
|
8868
|
+
} else if (via == "RangeValuePattern") res["rangeValue"] = ((RangeValuePattern)pat).Current.Value;
|
|
8869
|
+
else if (action == "addToSelection" || action == "removeFromSelection")
|
|
8870
|
+
res["isSelected"] = ((SelectionItemPattern)pat).Current.IsSelected;
|
|
8871
|
+
} catch (InvalidOperationException) { res["readbackUnavailable"] = true; }
|
|
8872
|
+
catch (System.Runtime.InteropServices.COMException) { res["readbackUnavailable"] = true; }
|
|
8023
8873
|
if (observed != null) res["resolution"] = Dict("target", token, "mode", resolution, "rebound", resolution != "runtime-id");
|
|
8024
8874
|
if (skipped.Count > 0) res["skippedEarlierMatches"] = skipped;
|
|
8025
8875
|
return res;
|
|
@@ -8250,6 +9100,7 @@ namespace DshComputerUse.Worker
|
|
|
8250
9100
|
// Compatibility entry point: no coordinate/frequency/quietMs override can
|
|
8251
9101
|
// disable the event-driven handoff. Plain Esc and the screen corner are ordinary UI.
|
|
8252
9102
|
CheckHumanInput();
|
|
9103
|
+
lastCaptureKey = null; lastCaptureSample = null;
|
|
8253
9104
|
Panic.AgentActed();
|
|
8254
9105
|
}
|
|
8255
9106
|
|