@aivin-labs/cli 1.0.46 → 1.0.50

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 (38) hide show
  1. package/bin/cli.mjs +16 -5
  2. package/bin/lib/auth.mjs +24 -10
  3. package/bin/lib/projectEnv.mjs +27 -0
  4. package/bin/lib/remote/client.mjs +1412 -1162
  5. package/bin/lib/remote/confirmBarrier.mjs +45 -0
  6. package/bin/lib/remote/constants.mjs +7 -1
  7. package/bin/lib/remote/desktop/aivinIco.mjs +696 -0
  8. package/bin/lib/remote/desktop/castAuth.mjs +74 -69
  9. package/bin/lib/remote/desktop/castConsent.mjs +90 -0
  10. package/bin/lib/remote/desktop/castFileDrop.mjs +24 -0
  11. package/bin/lib/remote/desktop/castInput.mjs +89 -24
  12. package/bin/lib/remote/desktop/castTouchViewers.mjs +26 -0
  13. package/bin/lib/remote/desktop/desktopCast.mjs +28 -2
  14. package/bin/lib/remote/desktop/desktopCastSource.mjs +410 -121
  15. package/bin/lib/remote/desktop/desktopWebRtc.mjs +17 -1
  16. package/bin/lib/remote/desktop/index.mjs +5 -3
  17. package/bin/lib/remote/desktop/traySource.mjs +1289 -1274
  18. package/bin/lib/remote/desktop/webrtcWorker.mjs +3 -0
  19. package/bin/lib/remote/deviceProfile.mjs +2 -0
  20. package/bin/lib/remote/gui/index.mjs +485 -480
  21. package/bin/lib/remote/humanInput.mjs +117 -0
  22. package/bin/lib/remote/idempotency.mjs +19 -2
  23. package/bin/lib/remote/keepAwake.mjs +15 -9
  24. package/bin/lib/remote/localConfirm.mjs +26 -7
  25. package/bin/lib/remote/localPolicy.mjs +15 -2
  26. package/bin/lib/remote/mascot/ask.mjs +23 -4
  27. package/bin/lib/remote/mascot/askHostSource.mjs +10 -4
  28. package/bin/lib/remote/mascot/bot.mjs +5 -1
  29. package/bin/lib/remote/mascot/hostSource.mjs +8 -1
  30. package/bin/lib/remote/mascot/index.mjs +55 -51
  31. package/bin/lib/remote/mascot/rigSource.mjs +28 -2
  32. package/bin/lib/remote/policyCommand.mjs +16 -3
  33. package/bin/lib/remote/processes.mjs +231 -230
  34. package/bin/lib/remote/sandbox.mjs +6 -4
  35. package/bin/lib/remote/scheduler.mjs +164 -124
  36. package/bin/lib/remote/toolHandlers.mjs +3 -2
  37. package/bin/lib/remote/winTree.mjs +29 -0
  38. package/package.json +1 -1
@@ -23,6 +23,8 @@ using System.Drawing.Imaging;
23
23
  using System.IO;
24
24
  using System.IO.Pipes;
25
25
  using System.Runtime.InteropServices;
26
+ using System.Security.AccessControl;
27
+ using System.Security.Principal;
26
28
  using System.Text;
27
29
  using System.Threading;
28
30
  using System.Threading.Tasks;
@@ -33,10 +35,30 @@ using System.Windows.Forms;
33
35
  namespace AivinDesktopCast {
34
36
  static class Native {
35
37
  [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
38
+ [DllImport("user32.dll")] public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
39
+ [DllImport("shcore.dll")] public static extern int SetProcessDpiAwareness(int value);
36
40
  [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);
41
+ [DllImport("user32.dll", EntryPoint = "mouse_event")] static extern void mouse_event_native(uint dwFlags, int dx, int dy, int dwData, UIntPtr dwExtraInfo);
42
+ [DllImport("user32.dll", EntryPoint = "keybd_event")] static extern void keybd_event_native(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
43
+
44
+ // Dấu của phiên (humanInput.mjs): mọi thao tác tiến trình này bơm vào mang tag bí mật trong dwExtraInfo — hộp xác nhận của Aivin nhận ra
45
+ // thao tác của người đang điều khiển từ xa (đã được chủ máy đồng ý), phân biệt với SendInput / UI Automation của AI. Tham số dwExtraInfo
46
+ // của nơi gọi bị bỏ qua, luôn dùng tag.
47
+ public static UIntPtr InputTag = UIntPtr.Zero;
48
+ public static void mouse_event(uint dwFlags, int dx, int dy, int dwData, int dwExtraInfo) { mouse_event_native(dwFlags, dx, dy, dwData, InputTag); }
49
+ public static void keybd_event(byte bVk, ushort bScan, uint dwFlags, UIntPtr dwExtraInfo) { keybd_event_native(bVk, (byte)bScan, dwFlags, InputTag); }
50
+
51
+ /**
52
+ * Per-monitor v2 (Win10 1703+) → per-monitor (8.1) → system aware. Chỉ system aware thì máy nhiều màn hình khác tỷ lệ phóng (100 % + 150 %)
53
+ * bị Windows ảo hoá toạ độ ở màn hình phụ: ảnh chụp / con trỏ / click lệch nhau.
54
+ */
55
+ public static void UsePerMonitorDpi() {
56
+ try { if (SetProcessDpiAwarenessContext(new IntPtr(-4))) return; } catch { }
57
+ try { if (SetProcessDpiAwareness(2) == 0) return; } catch { }
58
+ try { SetProcessDPIAware(); } catch { }
59
+ }
39
60
  [DllImport("user32.dll")] public static extern short VkKeyScan(char ch);
61
+ [DllImport("user32.dll")] public static extern uint MapVirtualKey(uint code, uint mapType);
40
62
 
41
63
  // 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
64
  // SendInput + KEYEVENTF_UNICODE mang đủ 16 bit mỗi đơn vị UTF-16.
@@ -125,6 +147,7 @@ namespace AivinDesktopCast {
125
147
  public const uint MOUSEEVENTF_WHEEL = 0x0800;
126
148
  public const uint MOUSEEVENTF_HWHEEL = 0x01000;
127
149
 
150
+ public const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
128
151
  public const uint KEYEVENTF_KEYUP = 0x0002;
129
152
  public const uint KEYEVENTF_UNICODE = 0x0004;
130
153
  }
@@ -155,6 +178,207 @@ namespace AivinDesktopCast {
155
178
  }
156
179
  }
157
180
 
181
+ /** Đưa nội dung vào clipboard của máy rồi bấm Ctrl + V. Không ghi được clipboard thì không bấm: bấm sẽ dán nội dung cũ vào chỗ người dùng đang đứng. */
182
+ public static class CastPaste {
183
+ public static bool Run(Func<System.Windows.Forms.DataObject> build, bool notifyOnFail) {
184
+ bool ok = false;
185
+ var sta = new Thread(() => {
186
+ try {
187
+ System.Windows.Forms.Clipboard.SetDataObject(build(), true, 10, 100);
188
+ ok = true;
189
+ } catch { }
190
+ });
191
+ sta.SetApartmentState(ApartmentState.STA);
192
+ sta.Start();
193
+ bool done = sta.Join(3000) && ok;
194
+ if (done) PressPaste();
195
+ else if (notifyOnFail) Out.Send(Out.Msg("paste_failed"));
196
+ return done;
197
+ }
198
+
199
+ static void PressPaste() {
200
+ Thread.Sleep(60);
201
+ Native.keybd_event(0x11, 0, 0, UIntPtr.Zero);
202
+ Thread.Sleep(20);
203
+ Native.keybd_event(0x56, 0, 0, UIntPtr.Zero);
204
+ Thread.Sleep(30);
205
+ Native.keybd_event(0x56, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
206
+ Thread.Sleep(15);
207
+ Native.keybd_event(0x11, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
208
+ }
209
+
210
+ /** Chỉ dạng ảnh, không kèm dạng tệp: có dạng tệp thì nhiều ứng dụng coi là gửi tệp đính kèm thay vì chèn ảnh. Dạng PNG giữ trong suốt; dạng bitmap nền trắng vì ứng dụng cũ vẽ vùng trong suốt thành đen. */
211
+ public static System.Windows.Forms.DataObject ImageData(byte[] bytes) {
212
+ var data = new System.Windows.Forms.DataObject();
213
+ using (var input = new MemoryStream(bytes))
214
+ using (var src = Image.FromStream(input)) {
215
+ var flat = new Bitmap(src.Width, src.Height, PixelFormat.Format32bppArgb);
216
+ using (var g = Graphics.FromImage(flat)) {
217
+ g.Clear(Color.White);
218
+ g.DrawImage(src, 0, 0, src.Width, src.Height);
219
+ }
220
+ data.SetImage(flat);
221
+ var png = new MemoryStream();
222
+ src.Save(png, ImageFormat.Png);
223
+ png.Position = 0;
224
+ data.SetData("PNG", false, png);
225
+ }
226
+ return data;
227
+ }
228
+
229
+ public static System.Windows.Forms.DataObject FileData(string filePath) {
230
+ var data = new System.Windows.Forms.DataObject();
231
+ var list = new System.Collections.Specialized.StringCollection();
232
+ list.Add(filePath);
233
+ data.SetFileDropList(list);
234
+ string ext = Path.GetExtension(filePath).ToLowerInvariant();
235
+ if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp" || ext == ".gif" || ext == ".webp") {
236
+ try {
237
+ using (var src = Image.FromFile(filePath)) {
238
+ var bmp = new Bitmap(src.Width, src.Height, PixelFormat.Format32bppArgb);
239
+ using (var g = Graphics.FromImage(bmp)) g.DrawImage(src, 0, 0, src.Width, src.Height);
240
+ data.SetImage(bmp);
241
+ }
242
+ } catch { }
243
+ }
244
+ return data;
245
+ }
246
+
247
+ public static System.Windows.Forms.DataObject HtmlData(string html, string plain) {
248
+ var data = new System.Windows.Forms.DataObject();
249
+ data.SetData(System.Windows.Forms.DataFormats.Html, false, new MemoryStream(BuildCfHtml(html)));
250
+ if (!string.IsNullOrEmpty(plain)) data.SetData(System.Windows.Forms.DataFormats.UnicodeText, plain);
251
+ return data;
252
+ }
253
+
254
+ /** Định dạng CF_HTML của Windows: phần đầu ghi vị trí theo BYTE của bản UTF-8, lệch một byte là ứng dụng đọc sai. */
255
+ public static byte[] BuildCfHtml(string html) {
256
+ const string pre = "<!DOCTYPE html><html><body><!--StartFragment-->";
257
+ const string post = "<!--EndFragment--></body></html>";
258
+ const string layout = "Version:0.9\r\nStartHTML:{0:D10}\r\nEndHTML:{1:D10}\r\nStartFragment:{2:D10}\r\nEndFragment:{3:D10}\r\n";
259
+ int headerLength = string.Format(layout, 0, 0, 0, 0).Length;
260
+ int fragmentStart = headerLength + pre.Length;
261
+ int fragmentEnd = fragmentStart + Encoding.UTF8.GetByteCount(html);
262
+ int end = fragmentEnd + post.Length;
263
+ return Encoding.UTF8.GetBytes(string.Format(layout, headerLength, end, fragmentStart, fragmentEnd) + pre + html + post);
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Thả tệp thật vào vị trí trên màn hình: mở một thao tác kéo tệp của Windows rồi đưa chuột tới đích, nên ứng dụng nhận như người kéo thật
269
+ * (vùng tải lên sáng lên, nhận nhiều tệp một lần). Thao tác kéo phải bắt đầu từ một cửa sổ của chính mình: nút chuột được nhấn trên ô gần như
270
+ * trong suốt này, không chạm vào thứ gì của người dùng.
271
+ */
272
+ public static class CastDrop {
273
+ const int SOURCE_SIZE = 16;
274
+ const int SOURCE_OFFSET = 36;
275
+ const int MOVE_STEPS = 10;
276
+ const int MOVE_STEP_MS = 25;
277
+ const int HOVER_TICKS = 8;
278
+ const int HOVER_TICK_MS = 40;
279
+ const int WINDOW_WAIT_MS = 2000;
280
+ const int START_WAIT_MS = 1000;
281
+ const int FINISH_WAIT_MS = 8000;
282
+
283
+ sealed class SourceWindow : Form {
284
+ readonly DataObject data;
285
+ public volatile bool Started;
286
+ public DragDropEffects Result = DragDropEffects.None;
287
+
288
+ public SourceWindow(DataObject payload, int centerX, int centerY) {
289
+ data = payload;
290
+ FormBorderStyle = FormBorderStyle.None;
291
+ ShowInTaskbar = false;
292
+ TopMost = true;
293
+ StartPosition = FormStartPosition.Manual;
294
+ Bounds = new Rectangle(centerX - SOURCE_SIZE / 2, centerY - SOURCE_SIZE / 2, SOURCE_SIZE, SOURCE_SIZE);
295
+ Opacity = 0.02;
296
+ BackColor = Color.Black;
297
+ }
298
+
299
+ protected override bool ShowWithoutActivation { get { return true; } }
300
+
301
+ protected override CreateParams CreateParams {
302
+ get {
303
+ var p = base.CreateParams;
304
+ p.ExStyle |= 0x08000000 | 0x00000080; // Không lấy tiêu điểm, không hiện trong Alt + Tab.
305
+ return p;
306
+ }
307
+ }
308
+
309
+ protected override void OnMouseDown(MouseEventArgs e) {
310
+ base.OnMouseDown(e);
311
+ Started = true;
312
+ try { Result = DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Move); } catch { }
313
+ Close();
314
+ }
315
+ }
316
+
317
+ static int Away(int target, int min, int max) {
318
+ int start = target - SOURCE_OFFSET;
319
+ return start - SOURCE_SIZE < min ? Math.Min(target + SOURCE_OFFSET, max - SOURCE_SIZE) : start;
320
+ }
321
+
322
+ /** Di chuột từng bước rồi dừng một lúc ở đích: trang web và ứng dụng cần vài sự kiện rê mới bật vùng thả. Luôn nhả nút, kể cả khi lỗi. */
323
+ static void Drive(SourceWindow window, int fromX, int fromY, int toX, int toY) {
324
+ Native.SetCursorPos(fromX, fromY);
325
+ Thread.Sleep(80);
326
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
327
+ try {
328
+ var waited = System.Diagnostics.Stopwatch.StartNew();
329
+ while (!window.Started && waited.ElapsedMilliseconds < START_WAIT_MS && CastHost.Running) Thread.Sleep(10);
330
+ if (!window.Started) return;
331
+ Thread.Sleep(80);
332
+ for (int i = 1; i <= MOVE_STEPS && CastHost.Running; i++) {
333
+ Native.SetCursorPos(fromX + (toX - fromX) * i / MOVE_STEPS, fromY + (toY - fromY) * i / MOVE_STEPS);
334
+ Thread.Sleep(MOVE_STEP_MS);
335
+ }
336
+ for (int i = 0; i < HOVER_TICKS && CastHost.Running; i++) {
337
+ Native.SetCursorPos(toX + (i % 2 == 0 ? 1 : 0), toY);
338
+ Thread.Sleep(HOVER_TICK_MS);
339
+ }
340
+ Native.SetCursorPos(toX, toY);
341
+ Thread.Sleep(60);
342
+ } finally {
343
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
344
+ }
345
+ }
346
+
347
+ /** Trả về đúng khi ứng dụng ở đích nhận thả. */
348
+ public static bool Run(IList<string> paths, int targetX, int targetY) {
349
+ var list = new System.Collections.Specialized.StringCollection();
350
+ foreach (var path in paths) list.Add(path);
351
+ var data = new DataObject();
352
+ data.SetFileDropList(list);
353
+
354
+ var area = System.Windows.Forms.Screen.FromPoint(new Point(targetX, targetY)).Bounds;
355
+ int fromX = Away(targetX, area.Left, area.Right);
356
+ int fromY = Away(targetY, area.Top, area.Bottom);
357
+
358
+ SourceWindow window = null;
359
+ var shown = new ManualResetEvent(false);
360
+ var host = new Thread(() => {
361
+ try {
362
+ window = new SourceWindow(data, fromX, fromY);
363
+ window.Shown += (sender, e) => shown.Set();
364
+ Application.Run(window);
365
+ } catch { shown.Set(); }
366
+ });
367
+ host.IsBackground = true;
368
+ host.SetApartmentState(ApartmentState.STA);
369
+ host.Start();
370
+ if (!shown.WaitOne(WINDOW_WAIT_MS) || window == null) return false;
371
+
372
+ Drive(window, fromX, fromY, targetX, targetY);
373
+ if (!window.Started) {
374
+ try { window.BeginInvoke(new Action(window.Close)); } catch { }
375
+ return false;
376
+ }
377
+ host.Join(FINISH_WAIT_MS);
378
+ return window.Result != DragDropEffects.None;
379
+ }
380
+ }
381
+
158
382
  /** Named pipe một chiều gửi khung thô I420 + âm thanh PCM cho tiến trình Node (một khách). Khách rớt → chờ khách mới. */
159
383
  static class RawPipe {
160
384
  static readonly object gate = new object();
@@ -164,11 +388,19 @@ namespace AivinDesktopCast {
164
388
  static readonly byte[] videoHeader = new byte[12];
165
389
  static byte[] audioPacket = new byte[12 + 1920];
166
390
 
391
+ /** Khung thô là toàn bộ màn hình: chỉ đúng tài khoản đang chạy mới mở được, không nhận kết nối qua mạng. */
392
+ static PipeSecurity OwnerOnly() {
393
+ var security = new PipeSecurity();
394
+ security.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().User, PipeAccessRights.FullControl, AccessControlType.Allow));
395
+ security.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.NetworkSid, null), PipeAccessRights.FullControl, AccessControlType.Deny));
396
+ return security;
397
+ }
398
+
167
399
  public static void Start(string name) {
168
400
  var t = new Thread(() => {
169
401
  while (CastHost.Running) {
170
402
  try {
171
- var p = new NamedPipeServerStream(name, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 8 * 1024 * 1024);
403
+ var p = new NamedPipeServerStream(name, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 8 * 1024 * 1024, OwnerOnly());
172
404
  p.WaitForConnection();
173
405
  lock (gate) { pipe = p; Connected = true; }
174
406
  while (CastHost.Running && p.IsConnected) Thread.Sleep(200);
@@ -233,6 +465,8 @@ namespace AivinDesktopCast {
233
465
 
234
466
  public static class CastScreen {
235
467
  static byte[] i420Raw;
468
+ static byte[] scaleRaw;
469
+ static byte[] scaleOut;
236
470
  static byte[] i420Out;
237
471
  static Bitmap cursorBuffer;
238
472
  static Bitmap scaleBuffer;
@@ -377,6 +611,51 @@ namespace AivinDesktopCast {
377
611
  return cursorBuffer;
378
612
  }
379
613
 
614
+ /** Song tuyến tính chia theo hàng trên nhiều nhân: GDI+ DrawImage chỉ chạy một nhân, đo 14 ms mỗi khung từ 1080p xuống 1280, là khâu đắt nhất của bộ quay. */
615
+ static void ScaleBilinear(Bitmap src, Bitmap dst) {
616
+ int sw = src.Width, sh = src.Height, dw = dst.Width, dh = dst.Height;
617
+ var sd = src.LockBits(new Rectangle(0, 0, sw, sh), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
618
+ try {
619
+ var dd = dst.LockBits(new Rectangle(0, 0, dw, dh), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);
620
+ try {
621
+ int sStride = Math.Abs(sd.Stride), dStride = Math.Abs(dd.Stride);
622
+ int sLen = sStride * sh, dLen = dStride * dh;
623
+ if (scaleRaw == null || scaleRaw.Length < sLen) scaleRaw = new byte[sLen];
624
+ if (scaleOut == null || scaleOut.Length < dLen) scaleOut = new byte[dLen];
625
+ byte[] raw = scaleRaw, output = scaleOut;
626
+ Marshal.Copy(sd.Scan0, raw, 0, sLen);
627
+ long xStep = ((long)(sw - 1) << 16) / Math.Max(1, dw - 1);
628
+ long yStep = ((long)(sh - 1) << 16) / Math.Max(1, dh - 1);
629
+ Parallel.For(0, dh, y => {
630
+ long fy = y * yStep;
631
+ int sy = (int)(fy >> 16);
632
+ int wy = (int)((fy >> 8) & 0xFF);
633
+ int row0 = sy * sStride;
634
+ int row1 = (sy + 1 < sh ? sy + 1 : sy) * sStride;
635
+ int o = y * dStride;
636
+ for (int x = 0; x < dw; x++, o += 4) {
637
+ long fx = x * xStep;
638
+ int sx = (int)(fx >> 16);
639
+ int wx = (int)((fx >> 8) & 0xFF);
640
+ int a = sx * 4;
641
+ int b = (sx + 1 < sw ? sx + 1 : sx) * 4;
642
+ for (int c = 0; c < 3; c++) {
643
+ int top = raw[row0 + a + c] * (256 - wx) + raw[row0 + b + c] * wx;
644
+ int bottom = raw[row1 + a + c] * (256 - wx) + raw[row1 + b + c] * wx;
645
+ output[o + c] = (byte)((top * (256 - wy) + bottom * wy) >> 16);
646
+ }
647
+ output[o + 3] = 255;
648
+ }
649
+ });
650
+ Marshal.Copy(output, 0, dd.Scan0, dLen);
651
+ } finally {
652
+ dst.UnlockBits(dd);
653
+ }
654
+ } finally {
655
+ src.UnlockBits(sd);
656
+ }
657
+ }
658
+
380
659
  public static Bitmap Scale(Bitmap src, int maxWidth) {
381
660
  if (src.Width <= maxWidth) return src;
382
661
  int h = (int)Math.Round(src.Height * (double)maxWidth / src.Width);
@@ -384,11 +663,7 @@ namespace AivinDesktopCast {
384
663
  if (scaleBuffer != null) scaleBuffer.Dispose();
385
664
  scaleBuffer = new Bitmap(maxWidth, h, PixelFormat.Format32bppRgb);
386
665
  }
387
- using (var g = Graphics.FromImage(scaleBuffer)) {
388
- g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
389
- g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
390
- g.DrawImage(src, 0, 0, maxWidth, h);
391
- }
666
+ ScaleBilinear(src, scaleBuffer);
392
667
  return scaleBuffer;
393
668
  }
394
669
 
@@ -464,8 +739,10 @@ namespace AivinDesktopCast {
464
739
  }
465
740
 
466
741
  public static class CastHost {
467
- const long JPEG_SMALL_CHANGE_INTERVAL_MS = 66;
742
+ const long JPEG_SMALL_CHANGE_INTERVAL_MS = 200;
468
743
  const double JPEG_BIG_CHANGE_DIFF = 4.5;
744
+ const long JPEG_IDLE_REFRESH_MS = 8000;
745
+ const long SCREENS_REFRESH_MS = 2000;
469
746
  const int RATIO_SCALE = 65535;
470
747
  static volatile bool running = true;
471
748
  public static bool Running { get { return running; } }
@@ -481,11 +758,14 @@ namespace AivinDesktopCast {
481
758
  static volatile int targetMaxWidth = 1366;
482
759
  static volatile int targetQuality = 65;
483
760
  static bool lastSecureDesktop = false;
761
+ static long lastScreensMs = -SCREENS_REFRESH_MS;
484
762
 
485
763
  public static void Run(string argsJson) {
486
- Native.SetProcessDPIAware();
764
+ Native.UsePerMonitorDpi();
487
765
  Native.timeBeginPeriod(1);
488
766
  var a = Out.Parse(argsJson);
767
+ long inputTag;
768
+ if (a.ContainsKey("input_tag") && long.TryParse(Convert.ToString(a["input_tag"]), out inputTag) && inputTag > 0 && inputTag <= 0xFFFFFFFFL) Native.InputTag = new UIntPtr((ulong)inputTag);
489
769
  currentMonitor = a.ContainsKey("monitor") ? Convert.ToInt32(a["monitor"]) : -1;
490
770
  targetMaxFps = a.ContainsKey("max_fps") ? Convert.ToInt32(a["max_fps"]) : 15;
491
771
  if (targetMaxFps < 1) targetMaxFps = 1;
@@ -504,6 +784,9 @@ namespace AivinDesktopCast {
504
784
  var inputThread = new Thread(ReadInputLoop);
505
785
  inputThread.IsBackground = true;
506
786
  inputThread.Start();
787
+ inputExecutor = new Thread(ExecuteInputLoop);
788
+ inputExecutor.IsBackground = true;
789
+ inputExecutor.Start();
507
790
 
508
791
  var readyMsg = Out.Msg("ready");
509
792
  readyMsg["monitor"] = currentMonitor;
@@ -522,6 +805,8 @@ namespace AivinDesktopCast {
522
805
  bool changePending = false;
523
806
  int lastCursorSeq = -1;
524
807
  long lastSendMs = 0;
808
+ long lastJpegMs = 0;
809
+ bool jpegSettled = false;
525
810
  long lastAuxCheckMs = 0;
526
811
 
527
812
  while (running) {
@@ -550,7 +835,10 @@ namespace AivinDesktopCast {
550
835
  long nowMs = clock.ElapsedMilliseconds;
551
836
  bool forceKeepAlive = (nowMs - lastSendMs) >= 1000;
552
837
  bool refresh = refreshRequested;
553
- if (refresh) refreshRequested = false;
838
+ if (refresh) {
839
+ refreshRequested = false;
840
+ lastScreensMs = -SCREENS_REFRESH_MS;
841
+ }
554
842
 
555
843
  bool jpegMode = jpegEnabled || !rawEnabled;
556
844
  bool sendChange = changePending;
@@ -562,9 +850,16 @@ namespace AivinDesktopCast {
562
850
  changePending = false;
563
851
  lastSendMs = nowMs;
564
852
  lastCursorSeq = cursorSeq;
565
- if (jpegMode) lastJpegThumb = CastScreen.Thumb(source.Frame);
853
+ // Mỗi ảnh JPEG là nguyên màn hình đi qua máy chủ. Màn hình đứng yên chỉ gửi gói giữ nhịp không ảnh; sau lần đổi cuối gửi lại một ảnh phòng ảnh trước bị rơi (đường này không gửi lại), rồi thưa hẳn.
854
+ bool changed = sendChange || refresh;
855
+ bool withJpeg = jpegMode && (changed || !jpegSettled || nowMs - lastJpegMs >= JPEG_IDLE_REFRESH_MS);
856
+ jpegSettled = !changed;
857
+ if (withJpeg) {
858
+ lastJpegMs = nowMs;
859
+ lastJpegThumb = CastScreen.Thumb(source.Frame);
860
+ }
566
861
  long sendStartMs = clock.ElapsedMilliseconds;
567
- SendFrame(source.Frame, cursorInFrame, jpegMode, nowMs, hostStats);
862
+ SendFrame(source.Frame, cursorInFrame, withJpeg, nowMs, hostStats);
568
863
  hostStats.AddLoad(clock.ElapsedMilliseconds - sendStartMs);
569
864
  }
570
865
  } catch (Exception ex) {
@@ -578,6 +873,8 @@ namespace AivinDesktopCast {
578
873
  else if (!source.UsingDxgi) Thread.Sleep(1);
579
874
  }
580
875
  source.Dispose();
876
+ StopInput();
877
+ try { if (inputExecutor != null) inputExecutor.Join(2000); } catch { }
581
878
 
582
879
  var stoppedMsg = Out.Msg("stopped");
583
880
  Out.Send(stoppedMsg);
@@ -607,35 +904,61 @@ namespace AivinDesktopCast {
607
904
  frameMsg["screenX"] = currentBounds.X;
608
905
  frameMsg["screenY"] = currentBounds.Y;
609
906
  frameMsg["monitor"] = currentMonitor;
610
- frameMsg["screens"] = CastScreen.GetScreens();
907
+ // Danh sách màn hình ít khi đổi: không gửi và không tra lại ở mọi khung.
908
+ if (nowMs - lastScreensMs >= SCREENS_REFRESH_MS) {
909
+ lastScreensMs = nowMs;
910
+ frameMsg["screens"] = CastScreen.GetScreens();
911
+ }
611
912
  frameMsg["ts"] = nowMs;
612
913
  frameMsg["stats"] = hostStats.Snapshot(nowMs);
613
914
  if (lastSecureDesktop) frameMsg["secureDesktop"] = true;
614
915
  Out.Send(frameMsg);
615
916
  }
616
917
 
918
+ /**
919
+ * Đọc lệnh từ stdin trên một luồng, thực thi trên luồng khác (ExecuteInputLoop). Trước đây đọc + thực thi chung một luồng: lệnh "stop"
920
+ * nằm sau các thao tác còn xếp hàng (một lần kéo thả, gõ dài…) nên chúng vẫn chạy hết sau khi chủ máy bấm ngắt. Nay đọc thấy "stop" (hoặc
921
+ * stdin đóng — daemon chết) là dừng ngay, bỏ phần còn xếp hàng.
922
+ */
923
+ static readonly Queue<Dictionary<string, object>> inputQueue = new Queue<Dictionary<string, object>>();
924
+ static Thread inputExecutor;
925
+
926
+ static void StopInput() {
927
+ running = false;
928
+ lock (inputQueue) { inputQueue.Clear(); Monitor.PulseAll(inputQueue); }
929
+ }
930
+
617
931
  static void ReadInputLoop() {
618
932
  try {
619
933
  string line;
620
934
  while (running && (line = Out.Stdin.ReadLine()) != null) {
621
935
  line = line.Trim();
622
936
  if (string.IsNullOrEmpty(line)) continue;
623
- if (line == "stop") {
624
- running = false;
625
- break;
626
- }
937
+ if (line == "stop") break;
627
938
  var cmd = Out.Parse(line);
628
939
  string op = cmd.ContainsKey("op") ? Convert.ToString(cmd["op"]) : "";
629
- if (op == "stop") {
630
- running = false;
631
- break;
632
- } else if (op == "input") {
633
- HandleInput(cmd);
634
- } else if (op == "config") {
635
- HandleConfig(cmd);
636
- } else if (op == "refresh") {
637
- refreshRequested = true;
940
+ if (op == "stop") break;
941
+ lock (inputQueue) { inputQueue.Enqueue(cmd); Monitor.Pulse(inputQueue); }
942
+ }
943
+ } catch {
944
+ } finally {
945
+ StopInput();
946
+ }
947
+ }
948
+
949
+ static void ExecuteInputLoop() {
950
+ try {
951
+ while (true) {
952
+ Dictionary<string, object> cmd;
953
+ lock (inputQueue) {
954
+ while (running && inputQueue.Count == 0) Monitor.Wait(inputQueue, 500);
955
+ if (!running) break;
956
+ cmd = inputQueue.Dequeue();
638
957
  }
958
+ string op = cmd.ContainsKey("op") ? Convert.ToString(cmd["op"]) : "";
959
+ if (op == "input") HandleInput(cmd);
960
+ else if (op == "config") HandleConfig(cmd);
961
+ else if (op == "refresh") refreshRequested = true;
639
962
  }
640
963
  } catch {
641
964
  running = false;
@@ -745,6 +1068,20 @@ namespace AivinDesktopCast {
745
1068
  }
746
1069
  }
747
1070
 
1071
+ /**
1072
+ * Phím thuộc cụm mở rộng phải gắn cờ extended. Thiếu cờ, Windows hiểu mũi tên / Home / End... là phím số bên phải:
1073
+ * NumLock đang bật thì Shift bị huỷ để phím đó vẫn là di chuyển, nên Shift + mũi tên chỉ di chuyển, không bôi đen.
1074
+ */
1075
+ static bool IsExtendedKey(byte vk) {
1076
+ return (vk >= 0x21 && vk <= 0x28) || vk == 0x2C || vk == 0x2D || vk == 0x2E
1077
+ || vk == 0x5B || vk == 0x5C || vk == 0x5D || vk == 0x90 || vk == 0xA3 || vk == 0xA5;
1078
+ }
1079
+
1080
+ static void SendKey(byte vk, bool up) {
1081
+ uint flags = (IsExtendedKey(vk) ? Native.KEYEVENTF_EXTENDEDKEY : 0) | (up ? Native.KEYEVENTF_KEYUP : 0);
1082
+ Native.keybd_event(vk, (byte)Native.MapVirtualKey(vk, 0), flags, UIntPtr.Zero);
1083
+ }
1084
+
748
1085
  static List<byte> ExtractModifiers(Dictionary<string, object> cmd) {
749
1086
  var list = new List<byte>();
750
1087
  if (!cmd.ContainsKey("modifiers") || cmd["modifiers"] == null) return list;
@@ -760,14 +1097,14 @@ namespace AivinDesktopCast {
760
1097
 
761
1098
  static void PressModifiers(List<byte> mods) {
762
1099
  for (int i = 0; i < mods.Count; i++) {
763
- Native.keybd_event(mods[i], 0, 0, UIntPtr.Zero);
1100
+ SendKey(mods[i], false);
764
1101
  }
765
1102
  if (mods.Count > 0) Thread.Sleep(8);
766
1103
  }
767
1104
 
768
1105
  static void ReleaseModifiers(List<byte> mods) {
769
1106
  for (int i = mods.Count - 1; i >= 0; i--) {
770
- Native.keybd_event(mods[i], 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1107
+ SendKey(mods[i], true);
771
1108
  }
772
1109
  }
773
1110
 
@@ -966,95 +1303,33 @@ namespace AivinDesktopCast {
966
1303
  } else if (action == "paste_image") {
967
1304
  string b64 = cmd.ContainsKey("data") ? Convert.ToString(cmd["data"]) : "";
968
1305
  if (!string.IsNullOrEmpty(b64)) {
969
- if (cmd.ContainsKey("click") && Convert.ToBoolean(cmd["click"])) {
970
- Native.SetCursorPos(targetX, targetY);
971
- Thread.Sleep(20);
972
- Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
973
- Thread.Sleep(15);
974
- Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
975
- Thread.Sleep(35);
976
- }
977
- var sta = new Thread(() => {
978
- try {
979
- byte[] bytes = Convert.FromBase64String(b64);
980
- using (var ms = new System.IO.MemoryStream(bytes)) {
981
- using (var src = System.Drawing.Image.FromStream(ms)) {
982
- var dataObj = new System.Windows.Forms.DataObject();
983
- var bmp = new System.Drawing.Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
984
- using (var g = System.Drawing.Graphics.FromImage(bmp)) {
985
- g.DrawImage(src, 0, 0, src.Width, src.Height);
986
- }
987
- dataObj.SetImage(bmp);
988
- try {
989
- string tempFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "aivin_paste_" + DateTime.Now.Ticks + ".png");
990
- bmp.Save(tempFile, System.Drawing.Imaging.ImageFormat.Png);
991
- var sc = new System.Collections.Specialized.StringCollection();
992
- sc.Add(tempFile);
993
- dataObj.SetFileDropList(sc);
994
- } catch { }
995
- System.Windows.Forms.Clipboard.SetDataObject(dataObj, true);
996
- }
997
- }
998
- } catch { }
999
- });
1000
- sta.SetApartmentState(ApartmentState.STA);
1001
- sta.Start();
1002
- if (sta.Join(3000)) {
1003
- Thread.Sleep(60);
1004
- Native.keybd_event(0x11, 0, 0, UIntPtr.Zero);
1005
- Thread.Sleep(20);
1006
- Native.keybd_event(0x56, 0, 0, UIntPtr.Zero);
1007
- Thread.Sleep(30);
1008
- Native.keybd_event(0x56, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1009
- Thread.Sleep(15);
1010
- Native.keybd_event(0x11, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1011
- }
1306
+ ClickIfAsked(cmd, targetX, targetY);
1307
+ CastPaste.Run(() => CastPaste.ImageData(Convert.FromBase64String(b64)), true);
1012
1308
  }
1309
+ } else if (action == "paste_html") {
1310
+ string html = cmd.ContainsKey("html") ? Convert.ToString(cmd["html"]) : "";
1311
+ string plain = cmd.ContainsKey("text") ? Convert.ToString(cmd["text"]) : "";
1312
+ if (!string.IsNullOrEmpty(html)) CastPaste.Run(() => CastPaste.HtmlData(html, plain), true);
1013
1313
  } else if (action == "paste_file") {
1014
1314
  string filePath = cmd.ContainsKey("path") ? Convert.ToString(cmd["path"]) : "";
1315
+ bool asImage = cmd.ContainsKey("as_image") && Convert.ToBoolean(cmd["as_image"]);
1015
1316
  if (!string.IsNullOrEmpty(filePath) && System.IO.File.Exists(filePath)) {
1016
- if (cmd.ContainsKey("click") && Convert.ToBoolean(cmd["click"])) {
1017
- Native.SetCursorPos(targetX, targetY);
1018
- Thread.Sleep(20);
1019
- Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
1020
- Thread.Sleep(15);
1021
- Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
1022
- Thread.Sleep(35);
1023
- }
1024
- var sta = new Thread(() => {
1025
- try {
1026
- var dataObj = new System.Windows.Forms.DataObject();
1027
- var sc = new System.Collections.Specialized.StringCollection();
1028
- sc.Add(filePath);
1029
- dataObj.SetFileDropList(sc);
1030
- string ext = System.IO.Path.GetExtension(filePath).ToLowerInvariant();
1031
- if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp" || ext == ".gif" || ext == ".webp") {
1032
- try {
1033
- using (var src = System.Drawing.Image.FromFile(filePath)) {
1034
- var bmp = new System.Drawing.Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
1035
- using (var g = System.Drawing.Graphics.FromImage(bmp)) {
1036
- g.DrawImage(src, 0, 0, src.Width, src.Height);
1037
- }
1038
- dataObj.SetImage(bmp);
1039
- }
1040
- } catch { }
1041
- }
1042
- System.Windows.Forms.Clipboard.SetDataObject(dataObj, true);
1043
- } catch { }
1044
- });
1045
- sta.SetApartmentState(ApartmentState.STA);
1046
- sta.Start();
1047
- if (sta.Join(3000)) {
1048
- Thread.Sleep(60);
1049
- Native.keybd_event(0x11, 0, 0, UIntPtr.Zero);
1050
- Thread.Sleep(20);
1051
- Native.keybd_event(0x56, 0, 0, UIntPtr.Zero);
1052
- Thread.Sleep(30);
1053
- Native.keybd_event(0x56, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1054
- Thread.Sleep(15);
1055
- Native.keybd_event(0x11, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1317
+ ClickIfAsked(cmd, targetX, targetY);
1318
+ // Ảnh từ clipboard của người xem: dán như ảnh, tệp lưu tạm không còn cần nữa. Không đọc được thì dán như tệp.
1319
+ if (asImage && CastPaste.Run(() => CastPaste.ImageData(System.IO.File.ReadAllBytes(filePath)), false)) {
1320
+ try { System.IO.File.Delete(filePath); } catch { }
1321
+ } else {
1322
+ CastPaste.Run(() => CastPaste.FileData(filePath), true);
1056
1323
  }
1057
1324
  }
1325
+ } else if (action == "drop_files") {
1326
+ var dropPaths = new List<string>();
1327
+ var rawPaths = cmd.ContainsKey("paths") ? cmd["paths"] as System.Collections.ArrayList : null;
1328
+ if (rawPaths != null) foreach (var item in rawPaths) {
1329
+ string one = Convert.ToString(item);
1330
+ if (System.IO.File.Exists(one)) dropPaths.Add(one);
1331
+ }
1332
+ if (dropPaths.Count > 0 && !CastDrop.Run(dropPaths, targetX, targetY)) Out.Send(Out.Msg("drop_refused"));
1058
1333
  } else if (action == "key") {
1059
1334
  string key = cmd.ContainsKey("key") ? Convert.ToString(cmd["key"]) : "";
1060
1335
  HandleSpecialKey(key);
@@ -1066,14 +1341,18 @@ namespace AivinDesktopCast {
1066
1341
  byte vk = KeyNameToVk(Convert.ToString(keys[i]));
1067
1342
  if (vk != 0) vks.Add(vk);
1068
1343
  }
1344
+ // Giữ tổ hợp thì trình duyệt lặp ~30 lần/giây: chậm hơn nhịp đó là lệnh dồn lại, nhả tay rồi vùng chọn vẫn chạy tiếp. Tổ hợp có Win giữ nhịp chậm vì shell xử lý chậm.
1345
+ bool withWin = vks.Contains(0x5B) || vks.Contains(0x5C);
1346
+ int stepMs = withWin ? 10 : 2;
1347
+ int holdMs = withWin ? 40 : 12;
1069
1348
  for (int i = 0; i < vks.Count; i++) {
1070
- Native.keybd_event(vks[i], 0, 0, UIntPtr.Zero);
1071
- Thread.Sleep(10);
1349
+ SendKey(vks[i], false);
1350
+ Thread.Sleep(stepMs);
1072
1351
  }
1073
- Thread.Sleep(40);
1352
+ Thread.Sleep(holdMs);
1074
1353
  for (int i = vks.Count - 1; i >= 0; i--) {
1075
- Native.keybd_event(vks[i], 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1076
- Thread.Sleep(10);
1354
+ SendKey(vks[i], true);
1355
+ Thread.Sleep(stepMs);
1077
1356
  }
1078
1357
  }
1079
1358
  }
@@ -1094,9 +1373,9 @@ namespace AivinDesktopCast {
1094
1373
  for (int i = start; i < end; i++) {
1095
1374
  int k = (i - start) * 2;
1096
1375
  inputs[k].type = Native.INPUT_KEYBOARD;
1097
- inputs[k].u.ki = new Native.KEYBDINPUT { wVk = 0, wScan = text[i], dwFlags = Native.KEYEVENTF_UNICODE };
1376
+ inputs[k].u.ki = new Native.KEYBDINPUT { wVk = 0, wScan = text[i], dwFlags = Native.KEYEVENTF_UNICODE, dwExtraInfo = (IntPtr)(long)Native.InputTag.ToUInt64() };
1098
1377
  inputs[k + 1].type = Native.INPUT_KEYBOARD;
1099
- inputs[k + 1].u.ki = new Native.KEYBDINPUT { wVk = 0, wScan = text[i], dwFlags = Native.KEYEVENTF_UNICODE | Native.KEYEVENTF_KEYUP };
1378
+ inputs[k + 1].u.ki = new Native.KEYBDINPUT { wVk = 0, wScan = text[i], dwFlags = Native.KEYEVENTF_UNICODE | Native.KEYEVENTF_KEYUP, dwExtraInfo = (IntPtr)(long)Native.InputTag.ToUInt64() };
1100
1379
  }
1101
1380
  Native.SendInput((uint)inputs.Length, inputs, size);
1102
1381
  start = end;
@@ -1154,12 +1433,22 @@ namespace AivinDesktopCast {
1154
1433
  return false;
1155
1434
  }
1156
1435
 
1436
+ static void ClickIfAsked(Dictionary<string, object> cmd, int x, int y) {
1437
+ if (!cmd.ContainsKey("click") || !Convert.ToBoolean(cmd["click"])) return;
1438
+ Native.SetCursorPos(x, y);
1439
+ Thread.Sleep(20);
1440
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
1441
+ Thread.Sleep(15);
1442
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
1443
+ Thread.Sleep(35);
1444
+ }
1445
+
1157
1446
  static void HandleSpecialKey(string key) {
1158
1447
  byte vk = KeyNameToVk(key);
1159
1448
  if (vk != 0) {
1160
- Native.keybd_event(vk, 0, 0, UIntPtr.Zero);
1449
+ SendKey(vk, false);
1161
1450
  Thread.Sleep(15);
1162
- Native.keybd_event(vk, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1451
+ SendKey(vk, true);
1163
1452
  }
1164
1453
  }
1165
1454
  }