Jason Lin | d66e6bf | 2022-08-22 14:47:10 +1000 | [diff] [blame] | 1 | // Copyright 2022 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 5 | /** |
| 6 | * @fileoverview For supporting xterm.js and the terminal emulator. |
| 7 | */ |
| 8 | |
| 9 | // TODO(b/236205389): add tests. For example, we should enable the test in |
| 10 | // terminal_tests.js for XtermTerminal. |
| 11 | |
Jason Lin | 6a402a7 | 2022-08-25 16:07:02 +1000 | [diff] [blame] | 12 | import {LitElement, css, html} from './lit.js'; |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 13 | import {FontManager, ORIGINAL_URL, TERMINAL_EMULATORS, delayedScheduler, |
| 14 | fontManager, getOSInfo, sleep} from './terminal_common.js'; |
Jason Lin | 6a402a7 | 2022-08-25 16:07:02 +1000 | [diff] [blame] | 15 | import {ICON_COPY} from './terminal_icons.js'; |
Jason Lin | 4de4f38 | 2022-09-01 14:10:18 +1000 | [diff] [blame] | 16 | import {FitAddon, Terminal, Unicode11Addon, WebLinksAddon, WebglAddon} |
| 17 | from './xterm.js'; |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 18 | |
Jason Lin | 5690e75 | 2022-08-30 15:36:45 +1000 | [diff] [blame] | 19 | |
| 20 | /** @enum {number} */ |
| 21 | export const Modifier = { |
| 22 | Shift: 1 << 0, |
| 23 | Alt: 1 << 1, |
| 24 | Ctrl: 1 << 2, |
| 25 | Meta: 1 << 3, |
| 26 | }; |
| 27 | |
| 28 | // This is just a static map from key names to key codes. It helps make the code |
| 29 | // a bit more readable. |
| 30 | const keyCodes = hterm.Parser.identifiers.keyCodes; |
| 31 | |
| 32 | /** |
| 33 | * Encode a key combo (i.e. modifiers + a normal key) to an unique number. |
| 34 | * |
| 35 | * @param {number} modifiers |
| 36 | * @param {number} keyCode |
| 37 | * @return {number} |
| 38 | */ |
| 39 | export function encodeKeyCombo(modifiers, keyCode) { |
| 40 | return keyCode << 4 | modifiers; |
| 41 | } |
| 42 | |
| 43 | const OS_DEFAULT_BINDINGS = [ |
| 44 | // Submit feedback. |
| 45 | encodeKeyCombo(Modifier.Alt | Modifier.Shift, keyCodes.I), |
| 46 | // Toggle chromevox. |
| 47 | encodeKeyCombo(Modifier.Ctrl | Modifier.Alt, keyCodes.Z), |
| 48 | // Switch input method. |
| 49 | encodeKeyCombo(Modifier.Ctrl, keyCodes.SPACE), |
| 50 | |
| 51 | // Dock window left/right. |
| 52 | encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_LEFT), |
| 53 | encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_RIGHT), |
| 54 | |
| 55 | // Maximize/minimize window. |
| 56 | encodeKeyCombo(Modifier.Alt, keyCodes.EQUAL), |
| 57 | encodeKeyCombo(Modifier.Alt, keyCodes.MINUS), |
| 58 | ]; |
| 59 | |
| 60 | |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 61 | const ANSI_COLOR_NAMES = [ |
| 62 | 'black', |
| 63 | 'red', |
| 64 | 'green', |
| 65 | 'yellow', |
| 66 | 'blue', |
| 67 | 'magenta', |
| 68 | 'cyan', |
| 69 | 'white', |
| 70 | 'brightBlack', |
| 71 | 'brightRed', |
| 72 | 'brightGreen', |
| 73 | 'brightYellow', |
| 74 | 'brightBlue', |
| 75 | 'brightMagenta', |
| 76 | 'brightCyan', |
| 77 | 'brightWhite', |
| 78 | ]; |
| 79 | |
| 80 | const PrefToXtermOptions = { |
| 81 | 'font-family': 'fontFamily', |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 82 | }; |
| 83 | |
| 84 | /** |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 85 | * @typedef {{ |
| 86 | * term: !Terminal, |
| 87 | * fontManager: !FontManager, |
| 88 | * fitAddon: !FitAddon, |
| 89 | * }} |
| 90 | */ |
| 91 | export let XtermTerminalTestParams; |
| 92 | |
| 93 | /** |
Jason Lin | 5690e75 | 2022-08-30 15:36:45 +1000 | [diff] [blame] | 94 | * Compute a control character for a given character. |
| 95 | * |
| 96 | * @param {string} ch |
| 97 | * @return {string} |
| 98 | */ |
| 99 | function ctl(ch) { |
| 100 | return String.fromCharCode(ch.charCodeAt(0) - 64); |
| 101 | } |
| 102 | |
| 103 | /** |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 104 | * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO |
| 105 | * because it always convert utf8 data to strings, which is not necessary for |
| 106 | * xterm. |
| 107 | */ |
| 108 | class XtermTerminalIO extends hterm.Terminal.IO { |
| 109 | /** @override */ |
| 110 | writeUTF8(buffer) { |
| 111 | this.terminal_.write(new Uint8Array(buffer)); |
| 112 | } |
| 113 | |
| 114 | /** @override */ |
| 115 | writelnUTF8(buffer) { |
| 116 | this.terminal_.writeln(new Uint8Array(buffer)); |
| 117 | } |
| 118 | |
| 119 | /** @override */ |
| 120 | print(string) { |
| 121 | this.terminal_.write(string); |
| 122 | } |
| 123 | |
| 124 | /** @override */ |
| 125 | writeUTF16(string) { |
| 126 | this.print(string); |
| 127 | } |
| 128 | |
| 129 | /** @override */ |
| 130 | println(string) { |
| 131 | this.terminal_.writeln(string); |
| 132 | } |
| 133 | |
| 134 | /** @override */ |
| 135 | writelnUTF16(string) { |
| 136 | this.println(string); |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | /** |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 141 | * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal` |
| 142 | * so that it can be used in existing code. |
| 143 | * |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 144 | * @extends {hterm.Terminal} |
| 145 | * @unrestricted |
| 146 | */ |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 147 | export class XtermTerminal { |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 148 | /** |
| 149 | * @param {{ |
| 150 | * storage: !lib.Storage, |
| 151 | * profileId: string, |
| 152 | * enableWebGL: boolean, |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 153 | * testParams: (!XtermTerminalTestParams|undefined), |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 154 | * }} args |
| 155 | */ |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 156 | constructor({storage, profileId, enableWebGL, testParams}) { |
Jason Lin | 5690e75 | 2022-08-30 15:36:45 +1000 | [diff] [blame] | 157 | this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this); |
| 158 | this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this); |
| 159 | this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this); |
| 160 | |
Jason Lin | 8de3d28 | 2022-09-01 21:29:05 +1000 | [diff] [blame] | 161 | this.inited_ = false; |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 162 | this.profileId_ = profileId; |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 163 | /** @type {!hterm.PreferenceManager} */ |
| 164 | this.prefs_ = new hterm.PreferenceManager(storage, profileId); |
| 165 | this.enableWebGL_ = enableWebGL; |
| 166 | |
Jason Lin | 5690e75 | 2022-08-30 15:36:45 +1000 | [diff] [blame] | 167 | // TODO: we should probably pass the initial prefs to the ctor. |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 168 | this.term = testParams?.term || new Terminal(); |
| 169 | this.fontManager_ = testParams?.fontManager || fontManager; |
| 170 | this.fitAddon = testParams?.fitAddon || new FitAddon(); |
| 171 | |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 172 | this.term.loadAddon(this.fitAddon); |
Jason Lin | 8de3d28 | 2022-09-01 21:29:05 +1000 | [diff] [blame] | 173 | this.scheduleFit_ = delayedScheduler( |
| 174 | () => { |
| 175 | if (this.inited_) { |
| 176 | this.fitAddon.fit(); |
| 177 | } |
| 178 | }, |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 179 | testParams ? 0 : 250); |
| 180 | |
Jason Lin | 4de4f38 | 2022-09-01 14:10:18 +1000 | [diff] [blame] | 181 | this.term.loadAddon(new WebLinksAddon()); |
| 182 | this.term.loadAddon(new Unicode11Addon()); |
| 183 | this.term.unicode.activeVersion = '11'; |
| 184 | |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 185 | this.pendingFont_ = null; |
| 186 | this.scheduleRefreshFont_ = delayedScheduler( |
| 187 | () => this.refreshFont_(), 100); |
| 188 | document.fonts.addEventListener('loadingdone', |
| 189 | () => this.onFontLoadingDone_()); |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 190 | |
| 191 | this.installUnimplementedStubs_(); |
Jason Lin | e9231bc | 2022-09-01 13:54:02 +1000 | [diff] [blame] | 192 | this.installEscapeSequenceHandlers_(); |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 193 | |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 194 | this.term.onResize(({cols, rows}) => this.io.onTerminalResize(cols, rows)); |
| 195 | // We could also use `this.io.sendString()` except for the nassh exit |
| 196 | // prompt, which only listens to onVTKeystroke(). |
| 197 | this.term.onData((data) => this.io.onVTKeystroke(data)); |
Jason Lin | 6a402a7 | 2022-08-25 16:07:02 +1000 | [diff] [blame] | 198 | this.term.onTitleChange((title) => document.title = title); |
Jason Lin | 5690e75 | 2022-08-30 15:36:45 +1000 | [diff] [blame] | 199 | this.term.onSelectionChange(() => this.copySelection_()); |
| 200 | |
| 201 | /** |
| 202 | * A mapping from key combo (see encodeKeyCombo()) to a handler function. |
| 203 | * |
| 204 | * If a key combo is in the map: |
| 205 | * |
| 206 | * - The handler instead of xterm.js will handle the keydown event. |
| 207 | * - Keyup and keypress will be ignored by both us and xterm.js. |
| 208 | * |
| 209 | * We re-generate this map every time a relevant pref value is changed. This |
| 210 | * is ok because pref changes are rare. |
| 211 | * |
| 212 | * @type {!Map<number, function(!KeyboardEvent)>} |
| 213 | */ |
| 214 | this.keyDownHandlers_ = new Map(); |
| 215 | this.scheduleResetKeyDownHandlers_ = |
| 216 | delayedScheduler(() => this.resetKeyDownHandlers_(), 250); |
| 217 | |
| 218 | this.term.attachCustomKeyEventHandler( |
| 219 | this.customKeyEventHandler_.bind(this)); |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 220 | |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 221 | this.io = new XtermTerminalIO(this); |
| 222 | this.notificationCenter_ = null; |
Jason Lin | 6a402a7 | 2022-08-25 16:07:02 +1000 | [diff] [blame] | 223 | |
| 224 | this.copyNotice_ = null; |
| 225 | |
| 226 | this.term.options.theme = { |
| 227 | selection: 'rgba(174, 203, 250, .6)', |
| 228 | selectionForeground: 'black', |
| 229 | customGlyphs: true, |
| 230 | }; |
| 231 | this.observePrefs_(); |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 232 | } |
| 233 | |
| 234 | /** |
| 235 | * Install stubs for stuff that we haven't implemented yet so that the code |
| 236 | * still runs. |
| 237 | */ |
| 238 | installUnimplementedStubs_() { |
| 239 | this.keyboard = { |
| 240 | keyMap: { |
| 241 | keyDefs: [], |
| 242 | }, |
| 243 | bindings: { |
| 244 | clear: () => {}, |
| 245 | addBinding: () => {}, |
| 246 | addBindings: () => {}, |
| 247 | OsDefaults: {}, |
| 248 | }, |
| 249 | }; |
| 250 | this.keyboard.keyMap.keyDefs[78] = {}; |
| 251 | |
| 252 | const methodNames = [ |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 253 | 'setAccessibilityEnabled', |
| 254 | 'setBackgroundImage', |
| 255 | 'setCursorPosition', |
| 256 | 'setCursorVisible', |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 257 | ]; |
| 258 | |
| 259 | for (const name of methodNames) { |
| 260 | this[name] = () => console.warn(`${name}() is not implemented`); |
| 261 | } |
| 262 | |
| 263 | this.contextMenu = { |
| 264 | setItems: () => { |
| 265 | console.warn('.contextMenu.setItems() is not implemented'); |
| 266 | }, |
| 267 | }; |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 268 | |
| 269 | this.vt = { |
| 270 | resetParseState: () => { |
| 271 | console.warn('.vt.resetParseState() is not implemented'); |
| 272 | }, |
| 273 | }; |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 274 | } |
| 275 | |
Jason Lin | e9231bc | 2022-09-01 13:54:02 +1000 | [diff] [blame] | 276 | installEscapeSequenceHandlers_() { |
| 277 | // OSC 52 for copy. |
| 278 | this.term.parser.registerOscHandler(52, (args) => { |
| 279 | // Args comes in as a single 'clipboard;b64-data' string. The clipboard |
| 280 | // parameter is used to select which of the X clipboards to address. Since |
| 281 | // we're not integrating with X, we treat them all the same. |
| 282 | const parsedArgs = args.match(/^[cps01234567]*;(.*)/); |
| 283 | if (!parsedArgs) { |
| 284 | return true; |
| 285 | } |
| 286 | |
| 287 | let data; |
| 288 | try { |
| 289 | data = window.atob(parsedArgs[1]); |
| 290 | } catch (e) { |
| 291 | // If the user sent us invalid base64 content, silently ignore it. |
| 292 | return true; |
| 293 | } |
| 294 | const decoder = new TextDecoder(); |
| 295 | const bytes = lib.codec.stringToCodeUnitArray(data); |
| 296 | this.copyString_(decoder.decode(bytes)); |
| 297 | |
| 298 | return true; |
| 299 | }); |
| 300 | } |
| 301 | |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 302 | /** |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 303 | * Write data to the terminal. |
| 304 | * |
| 305 | * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for |
| 306 | * UTF-8 data |
| 307 | */ |
| 308 | write(data) { |
| 309 | this.term.write(data); |
| 310 | } |
| 311 | |
| 312 | /** |
| 313 | * Like `this.write()` but also write a line break. |
| 314 | * |
| 315 | * @param {string|!Uint8Array} data |
| 316 | */ |
| 317 | writeln(data) { |
| 318 | this.term.writeln(data); |
| 319 | } |
| 320 | |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 321 | get screenSize() { |
| 322 | return new hterm.Size(this.term.cols, this.term.rows); |
| 323 | } |
| 324 | |
| 325 | /** |
| 326 | * Don't need to do anything. |
| 327 | * |
| 328 | * @override |
| 329 | */ |
| 330 | installKeyboard() {} |
| 331 | |
| 332 | /** |
| 333 | * @override |
| 334 | */ |
| 335 | decorate(elem) { |
Jason Lin | 8de3d28 | 2022-09-01 21:29:05 +1000 | [diff] [blame] | 336 | (async () => { |
| 337 | await new Promise((resolve) => this.prefs_.readStorage(resolve)); |
| 338 | // This will trigger all the observers to set the terminal options before |
| 339 | // we call `this.term.open()`. |
| 340 | this.prefs_.notifyAll(); |
| 341 | |
| 342 | this.inited_ = true; |
| 343 | this.term.open(elem); |
| 344 | |
| 345 | this.scheduleFit_(); |
| 346 | if (this.enableWebGL_) { |
| 347 | this.term.loadAddon(new WebglAddon()); |
| 348 | } |
| 349 | this.term.focus(); |
| 350 | (new ResizeObserver(() => this.scheduleFit_())).observe(elem); |
| 351 | // TODO: Make a11y work. Maybe we can just use hterm.AccessibilityReader. |
| 352 | this.notificationCenter_ = new hterm.NotificationCenter(document.body); |
| 353 | |
| 354 | this.onTerminalReady(); |
| 355 | })(); |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 356 | } |
| 357 | |
| 358 | /** @override */ |
| 359 | showOverlay(msg, timeout = 1500) { |
| 360 | if (this.notificationCenter_) { |
| 361 | this.notificationCenter_.show(msg, {timeout}); |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | /** @override */ |
| 366 | hideOverlay() { |
| 367 | if (this.notificationCenter_) { |
| 368 | this.notificationCenter_.hide(); |
| 369 | } |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 370 | } |
| 371 | |
| 372 | /** @override */ |
| 373 | getPrefs() { |
| 374 | return this.prefs_; |
| 375 | } |
| 376 | |
| 377 | /** @override */ |
| 378 | getDocument() { |
| 379 | return window.document; |
| 380 | } |
| 381 | |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 382 | /** @override */ |
| 383 | reset() { |
| 384 | this.term.reset(); |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 385 | } |
| 386 | |
| 387 | /** @override */ |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 388 | setProfile(profileId, callback = undefined) { |
| 389 | this.prefs_.setProfile(profileId, callback); |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 390 | } |
| 391 | |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 392 | /** @override */ |
| 393 | interpret(string) { |
| 394 | this.term.write(string); |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 395 | } |
| 396 | |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 397 | /** @override */ |
| 398 | focus() { |
| 399 | this.term.focus(); |
| 400 | } |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 401 | |
| 402 | /** @override */ |
| 403 | onOpenOptionsPage() {} |
| 404 | |
| 405 | /** @override */ |
| 406 | onTerminalReady() {} |
| 407 | |
Jason Lin | d04bab3 | 2022-08-22 14:48:39 +1000 | [diff] [blame] | 408 | observePrefs_() { |
| 409 | for (const pref in PrefToXtermOptions) { |
| 410 | this.prefs_.addObserver(pref, (v) => { |
| 411 | this.updateOption_(PrefToXtermOptions[pref], v); |
| 412 | }); |
| 413 | } |
| 414 | |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 415 | // This is for this.notificationCenter_. |
| 416 | const setHtermCSSVariable = (name, value) => { |
| 417 | document.body.style.setProperty(`--hterm-${name}`, value); |
| 418 | }; |
| 419 | |
| 420 | const setHtermColorCSSVariable = (name, color) => { |
| 421 | const css = lib.notNull(lib.colors.normalizeCSS(color)); |
| 422 | const rgb = lib.colors.crackRGB(css).slice(0, 3).join(','); |
| 423 | setHtermCSSVariable(name, rgb); |
| 424 | }; |
| 425 | |
| 426 | this.prefs_.addObserver('font-size', (v) => { |
| 427 | this.updateOption_('fontSize', v); |
| 428 | setHtermCSSVariable('font-size', `${v}px`); |
| 429 | }); |
| 430 | |
Jason Lin | d04bab3 | 2022-08-22 14:48:39 +1000 | [diff] [blame] | 431 | // Theme-related preference items. |
| 432 | this.prefs_.addObservers(null, { |
| 433 | 'background-color': (v) => { |
| 434 | this.updateTheme_({background: v}); |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 435 | setHtermColorCSSVariable('background-color', v); |
Jason Lin | d04bab3 | 2022-08-22 14:48:39 +1000 | [diff] [blame] | 436 | }, |
| 437 | 'foreground-color': (v) => { |
| 438 | this.updateTheme_({foreground: v}); |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 439 | setHtermColorCSSVariable('foreground-color', v); |
Jason Lin | d04bab3 | 2022-08-22 14:48:39 +1000 | [diff] [blame] | 440 | }, |
| 441 | 'cursor-color': (v) => { |
| 442 | this.updateTheme_({cursor: v}); |
| 443 | }, |
| 444 | 'color-palette-overrides': (v) => { |
| 445 | if (!(v instanceof Array)) { |
| 446 | // For terminal, we always expect this to be an array. |
| 447 | console.warn('unexpected color palette: ', v); |
| 448 | return; |
| 449 | } |
| 450 | const colors = {}; |
| 451 | for (let i = 0; i < v.length; ++i) { |
| 452 | colors[ANSI_COLOR_NAMES[i]] = v[i]; |
| 453 | } |
| 454 | this.updateTheme_(colors); |
| 455 | }, |
| 456 | }); |
Jason Lin | 5690e75 | 2022-08-30 15:36:45 +1000 | [diff] [blame] | 457 | |
| 458 | for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t', |
| 459 | 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number', |
| 460 | 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) { |
| 461 | this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_); |
| 462 | } |
Jason Lin | d04bab3 | 2022-08-22 14:48:39 +1000 | [diff] [blame] | 463 | } |
| 464 | |
| 465 | /** |
| 466 | * @param {!Object} theme |
| 467 | */ |
| 468 | updateTheme_(theme) { |
Jason Lin | 8de3d28 | 2022-09-01 21:29:05 +1000 | [diff] [blame] | 469 | const updateTheme = (target) => { |
| 470 | for (const [key, value] of Object.entries(theme)) { |
| 471 | target[key] = lib.colors.normalizeCSS(value); |
| 472 | } |
| 473 | }; |
| 474 | |
| 475 | // Must use a new theme object to trigger re-render if we have initialized. |
| 476 | if (this.inited_) { |
| 477 | const newTheme = {...this.term.options.theme}; |
| 478 | updateTheme(newTheme); |
| 479 | this.term.options.theme = newTheme; |
| 480 | return; |
Jason Lin | d04bab3 | 2022-08-22 14:48:39 +1000 | [diff] [blame] | 481 | } |
Jason Lin | 8de3d28 | 2022-09-01 21:29:05 +1000 | [diff] [blame] | 482 | |
| 483 | updateTheme(this.term.options.theme); |
Jason Lin | d04bab3 | 2022-08-22 14:48:39 +1000 | [diff] [blame] | 484 | } |
| 485 | |
| 486 | /** |
Jason Lin | 8de3d28 | 2022-09-01 21:29:05 +1000 | [diff] [blame] | 487 | * Update one xterm.js option. Use updateTheme_() for theme. |
Jason Lin | d04bab3 | 2022-08-22 14:48:39 +1000 | [diff] [blame] | 488 | * |
| 489 | * @param {string} key |
| 490 | * @param {*} value |
| 491 | */ |
| 492 | updateOption_(key, value) { |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 493 | if (key === 'fontFamily') { |
| 494 | this.updateFont_(/** @type {string} */(value)); |
| 495 | return; |
| 496 | } |
Jason Lin | d04bab3 | 2022-08-22 14:48:39 +1000 | [diff] [blame] | 497 | // TODO: xterm supports updating multiple options at the same time. We |
| 498 | // should probably do that. |
| 499 | this.term.options[key] = value; |
| 500 | this.scheduleFit_(); |
| 501 | } |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 502 | |
| 503 | /** |
| 504 | * Called when there is a "fontloadingdone" event. We need this because |
| 505 | * `FontManager.loadFont()` does not guarantee loading all the font files. |
| 506 | */ |
| 507 | async onFontLoadingDone_() { |
| 508 | // If there is a pending font, the font is going to be refresh soon, so we |
| 509 | // don't need to do anything. |
Jason Lin | 8de3d28 | 2022-09-01 21:29:05 +1000 | [diff] [blame] | 510 | if (this.inited_ && !this.pendingFont_) { |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 511 | this.scheduleRefreshFont_(); |
| 512 | } |
| 513 | } |
| 514 | |
Jason Lin | 5690e75 | 2022-08-30 15:36:45 +1000 | [diff] [blame] | 515 | copySelection_() { |
Jason Lin | e9231bc | 2022-09-01 13:54:02 +1000 | [diff] [blame] | 516 | this.copyString_(this.term.getSelection()); |
| 517 | } |
| 518 | |
| 519 | /** @param {string} data */ |
| 520 | copyString_(data) { |
| 521 | if (!data) { |
Jason Lin | 6a402a7 | 2022-08-25 16:07:02 +1000 | [diff] [blame] | 522 | return; |
| 523 | } |
Jason Lin | e9231bc | 2022-09-01 13:54:02 +1000 | [diff] [blame] | 524 | navigator.clipboard?.writeText(data); |
Jason Lin | 6a402a7 | 2022-08-25 16:07:02 +1000 | [diff] [blame] | 525 | if (!this.copyNotice_) { |
| 526 | this.copyNotice_ = document.createElement('terminal-copy-notice'); |
| 527 | } |
| 528 | setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200); |
| 529 | } |
| 530 | |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 531 | /** |
| 532 | * Refresh xterm rendering for a font related event. |
| 533 | */ |
| 534 | refreshFont_() { |
| 535 | // We have to set the fontFamily option to a different string to trigger the |
| 536 | // re-rendering. Appending a space at the end seems to be the easiest |
| 537 | // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for |
| 538 | // us. |
| 539 | // |
| 540 | // TODO: Report a bug to xterm.js and ask for exposing a public function for |
| 541 | // the refresh so that we don't need to do this hack. |
| 542 | this.term.options.fontFamily += ' '; |
| 543 | } |
| 544 | |
| 545 | /** |
| 546 | * Update a font. |
| 547 | * |
| 548 | * @param {string} cssFontFamily |
| 549 | */ |
| 550 | async updateFont_(cssFontFamily) { |
Jason Lin | 6a402a7 | 2022-08-25 16:07:02 +1000 | [diff] [blame] | 551 | this.pendingFont_ = cssFontFamily; |
| 552 | await this.fontManager_.loadFont(cssFontFamily); |
| 553 | // Sleep a bit to wait for flushing fontloadingdone events. This is not |
| 554 | // strictly necessary, but it should prevent `this.onFontLoadingDone_()` |
| 555 | // to refresh font unnecessarily in some cases. |
| 556 | await sleep(30); |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 557 | |
Jason Lin | 6a402a7 | 2022-08-25 16:07:02 +1000 | [diff] [blame] | 558 | if (this.pendingFont_ !== cssFontFamily) { |
| 559 | // `updateFont_()` probably is called again. Abort what we are doing. |
| 560 | console.log(`pendingFont_ (${this.pendingFont_}) is changed` + |
| 561 | ` (expecting ${cssFontFamily})`); |
| 562 | return; |
| 563 | } |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 564 | |
Jason Lin | 6a402a7 | 2022-08-25 16:07:02 +1000 | [diff] [blame] | 565 | if (this.term.options.fontFamily !== cssFontFamily) { |
| 566 | this.term.options.fontFamily = cssFontFamily; |
| 567 | } else { |
| 568 | // If the font is already the same, refresh font just to be safe. |
| 569 | this.refreshFont_(); |
| 570 | } |
| 571 | this.pendingFont_ = null; |
| 572 | this.scheduleFit_(); |
Jason Lin | abad756 | 2022-08-22 14:49:05 +1000 | [diff] [blame] | 573 | } |
Jason Lin | 5690e75 | 2022-08-30 15:36:45 +1000 | [diff] [blame] | 574 | |
| 575 | /** |
| 576 | * @param {!KeyboardEvent} ev |
| 577 | * @return {boolean} Return false if xterm.js should not handle the key event. |
| 578 | */ |
| 579 | customKeyEventHandler_(ev) { |
| 580 | const modifiers = (ev.shiftKey ? Modifier.Shift : 0) | |
| 581 | (ev.altKey ? Modifier.Alt : 0) | |
| 582 | (ev.ctrlKey ? Modifier.Ctrl : 0) | |
| 583 | (ev.metaKey ? Modifier.Meta : 0); |
| 584 | const handler = this.keyDownHandlers_.get( |
| 585 | encodeKeyCombo(modifiers, ev.keyCode)); |
| 586 | if (handler) { |
| 587 | if (ev.type === 'keydown') { |
| 588 | handler(ev); |
| 589 | } |
| 590 | return false; |
| 591 | } |
| 592 | |
| 593 | return true; |
| 594 | } |
| 595 | |
| 596 | /** |
| 597 | * A keydown handler for zoom-related keys. |
| 598 | * |
| 599 | * @param {!KeyboardEvent} ev |
| 600 | */ |
| 601 | zoomKeyDownHandler_(ev) { |
| 602 | ev.preventDefault(); |
| 603 | |
| 604 | if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) { |
| 605 | // The only one with a control code. |
| 606 | if (ev.keyCode === keyCodes.MINUS) { |
| 607 | this.io.onVTKeystroke('\x1f'); |
| 608 | } |
| 609 | return; |
| 610 | } |
| 611 | |
| 612 | let newFontSize; |
| 613 | switch (ev.keyCode) { |
| 614 | case keyCodes.ZERO: |
| 615 | newFontSize = this.prefs_.get('font-size'); |
| 616 | break; |
| 617 | case keyCodes.MINUS: |
| 618 | newFontSize = this.term.options.fontSize - 1; |
| 619 | break; |
| 620 | default: |
| 621 | newFontSize = this.term.options.fontSize + 1; |
| 622 | break; |
| 623 | } |
| 624 | |
| 625 | this.updateOption_('fontSize', Math.max(1, newFontSize)); |
| 626 | } |
| 627 | |
| 628 | /** @param {!KeyboardEvent} ev */ |
| 629 | ctrlCKeyDownHandler_(ev) { |
| 630 | ev.preventDefault(); |
| 631 | if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey && |
| 632 | this.term.hasSelection()) { |
| 633 | this.copySelection_(); |
| 634 | return; |
| 635 | } |
| 636 | |
| 637 | this.io.onVTKeystroke('\x03'); |
| 638 | } |
| 639 | |
| 640 | /** @param {!KeyboardEvent} ev */ |
| 641 | ctrlVKeyDownHandler_(ev) { |
| 642 | if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) { |
| 643 | // Don't do anything and let the browser handles the key. |
| 644 | return; |
| 645 | } |
| 646 | |
| 647 | ev.preventDefault(); |
| 648 | this.io.onVTKeystroke('\x16'); |
| 649 | } |
| 650 | |
| 651 | resetKeyDownHandlers_() { |
| 652 | this.keyDownHandlers_.clear(); |
| 653 | |
| 654 | /** |
| 655 | * Don't do anything and let the browser handles the key. |
| 656 | * |
| 657 | * @param {!KeyboardEvent} ev |
| 658 | */ |
| 659 | const noop = (ev) => {}; |
| 660 | |
| 661 | /** |
| 662 | * @param {number} modifiers |
| 663 | * @param {number} keyCode |
| 664 | * @param {function(!KeyboardEvent)} func |
| 665 | */ |
| 666 | const set = (modifiers, keyCode, func) => { |
| 667 | this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode), |
| 668 | func); |
| 669 | }; |
| 670 | |
| 671 | /** |
| 672 | * @param {number} modifiers |
| 673 | * @param {number} keyCode |
| 674 | * @param {function(!KeyboardEvent)} func |
| 675 | */ |
| 676 | const setWithShiftVersion = (modifiers, keyCode, func) => { |
| 677 | set(modifiers, keyCode, func); |
| 678 | set(modifiers | Modifier.Shift, keyCode, func); |
| 679 | }; |
| 680 | |
Jason Lin | f51162f | 2022-09-01 15:21:55 +1000 | [diff] [blame] | 681 | // Temporary shortcut to refresh the rendering in case of rendering errors. |
| 682 | // TODO(lxj): remove after this is fixed: |
| 683 | // https://github.com/xtermjs/xterm.js/issues/3878 |
| 684 | set(Modifier.Ctrl | Modifier.Shift, keyCodes.L, |
| 685 | /** @suppress {missingProperties} */ |
| 686 | () => { |
| 687 | this.scheduleRefreshFont_(); |
| 688 | // Refresh the cursor layer. |
| 689 | if (this.enableWebGL_) { |
| 690 | this.term?._core?._renderService?._renderer?._renderLayers[1] |
| 691 | ?._clearAll(); |
| 692 | } |
| 693 | }, |
| 694 | ); |
Jason Lin | 5690e75 | 2022-08-30 15:36:45 +1000 | [diff] [blame] | 695 | |
| 696 | // Ctrl+/ |
| 697 | set(Modifier.Ctrl, 191, (ev) => { |
| 698 | ev.preventDefault(); |
| 699 | this.io.onVTKeystroke(ctl('_')); |
| 700 | }); |
| 701 | |
| 702 | // Settings page. |
| 703 | set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => { |
| 704 | ev.preventDefault(); |
| 705 | chrome.terminalPrivate.openOptionsPage(() => {}); |
| 706 | }); |
| 707 | |
| 708 | if (this.prefs_.get('keybindings-os-defaults')) { |
| 709 | for (const binding of OS_DEFAULT_BINDINGS) { |
| 710 | this.keyDownHandlers_.set(binding, noop); |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | /** @param {!KeyboardEvent} ev */ |
| 715 | const newWindow = (ev) => { |
| 716 | ev.preventDefault(); |
| 717 | chrome.terminalPrivate.openWindow(); |
| 718 | }; |
| 719 | set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow); |
| 720 | if (this.prefs_.get('pass-ctrl-n')) { |
| 721 | set(Modifier.Ctrl, keyCodes.N, newWindow); |
| 722 | } |
| 723 | |
| 724 | if (this.prefs_.get('pass-ctrl-t')) { |
| 725 | setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop); |
| 726 | } |
| 727 | |
| 728 | if (this.prefs_.get('pass-ctrl-w')) { |
| 729 | setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop); |
| 730 | } |
| 731 | |
| 732 | if (this.prefs_.get('pass-ctrl-tab')) { |
| 733 | setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop); |
| 734 | } |
| 735 | |
| 736 | const passCtrlNumber = this.prefs_.get('pass-ctrl-number'); |
| 737 | |
| 738 | /** |
| 739 | * Set a handler for the key combo ctrl+<number>. |
| 740 | * |
| 741 | * @param {number} number 1 to 9 |
| 742 | * @param {string} controlCode The control code to send if we don't want to |
| 743 | * let the browser to handle it. |
| 744 | */ |
| 745 | const setCtrlNumberHandler = (number, controlCode) => { |
| 746 | let func = noop; |
| 747 | if (!passCtrlNumber) { |
| 748 | func = (ev) => { |
| 749 | ev.preventDefault(); |
| 750 | this.io.onVTKeystroke(controlCode); |
| 751 | }; |
| 752 | } |
| 753 | set(Modifier.Ctrl, keyCodes.ZERO + number, func); |
| 754 | }; |
| 755 | |
| 756 | setCtrlNumberHandler(1, '1'); |
| 757 | setCtrlNumberHandler(2, ctl('@')); |
| 758 | setCtrlNumberHandler(3, ctl('[')); |
| 759 | setCtrlNumberHandler(4, ctl('\\')); |
| 760 | setCtrlNumberHandler(5, ctl(']')); |
| 761 | setCtrlNumberHandler(6, ctl('^')); |
| 762 | setCtrlNumberHandler(7, ctl('_')); |
| 763 | setCtrlNumberHandler(8, '\x7f'); |
| 764 | setCtrlNumberHandler(9, '9'); |
| 765 | |
| 766 | if (this.prefs_.get('pass-alt-number')) { |
| 767 | for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) { |
| 768 | set(Modifier.Alt, keyCode, noop); |
| 769 | } |
| 770 | } |
| 771 | |
| 772 | for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) { |
| 773 | setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_); |
| 774 | } |
| 775 | |
| 776 | setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_); |
| 777 | setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_); |
| 778 | } |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 779 | } |
| 780 | |
Jason Lin | d66e6bf | 2022-08-22 14:47:10 +1000 | [diff] [blame] | 781 | class HtermTerminal extends hterm.Terminal { |
| 782 | /** @override */ |
| 783 | decorate(div) { |
| 784 | super.decorate(div); |
| 785 | |
| 786 | const fontManager = new FontManager(this.getDocument()); |
| 787 | fontManager.loadPowerlineCSS().then(() => { |
| 788 | const prefs = this.getPrefs(); |
| 789 | fontManager.loadFont(/** @type {string} */(prefs.get('font-family'))); |
| 790 | prefs.addObserver( |
| 791 | 'font-family', |
| 792 | (v) => fontManager.loadFont(/** @type {string} */(v))); |
| 793 | }); |
| 794 | } |
| 795 | } |
| 796 | |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 797 | /** |
| 798 | * Constructs and returns a `hterm.Terminal` or a compatible one based on the |
| 799 | * preference value. |
| 800 | * |
| 801 | * @param {{ |
| 802 | * storage: !lib.Storage, |
| 803 | * profileId: string, |
| 804 | * }} args |
| 805 | * @return {!Promise<!hterm.Terminal>} |
| 806 | */ |
| 807 | export async function createEmulator({storage, profileId}) { |
| 808 | let config = TERMINAL_EMULATORS.get('hterm'); |
| 809 | |
| 810 | if (getOSInfo().alternative_emulator) { |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 811 | // TODO: remove the url param logic. This is temporary to make manual |
| 812 | // testing a bit easier, which is also why this is not in |
| 813 | // './js/terminal_info.js'. |
| 814 | const emulator = ORIGINAL_URL.searchParams.get('emulator') || |
| 815 | await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`); |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 816 | // Use the default (i.e. first) one if the pref is not set or invalid. |
Jason Lin | 21d854f | 2022-08-22 14:49:59 +1000 | [diff] [blame] | 817 | config = TERMINAL_EMULATORS.get(emulator) || |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 818 | TERMINAL_EMULATORS.values().next().value; |
| 819 | console.log('Terminal emulator config: ', config); |
| 820 | } |
| 821 | |
| 822 | switch (config.lib) { |
| 823 | case 'xterm.js': |
| 824 | { |
| 825 | const terminal = new XtermTerminal({ |
| 826 | storage, |
| 827 | profileId, |
| 828 | enableWebGL: config.webgl, |
| 829 | }); |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 830 | return terminal; |
| 831 | } |
| 832 | case 'hterm': |
Jason Lin | d66e6bf | 2022-08-22 14:47:10 +1000 | [diff] [blame] | 833 | return new HtermTerminal({profileId, storage}); |
Jason Lin | ca61ffb | 2022-08-03 19:37:12 +1000 | [diff] [blame] | 834 | default: |
| 835 | throw new Error('incorrect emulator config'); |
| 836 | } |
| 837 | } |
| 838 | |
Jason Lin | 6a402a7 | 2022-08-25 16:07:02 +1000 | [diff] [blame] | 839 | class TerminalCopyNotice extends LitElement { |
| 840 | /** @override */ |
| 841 | static get styles() { |
| 842 | return css` |
| 843 | :host { |
| 844 | display: block; |
| 845 | text-align: center; |
| 846 | } |
| 847 | |
| 848 | svg { |
| 849 | fill: currentColor; |
| 850 | } |
| 851 | `; |
| 852 | } |
| 853 | |
| 854 | /** @override */ |
| 855 | render() { |
| 856 | return html` |
| 857 | ${ICON_COPY} |
| 858 | <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div> |
| 859 | `; |
| 860 | } |
| 861 | } |
| 862 | |
| 863 | customElements.define('terminal-copy-notice', TerminalCopyNotice); |