| 1 | |
| 2 | |
| 3 | import assert from "node:assert/strict"; |
| 4 | import { createRequire } from "node:module"; |
| 5 | const require = createRequire(import.meta.url); |
| 6 | const { chromium } = require( |
| 7 | process.env.CAGE_PLAYWRIGHT_MODULE || "playwright", |
| 8 | ); |
| 9 | const browser = await chromium.launch({ headless: true, executablePath: process.env.CAGE_TEST_BROWSER_PATH }); |
| 10 | const page = await browser.newPage(); |
| 11 | const errors = []; |
| 12 | page.on("pageerror", (error) => errors.push(error.message)); |
| 13 | const origin = process.env.CAGE_UI_URL || "http://127.0.0.1:5173"; |
| 14 | try { |
| 15 | await page.route("**/remote-input-smoke", (route) => |
| 16 | route.fulfill({ |
| 17 | contentType: "text/html; charset=utf-8", |
| 18 | body: '<div id="remote"><canvas tabindex="-1"></canvas></div><input aria-label="本机地址栏">', |
| 19 | }), |
| 20 | ); |
| 21 | await page.goto(origin + "/remote-input-smoke"); |
| 22 | await page.evaluate(async () => { |
| 23 | const [{ default: RFB }, { default: Keyboard }, { installRemoteInput }] = |
| 24 | await Promise.all([ |
| 25 | import("/.generated/novnc/core/rfb.js"), |
| 26 | import("/.generated/novnc/core/input/keyboard.js"), |
| 27 | import("/src/remote-input.js"), |
| 28 | ]); |
| 29 | const container = document.querySelector("#remote"); |
| 30 | const rfb = new EventTarget(); |
| 31 | |
| 32 | |
| 33 | for (const name of [ |
| 34 | "sendKey", |
| 35 | "_cageSendKey", |
| 36 | "_cageQueueInput", |
| 37 | "_handleKeyEvent", |
| 38 | "_handleServerFenceMsg", |
| 39 | "cageSetKeyboardTarget", |
| 40 | "focus", |
| 41 | "blur", |
| 42 | ]) |
| 43 | rfb[name] = RFB.prototype[name].bind(rfb); |
| 44 | rfb._canvas = container.querySelector("canvas"); |
| 45 | rfb._keyboard = new Keyboard(rfb._canvas); |
| 46 | rfb._rfbConnectionState = "connected"; |
| 47 | rfb._remoteCapsLock = rfb._remoteNumLock = null; |
| 48 | const packets = []; |
| 49 | let bytes = []; |
| 50 | rfb._sock = { |
| 51 | sQpush8(value) { |
| 52 | bytes.push(value); |
| 53 | }, |
| 54 | sQpush16(value) { |
| 55 | bytes.push((value >> 8) & 255, value & 255); |
| 56 | }, |
| 57 | sQpush32(value) { |
| 58 | bytes.push( |
| 59 | value >>> 24, |
| 60 | (value >> 16) & 255, |
| 61 | (value >> 8) & 255, |
| 62 | value & 255, |
| 63 | ); |
| 64 | }, |
| 65 | sQpushString(value) { |
| 66 | bytes.push(...new TextEncoder().encode(value)); |
| 67 | }, |
| 68 | flush() { |
| 69 | packets.push(bytes); |
| 70 | bytes = []; |
| 71 | }, |
| 72 | }; |
| 73 | const texts = []; |
| 74 | rfb.cagePasteText = (text) => |
| 75 | rfb._cageQueueInput(() => { |
| 76 | texts.push(text); |
| 77 | }); |
| 78 | let active = true; |
| 79 | const options = { |
| 80 | mode: () => "mac", |
| 81 | isActive: () => active, |
| 82 | insertText: (text) => rfb.cagePasteText(text), |
| 83 | onStatus() {}, |
| 84 | onFallback() {}, |
| 85 | }; |
| 86 | const install = () => installRemoteInput({ |
| 87 | events: rfb, |
| 88 | setKeyboardTarget: target => rfb.cageSetKeyboardTarget(target), |
| 89 | sendKey: (...key) => rfb.sendKey(...key), |
| 90 | focus: () => rfb.focus(), |
| 91 | pasteText: text => rfb.cagePasteText(text), |
| 92 | runKeyAction: action => rfb._cageQueueInput(() => action((...key) => rfb._cageSendKey(...key))), |
| 93 | }, container, options); |
| 94 | window.probe = { |
| 95 | rfb, |
| 96 | packets, |
| 97 | texts, |
| 98 | compositions: [], |
| 99 | input: install(), |
| 100 | install, |
| 101 | installComposition() { |
| 102 | this.input.dispose(); |
| 103 | options.tabId = () => "tab-1"; |
| 104 | options.caretRect = async () => ({ available: true, context: "a".repeat(32), rect: [240, 120, 0, 24] }); |
| 105 | options.insertComposition = (id, value) => rfb._cageQueueInput(async () => { |
| 106 | this.compositions.push({ id, ...value }); |
| 107 | if (value.mode === "commit") await new Promise(resolve => { this.finishComposition = resolve; }); |
| 108 | }); |
| 109 | const canvas = rfb._canvas; |
| 110 | canvas.width = 1000; canvas.height = 500; |
| 111 | canvas.style.cssText = "width:500px;height:250px;margin:40px"; |
| 112 | this.input = install(); |
| 113 | rfb.focus(); |
| 114 | }, |
| 115 | installNative() { |
| 116 | this.input.dispose(); |
| 117 | this.compositions.length = 0; |
| 118 | this.nativeRequests = []; |
| 119 | window.cageNativeIMEAvailable = true; |
| 120 | window.webkit = { messageHandlers: { cage: { postMessage: async value => { |
| 121 | this.nativeRequests.push(value); return true; |
| 122 | } } } }; |
| 123 | options.insertComposition = (id, value) => rfb._cageQueueInput(() => { this.compositions.push({ id, ...value }); }); |
| 124 | this.input = install(); rfb.focus(); |
| 125 | }, |
| 126 | setActive: (value) => { |
| 127 | active = value; |
| 128 | }, |
| 129 | fence(payload) { |
| 130 | const bytes = [0, 0, 0, 0, 0, 0, 0, payload.length, ...new TextEncoder().encode(payload)]; |
| 131 | rfb._sock.rQwait = () => false; |
| 132 | rfb._sock.rQskipBytes = (length) => bytes.splice(0, length); |
| 133 | rfb._sock.rQshift32 = () => bytes.splice(0, 4).reduce((value, byte) => (value << 8) | byte, 0); |
| 134 | rfb._sock.rQshift8 = () => bytes.shift(); |
| 135 | rfb._sock.rQshiftStr = (length) => String.fromCharCode(...bytes.splice(0, length)); |
| 136 | rfb._handleServerFenceMsg(); |
| 137 | }, |
| 138 | }; |
| 139 | rfb.focus(); |
| 140 | }); |
| 141 | const target = page.getByLabel("Cage 网页输入"); |
| 142 | const keys = () => |
| 143 | page.evaluate(() => |
| 144 | probe.packets.filter(p => p[0] !== 248).map((p) => { |
| 145 | if (p.length !== 8 || p[0] !== 4) |
| 146 | throw new Error("Unexpected RFB key packet"); |
| 147 | return { |
| 148 | down: p[1], |
| 149 | sym: ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]) >>> 0, |
| 150 | }; |
| 151 | }), |
| 152 | ); |
| 153 | const texts = () => page.evaluate(() => [...probe.texts]); |
| 154 | const clear = () => |
| 155 | page.evaluate(() => { |
| 156 | probe.packets.length = 0; |
| 157 | probe.texts.length = 0; |
| 158 | }); |
| 159 | const dispatch = (type, detail) => |
| 160 | target.evaluate( |
| 161 | (node, { type, detail }) => { |
| 162 | const EventType = type.startsWith("composition") |
| 163 | ? CompositionEvent |
| 164 | : InputEvent; |
| 165 | node.dispatchEvent(new EventType(type, { bubbles: true, ...detail })); |
| 166 | }, |
| 167 | { type, detail }, |
| 168 | ); |
| 169 | const compose = async (text) => { |
| 170 | await dispatch("compositionstart", { data: "" }); |
| 171 | await dispatch("input", { |
| 172 | data: "nihao", |
| 173 | isComposing: true, |
| 174 | inputType: "insertCompositionText", |
| 175 | }); |
| 176 | await dispatch("compositionend", { data: text }); |
| 177 | await dispatch("input", { data: text, inputType: "insertFromComposition" }); |
| 178 | }; |
| 179 | await page.keyboard.type("abc"); |
| 180 | assert.deepEqual( |
| 181 | (await keys()).filter((k) => k.down).map((k) => k.sym), |
| 182 | [97, 98, 99], |
| 183 | ); |
| 184 | assert.equal(await target.inputValue(), ""); |
| 185 | await clear(); |
| 186 | await page.keyboard.press("Shift+Enter"); |
| 187 | assert.deepEqual((await keys()).map(({ sym, down }) => [sym, down]), [ |
| 188 | [0xffe1, 1], [0xff0d, 1], [0xff0d, 0], [0xffe1, 0], |
| 189 | ], "Shift+Enter must preserve the modifier through the real RFB encoder"); |
| 190 | assert.deepEqual(await texts(), [], "newline must not also commit textarea text"); |
| 191 | await clear(); |
| 192 | await page.keyboard.down("Shift"); |
| 193 | await page.evaluate(() => { |
| 194 | probe.rfb._cagePasteJob = { id: "punctuation", phase: "fence", timer: setTimeout(() => {}, 1000), resolve() {} }; |
| 195 | probe.fence("punctuation"); |
| 196 | probe.fence("punctuation-keys"); |
| 197 | }); |
| 198 | await page.keyboard.up("Shift"); |
| 199 | assert.deepEqual((await keys()).map(({ sym, down }) => [sym, down]), [ |
| 200 | [0xffe1, 1], [0xffe1, 0], [0xffe3, 1], [0x76, 1], [0x76, 0], [0xffe3, 0], [0xffe1, 1], [0xffe1, 0], |
| 201 | ], "Desktop text commit releases held Shift for Ctrl+V and restores it before the host release"); |
| 202 | await clear(); |
| 203 | |
| 204 | |
| 205 | const cdp = await page.context().newCDPSession(page); |
| 206 | for (const character of ["?", "?", ",", "。", "!"]) { |
| 207 | await cdp.send("Input.dispatchKeyEvent", { type: "keyDown", key: character, code: "Slash", text: character }); |
| 208 | await cdp.send("Input.dispatchKeyEvent", { type: "keyUp", key: character, code: "Slash" }); |
| 209 | } |
| 210 | assert.deepEqual(await texts(), ["?", "?", ",", "。", "!"]); |
| 211 | assert.deepEqual(await keys(), [], "fullwidth punctuation must bypass X11 keysyms"); |
| 212 | await clear(); |
| 213 | await page.keyboard.press("Shift+?"); |
| 214 | assert.deepEqual(await texts(), ["?"]); |
| 215 | assert.deepEqual((await keys()).map(({ sym }) => sym), [0xffe1, 0xffe1], "only Shift is sent as a physical key"); |
| 216 | await clear(); |
| 217 | await cdp.send("Input.imeSetComposition", { |
| 218 | text: "nihao", |
| 219 | selectionStart: 5, |
| 220 | selectionEnd: 5, |
| 221 | }); |
| 222 | assert.equal(await target.inputValue(), "nihao"); |
| 223 | assert.deepEqual(await keys(), []); |
| 224 | await cdp.send("Input.insertText", { text: "你好" }); |
| 225 | assert.deepEqual(await texts(), ["你好"]); |
| 226 | assert.deepEqual(await keys(), []); |
| 227 | assert.equal(await target.inputValue(), ""); |
| 228 | await clear(); |
| 229 | await cdp.send("Input.insertText", { text: "🙂" }); |
| 230 | assert.deepEqual(await texts(), ["🙂"]); |
| 231 | await clear(); |
| 232 | await cdp.detach(); |
| 233 | await dispatch("compositionstart", { data: "" }); |
| 234 | const accepted = await target.evaluate((node) => |
| 235 | node.dispatchEvent( |
| 236 | new KeyboardEvent("keydown", { |
| 237 | key: "Process", |
| 238 | code: "KeyN", |
| 239 | keyCode: 229, |
| 240 | bubbles: true, |
| 241 | cancelable: true, |
| 242 | isComposing: true, |
| 243 | }), |
| 244 | ), |
| 245 | ); |
| 246 | assert.equal( |
| 247 | accepted, |
| 248 | true, |
| 249 | "host IME key default action must remain enabled", |
| 250 | ); |
| 251 | await page.keyboard.press("Space"); |
| 252 | assert.deepEqual( |
| 253 | await keys(), |
| 254 | [], |
| 255 | "candidate selection must not reach the guest", |
| 256 | ); |
| 257 | await dispatch("compositionend", { data: "你好🙂" }); |
| 258 | await dispatch("input", { |
| 259 | data: "你好🙂", |
| 260 | inputType: "insertFromComposition", |
| 261 | }); |
| 262 | await page.keyboard.press("Enter"); |
| 263 | assert.deepEqual( |
| 264 | (await keys()).filter((k) => k.down).map((k) => k.sym), |
| 265 | [0xff0d], |
| 266 | ); |
| 267 | assert.equal(await target.inputValue(), ""); |
| 268 | await clear(); |
| 269 | await compose("你"); |
| 270 | await compose("你"); |
| 271 | assert.deepEqual(await texts(), ["你", "你"]); |
| 272 | await clear(); |
| 273 | |
| 274 | await page.evaluate(() => { |
| 275 | probe.rfb._cageQueueInput( |
| 276 | () => |
| 277 | new Promise((resolve) => { |
| 278 | probe.finishText = resolve; |
| 279 | }), |
| 280 | ); |
| 281 | }); |
| 282 | await page.keyboard.press("Enter"); |
| 283 | assert.deepEqual(await keys(), []); |
| 284 | await page.evaluate(() => probe.finishText()); |
| 285 | assert.deepEqual( |
| 286 | (await keys()).map((k) => k.sym), |
| 287 | [0xff0d, 0xff0d], |
| 288 | ); |
| 289 | await clear(); |
| 290 | |
| 291 | await page.evaluate(() => { |
| 292 | probe.rfb._cageQueueInput( |
| 293 | () => |
| 294 | new Promise((resolve, reject) => { |
| 295 | probe.failText = reject; |
| 296 | }), |
| 297 | ); |
| 298 | }); |
| 299 | await page.keyboard.press("Enter"); |
| 300 | await page.evaluate(() => probe.failText(new Error("test transfer failure"))); |
| 301 | assert.deepEqual(await keys(), []); |
| 302 | await compose(""); |
| 303 | assert.deepEqual(await keys(), []); |
| 304 | await page.keyboard.down("Shift"); |
| 305 | await dispatch("compositionstart", { data: "" }); |
| 306 | await page.keyboard.up("Shift"); |
| 307 | assert.deepEqual( |
| 308 | (await keys()).map((k) => k.down), |
| 309 | [1, 0], |
| 310 | "modifiers released during composition must not stick", |
| 311 | ); |
| 312 | assert.equal( |
| 313 | await page.evaluate(() => probe.input.edit("undo")), |
| 314 | false, |
| 315 | "native menus must edit the host composition", |
| 316 | ); |
| 317 | await dispatch("compositionend", { data: "" }); |
| 318 | await clear(); |
| 319 | await page.getByLabel("本机地址栏").fill("本机文字"); |
| 320 | assert.deepEqual(await keys(), []); |
| 321 | await page.evaluate(() => probe.rfb.focus()); |
| 322 | await page.keyboard.press("Meta+f"); |
| 323 | assert.deepEqual( |
| 324 | (await keys()).filter((k) => k.down).map((k) => k.sym), |
| 325 | [0xffe3, 102], |
| 326 | ); |
| 327 | await clear(); |
| 328 | await page.evaluate(() => probe.setActive(false)); |
| 329 | await compose("后台不提交"); |
| 330 | assert.deepEqual(await keys(), []); |
| 331 | await page.evaluate(() => { |
| 332 | probe.setActive(true); |
| 333 | probe.input.dispose(); |
| 334 | probe.input = probe.install(); |
| 335 | probe.rfb.focus(); |
| 336 | }); |
| 337 | assert.equal(await target.count(), 1); |
| 338 | await page.keyboard.press("b"); |
| 339 | assert.deepEqual( |
| 340 | (await keys()).filter((k) => k.down).map((k) => k.sym), |
| 341 | [98], |
| 342 | ); |
| 343 | await clear(); |
| 344 | await page.evaluate(() => probe.installComposition()); |
| 345 | await page.waitForFunction(() => { |
| 346 | const box = probe.rfb._canvas.getBoundingClientRect(); |
| 347 | return document.activeElement.style.left === `${box.left + 120}px`; |
| 348 | }); |
| 349 | const nativeCDP = await page.context().newCDPSession(page); |
| 350 | await nativeCDP.send("Input.imeSetComposition", { text: "ni'hao", selectionStart: 6, selectionEnd: 6 }); |
| 351 | await nativeCDP.send("Input.insertText", { text: "你好?" }); |
| 352 | await page.waitForFunction(() => !!probe.finishComposition); |
| 353 | await page.keyboard.press("Enter"); |
| 354 | assert.deepEqual(await keys(), [], "Enter must wait behind the native composition commit"); |
| 355 | const nativeMessages = await page.evaluate(() => probe.compositions); |
| 356 | assert.equal(nativeMessages[0].mode, "begin"); |
| 357 | assert.equal(nativeMessages.at(-1).mode, "commit"); |
| 358 | assert.ok(nativeMessages.slice(1, -1).every(({ mode }) => mode === "update")); |
| 359 | assert.ok(nativeMessages.some(({ text }) => text === "ni'hao")); |
| 360 | assert.equal(nativeMessages.at(-1).text, "你好?"); |
| 361 | assert.equal(new Set(nativeMessages.map(({ session }) => session)).size, 1); |
| 362 | await page.evaluate(() => probe.finishComposition()); |
| 363 | assert.deepEqual((await keys()).map(({ sym }) => sym), [0xff0d, 0xff0d]); |
| 364 | await nativeCDP.detach(); |
| 365 | await clear(); |
| 366 | await page.evaluate(() => probe.installNative()); |
| 367 | await page.waitForFunction(() => probe.nativeRequests.some(value => value.operation === "activate")); |
| 368 | await page.evaluate(() => { |
| 369 | const owner = probe.nativeRequests.find(value => value.operation === "activate").owner; |
| 370 | for (const kind of ["keydown", "keyup"]) { |
| 371 | window.dispatchEvent(new CustomEvent("cage-native-input", { |
| 372 | detail: { owner, kind, key: "Enter", code: "Enter", shiftKey: true }, |
| 373 | })); |
| 374 | } |
| 375 | }); |
| 376 | assert.deepEqual((await keys()).map(({ sym, down }) => [sym, down]), [ |
| 377 | [0xffe1, 1], [0xff0d, 1], [0xff0d, 0], [0xffe1, 0], |
| 378 | ], "native Enter's shiftKey must survive without a preceding DOM Shift event"); |
| 379 | await clear(); |
| 380 | await page.evaluate(() => { |
| 381 | const owner = probe.nativeRequests.find(value => value.operation === "activate").owner; |
| 382 | const emit = value => window.dispatchEvent(new CustomEvent("cage-native-input", { detail: { owner, ...value } })); |
| 383 | emit({kind:"compositionstart"}); |
| 384 | emit({kind:"compositionupdate",text:"ni'hao",selectionStart:3,selectionEnd:6}); |
| 385 | emit({kind:"compositionend",text:"你好"}); |
| 386 | emit({kind:"input",text:"?"}); |
| 387 | emit({kind:"keydown",key:"?",code:"Slash",textKey:true}); |
| 388 | emit({kind:"keyup",key:"?",code:"Slash"}); |
| 389 | window.dispatchEvent(new CustomEvent("cage-native-input", {detail:{owner:"stale",kind:"input",text:"误写"}})); |
| 390 | }); |
| 391 | assert.deepEqual((await page.evaluate(() => probe.compositions)).map(({mode})=>mode), ["begin","update","commit"]); |
| 392 | assert.deepEqual(await texts(), ["?"], "native direct punctuation is committed exactly once"); |
| 393 | assert.deepEqual((await keys()).map(({sym})=>sym), [63,63], "native ASCII punctuation keeps the key path without needing a DOM default action"); |
| 394 | await page.getByLabel("本机地址栏").focus(); |
| 395 | await page.waitForFunction(() => probe.nativeRequests.some(value => value.operation === "deactivate")); |
| 396 | await clear(); |
| 397 | await page.evaluate(() => { |
| 398 | const oldTarget = document.activeElement; |
| 399 | probe.input.dispose(); |
| 400 | oldTarget.dispatchEvent( |
| 401 | new CompositionEvent("compositionend", { data: "迟到的文字" }), |
| 402 | ); |
| 403 | probe.rfb.focus(); |
| 404 | }); |
| 405 | assert.equal(await target.count(), 0); |
| 406 | assert.equal( |
| 407 | await page.evaluate(() => document.activeElement.tagName), |
| 408 | "CANVAS", |
| 409 | ); |
| 410 | assert.deepEqual(await keys(), []); |
| 411 | assert.deepEqual(errors, []); |
| 412 | console.log( |
| 413 | JSON.stringify( |
| 414 | { |
| 415 | passed: true, |
| 416 | checks: [ |
| 417 | "real noVNC keyboard and RFB encoding", |
| 418 | "Shift+Enter and native modifier recovery", |
| 419 | "English input", |
| 420 | "fullwidth question mark and punctuation", |
| 421 | "English question mark and modifier release", |
| 422 | "Desktop paste while Shift is held", |
| 423 | "shared composition begin, preedit and commit order", |
| 424 | "candidate anchor maps the actual canvas bounds", |
| 425 | "native host composition, punctuation and stale owner rejection", |
| 426 | "native focus returns to local inputs", |
| 427 | "Chromium IME engine commit", |
| 428 | "composition default action", |
| 429 | "candidate suppression", |
| 430 | "Unicode text transfer", |
| 431 | "text and Enter order", |
| 432 | "failed transfer cancels queued Enter", |
| 433 | "repeated commits", |
| 434 | "cancel", |
| 435 | "modifier release", |
| 436 | "native edit routing", |
| 437 | "local field isolation", |
| 438 | "Command mapping", |
| 439 | "inactive view", |
| 440 | "reconnect and disposal", |
| 441 | ], |
| 442 | limitation: |
| 443 | "Covers the Chromium composition engine and simulated event sequences; native macOS IME and guest rendering require separate acceptance.", |
| 444 | }, |
| 445 | null, |
| 446 | 2, |
| 447 | ), |
| 448 | ); |
| 449 | } finally { |
| 450 | await browser.close(); |
| 451 | } |