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