blob: b821926fa130b60c3aa758bbd22c2bf724ce89cf [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_();
Jason Line9231bc2022-09-01 13:54:02 +1000181 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000182
Jason Lin21d854f2022-08-22 14:49:59 +1000183 this.term.onResize(({cols, rows}) => this.io.onTerminalResize(cols, rows));
184 // We could also use `this.io.sendString()` except for the nassh exit
185 // prompt, which only listens to onVTKeystroke().
186 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin6a402a72022-08-25 16:07:02 +1000187 this.term.onTitleChange((title) => document.title = title);
Jason Lin5690e752022-08-30 15:36:45 +1000188 this.term.onSelectionChange(() => this.copySelection_());
189
190 /**
191 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
192 *
193 * If a key combo is in the map:
194 *
195 * - The handler instead of xterm.js will handle the keydown event.
196 * - Keyup and keypress will be ignored by both us and xterm.js.
197 *
198 * We re-generate this map every time a relevant pref value is changed. This
199 * is ok because pref changes are rare.
200 *
201 * @type {!Map<number, function(!KeyboardEvent)>}
202 */
203 this.keyDownHandlers_ = new Map();
204 this.scheduleResetKeyDownHandlers_ =
205 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
206
207 this.term.attachCustomKeyEventHandler(
208 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000209
Jason Lin21d854f2022-08-22 14:49:59 +1000210 this.io = new XtermTerminalIO(this);
211 this.notificationCenter_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000212
213 this.copyNotice_ = null;
214
215 this.term.options.theme = {
216 selection: 'rgba(174, 203, 250, .6)',
217 selectionForeground: 'black',
218 customGlyphs: true,
219 };
220 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000221 }
222
223 /**
224 * Install stubs for stuff that we haven't implemented yet so that the code
225 * still runs.
226 */
227 installUnimplementedStubs_() {
228 this.keyboard = {
229 keyMap: {
230 keyDefs: [],
231 },
232 bindings: {
233 clear: () => {},
234 addBinding: () => {},
235 addBindings: () => {},
236 OsDefaults: {},
237 },
238 };
239 this.keyboard.keyMap.keyDefs[78] = {};
240
241 const methodNames = [
Jason Linca61ffb2022-08-03 19:37:12 +1000242 'setAccessibilityEnabled',
243 'setBackgroundImage',
244 'setCursorPosition',
245 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000246 ];
247
248 for (const name of methodNames) {
249 this[name] = () => console.warn(`${name}() is not implemented`);
250 }
251
252 this.contextMenu = {
253 setItems: () => {
254 console.warn('.contextMenu.setItems() is not implemented');
255 },
256 };
Jason Lin21d854f2022-08-22 14:49:59 +1000257
258 this.vt = {
259 resetParseState: () => {
260 console.warn('.vt.resetParseState() is not implemented');
261 },
262 };
Jason Linca61ffb2022-08-03 19:37:12 +1000263 }
264
Jason Line9231bc2022-09-01 13:54:02 +1000265 installEscapeSequenceHandlers_() {
266 // OSC 52 for copy.
267 this.term.parser.registerOscHandler(52, (args) => {
268 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
269 // parameter is used to select which of the X clipboards to address. Since
270 // we're not integrating with X, we treat them all the same.
271 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
272 if (!parsedArgs) {
273 return true;
274 }
275
276 let data;
277 try {
278 data = window.atob(parsedArgs[1]);
279 } catch (e) {
280 // If the user sent us invalid base64 content, silently ignore it.
281 return true;
282 }
283 const decoder = new TextDecoder();
284 const bytes = lib.codec.stringToCodeUnitArray(data);
285 this.copyString_(decoder.decode(bytes));
286
287 return true;
288 });
289 }
290
Jason Linca61ffb2022-08-03 19:37:12 +1000291 /**
292 * One-time initialization at the beginning.
293 */
294 async init() {
295 await new Promise((resolve) => this.prefs_.readStorage(resolve));
296 this.prefs_.notifyAll();
297 this.onTerminalReady();
298 }
299
Jason Lin21d854f2022-08-22 14:49:59 +1000300 /**
301 * Write data to the terminal.
302 *
303 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
304 * UTF-8 data
305 */
306 write(data) {
307 this.term.write(data);
308 }
309
310 /**
311 * Like `this.write()` but also write a line break.
312 *
313 * @param {string|!Uint8Array} data
314 */
315 writeln(data) {
316 this.term.writeln(data);
317 }
318
Jason Linca61ffb2022-08-03 19:37:12 +1000319 get screenSize() {
320 return new hterm.Size(this.term.cols, this.term.rows);
321 }
322
323 /**
324 * Don't need to do anything.
325 *
326 * @override
327 */
328 installKeyboard() {}
329
330 /**
331 * @override
332 */
333 decorate(elem) {
334 this.term.open(elem);
Jason Lind04bab32022-08-22 14:48:39 +1000335 this.scheduleFit_();
Jason Linca61ffb2022-08-03 19:37:12 +1000336 if (this.enableWebGL_) {
337 this.term.loadAddon(new WebglAddon());
338 }
Jason Lin21d854f2022-08-22 14:49:59 +1000339 this.term.focus();
Jason Lind04bab32022-08-22 14:48:39 +1000340 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lin21d854f2022-08-22 14:49:59 +1000341 // TODO: Make a11y work. Maybe we can just use `hterm.AccessibilityReader`.
342 this.notificationCenter_ = new hterm.NotificationCenter(document.body);
343 }
344
345 /** @override */
346 showOverlay(msg, timeout = 1500) {
347 if (this.notificationCenter_) {
348 this.notificationCenter_.show(msg, {timeout});
349 }
350 }
351
352 /** @override */
353 hideOverlay() {
354 if (this.notificationCenter_) {
355 this.notificationCenter_.hide();
356 }
Jason Linca61ffb2022-08-03 19:37:12 +1000357 }
358
359 /** @override */
360 getPrefs() {
361 return this.prefs_;
362 }
363
364 /** @override */
365 getDocument() {
366 return window.document;
367 }
368
Jason Lin21d854f2022-08-22 14:49:59 +1000369 /** @override */
370 reset() {
371 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000372 }
373
374 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000375 setProfile(profileId, callback = undefined) {
376 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000377 }
378
Jason Lin21d854f2022-08-22 14:49:59 +1000379 /** @override */
380 interpret(string) {
381 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000382 }
383
Jason Lin21d854f2022-08-22 14:49:59 +1000384 /** @override */
385 focus() {
386 this.term.focus();
387 }
Jason Linca61ffb2022-08-03 19:37:12 +1000388
389 /** @override */
390 onOpenOptionsPage() {}
391
392 /** @override */
393 onTerminalReady() {}
394
Jason Lind04bab32022-08-22 14:48:39 +1000395 observePrefs_() {
396 for (const pref in PrefToXtermOptions) {
397 this.prefs_.addObserver(pref, (v) => {
398 this.updateOption_(PrefToXtermOptions[pref], v);
399 });
400 }
401
Jason Lin21d854f2022-08-22 14:49:59 +1000402 // This is for this.notificationCenter_.
403 const setHtermCSSVariable = (name, value) => {
404 document.body.style.setProperty(`--hterm-${name}`, value);
405 };
406
407 const setHtermColorCSSVariable = (name, color) => {
408 const css = lib.notNull(lib.colors.normalizeCSS(color));
409 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
410 setHtermCSSVariable(name, rgb);
411 };
412
413 this.prefs_.addObserver('font-size', (v) => {
414 this.updateOption_('fontSize', v);
415 setHtermCSSVariable('font-size', `${v}px`);
416 });
417
Jason Lind04bab32022-08-22 14:48:39 +1000418 // Theme-related preference items.
419 this.prefs_.addObservers(null, {
420 'background-color': (v) => {
421 this.updateTheme_({background: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000422 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000423 },
424 'foreground-color': (v) => {
425 this.updateTheme_({foreground: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000426 setHtermColorCSSVariable('foreground-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000427 },
428 'cursor-color': (v) => {
429 this.updateTheme_({cursor: v});
430 },
431 'color-palette-overrides': (v) => {
432 if (!(v instanceof Array)) {
433 // For terminal, we always expect this to be an array.
434 console.warn('unexpected color palette: ', v);
435 return;
436 }
437 const colors = {};
438 for (let i = 0; i < v.length; ++i) {
439 colors[ANSI_COLOR_NAMES[i]] = v[i];
440 }
441 this.updateTheme_(colors);
442 },
443 });
Jason Lin5690e752022-08-30 15:36:45 +1000444
445 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
446 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
447 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
448 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
449 }
Jason Lind04bab32022-08-22 14:48:39 +1000450 }
451
452 /**
453 * @param {!Object} theme
454 */
455 updateTheme_(theme) {
456 const newTheme = {...this.term.options.theme};
457 for (const key in theme) {
458 newTheme[key] = lib.colors.normalizeCSS(theme[key]);
459 }
460 this.updateOption_('theme', newTheme);
461 }
462
463 /**
464 * Update one xterm.js option.
465 *
466 * @param {string} key
467 * @param {*} value
468 */
469 updateOption_(key, value) {
Jason Linabad7562022-08-22 14:49:05 +1000470 if (key === 'fontFamily') {
471 this.updateFont_(/** @type {string} */(value));
472 return;
473 }
Jason Lind04bab32022-08-22 14:48:39 +1000474 // TODO: xterm supports updating multiple options at the same time. We
475 // should probably do that.
476 this.term.options[key] = value;
477 this.scheduleFit_();
478 }
Jason Linabad7562022-08-22 14:49:05 +1000479
480 /**
481 * Called when there is a "fontloadingdone" event. We need this because
482 * `FontManager.loadFont()` does not guarantee loading all the font files.
483 */
484 async onFontLoadingDone_() {
485 // If there is a pending font, the font is going to be refresh soon, so we
486 // don't need to do anything.
487 if (!this.pendingFont_) {
488 this.scheduleRefreshFont_();
489 }
490 }
491
Jason Lin5690e752022-08-30 15:36:45 +1000492 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000493 this.copyString_(this.term.getSelection());
494 }
495
496 /** @param {string} data */
497 copyString_(data) {
498 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000499 return;
500 }
Jason Line9231bc2022-09-01 13:54:02 +1000501 navigator.clipboard?.writeText(data);
Jason Lin6a402a72022-08-25 16:07:02 +1000502 if (!this.copyNotice_) {
503 this.copyNotice_ = document.createElement('terminal-copy-notice');
504 }
505 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200);
506 }
507
Jason Linabad7562022-08-22 14:49:05 +1000508 /**
509 * Refresh xterm rendering for a font related event.
510 */
511 refreshFont_() {
512 // We have to set the fontFamily option to a different string to trigger the
513 // re-rendering. Appending a space at the end seems to be the easiest
514 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
515 // us.
516 //
517 // TODO: Report a bug to xterm.js and ask for exposing a public function for
518 // the refresh so that we don't need to do this hack.
519 this.term.options.fontFamily += ' ';
520 }
521
522 /**
523 * Update a font.
524 *
525 * @param {string} cssFontFamily
526 */
527 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000528 this.pendingFont_ = cssFontFamily;
529 await this.fontManager_.loadFont(cssFontFamily);
530 // Sleep a bit to wait for flushing fontloadingdone events. This is not
531 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
532 // to refresh font unnecessarily in some cases.
533 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000534
Jason Lin6a402a72022-08-25 16:07:02 +1000535 if (this.pendingFont_ !== cssFontFamily) {
536 // `updateFont_()` probably is called again. Abort what we are doing.
537 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
538 ` (expecting ${cssFontFamily})`);
539 return;
540 }
Jason Linabad7562022-08-22 14:49:05 +1000541
Jason Lin6a402a72022-08-25 16:07:02 +1000542 if (this.term.options.fontFamily !== cssFontFamily) {
543 this.term.options.fontFamily = cssFontFamily;
544 } else {
545 // If the font is already the same, refresh font just to be safe.
546 this.refreshFont_();
547 }
548 this.pendingFont_ = null;
549 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000550 }
Jason Lin5690e752022-08-30 15:36:45 +1000551
552 /**
553 * @param {!KeyboardEvent} ev
554 * @return {boolean} Return false if xterm.js should not handle the key event.
555 */
556 customKeyEventHandler_(ev) {
557 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
558 (ev.altKey ? Modifier.Alt : 0) |
559 (ev.ctrlKey ? Modifier.Ctrl : 0) |
560 (ev.metaKey ? Modifier.Meta : 0);
561 const handler = this.keyDownHandlers_.get(
562 encodeKeyCombo(modifiers, ev.keyCode));
563 if (handler) {
564 if (ev.type === 'keydown') {
565 handler(ev);
566 }
567 return false;
568 }
569
570 return true;
571 }
572
573 /**
574 * A keydown handler for zoom-related keys.
575 *
576 * @param {!KeyboardEvent} ev
577 */
578 zoomKeyDownHandler_(ev) {
579 ev.preventDefault();
580
581 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
582 // The only one with a control code.
583 if (ev.keyCode === keyCodes.MINUS) {
584 this.io.onVTKeystroke('\x1f');
585 }
586 return;
587 }
588
589 let newFontSize;
590 switch (ev.keyCode) {
591 case keyCodes.ZERO:
592 newFontSize = this.prefs_.get('font-size');
593 break;
594 case keyCodes.MINUS:
595 newFontSize = this.term.options.fontSize - 1;
596 break;
597 default:
598 newFontSize = this.term.options.fontSize + 1;
599 break;
600 }
601
602 this.updateOption_('fontSize', Math.max(1, newFontSize));
603 }
604
605 /** @param {!KeyboardEvent} ev */
606 ctrlCKeyDownHandler_(ev) {
607 ev.preventDefault();
608 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
609 this.term.hasSelection()) {
610 this.copySelection_();
611 return;
612 }
613
614 this.io.onVTKeystroke('\x03');
615 }
616
617 /** @param {!KeyboardEvent} ev */
618 ctrlVKeyDownHandler_(ev) {
619 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
620 // Don't do anything and let the browser handles the key.
621 return;
622 }
623
624 ev.preventDefault();
625 this.io.onVTKeystroke('\x16');
626 }
627
628 resetKeyDownHandlers_() {
629 this.keyDownHandlers_.clear();
630
631 /**
632 * Don't do anything and let the browser handles the key.
633 *
634 * @param {!KeyboardEvent} ev
635 */
636 const noop = (ev) => {};
637
638 /**
639 * @param {number} modifiers
640 * @param {number} keyCode
641 * @param {function(!KeyboardEvent)} func
642 */
643 const set = (modifiers, keyCode, func) => {
644 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
645 func);
646 };
647
648 /**
649 * @param {number} modifiers
650 * @param {number} keyCode
651 * @param {function(!KeyboardEvent)} func
652 */
653 const setWithShiftVersion = (modifiers, keyCode, func) => {
654 set(modifiers, keyCode, func);
655 set(modifiers | Modifier.Shift, keyCode, func);
656 };
657
658
659 // Ctrl+/
660 set(Modifier.Ctrl, 191, (ev) => {
661 ev.preventDefault();
662 this.io.onVTKeystroke(ctl('_'));
663 });
664
665 // Settings page.
666 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
667 ev.preventDefault();
668 chrome.terminalPrivate.openOptionsPage(() => {});
669 });
670
671 if (this.prefs_.get('keybindings-os-defaults')) {
672 for (const binding of OS_DEFAULT_BINDINGS) {
673 this.keyDownHandlers_.set(binding, noop);
674 }
675 }
676
677 /** @param {!KeyboardEvent} ev */
678 const newWindow = (ev) => {
679 ev.preventDefault();
680 chrome.terminalPrivate.openWindow();
681 };
682 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
683 if (this.prefs_.get('pass-ctrl-n')) {
684 set(Modifier.Ctrl, keyCodes.N, newWindow);
685 }
686
687 if (this.prefs_.get('pass-ctrl-t')) {
688 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
689 }
690
691 if (this.prefs_.get('pass-ctrl-w')) {
692 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
693 }
694
695 if (this.prefs_.get('pass-ctrl-tab')) {
696 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
697 }
698
699 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
700
701 /**
702 * Set a handler for the key combo ctrl+<number>.
703 *
704 * @param {number} number 1 to 9
705 * @param {string} controlCode The control code to send if we don't want to
706 * let the browser to handle it.
707 */
708 const setCtrlNumberHandler = (number, controlCode) => {
709 let func = noop;
710 if (!passCtrlNumber) {
711 func = (ev) => {
712 ev.preventDefault();
713 this.io.onVTKeystroke(controlCode);
714 };
715 }
716 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
717 };
718
719 setCtrlNumberHandler(1, '1');
720 setCtrlNumberHandler(2, ctl('@'));
721 setCtrlNumberHandler(3, ctl('['));
722 setCtrlNumberHandler(4, ctl('\\'));
723 setCtrlNumberHandler(5, ctl(']'));
724 setCtrlNumberHandler(6, ctl('^'));
725 setCtrlNumberHandler(7, ctl('_'));
726 setCtrlNumberHandler(8, '\x7f');
727 setCtrlNumberHandler(9, '9');
728
729 if (this.prefs_.get('pass-alt-number')) {
730 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
731 set(Modifier.Alt, keyCode, noop);
732 }
733 }
734
735 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
736 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
737 }
738
739 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
740 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
741 }
Jason Linca61ffb2022-08-03 19:37:12 +1000742}
743
Jason Lind66e6bf2022-08-22 14:47:10 +1000744class HtermTerminal extends hterm.Terminal {
745 /** @override */
746 decorate(div) {
747 super.decorate(div);
748
749 const fontManager = new FontManager(this.getDocument());
750 fontManager.loadPowerlineCSS().then(() => {
751 const prefs = this.getPrefs();
752 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
753 prefs.addObserver(
754 'font-family',
755 (v) => fontManager.loadFont(/** @type {string} */(v)));
756 });
757 }
758}
759
Jason Linca61ffb2022-08-03 19:37:12 +1000760/**
761 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
762 * preference value.
763 *
764 * @param {{
765 * storage: !lib.Storage,
766 * profileId: string,
767 * }} args
768 * @return {!Promise<!hterm.Terminal>}
769 */
770export async function createEmulator({storage, profileId}) {
771 let config = TERMINAL_EMULATORS.get('hterm');
772
773 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +1000774 // TODO: remove the url param logic. This is temporary to make manual
775 // testing a bit easier, which is also why this is not in
776 // './js/terminal_info.js'.
777 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
778 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +1000779 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +1000780 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +1000781 TERMINAL_EMULATORS.values().next().value;
782 console.log('Terminal emulator config: ', config);
783 }
784
785 switch (config.lib) {
786 case 'xterm.js':
787 {
788 const terminal = new XtermTerminal({
789 storage,
790 profileId,
791 enableWebGL: config.webgl,
792 });
793 // Don't await it so that the caller can override
794 // `terminal.onTerminalReady()` before the terminal is ready.
795 terminal.init();
796 return terminal;
797 }
798 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +1000799 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +1000800 default:
801 throw new Error('incorrect emulator config');
802 }
803}
804
Jason Lin6a402a72022-08-25 16:07:02 +1000805class TerminalCopyNotice extends LitElement {
806 /** @override */
807 static get styles() {
808 return css`
809 :host {
810 display: block;
811 text-align: center;
812 }
813
814 svg {
815 fill: currentColor;
816 }
817 `;
818 }
819
820 /** @override */
821 render() {
822 return html`
823 ${ICON_COPY}
824 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
825 `;
826 }
827}
828
829customElements.define('terminal-copy-notice', TerminalCopyNotice);