blob: 9921d574e0a415cad2f54b316cd5b36b5e9c4743 [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 Lin6a402a72022-08-25 16:07:02 +1000189 this.term.onTitleChange((title) => document.title = title);
Jason Lin5690e752022-08-30 15:36:45 +1000190 this.term.onSelectionChange(() => this.copySelection_());
191
192 /**
193 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
194 *
195 * If a key combo is in the map:
196 *
197 * - The handler instead of xterm.js will handle the keydown event.
198 * - Keyup and keypress will be ignored by both us and xterm.js.
199 *
200 * We re-generate this map every time a relevant pref value is changed. This
201 * is ok because pref changes are rare.
202 *
203 * @type {!Map<number, function(!KeyboardEvent)>}
204 */
205 this.keyDownHandlers_ = new Map();
206 this.scheduleResetKeyDownHandlers_ =
207 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
208
209 this.term.attachCustomKeyEventHandler(
210 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000211
Jason Lin21d854f2022-08-22 14:49:59 +1000212 this.io = new XtermTerminalIO(this);
213 this.notificationCenter_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000214
215 this.copyNotice_ = null;
216
217 this.term.options.theme = {
218 selection: 'rgba(174, 203, 250, .6)',
219 selectionForeground: 'black',
220 customGlyphs: true,
221 };
222 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000223 }
224
225 /**
226 * Install stubs for stuff that we haven't implemented yet so that the code
227 * still runs.
228 */
229 installUnimplementedStubs_() {
230 this.keyboard = {
231 keyMap: {
232 keyDefs: [],
233 },
234 bindings: {
235 clear: () => {},
236 addBinding: () => {},
237 addBindings: () => {},
238 OsDefaults: {},
239 },
240 };
241 this.keyboard.keyMap.keyDefs[78] = {};
242
243 const methodNames = [
Jason Linca61ffb2022-08-03 19:37:12 +1000244 'setAccessibilityEnabled',
245 'setBackgroundImage',
246 'setCursorPosition',
247 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000248 ];
249
250 for (const name of methodNames) {
251 this[name] = () => console.warn(`${name}() is not implemented`);
252 }
253
254 this.contextMenu = {
255 setItems: () => {
256 console.warn('.contextMenu.setItems() is not implemented');
257 },
258 };
Jason Lin21d854f2022-08-22 14:49:59 +1000259
260 this.vt = {
261 resetParseState: () => {
262 console.warn('.vt.resetParseState() is not implemented');
263 },
264 };
Jason Linca61ffb2022-08-03 19:37:12 +1000265 }
266
Jason Line9231bc2022-09-01 13:54:02 +1000267 installEscapeSequenceHandlers_() {
268 // OSC 52 for copy.
269 this.term.parser.registerOscHandler(52, (args) => {
270 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
271 // parameter is used to select which of the X clipboards to address. Since
272 // we're not integrating with X, we treat them all the same.
273 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
274 if (!parsedArgs) {
275 return true;
276 }
277
278 let data;
279 try {
280 data = window.atob(parsedArgs[1]);
281 } catch (e) {
282 // If the user sent us invalid base64 content, silently ignore it.
283 return true;
284 }
285 const decoder = new TextDecoder();
286 const bytes = lib.codec.stringToCodeUnitArray(data);
287 this.copyString_(decoder.decode(bytes));
288
289 return true;
290 });
291 }
292
Jason Linca61ffb2022-08-03 19:37:12 +1000293 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000294 * Write data to the terminal.
295 *
296 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
297 * UTF-8 data
298 */
299 write(data) {
300 this.term.write(data);
301 }
302
303 /**
304 * Like `this.write()` but also write a line break.
305 *
306 * @param {string|!Uint8Array} data
307 */
308 writeln(data) {
309 this.term.writeln(data);
310 }
311
Jason Linca61ffb2022-08-03 19:37:12 +1000312 get screenSize() {
313 return new hterm.Size(this.term.cols, this.term.rows);
314 }
315
316 /**
317 * Don't need to do anything.
318 *
319 * @override
320 */
321 installKeyboard() {}
322
323 /**
324 * @override
325 */
326 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000327 this.container_ = elem;
Jason Lin8de3d282022-09-01 21:29:05 +1000328 (async () => {
329 await new Promise((resolve) => this.prefs_.readStorage(resolve));
330 // This will trigger all the observers to set the terminal options before
331 // we call `this.term.open()`.
332 this.prefs_.notifyAll();
333
Jason Linc2504ae2022-09-02 13:03:31 +1000334 const screenPaddingSize = /** @type {number} */(
335 this.prefs_.get('screen-padding-size'));
336 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
337
Jason Lin8de3d282022-09-01 21:29:05 +1000338 this.inited_ = true;
339 this.term.open(elem);
340
341 this.scheduleFit_();
342 if (this.enableWebGL_) {
343 this.term.loadAddon(new WebglAddon());
344 }
345 this.term.focus();
346 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
347 // TODO: Make a11y work. Maybe we can just use hterm.AccessibilityReader.
348 this.notificationCenter_ = new hterm.NotificationCenter(document.body);
349
350 this.onTerminalReady();
351 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000352 }
353
354 /** @override */
355 showOverlay(msg, timeout = 1500) {
356 if (this.notificationCenter_) {
357 this.notificationCenter_.show(msg, {timeout});
358 }
359 }
360
361 /** @override */
362 hideOverlay() {
363 if (this.notificationCenter_) {
364 this.notificationCenter_.hide();
365 }
Jason Linca61ffb2022-08-03 19:37:12 +1000366 }
367
368 /** @override */
369 getPrefs() {
370 return this.prefs_;
371 }
372
373 /** @override */
374 getDocument() {
375 return window.document;
376 }
377
Jason Lin21d854f2022-08-22 14:49:59 +1000378 /** @override */
379 reset() {
380 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000381 }
382
383 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000384 setProfile(profileId, callback = undefined) {
385 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000386 }
387
Jason Lin21d854f2022-08-22 14:49:59 +1000388 /** @override */
389 interpret(string) {
390 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000391 }
392
Jason Lin21d854f2022-08-22 14:49:59 +1000393 /** @override */
394 focus() {
395 this.term.focus();
396 }
Jason Linca61ffb2022-08-03 19:37:12 +1000397
398 /** @override */
399 onOpenOptionsPage() {}
400
401 /** @override */
402 onTerminalReady() {}
403
Jason Lind04bab32022-08-22 14:48:39 +1000404 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000405 // This is for this.notificationCenter_.
406 const setHtermCSSVariable = (name, value) => {
407 document.body.style.setProperty(`--hterm-${name}`, value);
408 };
409
410 const setHtermColorCSSVariable = (name, color) => {
411 const css = lib.notNull(lib.colors.normalizeCSS(color));
412 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
413 setHtermCSSVariable(name, rgb);
414 };
415
416 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000417 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000418 setHtermCSSVariable('font-size', `${v}px`);
419 });
420
Jason Linda56aa92022-09-02 13:01:49 +1000421 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000422 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000423 'audible-bell-sound': (v) => {
424 if (v) {
425 this.updateOption_('bellStyle', 'sound', false);
426 this.updateOption_('bellSound', lib.resource.getDataUrl(
427 'hterm/audio/bell'), false);
428 } else {
429 this.updateOption_('bellStyle', 'none', false);
430 }
431 },
Jason Lind04bab32022-08-22 14:48:39 +1000432 'background-color': (v) => {
433 this.updateTheme_({background: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000434 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000435 },
Jason Lind04bab32022-08-22 14:48:39 +1000436 '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 },
Jason Linda56aa92022-09-02 13:01:49 +1000448 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
449 'cursor-color': (v) => this.updateTheme_({cursor: v}),
450 'cursor-shape': (v) => {
451 let shape;
452 if (v === 'BEAM') {
453 shape = 'bar';
454 } else {
455 shape = v.toLowerCase();
456 }
457 this.updateOption_('cursorStyle', shape, false);
458 },
459 'font-family': (v) => this.updateFont_(v),
460 'foreground-color': (v) => {
461 // TODO(lxj): setting the cursorAccent to the foreground color mimics
462 // what hterm does, but I think it is better to expose this option.
463 this.updateTheme_({foreground: v, cursorAccent: v});
464 setHtermColorCSSVariable('foreground-color', v);
465 },
Jason Lind04bab32022-08-22 14:48:39 +1000466 });
Jason Lin5690e752022-08-30 15:36:45 +1000467
468 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
469 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
470 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
471 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
472 }
Jason Lind04bab32022-08-22 14:48:39 +1000473 }
474
475 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000476 * Fit the terminal to the containing HTML element.
477 */
478 fit_() {
479 if (!this.inited_) {
480 return;
481 }
482
483 const screenPaddingSize = /** @type {number} */(
484 this.prefs_.get('screen-padding-size'));
485
486 const calc = (size, cellSize) => {
487 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
488 };
489
490 // Unfortunately, it looks like we have to use private API from xterm.js.
491 // Maybe we should patch the FitAddon so that it works for us.
492 const dimensions = this.term._core._renderService.dimensions;
493 const cols = calc(this.container_.offsetWidth, dimensions.actualCellWidth);
494 const rows = calc(this.container_.offsetHeight,
495 dimensions.actualCellHeight);
496 if (cols >= 0 && rows >= 0) {
497 this.term.resize(cols, rows);
498 }
499 }
500
501 /**
Jason Lind04bab32022-08-22 14:48:39 +1000502 * @param {!Object} theme
503 */
504 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000505 const updateTheme = (target) => {
506 for (const [key, value] of Object.entries(theme)) {
507 target[key] = lib.colors.normalizeCSS(value);
508 }
509 };
510
511 // Must use a new theme object to trigger re-render if we have initialized.
512 if (this.inited_) {
513 const newTheme = {...this.term.options.theme};
514 updateTheme(newTheme);
515 this.term.options.theme = newTheme;
516 return;
Jason Lind04bab32022-08-22 14:48:39 +1000517 }
Jason Lin8de3d282022-09-01 21:29:05 +1000518
519 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000520 }
521
522 /**
Jason Linda56aa92022-09-02 13:01:49 +1000523 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
524 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000525 *
526 * @param {string} key
527 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000528 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000529 */
Jason Linda56aa92022-09-02 13:01:49 +1000530 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000531 // TODO: xterm supports updating multiple options at the same time. We
532 // should probably do that.
533 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000534 if (scheduleFit) {
535 this.scheduleFit_();
536 }
Jason Lind04bab32022-08-22 14:48:39 +1000537 }
Jason Linabad7562022-08-22 14:49:05 +1000538
539 /**
540 * Called when there is a "fontloadingdone" event. We need this because
541 * `FontManager.loadFont()` does not guarantee loading all the font files.
542 */
543 async onFontLoadingDone_() {
544 // If there is a pending font, the font is going to be refresh soon, so we
545 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000546 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000547 this.scheduleRefreshFont_();
548 }
549 }
550
Jason Lin5690e752022-08-30 15:36:45 +1000551 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000552 this.copyString_(this.term.getSelection());
553 }
554
555 /** @param {string} data */
556 copyString_(data) {
557 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000558 return;
559 }
Jason Line9231bc2022-09-01 13:54:02 +1000560 navigator.clipboard?.writeText(data);
Jason Lin6a402a72022-08-25 16:07:02 +1000561 if (!this.copyNotice_) {
562 this.copyNotice_ = document.createElement('terminal-copy-notice');
563 }
564 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200);
565 }
566
Jason Linabad7562022-08-22 14:49:05 +1000567 /**
568 * Refresh xterm rendering for a font related event.
569 */
570 refreshFont_() {
571 // We have to set the fontFamily option to a different string to trigger the
572 // re-rendering. Appending a space at the end seems to be the easiest
573 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
574 // us.
575 //
576 // TODO: Report a bug to xterm.js and ask for exposing a public function for
577 // the refresh so that we don't need to do this hack.
578 this.term.options.fontFamily += ' ';
579 }
580
581 /**
582 * Update a font.
583 *
584 * @param {string} cssFontFamily
585 */
586 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000587 this.pendingFont_ = cssFontFamily;
588 await this.fontManager_.loadFont(cssFontFamily);
589 // Sleep a bit to wait for flushing fontloadingdone events. This is not
590 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
591 // to refresh font unnecessarily in some cases.
592 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000593
Jason Lin6a402a72022-08-25 16:07:02 +1000594 if (this.pendingFont_ !== cssFontFamily) {
595 // `updateFont_()` probably is called again. Abort what we are doing.
596 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
597 ` (expecting ${cssFontFamily})`);
598 return;
599 }
Jason Linabad7562022-08-22 14:49:05 +1000600
Jason Lin6a402a72022-08-25 16:07:02 +1000601 if (this.term.options.fontFamily !== cssFontFamily) {
602 this.term.options.fontFamily = cssFontFamily;
603 } else {
604 // If the font is already the same, refresh font just to be safe.
605 this.refreshFont_();
606 }
607 this.pendingFont_ = null;
608 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000609 }
Jason Lin5690e752022-08-30 15:36:45 +1000610
611 /**
612 * @param {!KeyboardEvent} ev
613 * @return {boolean} Return false if xterm.js should not handle the key event.
614 */
615 customKeyEventHandler_(ev) {
616 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
617 (ev.altKey ? Modifier.Alt : 0) |
618 (ev.ctrlKey ? Modifier.Ctrl : 0) |
619 (ev.metaKey ? Modifier.Meta : 0);
620 const handler = this.keyDownHandlers_.get(
621 encodeKeyCombo(modifiers, ev.keyCode));
622 if (handler) {
623 if (ev.type === 'keydown') {
624 handler(ev);
625 }
626 return false;
627 }
628
629 return true;
630 }
631
632 /**
633 * A keydown handler for zoom-related keys.
634 *
635 * @param {!KeyboardEvent} ev
636 */
637 zoomKeyDownHandler_(ev) {
638 ev.preventDefault();
639
640 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
641 // The only one with a control code.
642 if (ev.keyCode === keyCodes.MINUS) {
643 this.io.onVTKeystroke('\x1f');
644 }
645 return;
646 }
647
648 let newFontSize;
649 switch (ev.keyCode) {
650 case keyCodes.ZERO:
651 newFontSize = this.prefs_.get('font-size');
652 break;
653 case keyCodes.MINUS:
654 newFontSize = this.term.options.fontSize - 1;
655 break;
656 default:
657 newFontSize = this.term.options.fontSize + 1;
658 break;
659 }
660
Jason Linda56aa92022-09-02 13:01:49 +1000661 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +1000662 }
663
664 /** @param {!KeyboardEvent} ev */
665 ctrlCKeyDownHandler_(ev) {
666 ev.preventDefault();
667 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
668 this.term.hasSelection()) {
669 this.copySelection_();
670 return;
671 }
672
673 this.io.onVTKeystroke('\x03');
674 }
675
676 /** @param {!KeyboardEvent} ev */
677 ctrlVKeyDownHandler_(ev) {
678 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
679 // Don't do anything and let the browser handles the key.
680 return;
681 }
682
683 ev.preventDefault();
684 this.io.onVTKeystroke('\x16');
685 }
686
687 resetKeyDownHandlers_() {
688 this.keyDownHandlers_.clear();
689
690 /**
691 * Don't do anything and let the browser handles the key.
692 *
693 * @param {!KeyboardEvent} ev
694 */
695 const noop = (ev) => {};
696
697 /**
698 * @param {number} modifiers
699 * @param {number} keyCode
700 * @param {function(!KeyboardEvent)} func
701 */
702 const set = (modifiers, keyCode, func) => {
703 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
704 func);
705 };
706
707 /**
708 * @param {number} modifiers
709 * @param {number} keyCode
710 * @param {function(!KeyboardEvent)} func
711 */
712 const setWithShiftVersion = (modifiers, keyCode, func) => {
713 set(modifiers, keyCode, func);
714 set(modifiers | Modifier.Shift, keyCode, func);
715 };
716
Jason Linf51162f2022-09-01 15:21:55 +1000717 // Temporary shortcut to refresh the rendering in case of rendering errors.
718 // TODO(lxj): remove after this is fixed:
719 // https://github.com/xtermjs/xterm.js/issues/3878
720 set(Modifier.Ctrl | Modifier.Shift, keyCodes.L,
721 /** @suppress {missingProperties} */
722 () => {
723 this.scheduleRefreshFont_();
724 // Refresh the cursor layer.
725 if (this.enableWebGL_) {
726 this.term?._core?._renderService?._renderer?._renderLayers[1]
727 ?._clearAll();
728 }
729 },
730 );
Jason Lin5690e752022-08-30 15:36:45 +1000731
732 // Ctrl+/
733 set(Modifier.Ctrl, 191, (ev) => {
734 ev.preventDefault();
735 this.io.onVTKeystroke(ctl('_'));
736 });
737
738 // Settings page.
739 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
740 ev.preventDefault();
741 chrome.terminalPrivate.openOptionsPage(() => {});
742 });
743
744 if (this.prefs_.get('keybindings-os-defaults')) {
745 for (const binding of OS_DEFAULT_BINDINGS) {
746 this.keyDownHandlers_.set(binding, noop);
747 }
748 }
749
750 /** @param {!KeyboardEvent} ev */
751 const newWindow = (ev) => {
752 ev.preventDefault();
753 chrome.terminalPrivate.openWindow();
754 };
755 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
756 if (this.prefs_.get('pass-ctrl-n')) {
757 set(Modifier.Ctrl, keyCodes.N, newWindow);
758 }
759
760 if (this.prefs_.get('pass-ctrl-t')) {
761 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
762 }
763
764 if (this.prefs_.get('pass-ctrl-w')) {
765 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
766 }
767
768 if (this.prefs_.get('pass-ctrl-tab')) {
769 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
770 }
771
772 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
773
774 /**
775 * Set a handler for the key combo ctrl+<number>.
776 *
777 * @param {number} number 1 to 9
778 * @param {string} controlCode The control code to send if we don't want to
779 * let the browser to handle it.
780 */
781 const setCtrlNumberHandler = (number, controlCode) => {
782 let func = noop;
783 if (!passCtrlNumber) {
784 func = (ev) => {
785 ev.preventDefault();
786 this.io.onVTKeystroke(controlCode);
787 };
788 }
789 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
790 };
791
792 setCtrlNumberHandler(1, '1');
793 setCtrlNumberHandler(2, ctl('@'));
794 setCtrlNumberHandler(3, ctl('['));
795 setCtrlNumberHandler(4, ctl('\\'));
796 setCtrlNumberHandler(5, ctl(']'));
797 setCtrlNumberHandler(6, ctl('^'));
798 setCtrlNumberHandler(7, ctl('_'));
799 setCtrlNumberHandler(8, '\x7f');
800 setCtrlNumberHandler(9, '9');
801
802 if (this.prefs_.get('pass-alt-number')) {
803 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
804 set(Modifier.Alt, keyCode, noop);
805 }
806 }
807
808 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
809 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
810 }
811
812 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
813 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
814 }
Jason Linca61ffb2022-08-03 19:37:12 +1000815}
816
Jason Lind66e6bf2022-08-22 14:47:10 +1000817class HtermTerminal extends hterm.Terminal {
818 /** @override */
819 decorate(div) {
820 super.decorate(div);
821
822 const fontManager = new FontManager(this.getDocument());
823 fontManager.loadPowerlineCSS().then(() => {
824 const prefs = this.getPrefs();
825 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
826 prefs.addObserver(
827 'font-family',
828 (v) => fontManager.loadFont(/** @type {string} */(v)));
829 });
830 }
831}
832
Jason Linca61ffb2022-08-03 19:37:12 +1000833/**
834 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
835 * preference value.
836 *
837 * @param {{
838 * storage: !lib.Storage,
839 * profileId: string,
840 * }} args
841 * @return {!Promise<!hterm.Terminal>}
842 */
843export async function createEmulator({storage, profileId}) {
844 let config = TERMINAL_EMULATORS.get('hterm');
845
846 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +1000847 // TODO: remove the url param logic. This is temporary to make manual
848 // testing a bit easier, which is also why this is not in
849 // './js/terminal_info.js'.
850 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
851 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +1000852 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +1000853 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +1000854 TERMINAL_EMULATORS.values().next().value;
855 console.log('Terminal emulator config: ', config);
856 }
857
858 switch (config.lib) {
859 case 'xterm.js':
860 {
861 const terminal = new XtermTerminal({
862 storage,
863 profileId,
864 enableWebGL: config.webgl,
865 });
Jason Linca61ffb2022-08-03 19:37:12 +1000866 return terminal;
867 }
868 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +1000869 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +1000870 default:
871 throw new Error('incorrect emulator config');
872 }
873}
874
Jason Lin6a402a72022-08-25 16:07:02 +1000875class TerminalCopyNotice extends LitElement {
876 /** @override */
877 static get styles() {
878 return css`
879 :host {
880 display: block;
881 text-align: center;
882 }
883
884 svg {
885 fill: currentColor;
886 }
887 `;
888 }
889
890 /** @override */
891 render() {
892 return html`
893 ${ICON_COPY}
894 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
895 `;
896 }
897}
898
899customElements.define('terminal-copy-notice', TerminalCopyNotice);