blob: 4568fdc4d4d84ec977813b4ceede4a041e862236 [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';
16import {Terminal, FitAddon, WebglAddon} from './xterm.js';
Jason Linca61ffb2022-08-03 19:37:12 +100017
Jason Lin5690e752022-08-30 15:36:45 +100018
19/** @enum {number} */
20export const Modifier = {
21 Shift: 1 << 0,
22 Alt: 1 << 1,
23 Ctrl: 1 << 2,
24 Meta: 1 << 3,
25};
26
27// This is just a static map from key names to key codes. It helps make the code
28// a bit more readable.
29const keyCodes = hterm.Parser.identifiers.keyCodes;
30
31/**
32 * Encode a key combo (i.e. modifiers + a normal key) to an unique number.
33 *
34 * @param {number} modifiers
35 * @param {number} keyCode
36 * @return {number}
37 */
38export function encodeKeyCombo(modifiers, keyCode) {
39 return keyCode << 4 | modifiers;
40}
41
42const OS_DEFAULT_BINDINGS = [
43 // Submit feedback.
44 encodeKeyCombo(Modifier.Alt | Modifier.Shift, keyCodes.I),
45 // Toggle chromevox.
46 encodeKeyCombo(Modifier.Ctrl | Modifier.Alt, keyCodes.Z),
47 // Switch input method.
48 encodeKeyCombo(Modifier.Ctrl, keyCodes.SPACE),
49
50 // Dock window left/right.
51 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_LEFT),
52 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_RIGHT),
53
54 // Maximize/minimize window.
55 encodeKeyCombo(Modifier.Alt, keyCodes.EQUAL),
56 encodeKeyCombo(Modifier.Alt, keyCodes.MINUS),
57];
58
59
Jason Linca61ffb2022-08-03 19:37:12 +100060const ANSI_COLOR_NAMES = [
61 'black',
62 'red',
63 'green',
64 'yellow',
65 'blue',
66 'magenta',
67 'cyan',
68 'white',
69 'brightBlack',
70 'brightRed',
71 'brightGreen',
72 'brightYellow',
73 'brightBlue',
74 'brightMagenta',
75 'brightCyan',
76 'brightWhite',
77];
78
79const PrefToXtermOptions = {
80 'font-family': 'fontFamily',
Jason Linca61ffb2022-08-03 19:37:12 +100081};
82
83/**
Jason Linabad7562022-08-22 14:49:05 +100084 * @typedef {{
85 * term: !Terminal,
86 * fontManager: !FontManager,
87 * fitAddon: !FitAddon,
88 * }}
89 */
90export let XtermTerminalTestParams;
91
92/**
Jason Lin5690e752022-08-30 15:36:45 +100093 * Compute a control character for a given character.
94 *
95 * @param {string} ch
96 * @return {string}
97 */
98function ctl(ch) {
99 return String.fromCharCode(ch.charCodeAt(0) - 64);
100}
101
102/**
Jason Lin21d854f2022-08-22 14:49:59 +1000103 * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO
104 * because it always convert utf8 data to strings, which is not necessary for
105 * xterm.
106 */
107class XtermTerminalIO extends hterm.Terminal.IO {
108 /** @override */
109 writeUTF8(buffer) {
110 this.terminal_.write(new Uint8Array(buffer));
111 }
112
113 /** @override */
114 writelnUTF8(buffer) {
115 this.terminal_.writeln(new Uint8Array(buffer));
116 }
117
118 /** @override */
119 print(string) {
120 this.terminal_.write(string);
121 }
122
123 /** @override */
124 writeUTF16(string) {
125 this.print(string);
126 }
127
128 /** @override */
129 println(string) {
130 this.terminal_.writeln(string);
131 }
132
133 /** @override */
134 writelnUTF16(string) {
135 this.println(string);
136 }
137}
138
139/**
Jason Linca61ffb2022-08-03 19:37:12 +1000140 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
141 * so that it can be used in existing code.
142 *
Jason Linca61ffb2022-08-03 19:37:12 +1000143 * @extends {hterm.Terminal}
144 * @unrestricted
145 */
Jason Linabad7562022-08-22 14:49:05 +1000146export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000147 /**
148 * @param {{
149 * storage: !lib.Storage,
150 * profileId: string,
151 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000152 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000153 * }} args
154 */
Jason Linabad7562022-08-22 14:49:05 +1000155 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000156 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
157 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
158 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
159
Jason Lin21d854f2022-08-22 14:49:59 +1000160 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000161 /** @type {!hterm.PreferenceManager} */
162 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
163 this.enableWebGL_ = enableWebGL;
164
Jason Lin5690e752022-08-30 15:36:45 +1000165 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linabad7562022-08-22 14:49:05 +1000166 this.term = testParams?.term || new Terminal();
167 this.fontManager_ = testParams?.fontManager || fontManager;
168 this.fitAddon = testParams?.fitAddon || new FitAddon();
169
Jason Linca61ffb2022-08-03 19:37:12 +1000170 this.term.loadAddon(this.fitAddon);
Jason Linabad7562022-08-22 14:49:05 +1000171 this.scheduleFit_ = delayedScheduler(() => this.fitAddon.fit(),
172 testParams ? 0 : 250);
173
174 this.pendingFont_ = null;
175 this.scheduleRefreshFont_ = delayedScheduler(
176 () => this.refreshFont_(), 100);
177 document.fonts.addEventListener('loadingdone',
178 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000179
180 this.installUnimplementedStubs_();
181
Jason Lin21d854f2022-08-22 14:49:59 +1000182 this.term.onResize(({cols, rows}) => this.io.onTerminalResize(cols, rows));
183 // We could also use `this.io.sendString()` except for the nassh exit
184 // prompt, which only listens to onVTKeystroke().
185 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin6a402a72022-08-25 16:07:02 +1000186 this.term.onTitleChange((title) => document.title = title);
Jason Lin5690e752022-08-30 15:36:45 +1000187 this.term.onSelectionChange(() => this.copySelection_());
188
189 /**
190 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
191 *
192 * If a key combo is in the map:
193 *
194 * - The handler instead of xterm.js will handle the keydown event.
195 * - Keyup and keypress will be ignored by both us and xterm.js.
196 *
197 * We re-generate this map every time a relevant pref value is changed. This
198 * is ok because pref changes are rare.
199 *
200 * @type {!Map<number, function(!KeyboardEvent)>}
201 */
202 this.keyDownHandlers_ = new Map();
203 this.scheduleResetKeyDownHandlers_ =
204 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
205
206 this.term.attachCustomKeyEventHandler(
207 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000208
Jason Lin21d854f2022-08-22 14:49:59 +1000209 this.io = new XtermTerminalIO(this);
210 this.notificationCenter_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000211
212 this.copyNotice_ = null;
213
214 this.term.options.theme = {
215 selection: 'rgba(174, 203, 250, .6)',
216 selectionForeground: 'black',
217 customGlyphs: true,
218 };
219 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000220 }
221
222 /**
223 * Install stubs for stuff that we haven't implemented yet so that the code
224 * still runs.
225 */
226 installUnimplementedStubs_() {
227 this.keyboard = {
228 keyMap: {
229 keyDefs: [],
230 },
231 bindings: {
232 clear: () => {},
233 addBinding: () => {},
234 addBindings: () => {},
235 OsDefaults: {},
236 },
237 };
238 this.keyboard.keyMap.keyDefs[78] = {};
239
240 const methodNames = [
Jason Linca61ffb2022-08-03 19:37:12 +1000241 'setAccessibilityEnabled',
242 'setBackgroundImage',
243 'setCursorPosition',
244 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000245 ];
246
247 for (const name of methodNames) {
248 this[name] = () => console.warn(`${name}() is not implemented`);
249 }
250
251 this.contextMenu = {
252 setItems: () => {
253 console.warn('.contextMenu.setItems() is not implemented');
254 },
255 };
Jason Lin21d854f2022-08-22 14:49:59 +1000256
257 this.vt = {
258 resetParseState: () => {
259 console.warn('.vt.resetParseState() is not implemented');
260 },
261 };
Jason Linca61ffb2022-08-03 19:37:12 +1000262 }
263
264 /**
265 * One-time initialization at the beginning.
266 */
267 async init() {
268 await new Promise((resolve) => this.prefs_.readStorage(resolve));
269 this.prefs_.notifyAll();
270 this.onTerminalReady();
271 }
272
Jason Lin21d854f2022-08-22 14:49:59 +1000273 /**
274 * Write data to the terminal.
275 *
276 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
277 * UTF-8 data
278 */
279 write(data) {
280 this.term.write(data);
281 }
282
283 /**
284 * Like `this.write()` but also write a line break.
285 *
286 * @param {string|!Uint8Array} data
287 */
288 writeln(data) {
289 this.term.writeln(data);
290 }
291
Jason Linca61ffb2022-08-03 19:37:12 +1000292 get screenSize() {
293 return new hterm.Size(this.term.cols, this.term.rows);
294 }
295
296 /**
297 * Don't need to do anything.
298 *
299 * @override
300 */
301 installKeyboard() {}
302
303 /**
304 * @override
305 */
306 decorate(elem) {
307 this.term.open(elem);
Jason Lind04bab32022-08-22 14:48:39 +1000308 this.scheduleFit_();
Jason Linca61ffb2022-08-03 19:37:12 +1000309 if (this.enableWebGL_) {
310 this.term.loadAddon(new WebglAddon());
311 }
Jason Lin21d854f2022-08-22 14:49:59 +1000312 this.term.focus();
Jason Lind04bab32022-08-22 14:48:39 +1000313 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lin21d854f2022-08-22 14:49:59 +1000314 // TODO: Make a11y work. Maybe we can just use `hterm.AccessibilityReader`.
315 this.notificationCenter_ = new hterm.NotificationCenter(document.body);
316 }
317
318 /** @override */
319 showOverlay(msg, timeout = 1500) {
320 if (this.notificationCenter_) {
321 this.notificationCenter_.show(msg, {timeout});
322 }
323 }
324
325 /** @override */
326 hideOverlay() {
327 if (this.notificationCenter_) {
328 this.notificationCenter_.hide();
329 }
Jason Linca61ffb2022-08-03 19:37:12 +1000330 }
331
332 /** @override */
333 getPrefs() {
334 return this.prefs_;
335 }
336
337 /** @override */
338 getDocument() {
339 return window.document;
340 }
341
Jason Lin21d854f2022-08-22 14:49:59 +1000342 /** @override */
343 reset() {
344 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000345 }
346
347 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000348 setProfile(profileId, callback = undefined) {
349 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000350 }
351
Jason Lin21d854f2022-08-22 14:49:59 +1000352 /** @override */
353 interpret(string) {
354 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000355 }
356
Jason Lin21d854f2022-08-22 14:49:59 +1000357 /** @override */
358 focus() {
359 this.term.focus();
360 }
Jason Linca61ffb2022-08-03 19:37:12 +1000361
362 /** @override */
363 onOpenOptionsPage() {}
364
365 /** @override */
366 onTerminalReady() {}
367
Jason Lind04bab32022-08-22 14:48:39 +1000368 observePrefs_() {
369 for (const pref in PrefToXtermOptions) {
370 this.prefs_.addObserver(pref, (v) => {
371 this.updateOption_(PrefToXtermOptions[pref], v);
372 });
373 }
374
Jason Lin21d854f2022-08-22 14:49:59 +1000375 // This is for this.notificationCenter_.
376 const setHtermCSSVariable = (name, value) => {
377 document.body.style.setProperty(`--hterm-${name}`, value);
378 };
379
380 const setHtermColorCSSVariable = (name, color) => {
381 const css = lib.notNull(lib.colors.normalizeCSS(color));
382 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
383 setHtermCSSVariable(name, rgb);
384 };
385
386 this.prefs_.addObserver('font-size', (v) => {
387 this.updateOption_('fontSize', v);
388 setHtermCSSVariable('font-size', `${v}px`);
389 });
390
Jason Lind04bab32022-08-22 14:48:39 +1000391 // Theme-related preference items.
392 this.prefs_.addObservers(null, {
393 'background-color': (v) => {
394 this.updateTheme_({background: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000395 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000396 },
397 'foreground-color': (v) => {
398 this.updateTheme_({foreground: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000399 setHtermColorCSSVariable('foreground-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000400 },
401 'cursor-color': (v) => {
402 this.updateTheme_({cursor: v});
403 },
404 'color-palette-overrides': (v) => {
405 if (!(v instanceof Array)) {
406 // For terminal, we always expect this to be an array.
407 console.warn('unexpected color palette: ', v);
408 return;
409 }
410 const colors = {};
411 for (let i = 0; i < v.length; ++i) {
412 colors[ANSI_COLOR_NAMES[i]] = v[i];
413 }
414 this.updateTheme_(colors);
415 },
416 });
Jason Lin5690e752022-08-30 15:36:45 +1000417
418 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
419 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
420 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
421 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
422 }
Jason Lind04bab32022-08-22 14:48:39 +1000423 }
424
425 /**
426 * @param {!Object} theme
427 */
428 updateTheme_(theme) {
429 const newTheme = {...this.term.options.theme};
430 for (const key in theme) {
431 newTheme[key] = lib.colors.normalizeCSS(theme[key]);
432 }
433 this.updateOption_('theme', newTheme);
434 }
435
436 /**
437 * Update one xterm.js option.
438 *
439 * @param {string} key
440 * @param {*} value
441 */
442 updateOption_(key, value) {
Jason Linabad7562022-08-22 14:49:05 +1000443 if (key === 'fontFamily') {
444 this.updateFont_(/** @type {string} */(value));
445 return;
446 }
Jason Lind04bab32022-08-22 14:48:39 +1000447 // TODO: xterm supports updating multiple options at the same time. We
448 // should probably do that.
449 this.term.options[key] = value;
450 this.scheduleFit_();
451 }
Jason Linabad7562022-08-22 14:49:05 +1000452
453 /**
454 * Called when there is a "fontloadingdone" event. We need this because
455 * `FontManager.loadFont()` does not guarantee loading all the font files.
456 */
457 async onFontLoadingDone_() {
458 // If there is a pending font, the font is going to be refresh soon, so we
459 // don't need to do anything.
460 if (!this.pendingFont_) {
461 this.scheduleRefreshFont_();
462 }
463 }
464
Jason Lin5690e752022-08-30 15:36:45 +1000465 copySelection_() {
Jason Lin6a402a72022-08-25 16:07:02 +1000466 const selection = this.term.getSelection();
467 if (!selection) {
468 return;
469 }
470 navigator.clipboard?.writeText(selection);
471 if (!this.copyNotice_) {
472 this.copyNotice_ = document.createElement('terminal-copy-notice');
473 }
474 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200);
475 }
476
Jason Linabad7562022-08-22 14:49:05 +1000477 /**
478 * Refresh xterm rendering for a font related event.
479 */
480 refreshFont_() {
481 // We have to set the fontFamily option to a different string to trigger the
482 // re-rendering. Appending a space at the end seems to be the easiest
483 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
484 // us.
485 //
486 // TODO: Report a bug to xterm.js and ask for exposing a public function for
487 // the refresh so that we don't need to do this hack.
488 this.term.options.fontFamily += ' ';
489 }
490
491 /**
492 * Update a font.
493 *
494 * @param {string} cssFontFamily
495 */
496 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000497 this.pendingFont_ = cssFontFamily;
498 await this.fontManager_.loadFont(cssFontFamily);
499 // Sleep a bit to wait for flushing fontloadingdone events. This is not
500 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
501 // to refresh font unnecessarily in some cases.
502 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000503
Jason Lin6a402a72022-08-25 16:07:02 +1000504 if (this.pendingFont_ !== cssFontFamily) {
505 // `updateFont_()` probably is called again. Abort what we are doing.
506 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
507 ` (expecting ${cssFontFamily})`);
508 return;
509 }
Jason Linabad7562022-08-22 14:49:05 +1000510
Jason Lin6a402a72022-08-25 16:07:02 +1000511 if (this.term.options.fontFamily !== cssFontFamily) {
512 this.term.options.fontFamily = cssFontFamily;
513 } else {
514 // If the font is already the same, refresh font just to be safe.
515 this.refreshFont_();
516 }
517 this.pendingFont_ = null;
518 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000519 }
Jason Lin5690e752022-08-30 15:36:45 +1000520
521 /**
522 * @param {!KeyboardEvent} ev
523 * @return {boolean} Return false if xterm.js should not handle the key event.
524 */
525 customKeyEventHandler_(ev) {
526 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
527 (ev.altKey ? Modifier.Alt : 0) |
528 (ev.ctrlKey ? Modifier.Ctrl : 0) |
529 (ev.metaKey ? Modifier.Meta : 0);
530 const handler = this.keyDownHandlers_.get(
531 encodeKeyCombo(modifiers, ev.keyCode));
532 if (handler) {
533 if (ev.type === 'keydown') {
534 handler(ev);
535 }
536 return false;
537 }
538
539 return true;
540 }
541
542 /**
543 * A keydown handler for zoom-related keys.
544 *
545 * @param {!KeyboardEvent} ev
546 */
547 zoomKeyDownHandler_(ev) {
548 ev.preventDefault();
549
550 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
551 // The only one with a control code.
552 if (ev.keyCode === keyCodes.MINUS) {
553 this.io.onVTKeystroke('\x1f');
554 }
555 return;
556 }
557
558 let newFontSize;
559 switch (ev.keyCode) {
560 case keyCodes.ZERO:
561 newFontSize = this.prefs_.get('font-size');
562 break;
563 case keyCodes.MINUS:
564 newFontSize = this.term.options.fontSize - 1;
565 break;
566 default:
567 newFontSize = this.term.options.fontSize + 1;
568 break;
569 }
570
571 this.updateOption_('fontSize', Math.max(1, newFontSize));
572 }
573
574 /** @param {!KeyboardEvent} ev */
575 ctrlCKeyDownHandler_(ev) {
576 ev.preventDefault();
577 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
578 this.term.hasSelection()) {
579 this.copySelection_();
580 return;
581 }
582
583 this.io.onVTKeystroke('\x03');
584 }
585
586 /** @param {!KeyboardEvent} ev */
587 ctrlVKeyDownHandler_(ev) {
588 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
589 // Don't do anything and let the browser handles the key.
590 return;
591 }
592
593 ev.preventDefault();
594 this.io.onVTKeystroke('\x16');
595 }
596
597 resetKeyDownHandlers_() {
598 this.keyDownHandlers_.clear();
599
600 /**
601 * Don't do anything and let the browser handles the key.
602 *
603 * @param {!KeyboardEvent} ev
604 */
605 const noop = (ev) => {};
606
607 /**
608 * @param {number} modifiers
609 * @param {number} keyCode
610 * @param {function(!KeyboardEvent)} func
611 */
612 const set = (modifiers, keyCode, func) => {
613 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
614 func);
615 };
616
617 /**
618 * @param {number} modifiers
619 * @param {number} keyCode
620 * @param {function(!KeyboardEvent)} func
621 */
622 const setWithShiftVersion = (modifiers, keyCode, func) => {
623 set(modifiers, keyCode, func);
624 set(modifiers | Modifier.Shift, keyCode, func);
625 };
626
627
628 // Ctrl+/
629 set(Modifier.Ctrl, 191, (ev) => {
630 ev.preventDefault();
631 this.io.onVTKeystroke(ctl('_'));
632 });
633
634 // Settings page.
635 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
636 ev.preventDefault();
637 chrome.terminalPrivate.openOptionsPage(() => {});
638 });
639
640 if (this.prefs_.get('keybindings-os-defaults')) {
641 for (const binding of OS_DEFAULT_BINDINGS) {
642 this.keyDownHandlers_.set(binding, noop);
643 }
644 }
645
646 /** @param {!KeyboardEvent} ev */
647 const newWindow = (ev) => {
648 ev.preventDefault();
649 chrome.terminalPrivate.openWindow();
650 };
651 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
652 if (this.prefs_.get('pass-ctrl-n')) {
653 set(Modifier.Ctrl, keyCodes.N, newWindow);
654 }
655
656 if (this.prefs_.get('pass-ctrl-t')) {
657 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
658 }
659
660 if (this.prefs_.get('pass-ctrl-w')) {
661 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
662 }
663
664 if (this.prefs_.get('pass-ctrl-tab')) {
665 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
666 }
667
668 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
669
670 /**
671 * Set a handler for the key combo ctrl+<number>.
672 *
673 * @param {number} number 1 to 9
674 * @param {string} controlCode The control code to send if we don't want to
675 * let the browser to handle it.
676 */
677 const setCtrlNumberHandler = (number, controlCode) => {
678 let func = noop;
679 if (!passCtrlNumber) {
680 func = (ev) => {
681 ev.preventDefault();
682 this.io.onVTKeystroke(controlCode);
683 };
684 }
685 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
686 };
687
688 setCtrlNumberHandler(1, '1');
689 setCtrlNumberHandler(2, ctl('@'));
690 setCtrlNumberHandler(3, ctl('['));
691 setCtrlNumberHandler(4, ctl('\\'));
692 setCtrlNumberHandler(5, ctl(']'));
693 setCtrlNumberHandler(6, ctl('^'));
694 setCtrlNumberHandler(7, ctl('_'));
695 setCtrlNumberHandler(8, '\x7f');
696 setCtrlNumberHandler(9, '9');
697
698 if (this.prefs_.get('pass-alt-number')) {
699 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
700 set(Modifier.Alt, keyCode, noop);
701 }
702 }
703
704 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
705 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
706 }
707
708 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
709 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
710 }
Jason Linca61ffb2022-08-03 19:37:12 +1000711}
712
Jason Lind66e6bf2022-08-22 14:47:10 +1000713class HtermTerminal extends hterm.Terminal {
714 /** @override */
715 decorate(div) {
716 super.decorate(div);
717
718 const fontManager = new FontManager(this.getDocument());
719 fontManager.loadPowerlineCSS().then(() => {
720 const prefs = this.getPrefs();
721 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
722 prefs.addObserver(
723 'font-family',
724 (v) => fontManager.loadFont(/** @type {string} */(v)));
725 });
726 }
727}
728
Jason Linca61ffb2022-08-03 19:37:12 +1000729/**
730 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
731 * preference value.
732 *
733 * @param {{
734 * storage: !lib.Storage,
735 * profileId: string,
736 * }} args
737 * @return {!Promise<!hterm.Terminal>}
738 */
739export async function createEmulator({storage, profileId}) {
740 let config = TERMINAL_EMULATORS.get('hterm');
741
742 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +1000743 // TODO: remove the url param logic. This is temporary to make manual
744 // testing a bit easier, which is also why this is not in
745 // './js/terminal_info.js'.
746 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
747 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +1000748 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +1000749 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +1000750 TERMINAL_EMULATORS.values().next().value;
751 console.log('Terminal emulator config: ', config);
752 }
753
754 switch (config.lib) {
755 case 'xterm.js':
756 {
757 const terminal = new XtermTerminal({
758 storage,
759 profileId,
760 enableWebGL: config.webgl,
761 });
762 // Don't await it so that the caller can override
763 // `terminal.onTerminalReady()` before the terminal is ready.
764 terminal.init();
765 return terminal;
766 }
767 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +1000768 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +1000769 default:
770 throw new Error('incorrect emulator config');
771 }
772}
773
Jason Lin6a402a72022-08-25 16:07:02 +1000774class TerminalCopyNotice extends LitElement {
775 /** @override */
776 static get styles() {
777 return css`
778 :host {
779 display: block;
780 text-align: center;
781 }
782
783 svg {
784 fill: currentColor;
785 }
786 `;
787 }
788
789 /** @override */
790 render() {
791 return html`
792 ${ICON_COPY}
793 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
794 `;
795 }
796}
797
798customElements.define('terminal-copy-notice', TerminalCopyNotice);