blob: 3ab74d07d2f7c4d387b9b00084990a31b99e21e8 [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 Linfc8a3722022-09-07 17:49:18 +1000163 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Linabad7562022-08-22 14:49:05 +1000164 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 = {
Jason Lin461ca562022-09-07 13:53:08 +1000219 // The webgl cursor layer also paints the character under the cursor with
220 // this `cursorAccent` color. We use a completely transparent color here
221 // to effectively disable that.
222 cursorAccent: 'rgba(0, 0, 0, 0)',
223 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000224 selectionBackground: 'rgba(174, 203, 250, .6)',
225 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000226 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000227 };
228 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000229 }
230
231 /**
232 * Install stubs for stuff that we haven't implemented yet so that the code
233 * still runs.
234 */
235 installUnimplementedStubs_() {
236 this.keyboard = {
237 keyMap: {
238 keyDefs: [],
239 },
240 bindings: {
241 clear: () => {},
242 addBinding: () => {},
243 addBindings: () => {},
244 OsDefaults: {},
245 },
246 };
247 this.keyboard.keyMap.keyDefs[78] = {};
248
249 const methodNames = [
Jason Linca61ffb2022-08-03 19:37:12 +1000250 'setAccessibilityEnabled',
251 'setBackgroundImage',
252 'setCursorPosition',
253 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000254 ];
255
256 for (const name of methodNames) {
257 this[name] = () => console.warn(`${name}() is not implemented`);
258 }
259
260 this.contextMenu = {
261 setItems: () => {
262 console.warn('.contextMenu.setItems() is not implemented');
263 },
264 };
Jason Lin21d854f2022-08-22 14:49:59 +1000265
266 this.vt = {
267 resetParseState: () => {
268 console.warn('.vt.resetParseState() is not implemented');
269 },
270 };
Jason Linca61ffb2022-08-03 19:37:12 +1000271 }
272
Jason Line9231bc2022-09-01 13:54:02 +1000273 installEscapeSequenceHandlers_() {
274 // OSC 52 for copy.
275 this.term.parser.registerOscHandler(52, (args) => {
276 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
277 // parameter is used to select which of the X clipboards to address. Since
278 // we're not integrating with X, we treat them all the same.
279 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
280 if (!parsedArgs) {
281 return true;
282 }
283
284 let data;
285 try {
286 data = window.atob(parsedArgs[1]);
287 } catch (e) {
288 // If the user sent us invalid base64 content, silently ignore it.
289 return true;
290 }
291 const decoder = new TextDecoder();
292 const bytes = lib.codec.stringToCodeUnitArray(data);
293 this.copyString_(decoder.decode(bytes));
294
295 return true;
296 });
297 }
298
Jason Linca61ffb2022-08-03 19:37:12 +1000299 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000300 * Write data to the terminal.
301 *
302 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
303 * UTF-8 data
304 */
305 write(data) {
306 this.term.write(data);
307 }
308
309 /**
310 * Like `this.write()` but also write a line break.
311 *
312 * @param {string|!Uint8Array} data
313 */
314 writeln(data) {
315 this.term.writeln(data);
316 }
317
Jason Linca61ffb2022-08-03 19:37:12 +1000318 get screenSize() {
319 return new hterm.Size(this.term.cols, this.term.rows);
320 }
321
322 /**
323 * Don't need to do anything.
324 *
325 * @override
326 */
327 installKeyboard() {}
328
329 /**
330 * @override
331 */
332 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000333 this.container_ = elem;
Jason Lin8de3d282022-09-01 21:29:05 +1000334 (async () => {
335 await new Promise((resolve) => this.prefs_.readStorage(resolve));
336 // This will trigger all the observers to set the terminal options before
337 // we call `this.term.open()`.
338 this.prefs_.notifyAll();
339
Jason Linc2504ae2022-09-02 13:03:31 +1000340 const screenPaddingSize = /** @type {number} */(
341 this.prefs_.get('screen-padding-size'));
342 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
343
Jason Lin8de3d282022-09-01 21:29:05 +1000344 this.inited_ = true;
345 this.term.open(elem);
346
347 this.scheduleFit_();
348 if (this.enableWebGL_) {
349 this.term.loadAddon(new WebglAddon());
350 }
351 this.term.focus();
352 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
353 // TODO: Make a11y work. Maybe we can just use hterm.AccessibilityReader.
354 this.notificationCenter_ = new hterm.NotificationCenter(document.body);
355
356 this.onTerminalReady();
357 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000358 }
359
360 /** @override */
361 showOverlay(msg, timeout = 1500) {
362 if (this.notificationCenter_) {
363 this.notificationCenter_.show(msg, {timeout});
364 }
365 }
366
367 /** @override */
368 hideOverlay() {
369 if (this.notificationCenter_) {
370 this.notificationCenter_.hide();
371 }
Jason Linca61ffb2022-08-03 19:37:12 +1000372 }
373
374 /** @override */
375 getPrefs() {
376 return this.prefs_;
377 }
378
379 /** @override */
380 getDocument() {
381 return window.document;
382 }
383
Jason Lin21d854f2022-08-22 14:49:59 +1000384 /** @override */
385 reset() {
386 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000387 }
388
389 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000390 setProfile(profileId, callback = undefined) {
391 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000392 }
393
Jason Lin21d854f2022-08-22 14:49:59 +1000394 /** @override */
395 interpret(string) {
396 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000397 }
398
Jason Lin21d854f2022-08-22 14:49:59 +1000399 /** @override */
400 focus() {
401 this.term.focus();
402 }
Jason Linca61ffb2022-08-03 19:37:12 +1000403
404 /** @override */
405 onOpenOptionsPage() {}
406
407 /** @override */
408 onTerminalReady() {}
409
Jason Lind04bab32022-08-22 14:48:39 +1000410 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000411 // This is for this.notificationCenter_.
412 const setHtermCSSVariable = (name, value) => {
413 document.body.style.setProperty(`--hterm-${name}`, value);
414 };
415
416 const setHtermColorCSSVariable = (name, color) => {
417 const css = lib.notNull(lib.colors.normalizeCSS(color));
418 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
419 setHtermCSSVariable(name, rgb);
420 };
421
422 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000423 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000424 setHtermCSSVariable('font-size', `${v}px`);
425 });
426
Jason Linda56aa92022-09-02 13:01:49 +1000427 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000428 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000429 'audible-bell-sound': (v) => {
430 if (v) {
431 this.updateOption_('bellStyle', 'sound', false);
432 this.updateOption_('bellSound', lib.resource.getDataUrl(
433 'hterm/audio/bell'), false);
434 } else {
435 this.updateOption_('bellStyle', 'none', false);
436 }
437 },
Jason Lind04bab32022-08-22 14:48:39 +1000438 'background-color': (v) => {
439 this.updateTheme_({background: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000440 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000441 },
Jason Lind04bab32022-08-22 14:48:39 +1000442 'color-palette-overrides': (v) => {
443 if (!(v instanceof Array)) {
444 // For terminal, we always expect this to be an array.
445 console.warn('unexpected color palette: ', v);
446 return;
447 }
448 const colors = {};
449 for (let i = 0; i < v.length; ++i) {
450 colors[ANSI_COLOR_NAMES[i]] = v[i];
451 }
452 this.updateTheme_(colors);
453 },
Jason Linda56aa92022-09-02 13:01:49 +1000454 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
455 'cursor-color': (v) => this.updateTheme_({cursor: v}),
456 'cursor-shape': (v) => {
457 let shape;
458 if (v === 'BEAM') {
459 shape = 'bar';
460 } else {
461 shape = v.toLowerCase();
462 }
463 this.updateOption_('cursorStyle', shape, false);
464 },
465 'font-family': (v) => this.updateFont_(v),
466 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000467 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000468 setHtermColorCSSVariable('foreground-color', v);
469 },
Jason Lind04bab32022-08-22 14:48:39 +1000470 });
Jason Lin5690e752022-08-30 15:36:45 +1000471
472 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
473 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
474 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
475 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
476 }
Jason Lind04bab32022-08-22 14:48:39 +1000477 }
478
479 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000480 * Fit the terminal to the containing HTML element.
481 */
482 fit_() {
483 if (!this.inited_) {
484 return;
485 }
486
487 const screenPaddingSize = /** @type {number} */(
488 this.prefs_.get('screen-padding-size'));
489
490 const calc = (size, cellSize) => {
491 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
492 };
493
494 // Unfortunately, it looks like we have to use private API from xterm.js.
495 // Maybe we should patch the FitAddon so that it works for us.
496 const dimensions = this.term._core._renderService.dimensions;
497 const cols = calc(this.container_.offsetWidth, dimensions.actualCellWidth);
498 const rows = calc(this.container_.offsetHeight,
499 dimensions.actualCellHeight);
500 if (cols >= 0 && rows >= 0) {
501 this.term.resize(cols, rows);
502 }
503 }
504
505 /**
Jason Lind04bab32022-08-22 14:48:39 +1000506 * @param {!Object} theme
507 */
508 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000509 const updateTheme = (target) => {
510 for (const [key, value] of Object.entries(theme)) {
511 target[key] = lib.colors.normalizeCSS(value);
512 }
513 };
514
515 // Must use a new theme object to trigger re-render if we have initialized.
516 if (this.inited_) {
517 const newTheme = {...this.term.options.theme};
518 updateTheme(newTheme);
519 this.term.options.theme = newTheme;
520 return;
Jason Lind04bab32022-08-22 14:48:39 +1000521 }
Jason Lin8de3d282022-09-01 21:29:05 +1000522
523 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000524 }
525
526 /**
Jason Linda56aa92022-09-02 13:01:49 +1000527 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
528 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000529 *
530 * @param {string} key
531 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000532 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000533 */
Jason Linda56aa92022-09-02 13:01:49 +1000534 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000535 // TODO: xterm supports updating multiple options at the same time. We
536 // should probably do that.
537 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000538 if (scheduleFit) {
539 this.scheduleFit_();
540 }
Jason Lind04bab32022-08-22 14:48:39 +1000541 }
Jason Linabad7562022-08-22 14:49:05 +1000542
543 /**
544 * Called when there is a "fontloadingdone" event. We need this because
545 * `FontManager.loadFont()` does not guarantee loading all the font files.
546 */
547 async onFontLoadingDone_() {
548 // If there is a pending font, the font is going to be refresh soon, so we
549 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000550 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000551 this.scheduleRefreshFont_();
552 }
553 }
554
Jason Lin5690e752022-08-30 15:36:45 +1000555 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000556 this.copyString_(this.term.getSelection());
557 }
558
559 /** @param {string} data */
560 copyString_(data) {
561 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000562 return;
563 }
Jason Line9231bc2022-09-01 13:54:02 +1000564 navigator.clipboard?.writeText(data);
Jason Lin6a402a72022-08-25 16:07:02 +1000565 if (!this.copyNotice_) {
566 this.copyNotice_ = document.createElement('terminal-copy-notice');
567 }
568 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200);
569 }
570
Jason Linabad7562022-08-22 14:49:05 +1000571 /**
572 * Refresh xterm rendering for a font related event.
573 */
574 refreshFont_() {
575 // We have to set the fontFamily option to a different string to trigger the
576 // re-rendering. Appending a space at the end seems to be the easiest
577 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
578 // us.
579 //
580 // TODO: Report a bug to xterm.js and ask for exposing a public function for
581 // the refresh so that we don't need to do this hack.
582 this.term.options.fontFamily += ' ';
583 }
584
585 /**
586 * Update a font.
587 *
588 * @param {string} cssFontFamily
589 */
590 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000591 this.pendingFont_ = cssFontFamily;
592 await this.fontManager_.loadFont(cssFontFamily);
593 // Sleep a bit to wait for flushing fontloadingdone events. This is not
594 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
595 // to refresh font unnecessarily in some cases.
596 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000597
Jason Lin6a402a72022-08-25 16:07:02 +1000598 if (this.pendingFont_ !== cssFontFamily) {
599 // `updateFont_()` probably is called again. Abort what we are doing.
600 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
601 ` (expecting ${cssFontFamily})`);
602 return;
603 }
Jason Linabad7562022-08-22 14:49:05 +1000604
Jason Lin6a402a72022-08-25 16:07:02 +1000605 if (this.term.options.fontFamily !== cssFontFamily) {
606 this.term.options.fontFamily = cssFontFamily;
607 } else {
608 // If the font is already the same, refresh font just to be safe.
609 this.refreshFont_();
610 }
611 this.pendingFont_ = null;
612 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000613 }
Jason Lin5690e752022-08-30 15:36:45 +1000614
615 /**
616 * @param {!KeyboardEvent} ev
617 * @return {boolean} Return false if xterm.js should not handle the key event.
618 */
619 customKeyEventHandler_(ev) {
620 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
621 (ev.altKey ? Modifier.Alt : 0) |
622 (ev.ctrlKey ? Modifier.Ctrl : 0) |
623 (ev.metaKey ? Modifier.Meta : 0);
624 const handler = this.keyDownHandlers_.get(
625 encodeKeyCombo(modifiers, ev.keyCode));
626 if (handler) {
627 if (ev.type === 'keydown') {
628 handler(ev);
629 }
630 return false;
631 }
632
633 return true;
634 }
635
636 /**
637 * A keydown handler for zoom-related keys.
638 *
639 * @param {!KeyboardEvent} ev
640 */
641 zoomKeyDownHandler_(ev) {
642 ev.preventDefault();
643
644 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
645 // The only one with a control code.
646 if (ev.keyCode === keyCodes.MINUS) {
647 this.io.onVTKeystroke('\x1f');
648 }
649 return;
650 }
651
652 let newFontSize;
653 switch (ev.keyCode) {
654 case keyCodes.ZERO:
655 newFontSize = this.prefs_.get('font-size');
656 break;
657 case keyCodes.MINUS:
658 newFontSize = this.term.options.fontSize - 1;
659 break;
660 default:
661 newFontSize = this.term.options.fontSize + 1;
662 break;
663 }
664
Jason Linda56aa92022-09-02 13:01:49 +1000665 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +1000666 }
667
668 /** @param {!KeyboardEvent} ev */
669 ctrlCKeyDownHandler_(ev) {
670 ev.preventDefault();
671 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
672 this.term.hasSelection()) {
673 this.copySelection_();
674 return;
675 }
676
677 this.io.onVTKeystroke('\x03');
678 }
679
680 /** @param {!KeyboardEvent} ev */
681 ctrlVKeyDownHandler_(ev) {
682 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
683 // Don't do anything and let the browser handles the key.
684 return;
685 }
686
687 ev.preventDefault();
688 this.io.onVTKeystroke('\x16');
689 }
690
691 resetKeyDownHandlers_() {
692 this.keyDownHandlers_.clear();
693
694 /**
695 * Don't do anything and let the browser handles the key.
696 *
697 * @param {!KeyboardEvent} ev
698 */
699 const noop = (ev) => {};
700
701 /**
702 * @param {number} modifiers
703 * @param {number} keyCode
704 * @param {function(!KeyboardEvent)} func
705 */
706 const set = (modifiers, keyCode, func) => {
707 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
708 func);
709 };
710
711 /**
712 * @param {number} modifiers
713 * @param {number} keyCode
714 * @param {function(!KeyboardEvent)} func
715 */
716 const setWithShiftVersion = (modifiers, keyCode, func) => {
717 set(modifiers, keyCode, func);
718 set(modifiers | Modifier.Shift, keyCode, func);
719 };
720
Jason Linf51162f2022-09-01 15:21:55 +1000721 // Temporary shortcut to refresh the rendering in case of rendering errors.
722 // TODO(lxj): remove after this is fixed:
723 // https://github.com/xtermjs/xterm.js/issues/3878
724 set(Modifier.Ctrl | Modifier.Shift, keyCodes.L,
725 /** @suppress {missingProperties} */
726 () => {
727 this.scheduleRefreshFont_();
728 // Refresh the cursor layer.
729 if (this.enableWebGL_) {
730 this.term?._core?._renderService?._renderer?._renderLayers[1]
731 ?._clearAll();
732 }
733 },
734 );
Jason Lin5690e752022-08-30 15:36:45 +1000735
736 // Ctrl+/
737 set(Modifier.Ctrl, 191, (ev) => {
738 ev.preventDefault();
739 this.io.onVTKeystroke(ctl('_'));
740 });
741
742 // Settings page.
743 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
744 ev.preventDefault();
745 chrome.terminalPrivate.openOptionsPage(() => {});
746 });
747
748 if (this.prefs_.get('keybindings-os-defaults')) {
749 for (const binding of OS_DEFAULT_BINDINGS) {
750 this.keyDownHandlers_.set(binding, noop);
751 }
752 }
753
754 /** @param {!KeyboardEvent} ev */
755 const newWindow = (ev) => {
756 ev.preventDefault();
757 chrome.terminalPrivate.openWindow();
758 };
759 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
760 if (this.prefs_.get('pass-ctrl-n')) {
761 set(Modifier.Ctrl, keyCodes.N, newWindow);
762 }
763
764 if (this.prefs_.get('pass-ctrl-t')) {
765 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
766 }
767
768 if (this.prefs_.get('pass-ctrl-w')) {
769 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
770 }
771
772 if (this.prefs_.get('pass-ctrl-tab')) {
773 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
774 }
775
776 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
777
778 /**
779 * Set a handler for the key combo ctrl+<number>.
780 *
781 * @param {number} number 1 to 9
782 * @param {string} controlCode The control code to send if we don't want to
783 * let the browser to handle it.
784 */
785 const setCtrlNumberHandler = (number, controlCode) => {
786 let func = noop;
787 if (!passCtrlNumber) {
788 func = (ev) => {
789 ev.preventDefault();
790 this.io.onVTKeystroke(controlCode);
791 };
792 }
793 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
794 };
795
796 setCtrlNumberHandler(1, '1');
797 setCtrlNumberHandler(2, ctl('@'));
798 setCtrlNumberHandler(3, ctl('['));
799 setCtrlNumberHandler(4, ctl('\\'));
800 setCtrlNumberHandler(5, ctl(']'));
801 setCtrlNumberHandler(6, ctl('^'));
802 setCtrlNumberHandler(7, ctl('_'));
803 setCtrlNumberHandler(8, '\x7f');
804 setCtrlNumberHandler(9, '9');
805
806 if (this.prefs_.get('pass-alt-number')) {
807 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
808 set(Modifier.Alt, keyCode, noop);
809 }
810 }
811
812 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
813 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
814 }
815
816 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
817 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
818 }
Jason Linca61ffb2022-08-03 19:37:12 +1000819}
820
Jason Lind66e6bf2022-08-22 14:47:10 +1000821class HtermTerminal extends hterm.Terminal {
822 /** @override */
823 decorate(div) {
824 super.decorate(div);
825
826 const fontManager = new FontManager(this.getDocument());
827 fontManager.loadPowerlineCSS().then(() => {
828 const prefs = this.getPrefs();
829 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
830 prefs.addObserver(
831 'font-family',
832 (v) => fontManager.loadFont(/** @type {string} */(v)));
833 });
834 }
835}
836
Jason Linca61ffb2022-08-03 19:37:12 +1000837/**
838 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
839 * preference value.
840 *
841 * @param {{
842 * storage: !lib.Storage,
843 * profileId: string,
844 * }} args
845 * @return {!Promise<!hterm.Terminal>}
846 */
847export async function createEmulator({storage, profileId}) {
848 let config = TERMINAL_EMULATORS.get('hterm');
849
850 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +1000851 // TODO: remove the url param logic. This is temporary to make manual
852 // testing a bit easier, which is also why this is not in
853 // './js/terminal_info.js'.
854 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
855 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +1000856 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +1000857 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +1000858 TERMINAL_EMULATORS.values().next().value;
859 console.log('Terminal emulator config: ', config);
860 }
861
862 switch (config.lib) {
863 case 'xterm.js':
864 {
865 const terminal = new XtermTerminal({
866 storage,
867 profileId,
868 enableWebGL: config.webgl,
869 });
Jason Linca61ffb2022-08-03 19:37:12 +1000870 return terminal;
871 }
872 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +1000873 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +1000874 default:
875 throw new Error('incorrect emulator config');
876 }
877}
878
Jason Lin6a402a72022-08-25 16:07:02 +1000879class TerminalCopyNotice extends LitElement {
880 /** @override */
881 static get styles() {
882 return css`
883 :host {
884 display: block;
885 text-align: center;
886 }
887
888 svg {
889 fill: currentColor;
890 }
891 `;
892 }
893
894 /** @override */
895 render() {
896 return html`
897 ${ICON_COPY}
898 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
899 `;
900 }
901}
902
903customElements.define('terminal-copy-notice', TerminalCopyNotice);