@copylee/dsh-computer-use 0.12.0 → 0.13.1
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/helper/Capture.cs +682 -0
- package/helper/Input.cs +500 -0
- package/helper/Native.cs +136 -0
- package/helper/Overlay.cs +1755 -0
- package/helper/Program.cs +244 -0
- package/helper/Uia.cs +899 -0
- package/helper/Windows.cs +761 -0
- package/lib/client.js +245 -53
- package/lib/index.js +828 -368
- package/lib/types/access.d.ts +7 -0
- package/lib/types/cdp.d.ts +14 -3
- package/lib/types/client/skills-card.d.ts +3 -3
- package/lib/types/computer.d.ts +15 -3
- package/lib/types/diagnostics.d.ts +1 -0
- package/lib/types/helper-client.d.ts +4 -2
- package/lib/types/index.d.ts +1 -0
- package/lib/types/lease.d.ts +30 -0
- package/lib/types/overlay.d.ts +2 -1
- package/lib/types/ui-diff.d.ts +28 -0
- package/package.json +3 -2
- package/helper/CuHelper.cs +0 -4749
|
@@ -0,0 +1,682 @@
|
|
|
1
|
+
// Display enumeration, BitBlt/Magnification screenshots, settle detection, and Windows WinRT OCR (C# 5).
|
|
2
|
+
|
|
3
|
+
using System;
|
|
4
|
+
using System.Collections;
|
|
5
|
+
using System.Collections.Generic;
|
|
6
|
+
using System.Diagnostics;
|
|
7
|
+
using System.Drawing;
|
|
8
|
+
using System.Drawing.Drawing2D;
|
|
9
|
+
using System.Drawing.Imaging;
|
|
10
|
+
using System.Drawing.Text;
|
|
11
|
+
using System.IO;
|
|
12
|
+
using System.Reflection;
|
|
13
|
+
using System.Runtime.InteropServices;
|
|
14
|
+
using System.Text;
|
|
15
|
+
using System.Threading;
|
|
16
|
+
using System.Web.Script.Serialization;
|
|
17
|
+
using System.Windows.Automation;
|
|
18
|
+
using System.Windows.Forms;
|
|
19
|
+
using Microsoft.Win32;
|
|
20
|
+
|
|
21
|
+
namespace DshComputerUse
|
|
22
|
+
{
|
|
23
|
+
internal static class Screen2
|
|
24
|
+
{
|
|
25
|
+
public static List<object> Displays()
|
|
26
|
+
{
|
|
27
|
+
var list = new List<object>();
|
|
28
|
+
Native.MonitorEnumProc cb = delegate (IntPtr h, IntPtr hdc, ref Native.RECT rc, IntPtr data)
|
|
29
|
+
{
|
|
30
|
+
var info = new Native.MONITORINFOEX();
|
|
31
|
+
info.cbSize = Marshal.SizeOf(typeof(Native.MONITORINFOEX));
|
|
32
|
+
Native.GetMonitorInfo(h, ref info);
|
|
33
|
+
uint dx = 96, dy = 96;
|
|
34
|
+
try { Native.GetDpiForMonitor(h, 0, out dx, out dy); } catch (Exception) { }
|
|
35
|
+
var d = new Dictionary<string, object>();
|
|
36
|
+
d["x"] = info.rcMonitor.Left; d["y"] = info.rcMonitor.Top;
|
|
37
|
+
d["width"] = info.rcMonitor.Right - info.rcMonitor.Left; d["height"] = info.rcMonitor.Bottom - info.rcMonitor.Top;
|
|
38
|
+
d["workX"] = info.rcWork.Left; d["workY"] = info.rcWork.Top;
|
|
39
|
+
d["workWidth"] = info.rcWork.Right - info.rcWork.Left; d["workHeight"] = info.rcWork.Bottom - info.rcWork.Top;
|
|
40
|
+
d["primary"] = (info.dwFlags & 1) != 0;
|
|
41
|
+
d["dpi"] = (int)dx;
|
|
42
|
+
d["name"] = info.szDevice;
|
|
43
|
+
list.Add(d);
|
|
44
|
+
return true;
|
|
45
|
+
};
|
|
46
|
+
Native.EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, cb, IntPtr.Zero);
|
|
47
|
+
GC.KeepAlive(cb);
|
|
48
|
+
return list;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Sample every 8th pixel of a screen rectangle (BGR bytes). */
|
|
52
|
+
/** Sample the screen for settle detection; the card area is blanked (no flicker). */
|
|
53
|
+
static byte[] Sample(int x, int y, int w, int h)
|
|
54
|
+
{
|
|
55
|
+
using (var bmp = new Bitmap(w, h, PixelFormat.Format24bppRgb))
|
|
56
|
+
{
|
|
57
|
+
using (var g = Graphics.FromImage(bmp))
|
|
58
|
+
{
|
|
59
|
+
IntPtr dst = g.GetHdc();
|
|
60
|
+
IntPtr src = Native.GetDC(IntPtr.Zero);
|
|
61
|
+
try { Native.BitBlt(dst, 0, 0, w, h, src, x, y, 0x00CC0020 | 0x40000000); }
|
|
62
|
+
finally { Native.ReleaseDC(IntPtr.Zero, src); g.ReleaseHdc(dst); }
|
|
63
|
+
CardLayer.Blank(g, x, y);
|
|
64
|
+
}
|
|
65
|
+
return SampleBitmap(bmp);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Every 8th pixel of a 24-bit bitmap (BGR bytes). */
|
|
70
|
+
static byte[] SampleBitmap(Bitmap bmp)
|
|
71
|
+
{
|
|
72
|
+
int w = bmp.Width, h = bmp.Height;
|
|
73
|
+
var data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
|
|
74
|
+
try
|
|
75
|
+
{
|
|
76
|
+
int sx = (w + 7) / 8, sy = (h + 7) / 8;
|
|
77
|
+
var row = new byte[data.Stride];
|
|
78
|
+
var outp = new byte[sx * sy * 3];
|
|
79
|
+
int k = 0;
|
|
80
|
+
for (int j = 0; j < sy; j++)
|
|
81
|
+
{
|
|
82
|
+
Marshal.Copy(new IntPtr(data.Scan0.ToInt64() + (long)j * 8 * data.Stride), row, 0, data.Stride);
|
|
83
|
+
for (int i = 0; i < sx; i++) { int o = i * 8 * 3; outp[k++] = row[o]; outp[k++] = row[o + 1]; outp[k++] = row[o + 2]; }
|
|
84
|
+
}
|
|
85
|
+
return outp;
|
|
86
|
+
}
|
|
87
|
+
finally { bmp.UnlockBits(data); }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** What the screen looked like in the last screenshot the model was shown (per slot: full vs zoom). */
|
|
91
|
+
sealed class MarkedFrame
|
|
92
|
+
{
|
|
93
|
+
public string Rect;
|
|
94
|
+
public byte[] Sample;
|
|
95
|
+
public long OutPixels;
|
|
96
|
+
public int Quality;
|
|
97
|
+
}
|
|
98
|
+
static readonly Dictionary<string, MarkedFrame> markedBySlot = new Dictionary<string, MarkedFrame>();
|
|
99
|
+
|
|
100
|
+
static string RectKey(int x, int y, int w, int h) { return x + "," + y + "," + w + "," + h; }
|
|
101
|
+
|
|
102
|
+
static double Changed(byte[] a, byte[] b)
|
|
103
|
+
{
|
|
104
|
+
int n = a.Length / 3, diff = 0;
|
|
105
|
+
for (int i = 0; i < a.Length; i += 3)
|
|
106
|
+
if (Math.Abs(a[i] - b[i]) + Math.Abs(a[i + 1] - b[i + 1]) + Math.Abs(a[i + 2] - b[i + 2]) > 30) diff++;
|
|
107
|
+
return n == 0 ? 0 : (double)diff / n;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Wait until the screen stops changing: at least minMs, then until two
|
|
112
|
+
* consecutive samples (quietMs apart in total) differ in under 0.2% of
|
|
113
|
+
* the sampled pixels, or maxMs passes (videos, spinners).
|
|
114
|
+
*/
|
|
115
|
+
public static Dictionary<string, object> Settle(Dictionary<string, object> r)
|
|
116
|
+
{
|
|
117
|
+
int x = Args.Int(r, "x", 0), y = Args.Int(r, "y", 0), w = Args.Int(r, "width", 0), h = Args.Int(r, "height", 0);
|
|
118
|
+
int minMs = Args.Int(r, "minMs", 300), maxMs = Args.Int(r, "maxMs", 2500), interval = Args.Int(r, "intervalMs", 120), quietMs = Args.Int(r, "quietMs", 240);
|
|
119
|
+
if (w <= 0 || h <= 0) throw new Exception("invalid settle rect");
|
|
120
|
+
var watch = System.Diagnostics.Stopwatch.StartNew();
|
|
121
|
+
byte[] prev = Sample(x, y, w, h);
|
|
122
|
+
long quietSince = -1;
|
|
123
|
+
bool stable = false;
|
|
124
|
+
while (true)
|
|
125
|
+
{
|
|
126
|
+
Thread.Sleep(interval);
|
|
127
|
+
byte[] cur = Sample(x, y, w, h);
|
|
128
|
+
long now = watch.ElapsedMilliseconds;
|
|
129
|
+
if (Changed(prev, cur) < 0.002) { if (quietSince < 0) quietSince = now - interval; }
|
|
130
|
+
else quietSince = -1;
|
|
131
|
+
prev = cur;
|
|
132
|
+
if (now >= minMs && quietSince >= 0 && now - quietSince >= quietMs) { stable = true; break; }
|
|
133
|
+
if (now >= maxMs) break;
|
|
134
|
+
}
|
|
135
|
+
var d = new Dictionary<string, object>();
|
|
136
|
+
d["ms"] = (int)watch.ElapsedMilliseconds;
|
|
137
|
+
d["stable"] = stable;
|
|
138
|
+
return d;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
static ImageCodecInfo jpegCodec;
|
|
142
|
+
|
|
143
|
+
public static Bitmap Grab(int x, int y, int w, int h, out string via)
|
|
144
|
+
{
|
|
145
|
+
via = "blt";
|
|
146
|
+
var bmp = new Bitmap(w, h, PixelFormat.Format24bppRgb);
|
|
147
|
+
try
|
|
148
|
+
{
|
|
149
|
+
using (var g = Graphics.FromImage(bmp))
|
|
150
|
+
{
|
|
151
|
+
IntPtr dst = g.GetHdc();
|
|
152
|
+
IntPtr src = Native.GetDC(IntPtr.Zero);
|
|
153
|
+
// The DSH card is for the user only: capture what is under it.
|
|
154
|
+
// Preferred: the Magnification API renders the screen without
|
|
155
|
+
// the card (no flicker). Fallback: hide the card for one BitBlt.
|
|
156
|
+
bool done = false;
|
|
157
|
+
var area = new Rectangle(x, y, w, h);
|
|
158
|
+
if (CardLayer.Covers(area))
|
|
159
|
+
{
|
|
160
|
+
g.ReleaseHdc(dst);
|
|
161
|
+
dst = IntPtr.Zero;
|
|
162
|
+
using (var mag = MagCapture.Capture(area, CardLayer.Hwnd))
|
|
163
|
+
{
|
|
164
|
+
if (mag != null) { g.DrawImageUnscaled(mag, 0, 0); done = true; via = "mag"; }
|
|
165
|
+
}
|
|
166
|
+
if (!done) dst = g.GetHdc();
|
|
167
|
+
}
|
|
168
|
+
if (!done)
|
|
169
|
+
{
|
|
170
|
+
using (CardLayer.Hide(area))
|
|
171
|
+
{
|
|
172
|
+
try { Native.BitBlt(dst, 0, 0, w, h, src, x, y, 0x00CC0020 | 0x40000000); }
|
|
173
|
+
finally { g.ReleaseHdc(dst); }
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
Native.ReleaseDC(IntPtr.Zero, src);
|
|
177
|
+
}
|
|
178
|
+
return bmp;
|
|
179
|
+
}
|
|
180
|
+
catch
|
|
181
|
+
{
|
|
182
|
+
bmp.Dispose();
|
|
183
|
+
throw;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
public static Dictionary<string, object> Capture(Dictionary<string, object> r)
|
|
188
|
+
{
|
|
189
|
+
int x = Args.Int(r, "x", 0), y = Args.Int(r, "y", 0), w = Args.Int(r, "width", 0), h = Args.Int(r, "height", 0);
|
|
190
|
+
int ow = Args.Int(r, "outWidth", w), oh = Args.Int(r, "outHeight", h);
|
|
191
|
+
int quality = Args.Int(r, "quality", 80);
|
|
192
|
+
if (w <= 0 || h <= 0 || ow <= 0 || oh <= 0) throw new Exception("invalid capture size");
|
|
193
|
+
string via;
|
|
194
|
+
using (var bmp = Grab(x, y, w, h, out via))
|
|
195
|
+
{
|
|
196
|
+
// compare: report "unchanged" instead of an identical image; mark: remember for next time.
|
|
197
|
+
bool compare = Args.Bool(r, "compare", false), mark = Args.Bool(r, "mark", false) || compare;
|
|
198
|
+
if (mark)
|
|
199
|
+
{
|
|
200
|
+
string slot = Args.Str(r, "slot", "full");
|
|
201
|
+
if (slot.Length == 0) slot = "full";
|
|
202
|
+
string key = RectKey(x, y, w, h);
|
|
203
|
+
byte[] sample = SampleBitmap(bmp);
|
|
204
|
+
long outPixels = (long)ow * oh;
|
|
205
|
+
MarkedFrame prev;
|
|
206
|
+
if (compare && markedBySlot.TryGetValue(slot, out prev) && prev.Rect == key
|
|
207
|
+
&& outPixels <= prev.OutPixels && quality <= prev.Quality
|
|
208
|
+
&& Changed(prev.Sample, sample) < Args.Double(r, "threshold", 0.0005))
|
|
209
|
+
{
|
|
210
|
+
var same = new Dictionary<string, object>();
|
|
211
|
+
same["unchanged"] = true;
|
|
212
|
+
return same;
|
|
213
|
+
}
|
|
214
|
+
var next = new MarkedFrame();
|
|
215
|
+
next.Rect = key;
|
|
216
|
+
next.Sample = sample;
|
|
217
|
+
next.OutPixels = outPixels;
|
|
218
|
+
next.Quality = quality;
|
|
219
|
+
markedBySlot[slot] = next;
|
|
220
|
+
}
|
|
221
|
+
Bitmap output = bmp;
|
|
222
|
+
Bitmap scaled = null;
|
|
223
|
+
try
|
|
224
|
+
{
|
|
225
|
+
if (ow != w || oh != h)
|
|
226
|
+
{
|
|
227
|
+
scaled = new Bitmap(ow, oh, PixelFormat.Format24bppRgb);
|
|
228
|
+
using (var g2 = Graphics.FromImage(scaled))
|
|
229
|
+
using (var attrs = new ImageAttributes())
|
|
230
|
+
{
|
|
231
|
+
attrs.SetWrapMode(WrapMode.TileFlipXY);
|
|
232
|
+
g2.InterpolationMode = InterpolationMode.HighQualityBicubic;
|
|
233
|
+
g2.PixelOffsetMode = PixelOffsetMode.HighQuality;
|
|
234
|
+
g2.CompositingQuality = CompositingQuality.HighQuality;
|
|
235
|
+
g2.DrawImage(bmp, new Rectangle(0, 0, ow, oh), 0, 0, w, h, GraphicsUnit.Pixel, attrs);
|
|
236
|
+
}
|
|
237
|
+
output = scaled;
|
|
238
|
+
}
|
|
239
|
+
if (jpegCodec == null)
|
|
240
|
+
foreach (var c in ImageCodecInfo.GetImageEncoders()) if (c.MimeType == "image/jpeg") jpegCodec = c;
|
|
241
|
+
using (var ms = new MemoryStream())
|
|
242
|
+
using (var ep = new EncoderParameters(1))
|
|
243
|
+
{
|
|
244
|
+
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
|
|
245
|
+
output.Save(ms, jpegCodec, ep);
|
|
246
|
+
var d = new Dictionary<string, object>();
|
|
247
|
+
d["data"] = Convert.ToBase64String(ms.ToArray());
|
|
248
|
+
d["via"] = via == "blt" && MagCapture.Why.Length > 0 ? "blt (" + MagCapture.Why + ")" : via;
|
|
249
|
+
d["width"] = ow; d["height"] = oh;
|
|
250
|
+
return d;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
finally { if (scaled != null) scaled.Dispose(); }
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Built-in Windows 10/11 OCR via WinRT reflection (Windows.Media.Ocr).
|
|
260
|
+
* Zero extra compile references or native DLLs: falls back cleanly if the
|
|
261
|
+
* host OS has no WinRT OCR language pack installed.
|
|
262
|
+
*/
|
|
263
|
+
internal static class Ocr
|
|
264
|
+
{
|
|
265
|
+
static Type tEngine, tDecoder, tStream, tWriter, tAsyncInfo;
|
|
266
|
+
static object cachedEngine;
|
|
267
|
+
static string cachedLanguage = "";
|
|
268
|
+
static int cachedMaxDim = 2600;
|
|
269
|
+
static bool initTried;
|
|
270
|
+
|
|
271
|
+
static void EnsureTypes()
|
|
272
|
+
{
|
|
273
|
+
if (initTried) return;
|
|
274
|
+
initTried = true;
|
|
275
|
+
tEngine = Type.GetType("Windows.Media.Ocr.OcrEngine, Windows.Media, ContentType=WindowsRuntime", false);
|
|
276
|
+
tDecoder = Type.GetType("Windows.Graphics.Imaging.BitmapDecoder, Windows.Graphics, ContentType=WindowsRuntime", false);
|
|
277
|
+
tStream = Type.GetType("Windows.Storage.Streams.InMemoryRandomAccessStream, Windows.Storage, ContentType=WindowsRuntime", false);
|
|
278
|
+
tWriter = Type.GetType("Windows.Storage.Streams.DataWriter, Windows.Storage, ContentType=WindowsRuntime", false);
|
|
279
|
+
tAsyncInfo = Type.GetType("Windows.Foundation.IAsyncInfo, Windows.Foundation, ContentType=WindowsRuntime", false);
|
|
280
|
+
if (tEngine == null || tDecoder == null || tStream == null || tWriter == null || tAsyncInfo == null) return;
|
|
281
|
+
try
|
|
282
|
+
{
|
|
283
|
+
var create = tEngine.GetMethod("TryCreateFromUserProfileLanguages", BindingFlags.Public | BindingFlags.Static);
|
|
284
|
+
if (create != null) cachedEngine = create.Invoke(null, null);
|
|
285
|
+
if (cachedEngine != null)
|
|
286
|
+
{
|
|
287
|
+
object lang = GetProp(cachedEngine, "RecognizerLanguage");
|
|
288
|
+
if (lang != null) cachedLanguage = Convert.ToString(GetProp(lang, "LanguageTag")) ?? "";
|
|
289
|
+
var maxProp = tEngine.GetProperty("MaxImageDimension", BindingFlags.Public | BindingFlags.Static);
|
|
290
|
+
if (maxProp != null)
|
|
291
|
+
{
|
|
292
|
+
int dim = Convert.ToInt32(maxProp.GetValue(null, null));
|
|
293
|
+
if (dim >= 512) cachedMaxDim = dim;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
catch (Exception) { cachedEngine = null; }
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
static MethodInfo FindMethod(Type t, string name, int argCount)
|
|
301
|
+
{
|
|
302
|
+
if (t == null) return null;
|
|
303
|
+
foreach (var m in t.GetMethods(BindingFlags.Public | BindingFlags.Instance))
|
|
304
|
+
if (m.Name == name && m.GetParameters().Length == argCount) return m;
|
|
305
|
+
foreach (var iface in t.GetInterfaces())
|
|
306
|
+
foreach (var m in iface.GetMethods(BindingFlags.Public | BindingFlags.Instance))
|
|
307
|
+
if (m.Name == name && m.GetParameters().Length == argCount) return m;
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
static object Invoke(object target, string name, params object[] args)
|
|
312
|
+
{
|
|
313
|
+
var m = FindMethod(target.GetType(), name, args == null ? 0 : args.Length);
|
|
314
|
+
if (m == null) throw new Exception("WinRT method not found: " + name);
|
|
315
|
+
return m.Invoke(target, args);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
static object InvokeAsync(object target, string name, int timeoutMs, params object[] args)
|
|
319
|
+
{
|
|
320
|
+
var m = FindMethod(target.GetType(), name, args == null ? 0 : args.Length);
|
|
321
|
+
if (m == null) throw new Exception("WinRT method not found: " + name);
|
|
322
|
+
object op = m.Invoke(target, args);
|
|
323
|
+
return AwaitWinRt(op, m.ReturnType, timeoutMs);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
static object GetProp(object target, string name)
|
|
327
|
+
{
|
|
328
|
+
var t = target.GetType();
|
|
329
|
+
var p = t.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
|
|
330
|
+
if (p != null) return p.GetValue(target, null);
|
|
331
|
+
foreach (var iface in t.GetInterfaces())
|
|
332
|
+
{
|
|
333
|
+
p = iface.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
|
|
334
|
+
if (p != null) return p.GetValue(target, null);
|
|
335
|
+
}
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
static object AwaitWinRt(object asyncOp, Type asyncType, int timeoutMs)
|
|
340
|
+
{
|
|
341
|
+
if (asyncOp == null) return null;
|
|
342
|
+
var statusProp = tAsyncInfo.GetProperty("Status");
|
|
343
|
+
var errProp = tAsyncInfo.GetProperty("ErrorCode");
|
|
344
|
+
var watch = Stopwatch.StartNew();
|
|
345
|
+
while (true)
|
|
346
|
+
{
|
|
347
|
+
int status = Convert.ToInt32(statusProp.GetValue(asyncOp, null));
|
|
348
|
+
if (status == 1) // Completed
|
|
349
|
+
{
|
|
350
|
+
var getResults = FindMethod(asyncType, "GetResults", 0) ?? FindMethod(asyncOp.GetType(), "GetResults", 0);
|
|
351
|
+
return getResults != null ? getResults.Invoke(asyncOp, null) : null;
|
|
352
|
+
}
|
|
353
|
+
if (status == 2) throw new Exception("Windows OCR operation was cancelled");
|
|
354
|
+
if (status == 3)
|
|
355
|
+
{
|
|
356
|
+
object err = errProp != null ? errProp.GetValue(asyncOp, null) : null;
|
|
357
|
+
throw new Exception("Windows OCR failed: " + (err != null ? err.ToString() : "unknown error"));
|
|
358
|
+
}
|
|
359
|
+
if (watch.ElapsedMilliseconds >= timeoutMs)
|
|
360
|
+
{
|
|
361
|
+
try { var cancel = tAsyncInfo.GetMethod("Cancel"); if (cancel != null) cancel.Invoke(asyncOp, null); } catch (Exception) { }
|
|
362
|
+
throw new Exception("Windows OCR timed out");
|
|
363
|
+
}
|
|
364
|
+
Thread.Sleep(5);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
static bool IsCjk(char c)
|
|
369
|
+
{
|
|
370
|
+
return (c >= '\u4E00' && c <= '\u9FFF') || (c >= '\u3400' && c <= '\u4DBF')
|
|
371
|
+
|| (c >= '\u3000' && c <= '\u303F') || (c >= '\uFF00' && c <= '\uFFEF');
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** Collapse spaces Windows.Media.Ocr inserts between adjacent CJK characters. */
|
|
375
|
+
static string CleanLineText(string s)
|
|
376
|
+
{
|
|
377
|
+
if (string.IsNullOrEmpty(s)) return "";
|
|
378
|
+
var sb = new StringBuilder(s.Length);
|
|
379
|
+
for (int i = 0; i < s.Length; i++)
|
|
380
|
+
{
|
|
381
|
+
char c = s[i];
|
|
382
|
+
if (c == ' ' && sb.Length > 0 && i + 1 < s.Length && IsCjk(sb[sb.Length - 1]) && IsCjk(s[i + 1]))
|
|
383
|
+
continue;
|
|
384
|
+
sb.Append(c);
|
|
385
|
+
}
|
|
386
|
+
return sb.ToString();
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
static void TryDispose(object obj)
|
|
390
|
+
{
|
|
391
|
+
var d = obj as IDisposable;
|
|
392
|
+
if (d != null) { try { d.Dispose(); } catch (Exception) { } }
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
public static Dictionary<string, object> Read(Dictionary<string, object> r)
|
|
396
|
+
{
|
|
397
|
+
EnsureTypes();
|
|
398
|
+
if (cachedEngine == null)
|
|
399
|
+
throw new Exception("Windows OCR is not available on this system (no OCR language pack found).");
|
|
400
|
+
|
|
401
|
+
int x, y, w, h;
|
|
402
|
+
var meta = new Dictionary<string, object>();
|
|
403
|
+
if (Args.Has(r, "width") && Args.Has(r, "height"))
|
|
404
|
+
{
|
|
405
|
+
x = Args.Int(r, "x", 0);
|
|
406
|
+
y = Args.Int(r, "y", 0);
|
|
407
|
+
w = Args.Int(r, "width", 0);
|
|
408
|
+
h = Args.Int(r, "height", 0);
|
|
409
|
+
}
|
|
410
|
+
else
|
|
411
|
+
{
|
|
412
|
+
IntPtr hwnd = Args.Has(r, "hwnd") ? new IntPtr(Convert.ToInt64(r["hwnd"])) : Native.GetForegroundWindow();
|
|
413
|
+
var desc = Windows.Describe(hwnd);
|
|
414
|
+
if (desc.Count == 0) throw new Exception("No target window found for OCR.");
|
|
415
|
+
foreach (var kv in desc) meta[kv.Key] = kv.Value;
|
|
416
|
+
var vs = SystemInformation.VirtualScreen;
|
|
417
|
+
int rx = Convert.ToInt32(desc["x"]), ry = Convert.ToInt32(desc["y"]);
|
|
418
|
+
int rw = Convert.ToInt32(desc["width"]), rh = Convert.ToInt32(desc["height"]);
|
|
419
|
+
int left = Math.Max(vs.Left, rx);
|
|
420
|
+
int top = Math.Max(vs.Top, ry);
|
|
421
|
+
int right = Math.Min(vs.Right, rx + rw);
|
|
422
|
+
int bottom = Math.Min(vs.Bottom, ry + rh);
|
|
423
|
+
x = left; y = top; w = right - left; h = bottom - top;
|
|
424
|
+
}
|
|
425
|
+
if (w <= 2 || h <= 2) throw new Exception("Target area is too small for OCR.");
|
|
426
|
+
|
|
427
|
+
string via;
|
|
428
|
+
using (var rawBmp = Screen2.Grab(x, y, w, h, out via))
|
|
429
|
+
{
|
|
430
|
+
double scale = 1.0;
|
|
431
|
+
int maxSide = Math.Max(w, h);
|
|
432
|
+
if (maxSide > cachedMaxDim) scale = (double)cachedMaxDim / maxSide;
|
|
433
|
+
Bitmap work = rawBmp;
|
|
434
|
+
Bitmap resized = null;
|
|
435
|
+
byte[] pngBytes;
|
|
436
|
+
try
|
|
437
|
+
{
|
|
438
|
+
if (scale < 1.0)
|
|
439
|
+
{
|
|
440
|
+
int nw = Math.Max(1, (int)Math.Round(w * scale));
|
|
441
|
+
int nh = Math.Max(1, (int)Math.Round(h * scale));
|
|
442
|
+
resized = new Bitmap(nw, nh, PixelFormat.Format24bppRgb);
|
|
443
|
+
using (var g = Graphics.FromImage(resized))
|
|
444
|
+
{
|
|
445
|
+
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
|
|
446
|
+
g.DrawImage(rawBmp, 0, 0, nw, nh);
|
|
447
|
+
}
|
|
448
|
+
work = resized;
|
|
449
|
+
}
|
|
450
|
+
using (var ms = new MemoryStream())
|
|
451
|
+
{
|
|
452
|
+
work.Save(ms, ImageFormat.Png);
|
|
453
|
+
pngBytes = ms.ToArray();
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
finally { if (resized != null) resized.Dispose(); }
|
|
457
|
+
|
|
458
|
+
object ras = null, writer = null, softwareBitmap = null;
|
|
459
|
+
try
|
|
460
|
+
{
|
|
461
|
+
ras = Activator.CreateInstance(tStream);
|
|
462
|
+
writer = Activator.CreateInstance(tWriter, new object[] { ras });
|
|
463
|
+
Invoke(writer, "WriteBytes", new object[] { pngBytes });
|
|
464
|
+
InvokeAsync(writer, "StoreAsync", 8000);
|
|
465
|
+
InvokeAsync(writer, "FlushAsync", 8000);
|
|
466
|
+
Invoke(writer, "DetachStream");
|
|
467
|
+
TryDispose(writer); writer = null;
|
|
468
|
+
Invoke(ras, "Seek", new object[] { (ulong)0 });
|
|
469
|
+
|
|
470
|
+
MethodInfo createDecoder = null;
|
|
471
|
+
foreach (var m in tDecoder.GetMethods(BindingFlags.Public | BindingFlags.Static))
|
|
472
|
+
if (m.Name == "CreateAsync" && m.GetParameters().Length == 1) { createDecoder = m; break; }
|
|
473
|
+
if (createDecoder == null) throw new Exception("BitmapDecoder.CreateAsync not found");
|
|
474
|
+
object decoder = AwaitWinRt(createDecoder.Invoke(null, new object[] { ras }), createDecoder.ReturnType, 8000);
|
|
475
|
+
if (decoder == null) throw new Exception("BitmapDecoder returned null");
|
|
476
|
+
softwareBitmap = InvokeAsync(decoder, "GetSoftwareBitmapAsync", 8000);
|
|
477
|
+
if (softwareBitmap == null) throw new Exception("GetSoftwareBitmapAsync returned null");
|
|
478
|
+
object ocrResult = InvokeAsync(cachedEngine, "RecognizeAsync", 10000, new object[] { softwareBitmap });
|
|
479
|
+
if (ocrResult == null) throw new Exception("OcrEngine.RecognizeAsync returned null");
|
|
480
|
+
|
|
481
|
+
var linesOut = new List<object>();
|
|
482
|
+
var allLines = new List<string>();
|
|
483
|
+
double invScale = 1.0 / scale;
|
|
484
|
+
var rawLines = GetProp(ocrResult, "Lines") as IEnumerable;
|
|
485
|
+
if (rawLines != null)
|
|
486
|
+
{
|
|
487
|
+
foreach (var line in rawLines)
|
|
488
|
+
{
|
|
489
|
+
string lineText = CleanLineText(Convert.ToString(GetProp(line, "Text")) ?? "");
|
|
490
|
+
if (lineText.Trim().Length == 0) continue;
|
|
491
|
+
var wordsOut = new List<object>();
|
|
492
|
+
double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue;
|
|
493
|
+
var rawWords = GetProp(line, "Words") as IEnumerable;
|
|
494
|
+
if (rawWords != null)
|
|
495
|
+
{
|
|
496
|
+
foreach (var word in rawWords)
|
|
497
|
+
{
|
|
498
|
+
string wt = Convert.ToString(GetProp(word, "Text")) ?? "";
|
|
499
|
+
object rect = GetProp(word, "BoundingRect");
|
|
500
|
+
if (rect == null) continue;
|
|
501
|
+
double wx = Convert.ToDouble(GetProp(rect, "X")) * invScale;
|
|
502
|
+
double wy = Convert.ToDouble(GetProp(rect, "Y")) * invScale;
|
|
503
|
+
double ww = Convert.ToDouble(GetProp(rect, "Width")) * invScale;
|
|
504
|
+
double wh = Convert.ToDouble(GetProp(rect, "Height")) * invScale;
|
|
505
|
+
if (wx < minX) minX = wx;
|
|
506
|
+
if (wy < minY) minY = wy;
|
|
507
|
+
if (wx + ww > maxX) maxX = wx + ww;
|
|
508
|
+
if (wy + wh > maxY) maxY = wy + wh;
|
|
509
|
+
var wd = new Dictionary<string, object>();
|
|
510
|
+
wd["text"] = wt;
|
|
511
|
+
wd["x"] = x + (int)Math.Round(wx);
|
|
512
|
+
wd["y"] = y + (int)Math.Round(wy);
|
|
513
|
+
wd["width"] = Math.Max(1, (int)Math.Round(ww));
|
|
514
|
+
wd["height"] = Math.Max(1, (int)Math.Round(wh));
|
|
515
|
+
wordsOut.Add(wd);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
if (minX == double.MaxValue) continue;
|
|
519
|
+
var ld = new Dictionary<string, object>();
|
|
520
|
+
ld["text"] = lineText;
|
|
521
|
+
ld["x"] = x + (int)Math.Round(minX);
|
|
522
|
+
ld["y"] = y + (int)Math.Round(minY);
|
|
523
|
+
ld["width"] = Math.Max(1, (int)Math.Round(maxX - minX));
|
|
524
|
+
ld["height"] = Math.Max(1, (int)Math.Round(maxY - minY));
|
|
525
|
+
ld["words"] = wordsOut;
|
|
526
|
+
linesOut.Add(ld);
|
|
527
|
+
allLines.Add(lineText);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
meta["language"] = cachedLanguage;
|
|
532
|
+
meta["x"] = x;
|
|
533
|
+
meta["y"] = y;
|
|
534
|
+
meta["width"] = w;
|
|
535
|
+
meta["height"] = h;
|
|
536
|
+
meta["text"] = string.Join("\n", allLines.ToArray());
|
|
537
|
+
meta["lines"] = linesOut;
|
|
538
|
+
return meta;
|
|
539
|
+
}
|
|
540
|
+
finally
|
|
541
|
+
{
|
|
542
|
+
TryDispose(softwareBitmap);
|
|
543
|
+
TryDispose(writer);
|
|
544
|
+
TryDispose(ras);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Screen capture through the Windows Magnification API, which can leave
|
|
553
|
+
* out windows of other processes (MagSetWindowFilterList). The magnifier
|
|
554
|
+
* control lives in a never-shown host window; MagSetWindowSource renders
|
|
555
|
+
* synchronously into the scaling callback. Any failure disables it for the
|
|
556
|
+
* rest of the run and callers fall back to BitBlt.
|
|
557
|
+
*/
|
|
558
|
+
internal static class MagCapture
|
|
559
|
+
{
|
|
560
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
561
|
+
public struct MAGIMAGEHEADER { public uint width; public uint height; public Guid format; public uint stride; public uint offset; public UIntPtr cbSize; }
|
|
562
|
+
|
|
563
|
+
delegate bool ScalingCallback(IntPtr hwnd, IntPtr srcdata, MAGIMAGEHEADER srcheader, IntPtr destdata, MAGIMAGEHEADER destheader, Native.RECT unclipped, Native.RECT clipped, IntPtr dirty);
|
|
564
|
+
|
|
565
|
+
[DllImport("Magnification.dll")] static extern bool MagInitialize();
|
|
566
|
+
[DllImport("Magnification.dll")] static extern bool MagSetWindowSource(IntPtr hwnd, Native.RECT rect);
|
|
567
|
+
[DllImport("Magnification.dll")] static extern bool MagSetWindowFilterList(IntPtr hwnd, int mode, int count, IntPtr[] list);
|
|
568
|
+
[DllImport("Magnification.dll")] static extern bool MagSetImageScalingCallback(IntPtr hwnd, ScalingCallback cb);
|
|
569
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
|
|
570
|
+
static extern IntPtr CreateWindowEx(int ex, string cls, string name, int style, int x, int y, int w, int h, IntPtr parent, IntPtr menu, IntPtr inst, IntPtr param);
|
|
571
|
+
|
|
572
|
+
static bool broken;
|
|
573
|
+
public static string Why = "";
|
|
574
|
+
static Form host;
|
|
575
|
+
static IntPtr magnifier = IntPtr.Zero;
|
|
576
|
+
static ScalingCallback callback;
|
|
577
|
+
static Bitmap frame;
|
|
578
|
+
|
|
579
|
+
static bool Ready()
|
|
580
|
+
{
|
|
581
|
+
if (broken) return false;
|
|
582
|
+
if (magnifier != IntPtr.Zero) return true;
|
|
583
|
+
try
|
|
584
|
+
{
|
|
585
|
+
if (!MagInitialize()) { broken = true; Why = "init"; return false; }
|
|
586
|
+
host = new Form { FormBorderStyle = FormBorderStyle.None, ShowInTaskbar = false, StartPosition = FormStartPosition.Manual, Location = new Point(0, 0), Size = new Size(16, 16) };
|
|
587
|
+
IntPtr parent = host.Handle; // created, never shown
|
|
588
|
+
magnifier = CreateWindowEx(0, "Magnifier", "cu-magnifier", 0x40000000 | 0x10000000, 0, 0, 16, 16, parent, IntPtr.Zero, Native.GetModuleHandle(null), IntPtr.Zero);
|
|
589
|
+
callback = OnImage;
|
|
590
|
+
if (magnifier == IntPtr.Zero || !MagSetImageScalingCallback(magnifier, callback)) { broken = true; Why = "callback"; return false; }
|
|
591
|
+
return true;
|
|
592
|
+
}
|
|
593
|
+
catch (Exception e) { broken = true; Why = "ready: " + e.Message; return false; }
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** The screen rectangle without the `exclude` window, or null when unavailable. */
|
|
597
|
+
public static Bitmap Capture(Rectangle area, IntPtr exclude)
|
|
598
|
+
{
|
|
599
|
+
if (!Ready()) return null;
|
|
600
|
+
Bitmap result = null;
|
|
601
|
+
try
|
|
602
|
+
{
|
|
603
|
+
// The never-shown host must be as large as the capture, or the control is clipped.
|
|
604
|
+
Native.SetWindowPos(host.Handle, IntPtr.Zero, 0, 0, area.Width, area.Height, 0x0004 | 0x0010);
|
|
605
|
+
Native.SetWindowPos(magnifier, IntPtr.Zero, 0, 0, area.Width, area.Height, 0x0004 | 0x0010); // NOZORDER | NOACTIVATE
|
|
606
|
+
if (!MagSetWindowFilterList(magnifier, 0 /* MW_FILTERMODE_EXCLUDE */, 1, new[] { exclude })) { broken = true; Why = "filter"; return null; }
|
|
607
|
+
frame = null;
|
|
608
|
+
var rc = new Native.RECT { Left = area.Left, Top = area.Top, Right = area.Right, Bottom = area.Bottom };
|
|
609
|
+
if (!MagSetWindowSource(magnifier, rc)) { broken = true; Why = "source"; return null; }
|
|
610
|
+
result = frame;
|
|
611
|
+
frame = null;
|
|
612
|
+
if (result == null || result.Width != area.Width || result.Height != area.Height)
|
|
613
|
+
{
|
|
614
|
+
Why = result == null ? "no frame" : "size " + result.Width + "x" + result.Height;
|
|
615
|
+
if (result != null) result.Dispose();
|
|
616
|
+
broken = true;
|
|
617
|
+
return null;
|
|
618
|
+
}
|
|
619
|
+
if (!HasVisiblePixels(result))
|
|
620
|
+
{
|
|
621
|
+
result.Dispose();
|
|
622
|
+
broken = true;
|
|
623
|
+
Why = "black magnifier frame";
|
|
624
|
+
Console.Error.WriteLine("Magnification capture returned a black frame; using BitBlt for the rest of this helper process.");
|
|
625
|
+
return null;
|
|
626
|
+
}
|
|
627
|
+
return result;
|
|
628
|
+
}
|
|
629
|
+
catch (Exception e)
|
|
630
|
+
{
|
|
631
|
+
if (result != null) result.Dispose();
|
|
632
|
+
broken = true;
|
|
633
|
+
Why = "capture: " + e.Message;
|
|
634
|
+
return null;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
internal static bool HasVisiblePixels(Bitmap bitmap)
|
|
639
|
+
{
|
|
640
|
+
var data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
|
|
641
|
+
try
|
|
642
|
+
{
|
|
643
|
+
var row = new byte[bitmap.Width * 4];
|
|
644
|
+
for (int y = 0; y < bitmap.Height; y++)
|
|
645
|
+
{
|
|
646
|
+
Marshal.Copy(IntPtr.Add(data.Scan0, y * data.Stride), row, 0, row.Length);
|
|
647
|
+
for (int x = 0; x < row.Length; x += 4)
|
|
648
|
+
{
|
|
649
|
+
// Ignore the padding byte and allow black-level noise.
|
|
650
|
+
if (row[x] > 3 || row[x + 1] > 3 || row[x + 2] > 3) return true;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
return false;
|
|
654
|
+
}
|
|
655
|
+
finally { bitmap.UnlockBits(data); }
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
static bool OnImage(IntPtr hwnd, IntPtr srcdata, MAGIMAGEHEADER h, IntPtr destdata, MAGIMAGEHEADER dh, Native.RECT unclipped, Native.RECT clipped, IntPtr dirty)
|
|
659
|
+
{
|
|
660
|
+
try
|
|
661
|
+
{
|
|
662
|
+
var bmp = new Bitmap((int)h.width, (int)h.height, PixelFormat.Format32bppRgb);
|
|
663
|
+
var data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);
|
|
664
|
+
try
|
|
665
|
+
{
|
|
666
|
+
int rowBytes = (int)h.width * 4;
|
|
667
|
+
var row = new byte[rowBytes];
|
|
668
|
+
for (int y = 0; y < h.height; y++)
|
|
669
|
+
{
|
|
670
|
+
Marshal.Copy(new IntPtr(srcdata.ToInt64() + h.offset + (long)y * h.stride), row, 0, rowBytes);
|
|
671
|
+
Marshal.Copy(row, 0, new IntPtr(data.Scan0.ToInt64() + (long)y * data.Stride), rowBytes);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
finally { bmp.UnlockBits(data); }
|
|
675
|
+
frame = bmp;
|
|
676
|
+
}
|
|
677
|
+
catch (Exception) { frame = null; }
|
|
678
|
+
return true;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
}
|