blob: 7a11072c69c5caefc366dd523a05e7f133b579f2 [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 Linc2504ae2022-09-02 13:03:31 +100016import {Terminal, Unicode11Addon, WebLinksAddon, WebglAddon}
Jason Lin4de4f382022-09-01 14:10:18 +100017 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
Jason Linca61ffb2022-08-03 19:37:12 +100080/**
Jason Linabad7562022-08-22 14:49:05 +100081 * @typedef {{
82 * term: !Terminal,
83 * fontManager: !FontManager,
Jason Linabad7562022-08-22 14:49:05 +100084 * }}
85 */
86export let XtermTerminalTestParams;
87
88/**
Jason Lin5690e752022-08-30 15:36:45 +100089 * Compute a control character for a given character.
90 *
91 * @param {string} ch
92 * @return {string}
93 */
94function ctl(ch) {
95 return String.fromCharCode(ch.charCodeAt(0) - 64);
96}
97
98/**
Jason Lin21d854f2022-08-22 14:49:59 +100099 * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO
100 * because it always convert utf8 data to strings, which is not necessary for
101 * xterm.
102 */
103class XtermTerminalIO extends hterm.Terminal.IO {
104 /** @override */
105 writeUTF8(buffer) {
106 this.terminal_.write(new Uint8Array(buffer));
107 }
108
109 /** @override */
110 writelnUTF8(buffer) {
111 this.terminal_.writeln(new Uint8Array(buffer));
112 }
113
114 /** @override */
115 print(string) {
116 this.terminal_.write(string);
117 }
118
119 /** @override */
120 writeUTF16(string) {
121 this.print(string);
122 }
123
124 /** @override */
125 println(string) {
126 this.terminal_.writeln(string);
127 }
128
129 /** @override */
130 writelnUTF16(string) {
131 this.println(string);
132 }
133}
134
135/**
Jason Linca61ffb2022-08-03 19:37:12 +1000136 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
137 * so that it can be used in existing code.
138 *
Jason Linca61ffb2022-08-03 19:37:12 +1000139 * @extends {hterm.Terminal}
140 * @unrestricted
141 */
Jason Linabad7562022-08-22 14:49:05 +1000142export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000143 /**
144 * @param {{
145 * storage: !lib.Storage,
146 * profileId: string,
147 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000148 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000149 * }} args
150 */
Jason Linabad7562022-08-22 14:49:05 +1000151 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000152 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
153 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
154 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
155
Jason Lin8de3d282022-09-01 21:29:05 +1000156 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000157 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000158 /** @type {!hterm.PreferenceManager} */
159 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
160 this.enableWebGL_ = enableWebGL;
161
Jason Lin5690e752022-08-30 15:36:45 +1000162 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linabad7562022-08-22 14:49:05 +1000163 this.term = testParams?.term || new Terminal();
164 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000165
Jason Linc2504ae2022-09-02 13:03:31 +1000166 /** @type {?Element} */
167 this.container_;
168
169 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000170 testParams ? 0 : 250);
171
Jason Lin4de4f382022-09-01 14:10:18 +1000172 this.term.loadAddon(new WebLinksAddon());
173 this.term.loadAddon(new Unicode11Addon());
174 this.term.unicode.activeVersion = '11';
175
Jason Linabad7562022-08-22 14:49:05 +1000176 this.pendingFont_ = null;
177 this.scheduleRefreshFont_ = delayedScheduler(
178 () => this.refreshFont_(), 100);
179 document.fonts.addEventListener('loadingdone',
180 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000181
182 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000183 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000184
Jason Lin21d854f2022-08-22 14:49:59 +1000185 this.term.onResize(({cols, rows}) => this.io.onTerminalResize(cols, rows));
186 // We could also use `this.io.sendString()` except for the nassh exit
187 // prompt, which only listens to onVTKeystroke().
188 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000189 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin6a402a72022-08-25 16:07:02 +1000190 this.term.onTitleChange((title) => document.title = title);
Jason Lin5690e752022-08-30 15:36:45 +1000191 this.term.onSelectionChange(() => this.copySelection_());
192
193 /**
194 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
195 *
196 * If a key combo is in the map:
197 *
198 * - The handler instead of xterm.js will handle the keydown event.
199 * - Keyup and keypress will be ignored by both us and xterm.js.
200 *
201 * We re-generate this map every time a relevant pref value is changed. This
202 * is ok because pref changes are rare.
203 *
204 * @type {!Map<number, function(!KeyboardEvent)>}
205 */
206 this.keyDownHandlers_ = new Map();
207 this.scheduleResetKeyDownHandlers_ =
208 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
209
210 this.term.attachCustomKeyEventHandler(
211 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000212
Jason Lin21d854f2022-08-22 14:49:59 +1000213 this.io = new XtermTerminalIO(this);
214 this.notificationCenter_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000215
216 this.copyNotice_ = null;
217
218 this.term.options.theme = {
219 selection: 'rgba(174, 203, 250, .6)',
220 selectionForeground: 'black',
221 customGlyphs: true,
222 };
223 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000224 }
225
226 /**
227 * Install stubs for stuff that we haven't implemented yet so that the code
228 * still runs.
229 */
230 installUnimplementedStubs_() {
231 this.keyboard = {
232 keyMap: {
233 keyDefs: [],
234 },
235 bindings: {
236 clear: () => {},
237 addBinding: () => {},
238 addBindings: () => {},
239 OsDefaults: {},
240 },
241 };
242 this.keyboard.keyMap.keyDefs[78] = {};
243
244 const methodNames = [
Jason Linca61ffb2022-08-03 19:37:12 +1000245 'setAccessibilityEnabled',
246 'setBackgroundImage',
247 'setCursorPosition',
248 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000249 ];
250
251 for (const name of methodNames) {
252 this[name] = () => console.warn(`${name}() is not implemented`);
253 }
254
255 this.contextMenu = {
256 setItems: () => {
257 console.warn('.contextMenu.setItems() is not implemented');
258 },
259 };
Jason Lin21d854f2022-08-22 14:49:59 +1000260
261 this.vt = {
262 resetParseState: () => {
263 console.warn('.vt.resetParseState() is not implemented');
264 },
265 };
Jason Linca61ffb2022-08-03 19:37:12 +1000266 }
267
Jason Line9231bc2022-09-01 13:54:02 +1000268 installEscapeSequenceHandlers_() {
269 // OSC 52 for copy.
270 this.term.parser.registerOscHandler(52, (args) => {
271 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
272 // parameter is used to select which of the X clipboards to address. Since
273 // we're not integrating with X, we treat them all the same.
274 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
275 if (!parsedArgs) {
276 return true;
277 }
278
279 let data;
280 try {
281 data = window.atob(parsedArgs[1]);
282 } catch (e) {
283 // If the user sent us invalid base64 content, silently ignore it.
284 return true;
285 }
286 const decoder = new TextDecoder();
287 const bytes = lib.codec.stringToCodeUnitArray(data);
288 this.copyString_(decoder.decode(bytes));
289
290 return true;
291 });
292 }
293
Jason Linca61ffb2022-08-03 19:37:12 +1000294 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000295 * Write data to the terminal.
296 *
297 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
298 * UTF-8 data
299 */
300 write(data) {
301 this.term.write(data);
302 }
303
304 /**
305 * Like `this.write()` but also write a line break.
306 *
307 * @param {string|!Uint8Array} data
308 */
309 writeln(data) {
310 this.term.writeln(data);
311 }
312
Jason Linca61ffb2022-08-03 19:37:12 +1000313 get screenSize() {
314 return new hterm.Size(this.term.cols, this.term.rows);
315 }
316
317 /**
318 * Don't need to do anything.
319 *
320 * @override
321 */
322 installKeyboard() {}
323
324 /**
325 * @override
326 */
327 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000328 this.container_ = elem;
Jason Lin8de3d282022-09-01 21:29:05 +1000329 (async () => {
330 await new Promise((resolve) => this.prefs_.readStorage(resolve));
331 // This will trigger all the observers to set the terminal options before
332 // we call `this.term.open()`.
333 this.prefs_.notifyAll();
334
Jason Linc2504ae2022-09-02 13:03:31 +1000335 const screenPaddingSize = /** @type {number} */(
336 this.prefs_.get('screen-padding-size'));
337 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
338
Jason Lin8de3d282022-09-01 21:29:05 +1000339 this.inited_ = true;
340 this.term.open(elem);
341
342 this.scheduleFit_();
343 if (this.enableWebGL_) {
344 this.term.loadAddon(new WebglAddon());
345 }
346 this.term.focus();
347 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
348 // TODO: Make a11y work. Maybe we can just use hterm.AccessibilityReader.
349 this.notificationCenter_ = new hterm.NotificationCenter(document.body);
350
351 this.onTerminalReady();
352 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000353 }
354
355 /** @override */
356 showOverlay(msg, timeout = 1500) {
357 if (this.notificationCenter_) {
358 this.notificationCenter_.show(msg, {timeout});
359 }
360 }
361
362 /** @override */
363 hideOverlay() {
364 if (this.notificationCenter_) {
365 this.notificationCenter_.hide();
366 }
Jason Linca61ffb2022-08-03 19:37:12 +1000367 }
368
369 /** @override */
370 getPrefs() {
371 return this.prefs_;
372 }
373
374 /** @override */
375 getDocument() {
376 return window.document;
377 }
378
Jason Lin21d854f2022-08-22 14:49:59 +1000379 /** @override */
380 reset() {
381 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000382 }
383
384 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000385 setProfile(profileId, callback = undefined) {
386 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000387 }
388
Jason Lin21d854f2022-08-22 14:49:59 +1000389 /** @override */
390 interpret(string) {
391 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000392 }
393
Jason Lin21d854f2022-08-22 14:49:59 +1000394 /** @override */
395 focus() {
396 this.term.focus();
397 }
Jason Linca61ffb2022-08-03 19:37:12 +1000398
399 /** @override */
400 onOpenOptionsPage() {}
401
402 /** @override */
403 onTerminalReady() {}
404
Jason Lind04bab32022-08-22 14:48:39 +1000405 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000406 // This is for this.notificationCenter_.
407 const setHtermCSSVariable = (name, value) => {
408 document.body.style.setProperty(`--hterm-${name}`, value);
409 };
410
411 const setHtermColorCSSVariable = (name, color) => {
412 const css = lib.notNull(lib.colors.normalizeCSS(color));
413 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
414 setHtermCSSVariable(name, rgb);
415 };
416
417 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000418 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000419 setHtermCSSVariable('font-size', `${v}px`);
420 });
421
Jason Linda56aa92022-09-02 13:01:49 +1000422 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000423 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000424 'audible-bell-sound': (v) => {
425 if (v) {
426 this.updateOption_('bellStyle', 'sound', false);
427 this.updateOption_('bellSound', lib.resource.getDataUrl(
428 'hterm/audio/bell'), false);
429 } else {
430 this.updateOption_('bellStyle', 'none', false);
431 }
432 },
Jason Lind04bab32022-08-22 14:48:39 +1000433 'background-color': (v) => {
434 this.updateTheme_({background: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000435 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000436 },
Jason Lind04bab32022-08-22 14:48:39 +1000437 'color-palette-overrides': (v) => {
438 if (!(v instanceof Array)) {
439 // For terminal, we always expect this to be an array.
440 console.warn('unexpected color palette: ', v);
441 return;
442 }
443 const colors = {};
444 for (let i = 0; i < v.length; ++i) {
445 colors[ANSI_COLOR_NAMES[i]] = v[i];
446 }
447 this.updateTheme_(colors);
448 },
Jason Linda56aa92022-09-02 13:01:49 +1000449 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
450 'cursor-color': (v) => this.updateTheme_({cursor: v}),
451 'cursor-shape': (v) => {
452 let shape;
453 if (v === 'BEAM') {
454 shape = 'bar';
455 } else {
456 shape = v.toLowerCase();
457 }
458 this.updateOption_('cursorStyle', shape, false);
459 },
460 'font-family': (v) => this.updateFont_(v),
461 'foreground-color': (v) => {
462 // TODO(lxj): setting the cursorAccent to the foreground color mimics
463 // what hterm does, but I think it is better to expose this option.
464 this.updateTheme_({foreground: v, cursorAccent: v});
465 setHtermColorCSSVariable('foreground-color', v);
466 },
Jason Lind04bab32022-08-22 14:48:39 +1000467 });
Jason Lin5690e752022-08-30 15:36:45 +1000468
469 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
470 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
471 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
472 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
473 }
Jason Lind04bab32022-08-22 14:48:39 +1000474 }
475
476 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000477 * Fit the terminal to the containing HTML element.
478 */
479 fit_() {
480 if (!this.inited_) {
481 return;
482 }
483
484 const screenPaddingSize = /** @type {number} */(
485 this.prefs_.get('screen-padding-size'));
486
487 const calc = (size, cellSize) => {
488 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
489 };
490
491 // Unfortunately, it looks like we have to use private API from xterm.js.
492 // Maybe we should patch the FitAddon so that it works for us.
493 const dimensions = this.term._core._renderService.dimensions;
494 const cols = calc(this.container_.offsetWidth, dimensions.actualCellWidth);
495 const rows = calc(this.container_.offsetHeight,
496 dimensions.actualCellHeight);
497 if (cols >= 0 && rows >= 0) {
498 this.term.resize(cols, rows);
499 }
500 }
501
502 /**
Jason Lind04bab32022-08-22 14:48:39 +1000503 * @param {!Object} theme
504 */
505 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000506 const updateTheme = (target) => {
507 for (const [key, value] of Object.entries(theme)) {
508 target[key] = lib.colors.normalizeCSS(value);
509 }
510 };
511
512 // Must use a new theme object to trigger re-render if we have initialized.
513 if (this.inited_) {
514 const newTheme = {...this.term.options.theme};
515 updateTheme(newTheme);
516 this.term.options.theme = newTheme;
517 return;
Jason Lind04bab32022-08-22 14:48:39 +1000518 }
Jason Lin8de3d282022-09-01 21:29:05 +1000519
520 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000521 }
522
523 /**
Jason Linda56aa92022-09-02 13:01:49 +1000524 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
525 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000526 *
527 * @param {string} key
528 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000529 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000530 */
Jason Linda56aa92022-09-02 13:01:49 +1000531 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000532 // TODO: xterm supports updating multiple options at the same time. We
533 // should probably do that.
534 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000535 if (scheduleFit) {
536 this.scheduleFit_();
537 }
Jason Lind04bab32022-08-22 14:48:39 +1000538 }
Jason Linabad7562022-08-22 14:49:05 +1000539
540 /**
541 * Called when there is a "fontloadingdone" event. We need this because
542 * `FontManager.loadFont()` does not guarantee loading all the font files.
543 */
544 async onFontLoadingDone_() {
545 // If there is a pending font, the font is going to be refresh soon, so we
546 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000547 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000548 this.scheduleRefreshFont_();
549 }
550 }
551
Jason Lin5690e752022-08-30 15:36:45 +1000552 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000553 this.copyString_(this.term.getSelection());
554 }
555
556 /** @param {string} data */
557 copyString_(data) {
558 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000559 return;
560 }
Jason Line9231bc2022-09-01 13:54:02 +1000561 navigator.clipboard?.writeText(data);
Jason Lin6a402a72022-08-25 16:07:02 +1000562 if (!this.copyNotice_) {
563 this.copyNotice_ = document.createElement('terminal-copy-notice');
564 }
565 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200);
566 }
567
Jason Linabad7562022-08-22 14:49:05 +1000568 /**
569 * Refresh xterm rendering for a font related event.
570 */
571 refreshFont_() {
572 // We have to set the fontFamily option to a different string to trigger the
573 // re-rendering. Appending a space at the end seems to be the easiest
574 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
575 // us.
576 //
577 // TODO: Report a bug to xterm.js and ask for exposing a public function for
578 // the refresh so that we don't need to do this hack.
579 this.term.options.fontFamily += ' ';
580 }
581
582 /**
583 * Update a font.
584 *
585 * @param {string} cssFontFamily
586 */
587 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000588 this.pendingFont_ = cssFontFamily;
589 await this.fontManager_.loadFont(cssFontFamily);
590 // Sleep a bit to wait for flushing fontloadingdone events. This is not
591 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
592 // to refresh font unnecessarily in some cases.
593 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000594
Jason Lin6a402a72022-08-25 16:07:02 +1000595 if (this.pendingFont_ !== cssFontFamily) {
596 // `updateFont_()` probably is called again. Abort what we are doing.
597 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
598 ` (expecting ${cssFontFamily})`);
599 return;
600 }
Jason Linabad7562022-08-22 14:49:05 +1000601
Jason Lin6a402a72022-08-25 16:07:02 +1000602 if (this.term.options.fontFamily !== cssFontFamily) {
603 this.term.options.fontFamily = cssFontFamily;
604 } else {
605 // If the font is already the same, refresh font just to be safe.
606 this.refreshFont_();
607 }
608 this.pendingFont_ = null;
609 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000610 }
Jason Lin5690e752022-08-30 15:36:45 +1000611
612 /**
613 * @param {!KeyboardEvent} ev
614 * @return {boolean} Return false if xterm.js should not handle the key event.
615 */
616 customKeyEventHandler_(ev) {
617 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
618 (ev.altKey ? Modifier.Alt : 0) |
619 (ev.ctrlKey ? Modifier.Ctrl : 0) |
620 (ev.metaKey ? Modifier.Meta : 0);
621 const handler = this.keyDownHandlers_.get(
622 encodeKeyCombo(modifiers, ev.keyCode));
623 if (handler) {
624 if (ev.type === 'keydown') {
625 handler(ev);
626 }
627 return false;
628 }
629
630 return true;
631 }
632
633 /**
634 * A keydown handler for zoom-related keys.
635 *
636 * @param {!KeyboardEvent} ev
637 */
638 zoomKeyDownHandler_(ev) {
639 ev.preventDefault();
640
641 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
642 // The only one with a control code.
643 if (ev.keyCode === keyCodes.MINUS) {
644 this.io.onVTKeystroke('\x1f');
645 }
646 return;
647 }
648
649 let newFontSize;
650 switch (ev.keyCode) {
651 case keyCodes.ZERO:
652 newFontSize = this.prefs_.get('font-size');
653 break;
654 case keyCodes.MINUS:
655 newFontSize = this.term.options.fontSize - 1;
656 break;
657 default:
658 newFontSize = this.term.options.fontSize + 1;
659 break;
660 }
661
Jason Linda56aa92022-09-02 13:01:49 +1000662 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +1000663 }
664
665 /** @param {!KeyboardEvent} ev */
666 ctrlCKeyDownHandler_(ev) {
667 ev.preventDefault();
668 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
669 this.term.hasSelection()) {
670 this.copySelection_();
671 return;
672 }
673
674 this.io.onVTKeystroke('\x03');
675 }
676
677 /** @param {!KeyboardEvent} ev */
678 ctrlVKeyDownHandler_(ev) {
679 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
680 // Don't do anything and let the browser handles the key.
681 return;
682 }
683
684 ev.preventDefault();
685 this.io.onVTKeystroke('\x16');
686 }
687
688 resetKeyDownHandlers_() {
689 this.keyDownHandlers_.clear();
690
691 /**
692 * Don't do anything and let the browser handles the key.
693 *
694 * @param {!KeyboardEvent} ev
695 */
696 const noop = (ev) => {};
697
698 /**
699 * @param {number} modifiers
700 * @param {number} keyCode
701 * @param {function(!KeyboardEvent)} func
702 */
703 const set = (modifiers, keyCode, func) => {
704 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
705 func);
706 };
707
708 /**
709 * @param {number} modifiers
710 * @param {number} keyCode
711 * @param {function(!KeyboardEvent)} func
712 */
713 const setWithShiftVersion = (modifiers, keyCode, func) => {
714 set(modifiers, keyCode, func);
715 set(modifiers | Modifier.Shift, keyCode, func);
716 };
717
Jason Linf51162f2022-09-01 15:21:55 +1000718 // Temporary shortcut to refresh the rendering in case of rendering errors.
719 // TODO(lxj): remove after this is fixed:
720 // https://github.com/xtermjs/xterm.js/issues/3878
721 set(Modifier.Ctrl | Modifier.Shift, keyCodes.L,
722 /** @suppress {missingProperties} */
723 () => {
724 this.scheduleRefreshFont_();
725 // Refresh the cursor layer.
726 if (this.enableWebGL_) {
727 this.term?._core?._renderService?._renderer?._renderLayers[1]
728 ?._clearAll();
729 }
730 },
731 );
Jason Lin5690e752022-08-30 15:36:45 +1000732
733 // Ctrl+/
734 set(Modifier.Ctrl, 191, (ev) => {
735 ev.preventDefault();
736 this.io.onVTKeystroke(ctl('_'));
737 });
738
739 // Settings page.
740 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
741 ev.preventDefault();
742 chrome.terminalPrivate.openOptionsPage(() => {});
743 });
744
745 if (this.prefs_.get('keybindings-os-defaults')) {
746 for (const binding of OS_DEFAULT_BINDINGS) {
747 this.keyDownHandlers_.set(binding, noop);
748 }
749 }
750
751 /** @param {!KeyboardEvent} ev */
752 const newWindow = (ev) => {
753 ev.preventDefault();
754 chrome.terminalPrivate.openWindow();
755 };
756 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
757 if (this.prefs_.get('pass-ctrl-n')) {
758 set(Modifier.Ctrl, keyCodes.N, newWindow);
759 }
760
761 if (this.prefs_.get('pass-ctrl-t')) {
762 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
763 }
764
765 if (this.prefs_.get('pass-ctrl-w')) {
766 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
767 }
768
769 if (this.prefs_.get('pass-ctrl-tab')) {
770 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
771 }
772
773 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
774
775 /**
776 * Set a handler for the key combo ctrl+<number>.
777 *
778 * @param {number} number 1 to 9
779 * @param {string} controlCode The control code to send if we don't want to
780 * let the browser to handle it.
781 */
782 const setCtrlNumberHandler = (number, controlCode) => {
783 let func = noop;
784 if (!passCtrlNumber) {
785 func = (ev) => {
786 ev.preventDefault();
787 this.io.onVTKeystroke(controlCode);
788 };
789 }
790 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
791 };
792
793 setCtrlNumberHandler(1, '1');
794 setCtrlNumberHandler(2, ctl('@'));
795 setCtrlNumberHandler(3, ctl('['));
796 setCtrlNumberHandler(4, ctl('\\'));
797 setCtrlNumberHandler(5, ctl(']'));
798 setCtrlNumberHandler(6, ctl('^'));
799 setCtrlNumberHandler(7, ctl('_'));
800 setCtrlNumberHandler(8, '\x7f');
801 setCtrlNumberHandler(9, '9');
802
803 if (this.prefs_.get('pass-alt-number')) {
804 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
805 set(Modifier.Alt, keyCode, noop);
806 }
807 }
808
809 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
810 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
811 }
812
813 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
814 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
815 }
Jason Linca61ffb2022-08-03 19:37:12 +1000816}
817
Jason Lind66e6bf2022-08-22 14:47:10 +1000818class HtermTerminal extends hterm.Terminal {
819 /** @override */
820 decorate(div) {
821 super.decorate(div);
822
823 const fontManager = new FontManager(this.getDocument());
824 fontManager.loadPowerlineCSS().then(() => {
825 const prefs = this.getPrefs();
826 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
827 prefs.addObserver(
828 'font-family',
829 (v) => fontManager.loadFont(/** @type {string} */(v)));
830 });
831 }
832}
833
Jason Linca61ffb2022-08-03 19:37:12 +1000834/**
835 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
836 * preference value.
837 *
838 * @param {{
839 * storage: !lib.Storage,
840 * profileId: string,
841 * }} args
842 * @return {!Promise<!hterm.Terminal>}
843 */
844export async function createEmulator({storage, profileId}) {
845 let config = TERMINAL_EMULATORS.get('hterm');
846
847 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +1000848 // TODO: remove the url param logic. This is temporary to make manual
849 // testing a bit easier, which is also why this is not in
850 // './js/terminal_info.js'.
851 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
852 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +1000853 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +1000854 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +1000855 TERMINAL_EMULATORS.values().next().value;
856 console.log('Terminal emulator config: ', config);
857 }
858
859 switch (config.lib) {
860 case 'xterm.js':
861 {
862 const terminal = new XtermTerminal({
863 storage,
864 profileId,
865 enableWebGL: config.webgl,
866 });
Jason Linca61ffb2022-08-03 19:37:12 +1000867 return terminal;
868 }
869 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +1000870 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +1000871 default:
872 throw new Error('incorrect emulator config');
873 }
874}
875
Jason Lin6a402a72022-08-25 16:07:02 +1000876class TerminalCopyNotice extends LitElement {
877 /** @override */
878 static get styles() {
879 return css`
880 :host {
881 display: block;
882 text-align: center;
883 }
884
885 svg {
886 fill: currentColor;
887 }
888 `;
889 }
890
891 /** @override */
892 render() {
893 return html`
894 ${ICON_COPY}
895 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
896 `;
897 }
898}
899
900customElements.define('terminal-copy-notice', TerminalCopyNotice);