blob: c346cc9512ce1644042481fe77f7d758e0be08b4 [file] [log] [blame]
Jason Lind66e6bf2022-08-22 14:47:10 +10001// 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 Linca61ffb2022-08-03 19:37:12 +10005/**
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 Lin6a402a72022-08-25 16:07:02 +100012import {LitElement, css, html} from './lit.js';
Jason Lin21d854f2022-08-22 14:49:59 +100013import {FontManager, ORIGINAL_URL, TERMINAL_EMULATORS, delayedScheduler,
14 fontManager, getOSInfo, sleep} from './terminal_common.js';
Jason Lin6a402a72022-08-25 16:07:02 +100015import {ICON_COPY} from './terminal_icons.js';
Jason Lin4de4f382022-09-01 14:10:18 +100016import {FitAddon, Terminal, Unicode11Addon, WebLinksAddon, WebglAddon}
17 from './xterm.js';
Jason Linca61ffb2022-08-03 19:37:12 +100018
Jason Lin5690e752022-08-30 15:36:45 +100019
20/** @enum {number} */
21export 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.
30const 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 */
39export function encodeKeyCombo(modifiers, keyCode) {
40 return keyCode << 4 | modifiers;
41}
42
43const 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 Linca61ffb2022-08-03 19:37:12 +100061const 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
80const PrefToXtermOptions = {
81 'font-family': 'fontFamily',
Jason Linca61ffb2022-08-03 19:37:12 +100082};
83
84/**
Jason Linabad7562022-08-22 14:49:05 +100085 * @typedef {{
86 * term: !Terminal,
87 * fontManager: !FontManager,
88 * fitAddon: !FitAddon,
89 * }}
90 */
91export let XtermTerminalTestParams;
92
93/**
Jason Lin5690e752022-08-30 15:36:45 +100094 * Compute a control character for a given character.
95 *
96 * @param {string} ch
97 * @return {string}
98 */
99function ctl(ch) {
100 return String.fromCharCode(ch.charCodeAt(0) - 64);
101}
102
103/**
Jason Lin21d854f2022-08-22 14:49:59 +1000104 * 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 */
108class 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 Linca61ffb2022-08-03 19:37:12 +1000141 * 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 Linca61ffb2022-08-03 19:37:12 +1000144 * @extends {hterm.Terminal}
145 * @unrestricted
146 */
Jason Linabad7562022-08-22 14:49:05 +1000147export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000148 /**
149 * @param {{
150 * storage: !lib.Storage,
151 * profileId: string,
152 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000153 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000154 * }} args
155 */
Jason Linabad7562022-08-22 14:49:05 +1000156 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000157 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
158 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
159 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
160
Jason Lin21d854f2022-08-22 14:49:59 +1000161 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000162 /** @type {!hterm.PreferenceManager} */
163 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
164 this.enableWebGL_ = enableWebGL;
165
Jason Lin5690e752022-08-30 15:36:45 +1000166 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linabad7562022-08-22 14:49:05 +1000167 this.term = testParams?.term || new Terminal();
168 this.fontManager_ = testParams?.fontManager || fontManager;
169 this.fitAddon = testParams?.fitAddon || new FitAddon();
170
Jason Linca61ffb2022-08-03 19:37:12 +1000171 this.term.loadAddon(this.fitAddon);
Jason Linabad7562022-08-22 14:49:05 +1000172 this.scheduleFit_ = delayedScheduler(() => this.fitAddon.fit(),
173 testParams ? 0 : 250);
174
Jason Lin4de4f382022-09-01 14:10:18 +1000175 this.term.loadAddon(new WebLinksAddon());
176 this.term.loadAddon(new Unicode11Addon());
177 this.term.unicode.activeVersion = '11';
178
Jason Linabad7562022-08-22 14:49:05 +1000179 this.pendingFont_ = null;
180 this.scheduleRefreshFont_ = delayedScheduler(
181 () => this.refreshFont_(), 100);
182 document.fonts.addEventListener('loadingdone',
183 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000184
185 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000186 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000187
Jason Lin21d854f2022-08-22 14:49:59 +1000188 this.term.onResize(({cols, rows}) => this.io.onTerminalResize(cols, rows));
189 // We could also use `this.io.sendString()` except for the nassh exit
190 // prompt, which only listens to onVTKeystroke().
191 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin6a402a72022-08-25 16:07:02 +1000192 this.term.onTitleChange((title) => document.title = title);
Jason Lin5690e752022-08-30 15:36:45 +1000193 this.term.onSelectionChange(() => this.copySelection_());
194
195 /**
196 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
197 *
198 * If a key combo is in the map:
199 *
200 * - The handler instead of xterm.js will handle the keydown event.
201 * - Keyup and keypress will be ignored by both us and xterm.js.
202 *
203 * We re-generate this map every time a relevant pref value is changed. This
204 * is ok because pref changes are rare.
205 *
206 * @type {!Map<number, function(!KeyboardEvent)>}
207 */
208 this.keyDownHandlers_ = new Map();
209 this.scheduleResetKeyDownHandlers_ =
210 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
211
212 this.term.attachCustomKeyEventHandler(
213 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000214
Jason Lin21d854f2022-08-22 14:49:59 +1000215 this.io = new XtermTerminalIO(this);
216 this.notificationCenter_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000217
218 this.copyNotice_ = null;
219
220 this.term.options.theme = {
221 selection: 'rgba(174, 203, 250, .6)',
222 selectionForeground: 'black',
223 customGlyphs: true,
224 };
225 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000226 }
227
228 /**
229 * Install stubs for stuff that we haven't implemented yet so that the code
230 * still runs.
231 */
232 installUnimplementedStubs_() {
233 this.keyboard = {
234 keyMap: {
235 keyDefs: [],
236 },
237 bindings: {
238 clear: () => {},
239 addBinding: () => {},
240 addBindings: () => {},
241 OsDefaults: {},
242 },
243 };
244 this.keyboard.keyMap.keyDefs[78] = {};
245
246 const methodNames = [
Jason Linca61ffb2022-08-03 19:37:12 +1000247 'setAccessibilityEnabled',
248 'setBackgroundImage',
249 'setCursorPosition',
250 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000251 ];
252
253 for (const name of methodNames) {
254 this[name] = () => console.warn(`${name}() is not implemented`);
255 }
256
257 this.contextMenu = {
258 setItems: () => {
259 console.warn('.contextMenu.setItems() is not implemented');
260 },
261 };
Jason Lin21d854f2022-08-22 14:49:59 +1000262
263 this.vt = {
264 resetParseState: () => {
265 console.warn('.vt.resetParseState() is not implemented');
266 },
267 };
Jason Linca61ffb2022-08-03 19:37:12 +1000268 }
269
Jason Line9231bc2022-09-01 13:54:02 +1000270 installEscapeSequenceHandlers_() {
271 // OSC 52 for copy.
272 this.term.parser.registerOscHandler(52, (args) => {
273 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
274 // parameter is used to select which of the X clipboards to address. Since
275 // we're not integrating with X, we treat them all the same.
276 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
277 if (!parsedArgs) {
278 return true;
279 }
280
281 let data;
282 try {
283 data = window.atob(parsedArgs[1]);
284 } catch (e) {
285 // If the user sent us invalid base64 content, silently ignore it.
286 return true;
287 }
288 const decoder = new TextDecoder();
289 const bytes = lib.codec.stringToCodeUnitArray(data);
290 this.copyString_(decoder.decode(bytes));
291
292 return true;
293 });
294 }
295
Jason Linca61ffb2022-08-03 19:37:12 +1000296 /**
297 * One-time initialization at the beginning.
298 */
299 async init() {
300 await new Promise((resolve) => this.prefs_.readStorage(resolve));
301 this.prefs_.notifyAll();
302 this.onTerminalReady();
303 }
304
Jason Lin21d854f2022-08-22 14:49:59 +1000305 /**
306 * Write data to the terminal.
307 *
308 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
309 * UTF-8 data
310 */
311 write(data) {
312 this.term.write(data);
313 }
314
315 /**
316 * Like `this.write()` but also write a line break.
317 *
318 * @param {string|!Uint8Array} data
319 */
320 writeln(data) {
321 this.term.writeln(data);
322 }
323
Jason Linca61ffb2022-08-03 19:37:12 +1000324 get screenSize() {
325 return new hterm.Size(this.term.cols, this.term.rows);
326 }
327
328 /**
329 * Don't need to do anything.
330 *
331 * @override
332 */
333 installKeyboard() {}
334
335 /**
336 * @override
337 */
338 decorate(elem) {
339 this.term.open(elem);
Jason Lind04bab32022-08-22 14:48:39 +1000340 this.scheduleFit_();
Jason Linca61ffb2022-08-03 19:37:12 +1000341 if (this.enableWebGL_) {
342 this.term.loadAddon(new WebglAddon());
343 }
Jason Lin21d854f2022-08-22 14:49:59 +1000344 this.term.focus();
Jason Lind04bab32022-08-22 14:48:39 +1000345 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lin21d854f2022-08-22 14:49:59 +1000346 // TODO: Make a11y work. Maybe we can just use `hterm.AccessibilityReader`.
347 this.notificationCenter_ = new hterm.NotificationCenter(document.body);
348 }
349
350 /** @override */
351 showOverlay(msg, timeout = 1500) {
352 if (this.notificationCenter_) {
353 this.notificationCenter_.show(msg, {timeout});
354 }
355 }
356
357 /** @override */
358 hideOverlay() {
359 if (this.notificationCenter_) {
360 this.notificationCenter_.hide();
361 }
Jason Linca61ffb2022-08-03 19:37:12 +1000362 }
363
364 /** @override */
365 getPrefs() {
366 return this.prefs_;
367 }
368
369 /** @override */
370 getDocument() {
371 return window.document;
372 }
373
Jason Lin21d854f2022-08-22 14:49:59 +1000374 /** @override */
375 reset() {
376 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000377 }
378
379 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000380 setProfile(profileId, callback = undefined) {
381 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000382 }
383
Jason Lin21d854f2022-08-22 14:49:59 +1000384 /** @override */
385 interpret(string) {
386 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000387 }
388
Jason Lin21d854f2022-08-22 14:49:59 +1000389 /** @override */
390 focus() {
391 this.term.focus();
392 }
Jason Linca61ffb2022-08-03 19:37:12 +1000393
394 /** @override */
395 onOpenOptionsPage() {}
396
397 /** @override */
398 onTerminalReady() {}
399
Jason Lind04bab32022-08-22 14:48:39 +1000400 observePrefs_() {
401 for (const pref in PrefToXtermOptions) {
402 this.prefs_.addObserver(pref, (v) => {
403 this.updateOption_(PrefToXtermOptions[pref], v);
404 });
405 }
406
Jason Lin21d854f2022-08-22 14:49:59 +1000407 // This is for this.notificationCenter_.
408 const setHtermCSSVariable = (name, value) => {
409 document.body.style.setProperty(`--hterm-${name}`, value);
410 };
411
412 const setHtermColorCSSVariable = (name, color) => {
413 const css = lib.notNull(lib.colors.normalizeCSS(color));
414 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
415 setHtermCSSVariable(name, rgb);
416 };
417
418 this.prefs_.addObserver('font-size', (v) => {
419 this.updateOption_('fontSize', v);
420 setHtermCSSVariable('font-size', `${v}px`);
421 });
422
Jason Lind04bab32022-08-22 14:48:39 +1000423 // Theme-related preference items.
424 this.prefs_.addObservers(null, {
425 'background-color': (v) => {
426 this.updateTheme_({background: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000427 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000428 },
429 'foreground-color': (v) => {
430 this.updateTheme_({foreground: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000431 setHtermColorCSSVariable('foreground-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000432 },
433 'cursor-color': (v) => {
434 this.updateTheme_({cursor: v});
435 },
436 'color-palette-overrides': (v) => {
437 if (!(v instanceof Array)) {
438 // For terminal, we always expect this to be an array.
439 console.warn('unexpected color palette: ', v);
440 return;
441 }
442 const colors = {};
443 for (let i = 0; i < v.length; ++i) {
444 colors[ANSI_COLOR_NAMES[i]] = v[i];
445 }
446 this.updateTheme_(colors);
447 },
448 });
Jason Lin5690e752022-08-30 15:36:45 +1000449
450 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
451 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
452 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
453 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
454 }
Jason Lind04bab32022-08-22 14:48:39 +1000455 }
456
457 /**
458 * @param {!Object} theme
459 */
460 updateTheme_(theme) {
461 const newTheme = {...this.term.options.theme};
462 for (const key in theme) {
463 newTheme[key] = lib.colors.normalizeCSS(theme[key]);
464 }
465 this.updateOption_('theme', newTheme);
466 }
467
468 /**
469 * Update one xterm.js option.
470 *
471 * @param {string} key
472 * @param {*} value
473 */
474 updateOption_(key, value) {
Jason Linabad7562022-08-22 14:49:05 +1000475 if (key === 'fontFamily') {
476 this.updateFont_(/** @type {string} */(value));
477 return;
478 }
Jason Lind04bab32022-08-22 14:48:39 +1000479 // TODO: xterm supports updating multiple options at the same time. We
480 // should probably do that.
481 this.term.options[key] = value;
482 this.scheduleFit_();
483 }
Jason Linabad7562022-08-22 14:49:05 +1000484
485 /**
486 * Called when there is a "fontloadingdone" event. We need this because
487 * `FontManager.loadFont()` does not guarantee loading all the font files.
488 */
489 async onFontLoadingDone_() {
490 // If there is a pending font, the font is going to be refresh soon, so we
491 // don't need to do anything.
492 if (!this.pendingFont_) {
493 this.scheduleRefreshFont_();
494 }
495 }
496
Jason Lin5690e752022-08-30 15:36:45 +1000497 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000498 this.copyString_(this.term.getSelection());
499 }
500
501 /** @param {string} data */
502 copyString_(data) {
503 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000504 return;
505 }
Jason Line9231bc2022-09-01 13:54:02 +1000506 navigator.clipboard?.writeText(data);
Jason Lin6a402a72022-08-25 16:07:02 +1000507 if (!this.copyNotice_) {
508 this.copyNotice_ = document.createElement('terminal-copy-notice');
509 }
510 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200);
511 }
512
Jason Linabad7562022-08-22 14:49:05 +1000513 /**
514 * Refresh xterm rendering for a font related event.
515 */
516 refreshFont_() {
517 // We have to set the fontFamily option to a different string to trigger the
518 // re-rendering. Appending a space at the end seems to be the easiest
519 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
520 // us.
521 //
522 // TODO: Report a bug to xterm.js and ask for exposing a public function for
523 // the refresh so that we don't need to do this hack.
524 this.term.options.fontFamily += ' ';
525 }
526
527 /**
528 * Update a font.
529 *
530 * @param {string} cssFontFamily
531 */
532 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000533 this.pendingFont_ = cssFontFamily;
534 await this.fontManager_.loadFont(cssFontFamily);
535 // Sleep a bit to wait for flushing fontloadingdone events. This is not
536 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
537 // to refresh font unnecessarily in some cases.
538 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000539
Jason Lin6a402a72022-08-25 16:07:02 +1000540 if (this.pendingFont_ !== cssFontFamily) {
541 // `updateFont_()` probably is called again. Abort what we are doing.
542 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
543 ` (expecting ${cssFontFamily})`);
544 return;
545 }
Jason Linabad7562022-08-22 14:49:05 +1000546
Jason Lin6a402a72022-08-25 16:07:02 +1000547 if (this.term.options.fontFamily !== cssFontFamily) {
548 this.term.options.fontFamily = cssFontFamily;
549 } else {
550 // If the font is already the same, refresh font just to be safe.
551 this.refreshFont_();
552 }
553 this.pendingFont_ = null;
554 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000555 }
Jason Lin5690e752022-08-30 15:36:45 +1000556
557 /**
558 * @param {!KeyboardEvent} ev
559 * @return {boolean} Return false if xterm.js should not handle the key event.
560 */
561 customKeyEventHandler_(ev) {
562 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
563 (ev.altKey ? Modifier.Alt : 0) |
564 (ev.ctrlKey ? Modifier.Ctrl : 0) |
565 (ev.metaKey ? Modifier.Meta : 0);
566 const handler = this.keyDownHandlers_.get(
567 encodeKeyCombo(modifiers, ev.keyCode));
568 if (handler) {
569 if (ev.type === 'keydown') {
570 handler(ev);
571 }
572 return false;
573 }
574
575 return true;
576 }
577
578 /**
579 * A keydown handler for zoom-related keys.
580 *
581 * @param {!KeyboardEvent} ev
582 */
583 zoomKeyDownHandler_(ev) {
584 ev.preventDefault();
585
586 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
587 // The only one with a control code.
588 if (ev.keyCode === keyCodes.MINUS) {
589 this.io.onVTKeystroke('\x1f');
590 }
591 return;
592 }
593
594 let newFontSize;
595 switch (ev.keyCode) {
596 case keyCodes.ZERO:
597 newFontSize = this.prefs_.get('font-size');
598 break;
599 case keyCodes.MINUS:
600 newFontSize = this.term.options.fontSize - 1;
601 break;
602 default:
603 newFontSize = this.term.options.fontSize + 1;
604 break;
605 }
606
607 this.updateOption_('fontSize', Math.max(1, newFontSize));
608 }
609
610 /** @param {!KeyboardEvent} ev */
611 ctrlCKeyDownHandler_(ev) {
612 ev.preventDefault();
613 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
614 this.term.hasSelection()) {
615 this.copySelection_();
616 return;
617 }
618
619 this.io.onVTKeystroke('\x03');
620 }
621
622 /** @param {!KeyboardEvent} ev */
623 ctrlVKeyDownHandler_(ev) {
624 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
625 // Don't do anything and let the browser handles the key.
626 return;
627 }
628
629 ev.preventDefault();
630 this.io.onVTKeystroke('\x16');
631 }
632
633 resetKeyDownHandlers_() {
634 this.keyDownHandlers_.clear();
635
636 /**
637 * Don't do anything and let the browser handles the key.
638 *
639 * @param {!KeyboardEvent} ev
640 */
641 const noop = (ev) => {};
642
643 /**
644 * @param {number} modifiers
645 * @param {number} keyCode
646 * @param {function(!KeyboardEvent)} func
647 */
648 const set = (modifiers, keyCode, func) => {
649 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
650 func);
651 };
652
653 /**
654 * @param {number} modifiers
655 * @param {number} keyCode
656 * @param {function(!KeyboardEvent)} func
657 */
658 const setWithShiftVersion = (modifiers, keyCode, func) => {
659 set(modifiers, keyCode, func);
660 set(modifiers | Modifier.Shift, keyCode, func);
661 };
662
Jason Linf51162f2022-09-01 15:21:55 +1000663 // Temporary shortcut to refresh the rendering in case of rendering errors.
664 // TODO(lxj): remove after this is fixed:
665 // https://github.com/xtermjs/xterm.js/issues/3878
666 set(Modifier.Ctrl | Modifier.Shift, keyCodes.L,
667 /** @suppress {missingProperties} */
668 () => {
669 this.scheduleRefreshFont_();
670 // Refresh the cursor layer.
671 if (this.enableWebGL_) {
672 this.term?._core?._renderService?._renderer?._renderLayers[1]
673 ?._clearAll();
674 }
675 },
676 );
Jason Lin5690e752022-08-30 15:36:45 +1000677
678 // Ctrl+/
679 set(Modifier.Ctrl, 191, (ev) => {
680 ev.preventDefault();
681 this.io.onVTKeystroke(ctl('_'));
682 });
683
684 // Settings page.
685 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
686 ev.preventDefault();
687 chrome.terminalPrivate.openOptionsPage(() => {});
688 });
689
690 if (this.prefs_.get('keybindings-os-defaults')) {
691 for (const binding of OS_DEFAULT_BINDINGS) {
692 this.keyDownHandlers_.set(binding, noop);
693 }
694 }
695
696 /** @param {!KeyboardEvent} ev */
697 const newWindow = (ev) => {
698 ev.preventDefault();
699 chrome.terminalPrivate.openWindow();
700 };
701 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
702 if (this.prefs_.get('pass-ctrl-n')) {
703 set(Modifier.Ctrl, keyCodes.N, newWindow);
704 }
705
706 if (this.prefs_.get('pass-ctrl-t')) {
707 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
708 }
709
710 if (this.prefs_.get('pass-ctrl-w')) {
711 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
712 }
713
714 if (this.prefs_.get('pass-ctrl-tab')) {
715 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
716 }
717
718 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
719
720 /**
721 * Set a handler for the key combo ctrl+<number>.
722 *
723 * @param {number} number 1 to 9
724 * @param {string} controlCode The control code to send if we don't want to
725 * let the browser to handle it.
726 */
727 const setCtrlNumberHandler = (number, controlCode) => {
728 let func = noop;
729 if (!passCtrlNumber) {
730 func = (ev) => {
731 ev.preventDefault();
732 this.io.onVTKeystroke(controlCode);
733 };
734 }
735 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
736 };
737
738 setCtrlNumberHandler(1, '1');
739 setCtrlNumberHandler(2, ctl('@'));
740 setCtrlNumberHandler(3, ctl('['));
741 setCtrlNumberHandler(4, ctl('\\'));
742 setCtrlNumberHandler(5, ctl(']'));
743 setCtrlNumberHandler(6, ctl('^'));
744 setCtrlNumberHandler(7, ctl('_'));
745 setCtrlNumberHandler(8, '\x7f');
746 setCtrlNumberHandler(9, '9');
747
748 if (this.prefs_.get('pass-alt-number')) {
749 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
750 set(Modifier.Alt, keyCode, noop);
751 }
752 }
753
754 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
755 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
756 }
757
758 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
759 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
760 }
Jason Linca61ffb2022-08-03 19:37:12 +1000761}
762
Jason Lind66e6bf2022-08-22 14:47:10 +1000763class HtermTerminal extends hterm.Terminal {
764 /** @override */
765 decorate(div) {
766 super.decorate(div);
767
768 const fontManager = new FontManager(this.getDocument());
769 fontManager.loadPowerlineCSS().then(() => {
770 const prefs = this.getPrefs();
771 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
772 prefs.addObserver(
773 'font-family',
774 (v) => fontManager.loadFont(/** @type {string} */(v)));
775 });
776 }
777}
778
Jason Linca61ffb2022-08-03 19:37:12 +1000779/**
780 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
781 * preference value.
782 *
783 * @param {{
784 * storage: !lib.Storage,
785 * profileId: string,
786 * }} args
787 * @return {!Promise<!hterm.Terminal>}
788 */
789export async function createEmulator({storage, profileId}) {
790 let config = TERMINAL_EMULATORS.get('hterm');
791
792 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +1000793 // TODO: remove the url param logic. This is temporary to make manual
794 // testing a bit easier, which is also why this is not in
795 // './js/terminal_info.js'.
796 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
797 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +1000798 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +1000799 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +1000800 TERMINAL_EMULATORS.values().next().value;
801 console.log('Terminal emulator config: ', config);
802 }
803
804 switch (config.lib) {
805 case 'xterm.js':
806 {
807 const terminal = new XtermTerminal({
808 storage,
809 profileId,
810 enableWebGL: config.webgl,
811 });
812 // Don't await it so that the caller can override
813 // `terminal.onTerminalReady()` before the terminal is ready.
814 terminal.init();
815 return terminal;
816 }
817 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +1000818 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +1000819 default:
820 throw new Error('incorrect emulator config');
821 }
822}
823
Jason Lin6a402a72022-08-25 16:07:02 +1000824class TerminalCopyNotice extends LitElement {
825 /** @override */
826 static get styles() {
827 return css`
828 :host {
829 display: block;
830 text-align: center;
831 }
832
833 svg {
834 fill: currentColor;
835 }
836 `;
837 }
838
839 /** @override */
840 render() {
841 return html`
842 ${ICON_COPY}
843 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
844 `;
845 }
846}
847
848customElements.define('terminal-copy-notice', TerminalCopyNotice);