@aivin-labs/cli 1.0.13 → 1.0.24

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 (73) hide show
  1. package/README.md +325 -304
  2. package/bin/cli.mjs +97 -18
  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 +153 -129
  9. package/bin/lib/remote/callLedger.mjs +21 -0
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -2
  11. package/bin/lib/remote/client.mjs +1025 -889
  12. package/bin/lib/remote/codingAgents.mjs +2 -2
  13. package/bin/lib/remote/constants.mjs +263 -251
  14. package/bin/lib/remote/credentials.mjs +81 -4
  15. package/bin/lib/remote/daemonLock.mjs +57 -17
  16. package/bin/lib/remote/desktop/castInput.mjs +98 -0
  17. package/bin/lib/remote/desktop/desktopCast.mjs +337 -198
  18. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
  19. package/bin/lib/remote/desktop/desktopCastSource.mjs +880 -514
  20. package/bin/lib/remote/desktop/desktopWebRtc.mjs +251 -95
  21. package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
  22. package/bin/lib/remote/desktop/index.mjs +21 -7
  23. package/bin/lib/remote/desktop/linuxTraySource.mjs +1 -8
  24. package/bin/lib/remote/desktop/macTraySource.mjs +0 -2
  25. package/bin/lib/remote/desktop/strings.mjs +28 -2
  26. package/bin/lib/remote/desktop/traySource.mjs +380 -16
  27. package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
  28. package/bin/lib/remote/desktop/webrtcWorker.mjs +183 -0
  29. package/bin/lib/remote/deviceProfile.mjs +2 -4
  30. package/bin/lib/remote/fileIndexer.mjs +30 -14
  31. package/bin/lib/remote/folderRules.mjs +3 -0
  32. package/bin/lib/remote/gitSafe.mjs +31 -0
  33. package/bin/lib/remote/gui/index.mjs +66 -24
  34. package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
  35. package/bin/lib/remote/gui/windowsHost.mjs +3 -1
  36. package/bin/lib/remote/gui/windowsHostSource.mjs +291 -60
  37. package/bin/lib/remote/httpTransfer.mjs +64 -3
  38. package/bin/lib/remote/localPolicy.mjs +73 -7
  39. package/bin/lib/remote/mascot/ask.mjs +956 -768
  40. package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
  41. package/bin/lib/remote/mascot/askHostSource.mjs +658 -530
  42. package/bin/lib/remote/mascot/blocks.mjs +201 -0
  43. package/bin/lib/remote/mascot/bot.mjs +26 -2
  44. package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
  45. package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
  46. package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
  47. package/bin/lib/remote/mascot/fileChips.mjs +62 -0
  48. package/bin/lib/remote/mascot/hostSource.mjs +328 -49
  49. package/bin/lib/remote/mascot/hotkey.mjs +31 -7
  50. package/bin/lib/remote/mascot/images.mjs +111 -0
  51. package/bin/lib/remote/mascot/index.mjs +663 -493
  52. package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
  53. package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
  54. package/bin/lib/remote/mascot/mood.mjs +57 -0
  55. package/bin/lib/remote/mascot/rigSource.mjs +643 -609
  56. package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
  57. package/bin/lib/remote/mascot/strings.mjs +459 -375
  58. package/bin/lib/remote/mascot/ui.mjs +27 -7
  59. package/bin/lib/remote/multiUser.mjs +7 -2
  60. package/bin/lib/remote/notify.mjs +4 -1
  61. package/bin/lib/remote/office/index.mjs +12 -6
  62. package/bin/lib/remote/processes.mjs +5 -2
  63. package/bin/lib/remote/sandbox.mjs +26 -0
  64. package/bin/lib/remote/secretPaths.mjs +21 -0
  65. package/bin/lib/remote/tokenRotation.mjs +28 -0
  66. package/bin/lib/remote/toolHandlers.mjs +79 -15
  67. package/bin/lib/remote/watchBatcher.mjs +56 -0
  68. package/bin/lib/selfUpdate.mjs +12 -2
  69. package/bin/lib/update/binarySwap.mjs +15 -1
  70. package/bin/lib/update/state.mjs +10 -0
  71. package/docs/CLI.md +1545 -1504
  72. package/docs/media/aivin-ecosystem.jpg +0 -0
  73. package/package.json +75 -71
@@ -1,514 +1,880 @@
1
- /**
2
- * Tiến trình phát hình ảnh màn hình trực tiếp và điều khiển từ xa trên Windows (Desktop Scenecast).
3
- * Tương thích C# 5 / .NET Framework 4.5+ / PowerShell 5.1:
4
- * - Chụp màn hình qua Graphics.CopyFromScreen.
5
- * - Lồng con trỏ chuột thật của Windows vào khung hình (GetCursorInfo + DrawIcon).
6
- * - Hỗ trợ đa màn hình: lấy danh sách màn hình và chuyển đổi màn hình cần chụp theo thời gian thực.
7
- * - Co ảnh về chiều rộng tối đa (giữ tỉ lệ), nén ảnh sang định dạng JPEG nhẹ.
8
- * - So sánh ảnh thu nhỏ (64x36) để chỉ gửi khung hình khi có chuyển động hoặc giữ nhịp định kỳ (1 FPS).
9
- * - Nhận lệnh chuột, bàn phím và phím tắt hệ thống (hotkeys) qua stdin và thực thi qua Win32 API.
10
- * - Hỗ trợ thay đổi độ phân giải, chất lượng nén JPEG, giới hạn FPS và chọn màn hình theo thời gian thực.
11
- */
12
-
13
- export const DESKTOP_CAST_CSHARP = String.raw`
14
- using System;
15
- using System.Collections.Generic;
16
- using System.Drawing;
17
- using System.Drawing.Imaging;
18
- using System.IO;
19
- using System.Runtime.InteropServices;
20
- using System.Text;
21
- using System.Threading;
22
- using System.Web.Script.Serialization;
23
- using System.Windows.Forms;
24
-
25
- namespace AivinDesktopCast {
26
- static class Native {
27
- [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
28
- [DllImport("user32.dll")] public static extern bool SetCursorPos(int X, int Y);
29
- [DllImport("user32.dll")] public static extern void mouse_event(uint dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
30
- [DllImport("user32.dll")] public static extern void keybd_event(byte bVk, ushort bScan, uint dwFlags, UIntPtr dwExtraInfo);
31
- [DllImport("user32.dll")] public static extern short VkKeyScan(char ch);
32
-
33
- [StructLayout(LayoutKind.Sequential)]
34
- public struct POINT { public int x; public int y; }
35
-
36
- [StructLayout(LayoutKind.Sequential)]
37
- public struct CURSORINFO {
38
- public int cbSize;
39
- public int flags;
40
- public IntPtr hCursor;
41
- public POINT ptScreenPos;
42
- }
43
-
44
- [DllImport("user32.dll")] public static extern bool GetCursorInfo(out CURSORINFO pci);
45
- [DllImport("user32.dll")] public static extern bool DrawIcon(IntPtr hDC, int X, int Y, IntPtr hIcon);
46
-
47
- public const int CURSOR_SHOWING = 0x00000001;
48
-
49
- public const uint MOUSEEVENTF_MOVE = 0x0001;
50
- public const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
51
- public const uint MOUSEEVENTF_LEFTUP = 0x0004;
52
- public const uint MOUSEEVENTF_RIGHTDOWN = 0x0008;
53
- public const uint MOUSEEVENTF_RIGHTUP = 0x0010;
54
- public const uint MOUSEEVENTF_MIDDLEDOWN = 0x0020;
55
- public const uint MOUSEEVENTF_MIDDLEUP = 0x0040;
56
- public const uint MOUSEEVENTF_WHEEL = 0x0800;
57
-
58
- public const uint KEYEVENTF_KEYUP = 0x0002;
59
- public const uint KEYEVENTF_UNICODE = 0x0004;
60
- }
61
-
62
- static class Out {
63
- static readonly object gate = new object();
64
- static readonly JavaScriptSerializer json = new JavaScriptSerializer { MaxJsonLength = int.MaxValue };
65
-
66
- public static void Send(Dictionary<string, object> msg) {
67
- string line = json.Serialize(msg);
68
- lock (gate) { Console.Out.WriteLine(line); Console.Out.Flush(); }
69
- }
70
-
71
- public static Dictionary<string, object> Parse(string text) {
72
- if (string.IsNullOrEmpty(text)) return new Dictionary<string, object>();
73
- return json.Deserialize<Dictionary<string, object>>(text);
74
- }
75
-
76
- public static Dictionary<string, object> Msg(string t) {
77
- var d = new Dictionary<string, object>();
78
- d["t"] = t;
79
- return d;
80
- }
81
- }
82
-
83
- public static class CastScreen {
84
- public static Rectangle GetBounds(int monitor) {
85
- if (monitor < 0 || monitor >= Screen.AllScreens.Length) {
86
- return SystemInformation.VirtualScreen;
87
- }
88
- return Screen.AllScreens[monitor].Bounds;
89
- }
90
-
91
- public static List<Dictionary<string, object>> GetScreens() {
92
- var list = new List<Dictionary<string, object>>();
93
- var all = Screen.AllScreens;
94
- for (int i = 0; i < all.Length; i++) {
95
- var s = all[i];
96
- var d = new Dictionary<string, object>();
97
- d["index"] = i;
98
- d["name"] = "Màn hình " + (i + 1) + (s.Primary ? " (Chính)" : "");
99
- d["primary"] = s.Primary;
100
- d["width"] = s.Bounds.Width;
101
- d["height"] = s.Bounds.Height;
102
- d["x"] = s.Bounds.X;
103
- d["y"] = s.Bounds.Y;
104
- list.Add(d);
105
- }
106
- return list;
107
- }
108
-
109
- public static Bitmap Grab(Rectangle r) {
110
- var bmp = new Bitmap(r.Width, r.Height, PixelFormat.Format24bppRgb);
111
- using (var g = Graphics.FromImage(bmp)) {
112
- g.CopyFromScreen(r.Left, r.Top, 0, 0, r.Size);
113
-
114
- // Lồng con trỏ chuột thật của Windows vào ảnh
115
- try {
116
- Native.CURSORINFO pci;
117
- pci.cbSize = Marshal.SizeOf(typeof(Native.CURSORINFO));
118
- if (Native.GetCursorInfo(out pci) && (pci.flags & Native.CURSOR_SHOWING) != 0) {
119
- int cursorX = pci.ptScreenPos.x - r.Left;
120
- int cursorY = pci.ptScreenPos.y - r.Top;
121
- if (cursorX >= -32 && cursorX < r.Width && cursorY >= -32 && cursorY < r.Height) {
122
- IntPtr hdc = g.GetHdc();
123
- try {
124
- Native.DrawIcon(hdc, cursorX, cursorY, pci.hCursor);
125
- } finally {
126
- g.ReleaseHdc(hdc);
127
- }
128
- }
129
- }
130
- } catch {}
131
- }
132
- return bmp;
133
- }
134
-
135
- public static Bitmap Scale(Bitmap src, int maxWidth) {
136
- if (src.Width <= maxWidth) return src;
137
- int h = (int)Math.Round(src.Height * (double)maxWidth / src.Width);
138
- var dst = new Bitmap(maxWidth, h, PixelFormat.Format24bppRgb);
139
- using (var g = Graphics.FromImage(dst)) {
140
- g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
141
- g.DrawImage(src, 0, 0, maxWidth, h);
142
- }
143
- src.Dispose();
144
- return dst;
145
- }
146
-
147
- public static byte[] Jpeg(Bitmap bmp, int quality) {
148
- var encoders = ImageCodecInfo.GetImageEncoders();
149
- ImageCodecInfo codec = null;
150
- for (int i = 0; i < encoders.Length; i++) {
151
- if (encoders[i].MimeType == "image/jpeg") { codec = encoders[i]; break; }
152
- }
153
- if (codec == null) {
154
- using (var ms = new MemoryStream()) { bmp.Save(ms, ImageFormat.Jpeg); return ms.ToArray(); }
155
- }
156
- var p = new EncoderParameters(1);
157
- p.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
158
- using (var ms = new MemoryStream()) {
159
- bmp.Save(ms, codec, p);
160
- return ms.ToArray();
161
- }
162
- }
163
-
164
- public static byte[] Thumb(Bitmap src) {
165
- var t = new byte[64 * 36];
166
- using (var small = new Bitmap(64, 36, PixelFormat.Format24bppRgb)) {
167
- using (var g = Graphics.FromImage(small)) {
168
- g.DrawImage(src, 0, 0, 64, 36);
169
- }
170
- for (int y = 0; y < 36; y++) {
171
- for (int x = 0; x < 64; x++) {
172
- var c = small.GetPixel(x, y);
173
- t[y * 64 + x] = (byte)((c.R * 3 + c.G * 6 + c.B) / 10);
174
- }
175
- }
176
- }
177
- return t;
178
- }
179
-
180
- public static double Diff(byte[] a, byte[] b) {
181
- if (a == null || b == null) return 255;
182
- long s = 0;
183
- for (int i = 0; i < a.Length; i++) s += Math.Abs(a[i] - b[i]);
184
- return (double)s / a.Length;
185
- }
186
- }
187
-
188
- public static class CastHost {
189
- static volatile bool running = true;
190
- static volatile int currentMonitor = -1;
191
- static Rectangle currentBounds;
192
- static int currentImageWidth = 0;
193
- static int currentImageHeight = 0;
194
- static volatile int targetMaxFps = 15;
195
- static volatile int targetMaxWidth = 1366;
196
- static volatile int targetQuality = 65;
197
-
198
- public static void Run(string argsJson) {
199
- Native.SetProcessDPIAware();
200
- var a = Out.Parse(argsJson);
201
- currentMonitor = a.ContainsKey("monitor") ? Convert.ToInt32(a["monitor"]) : -1;
202
- targetMaxFps = a.ContainsKey("max_fps") ? Convert.ToInt32(a["max_fps"]) : 15;
203
- if (targetMaxFps < 1) targetMaxFps = 1;
204
- if (targetMaxFps > 30) targetMaxFps = 30;
205
- targetMaxWidth = a.ContainsKey("max_width") ? Convert.ToInt32(a["max_width"]) : 1366;
206
- targetQuality = a.ContainsKey("quality") ? Convert.ToInt32(a["quality"]) : 65;
207
-
208
- currentBounds = CastScreen.GetBounds(currentMonitor);
209
-
210
- // Luồng đọc lệnh điều khiển từ xa từ stdin
211
- var inputThread = new Thread(ReadInputLoop);
212
- inputThread.IsBackground = true;
213
- inputThread.Start();
214
-
215
- var readyMsg = Out.Msg("ready");
216
- readyMsg["monitor"] = currentMonitor;
217
- readyMsg["screens"] = CastScreen.GetScreens();
218
- readyMsg["bounds"] = new Dictionary<string, object> {
219
- { "x", currentBounds.X }, { "y", currentBounds.Y },
220
- { "width", currentBounds.Width }, { "height", currentBounds.Height }
221
- };
222
- Out.Send(readyMsg);
223
-
224
- var clock = System.Diagnostics.Stopwatch.StartNew();
225
- byte[] lastThumb = null;
226
- long lastSendMs = 0;
227
-
228
- while (running) {
229
- long frameStartMs = clock.ElapsedMilliseconds;
230
- long targetFrameInterval = 1000 / Math.Max(1, targetMaxFps);
231
- try {
232
- currentBounds = CastScreen.GetBounds(currentMonitor);
233
- using (var rawBmp = CastScreen.Grab(currentBounds)) {
234
- var thumb = CastScreen.Thumb(rawBmp);
235
- double diff = CastScreen.Diff(thumb, lastThumb);
236
- long nowMs = clock.ElapsedMilliseconds;
237
- bool forceKeepAlive = (nowMs - lastSendMs) >= 1000;
238
-
239
- if (diff > 4.5 || forceKeepAlive || lastThumb == null) {
240
- lastThumb = thumb;
241
- lastSendMs = nowMs;
242
-
243
- using (var scaled = CastScreen.Scale(new Bitmap(rawBmp), targetMaxWidth)) {
244
- currentImageWidth = scaled.Width;
245
- currentImageHeight = scaled.Height;
246
- byte[] jpegBytes = CastScreen.Jpeg(scaled, targetQuality);
247
- string base64 = Convert.ToBase64String(jpegBytes);
248
-
249
- var frameMsg = Out.Msg("frame");
250
- frameMsg["image"] = base64;
251
- frameMsg["width"] = currentImageWidth;
252
- frameMsg["height"] = currentImageHeight;
253
- frameMsg["screenWidth"] = currentBounds.Width;
254
- frameMsg["screenHeight"] = currentBounds.Height;
255
- frameMsg["monitor"] = currentMonitor;
256
- frameMsg["screens"] = CastScreen.GetScreens();
257
- frameMsg["ts"] = nowMs;
258
- Out.Send(frameMsg);
259
- }
260
- }
261
- }
262
- } catch (Exception ex) {
263
- var warnMsg = Out.Msg("warn");
264
- warnMsg["error"] = ex.Message;
265
- Out.Send(warnMsg);
266
- }
267
-
268
- long elapsed = clock.ElapsedMilliseconds - frameStartMs;
269
- long sleepMs = targetFrameInterval - elapsed;
270
- if (sleepMs > 5) {
271
- Thread.Sleep((int)sleepMs);
272
- } else {
273
- Thread.Sleep(5);
274
- }
275
- }
276
-
277
- var stoppedMsg = Out.Msg("stopped");
278
- Out.Send(stoppedMsg);
279
- }
280
-
281
- static void ReadInputLoop() {
282
- try {
283
- string line;
284
- while (running && (line = Console.In.ReadLine()) != null) {
285
- line = line.Trim();
286
- if (string.IsNullOrEmpty(line)) continue;
287
- if (line == "stop") {
288
- running = false;
289
- break;
290
- }
291
- var cmd = Out.Parse(line);
292
- string op = cmd.ContainsKey("op") ? Convert.ToString(cmd["op"]) : "";
293
- if (op == "stop") {
294
- running = false;
295
- break;
296
- } else if (op == "input") {
297
- HandleInput(cmd);
298
- } else if (op == "config") {
299
- HandleConfig(cmd);
300
- }
301
- }
302
- } catch {
303
- running = false;
304
- }
305
- }
306
-
307
- static void HandleConfig(Dictionary<string, object> cmd) {
308
- try {
309
- if (cmd.ContainsKey("max_fps")) {
310
- int fps = Convert.ToInt32(cmd["max_fps"]);
311
- if (fps >= 1 && fps <= 30) targetMaxFps = fps;
312
- }
313
- if (cmd.ContainsKey("quality")) {
314
- int q = Convert.ToInt32(cmd["quality"]);
315
- if (q >= 10 && q <= 95) targetQuality = q;
316
- }
317
- if (cmd.ContainsKey("max_width")) {
318
- int w = Convert.ToInt32(cmd["max_width"]);
319
- if (w >= 640 && w <= 2560) targetMaxWidth = w;
320
- }
321
- if (cmd.ContainsKey("monitor")) {
322
- int m = Convert.ToInt32(cmd["monitor"]);
323
- if (m >= -1 && m < Screen.AllScreens.Length) {
324
- currentMonitor = m;
325
- }
326
- }
327
- var ack = Out.Msg("config_ack");
328
- ack["max_fps"] = targetMaxFps;
329
- ack["quality"] = targetQuality;
330
- ack["max_width"] = targetMaxWidth;
331
- ack["monitor"] = currentMonitor;
332
- Out.Send(ack);
333
- } catch {
334
- }
335
- }
336
-
337
- static byte KeyNameToVk(string name) {
338
- if (string.IsNullOrEmpty(name)) return 0;
339
- switch (name.ToLower().Trim()) {
340
- case "win": case "windows": case "lwin": case "meta": case "cmd": return 0x5B;
341
- case "rwin": return 0x5C;
342
- case "ctrl": case "control": case "lctrl": return 0x11;
343
- case "rctrl": return 0xA3;
344
- case "alt": case "menu": case "lalt": return 0x12;
345
- case "ralt": return 0xA5;
346
- case "shift": case "lshift": return 0x10;
347
- case "rshift": return 0xA1;
348
- case "tab": return 0x09;
349
- case "escape": case "esc": return 0x1B;
350
- case "enter": case "return": return 0x0D;
351
- case "backspace": return 0x08;
352
- case "space": return 0x20;
353
- case "delete": case "del": return 0x2E;
354
- case "insert": case "ins": return 0x2D;
355
- case "home": return 0x24;
356
- case "end": return 0x23;
357
- case "pageup": return 0x21;
358
- case "pagedown": return 0x22;
359
- case "up": case "arrowup": return 0x26;
360
- case "down": case "arrowdown": return 0x28;
361
- case "left": case "arrowleft": return 0x25;
362
- case "right": case "arrowright": return 0x27;
363
- case "f1": return 0x70;
364
- case "f2": return 0x71;
365
- case "f3": return 0x72;
366
- case "f4": return 0x73;
367
- case "f5": return 0x74;
368
- case "f6": return 0x75;
369
- case "f7": return 0x76;
370
- case "f8": return 0x77;
371
- case "f9": return 0x78;
372
- case "f10": return 0x79;
373
- case "f11": return 0x7A;
374
- case "f12": return 0x7B;
375
- case "printscreen": case "prtsc": return 0x2C;
376
- default:
377
- if (name.Length == 1) {
378
- char ch = char.ToUpperInvariant(name[0]);
379
- if (ch >= 'A' && ch <= 'Z') return (byte)ch;
380
- if (ch >= '0' && ch <= '9') return (byte)ch;
381
- }
382
- return 0;
383
- }
384
- }
385
-
386
- static void HandleInput(Dictionary<string, object> cmd) {
387
- try {
388
- string action = cmd.ContainsKey("action") ? Convert.ToString(cmd["action"]) : "";
389
- double rx = cmd.ContainsKey("x") ? Convert.ToDouble(cmd["x"]) : 0;
390
- double ry = cmd.ContainsKey("y") ? Convert.ToDouble(cmd["y"]) : 0;
391
-
392
- int targetX = currentBounds.X;
393
- int targetY = currentBounds.Y;
394
- if (currentImageWidth > 0 && currentImageHeight > 0) {
395
- targetX += (int)Math.Round((rx / currentImageWidth) * currentBounds.Width);
396
- targetY += (int)Math.Round((ry / currentImageHeight) * currentBounds.Height);
397
- }
398
-
399
- if (action == "move") {
400
- Native.SetCursorPos(targetX, targetY);
401
- } else if (action == "click") {
402
- int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
403
- Native.SetCursorPos(targetX, targetY);
404
- Thread.Sleep(10);
405
- if (button == 2) {
406
- Native.mouse_event(Native.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
407
- Thread.Sleep(15);
408
- Native.mouse_event(Native.MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
409
- } else if (button == 1) {
410
- Native.mouse_event(Native.MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0, 0);
411
- Thread.Sleep(15);
412
- Native.mouse_event(Native.MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
413
- } else {
414
- Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
415
- Thread.Sleep(15);
416
- Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
417
- }
418
- } else if (action == "dblclick") {
419
- Native.SetCursorPos(targetX, targetY);
420
- Thread.Sleep(10);
421
- Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
422
- Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
423
- Thread.Sleep(40);
424
- Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
425
- Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
426
- } else if (action == "rightclick") {
427
- Native.SetCursorPos(targetX, targetY);
428
- Thread.Sleep(10);
429
- Native.mouse_event(Native.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
430
- Thread.Sleep(15);
431
- Native.mouse_event(Native.MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
432
- } else if (action == "mousedown") {
433
- int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
434
- Native.SetCursorPos(targetX, targetY);
435
- if (button == 2) Native.mouse_event(Native.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
436
- else if (button == 1) Native.mouse_event(Native.MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0, 0);
437
- else Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
438
- } else if (action == "mouseup") {
439
- int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
440
- Native.SetCursorPos(targetX, targetY);
441
- if (button == 2) Native.mouse_event(Native.MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
442
- else if (button == 1) Native.mouse_event(Native.MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
443
- else Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
444
- } else if (action == "scroll") {
445
- int deltaY = cmd.ContainsKey("deltaY") ? Convert.ToInt32(cmd["deltaY"]) : 0;
446
- Native.SetCursorPos(targetX, targetY);
447
- Native.mouse_event(Native.MOUSEEVENTF_WHEEL, 0, 0, -deltaY, 0);
448
- } else if (action == "type") {
449
- string text = cmd.ContainsKey("text") ? Convert.ToString(cmd["text"]) : "";
450
- if (!string.IsNullOrEmpty(text)) {
451
- for (int i = 0; i < text.Length; i++) {
452
- char c = text[i];
453
- Native.keybd_event(0, (ushort)c, Native.KEYEVENTF_UNICODE, UIntPtr.Zero);
454
- Native.keybd_event(0, (ushort)c, Native.KEYEVENTF_UNICODE | Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
455
- }
456
- }
457
- } else if (action == "key") {
458
- string key = cmd.ContainsKey("key") ? Convert.ToString(cmd["key"]) : "";
459
- HandleSpecialKey(key);
460
- } else if (action == "hotkey") {
461
- System.Collections.ArrayList keys = cmd.ContainsKey("keys") ? cmd["keys"] as System.Collections.ArrayList : null;
462
- if (keys != null && keys.Count > 0) {
463
- var vks = new List<byte>();
464
- for (int i = 0; i < keys.Count; i++) {
465
- byte vk = KeyNameToVk(Convert.ToString(keys[i]));
466
- if (vk != 0) vks.Add(vk);
467
- }
468
- for (int i = 0; i < vks.Count; i++) {
469
- Native.keybd_event(vks[i], 0, 0, UIntPtr.Zero);
470
- Thread.Sleep(10);
471
- }
472
- Thread.Sleep(40);
473
- for (int i = vks.Count - 1; i >= 0; i--) {
474
- Native.keybd_event(vks[i], 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
475
- Thread.Sleep(10);
476
- }
477
- }
478
- }
479
- } catch {
480
- }
481
- }
482
-
483
- static void HandleSpecialKey(string key) {
484
- byte vk = KeyNameToVk(key);
485
- if (vk != 0) {
486
- Native.keybd_event(vk, 0, 0, UIntPtr.Zero);
487
- Thread.Sleep(15);
488
- Native.keybd_event(vk, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
489
- }
490
- }
491
- }
492
- }
493
- `;
494
-
495
- export const DESKTOP_CAST_PS1 = String.raw`
496
- $ErrorActionPreference = 'Stop'
497
- $dll = $env:AIVIN_CAST_DLL
498
- $src = $env:AIVIN_CAST_SRC
499
- $refs = @('System.Drawing', 'System.Windows.Forms', 'System.Web.Extensions')
500
- foreach ($r in $refs) { Add-Type -AssemblyName $r }
501
- if ($dll -and (Test-Path -LiteralPath $dll)) {
502
- Add-Type -Path $dll
503
- } else {
504
- Add-Type -TypeDefinition ([IO.File]::ReadAllText($src)) -ReferencedAssemblies $refs -OutputAssembly $dll -OutputType Library
505
- Add-Type -Path $dll
506
- }
507
- try {
508
- [AivinDesktopCast.CastHost]::Run($env:AIVIN_CAST_ARGS)
509
- } catch {
510
- $m = @{ t = 'error'; error = $_.Exception.Message } | ConvertTo-Json -Compress
511
- [Console]::Out.WriteLine($m)
512
- exit 1
513
- }
514
- `;
1
+ /**
2
+ * Tiến trình phát hình ảnh màn hình trực tiếp và điều khiển từ xa trên Windows (Desktop Scenecast).
3
+ * Tương thích C# 5 / .NET Framework 4.5+ / PowerShell 5.1:
4
+ * - Chụp màn hình bằng Desktop Duplication, lùi Graphics.CopyFromScreen khi không dùng được (desktopCastCaptureSource.mjs).
5
+ * - Con trỏ: gửi vị trí + hình riêng để FE vẽ tức thì; người xem chưa hỗ trợ / đường JPEG thì lồng vào khung hình (GetCursorInfo + DrawIcon).
6
+ * - Hỗ trợ đa màn hình: lấy danh sách màn hình và chuyển đổi màn hình cần chụp theo thời gian thực.
7
+ * - Co ảnh về chiều rộng tối đa (giữ tỉ lệ), nén ảnh sang định dạng JPEG nhẹ.
8
+ * - So sánh nguyên khung (memcmp) để chỉ gửi khi hình đổi hoặc giữ nhịp định kỳ (1 FPS): thay đổi nhỏ như con trỏ, gõ chữ cũng phải đi ngay
9
+ * (đo 03/11/2026: ảnh thu nhỏ 64x36 + ngưỡng làm chúng chờ tới nhịp 1 s). Đường JPEG thì đổi nhỏ giới hạn 5 khung/giây, đỡ tải máy chủ.
10
+ * - Nhận lệnh chuột, bàn phím và phím tắt hệ thống (hotkeys) qua stdin và thực thi qua Win32 API.
11
+ * - Hỗ trợ thay đổi độ phân giải, chất lượng nén JPEG, giới hạn FPS và chọn màn hình theo thời gian thực.
12
+ * - Luồng video (02/11/2026): có `pipe` → mở named pipe gửi khung thô I420 ([rộng, cao, độ dài] int32 LE + dữ liệu) cho Node đưa vào
13
+ * RTCVideoSource (WebRTC tự mã hoá VP8, chỉ gửi phần đổi). JPEG chỉ nén khi còn người xem cần (`jpeg` qua config); không thì gửi dòng
14
+ * `meta` (kích thước, màn hình) để FE quy đổi toạ độ.
15
+ */
16
+
17
+ import { DESKTOP_CAST_CAPTURE_CSHARP } from './desktopCastCaptureSource.mjs';
18
+
19
+ export const DESKTOP_CAST_CSHARP = String.raw`
20
+ using System;
21
+ using System.Collections.Generic;
22
+ using System.Drawing;
23
+ using System.Drawing.Imaging;
24
+ using System.IO;
25
+ using System.IO.Pipes;
26
+ using System.Runtime.InteropServices;
27
+ using System.Text;
28
+ using System.Threading;
29
+ using System.Web.Script.Serialization;
30
+ using System.Windows.Automation;
31
+ using System.Windows.Forms;
32
+
33
+ namespace AivinDesktopCast {
34
+ static class Native {
35
+ [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
36
+ [DllImport("user32.dll")] public static extern bool SetCursorPos(int X, int Y);
37
+ [DllImport("user32.dll")] public static extern void mouse_event(uint dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
38
+ [DllImport("user32.dll")] public static extern void keybd_event(byte bVk, ushort bScan, uint dwFlags, UIntPtr dwExtraInfo);
39
+ [DllImport("user32.dll")] public static extern short VkKeyScan(char ch);
40
+
41
+ // Gõ chữ: keybd_event chỉ mang được 1 byte mã quét (BYTE bScan) → chữ ngoài Latin-1 (ư ơ đ ạ ế…) bị cắt thành ký tự rác.
42
+ // SendInput + KEYEVENTF_UNICODE mang đủ 16 bit mỗi đơn vị UTF-16.
43
+ [StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT { public int dx; public int dy; public int mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
44
+ [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
45
+ [StructLayout(LayoutKind.Explicit)] public struct INPUTUNION { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; }
46
+ [StructLayout(LayoutKind.Sequential)] public struct INPUT { public uint type; public INPUTUNION u; }
47
+ [DllImport("user32.dll")] public static extern uint SendInput(uint n, INPUT[] inputs, int size);
48
+ public const uint INPUT_KEYBOARD = 1;
49
+
50
+ // Ô nhập chữ đang có tiêu điểm: cửa sổ trước mặt có caret hệ thống (ô Win32, Office, Chromium / Edge đều tạo caret cho trợ năng).
51
+ [StructLayout(LayoutKind.Sequential)]
52
+ public struct RECT { public int left; public int top; public int right; public int bottom; }
53
+ [StructLayout(LayoutKind.Sequential)]
54
+ public struct GUITHREADINFO {
55
+ public int cbSize; public uint flags; public IntPtr hwndActive; public IntPtr hwndFocus; public IntPtr hwndCapture;
56
+ public IntPtr hwndMenuOwner; public IntPtr hwndMoveSize; public IntPtr hwndCaret; public RECT rcCaret;
57
+ }
58
+ [DllImport("user32.dll")] public static extern bool GetGUIThreadInfo(uint idThread, ref GUITHREADINFO info);
59
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
60
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr pid);
61
+
62
+ [StructLayout(LayoutKind.Sequential)]
63
+ public struct POINT { public int x; public int y; }
64
+
65
+ [StructLayout(LayoutKind.Sequential)]
66
+ public struct CURSORINFO {
67
+ public int cbSize;
68
+ public int flags;
69
+ public IntPtr hCursor;
70
+ public POINT ptScreenPos;
71
+ }
72
+
73
+ [DllImport("user32.dll")] public static extern bool GetCursorInfo(out CURSORINFO pci);
74
+ [DllImport("user32.dll")] public static extern bool DrawIcon(IntPtr hDC, int X, int Y, IntPtr hIcon);
75
+ [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int memcmp(IntPtr a, IntPtr b, UIntPtr count);
76
+ [DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")] public static extern void CopyMemory(IntPtr dst, IntPtr src, uint count);
77
+ [DllImport("winmm.dll")] public static extern uint timeBeginPeriod(uint ms);
78
+ [DllImport("kernel32.dll")] public static extern bool GetSystemTimes(out long idle, out long kernel, out long user);
79
+ [DllImport("user32.dll")] public static extern bool GetIconInfo(IntPtr hIcon, out ICONINFO info);
80
+ [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hWnd);
81
+ [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
82
+ [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr obj);
83
+ [DllImport("gdi32.dll")] public static extern int GetObject(IntPtr obj, int size, out BITMAP bm);
84
+ [DllImport("gdi32.dll")] public static extern int GetDIBits(IntPtr hdc, IntPtr hbm, uint start, uint lines, [Out] int[] bits, ref BITMAPINFOHEADER info, uint usage);
85
+
86
+ [StructLayout(LayoutKind.Sequential)]
87
+ public struct ICONINFO { public bool fIcon; public int xHotspot; public int yHotspot; public IntPtr hbmMask; public IntPtr hbmColor; }
88
+
89
+ [StructLayout(LayoutKind.Sequential)]
90
+ public struct BITMAP { public int bmType; public int bmWidth; public int bmHeight; public int bmWidthBytes; public ushort bmPlanes; public ushort bmBitsPixel; public IntPtr bmBits; }
91
+
92
+ [StructLayout(LayoutKind.Sequential)]
93
+ public struct BITMAPINFOHEADER {
94
+ public int biSize; public int biWidth; public int biHeight; public ushort biPlanes; public ushort biBitCount;
95
+ public int biCompression; public int biSizeImage; public int biXPelsPerMeter; public int biYPelsPerMeter; public int biClrUsed; public int biClrImportant;
96
+ }
97
+
98
+ public const int CURSOR_SHOWING = 0x00000001;
99
+
100
+ public const uint MOUSEEVENTF_MOVE = 0x0001;
101
+ public const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
102
+ public const uint MOUSEEVENTF_LEFTUP = 0x0004;
103
+ public const uint MOUSEEVENTF_RIGHTDOWN = 0x0008;
104
+ public const uint MOUSEEVENTF_RIGHTUP = 0x0010;
105
+ public const uint MOUSEEVENTF_MIDDLEDOWN = 0x0020;
106
+ public const uint MOUSEEVENTF_MIDDLEUP = 0x0040;
107
+ public const uint MOUSEEVENTF_WHEEL = 0x0800;
108
+ public const uint MOUSEEVENTF_HWHEEL = 0x01000;
109
+
110
+ public const uint KEYEVENTF_KEYUP = 0x0002;
111
+ public const uint KEYEVENTF_UNICODE = 0x0004;
112
+ }
113
+
114
+ static class Out {
115
+ static readonly object gate = new object();
116
+ static readonly JavaScriptSerializer json = new JavaScriptSerializer { MaxJsonLength = int.MaxValue };
117
+
118
+ public static void Send(Dictionary<string, object> msg) {
119
+ string line = json.Serialize(msg);
120
+ lock (gate) { Console.Out.WriteLine(line); Console.Out.Flush(); }
121
+ }
122
+
123
+ public static Dictionary<string, object> Parse(string text) {
124
+ if (string.IsNullOrEmpty(text)) return new Dictionary<string, object>();
125
+ return json.Deserialize<Dictionary<string, object>>(text);
126
+ }
127
+
128
+ public static Dictionary<string, object> Msg(string t) {
129
+ var d = new Dictionary<string, object>();
130
+ d["t"] = t;
131
+ return d;
132
+ }
133
+ }
134
+
135
+ /** Named pipe một chiều gửi khung thô cho tiến trình Node (một khách). Khách rớt → chờ khách mới. */
136
+ static class RawPipe {
137
+ static readonly object gate = new object();
138
+ static NamedPipeServerStream pipe;
139
+ public static volatile bool Connected;
140
+
141
+ public static void Start(string name) {
142
+ var t = new Thread(() => {
143
+ while (CastHost.Running) {
144
+ try {
145
+ var p = new NamedPipeServerStream(name, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 4 * 1024 * 1024);
146
+ p.WaitForConnection();
147
+ lock (gate) { pipe = p; Connected = true; }
148
+ while (CastHost.Running && p.IsConnected) Thread.Sleep(200);
149
+ } catch {
150
+ Thread.Sleep(300);
151
+ } finally {
152
+ lock (gate) { Connected = false; if (pipe != null) { try { pipe.Dispose(); } catch { } pipe = null; } }
153
+ }
154
+ }
155
+ });
156
+ t.IsBackground = true;
157
+ t.Start();
158
+ }
159
+
160
+ public static void Write(int width, int height, byte[] data) {
161
+ lock (gate) {
162
+ if (pipe == null || !Connected) return;
163
+ try {
164
+ var header = new byte[12];
165
+ BitConverter.GetBytes(width).CopyTo(header, 0);
166
+ BitConverter.GetBytes(height).CopyTo(header, 4);
167
+ BitConverter.GetBytes(data.Length).CopyTo(header, 8);
168
+ pipe.Write(header, 0, 12);
169
+ pipe.Write(data, 0, data.Length);
170
+ pipe.Flush();
171
+ } catch {
172
+ Connected = false;
173
+ try { pipe.Dispose(); } catch { }
174
+ pipe = null;
175
+ }
176
+ }
177
+ }
178
+ }
179
+
180
+ public static class CastScreen {
181
+ /** BGRX 32 bit → I420 (Y đủ, U/V lấy trung bình khối 2x2); kích thước cắt về số chẵn. */
182
+ public static byte[] ToI420(Bitmap bmp, out int w, out int h) {
183
+ w = bmp.Width & ~1;
184
+ h = bmp.Height & ~1;
185
+ var data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
186
+ try {
187
+ int stride = Math.Abs(data.Stride);
188
+ var raw = new byte[stride * h];
189
+ Marshal.Copy(data.Scan0, raw, 0, raw.Length);
190
+ int ySize = w * h;
191
+ int cw = w / 2;
192
+ var outBuf = new byte[ySize + ySize / 2];
193
+ int uBase = ySize;
194
+ int vBase = ySize + ySize / 4;
195
+ for (int y = 0; y < h; y++) {
196
+ int row = y * stride;
197
+ int yRow = y * w;
198
+ for (int x = 0; x < w; x++) {
199
+ int i = row + x * 4;
200
+ int b = raw[i], g = raw[i + 1], r = raw[i + 2];
201
+ outBuf[yRow + x] = (byte)(((66 * r + 129 * g + 25 * b + 128) >> 8) + 16);
202
+ }
203
+ }
204
+ for (int y = 0; y < h; y += 2) {
205
+ int row0 = y * stride;
206
+ int row1 = row0 + stride;
207
+ int cRow = (y / 2) * cw;
208
+ for (int x = 0; x < w; x += 2) {
209
+ int i0 = row0 + x * 4, i1 = i0 + 4, i2 = row1 + x * 4, i3 = i2 + 4;
210
+ int b = (raw[i0] + raw[i1] + raw[i2] + raw[i3]) >> 2;
211
+ int g = (raw[i0 + 1] + raw[i1 + 1] + raw[i2 + 1] + raw[i3 + 1]) >> 2;
212
+ int r = (raw[i0 + 2] + raw[i1 + 2] + raw[i2 + 2] + raw[i3 + 2]) >> 2;
213
+ int ci = cRow + x / 2;
214
+ outBuf[uBase + ci] = (byte)(((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128);
215
+ outBuf[vBase + ci] = (byte)(((112 * r - 94 * g - 18 * b + 128) >> 8) + 128);
216
+ }
217
+ }
218
+ return outBuf;
219
+ } finally {
220
+ bmp.UnlockBits(data);
221
+ }
222
+ }
223
+
224
+ public static Rectangle GetBounds(int monitor) {
225
+ if (monitor < 0 || monitor >= Screen.AllScreens.Length) {
226
+ return SystemInformation.VirtualScreen;
227
+ }
228
+ return Screen.AllScreens[monitor].Bounds;
229
+ }
230
+
231
+ public static List<Dictionary<string, object>> GetScreens() {
232
+ var list = new List<Dictionary<string, object>>();
233
+ var all = Screen.AllScreens;
234
+ for (int i = 0; i < all.Length; i++) {
235
+ var s = all[i];
236
+ var d = new Dictionary<string, object>();
237
+ d["index"] = i;
238
+ d["name"] = "Màn hình " + (i + 1) + (s.Primary ? " (Chính)" : "");
239
+ d["primary"] = s.Primary;
240
+ d["width"] = s.Bounds.Width;
241
+ d["height"] = s.Bounds.Height;
242
+ d["x"] = s.Bounds.X;
243
+ d["y"] = s.Bounds.Y;
244
+ list.Add(d);
245
+ }
246
+ return list;
247
+ }
248
+
249
+ /** Chụp vùng màn hình vào ảnh có sẵn (không kèm con trỏ). */
250
+ public static void CopyScreen(Bitmap dst, Rectangle r) {
251
+ using (var g = Graphics.FromImage(dst)) {
252
+ g.CopyFromScreen(r.Left, r.Top, 0, 0, r.Size);
253
+ }
254
+ }
255
+
256
+ /** Bản sao của khung có lồng con trỏ thật của Windows (đường JPEG / người xem chưa tự vẽ con trỏ). */
257
+ public static Bitmap WithCursor(Bitmap src, Rectangle r) {
258
+ var copy = new Bitmap(src.Width, src.Height, PixelFormat.Format32bppRgb);
259
+ using (var g = Graphics.FromImage(copy)) {
260
+ g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
261
+ g.DrawImageUnscaled(src, 0, 0);
262
+ try {
263
+ Native.CURSORINFO pci;
264
+ pci.cbSize = Marshal.SizeOf(typeof(Native.CURSORINFO));
265
+ if (Native.GetCursorInfo(out pci) && (pci.flags & Native.CURSOR_SHOWING) != 0) {
266
+ var hot = CursorTracker.Hotspot(pci.hCursor);
267
+ int cursorX = pci.ptScreenPos.x - hot.X - r.Left;
268
+ int cursorY = pci.ptScreenPos.y - hot.Y - r.Top;
269
+ if (cursorX >= -32 && cursorX < r.Width && cursorY >= -32 && cursorY < r.Height) {
270
+ IntPtr hdc = g.GetHdc();
271
+ try {
272
+ Native.DrawIcon(hdc, cursorX, cursorY, pci.hCursor);
273
+ } finally {
274
+ g.ReleaseHdc(hdc);
275
+ }
276
+ }
277
+ }
278
+ } catch {}
279
+ }
280
+ return copy;
281
+ }
282
+
283
+ public static Bitmap Scale(Bitmap src, int maxWidth) {
284
+ if (src.Width <= maxWidth) return src;
285
+ int h = (int)Math.Round(src.Height * (double)maxWidth / src.Width);
286
+ var dst = new Bitmap(maxWidth, h, PixelFormat.Format32bppRgb);
287
+ using (var g = Graphics.FromImage(dst)) {
288
+ g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
289
+ g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
290
+ g.DrawImage(src, 0, 0, maxWidth, h);
291
+ }
292
+ return dst;
293
+ }
294
+
295
+ public static byte[] Jpeg(Bitmap bmp, int quality) {
296
+ var encoders = ImageCodecInfo.GetImageEncoders();
297
+ ImageCodecInfo codec = null;
298
+ for (int i = 0; i < encoders.Length; i++) {
299
+ if (encoders[i].MimeType == "image/jpeg") { codec = encoders[i]; break; }
300
+ }
301
+ if (codec == null) {
302
+ using (var ms = new MemoryStream()) { bmp.Save(ms, ImageFormat.Jpeg); return ms.ToArray(); }
303
+ }
304
+ var p = new EncoderParameters(1);
305
+ p.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
306
+ using (var ms = new MemoryStream()) {
307
+ bmp.Save(ms, codec, p);
308
+ return ms.ToArray();
309
+ }
310
+ }
311
+
312
+ public static byte[] Thumb(Bitmap src) {
313
+ var t = new byte[64 * 36];
314
+ using (var small = new Bitmap(64, 36, PixelFormat.Format24bppRgb)) {
315
+ using (var g = Graphics.FromImage(small)) {
316
+ g.DrawImage(src, 0, 0, 64, 36);
317
+ }
318
+ var data = small.LockBits(new Rectangle(0, 0, 64, 36), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
319
+ try {
320
+ int stride = Math.Abs(data.Stride);
321
+ var raw = new byte[stride * 36];
322
+ Marshal.Copy(data.Scan0, raw, 0, raw.Length);
323
+ for (int y = 0; y < 36; y++) {
324
+ int rowOffset = y * stride;
325
+ int outOffset = y * 64;
326
+ for (int x = 0; x < 64; x++) {
327
+ int idx = rowOffset + x * 3;
328
+ int b = raw[idx];
329
+ int gVal = raw[idx + 1];
330
+ int r = raw[idx + 2];
331
+ t[outOffset + x] = (byte)((r * 3 + gVal * 6 + b) / 10);
332
+ }
333
+ }
334
+ } finally {
335
+ small.UnlockBits(data);
336
+ }
337
+ }
338
+ return t;
339
+ }
340
+
341
+ public static double Diff(byte[] a, byte[] b) {
342
+ if (a == null || b == null) return 255;
343
+ long s = 0;
344
+ for (int i = 0; i < a.Length; i++) s += Math.Abs(a[i] - b[i]);
345
+ return (double)s / a.Length;
346
+ }
347
+
348
+ /** Hai khung giống hệt từng điểm ảnh — ~0,3 ms ở 1080p, rẻ hơn tạo ảnh thu nhỏ. */
349
+ public static bool SameFrame(Bitmap a, Bitmap b) {
350
+ if (a == null || b == null || a.Width != b.Width || a.Height != b.Height) return false;
351
+ var rect = new Rectangle(0, 0, a.Width, a.Height);
352
+ var da = a.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
353
+ try {
354
+ var db = b.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
355
+ try {
356
+ return Native.memcmp(da.Scan0, db.Scan0, (UIntPtr)(ulong)((long)Math.Abs(da.Stride) * a.Height)) == 0;
357
+ } finally {
358
+ b.UnlockBits(db);
359
+ }
360
+ } finally {
361
+ a.UnlockBits(da);
362
+ }
363
+ }
364
+ }
365
+
366
+ public static class CastHost {
367
+ const long JPEG_SMALL_CHANGE_INTERVAL_MS = 200;
368
+ const double JPEG_BIG_CHANGE_DIFF = 4.5;
369
+ const int RATIO_SCALE = 65535;
370
+ static volatile bool running = true;
371
+ public static bool Running { get { return running; } }
372
+ static volatile bool jpegEnabled = true;
373
+ static volatile bool refreshRequested = false;
374
+ static bool rawEnabled = false;
375
+ static volatile int currentMonitor = -1;
376
+ static Rectangle currentBounds;
377
+ public static Rectangle CurrentBounds { get { return currentBounds; } }
378
+ static int currentImageWidth = 0;
379
+ static int currentImageHeight = 0;
380
+ static volatile int targetMaxFps = 15;
381
+ static volatile int targetMaxWidth = 1366;
382
+ static volatile int targetQuality = 65;
383
+
384
+ public static void Run(string argsJson) {
385
+ Native.SetProcessDPIAware();
386
+ Native.timeBeginPeriod(1);
387
+ var a = Out.Parse(argsJson);
388
+ currentMonitor = a.ContainsKey("monitor") ? Convert.ToInt32(a["monitor"]) : -1;
389
+ targetMaxFps = a.ContainsKey("max_fps") ? Convert.ToInt32(a["max_fps"]) : 15;
390
+ if (targetMaxFps < 1) targetMaxFps = 1;
391
+ if (targetMaxFps > 30) targetMaxFps = 30;
392
+ targetMaxWidth = a.ContainsKey("max_width") ? Convert.ToInt32(a["max_width"]) : 1366;
393
+ targetQuality = a.ContainsKey("quality") ? Convert.ToInt32(a["quality"]) : 65;
394
+ string pipeName = a.ContainsKey("pipe") ? Convert.ToString(a["pipe"]) : "";
395
+ if (!string.IsNullOrEmpty(pipeName)) { rawEnabled = true; RawPipe.Start(pipeName); }
396
+
397
+ currentBounds = CastScreen.GetBounds(currentMonitor);
398
+
399
+ // Luồng đọc lệnh điều khiển từ xa từ stdin
400
+ var inputThread = new Thread(ReadInputLoop);
401
+ inputThread.IsBackground = true;
402
+ inputThread.Start();
403
+
404
+ var readyMsg = Out.Msg("ready");
405
+ readyMsg["monitor"] = currentMonitor;
406
+ readyMsg["screens"] = CastScreen.GetScreens();
407
+ readyMsg["bounds"] = new Dictionary<string, object> {
408
+ { "x", currentBounds.X }, { "y", currentBounds.Y },
409
+ { "width", currentBounds.Width }, { "height", currentBounds.Height }
410
+ };
411
+ Out.Send(readyMsg);
412
+
413
+ var clock = System.Diagnostics.Stopwatch.StartNew();
414
+ var source = new FrameSource();
415
+ var hostStats = new HostStats();
416
+ CursorTracker.Start();
417
+ byte[] lastJpegThumb = null;
418
+ bool changePending = false;
419
+ int lastCursorSeq = -1;
420
+ long lastSendMs = 0;
421
+
422
+ while (running) {
423
+ long frameStartMs = clock.ElapsedMilliseconds;
424
+ long targetFrameInterval = 1000 / Math.Max(1, targetMaxFps);
425
+ try {
426
+ currentBounds = CastScreen.GetBounds(currentMonitor);
427
+ if (source.Capture(currentBounds, (int)targetFrameInterval, frameStartMs)) {
428
+ changePending = true;
429
+ hostStats.OnChange(source.Frame, clock.ElapsedMilliseconds);
430
+ }
431
+ bool cursorInFrame = CursorTracker.DrawInFrame;
432
+ int cursorSeq = CursorTracker.Seq;
433
+ if (cursorInFrame && cursorSeq != lastCursorSeq) changePending = true;
434
+ long nowMs = clock.ElapsedMilliseconds;
435
+ bool forceKeepAlive = (nowMs - lastSendMs) >= 1000;
436
+ bool refresh = refreshRequested;
437
+ if (refresh) refreshRequested = false;
438
+
439
+ bool jpegMode = jpegEnabled || !rawEnabled;
440
+ bool sendChange = changePending;
441
+ if (sendChange && jpegMode && lastJpegThumb != null && (nowMs - lastSendMs) < JPEG_SMALL_CHANGE_INTERVAL_MS) {
442
+ sendChange = CastScreen.Diff(CastScreen.Thumb(source.Frame), lastJpegThumb) > JPEG_BIG_CHANGE_DIFF;
443
+ }
444
+
445
+ if (sendChange || forceKeepAlive || refresh) {
446
+ changePending = false;
447
+ lastSendMs = nowMs;
448
+ lastCursorSeq = cursorSeq;
449
+ if (jpegMode) lastJpegThumb = CastScreen.Thumb(source.Frame);
450
+ long sendStartMs = clock.ElapsedMilliseconds;
451
+ SendFrame(source.Frame, cursorInFrame, jpegMode, nowMs, hostStats);
452
+ hostStats.AddLoad(clock.ElapsedMilliseconds - sendStartMs);
453
+ }
454
+ } catch (Exception ex) {
455
+ var warnMsg = Out.Msg("warn");
456
+ warnMsg["error"] = ex.Message;
457
+ Out.Send(warnMsg);
458
+ }
459
+
460
+ long sleepMs = targetFrameInterval - (clock.ElapsedMilliseconds - frameStartMs);
461
+ if (sleepMs > 0) Thread.Sleep((int)sleepMs);
462
+ else if (!source.UsingDxgi) Thread.Sleep(1);
463
+ }
464
+ source.Dispose();
465
+
466
+ var stoppedMsg = Out.Msg("stopped");
467
+ Out.Send(stoppedMsg);
468
+ }
469
+
470
+ static void SendFrame(Bitmap frame, bool cursorInFrame, bool jpegMode, long nowMs, HostStats hostStats) {
471
+ Bitmap withCursor = null;
472
+ Bitmap scaled = null;
473
+ try {
474
+ Bitmap encodeBmp = frame;
475
+ if (cursorInFrame) {
476
+ withCursor = CastScreen.WithCursor(frame, currentBounds);
477
+ encodeBmp = withCursor;
478
+ }
479
+ if (encodeBmp.Width > targetMaxWidth) {
480
+ scaled = CastScreen.Scale(encodeBmp, targetMaxWidth);
481
+ encodeBmp = scaled;
482
+ }
483
+ currentImageWidth = encodeBmp.Width;
484
+ currentImageHeight = encodeBmp.Height;
485
+ if (rawEnabled && RawPipe.Connected) {
486
+ int rw, rh;
487
+ byte[] i420 = CastScreen.ToI420(encodeBmp, out rw, out rh);
488
+ RawPipe.Write(rw, rh, i420);
489
+ }
490
+ var frameMsg = Out.Msg(jpegMode ? "frame" : "meta");
491
+ if (jpegMode) frameMsg["image"] = Convert.ToBase64String(CastScreen.Jpeg(encodeBmp, targetQuality));
492
+ frameMsg["width"] = currentImageWidth;
493
+ frameMsg["height"] = currentImageHeight;
494
+ frameMsg["screenWidth"] = currentBounds.Width;
495
+ frameMsg["screenHeight"] = currentBounds.Height;
496
+ frameMsg["screenX"] = currentBounds.X;
497
+ frameMsg["screenY"] = currentBounds.Y;
498
+ frameMsg["monitor"] = currentMonitor;
499
+ frameMsg["screens"] = CastScreen.GetScreens();
500
+ frameMsg["ts"] = nowMs;
501
+ frameMsg["stats"] = hostStats.Snapshot(nowMs);
502
+ Out.Send(frameMsg);
503
+ } finally {
504
+ if (scaled != null) scaled.Dispose();
505
+ if (withCursor != null) withCursor.Dispose();
506
+ }
507
+ }
508
+
509
+ static void ReadInputLoop() {
510
+ try {
511
+ string line;
512
+ while (running && (line = Console.In.ReadLine()) != null) {
513
+ line = line.Trim();
514
+ if (string.IsNullOrEmpty(line)) continue;
515
+ if (line == "stop") {
516
+ running = false;
517
+ break;
518
+ }
519
+ var cmd = Out.Parse(line);
520
+ string op = cmd.ContainsKey("op") ? Convert.ToString(cmd["op"]) : "";
521
+ if (op == "stop") {
522
+ running = false;
523
+ break;
524
+ } else if (op == "input") {
525
+ HandleInput(cmd);
526
+ } else if (op == "config") {
527
+ HandleConfig(cmd);
528
+ } else if (op == "refresh") {
529
+ refreshRequested = true;
530
+ }
531
+ }
532
+ } catch {
533
+ running = false;
534
+ }
535
+ }
536
+
537
+ static void HandleConfig(Dictionary<string, object> cmd) {
538
+ try {
539
+ if (cmd.ContainsKey("max_fps")) {
540
+ int fps = Convert.ToInt32(cmd["max_fps"]);
541
+ if (fps >= 1 && fps <= 30) targetMaxFps = fps;
542
+ }
543
+ if (cmd.ContainsKey("quality")) {
544
+ int q = Convert.ToInt32(cmd["quality"]);
545
+ if (q >= 10 && q <= 95) targetQuality = q;
546
+ }
547
+ if (cmd.ContainsKey("max_width")) {
548
+ int w = Convert.ToInt32(cmd["max_width"]);
549
+ if (w >= 640 && w <= 2560) {
550
+ // Đổi độ rộng lúc màn hình đứng yên: phải có khung mới ngay, không chờ nhịp giữ.
551
+ if (w != targetMaxWidth) refreshRequested = true;
552
+ targetMaxWidth = w;
553
+ }
554
+ }
555
+ if (cmd.ContainsKey("jpeg") && cmd["jpeg"] is bool) {
556
+ jpegEnabled = (bool)cmd["jpeg"];
557
+ refreshRequested = true;
558
+ }
559
+ if (cmd.ContainsKey("cursor") && cmd["cursor"] is bool) {
560
+ CursorTracker.SetDrawInFrame((bool)cmd["cursor"]);
561
+ refreshRequested = true;
562
+ }
563
+ if (cmd.ContainsKey("monitor")) {
564
+ int m = Convert.ToInt32(cmd["monitor"]);
565
+ if (m >= -1 && m < Screen.AllScreens.Length) {
566
+ currentMonitor = m;
567
+ }
568
+ }
569
+ var ack = Out.Msg("config_ack");
570
+ ack["max_fps"] = targetMaxFps;
571
+ ack["quality"] = targetQuality;
572
+ ack["max_width"] = targetMaxWidth;
573
+ ack["monitor"] = currentMonitor;
574
+ Out.Send(ack);
575
+ } catch {
576
+ }
577
+ }
578
+
579
+ static byte KeyNameToVk(string name) {
580
+ if (string.IsNullOrEmpty(name)) return 0;
581
+ switch (name.ToLower().Trim()) {
582
+ case "win": case "windows": case "lwin": case "meta": case "cmd": return 0x5B;
583
+ case "rwin": return 0x5C;
584
+ case "ctrl": case "control": case "lctrl": return 0x11;
585
+ case "rctrl": return 0xA3;
586
+ case "alt": case "menu": case "lalt": return 0x12;
587
+ case "ralt": return 0xA5;
588
+ case "shift": case "lshift": return 0x10;
589
+ case "rshift": return 0xA1;
590
+ case "tab": return 0x09;
591
+ case "escape": case "esc": return 0x1B;
592
+ case "enter": case "return": return 0x0D;
593
+ case "backspace": return 0x08;
594
+ case "space": return 0x20;
595
+ case "delete": case "del": return 0x2E;
596
+ case "insert": case "ins": return 0x2D;
597
+ case "home": return 0x24;
598
+ case "end": return 0x23;
599
+ case "pageup": return 0x21;
600
+ case "pagedown": return 0x22;
601
+ case "up": case "arrowup": return 0x26;
602
+ case "down": case "arrowdown": return 0x28;
603
+ case "left": case "arrowleft": return 0x25;
604
+ case "right": case "arrowright": return 0x27;
605
+ case "f1": return 0x70;
606
+ case "f2": return 0x71;
607
+ case "f3": return 0x72;
608
+ case "f4": return 0x73;
609
+ case "f5": return 0x74;
610
+ case "f6": return 0x75;
611
+ case "f7": return 0x76;
612
+ case "f8": return 0x77;
613
+ case "f9": return 0x78;
614
+ case "f10": return 0x79;
615
+ case "f11": return 0x7A;
616
+ case "f12": return 0x7B;
617
+ case "printscreen": case "prtsc": return 0x2C;
618
+ case "capslock": return 0x14;
619
+ case "numlock": return 0x90;
620
+ case "scrolllock": return 0x91;
621
+ case "contextmenu": case "apps": return 0x5D;
622
+ default:
623
+ if (name.Length == 1) {
624
+ char ch = char.ToUpperInvariant(name[0]);
625
+ if (ch >= 'A' && ch <= 'Z') return (byte)ch;
626
+ if (ch >= '0' && ch <= '9') return (byte)ch;
627
+ short vks = Native.VkKeyScan(name[0]);
628
+ if (vks != -1) return (byte)(vks & 0xFF);
629
+ }
630
+ return 0;
631
+ }
632
+ }
633
+
634
+ static List<byte> ExtractModifiers(Dictionary<string, object> cmd) {
635
+ var list = new List<byte>();
636
+ if (!cmd.ContainsKey("modifiers") || cmd["modifiers"] == null) return list;
637
+ System.Collections.ArrayList raw = cmd["modifiers"] as System.Collections.ArrayList;
638
+ if (raw != null) {
639
+ for (int i = 0; i < raw.Count; i++) {
640
+ byte vk = KeyNameToVk(Convert.ToString(raw[i]));
641
+ if (vk != 0 && !list.Contains(vk)) list.Add(vk);
642
+ }
643
+ }
644
+ return list;
645
+ }
646
+
647
+ static void PressModifiers(List<byte> mods) {
648
+ for (int i = 0; i < mods.Count; i++) {
649
+ Native.keybd_event(mods[i], 0, 0, UIntPtr.Zero);
650
+ }
651
+ if (mods.Count > 0) Thread.Sleep(8);
652
+ }
653
+
654
+ static void ReleaseModifiers(List<byte> mods) {
655
+ for (int i = mods.Count - 1; i >= 0; i--) {
656
+ Native.keybd_event(mods[i], 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
657
+ }
658
+ }
659
+
660
+ static void HandleInput(Dictionary<string, object> cmd) {
661
+ try {
662
+ string action = cmd.ContainsKey("action") ? Convert.ToString(cmd["action"]) : "";
663
+ double rx = cmd.ContainsKey("x") ? Convert.ToDouble(cmd["x"]) : 0;
664
+ double ry = cmd.ContainsKey("y") ? Convert.ToDouble(cmd["y"]) : 0;
665
+ var mods = ExtractModifiers(cmd);
666
+
667
+ int targetX = currentBounds.X;
668
+ int targetY = currentBounds.Y;
669
+ if (cmd.ContainsKey("rx") && cmd.ContainsKey("ry")) {
670
+ // Toạ độ theo tỷ lệ: đúng cả khi độ rộng khung vừa đổi (chế độ Tự động) hoặc video bị hạ độ phân giải.
671
+ targetX += (int)Math.Round(Convert.ToDouble(cmd["rx"]) / RATIO_SCALE * (currentBounds.Width - 1));
672
+ targetY += (int)Math.Round(Convert.ToDouble(cmd["ry"]) / RATIO_SCALE * (currentBounds.Height - 1));
673
+ } else if (currentImageWidth > 0 && currentImageHeight > 0) {
674
+ targetX += (int)Math.Round((rx / currentImageWidth) * currentBounds.Width);
675
+ targetY += (int)Math.Round((ry / currentImageHeight) * currentBounds.Height);
676
+ }
677
+
678
+ if (action == "move") {
679
+ Native.SetCursorPos(targetX, targetY);
680
+ } else if (action == "click") {
681
+ int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
682
+ Native.SetCursorPos(targetX, targetY);
683
+ Thread.Sleep(10);
684
+ PressModifiers(mods);
685
+ try {
686
+ if (button == 2) {
687
+ Native.mouse_event(Native.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
688
+ Thread.Sleep(15);
689
+ Native.mouse_event(Native.MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
690
+ } else if (button == 1) {
691
+ Native.mouse_event(Native.MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0, 0);
692
+ Thread.Sleep(15);
693
+ Native.mouse_event(Native.MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
694
+ } else {
695
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
696
+ Thread.Sleep(15);
697
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
698
+ }
699
+ } finally {
700
+ ReleaseModifiers(mods);
701
+ }
702
+ if (button == 0) ProbeInputFocus();
703
+ } else if (action == "dblclick") {
704
+ Native.SetCursorPos(targetX, targetY);
705
+ Thread.Sleep(10);
706
+ PressModifiers(mods);
707
+ try {
708
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
709
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
710
+ Thread.Sleep(40);
711
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
712
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
713
+ } finally {
714
+ ReleaseModifiers(mods);
715
+ }
716
+ } else if (action == "rightclick") {
717
+ Native.SetCursorPos(targetX, targetY);
718
+ Thread.Sleep(10);
719
+ PressModifiers(mods);
720
+ try {
721
+ Native.mouse_event(Native.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
722
+ Thread.Sleep(15);
723
+ Native.mouse_event(Native.MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
724
+ } finally {
725
+ ReleaseModifiers(mods);
726
+ }
727
+ } else if (action == "mousedown") {
728
+ int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
729
+ Native.SetCursorPos(targetX, targetY);
730
+ PressModifiers(mods);
731
+ if (button == 2) Native.mouse_event(Native.MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
732
+ else if (button == 1) Native.mouse_event(Native.MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0, 0);
733
+ else Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
734
+ } else if (action == "mouseup") {
735
+ int button = cmd.ContainsKey("button") ? Convert.ToInt32(cmd["button"]) : 0;
736
+ Native.SetCursorPos(targetX, targetY);
737
+ try {
738
+ if (button == 2) Native.mouse_event(Native.MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
739
+ else if (button == 1) Native.mouse_event(Native.MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
740
+ else Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
741
+ } finally {
742
+ ReleaseModifiers(mods);
743
+ }
744
+ if (button == 0) ProbeInputFocus();
745
+ } else if (action == "scroll") {
746
+ int deltaY = cmd.ContainsKey("deltaY") ? Convert.ToInt32(cmd["deltaY"]) : 0;
747
+ int deltaX = cmd.ContainsKey("deltaX") ? Convert.ToInt32(cmd["deltaX"]) : 0;
748
+ Native.SetCursorPos(targetX, targetY);
749
+ PressModifiers(mods);
750
+ try {
751
+ if (deltaY != 0) Native.mouse_event(Native.MOUSEEVENTF_WHEEL, 0, 0, -deltaY, 0);
752
+ if (deltaX != 0) Native.mouse_event(Native.MOUSEEVENTF_HWHEEL, 0, 0, deltaX, 0);
753
+ } finally {
754
+ ReleaseModifiers(mods);
755
+ }
756
+ } else if (action == "type") {
757
+ string text = cmd.ContainsKey("text") ? Convert.ToString(cmd["text"]) : "";
758
+ if (!string.IsNullOrEmpty(text)) TypeUnicode(text);
759
+ } else if (action == "key") {
760
+ string key = cmd.ContainsKey("key") ? Convert.ToString(cmd["key"]) : "";
761
+ HandleSpecialKey(key);
762
+ } else if (action == "hotkey") {
763
+ System.Collections.ArrayList keys = cmd.ContainsKey("keys") ? cmd["keys"] as System.Collections.ArrayList : null;
764
+ if (keys != null && keys.Count > 0) {
765
+ var vks = new List<byte>();
766
+ for (int i = 0; i < keys.Count; i++) {
767
+ byte vk = KeyNameToVk(Convert.ToString(keys[i]));
768
+ if (vk != 0) vks.Add(vk);
769
+ }
770
+ for (int i = 0; i < vks.Count; i++) {
771
+ Native.keybd_event(vks[i], 0, 0, UIntPtr.Zero);
772
+ Thread.Sleep(10);
773
+ }
774
+ Thread.Sleep(40);
775
+ for (int i = vks.Count - 1; i >= 0; i--) {
776
+ Native.keybd_event(vks[i], 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
777
+ Thread.Sleep(10);
778
+ }
779
+ }
780
+ }
781
+ } catch {
782
+ }
783
+ }
784
+
785
+ /** Gõ nguyên văn: mỗi đơn vị UTF-16 một cặp nhấn / nhả KEYEVENTF_UNICODE (cặp đại diện của emoji đi liền nhau), gửi theo lô. */
786
+ static void TypeUnicode(string text) {
787
+ const int chunk = 64;
788
+ int size = Marshal.SizeOf(typeof(Native.INPUT));
789
+ int start = 0;
790
+ while (start < text.Length) {
791
+ int end = Math.Min(text.Length, start + chunk);
792
+ // Không cắt đôi một cặp đại diện giữa hai lô.
793
+ if (end < text.Length && char.IsHighSurrogate(text[end - 1])) end--;
794
+ var inputs = new Native.INPUT[(end - start) * 2];
795
+ for (int i = start; i < end; i++) {
796
+ int k = (i - start) * 2;
797
+ inputs[k].type = Native.INPUT_KEYBOARD;
798
+ inputs[k].u.ki = new Native.KEYBDINPUT { wVk = 0, wScan = text[i], dwFlags = Native.KEYEVENTF_UNICODE };
799
+ inputs[k + 1].type = Native.INPUT_KEYBOARD;
800
+ inputs[k + 1].u.ki = new Native.KEYBDINPUT { wVk = 0, wScan = text[i], dwFlags = Native.KEYEVENTF_UNICODE | Native.KEYEVENTF_KEYUP };
801
+ }
802
+ Native.SendInput((uint)inputs.Length, inputs, size);
803
+ start = end;
804
+ }
805
+ }
806
+
807
+ static int focusProbeSeq = 0;
808
+
809
+ /**
810
+ * Sau cú nhấp trái của người xem: chờ ứng dụng nhận tiêu điểm rồi báo ô đang chọn có phải ô nhập chữ (có caret) không —
811
+ * trình duyệt trên điện thoại dựa vào đó tự mở bàn phím ảo. Chạy luồng riêng, không giữ hàng thao tác.
812
+ */
813
+ static void ProbeInputFocus() {
814
+ int seq = Interlocked.Increment(ref focusProbeSeq);
815
+ ThreadPool.QueueUserWorkItem(_ => {
816
+ try {
817
+ Thread.Sleep(150);
818
+ if (seq != focusProbeSeq) return;
819
+ var info = new Native.GUITHREADINFO();
820
+ info.cbSize = Marshal.SizeOf(typeof(Native.GUITHREADINFO));
821
+ IntPtr fg = Native.GetForegroundWindow();
822
+ uint tid = fg == IntPtr.Zero ? 0 : Native.GetWindowThreadProcessId(fg, IntPtr.Zero);
823
+ bool editable = (tid != 0 && Native.GetGUIThreadInfo(tid, ref info) && info.hwndCaret != IntPtr.Zero) || FocusedIsTextInput();
824
+ var msg = new Dictionary<string, object>();
825
+ msg["t"] = "input_focus";
826
+ msg["editable"] = editable;
827
+ Out.Send(msg);
828
+ } catch {
829
+ }
830
+ });
831
+ }
832
+
833
+ /** Chromium / Edge / Electron chỉ tạo caret hệ thống khi bật trợ năng → hỏi UI Automation: ô Edit, hoặc ô có giá trị sửa được. */
834
+ static bool FocusedIsTextInput() {
835
+ try {
836
+ var fe = AutomationElement.FocusedElement;
837
+ if (fe == null) return false;
838
+ var ct = fe.Current.ControlType;
839
+ if (ct == ControlType.Edit) return true;
840
+ if (ct == ControlType.ComboBox || ct == ControlType.Document) {
841
+ object vp;
842
+ if (fe.TryGetCurrentPattern(ValuePattern.Pattern, out vp)) return !((ValuePattern)vp).Current.IsReadOnly;
843
+ }
844
+ } catch {
845
+ }
846
+ return false;
847
+ }
848
+
849
+ static void HandleSpecialKey(string key) {
850
+ byte vk = KeyNameToVk(key);
851
+ if (vk != 0) {
852
+ Native.keybd_event(vk, 0, 0, UIntPtr.Zero);
853
+ Thread.Sleep(15);
854
+ Native.keybd_event(vk, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
855
+ }
856
+ }
857
+ }
858
+ }
859
+ ` + DESKTOP_CAST_CAPTURE_CSHARP;
860
+
861
+ export const DESKTOP_CAST_PS1 = String.raw`
862
+ $ErrorActionPreference = 'Stop'
863
+ $dll = $env:AIVIN_CAST_DLL
864
+ $src = $env:AIVIN_CAST_SRC
865
+ $refs = @('UIAutomationClient', 'UIAutomationTypes', 'WindowsBase', 'System.Drawing', 'System.Windows.Forms', 'System.Web.Extensions', 'System.Core')
866
+ foreach ($r in $refs) { Add-Type -AssemblyName $r }
867
+ if ($dll -and (Test-Path -LiteralPath $dll)) {
868
+ Add-Type -Path $dll
869
+ } else {
870
+ Add-Type -TypeDefinition ([IO.File]::ReadAllText($src)) -ReferencedAssemblies $refs -OutputAssembly $dll -OutputType Library
871
+ Add-Type -Path $dll
872
+ }
873
+ try {
874
+ [AivinDesktopCast.CastHost]::Run($env:AIVIN_CAST_ARGS)
875
+ } catch {
876
+ $m = @{ t = 'error'; error = $_.Exception.Message } | ConvertTo-Json -Compress
877
+ [Console]::Out.WriteLine($m)
878
+ exit 1
879
+ }
880
+ `;