跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

remote-input.js

687 行 · 27.3 KB历史下载
1import { getKeycode, getKeysym } from "../.generated/novnc/core/input/util.js";
2import { api, writeClipboard, nativeAvailable, native } from "./api";
3import { caretPollDelay, caretPollFast, caretFreshFor } from "./caret-poll.mjs";
4import {
5 readClipboardContent,
6 transferFiles,
7 hasFiles,
8 imagePayload,
9} from "./image-transfer";
10
11// A user gesture starts every host clipboard access. Fences and serialization
12// in the shared RFB patch ensure that repeated pastes are processed in order.
13export function installRemoteInput(
14 transport,
15 container,
16 { mode, guestPlatform = () => "linux", systemClipboard = () => true, onStatus, onFallback, isActive,
17 insertText, insertComposition, caretRect, surface, inputLabel = "Cage 网页输入", tabId: getTargetId = () => "", pasteContent, preparePaste, setCopyContext, copyText },
18) {
19 const listeners = [],
20 handled = new Set(),
21 physical = new Set(),
22 remote = new Map();
23 let lastText = "",
24 copyRequested = false,
25 copyContext = "",
26 copyRevision,
27 copyTimer,
28 pending = 0,
29 composing = false,
30 compositionTarget = "",
31 compositionSession = "",
32 compositionSequence = 0,
33 caretState,
34 caretTimer,
35 caretWait = caretPollFast,
36 lastAction = Date.now(),
37 caretPending = false,
38 nativeOwner = "",
39 nativeTarget = "",
40 nativeOwned = false,
41 nativeFailed = false,
42 disposed = false;
43 const target = document.createElement("textarea");
44 target.setAttribute("aria-label", inputLabel);
45 target.setAttribute("autocomplete", "off");
46 target.setAttribute("autocapitalize", "off");
47 target.setAttribute("wrap", "off");
48 target.spellcheck = false;
49 target.className = "remote-text-input";
50 target.style.cssText = "position:fixed;left:0;top:0";
51 container.append(target);
52 transport.setKeyboardTarget(target);
53 const on = (object, type, fn, options) => {
54 object.addEventListener(type, fn, options);
55 listeners.push(() => object.removeEventListener(type, fn, options));
56 };
57 const focused = () =>
58 isActive() &&
59 (nativeOwned || container.contains(document.activeElement) ||
60 document.activeElement === target);
61 const macGuest = () => ["darwin", "macos"].includes(guestPlatform());
62 const sharedClipboard = () => systemClipboard() && window.cageSharedClipboardActive;
63 const shortcutModifier = () => {
64 if (macGuest()) return physical.has("MetaRight") ? [0xffec, "MetaRight"] : [0xffeb, "MetaLeft"];
65 return physical.has("ControlRight") ? [0xffe4, "ControlRight"] : [0xffe3, "ControlLeft"];
66 };
67 const cancelCopy = () => {
68 copyContext = "";
69 copyRevision = undefined;
70 copyRequested = false;
71 clearTimeout(copyTimer);
72 };
73 const prepareCopy = () => {
74 if (!isActive() || disposed) return;
75 // The shared clipboard delivers guest copies independently of RFB input.
76 if (sharedClipboard()) {
77 if (copyContext) cancelCopy();
78 return;
79 }
80 copyContext = crypto.randomUUID().replaceAll("-", "");
81 copyRevision = nativeAvailable() ? native("clipboardRevision").catch(() => undefined) : Promise.resolve(undefined);
82 const context = copyContext;
83 void setCopyContext?.(context, () => !disposed && isActive() && context === copyContext).catch(() => {
84 if (copyContext === context) cancelCopy();
85 });
86 };
87 const deactivateNative = () => {
88 const owner = nativeOwner;
89 nativeOwned = false;
90 nativeOwner = "";
91 nativeTarget = "";
92 if (owner) void native("remoteInput", { operation: "deactivate", owner }).catch(() => {});
93 };
94 const updateNative = (rect) => {
95 if (nativeFailed || !window.cageNativeIMEAvailable || !nativeAvailable() || !focused()) return;
96 if (!nativeOwned && composing) return;
97 const operation = nativeOwned ? "caret" : "activate";
98 if (!nativeOwned) { nativeOwner = crypto.randomUUID(); nativeTarget = getTargetId(); nativeOwned = true; }
99 const owner = nativeOwner;
100 void native("remoteInput", { operation, owner, ...rect }).then((accepted) => {
101 if (owner !== nativeOwner) return;
102 if (!accepted || disposed) {
103 deactivateNative();
104 nativeFailed = !accepted;
105 }
106 }).catch(() => { if (owner === nativeOwner) { deactivateNative(); nativeFailed = true; } });
107 };
108 const position = (x, y) => {
109 target.style.left = `${Math.max(0, Math.min(x, window.innerWidth - 1))}px`;
110 target.style.top = `${Math.max(0, Math.min(y, window.innerHeight - 24))}px`;
111 };
112 const syncCaret = async () => {
113 if (!caretRect || caretPending || disposed || !isActive()) return;
114 caretPending = true;
115 const id = getTargetId();
116 if (nativeOwned && nativeTarget !== id) deactivateNative();
117 try {
118 const value = await caretRect(compositionSession);
119 if (disposed || !isActive() || id !== getTargetId()) return;
120 caretState = value?.available ? { ...value, target: id, time: Date.now() } : null;
121 if (!value?.available) { deactivateNative(); return; }
122 if (!value.rect || value.rect[3] <= 0) return;
123 const canvas = surface?.() || container.querySelector("canvas");
124 const width = value.width || canvas?.width, imageHeight = value.height || canvas?.height;
125 if (!width || !imageHeight) return;
126 const bounds = canvas.getBoundingClientRect();
127 const height = Math.max(1, value.rect[3] / imageHeight * bounds.height);
128 target.style.height = `${height}px`;
129 target.style.lineHeight = `${height}px`;
130 const x = bounds.left + (value.rect[0] / width) * bounds.width;
131 const y = bounds.top + (value.rect[1] / imageHeight) * bounds.height;
132 position(x, y);
133 updateNative({ x, y, height });
134 } catch {} finally { caretPending = false; }
135 };
136 const pollCaret = async () => {
137 if (focused()) await syncCaret();
138 if (disposed) return;
139 caretWait = caretPollDelay(Date.now() - lastAction);
140 caretTimer = setTimeout(pollCaret, caretWait);
141 };
142 if (caretRect) caretTimer = setTimeout(pollCaret, 0);
143 const acted = () => {
144 lastAction = Date.now();
145 // A slow wait scheduled while the viewer was quiet must not delay the
146 // readings that follow their input.
147 if (!caretRect || disposed || caretWait <= caretPollFast) return;
148 clearTimeout(caretTimer);
149 caretWait = caretPollFast;
150 caretTimer = setTimeout(pollCaret, caretWait);
151 };
152 const bounds = container.getBoundingClientRect();
153 position(bounds.left + 12, bounds.top + 12);
154 on(
155 container,
156 "pointerdown",
157 (event) => {
158 acted();
159 // Cancel before noVNC queues a click into another remote field.
160 if (composing) {
161 if (compositionSession) queueComposition({ mode: "cancel" });
162 resetComposition();
163 const owner = nativeOwner;
164 if (owner) void native("remoteInput", { operation: "cancel", owner }).catch(() => {});
165 target.blur();
166 }
167 position(event.clientX, event.clientY);
168 if (event.isTrusted && event.button === 0) prepareCopy();
169 },
170 true,
171 );
172 const commit = (text) => {
173 if (disposed || !isActive() || !text) return;
174 // X0tigervnc cannot map arbitrary Unicode to its finite X11 keycode pool.
175 // The browser inserts committed text directly, without clipboard mutation.
176 insertText(text).catch(() => {
177 if (!disposed) onStatus("文字输入未完成,请重新连接画面后重试");
178 });
179 };
180 const queueComposition = (value) => {
181 const targetId = compositionTarget;
182 if (!insertComposition || !compositionSession || !targetId || disposed ||
183 (!isActive() && value.mode !== "cancel")) return;
184 // Reserve the shared RFB input queue in this event handler. Deferring this
185 // call to another promise would let the next Enter overtake the commit.
186 insertComposition(targetId, { session: compositionSession, sequence: compositionSequence++, ...value }).catch((error) => {
187 if (!disposed && value.mode !== "cancel")
188 say(error.message || "输入法组合文字未能同步");
189 });
190 };
191 const resetComposition = () => {
192 composing = false;
193 compositionTarget = "";
194 compositionSession = "";
195 target.value = "";
196 };
197 const startComposition = () => {
198 acted();
199 composing = true;
200 compositionTarget = getTargetId();
201 if (insertComposition && caretState?.context && caretState.target === compositionTarget &&
202 Date.now() - caretState.time < caretFreshFor) {
203 compositionSession = crypto.randomUUID().replaceAll("-", "");
204 compositionSequence = 0;
205 queueComposition({ mode: "begin", context: caretState.context });
206 }
207 void syncCaret();
208 };
209 on(target, "compositionstart", startComposition);
210 on(target, "compositionupdate", () => {
211 void syncCaret();
212 });
213 const endComposition = (text) => {
214 if (composing) {
215 if (compositionSession) queueComposition({ mode: "commit", text, selectionStart: 0, selectionEnd: 0 });
216 else if (compositionTarget === getTargetId()) commit(text);
217 }
218 resetComposition();
219 void syncCaret();
220 };
221 on(target, "compositionend", (event) => endComposition(event.data || ""));
222 on(target, "input", (event) => {
223 if (document.activeElement !== target) {
224 if (!composing) target.value = "";
225 return;
226 }
227 if (composing || event.isComposing) {
228 if (compositionSession && ["insertCompositionText", "insertFromComposition"].includes(event.inputType)) {
229 queueComposition({
230 mode: "update",
231 text: target.value,
232 selectionStart: target.selectionStart ?? target.value.length,
233 selectionEnd: target.selectionEnd ?? target.value.length,
234 });
235 }
236 return;
237 }
238 // WebKit may deliver the final input after compositionend. That text has
239 // already been sent. Input without composition covers emoji and dictation.
240 if (
241 !["insertFromComposition", "insertCompositionText"].includes(
242 event.inputType,
243 )
244 )
245 commit(target.value);
246 target.value = "";
247 });
248 on(target, "blur", () => {
249 if (nativeOwned) return;
250 if (composing && compositionSession) queueComposition({ mode: "cancel", text: "", selectionStart: 0, selectionEnd: 0 });
251 resetComposition();
252 });
253 on(document, "focusin", (event) => {
254 if (!container.contains(event.target)) cancelCopy();
255 if (nativeOwned && !container.contains(event.target)) deactivateNative();
256 });
257 on(document, "pointerdown", (event) => {
258 if (!container.contains(event.target)) cancelCopy();
259 }, true);
260 on(document, "visibilitychange", () => {
261 if (document.visibilityState === "hidden") cancelCopy();
262 });
263 on(window, "cage-native-input", (event) => {
264 const value = event.detail;
265 if (disposed || !value || value.owner !== nativeOwner) return;
266 if (value.kind === "deactivated") {
267 nativeOwned = false;
268 nativeOwner = "";
269 if (composing && compositionSession) queueComposition({ mode: "cancel" });
270 resetComposition();
271 return;
272 }
273 if (!isActive() || nativeTarget !== getTargetId()) { deactivateNative(); return; }
274 if (value.kind === "compositionstart") startComposition();
275 else if (value.kind === "compositionupdate" && composing) {
276 queueComposition({ mode: "update", text: value.text, selectionStart: value.selectionStart, selectionEnd: value.selectionEnd });
277 } else if (value.kind === "compositionend") endComposition(value.text || "");
278 else if (value.kind === "input") commit(value.text);
279 else if (["keydown", "keyup"].includes(value.kind)) {
280 const key = new KeyboardEvent(value.kind, { ...value, bubbles: true, cancelable: true });
281 key.cageNativeTextKey = value.textKey;
282 key.cageNativeInput = true;
283 target.dispatchEvent(key);
284 }
285 });
286 on(container, "pointerup", () => {
287 acted();
288 setTimeout(() => void syncCaret(), 50);
289 });
290 // Scrolling moves the caret without moving focus.
291 on(container, "wheel", acted, { capture: true, passive: true });
292 const say = (text) => {
293 if (!disposed) onStatus(text);
294 };
295 const shortcutKeys = (key, shift = false) => {
296 const modifier = shortcutModifier();
297 const keys = [[...modifier, true]];
298 if (shift) keys.push([0xffe1, "ShiftLeft", true]);
299 keys.push([key.charCodeAt(0), "Key" + key.toUpperCase(), true], [key.charCodeAt(0), "Key" + key.toUpperCase(), false]);
300 if (shift && !physical.has("ShiftLeft")) keys.push([0xffe1, "ShiftLeft", false]);
301 if (!physical.has(modifier[1])) keys.push([...modifier, false]);
302 return keys;
303 };
304 const chord = (key, shift = false) => shortcutKeys(key, shift).forEach(value => transport.sendKey(...value));
305 const receiveCopy = async ({ id, text, clipboard, context, document: sourceDocument, error }) => {
306 if (sharedClipboard()) return;
307 const valid = () => !disposed && Boolean(copyContext) && context === copyContext && id === getTargetId() && focused() &&
308 document.visibilityState !== "hidden" && document.hasFocus();
309 if (!valid()) return;
310 if (error) { copyRequested = false; clearTimeout(copyTimer); say("复制未完成,请重新选择内容后重试。"); return; }
311 const revision = copyRevision;
312 let content = { text };
313 try {
314 const expected = await revision;
315 if (!valid()) return;
316 if (clipboard) {
317 const limit = clipboard.mime === "image/png" ? 20 * 1024 * 1024 : 2 * 1024 * 1024;
318 if (!["text/plain", "image/png"].includes(clipboard.mime) || !Number.isInteger(clipboard.size) || clipboard.size < 0 || clipboard.size > limit) return;
319 content = await api("/browser/clipboard", { id: clipboard.id, tab: id, context, document: sourceDocument });
320 if (!valid()) return;
321 }
322 if (typeof content.text === "string") {
323 if (new TextEncoder().encode(content.text).length > 2 * 1024 * 1024) return;
324 lastText = content.text;
325 } else if (typeof content.png !== "string" || content.png.length > 28 * 1024 * 1024) return;
326 copyRequested = false;
327 clearTimeout(copyTimer);
328 if (nativeAvailable()) {
329 if (typeof expected !== "number") throw new Error("无法确认本机剪贴板版本,请重新复制。");
330 const result = await native("clipboardSyncWrite", { ...content, revision: expected });
331 if (result?.superseded) { if (valid()) say("本机剪贴板已更新,请重新复制客机内容。"); return; }
332 } else if (typeof content.png === "string") {
333 const bytes = Uint8Array.from(atob(content.png), character => character.charCodeAt(0));
334 if (bytes.length > 20 * 1024 * 1024) return;
335 await navigator.clipboard.write([new ClipboardItem({ "image/png": new Blob([bytes], { type: "image/png" }) })]);
336 } else {
337 await writeClipboard(content.text);
338 }
339 if (valid()) say("已复制到本机");
340 } catch (error) {
341 if (!valid()) return;
342 if (typeof content.text === "string") onFallback(content.text, "请在这里复制到本机。");
343 else say(error.name === "NotAllowedError" ? "浏览器未允许写入图片剪贴板,请允许剪贴板访问后重试。" : error.message || "复制内容读取失败,请重试。");
344 }
345 };
346 const waitForCopy = () => {
347 if (!copyRequested) return;
348 clearTimeout(copyTimer);
349 copyTimer = setTimeout(() => {
350 copyRequested = false;
351 onFallback(lastText, "未收到新的选中文本,可在这里复制 Cage 剪贴板。");
352 }, 1600);
353 };
354 const copy = (key = "c") => {
355 if (disposed || !isActive()) return;
356 copyRequested = true;
357 say("正在复制所选文本…");
358 clearTimeout(copyTimer);
359 if (sharedClipboard()) { chord(key); copyRequested = false; return; }
360 prepareCopy();
361 if (copyText) {
362 const context = copyContext, id = getTargetId();
363 const valid = () => !disposed && isActive() && context === copyContext && id === getTargetId() &&
364 document.visibilityState !== "hidden" && document.hasFocus();
365 return transport.runKeyAction(async sendKey => {
366 const before = await caretRect?.();
367 const sendCopy = async () => {
368 if (!valid()) throw new Error("复制窗口已变化,请重新选择文本。");
369 for (const value of shortcutKeys(key)) await sendKey(...value);
370 };
371 const content = await copyText(sendCopy, valid, { id, context, key });
372 if (content === undefined) { await sendCopy(); waitForCopy(); return; }
373 const after = await caretRect?.();
374 if (before?.available && (!after?.available || before.context !== after.context)) throw new Error("复制位置已变化,请重新选择文本。");
375 if (valid()) await receiveCopy({ ...content, id, context });
376 }).catch(error => { if (valid()) say(error.message || "未收到新的选中文本,请重新选择后复制。"); });
377 }
378 chord(key);
379 waitForCopy();
380 };
381 const paste = (text) => {
382 if (disposed) return;
383 pending++;
384 say("正在粘贴…");
385 transport.focus();
386 transport.pasteText(text).then(
387 () => {
388 pending--;
389 say(pending ? "正在粘贴…" : "已粘贴");
390 },
391 () => {
392 pending--;
393 say("粘贴连接未就绪,请重新连接画面后重试");
394 },
395 );
396 };
397 const receive = (content, preparation = preparePaste?.()) => {
398 if (disposed || !isActive()) { preparation?.dispose(); return; }
399 pending++;
400 say("正在传递剪贴板内容…");
401 transport.focus();
402 return pasteContent(content, preparation).then(
403 () => {
404 pending--;
405 say(pending ? "正在粘贴…" : "已传递到当前输入位置");
406 },
407 (error) => {
408 pending--;
409 if (error.name === "NotAllowedError" && !disposed) {
410 onFallback(
411 "",
412 "浏览器未允许读取剪贴板。图片可直接拖入画面;文本可在这里粘贴。",
413 );
414 return;
415 }
416 say(error.message || "图片或文本未能传入,请重新连接后重试");
417 },
418 ).finally(() => preparation?.dispose());
419 };
420 const readAndPaste = () => {
421 if (disposed || !isActive()) return;
422 if (sharedClipboard()) {
423 const id = getTargetId();
424 say("正在粘贴…");
425 return transport.runKeyAction(async sendKey => {
426 const before = await caretRect?.();
427 await window.cageSyncClipboard();
428 const after = await caretRect?.();
429 if (disposed || !isActive() || id !== getTargetId() ||
430 (before?.available && (!after?.available || before.context !== after.context))) {
431 throw new Error("粘贴位置已切换,请回到原输入位置重试");
432 }
433 for (const key of shortcutKeys("v")) await sendKey(...key);
434 say("已粘贴");
435 }).catch(error => say(error.message || "剪贴板尚未同步,请重新复制后重试"));
436 }
437 const preparation = preparePaste?.();
438 return receive(readClipboardContent(), preparation);
439 };
440 on(transport.events, "clipboard", async (event) => {
441 lastText = event.detail.text;
442 if (sharedClipboard()) {
443 copyRequested = false;
444 clearTimeout(copyTimer);
445 return;
446 }
447 if (copyRequested) await receiveCopy({ id: getTargetId(), text: lastText, context: copyContext });
448 });
449 const release = () => {
450 cancelCopy();
451 for (const [code, keysym] of remote) transport.sendKey(keysym, code, false);
452 remote.clear();
453 physical.clear();
454 handled.clear();
455 };
456 on(window, "blur", release);
457 on(
458 document,
459 "keydown",
460 (event) => {
461 if (!focused()) return;
462 acted();
463 if ((event.isTrusted || event.cageNativeInput) && (!copyContext || ["Enter", " ", "Tab"].includes(event.key) ||
464 event.ctrlKey || event.metaKey || event.altKey)) prepareCopy();
465 if (
466 composing ||
467 event.isComposing ||
468 event.keyCode === 229 ||
469 ["Process", "Dead"].includes(event.key)
470 ) {
471 // Leave composition keys to the host IME. The guest receives the
472 // composition text through the authenticated browser IME endpoint.
473 event.stopImmediatePropagation();
474 return;
475 }
476 const code = getKeycode(event),
477 mapping = mode() === "mac" && !macGuest(),
478 malformedCommandLetter =
479 event.metaKey &&
480 /^Key[A-Z]$/.test(code) &&
481 !/^[a-z]$/i.test(event.key),
482 key = malformedCommandLetter
483 ? code[3].toLowerCase()
484 : event.key.toLowerCase();
485 if (["Shift", "Control", "Alt", "Meta"].includes(event.key)) physical.add(code);
486 if (event.key === "Shift") {
487 const sym = getKeysym(event);
488 transport.sendKey(sym, code, true);
489 remote.set(code, sym);
490 event.preventDefault();
491 event.stopImmediatePropagation();
492 return;
493 }
494 if (event.key === "Enter" && event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey) {
495 // Native IME focus can change after Shift was pressed. RFB carries
496 // modifier key events, not the Enter event's shiftKey flag.
497 const shift = physical.has("ShiftRight") ? [0xffe2, "ShiftRight"] : [0xffe1, "ShiftLeft"];
498 const sym = getKeysym(event);
499 if (!remote.has(shift[1])) transport.sendKey(...shift, true);
500 transport.sendKey(sym, code, true);
501 transport.sendKey(sym, code, false);
502 if (physical.has(shift[1])) remote.set(shift[1], shift[0]);
503 else transport.sendKey(...shift, false);
504 handled.add(code);
505 event.preventDefault();
506 event.stopImmediatePropagation();
507 return;
508 }
509 if (
510 mapping &&
511 event.metaKey &&
512 ["Shift", "Control", "Alt"].includes(event.key)
513 ) {
514 const sym = getKeysym(event);
515 transport.sendKey(sym, code, true);
516 remote.set(code, sym);
517 event.preventDefault();
518 event.stopImmediatePropagation();
519 return;
520 }
521 const clipboard =
522 (event.metaKey || (!macGuest() && event.ctrlKey)) &&
523 !event.altKey &&
524 ((!event.shiftKey && ["c", "x"].includes(key)) || key === "v");
525 if (clipboard) {
526 event.stopImmediatePropagation();
527 handled.add(code);
528 if (key === "v") {
529 if (nativeAvailable()) {
530 event.preventDefault();
531 void readAndPaste();
532 } else {
533 target.value = "";
534 target.focus({ preventScroll: true });
535 }
536 } else {
537 event.preventDefault();
538 copy(key);
539 }
540 return;
541 }
542 if (
543 (mapping || macGuest()) &&
544 event.metaKey &&
545 !["Meta", "Shift", "Control", "Alt", "CapsLock"].includes(event.key)
546 ) {
547 let sym = getKeysym(event);
548 if (
549 (malformedCommandLetter || sym === null || sym < 32) &&
550 /^Key[A-Z]$/.test(code)
551 )
552 sym = (event.shiftKey ? code[3] : code[3].toLowerCase()).codePointAt(
553 0,
554 );
555 if (sym !== null) {
556 const held = (p) => [...physical].some((c) => c.startsWith(p)),
557 modifier = shortcutModifier(),
558 shift = physical.has("ShiftRight")
559 ? [0xffe2, "ShiftRight"]
560 : [0xffe1, "ShiftLeft"];
561 transport.sendKey(...modifier, true);
562 if (event.shiftKey) transport.sendKey(...shift, true);
563 transport.sendKey(sym, code, true);
564 transport.sendKey(sym, code, false);
565 if (event.shiftKey && !held("Shift")) transport.sendKey(...shift, false);
566 if (!held(macGuest() ? "Meta" : "Control")) transport.sendKey(...modifier, false);
567 event.preventDefault();
568 event.stopImmediatePropagation();
569 handled.add(code);
570 return;
571 }
572 }
573 if (mapping && event.key === "Meta") event.stopImmediatePropagation();
574 if (!event.metaKey && !event.ctrlKey && [...event.key].length === 1 &&
575 event.key.codePointAt(0) > 127) {
576 // Fullwidth punctuation may arrive without a composition session.
577 // Sending it as an X11 keysym can silently drop it in X0tigervnc.
578 event.preventDefault();
579 event.stopImmediatePropagation();
580 handled.add(code);
581 commit(event.key);
582 } else if (!event.cageNativeTextKey && !event.metaKey && !event.ctrlKey && !event.altKey &&
583 event.key.length === 1 && /[^a-zA-Z0-9 ]/.test(event.key)) {
584 // Let the host input method choose punctuation (e.g. ? -> ?).
585 // The resulting input event carries the actual character to insert.
586 event.stopImmediatePropagation();
587 } else if (macGuest()) {
588 // noVNC's host-Mac modifier conversion targets non-Mac guests.
589 const sym = getKeysym(event);
590 if (sym !== null) { transport.sendKey(sym, code, true); remote.set(code, sym); }
591 event.preventDefault();
592 event.stopImmediatePropagation();
593 }
594 },
595 true,
596 );
597 on(
598 document,
599 "keyup",
600 (event) => {
601 const code = getKeycode(event);
602 // noVNC ignores releases for keys it never sent. Let keyup through so a
603 // modifier pressed before composition can still be released normally.
604 physical.delete(code);
605 if (remote.has(code)) {
606 transport.sendKey(remote.get(code), code, false);
607 remote.delete(code);
608 event.stopImmediatePropagation();
609 return;
610 }
611 if (
612 handled.delete(code) ||
613 (focused() && mode() === "mac" && event.key === "Meta")
614 )
615 event.stopImmediatePropagation();
616 else if (focused() && !composing && caretRect)
617 setTimeout(() => void syncCaret(), 35);
618 },
619 true,
620 );
621 on(
622 document,
623 "paste",
624 (event) => {
625 if (!isActive() || (!focused() && event.target !== target)) return;
626 event.preventDefault();
627 event.stopImmediatePropagation();
628 const files = transferFiles(event.clipboardData);
629 if (files.length === 1 && files[0].type.startsWith("image/")) {
630 const preparation = preparePaste?.();
631 receive(imagePayload(files[0]), preparation);
632 } else if (files.length) {
633 receive({ files, kind: "paste" });
634 } else if (event.clipboardData.types.includes("text/plain"))
635 paste(event.clipboardData.getData("text/plain"));
636 else say("剪贴板中没有可粘贴的图片或文本");
637 },
638 true,
639 );
640 on(container, "dragover", (event) => {
641 if (!isActive() || !hasFiles(event.dataTransfer)) return;
642 event.preventDefault();
643 event.dataTransfer.dropEffect = "copy";
644 });
645 on(container, "drop", (event) => {
646 if (!isActive() || !hasFiles(event.dataTransfer)) return;
647 event.preventDefault();
648 event.stopPropagation();
649 const canvas = surface?.() || container.querySelector("canvas") || container;
650 const rect = canvas.getBoundingClientRect();
651 receive({ files: transferFiles(event.dataTransfer), kind: "drop",
652 x: Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width)),
653 y: Math.max(0, Math.min(1, (event.clientY - rect.top) / rect.height)) });
654 });
655 return {
656 copy,
657 cancelCopy,
658 receiveCopy,
659 readAndPaste,
660 paste,
661 text: () => lastText,
662 edit(action) {
663 if (composing) return false;
664 if (action === "copy") copy();
665 else if (action === "cut") copy("x");
666 else if (action === "paste") void readAndPaste();
667 else if (action === "selectAll") chord("a");
668 else if (action === "undo") chord("z");
669 else if (action === "redo") chord("Z", true);
670 else return false;
671 return true;
672 },
673 focused,
674 dispose() {
675 if (composing && compositionSession)
676 queueComposition({ mode: "cancel", text: "", selectionStart: 0, selectionEnd: 0 });
677 disposed = true;
678 deactivateNative();
679 clearTimeout(copyTimer);
680 clearTimeout(caretTimer);
681 release();
682 listeners.forEach((remove) => remove());
683 transport.setKeyboardTarget(null);
684 target.remove();
685 },
686 };
687}