ai-remote 0.1.0

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 (114) hide show
  1. package/README.md +50 -0
  2. package/dist/index.js +7 -0
  3. package/dist/index.js.map +7 -0
  4. package/dist/protocols/index.js +35 -0
  5. package/dist/protocols/index.js.map +7 -0
  6. package/dist/protocols/rdp/buffer.js +170 -0
  7. package/dist/protocols/rdp/buffer.js.map +7 -0
  8. package/dist/protocols/rdp/caps.js +260 -0
  9. package/dist/protocols/rdp/caps.js.map +7 -0
  10. package/dist/protocols/rdp/cert.js +135 -0
  11. package/dist/protocols/rdp/cert.js.map +7 -0
  12. package/dist/protocols/rdp/client.js +1068 -0
  13. package/dist/protocols/rdp/client.js.map +7 -0
  14. package/dist/protocols/rdp/cliprdr.js +240 -0
  15. package/dist/protocols/rdp/cliprdr.js.map +7 -0
  16. package/dist/protocols/rdp/credssp.js +254 -0
  17. package/dist/protocols/rdp/credssp.js.map +7 -0
  18. package/dist/protocols/rdp/crypto.js +369 -0
  19. package/dist/protocols/rdp/crypto.js.map +7 -0
  20. package/dist/protocols/rdp/display.js +589 -0
  21. package/dist/protocols/rdp/display.js.map +7 -0
  22. package/dist/protocols/rdp/gcc.js +132 -0
  23. package/dist/protocols/rdp/gcc.js.map +7 -0
  24. package/dist/protocols/rdp/keymap.js +132 -0
  25. package/dist/protocols/rdp/keymap.js.map +7 -0
  26. package/dist/protocols/rdp/mcs.js +223 -0
  27. package/dist/protocols/rdp/mcs.js.map +7 -0
  28. package/dist/protocols/rdp/ntlm.js +305 -0
  29. package/dist/protocols/rdp/ntlm.js.map +7 -0
  30. package/dist/protocols/rdp/pdu.js +444 -0
  31. package/dist/protocols/rdp/pdu.js.map +7 -0
  32. package/dist/protocols/rdp/rail.js +383 -0
  33. package/dist/protocols/rdp/rail.js.map +7 -0
  34. package/dist/protocols/rdp/rle.js +276 -0
  35. package/dist/protocols/rdp/rle.js.map +7 -0
  36. package/dist/protocols/rdp/sec.js +156 -0
  37. package/dist/protocols/rdp/sec.js.map +7 -0
  38. package/dist/protocols/rdp/session.js +307 -0
  39. package/dist/protocols/rdp/session.js.map +7 -0
  40. package/dist/protocols/rdp/tls.js +354 -0
  41. package/dist/protocols/rdp/tls.js.map +7 -0
  42. package/dist/protocols/rdp/vchannel.js +59 -0
  43. package/dist/protocols/rdp/vchannel.js.map +7 -0
  44. package/dist/protocols/rdp/x224.js +110 -0
  45. package/dist/protocols/rdp/x224.js.map +7 -0
  46. package/dist/protocols/ssh/kex.js +177 -0
  47. package/dist/protocols/ssh/kex.js.map +7 -0
  48. package/dist/protocols/ssh/messages.js +55 -0
  49. package/dist/protocols/ssh/messages.js.map +7 -0
  50. package/dist/protocols/ssh/session.js +608 -0
  51. package/dist/protocols/ssh/session.js.map +7 -0
  52. package/dist/protocols/ssh/terminal.js +191 -0
  53. package/dist/protocols/ssh/terminal.js.map +7 -0
  54. package/dist/protocols/ssh/transport.js +611 -0
  55. package/dist/protocols/ssh/transport.js.map +7 -0
  56. package/dist/protocols/ssh/wire.js +189 -0
  57. package/dist/protocols/ssh/wire.js.map +7 -0
  58. package/dist/protocols/types.js +1 -0
  59. package/dist/protocols/types.js.map +7 -0
  60. package/dist/protocols/vnc/input.js +16 -0
  61. package/dist/protocols/vnc/input.js.map +7 -0
  62. package/dist/protocols/vnc/session.js +259 -0
  63. package/dist/protocols/vnc/session.js.map +7 -0
  64. package/dist/shared/connection.js +114 -0
  65. package/dist/shared/connection.js.map +7 -0
  66. package/dist/shared/device.js +1 -0
  67. package/dist/shared/device.js.map +7 -0
  68. package/dist/shared/hosts.js +133 -0
  69. package/dist/shared/hosts.js.map +7 -0
  70. package/dist/shared/icons.js +42 -0
  71. package/dist/shared/icons.js.map +7 -0
  72. package/dist/shared/protocol.js +40 -0
  73. package/dist/shared/protocol.js.map +7 -0
  74. package/dist/shared/signals.js +42 -0
  75. package/dist/shared/signals.js.map +7 -0
  76. package/package.json +82 -0
  77. package/src/index.ts +14 -0
  78. package/src/protocols/index.ts +72 -0
  79. package/src/protocols/rdp/buffer.ts +204 -0
  80. package/src/protocols/rdp/caps.ts +304 -0
  81. package/src/protocols/rdp/cert.ts +190 -0
  82. package/src/protocols/rdp/client.ts +1363 -0
  83. package/src/protocols/rdp/cliprdr.ts +344 -0
  84. package/src/protocols/rdp/credssp.ts +319 -0
  85. package/src/protocols/rdp/crypto.ts +416 -0
  86. package/src/protocols/rdp/display.ts +750 -0
  87. package/src/protocols/rdp/gcc.ts +162 -0
  88. package/src/protocols/rdp/keymap.ts +68 -0
  89. package/src/protocols/rdp/mcs.ts +283 -0
  90. package/src/protocols/rdp/ntlm.ts +380 -0
  91. package/src/protocols/rdp/pdu.ts +497 -0
  92. package/src/protocols/rdp/rail.ts +480 -0
  93. package/src/protocols/rdp/rle.ts +343 -0
  94. package/src/protocols/rdp/sec.ts +184 -0
  95. package/src/protocols/rdp/session.ts +393 -0
  96. package/src/protocols/rdp/tls.ts +452 -0
  97. package/src/protocols/rdp/vchannel.ts +89 -0
  98. package/src/protocols/rdp/x224.ts +139 -0
  99. package/src/protocols/ssh/kex.ts +227 -0
  100. package/src/protocols/ssh/messages.ts +54 -0
  101. package/src/protocols/ssh/session.ts +878 -0
  102. package/src/protocols/ssh/terminal.ts +242 -0
  103. package/src/protocols/ssh/transport.ts +732 -0
  104. package/src/protocols/ssh/wire.ts +220 -0
  105. package/src/protocols/types.ts +146 -0
  106. package/src/protocols/vnc/input.ts +13 -0
  107. package/src/protocols/vnc/novnc.d.ts +75 -0
  108. package/src/protocols/vnc/session.ts +367 -0
  109. package/src/shared/connection.ts +206 -0
  110. package/src/shared/device.ts +28 -0
  111. package/src/shared/hosts.ts +240 -0
  112. package/src/shared/icons.ts +49 -0
  113. package/src/shared/protocol.ts +55 -0
  114. package/src/shared/signals.ts +67 -0
@@ -0,0 +1,750 @@
1
+ // Canvas rendering and input capture for an RDP session.
2
+ //
3
+ // The host sends rectangles of pixels and a cursor shape; this module paints
4
+ // them, maps browser events back into desktop coordinates, and turns key events
5
+ // into the scancodes RDP expects.
6
+
7
+ import { decodeBitmapRect } from './rle';
8
+ import { TOGGLE_FLAG } from './pdu';
9
+
10
+ /**
11
+ * On a Mac the editing shortcuts live on Command, and Windows expects them on
12
+ * Control. Sending Command through as the Windows key -- which is what its
13
+ * scancode means -- would make copy and paste unreachable, so it is translated
14
+ * instead. The Special Keys panel still sends a real Windows key.
15
+ */
16
+ const IS_MAC = /Mac|iPod|iPhone|iPad/.test(
17
+ globalThis.navigator?.platform || globalThis.navigator?.userAgent || ''
18
+ );
19
+
20
+ const COMMAND_TO_CONTROL = {
21
+ MetaLeft: 'ControlLeft',
22
+ MetaRight: 'ControlRight',
23
+ };
24
+
25
+ // Trackpads emit many small wheel events. Waiting for roughly one line of
26
+ // accumulated motion prevents each tiny event from becoming a full RDP notch.
27
+ const WHEEL_STEP_PIXELS = 60;
28
+ const WHEEL_LINE_PIXELS = 16;
29
+
30
+ /** Two fingers dragged this far, per notch, count as one wheel click. */
31
+ const TOUCH_SCROLL_STEP = 20;
32
+
33
+ /**
34
+ * How far past "the whole desktop is visible" a pinch may go. Eight is well
35
+ * past readable on any phone; the floor of 1 is the fitted view, because
36
+ * zooming out beyond the window only adds letterboxing.
37
+ */
38
+ const MAX_ZOOM = 8;
39
+ const MIN_ZOOM = 1;
40
+
41
+
42
+ export class RdpDisplay {
43
+ constructor(container) {
44
+ this.container = container;
45
+ this.canvas = document.createElement('canvas');
46
+ this.canvas.tabIndex = 0;
47
+ this.canvas.style.display = 'block';
48
+ this.canvas.style.position = 'absolute';
49
+ this.canvas.style.outline = 'none';
50
+ this.canvas.style.imageRendering = 'auto';
51
+ this.canvas.style.boxShadow = 'none';
52
+ this.context = this.canvas.getContext('2d', { alpha: false });
53
+
54
+ // The canvas is always the whole remote desktop, and this element decides
55
+ // how much of it is on screen. A full-desktop session shows all of it; a
56
+ // RemoteApp session shows only the application's own window, because
57
+ // RemoteApp paints nothing around it.
58
+ this.viewportElement = document.createElement('div');
59
+ this.viewportElement.style.position = 'relative';
60
+ this.viewportElement.style.overflow = 'hidden';
61
+ this.viewportElement.style.margin = 'auto';
62
+ this.viewportElement.style.background = '#000';
63
+ this.viewportElement.style.boxShadow = '0 10px 30px rgba(0, 0, 0, 0.8)';
64
+ this.viewportElement.appendChild(this.canvas);
65
+
66
+ container.replaceChildren(this.viewportElement);
67
+
68
+ // The element that actually scrolls when the desktop is larger than the
69
+ // window. `container` grows with its contents, so it is the wrong thing to
70
+ // measure the available space against.
71
+ this.scrollHost = container.parentElement || container;
72
+
73
+ this.width = 0;
74
+ this.height = 0;
75
+ this.viewport = { x: 0, y: 0, width: 0, height: 0 };
76
+ this.scale = 1;
77
+ this.scaleViewport = true;
78
+ // A multiplier on top of the fitted scale. 1 shows the whole desktop.
79
+ this.zoom = 1;
80
+ // Once the user has pinched, their zoom is theirs to keep: rotating the
81
+ // phone should not silently throw it away.
82
+ this.userZoomed = false;
83
+ this.viewOnly = false;
84
+ this.client = null;
85
+ this.palette = null;
86
+ this.cursorCache = new Map();
87
+ this.heldKeys = new Set();
88
+ this.keyboardSynced = false;
89
+
90
+ // Turning the phone changes which axis is the tight one; applyScale picks
91
+ // the opening zoom up again unless the user has since chosen their own.
92
+ this.onWindowResize = () => this.applyScale();
93
+ window.addEventListener('resize', this.onWindowResize);
94
+
95
+ // The workspace also changes width without the window changing at all --
96
+ // the SSH panel docking beside it, for one -- and no `resize` is fired for
97
+ // that, so the desktop would keep the scale it had before the panel opened.
98
+ this.resizeObserver = typeof ResizeObserver === 'function'
99
+ ? new ResizeObserver(() => this.applyScale())
100
+ : null;
101
+ this.resizeObserver?.observe(this.scrollHost);
102
+ }
103
+
104
+ resize(width: number, height: number) {
105
+ this.width = width;
106
+ this.height = height;
107
+ this.canvas.width = width;
108
+ this.canvas.height = height;
109
+
110
+ this.context.fillStyle = '#000';
111
+ this.context.fillRect(0, 0, width, height);
112
+ this.setViewport({ x: 0, y: 0, width, height });
113
+ }
114
+
115
+ /**
116
+ * Choose the part of the desktop that is on screen. Everything else about
117
+ * the session -- painting, input coordinates, the remote pointer -- keeps
118
+ * working in desktop coordinates, so only the framing changes here.
119
+ */
120
+ setViewport({ x = 0, y = 0, width, height } = {}) {
121
+ if (!this.width || !this.height) return;
122
+
123
+ const left = Math.max(0, Math.min(this.width - 1, Math.floor(x)));
124
+ const top = Math.max(0, Math.min(this.height - 1, Math.floor(y)));
125
+ this.viewport = {
126
+ x: left,
127
+ y: top,
128
+ width: Math.max(1, Math.min(this.width - left, Math.floor(width || this.width))),
129
+ height: Math.max(1, Math.min(this.height - top, Math.floor(height || this.height))),
130
+ };
131
+
132
+ // The toolbar reads the resolution off the canvas, and a screenshot of a
133
+ // RemoteApp session should be the window rather than the desktop it sits on.
134
+ this.canvas.dataset.viewport = [
135
+ this.viewport.x, this.viewport.y, this.viewport.width, this.viewport.height,
136
+ ].join(',');
137
+ this.applyScale();
138
+ }
139
+
140
+ /** The space a fitted desktop has to fit into: the window, not the content. */
141
+ #available() {
142
+ const host = this.scrollHost;
143
+ return {
144
+ width: host.clientWidth || this.container.clientWidth || 1,
145
+ height: host.clientHeight || this.container.clientHeight || 1,
146
+ };
147
+ }
148
+
149
+ /** The scale at which the whole desktop is on screen, letterboxed. */
150
+ #fitScale(available = this.#available()) {
151
+ const fitted = Math.min(
152
+ available.width / this.viewport.width,
153
+ available.height / this.viewport.height
154
+ );
155
+ return Number.isFinite(fitted) && fitted > 0 ? fitted : 1;
156
+ }
157
+
158
+ /**
159
+ * The zoom to open a session at.
160
+ *
161
+ * On a laptop the fitted view is the right one: the whole desktop is on
162
+ * screen and readable, and that is where this stays. On a phone it is not --
163
+ * a 1024x768 desktop fitted to a 375pt-wide window lands at about a third of
164
+ * full size, a band of unreadable pixels across the middle of a tall black
165
+ * screen. When fitting would land under LEGIBLE_SCALE the desktop is scaled
166
+ * to fill the window instead: the short edge matches exactly and the long one
167
+ * is panned. Everything is still reachable, and a pinch still gets back to
168
+ * the whole desktop. Legible first and complete second is the right way round
169
+ * on a screen this size.
170
+ */
171
+ #defaultZoom() {
172
+ return 1;
173
+ }
174
+
175
+ applyScale() {
176
+ if (!this.width || !this.height) return;
177
+ const viewport = this.viewport;
178
+
179
+ // Measured once and shared, so the zoom and the scale it multiplies can
180
+ // never come from two different layouts. Turning the phone fires `resize`
181
+ // while the new size is still settling, and reading it twice there is how
182
+ // the desktop ends up fitted on one axis and filled on the other.
183
+ const available = this.#available();
184
+ const fitted = this.#fitScale(available);
185
+ if (!this.userZoomed) this.zoom = this.#defaultZoom();
186
+
187
+ const scale = (this.scaleViewport ? fitted : 1) * this.zoom;
188
+ this.scale = scale;
189
+
190
+ // Sized in exact fractions of a pixel rather than whole ones: rounding the
191
+ // two axes apart is what makes a scaled desktop very slightly the wrong
192
+ // shape, which is visible as soon as the scale factor is small -- a phone
193
+ // fitting a 1024x768 desktop into 375 points, for instance.
194
+ this.viewportElement.style.width = `${viewport.width * scale}px`;
195
+ this.viewportElement.style.height = `${viewport.height * scale}px`;
196
+ this.canvas.style.width = `${this.width * scale}px`;
197
+ this.canvas.style.height = `${this.height * scale}px`;
198
+ this.canvas.style.left = `${-viewport.x * scale}px`;
199
+ this.canvas.style.top = `${-viewport.y * scale}px`;
200
+ }
201
+
202
+ /**
203
+ * Zoom about a point, keeping whatever is under it in place. `focal` is in
204
+ * client coordinates -- the midpoint between two fingers, usually.
205
+ */
206
+ setZoom(next, focal = null) {
207
+ const clamped = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, next));
208
+ if (!Number.isFinite(clamped) || clamped === this.zoom) return;
209
+
210
+ const host = this.scrollHost;
211
+ const before = this.scale;
212
+ const bounds = host.getBoundingClientRect();
213
+ const anchorX = focal ? focal.x - bounds.left : bounds.width / 2;
214
+ const anchorY = focal ? focal.y - bounds.top : bounds.height / 2;
215
+ const contentX = host.scrollLeft + anchorX;
216
+ const contentY = host.scrollTop + anchorY;
217
+
218
+ this.zoom = clamped;
219
+ this.applyScale();
220
+
221
+ const ratio = before > 0 ? this.scale / before : 1;
222
+ host.scrollLeft = contentX * ratio - anchorX;
223
+ host.scrollTop = contentY * ratio - anchorY;
224
+ }
225
+
226
+ /** Move the visible window over the desktop. Returns what it actually used. */
227
+ panBy(dx, dy) {
228
+ const host = this.scrollHost;
229
+ const beforeX = host.scrollLeft;
230
+ const beforeY = host.scrollTop;
231
+ host.scrollLeft = beforeX - dx;
232
+ host.scrollTop = beforeY - dy;
233
+ return {
234
+ x: beforeX - host.scrollLeft,
235
+ y: beforeY - host.scrollTop,
236
+ };
237
+ }
238
+
239
+ /** True when the desktop is larger than the window on either axis. */
240
+ canPan() {
241
+ if (this.zoom <= 1.05) return false;
242
+ const host = this.scrollHost;
243
+ return host.scrollWidth > host.clientWidth + 2 || host.scrollHeight > host.clientHeight + 2;
244
+ }
245
+
246
+ setScaleViewport(enabled: boolean) {
247
+ this.scaleViewport = enabled;
248
+ if (!enabled) this.userZoomed = false;
249
+ this.applyScale();
250
+ }
251
+
252
+ /** Back to the opening view: whole desktop fitted on screen. */
253
+ resetZoom() {
254
+ this.userZoomed = false;
255
+ this.zoom = 1;
256
+ this.applyScale();
257
+ const host = this.scrollHost;
258
+ host.scrollLeft = 0;
259
+ host.scrollTop = 0;
260
+ }
261
+
262
+ drawRects(rects, palette) {
263
+ if (palette) this.palette = palette;
264
+
265
+ for (const rect of rects) {
266
+ if (rect.width === 0 || rect.height === 0) continue;
267
+ try {
268
+ const rgba = decodeBitmapRect(rect, this.palette);
269
+ const image = new ImageData(rgba, rect.width, rect.height);
270
+ this.context.putImageData(image, rect.left, rect.top);
271
+ } catch (error) {
272
+ // One malformed rectangle must not kill the session; the next full
273
+ // update repaints the area anyway.
274
+ console.warn('[RDP] Dropped an undecodable bitmap rectangle', {
275
+ geometry: `${rect.width}x${rect.height}+${rect.left}+${rect.top}`,
276
+ bitsPerPixel: rect.bitsPerPixel,
277
+ compressed: rect.compressed,
278
+ error: error instanceof Error ? error.message : String(error),
279
+ });
280
+ }
281
+ }
282
+ }
283
+
284
+ // --- cursor ---------------------------------------------------------------
285
+
286
+ /**
287
+ * Turn an RDP pointer bitmap into a CSS cursor. RDP stores both masks
288
+ * bottom-up with rows padded to an even number of bytes, and a set AND-mask
289
+ * bit means "leave this pixel alone", which becomes transparency here.
290
+ */
291
+ #cursorFromPointer(pointer) {
292
+ const { width, height, xorBpp, xorMask, andMask, hotSpotX, hotSpotY } = pointer;
293
+ if (!width || !height) return null;
294
+
295
+ const xorBytesPerRow = Math.ceil((width * xorBpp) / 8 / 2) * 2;
296
+ const andBytesPerRow = Math.ceil(width / 8 / 2) * 2;
297
+ const rgba = new Uint8ClampedArray(width * height * 4);
298
+
299
+ for (let y = 0; y < height; y++) {
300
+ const sourceRow = height - 1 - y; // bottom-up
301
+ for (let x = 0; x < width; x++) {
302
+ const andByte = andMask[sourceRow * andBytesPerRow + (x >> 3)];
303
+ const transparent = andByte !== undefined && (andByte & (0x80 >> (x & 7))) !== 0;
304
+
305
+ let r = 0;
306
+ let g = 0;
307
+ let b = 0;
308
+ let a = transparent ? 0 : 255;
309
+
310
+ if (xorBpp === 1) {
311
+ const bit = xorMask[sourceRow * xorBytesPerRow + (x >> 3)] & (0x80 >> (x & 7));
312
+ r = g = b = bit ? 255 : 0;
313
+ } else {
314
+ const bytesPerPixel = xorBpp / 8;
315
+ const offset = sourceRow * xorBytesPerRow + x * bytesPerPixel;
316
+ if (xorBpp === 16) {
317
+ const value = xorMask[offset] | (xorMask[offset + 1] << 8);
318
+ r = ((value >> 11) & 0x1f) * 255 / 31;
319
+ g = ((value >> 5) & 0x3f) * 255 / 63;
320
+ b = (value & 0x1f) * 255 / 31;
321
+ } else {
322
+ b = xorMask[offset] || 0;
323
+ g = xorMask[offset + 1] || 0;
324
+ r = xorMask[offset + 2] || 0;
325
+ if (xorBpp === 32 && xorMask[offset + 3] !== undefined && andMask.length === 0) {
326
+ a = xorMask[offset + 3];
327
+ }
328
+ }
329
+ }
330
+
331
+ const target = (y * width + x) * 4;
332
+ rgba[target] = r;
333
+ rgba[target + 1] = g;
334
+ rgba[target + 2] = b;
335
+ rgba[target + 3] = a;
336
+ }
337
+ }
338
+
339
+ const cursorCanvas = document.createElement('canvas');
340
+ cursorCanvas.width = width;
341
+ cursorCanvas.height = height;
342
+ cursorCanvas.getContext('2d').putImageData(new ImageData(rgba, width, height), 0, 0);
343
+
344
+ const hotX = Math.min(hotSpotX || 0, width - 1);
345
+ const hotY = Math.min(hotSpotY || 0, height - 1);
346
+ return `url(${cursorCanvas.toDataURL('image/png')}) ${hotX} ${hotY}, default`;
347
+ }
348
+
349
+ applyPointer(pointer) {
350
+ if (pointer.kind === 'system') {
351
+ this.canvas.style.cursor = pointer.hidden ? 'none' : 'default';
352
+ return;
353
+ }
354
+
355
+ if (pointer.kind === 'position') {
356
+ // Host-driven pointer warps cannot move the real mouse; ignore them and
357
+ // let the local pointer stay where the user put it.
358
+ return;
359
+ }
360
+
361
+ if (pointer.kind === 'cached') {
362
+ const cached = this.cursorCache.get(pointer.cacheIndex);
363
+ if (cached) this.canvas.style.cursor = cached;
364
+ return;
365
+ }
366
+
367
+ if (pointer.kind === 'bitmap') {
368
+ try {
369
+ const cursor = this.#cursorFromPointer(pointer);
370
+ if (!cursor) return;
371
+ this.cursorCache.set(pointer.cacheIndex, cursor);
372
+ this.canvas.style.cursor = cursor;
373
+ } catch (error) {
374
+ console.warn('[RDP] Could not build a cursor from the host pointer update', error);
375
+ }
376
+ }
377
+ }
378
+
379
+ // --- input ----------------------------------------------------------------
380
+
381
+ #toRemote(event) {
382
+ const bounds = this.canvas.getBoundingClientRect();
383
+ const scaleX = this.width / (bounds.width || 1);
384
+ const scaleY = this.height / (bounds.height || 1);
385
+ return {
386
+ x: Math.max(0, Math.min(this.width - 1, (event.clientX - bounds.left) * scaleX)),
387
+ y: Math.max(0, Math.min(this.height - 1, (event.clientY - bounds.top) * scaleY)),
388
+ };
389
+ }
390
+
391
+ #syncKeyboardOnce(event) {
392
+ if (this.keyboardSynced || !this.client) return;
393
+ this.keyboardSynced = true;
394
+
395
+ let flags = 0;
396
+ if (event.getModifierState?.('CapsLock')) flags |= TOGGLE_FLAG.CAPS_LOCK;
397
+ if (event.getModifierState?.('NumLock')) flags |= TOGGLE_FLAG.NUM_LOCK;
398
+ if (event.getModifierState?.('ScrollLock')) flags |= TOGGLE_FLAG.SCROLL_LOCK;
399
+ this.client.sendKeyboardSync(flags);
400
+ }
401
+
402
+ attachInput(client) {
403
+ this.client = client;
404
+ this.keyboardSynced = false;
405
+
406
+ const canSend = () => this.client && this.client.connected && !this.viewOnly;
407
+
408
+ let pendingMove = null;
409
+ let moveScheduled = false;
410
+ let pendingWheelDelta = 0;
411
+ let touchIsDown = false;
412
+ let lastTouchX = 0;
413
+ let lastTouchY = 0;
414
+ let lastTouchScrollY = 0;
415
+ let lastTouchScrollX = 0;
416
+ let gestureStartMid = { x: 0, y: 0 };
417
+ let gestureStartDistance = 0;
418
+ let lastPinchDistance = 0;
419
+ let pendingTouchWheelDelta = 0;
420
+ let touchMode = null;
421
+
422
+ const touchMidpoint = (touches) => ({
423
+ x: (touches[0].clientX + touches[1].clientX) / 2,
424
+ y: (touches[0].clientY + touches[1].clientY) / 2,
425
+ });
426
+
427
+ const touchDistance = (touches) => Math.hypot(
428
+ touches[0].clientX - touches[1].clientX,
429
+ touches[0].clientY - touches[1].clientY
430
+ );
431
+ const flushMove = () => {
432
+ moveScheduled = false;
433
+ if (pendingMove && canSend()) this.client.sendMouseMove(pendingMove.x, pendingMove.y);
434
+ pendingMove = null;
435
+ };
436
+
437
+ this.handlers = {
438
+ mousemove: (event) => {
439
+ if (!canSend()) return;
440
+ pendingMove = this.#toRemote(event);
441
+ if (!moveScheduled) {
442
+ moveScheduled = true;
443
+ requestAnimationFrame(flushMove);
444
+ }
445
+ },
446
+ mousedown: (event) => {
447
+ this.canvas.focus();
448
+ if (!canSend()) return;
449
+ event.preventDefault();
450
+ const { x, y } = this.#toRemote(event);
451
+ this.client.sendMouseButton(event.button, true, x, y);
452
+ },
453
+ mouseup: (event) => {
454
+ if (!canSend()) return;
455
+ event.preventDefault();
456
+ const { x, y } = this.#toRemote(event);
457
+ this.client.sendMouseButton(event.button, false, x, y);
458
+ },
459
+ contextmenu: (event) => event.preventDefault(),
460
+ wheel: (event) => {
461
+ if (!canSend()) return;
462
+ event.preventDefault();
463
+
464
+ let delta = event.deltaY;
465
+ if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) delta *= WHEEL_LINE_PIXELS;
466
+ if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
467
+ delta *= Math.max(1, this.canvas.clientHeight || this.height);
468
+ }
469
+ if (!delta) return;
470
+
471
+ // Do not let a partial gesture in one direction accelerate the next
472
+ // gesture in the opposite direction.
473
+ if (pendingWheelDelta && Math.sign(pendingWheelDelta) !== Math.sign(delta)) {
474
+ pendingWheelDelta = 0;
475
+ }
476
+ pendingWheelDelta += delta;
477
+ if (Math.abs(pendingWheelDelta) < WHEEL_STEP_PIXELS) return;
478
+
479
+ const direction = Math.sign(pendingWheelDelta);
480
+ pendingWheelDelta -= direction * WHEEL_STEP_PIXELS;
481
+ const { x, y } = this.#toRemote(event);
482
+ this.client.sendWheel(direction, x, y);
483
+ },
484
+ touchstart: (event) => {
485
+ this.canvas.focus();
486
+ if (!canSend()) return;
487
+ event.preventDefault();
488
+
489
+ if (event.touches.length === 1) {
490
+ touchMode = 'tap';
491
+ const touch = event.touches[0];
492
+ lastTouchX = touch.clientX;
493
+ lastTouchY = touch.clientY;
494
+ const { x, y } = this.#toRemote(touch);
495
+ this.client.sendMouseMove(x, y);
496
+ this.client.sendMouseButton(0, true, x, y);
497
+ touchIsDown = true;
498
+ } else if (event.touches.length === 2) {
499
+ touchMode = 'undecided';
500
+ if (touchIsDown) {
501
+ const { x, y } = this.#toRemote({ clientX: lastTouchX, clientY: lastTouchY });
502
+ this.client.sendMouseButton(0, false, x, y);
503
+ touchIsDown = false;
504
+ }
505
+ const mid = touchMidpoint(event.touches);
506
+ const dist = touchDistance(event.touches);
507
+ gestureStartMid = { x: mid.x, y: mid.y };
508
+ gestureStartDistance = dist;
509
+ lastTouchScrollY = mid.y;
510
+ lastTouchScrollX = mid.x;
511
+ lastPinchDistance = dist;
512
+ pendingTouchWheelDelta = 0;
513
+ }
514
+ },
515
+ touchmove: (event) => {
516
+ if (!canSend()) return;
517
+ event.preventDefault();
518
+
519
+ if (event.touches.length === 1 && touchMode === 'tap') {
520
+ const touch = event.touches[0];
521
+ lastTouchX = touch.clientX;
522
+ lastTouchY = touch.clientY;
523
+ const { x, y } = this.#toRemote(touch);
524
+ this.client.sendMouseMove(x, y);
525
+ } else if (event.touches.length === 2) {
526
+ const mid = touchMidpoint(event.touches);
527
+ const currX = mid.x;
528
+ const currY = mid.y;
529
+ const distance = touchDistance(event.touches);
530
+ const deltaY = lastTouchScrollY - currY;
531
+ const deltaX = lastTouchScrollX - currX;
532
+ lastTouchScrollY = currY;
533
+ lastTouchScrollX = currX;
534
+
535
+ const totalMove = Math.hypot(currX - gestureStartMid.x, currY - gestureStartMid.y);
536
+ const pinchDelta = Math.abs(distance - gestureStartDistance);
537
+ const pinchRatio = gestureStartDistance > 0 ? distance / gestureStartDistance : 1;
538
+
539
+ if (touchMode === 'undecided' || touchMode === 'gesture') {
540
+ // Disambiguate between pinch-to-zoom and two-finger scroll
541
+ if (pinchDelta > 20 && Math.abs(pinchRatio - 1) > 0.15 && pinchDelta > totalMove * 0.8) {
542
+ touchMode = 'pinch';
543
+ } else if (totalMove > 8) {
544
+ touchMode = 'scroll';
545
+ }
546
+ }
547
+
548
+ if (touchMode === 'pinch') {
549
+ if (lastPinchDistance > 0 && Math.abs(distance - lastPinchDistance) > 1) {
550
+ this.userZoomed = true;
551
+ this.setZoom(this.zoom * (distance / lastPinchDistance), { x: currX, y: currY });
552
+ }
553
+ lastPinchDistance = distance;
554
+ } else if (touchMode === 'scroll') {
555
+ lastPinchDistance = distance;
556
+
557
+ // A zoomed-in desktop pans; a fitted desktop turns the remote mouse wheel.
558
+ if (this.canPan()) {
559
+ this.panBy(deltaX * -1, deltaY * -1);
560
+ pendingTouchWheelDelta = 0;
561
+ return;
562
+ }
563
+
564
+ if (deltaY && pendingTouchWheelDelta
565
+ && Math.sign(pendingTouchWheelDelta) !== Math.sign(deltaY)) {
566
+ pendingTouchWheelDelta = 0;
567
+ }
568
+ pendingTouchWheelDelta += deltaY;
569
+
570
+ while (Math.abs(pendingTouchWheelDelta) >= TOUCH_SCROLL_STEP) {
571
+ const direction = Math.sign(pendingTouchWheelDelta);
572
+ pendingTouchWheelDelta -= direction * TOUCH_SCROLL_STEP;
573
+ const { x, y } = this.#toRemote({ clientX: currX, clientY: currY });
574
+ this.client.sendWheel(direction, x, y);
575
+ }
576
+ }
577
+ }
578
+ },
579
+ touchend: (event) => {
580
+ if (!canSend()) return;
581
+ event.preventDefault();
582
+
583
+ if (event.touches.length === 0) {
584
+ if (touchIsDown) {
585
+ const { x, y } = this.#toRemote({ clientX: lastTouchX, clientY: lastTouchY });
586
+ this.client.sendMouseButton(0, false, x, y);
587
+ touchIsDown = false;
588
+ }
589
+ if (touchMode === 'pinch' && this.zoom <= 1.05) {
590
+ this.resetZoom();
591
+ }
592
+ touchMode = null;
593
+ pendingTouchWheelDelta = 0;
594
+ lastPinchDistance = 0;
595
+ } else if (event.touches.length === 1) {
596
+ // A finger lifted mid-gesture leaves one behind that was never a tap;
597
+ // letting it fall through would press the mouse where it happens to
598
+ // rest. The gesture ends here and the stray finger is ignored.
599
+ if (touchMode === 'gesture' || touchMode === 'pinch' || touchMode === 'scroll' || touchMode === 'undecided') {
600
+ if (touchMode === 'pinch' && this.zoom <= 1.05) {
601
+ this.resetZoom();
602
+ }
603
+ touchMode = null;
604
+ lastPinchDistance = 0;
605
+ pendingTouchWheelDelta = 0;
606
+ }
607
+ }
608
+ },
609
+ touchcancel: (event) => {
610
+ if (!canSend()) return;
611
+ if (touchIsDown) {
612
+ const { x, y } = this.#toRemote({ clientX: lastTouchX, clientY: lastTouchY });
613
+ this.client.sendMouseButton(0, false, x, y);
614
+ touchIsDown = false;
615
+ }
616
+ if (touchMode === 'pinch' && this.zoom <= 1.05) {
617
+ this.resetZoom();
618
+ }
619
+ touchMode = null;
620
+ pendingTouchWheelDelta = 0;
621
+ lastPinchDistance = 0;
622
+ },
623
+ keydown: (event) => {
624
+ if (!canSend()) return;
625
+ this.#syncKeyboardOnce(event);
626
+
627
+ // Paste is the browser's to deliver: preventing the default here would
628
+ // stop the paste event that carries the text the host is about to ask
629
+ // for. The keystroke is sent from the paste handler instead.
630
+ if (this.#isPasteShortcut(event)) return;
631
+
632
+ const code = this.#translateCode(event.code);
633
+ if (!this.client.sendKeyByCode(code, true)) return;
634
+ event.preventDefault();
635
+
636
+ // macOS withholds keyup while Command is held, which would leave the
637
+ // key stuck down on the host. Releasing it at once is the only way to
638
+ // keep the shortcut from repeating forever.
639
+ if (IS_MAC && event.metaKey && !COMMAND_TO_CONTROL[event.code]) {
640
+ this.client.sendKeyByCode(code, false);
641
+ return;
642
+ }
643
+
644
+ this.heldKeys.add(code);
645
+ },
646
+ keyup: (event) => {
647
+ if (!canSend()) return;
648
+ if (this.#isPasteShortcut(event)) return;
649
+
650
+ const code = this.#translateCode(event.code);
651
+ if (this.client.sendKeyByCode(code, false)) {
652
+ this.heldKeys.delete(code);
653
+ event.preventDefault();
654
+ }
655
+ },
656
+ paste: (event) => {
657
+ if (!canSend()) return;
658
+
659
+ /**
660
+ * Only when the screen is what is being pasted into.
661
+ *
662
+ * This listener is on the document because a canvas cannot receive a
663
+ * paste event of its own -- which means *every* paste in the page
664
+ * arrives here, including one typed into the assistant's message box or
665
+ * a password field. Without this guard the text went two places at
666
+ * once: into the box the user was looking at, and into whatever window
667
+ * happened to be open on the far machine.
668
+ *
669
+ * Focus is the test. The remote screen holds it when the remote screen
670
+ * is what you are working in, and nothing else does at the same time.
671
+ * (The terminal never had this problem because xterm stops the event
672
+ * from propagating; a text field cannot be relied on to do that.)
673
+ */
674
+ const target = event.target;
675
+ const onTheScreen = target instanceof Node && this.container.contains(target);
676
+ if (document.activeElement !== this.canvas && !onTheScreen) return;
677
+
678
+ event.preventDefault();
679
+ const text = event.clipboardData?.getData('text/plain') || '';
680
+ if (text) this.client.pasteToHost(text);
681
+ },
682
+ blur: () => this.releaseAllKeys(),
683
+ };
684
+
685
+ this.canvas.addEventListener('mousemove', this.handlers.mousemove);
686
+ this.canvas.addEventListener('mousedown', this.handlers.mousedown);
687
+ this.canvas.addEventListener('mouseup', this.handlers.mouseup);
688
+ this.canvas.addEventListener('contextmenu', this.handlers.contextmenu);
689
+ this.canvas.addEventListener('wheel', this.handlers.wheel, { passive: false });
690
+ this.canvas.addEventListener('touchstart', this.handlers.touchstart, { passive: false });
691
+ this.canvas.addEventListener('touchmove', this.handlers.touchmove, { passive: false });
692
+ this.canvas.addEventListener('touchend', this.handlers.touchend, { passive: false });
693
+ this.canvas.addEventListener('touchcancel', this.handlers.touchcancel, { passive: false });
694
+ this.canvas.addEventListener('keydown', this.handlers.keydown);
695
+ this.canvas.addEventListener('keyup', this.handlers.keyup);
696
+ this.canvas.addEventListener('blur', this.handlers.blur);
697
+ // A canvas is not editable, so the paste event lands on the document. The
698
+ // handler checks that the canvas has focus before treating it as its own.
699
+ document.addEventListener('paste', this.handlers.paste);
700
+ }
701
+
702
+ /** Command on a Mac stands in for Control everywhere the host is concerned. */
703
+ #translateCode(code: number) {
704
+ return IS_MAC ? COMMAND_TO_CONTROL[code] || code : code;
705
+ }
706
+
707
+ #isPasteShortcut(event) {
708
+ if (event.code !== 'KeyV') return false;
709
+ return IS_MAC ? event.metaKey : event.ctrlKey;
710
+ }
711
+
712
+ /** A key held while focus moves away would otherwise stay down on the host. */
713
+ releaseAllKeys() {
714
+ if (!this.client) return;
715
+ for (const code of this.heldKeys) this.client.sendKeyByCode(code, false);
716
+ this.heldKeys.clear();
717
+ }
718
+
719
+ focus() {
720
+ this.canvas.focus();
721
+ }
722
+
723
+ blur() {
724
+ this.canvas.blur();
725
+ }
726
+
727
+ destroy() {
728
+ this.releaseAllKeys();
729
+ window.removeEventListener('resize', this.onWindowResize);
730
+ this.resizeObserver?.disconnect();
731
+
732
+ if (this.handlers) {
733
+ this.canvas.removeEventListener('mousemove', this.handlers.mousemove);
734
+ this.canvas.removeEventListener('mousedown', this.handlers.mousedown);
735
+ this.canvas.removeEventListener('mouseup', this.handlers.mouseup);
736
+ this.canvas.removeEventListener('contextmenu', this.handlers.contextmenu);
737
+ this.canvas.removeEventListener('wheel', this.handlers.wheel);
738
+ this.canvas.removeEventListener('touchstart', this.handlers.touchstart);
739
+ this.canvas.removeEventListener('touchmove', this.handlers.touchmove);
740
+ this.canvas.removeEventListener('touchend', this.handlers.touchend);
741
+ this.canvas.removeEventListener('touchcancel', this.handlers.touchcancel);
742
+ this.canvas.removeEventListener('keydown', this.handlers.keydown);
743
+ this.canvas.removeEventListener('keyup', this.handlers.keyup);
744
+ this.canvas.removeEventListener('blur', this.handlers.blur);
745
+ document.removeEventListener('paste', this.handlers.paste);
746
+ }
747
+
748
+ this.client = null;
749
+ }
750
+ }