@aivin-labs/cli 1.0.11 → 1.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +325 -288
  2. package/bin/cli.mjs +163 -17
  3. package/bin/lib/localPreview.mjs +437 -0
  4. package/bin/lib/openFile.mjs +235 -0
  5. package/bin/lib/previewCache.mjs +71 -0
  6. package/bin/lib/remote/atomicFile.mjs +32 -0
  7. package/bin/lib/remote/autoStart.mjs +2 -1
  8. package/bin/lib/remote/autoUpdate.mjs +12 -0
  9. package/bin/lib/remote/browserTunnel.mjs +47 -8
  10. package/bin/lib/remote/callLedger.mjs +94 -14
  11. package/bin/lib/remote/cdpPolicy.mjs +14 -2
  12. package/bin/lib/remote/client.mjs +1024 -808
  13. package/bin/lib/remote/cloudFiles.mjs +53 -0
  14. package/bin/lib/remote/codingAgents.mjs +2 -2
  15. package/bin/lib/remote/constants.mjs +261 -234
  16. package/bin/lib/remote/credentials.mjs +81 -4
  17. package/bin/lib/remote/daemonLock.mjs +57 -17
  18. package/bin/lib/remote/dailyBrowser.mjs +8 -2
  19. package/bin/lib/remote/desktop/castInput.mjs +98 -0
  20. package/bin/lib/remote/desktop/desktopCast.mjs +334 -0
  21. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
  22. package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -0
  23. package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -0
  24. package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
  25. package/bin/lib/remote/desktop/index.mjs +58 -7
  26. package/bin/lib/remote/desktop/linux.mjs +1 -1
  27. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -427
  28. package/bin/lib/remote/desktop/mac.mjs +2 -2
  29. package/bin/lib/remote/desktop/macTraySource.mjs +293 -292
  30. package/bin/lib/remote/desktop/strings.mjs +28 -2
  31. package/bin/lib/remote/desktop/traySource.mjs +905 -527
  32. package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
  33. package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
  34. package/bin/lib/remote/deviceProfile.mjs +1 -0
  35. package/bin/lib/remote/docText.mjs +85 -0
  36. package/bin/lib/remote/fileIndexer.mjs +773 -399
  37. package/bin/lib/remote/folderRules.mjs +143 -0
  38. package/bin/lib/remote/gitSafe.mjs +31 -0
  39. package/bin/lib/remote/gui/index.mjs +170 -19
  40. package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
  41. package/bin/lib/remote/gui/windowsHost.mjs +12 -3
  42. package/bin/lib/remote/gui/windowsHostSource.mjs +461 -87
  43. package/bin/lib/remote/httpTransfer.mjs +64 -3
  44. package/bin/lib/remote/idempotency.mjs +49 -20
  45. package/bin/lib/remote/localPolicy.mjs +81 -9
  46. package/bin/lib/remote/mascot/ask.mjs +207 -42
  47. package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
  48. package/bin/lib/remote/mascot/askHostSource.mjs +658 -512
  49. package/bin/lib/remote/mascot/blocks.mjs +201 -0
  50. package/bin/lib/remote/mascot/bot.mjs +54 -5
  51. package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
  52. package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
  53. package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
  54. package/bin/lib/remote/mascot/fileChips.mjs +62 -0
  55. package/bin/lib/remote/mascot/hostSource.mjs +331 -52
  56. package/bin/lib/remote/mascot/hotkey.mjs +31 -7
  57. package/bin/lib/remote/mascot/images.mjs +111 -0
  58. package/bin/lib/remote/mascot/index.mjs +663 -493
  59. package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
  60. package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
  61. package/bin/lib/remote/mascot/mood.mjs +57 -0
  62. package/bin/lib/remote/mascot/rigSource.mjs +648 -609
  63. package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
  64. package/bin/lib/remote/mascot/strings.mjs +456 -375
  65. package/bin/lib/remote/mascot/ui.mjs +27 -7
  66. package/bin/lib/remote/multiUser.mjs +7 -2
  67. package/bin/lib/remote/notify.mjs +4 -1
  68. package/bin/lib/remote/office/index.mjs +12 -6
  69. package/bin/lib/remote/osSearch.mjs +107 -0
  70. package/bin/lib/remote/processes.mjs +5 -2
  71. package/bin/lib/remote/sandbox.mjs +26 -0
  72. package/bin/lib/remote/secretPaths.mjs +21 -0
  73. package/bin/lib/remote/sqliteDb.mjs +51 -0
  74. package/bin/lib/remote/tokenRotation.mjs +28 -0
  75. package/bin/lib/remote/toolHandlers.mjs +852 -741
  76. package/bin/lib/remote/watchBatcher.mjs +56 -0
  77. package/bin/lib/remoteControl.mjs +26 -26
  78. package/bin/lib/selfUpdate.mjs +12 -2
  79. package/bin/lib/update/binarySwap.mjs +15 -1
  80. package/bin/lib/update/state.mjs +10 -0
  81. package/docs/AIVIN_MASCOT.md +14 -0
  82. package/docs/CLI.md +1545 -1484
  83. package/docs/media/aivin-ecosystem.jpg +0 -0
  84. package/docs/media/aivin-mascot-live.gif +0 -0
  85. package/docs/media/aivin-mascot-live.png +0 -0
  86. package/docs/media/aivin-remote-architecture.svg +102 -0
  87. package/package.json +75 -71
  88. package/docs/media/aivin-mascot-states.mp4 +0 -0
@@ -0,0 +1,598 @@
1
+ /**
2
+ * Phần chụp hình + con trỏ của tiến trình quay (ghép vào DESKTOP_CAST_CSHARP, cùng C# 5 / .NET Framework 4.5+, không thư viện ngoài):
3
+ * - DxgiScreen: Desktop Duplication API qua vtable COM thô — chờ tới khi màn hình đổi thật (không tốn CPU lúc đứng yên), nhanh hơn GDI, không kèm con trỏ.
4
+ * - FrameSource: dùng DXGI khi được, không thì CopyFromScreen (máy ảo / RDP không có duplication, xoay màn hình, màn hình bảo mật UAC / khoá);
5
+ * DXGI hỏng giữa chừng (đổi độ phân giải, desktop bảo mật) thì lùi GDI + thử lại sau, không ngắt phiên.
6
+ * - CursorTracker: vị trí + hình con trỏ tách khỏi khung hình để FE vẽ tức thì; `drawInFrame` (mặc định) thì vẽ vào khung như trước.
7
+ */
8
+ export const DESKTOP_CAST_CAPTURE_CSHARP = String.raw`
9
+ namespace AivinDesktopCast {
10
+ using System;
11
+ using System.Collections.Generic;
12
+ using System.Drawing;
13
+ using System.Drawing.Imaging;
14
+ using System.IO;
15
+ using System.Runtime.InteropServices;
16
+ using System.Threading;
17
+
18
+ static class Com {
19
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate uint ReleaseFn(IntPtr self);
20
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int QueryFn(IntPtr self, ref Guid iid, out IntPtr result);
21
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int EnumFn(IntPtr self, uint index, out IntPtr result);
22
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int OutputDescFn(IntPtr self, out DxgiOutputDesc desc);
23
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int DuplicateFn(IntPtr self, IntPtr device, out IntPtr result);
24
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int AcquireFn(IntPtr self, uint timeoutMs, out DxgiFrameInfo info, out IntPtr resource);
25
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int ReleaseFrameFn(IntPtr self);
26
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void TexDescFn(IntPtr self, out D3dTexDesc desc);
27
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int CreateTexFn(IntPtr self, ref D3dTexDesc desc, IntPtr init, out IntPtr result);
28
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void CopyResourceFn(IntPtr self, IntPtr dst, IntPtr src);
29
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate int MapFn(IntPtr self, IntPtr resource, uint sub, int mapType, uint flags, out D3dMapped mapped);
30
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void UnmapFn(IntPtr self, IntPtr resource, uint sub);
31
+
32
+ public static T Fn<T>(IntPtr self, int slot) where T : class {
33
+ IntPtr vtable = Marshal.ReadIntPtr(self);
34
+ return (T)(object)Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(vtable, slot * IntPtr.Size), typeof(T));
35
+ }
36
+
37
+ public static void Release(ref IntPtr p) {
38
+ if (p == IntPtr.Zero) return;
39
+ Fn<ReleaseFn>(p, 2)(p);
40
+ p = IntPtr.Zero;
41
+ }
42
+
43
+ public static IntPtr Query(IntPtr self, Guid iid) {
44
+ IntPtr result;
45
+ int hr = Fn<QueryFn>(self, 0)(self, ref iid, out result);
46
+ return hr < 0 ? IntPtr.Zero : result;
47
+ }
48
+ }
49
+
50
+ [StructLayout(LayoutKind.Sequential)] public struct DxgiRect { public int Left, Top, Right, Bottom; }
51
+
52
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
53
+ public struct DxgiOutputDesc {
54
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DeviceName;
55
+ public DxgiRect Coordinates;
56
+ public int AttachedToDesktop;
57
+ public int Rotation;
58
+ public IntPtr Monitor;
59
+ }
60
+
61
+ [StructLayout(LayoutKind.Sequential)]
62
+ public struct DxgiFrameInfo {
63
+ public long LastPresentTime;
64
+ public long LastMouseUpdateTime;
65
+ public uint AccumulatedFrames;
66
+ public int RectsCoalesced;
67
+ public int ProtectedContentMaskedOut;
68
+ public int PointerX, PointerY, PointerVisible;
69
+ public uint TotalMetadataBufferSize;
70
+ public uint PointerShapeBufferSize;
71
+ }
72
+
73
+ [StructLayout(LayoutKind.Sequential)]
74
+ public struct D3dTexDesc {
75
+ public uint Width, Height, MipLevels, ArraySize, Format, SampleCount, SampleQuality, Usage, BindFlags, CpuAccessFlags, MiscFlags;
76
+ }
77
+
78
+ [StructLayout(LayoutKind.Sequential)]
79
+ public struct D3dMapped { public IntPtr Data; public uint RowPitch; public uint DepthPitch; }
80
+
81
+ /** Một màn hình đang được nhân bản (Desktop Duplication). */
82
+ class DuplicatedOutput {
83
+ const int WAIT_TIMEOUT = unchecked((int)0x887A0027);
84
+ const uint FORMAT_BGRA = 87;
85
+ const uint USAGE_STAGING = 3;
86
+ const uint CPU_ACCESS_READ = 0x20000;
87
+ const int MAP_READ = 1;
88
+ static readonly Guid IID_TEXTURE2D = new Guid("6f15aaf2-d208-4e89-9ab4-489535d34f9c");
89
+
90
+ public Rectangle Rect;
91
+ public IntPtr Device, Context, Duplication, Staging;
92
+ readonly Com.AcquireFn acquire;
93
+ readonly Com.ReleaseFrameFn releaseFrame;
94
+ readonly Com.CopyResourceFn copyResource;
95
+ readonly Com.MapFn map;
96
+ readonly Com.UnmapFn unmap;
97
+
98
+ public DuplicatedOutput(Rectangle rect, IntPtr device, IntPtr context, IntPtr duplication) {
99
+ Rect = rect; Device = device; Context = context; Duplication = duplication;
100
+ acquire = Com.Fn<Com.AcquireFn>(duplication, 8);
101
+ releaseFrame = Com.Fn<Com.ReleaseFrameFn>(duplication, 14);
102
+ copyResource = Com.Fn<Com.CopyResourceFn>(context, 47);
103
+ map = Com.Fn<Com.MapFn>(context, 14);
104
+ unmap = Com.Fn<Com.UnmapFn>(context, 15);
105
+ }
106
+
107
+ /** 1 = đã chép khung mới vào đích, 0 = màn hình không đổi, -1 = hỏng (mất quyền nhân bản: đổi chế độ hiển thị, desktop bảo mật). */
108
+ public int Acquire(uint timeoutMs, IntPtr dst, int dstStride, Rectangle dstBounds) {
109
+ DxgiFrameInfo info;
110
+ IntPtr resource;
111
+ int hr = acquire(Duplication, timeoutMs, out info, out resource);
112
+ if (hr == WAIT_TIMEOUT) return 0;
113
+ if (hr < 0) return -1;
114
+ try {
115
+ // Chỉ con trỏ đổi: hình màn hình không có gì mới (con trỏ đi đường riêng).
116
+ if (info.LastPresentTime == 0) return 0;
117
+ IntPtr texture = Com.Query(resource, IID_TEXTURE2D);
118
+ if (texture == IntPtr.Zero) return -1;
119
+ try {
120
+ return CopyTexture(texture, dst, dstStride, dstBounds) ? 1 : -1;
121
+ } finally {
122
+ Com.Release(ref texture);
123
+ }
124
+ } finally {
125
+ Com.Release(ref resource);
126
+ releaseFrame(Duplication);
127
+ }
128
+ }
129
+
130
+ bool CopyTexture(IntPtr texture, IntPtr dst, int dstStride, Rectangle dstBounds) {
131
+ if (Staging == IntPtr.Zero && !CreateStaging(texture)) return false;
132
+ copyResource(Context, Staging, texture);
133
+ D3dMapped mapped;
134
+ if (map(Context, Staging, 0, MAP_READ, 0, out mapped) < 0) return false;
135
+ try {
136
+ int offX = Rect.Left - dstBounds.Left;
137
+ int offY = Rect.Top - dstBounds.Top;
138
+ uint rowBytes = (uint)(Math.Min(Rect.Width, dstBounds.Width - offX) * 4);
139
+ int rows = Math.Min(Rect.Height, dstBounds.Height - offY);
140
+ long dstBase = dst.ToInt64() + (long)offY * dstStride + offX * 4;
141
+ long srcBase = mapped.Data.ToInt64();
142
+ for (int y = 0; y < rows; y++) {
143
+ Native.CopyMemory(new IntPtr(dstBase + (long)y * dstStride), new IntPtr(srcBase + (long)y * mapped.RowPitch), rowBytes);
144
+ }
145
+ return true;
146
+ } finally {
147
+ unmap(Context, Staging, 0);
148
+ }
149
+ }
150
+
151
+ bool CreateStaging(IntPtr texture) {
152
+ D3dTexDesc desc;
153
+ Com.Fn<Com.TexDescFn>(texture, 10)(texture, out desc);
154
+ if (desc.Format != FORMAT_BGRA) return false;
155
+ desc.MipLevels = 1;
156
+ desc.ArraySize = 1;
157
+ desc.SampleCount = 1;
158
+ desc.SampleQuality = 0;
159
+ desc.Usage = USAGE_STAGING;
160
+ desc.BindFlags = 0;
161
+ desc.CpuAccessFlags = CPU_ACCESS_READ;
162
+ desc.MiscFlags = 0;
163
+ return Com.Fn<Com.CreateTexFn>(Device, 5)(Device, ref desc, IntPtr.Zero, out Staging) >= 0;
164
+ }
165
+
166
+ public void Dispose() {
167
+ Com.Release(ref Staging);
168
+ Com.Release(ref Duplication);
169
+ Com.Release(ref Context);
170
+ Com.Release(ref Device);
171
+ }
172
+ }
173
+
174
+ /** Nhân bản mọi màn hình nằm trong vùng cần quay; monitor = -1 ghép nhiều màn hình về đúng toạ độ. */
175
+ public class DxgiScreen {
176
+ static readonly Guid IID_FACTORY1 = new Guid("770aae78-f26f-4dba-a829-253c83d1b387");
177
+ static readonly Guid IID_OUTPUT1 = new Guid("00cddea8-939b-4b83-a340-a685226666cc");
178
+ const int DRIVER_TYPE_UNKNOWN = 0;
179
+ const uint SDK_VERSION = 7;
180
+ const int ROTATION_UNSPECIFIED = 0;
181
+ const int ROTATION_IDENTITY = 1;
182
+
183
+ [DllImport("dxgi.dll")] static extern int CreateDXGIFactory1(ref Guid iid, out IntPtr factory);
184
+ [DllImport("d3d11.dll")] static extern int D3D11CreateDevice(IntPtr adapter, int driverType, IntPtr software, uint flags, IntPtr levels, uint levelCount, uint sdk, out IntPtr device, out int level, out IntPtr context);
185
+
186
+ public Rectangle Bounds;
187
+ readonly List<DuplicatedOutput> outputs = new List<DuplicatedOutput>();
188
+
189
+ /** Không dùng được (không có GPU / driver, phiên RDP, màn hình xoay, không phủ hết vùng cần quay) → null + lý do, dùng GDI. */
190
+ public static DxgiScreen TryCreate(Rectangle bounds, out string reason) {
191
+ reason = "";
192
+ var screen = new DxgiScreen { Bounds = bounds };
193
+ try {
194
+ reason = screen.OpenOutputs();
195
+ if (reason == "" && screen.outputs.Count == 0) reason = "no_output";
196
+ if (reason == "") return screen;
197
+ } catch (Exception ex) {
198
+ reason = ex.GetType().Name;
199
+ }
200
+ screen.Dispose();
201
+ return null;
202
+ }
203
+
204
+ string OpenOutputs() {
205
+ Guid iid = IID_FACTORY1;
206
+ IntPtr factory;
207
+ int hr = CreateDXGIFactory1(ref iid, out factory);
208
+ if (hr < 0) return "factory_" + hr.ToString("x");
209
+ long covered = 0;
210
+ try {
211
+ var enumAdapters = Com.Fn<Com.EnumFn>(factory, 7);
212
+ for (uint a = 0; ; a++) {
213
+ IntPtr adapter;
214
+ if (enumAdapters(factory, a, out adapter) < 0) break;
215
+ try {
216
+ for (uint o = 0; ; o++) {
217
+ IntPtr output;
218
+ if (Com.Fn<Com.EnumFn>(adapter, 7)(adapter, o, out output) < 0) break;
219
+ try {
220
+ DxgiOutputDesc desc;
221
+ if (Com.Fn<Com.OutputDescFn>(output, 7)(output, out desc) < 0 || desc.AttachedToDesktop == 0) continue;
222
+ var rect = Rectangle.FromLTRB(desc.Coordinates.Left, desc.Coordinates.Top, desc.Coordinates.Right, desc.Coordinates.Bottom);
223
+ var inter = Rectangle.Intersect(rect, Bounds);
224
+ if (inter.Width <= 0 || inter.Height <= 0) continue;
225
+ if (rect.Left < Bounds.Left || rect.Top < Bounds.Top) return "partial_output";
226
+ if (desc.Rotation != ROTATION_UNSPECIFIED && desc.Rotation != ROTATION_IDENTITY) return "rotated";
227
+ string failed = OpenOutput(adapter, output, rect);
228
+ if (failed != "") return failed;
229
+ covered += (long)rect.Width * rect.Height;
230
+ } finally {
231
+ Com.Release(ref output);
232
+ }
233
+ }
234
+ } finally {
235
+ Com.Release(ref adapter);
236
+ }
237
+ }
238
+ } finally {
239
+ Com.Release(ref factory);
240
+ }
241
+ return covered > 0 ? "" : "no_output";
242
+ }
243
+
244
+ string OpenOutput(IntPtr adapter, IntPtr output, Rectangle rect) {
245
+ IntPtr output1 = Com.Query(output, IID_OUTPUT1);
246
+ if (output1 == IntPtr.Zero) return "no_output1";
247
+ IntPtr device = IntPtr.Zero, context = IntPtr.Zero, duplication = IntPtr.Zero;
248
+ try {
249
+ int level;
250
+ int hr = D3D11CreateDevice(adapter, DRIVER_TYPE_UNKNOWN, IntPtr.Zero, 0, IntPtr.Zero, 0, SDK_VERSION, out device, out level, out context);
251
+ if (hr < 0) return "device_" + hr.ToString("x");
252
+ hr = Com.Fn<Com.DuplicateFn>(output1, 22)(output1, device, out duplication);
253
+ if (hr < 0) {
254
+ Com.Release(ref context);
255
+ Com.Release(ref device);
256
+ return "duplicate_" + hr.ToString("x");
257
+ }
258
+ outputs.Add(new DuplicatedOutput(rect, device, context, duplication));
259
+ return "";
260
+ } finally {
261
+ Com.Release(ref output1);
262
+ }
263
+ }
264
+
265
+ /** Chờ tối đa waitMs trên màn hình đầu, các màn hình sau không chờ. 1 = có đổi, 0 = không, -1 = hỏng. */
266
+ public int Acquire(Bitmap frame, int waitMs) {
267
+ var rect = new Rectangle(0, 0, frame.Width, frame.Height);
268
+ var data = frame.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);
269
+ try {
270
+ int result = 0;
271
+ for (int i = 0; i < outputs.Count; i++) {
272
+ int r = outputs[i].Acquire(i == 0 ? (uint)Math.Max(0, waitMs) : 0, data.Scan0, data.Stride, Bounds);
273
+ if (r < 0) return -1;
274
+ if (r > 0) result = 1;
275
+ }
276
+ return result;
277
+ } finally {
278
+ frame.UnlockBits(data);
279
+ }
280
+ }
281
+
282
+ public void Dispose() {
283
+ foreach (var o in outputs) o.Dispose();
284
+ outputs.Clear();
285
+ }
286
+ }
287
+
288
+ /** Nguồn khung hình của vòng quay: giữ khung mới nhất (không kèm con trỏ), báo có đổi không. */
289
+ public class FrameSource {
290
+ const long DXGI_RETRY_MS = 5000;
291
+ const long DXGI_LOST_RETRY_MS = 1000;
292
+
293
+ Bitmap frame;
294
+ Bitmap scratch;
295
+ DxgiScreen dxgi;
296
+ long retryAt;
297
+ string reported;
298
+
299
+ public Bitmap Frame { get { return frame; } }
300
+ public bool UsingDxgi { get { return dxgi != null; } }
301
+
302
+ /** true = khung đổi so với lần trước. DXGI chờ tới waitMs trong lúc màn hình đứng yên. */
303
+ public bool Capture(Rectangle bounds, int waitMs, long nowMs) {
304
+ bool resized = frame == null || frame.Width != bounds.Width || frame.Height != bounds.Height;
305
+ if (resized) {
306
+ if (frame != null) frame.Dispose();
307
+ if (scratch != null) { scratch.Dispose(); scratch = null; }
308
+ frame = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppRgb);
309
+ }
310
+ if (dxgi != null && dxgi.Bounds != bounds) CloseDxgi(0);
311
+ if (dxgi == null && nowMs >= retryAt && OpenDxgi(bounds, nowMs)) {
312
+ CastScreen.CopyScreen(frame, bounds);
313
+ return true;
314
+ }
315
+ if (dxgi != null) {
316
+ int r = dxgi.Acquire(frame, waitMs);
317
+ if (r >= 0) return r > 0 || resized;
318
+ CloseDxgi(nowMs + DXGI_LOST_RETRY_MS);
319
+ Report("gdi", "lost");
320
+ }
321
+ return CaptureGdi(bounds) || resized;
322
+ }
323
+
324
+ bool OpenDxgi(Rectangle bounds, long nowMs) {
325
+ string reason;
326
+ dxgi = DxgiScreen.TryCreate(bounds, out reason);
327
+ if (dxgi == null) {
328
+ retryAt = nowMs + DXGI_RETRY_MS;
329
+ Report("gdi", reason);
330
+ return false;
331
+ }
332
+ Report("dxgi", "");
333
+ return true;
334
+ }
335
+
336
+ void CloseDxgi(long nextRetry) {
337
+ if (dxgi != null) dxgi.Dispose();
338
+ dxgi = null;
339
+ retryAt = nextRetry;
340
+ }
341
+
342
+ bool CaptureGdi(Rectangle bounds) {
343
+ if (scratch == null) scratch = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppRgb);
344
+ CastScreen.CopyScreen(scratch, bounds);
345
+ bool same = CastScreen.SameFrame(scratch, frame);
346
+ var t = frame;
347
+ frame = scratch;
348
+ scratch = t;
349
+ return !same;
350
+ }
351
+
352
+ void Report(string mode, string reason) {
353
+ string key = mode + ":" + reason;
354
+ if (key == reported) return;
355
+ reported = key;
356
+ var msg = Out.Msg("capture");
357
+ msg["mode"] = mode;
358
+ msg["reason"] = reason;
359
+ Out.Send(msg);
360
+ }
361
+
362
+ public void Dispose() {
363
+ CloseDxgi(0);
364
+ }
365
+ }
366
+
367
+ /** Số liệu máy báo trong mỗi khung để chế độ Tự động ở FE quyết định: hình đổi bao nhiêu, máy có quá tải không. */
368
+ public class HostStats {
369
+ const long WINDOW_MS = 1000;
370
+ const long THUMB_INTERVAL_MS = 100;
371
+ const double LOAD_SMOOTHING = 0.2;
372
+
373
+ long windowStart;
374
+ long lastThumbMs;
375
+ byte[] lastThumb;
376
+ int changes;
377
+ double maxDiff;
378
+ double loadMs;
379
+ long lastIdle, lastKernel, lastUser;
380
+ Dictionary<string, object> published = new Dictionary<string, object>();
381
+
382
+ public void OnChange(Bitmap frame, long nowMs) {
383
+ changes++;
384
+ if (nowMs - lastThumbMs < THUMB_INTERVAL_MS) return;
385
+ lastThumbMs = nowMs;
386
+ byte[] thumb = CastScreen.Thumb(frame);
387
+ if (lastThumb != null) maxDiff = Math.Max(maxDiff, CastScreen.Diff(thumb, lastThumb));
388
+ lastThumb = thumb;
389
+ }
390
+
391
+ public void AddLoad(long ms) {
392
+ loadMs = loadMs <= 0 ? ms : loadMs + (ms - loadMs) * LOAD_SMOOTHING;
393
+ }
394
+
395
+ public Dictionary<string, object> Snapshot(long nowMs) {
396
+ if (nowMs - windowStart >= WINDOW_MS) {
397
+ var next = new Dictionary<string, object>();
398
+ next["changes"] = changes;
399
+ next["diff"] = Math.Round(maxDiff, 3);
400
+ next["loadMs"] = Math.Round(loadMs, 1);
401
+ next["cpu"] = CpuPercent();
402
+ published = next;
403
+ changes = 0;
404
+ maxDiff = 0;
405
+ windowStart = nowMs;
406
+ }
407
+ return published;
408
+ }
409
+
410
+ int CpuPercent() {
411
+ long idle, kernel, user;
412
+ if (!Native.GetSystemTimes(out idle, out kernel, out user)) return 0;
413
+ long total = (kernel - lastKernel) + (user - lastUser);
414
+ long idleDelta = idle - lastIdle;
415
+ bool first = lastKernel == 0;
416
+ lastIdle = idle; lastKernel = kernel; lastUser = user;
417
+ if (first || total <= 0) return 0;
418
+ return (int)Math.Round(100.0 * (total - idleDelta) / total);
419
+ }
420
+ }
421
+
422
+ /** Theo dõi con trỏ ở luồng riêng (nhẹ, ~60 lần/giây): gửi vị trí khi đổi, gửi hình một lần cho mỗi con trỏ. */
423
+ public static class CursorTracker {
424
+ const int POLL_MS = 15;
425
+ const int MAX_SHAPE_SIDE = 128;
426
+ /** Vẽ con trỏ vào khung hình (mặc định, đường JPEG / FE cũ) thay vì gửi riêng. */
427
+ public static volatile bool DrawInFrame = true;
428
+ /** Tăng mỗi khi con trỏ đổi — vòng quay dùng để gửi khung khi con trỏ nằm trong hình. */
429
+ public static volatile int Seq = 0;
430
+ static volatile bool forceEmit = false;
431
+ static readonly Dictionary<IntPtr, int> shapeIds = new Dictionary<IntPtr, int>();
432
+
433
+ public static void Start() {
434
+ var t = new Thread(Loop);
435
+ t.IsBackground = true;
436
+ t.Start();
437
+ }
438
+
439
+ public static void SetDrawInFrame(bool value) {
440
+ DrawInFrame = value;
441
+ forceEmit = true;
442
+ }
443
+
444
+ static void Loop() {
445
+ int lastX = int.MinValue, lastY = int.MinValue, lastShape = -1;
446
+ bool lastVisible = false;
447
+ while (CastHost.Running) {
448
+ try {
449
+ Native.CURSORINFO pci;
450
+ pci.cbSize = Marshal.SizeOf(typeof(Native.CURSORINFO));
451
+ if (Native.GetCursorInfo(out pci)) {
452
+ bool visible = (pci.flags & Native.CURSOR_SHOWING) != 0;
453
+ int x = pci.ptScreenPos.x, y = pci.ptScreenPos.y;
454
+ bool drawInFrame = DrawInFrame;
455
+ int shape = visible && !drawInFrame ? EnsureShape(pci.hCursor) : lastShape;
456
+ bool changed = x != lastX || y != lastY || visible != lastVisible || shape != lastShape;
457
+ if (changed) Seq = Seq + 1;
458
+ if ((changed || forceEmit) && !drawInFrame) {
459
+ forceEmit = false;
460
+ Emit(x, y, visible, shape);
461
+ }
462
+ lastX = x; lastY = y; lastVisible = visible; lastShape = shape;
463
+ }
464
+ } catch {
465
+ }
466
+ Thread.Sleep(POLL_MS);
467
+ }
468
+ }
469
+
470
+ static void Emit(int x, int y, bool visible, int shape) {
471
+ var b = CastHost.CurrentBounds;
472
+ var msg = Out.Msg("cursor");
473
+ msg["x"] = x - b.X;
474
+ msg["y"] = y - b.Y;
475
+ msg["visible"] = visible;
476
+ msg["shape"] = shape;
477
+ Out.Send(msg);
478
+ }
479
+
480
+ static int EnsureShape(IntPtr handle) {
481
+ int id;
482
+ if (shapeIds.TryGetValue(handle, out id)) return id;
483
+ id = shapeIds.Count + 1;
484
+ shapeIds[handle] = id;
485
+ var msg = Out.Msg("cursor_shape");
486
+ msg["id"] = id;
487
+ int hotX, hotY;
488
+ msg["png"] = RenderShape(handle, out hotX, out hotY);
489
+ msg["hotX"] = hotX;
490
+ msg["hotY"] = hotY;
491
+ Out.Send(msg);
492
+ return id;
493
+ }
494
+
495
+ /** Điểm nóng của con trỏ (đầu mũi tên): ptScreenPos là vị trí điểm này, không phải góc ảnh. */
496
+ public static Point Hotspot(IntPtr handle) {
497
+ Native.ICONINFO ii;
498
+ if (!Native.GetIconInfo(handle, out ii)) return Point.Empty;
499
+ if (ii.hbmMask != IntPtr.Zero) Native.DeleteObject(ii.hbmMask);
500
+ if (ii.hbmColor != IntPtr.Zero) Native.DeleteObject(ii.hbmColor);
501
+ return new Point(ii.xHotspot, ii.yHotspot);
502
+ }
503
+
504
+ static string RenderShape(IntPtr handle, out int hotX, out int hotY) {
505
+ hotX = 0; hotY = 0;
506
+ Native.ICONINFO ii;
507
+ if (!Native.GetIconInfo(handle, out ii)) return "";
508
+ try {
509
+ hotX = ii.xHotspot;
510
+ hotY = ii.yHotspot;
511
+ int w, h;
512
+ int[] pixels = ii.hbmColor != IntPtr.Zero ? ColorPixels(ii, out w, out h) : MonochromePixels(ii, out w, out h);
513
+ if (pixels == null || w > MAX_SHAPE_SIDE || h > MAX_SHAPE_SIDE) return "";
514
+ using (var bmp = new Bitmap(w, h, PixelFormat.Format32bppArgb)) {
515
+ var data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
516
+ for (int y = 0; y < h; y++) Marshal.Copy(pixels, y * w, new IntPtr(data.Scan0.ToInt64() + (long)y * data.Stride), w);
517
+ bmp.UnlockBits(data);
518
+ using (var ms = new MemoryStream()) {
519
+ bmp.Save(ms, ImageFormat.Png);
520
+ return Convert.ToBase64String(ms.ToArray());
521
+ }
522
+ }
523
+ } finally {
524
+ if (ii.hbmMask != IntPtr.Zero) Native.DeleteObject(ii.hbmMask);
525
+ if (ii.hbmColor != IntPtr.Zero) Native.DeleteObject(ii.hbmColor);
526
+ }
527
+ }
528
+
529
+ static int[] ColorPixels(Native.ICONINFO ii, out int w, out int h) {
530
+ int[] color = ReadBitmap(ii.hbmColor, out w, out h);
531
+ if (color == null) return null;
532
+ bool hasAlpha = false;
533
+ for (int i = 0; i < color.Length && !hasAlpha; i++) hasAlpha = ((uint)color[i] >> 24) != 0;
534
+ if (hasAlpha) return color;
535
+ int mw, mh;
536
+ int[] mask = ReadBitmap(ii.hbmMask, out mw, out mh);
537
+ if (mask == null || mw != w || mh != h) return null;
538
+ for (int i = 0; i < color.Length; i++) {
539
+ color[i] = (mask[i] & 0xFFFFFF) != 0 ? 0 : (color[i] | unchecked((int)0xFF000000));
540
+ }
541
+ return color;
542
+ }
543
+
544
+ /** Con trỏ đen trắng (chữ I...): nửa trên AND, nửa dưới XOR. Điểm "đảo màu" không vẽ được bằng ảnh → đen, viền trắng để thấy trên cả nền tối. */
545
+ static int[] MonochromePixels(Native.ICONINFO ii, out int w, out int h) {
546
+ int fullH;
547
+ int[] mask = ReadBitmap(ii.hbmMask, out w, out fullH);
548
+ h = fullH / 2;
549
+ if (mask == null) return null;
550
+ const int BLACK = unchecked((int)0xFF000000);
551
+ const int WHITE = unchecked((int)0xFFFFFFFF);
552
+ var pixels = new int[w * h];
553
+ var inverted = new bool[w * h];
554
+ for (int y = 0; y < h; y++) {
555
+ for (int x = 0; x < w; x++) {
556
+ bool and = (mask[y * w + x] & 0xFFFFFF) != 0;
557
+ bool xor = (mask[(y + h) * w + x] & 0xFFFFFF) != 0;
558
+ if (and && xor) inverted[y * w + x] = true;
559
+ pixels[y * w + x] = and && !xor ? 0 : (!and && xor ? WHITE : BLACK);
560
+ }
561
+ }
562
+ for (int y = 0; y < h; y++) {
563
+ for (int x = 0; x < w; x++) {
564
+ if (!inverted[y * w + x]) continue;
565
+ for (int dy = -1; dy <= 1; dy++) {
566
+ for (int dx = -1; dx <= 1; dx++) {
567
+ int nx = x + dx, ny = y + dy;
568
+ if (nx >= 0 && ny >= 0 && nx < w && ny < h && pixels[ny * w + nx] == 0) pixels[ny * w + nx] = WHITE;
569
+ }
570
+ }
571
+ }
572
+ }
573
+ return pixels;
574
+ }
575
+
576
+ static int[] ReadBitmap(IntPtr hbm, out int w, out int h) {
577
+ w = 0; h = 0;
578
+ Native.BITMAP bm;
579
+ if (Native.GetObject(hbm, Marshal.SizeOf(typeof(Native.BITMAP)), out bm) == 0) return null;
580
+ w = bm.bmWidth;
581
+ h = bm.bmHeight;
582
+ var info = new Native.BITMAPINFOHEADER();
583
+ info.biSize = Marshal.SizeOf(typeof(Native.BITMAPINFOHEADER));
584
+ info.biWidth = w;
585
+ info.biHeight = -h;
586
+ info.biPlanes = 1;
587
+ info.biBitCount = 32;
588
+ var pixels = new int[w * h];
589
+ IntPtr dc = Native.GetDC(IntPtr.Zero);
590
+ try {
591
+ return Native.GetDIBits(dc, hbm, 0, (uint)h, pixels, ref info, 0) == 0 ? null : pixels;
592
+ } finally {
593
+ Native.ReleaseDC(IntPtr.Zero, dc);
594
+ }
595
+ }
596
+ }
597
+ }
598
+ `;