blob: d02f39b2d96d8e79f96597df8a9a5bfd4ce4f94a [file] [log] [blame]
Mike Frysinger598e8012022-09-07 08:38:34 -04001// Copyright 2022 The ChromiumOS Authors
Jason Lind66e6bf2022-08-22 14:47:10 +10002// 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 Lin2649da22022-10-12 10:16:44 +110012// TODO(b/236205389): support option smoothScrollDuration?
13
Jason Lin6a402a72022-08-25 16:07:02 +100014import {LitElement, css, html} from './lit.js';
Jason Lin21d854f2022-08-22 14:49:59 +100015import {FontManager, ORIGINAL_URL, TERMINAL_EMULATORS, delayedScheduler,
16 fontManager, getOSInfo, sleep} from './terminal_common.js';
Jason Lin6a402a72022-08-25 16:07:02 +100017import {ICON_COPY} from './terminal_icons.js';
Jason Lin83707c92022-09-20 19:09:41 +100018import {TerminalTooltip} from './terminal_tooltip.js';
Jason Linc2504ae2022-09-02 13:03:31 +100019import {Terminal, Unicode11Addon, WebLinksAddon, WebglAddon}
Jason Lin4de4f382022-09-01 14:10:18 +100020 from './xterm.js';
Jason Lin2649da22022-10-12 10:16:44 +110021import {XtermInternal} from './terminal_xterm_internal.js';
Jason Linca61ffb2022-08-03 19:37:12 +100022
Jason Lin5690e752022-08-30 15:36:45 +100023
24/** @enum {number} */
25export const Modifier = {
26 Shift: 1 << 0,
27 Alt: 1 << 1,
28 Ctrl: 1 << 2,
29 Meta: 1 << 3,
30};
31
32// This is just a static map from key names to key codes. It helps make the code
33// a bit more readable.
34const keyCodes = hterm.Parser.identifiers.keyCodes;
35
36/**
37 * Encode a key combo (i.e. modifiers + a normal key) to an unique number.
38 *
39 * @param {number} modifiers
40 * @param {number} keyCode
41 * @return {number}
42 */
43export function encodeKeyCombo(modifiers, keyCode) {
44 return keyCode << 4 | modifiers;
45}
46
47const OS_DEFAULT_BINDINGS = [
48 // Submit feedback.
49 encodeKeyCombo(Modifier.Alt | Modifier.Shift, keyCodes.I),
50 // Toggle chromevox.
51 encodeKeyCombo(Modifier.Ctrl | Modifier.Alt, keyCodes.Z),
52 // Switch input method.
53 encodeKeyCombo(Modifier.Ctrl, keyCodes.SPACE),
54
55 // Dock window left/right.
56 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_LEFT),
57 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_RIGHT),
58
59 // Maximize/minimize window.
60 encodeKeyCombo(Modifier.Alt, keyCodes.EQUAL),
61 encodeKeyCombo(Modifier.Alt, keyCodes.MINUS),
62];
63
64
Jason Linca61ffb2022-08-03 19:37:12 +100065const ANSI_COLOR_NAMES = [
66 'black',
67 'red',
68 'green',
69 'yellow',
70 'blue',
71 'magenta',
72 'cyan',
73 'white',
74 'brightBlack',
75 'brightRed',
76 'brightGreen',
77 'brightYellow',
78 'brightBlue',
79 'brightMagenta',
80 'brightCyan',
81 'brightWhite',
82];
83
Jason Linca61ffb2022-08-03 19:37:12 +100084/**
Jason Linabad7562022-08-22 14:49:05 +100085 * @typedef {{
86 * term: !Terminal,
87 * fontManager: !FontManager,
Jason Lin2649da22022-10-12 10:16:44 +110088 * xtermInternal: !XtermInternal,
Jason Linabad7562022-08-22 14:49:05 +100089 * }}
90 */
91export let XtermTerminalTestParams;
92
93/**
Jason Lin5690e752022-08-30 15:36:45 +100094 * Compute a control character for a given character.
95 *
96 * @param {string} ch
97 * @return {string}
98 */
99function ctl(ch) {
100 return String.fromCharCode(ch.charCodeAt(0) - 64);
101}
102
103/**
Jason Lin21d854f2022-08-22 14:49:59 +1000104 * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO
105 * because it always convert utf8 data to strings, which is not necessary for
106 * xterm.
107 */
108class XtermTerminalIO extends hterm.Terminal.IO {
109 /** @override */
110 writeUTF8(buffer) {
111 this.terminal_.write(new Uint8Array(buffer));
112 }
113
114 /** @override */
115 writelnUTF8(buffer) {
116 this.terminal_.writeln(new Uint8Array(buffer));
117 }
118
119 /** @override */
120 print(string) {
121 this.terminal_.write(string);
122 }
123
124 /** @override */
125 writeUTF16(string) {
126 this.print(string);
127 }
128
129 /** @override */
130 println(string) {
131 this.terminal_.writeln(string);
132 }
133
134 /** @override */
135 writelnUTF16(string) {
136 this.println(string);
137 }
138}
139
140/**
Jason Lin83707c92022-09-20 19:09:41 +1000141 * A custom link handler that:
142 *
143 * - Shows a tooltip with the url on a OSC 8 link. This is following what hterm
144 * is doing. Also, showing the tooltip is better for the security of the user
145 * because the link can have arbitrary text.
146 * - Uses our own way to open the window.
147 */
148class LinkHandler {
149 /**
150 * @param {!Terminal} term
151 */
152 constructor(term) {
153 this.term_ = term;
154 /** @type {?TerminalTooltip} */
155 this.tooltip_ = null;
156 }
157
158 /**
159 * @return {!TerminalTooltip}
160 */
161 getTooltip_() {
162 if (!this.tooltip_) {
163 this.tooltip_ = /** @type {!TerminalTooltip} */(
164 document.createElement('terminal-tooltip'));
165 this.tooltip_.classList.add('xterm-hover');
166 lib.notNull(this.term_.element).appendChild(this.tooltip_);
167 }
168 return this.tooltip_;
169 }
170
171 /**
172 * @param {!MouseEvent} ev
173 * @param {string} url
174 * @param {!Object} range
175 */
176 activate(ev, url, range) {
177 lib.f.openWindow(url, '_blank');
178 }
179
180 /**
181 * @param {!MouseEvent} ev
182 * @param {string} url
183 * @param {!Object} range
184 */
185 hover(ev, url, range) {
186 this.getTooltip_().show(url, {x: ev.clientX, y: ev.clientY});
187 }
188
189 /**
190 * @param {!MouseEvent} ev
191 * @param {string} url
192 * @param {!Object} range
193 */
194 leave(ev, url, range) {
195 this.getTooltip_().hide();
196 }
197}
198
Jason Linc7afb672022-10-11 15:54:17 +1100199class Bell {
200 constructor() {
201 this.showNotification = false;
202
203 /** @type {?Audio} */
204 this.audio_ = null;
205 /** @type {?Notification} */
206 this.notification_ = null;
207 this.coolDownUntil_ = 0;
208 }
209
210 /**
211 * Set whether a bell audio should be played.
212 *
213 * @param {boolean} value
214 */
215 set playAudio(value) {
216 this.audio_ = value ?
217 new Audio(lib.resource.getDataUrl('hterm/audio/bell')) : null;
218 }
219
220 ring() {
221 const now = Date.now();
222 if (now < this.coolDownUntil_) {
223 return;
224 }
225 this.coolDownUntil_ = now + 500;
226
227 this.audio_?.play();
228 if (this.showNotification && !document.hasFocus() && !this.notification_) {
229 this.notification_ = new Notification(
230 `\u266A ${document.title} \u266A`,
231 {icon: lib.resource.getDataUrl('hterm/images/icon-96')});
232 // Close the notification after a timeout. Note that this is different
233 // from hterm's behavior, but I think it makes more sense to do so.
234 setTimeout(() => {
235 this.notification_.close();
236 this.notification_ = null;
237 }, 5000);
238 }
239 }
240}
241
Jason Lind3aacef2022-10-12 19:03:37 +1100242const A11Y_BUTTON_STYLE = `
243position: fixed;
244z-index: 10;
245right: 16px;
246`;
247
248class A11yButtons {
249 /**
250 * @param {!Terminal} term
251 * @param {!Element} elem The container element for the terminal.
252 */
253 constructor(term, elem) {
254 this.pageUpButton_ = document.createElement('button');
255 this.pageUpButton_.style.cssText = A11Y_BUTTON_STYLE;
256 this.pageUpButton_.textContent =
257 hterm.messageManager.get('HTERM_BUTTON_PAGE_UP');
258 this.pageUpButton_.addEventListener('click',
259 () => term.scrollPages(-1));
260
261 this.pageDownButton_ = document.createElement('button');
262 this.pageDownButton_.style.cssText = A11Y_BUTTON_STYLE;
263 this.pageDownButton_.textContent =
264 hterm.messageManager.get('HTERM_BUTTON_PAGE_DOWN');
265 this.pageDownButton_.addEventListener('click',
266 () => term.scrollPages(1));
267
268 this.resetPos_();
269 elem.prepend(this.pageUpButton_);
270 elem.append(this.pageDownButton_);
271
272 this.onSelectionChange_ = this.onSelectionChange_.bind(this);
273 }
274
275 /**
276 * @param {boolean} enabled
277 */
278 setEnabled(enabled) {
279 if (enabled) {
280 document.addEventListener('selectionchange', this.onSelectionChange_);
281 } else {
282 this.resetPos_();
283 document.removeEventListener('selectionchange', this.onSelectionChange_);
284 }
285 }
286
287 resetPos_() {
288 this.pageUpButton_.style.top = '-200px';
289 this.pageDownButton_.style.bottom = '-200px';
290 }
291
292 onSelectionChange_() {
293 this.resetPos_();
294
295 const selectedElement = document.getSelection().anchorNode.parentElement;
296 if (selectedElement === this.pageUpButton_) {
297 this.pageUpButton_.style.top = '16px';
298 } else if (selectedElement === this.pageDownButton_) {
299 this.pageDownButton_.style.bottom = '16px';
300 }
301 }
302}
303
Jason Lin83707c92022-09-20 19:09:41 +1000304/**
Jason Linca61ffb2022-08-03 19:37:12 +1000305 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
306 * so that it can be used in existing code.
307 *
Jason Linca61ffb2022-08-03 19:37:12 +1000308 * @extends {hterm.Terminal}
309 * @unrestricted
310 */
Jason Linabad7562022-08-22 14:49:05 +1000311export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000312 /**
313 * @param {{
314 * storage: !lib.Storage,
315 * profileId: string,
316 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000317 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000318 * }} args
319 */
Jason Linabad7562022-08-22 14:49:05 +1000320 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000321 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
322 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
323 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
324
Jason Lin8de3d282022-09-01 21:29:05 +1000325 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000326 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000327 /** @type {!hterm.PreferenceManager} */
328 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
329 this.enableWebGL_ = enableWebGL;
330
Jason Lin5690e752022-08-30 15:36:45 +1000331 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linfc8a3722022-09-07 17:49:18 +1000332 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Lin2649da22022-10-12 10:16:44 +1100333 this.xtermInternal_ = testParams?.xtermInternal ||
334 new XtermInternal(this.term);
Jason Linabad7562022-08-22 14:49:05 +1000335 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000336
Jason Linc2504ae2022-09-02 13:03:31 +1000337 /** @type {?Element} */
338 this.container_;
Jason Linc7afb672022-10-11 15:54:17 +1100339 this.bell_ = new Bell();
Jason Linc2504ae2022-09-02 13:03:31 +1000340 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000341 testParams ? 0 : 250);
342
Jason Lin83707c92022-09-20 19:09:41 +1000343 this.term.loadAddon(
344 new WebLinksAddon((e, uri) => lib.f.openWindow(uri, '_blank')));
Jason Lin4de4f382022-09-01 14:10:18 +1000345 this.term.loadAddon(new Unicode11Addon());
346 this.term.unicode.activeVersion = '11';
347
Jason Linabad7562022-08-22 14:49:05 +1000348 this.pendingFont_ = null;
349 this.scheduleRefreshFont_ = delayedScheduler(
350 () => this.refreshFont_(), 100);
351 document.fonts.addEventListener('loadingdone',
352 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000353
354 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000355 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000356
Jason Lin34a45322022-10-12 19:10:52 +1100357 this.term.onResize(({cols, rows}) => {
358 this.io.onTerminalResize(cols, rows);
359 if (this.prefs_.get('enable-resize-status')) {
360 this.showOverlay(`${cols} × ${rows}`);
361 }
362 });
Jason Lin21d854f2022-08-22 14:49:59 +1000363 // We could also use `this.io.sendString()` except for the nassh exit
364 // prompt, which only listens to onVTKeystroke().
365 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000366 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100367 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin5690e752022-08-30 15:36:45 +1000368 this.term.onSelectionChange(() => this.copySelection_());
Jason Linc7afb672022-10-11 15:54:17 +1100369 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000370
371 /**
372 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
373 *
374 * If a key combo is in the map:
375 *
376 * - The handler instead of xterm.js will handle the keydown event.
377 * - Keyup and keypress will be ignored by both us and xterm.js.
378 *
379 * We re-generate this map every time a relevant pref value is changed. This
380 * is ok because pref changes are rare.
381 *
382 * @type {!Map<number, function(!KeyboardEvent)>}
383 */
384 this.keyDownHandlers_ = new Map();
385 this.scheduleResetKeyDownHandlers_ =
386 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
387
388 this.term.attachCustomKeyEventHandler(
389 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000390
Jason Lin21d854f2022-08-22 14:49:59 +1000391 this.io = new XtermTerminalIO(this);
392 this.notificationCenter_ = null;
Jason Lind3aacef2022-10-12 19:03:37 +1100393 this.htermA11yReader_ = null;
394 this.a11yButtons_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000395 this.copyNotice_ = null;
396
Jason Lin83707c92022-09-20 19:09:41 +1000397 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000398 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000399 // The webgl cursor layer also paints the character under the cursor with
400 // this `cursorAccent` color. We use a completely transparent color here
401 // to effectively disable that.
402 cursorAccent: 'rgba(0, 0, 0, 0)',
403 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000404 selectionBackground: 'rgba(174, 203, 250, .6)',
405 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000406 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000407 };
408 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000409 }
410
Jason Linc7afb672022-10-11 15:54:17 +1100411 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100412 setWindowTitle(title) {
413 document.title = title;
414 }
415
416 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100417 ringBell() {
418 this.bell_.ring();
419 }
420
Jason Lin2649da22022-10-12 10:16:44 +1100421 /** @override */
422 print(str) {
423 this.xtermInternal_.print(str);
424 }
425
426 /** @override */
427 wipeContents() {
428 this.term.clear();
429 }
430
431 /** @override */
432 newLine() {
433 this.xtermInternal_.newLine();
434 }
435
436 /** @override */
437 cursorLeft(number) {
438 this.xtermInternal_.cursorLeft(number ?? 1);
439 }
440
Jason Lind3aacef2022-10-12 19:03:37 +1100441 /** @override */
442 setAccessibilityEnabled(enabled) {
443 this.a11yButtons_.setEnabled(enabled);
444 this.htermA11yReader_.setAccessibilityEnabled(enabled);
445 this.term.options.screenReaderMode = enabled;
446 }
447
Jason Linca61ffb2022-08-03 19:37:12 +1000448 /**
449 * Install stubs for stuff that we haven't implemented yet so that the code
450 * still runs.
451 */
452 installUnimplementedStubs_() {
453 this.keyboard = {
454 keyMap: {
455 keyDefs: [],
456 },
457 bindings: {
458 clear: () => {},
459 addBinding: () => {},
460 addBindings: () => {},
461 OsDefaults: {},
462 },
463 };
464 this.keyboard.keyMap.keyDefs[78] = {};
465
466 const methodNames = [
Jason Linca61ffb2022-08-03 19:37:12 +1000467 'setBackgroundImage',
468 'setCursorPosition',
469 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000470 ];
471
472 for (const name of methodNames) {
473 this[name] = () => console.warn(`${name}() is not implemented`);
474 }
475
476 this.contextMenu = {
477 setItems: () => {
478 console.warn('.contextMenu.setItems() is not implemented');
479 },
480 };
Jason Lin21d854f2022-08-22 14:49:59 +1000481
482 this.vt = {
483 resetParseState: () => {
484 console.warn('.vt.resetParseState() is not implemented');
485 },
486 };
Jason Linca61ffb2022-08-03 19:37:12 +1000487 }
488
Jason Line9231bc2022-09-01 13:54:02 +1000489 installEscapeSequenceHandlers_() {
490 // OSC 52 for copy.
491 this.term.parser.registerOscHandler(52, (args) => {
492 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
493 // parameter is used to select which of the X clipboards to address. Since
494 // we're not integrating with X, we treat them all the same.
495 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
496 if (!parsedArgs) {
497 return true;
498 }
499
500 let data;
501 try {
502 data = window.atob(parsedArgs[1]);
503 } catch (e) {
504 // If the user sent us invalid base64 content, silently ignore it.
505 return true;
506 }
507 const decoder = new TextDecoder();
508 const bytes = lib.codec.stringToCodeUnitArray(data);
509 this.copyString_(decoder.decode(bytes));
510
511 return true;
512 });
Jason Lin2649da22022-10-12 10:16:44 +1100513
514 this.xtermInternal_.installTmuxControlModeHandler(
515 (data) => this.onTmuxControlModeLine(data));
516 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000517 }
518
Jason Linca61ffb2022-08-03 19:37:12 +1000519 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000520 * Write data to the terminal.
521 *
522 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
523 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100524 * @param {function()=} callback Optional callback that fires when the data
525 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000526 */
Jason Lin2649da22022-10-12 10:16:44 +1100527 write(data, callback) {
528 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000529 }
530
531 /**
532 * Like `this.write()` but also write a line break.
533 *
534 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100535 * @param {function()=} callback Optional callback that fires when the data
536 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000537 */
Jason Lin2649da22022-10-12 10:16:44 +1100538 writeln(data, callback) {
539 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000540 }
541
Jason Linca61ffb2022-08-03 19:37:12 +1000542 get screenSize() {
543 return new hterm.Size(this.term.cols, this.term.rows);
544 }
545
546 /**
547 * Don't need to do anything.
548 *
549 * @override
550 */
551 installKeyboard() {}
552
553 /**
554 * @override
555 */
556 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000557 this.container_ = elem;
Jason Lin8de3d282022-09-01 21:29:05 +1000558 (async () => {
559 await new Promise((resolve) => this.prefs_.readStorage(resolve));
560 // This will trigger all the observers to set the terminal options before
561 // we call `this.term.open()`.
562 this.prefs_.notifyAll();
563
Jason Linc2504ae2022-09-02 13:03:31 +1000564 const screenPaddingSize = /** @type {number} */(
565 this.prefs_.get('screen-padding-size'));
566 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
567
Jason Lin8de3d282022-09-01 21:29:05 +1000568 this.inited_ = true;
569 this.term.open(elem);
570
Jason Lin8de3d282022-09-01 21:29:05 +1000571 if (this.enableWebGL_) {
572 this.term.loadAddon(new WebglAddon());
573 }
574 this.term.focus();
575 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100576 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
577 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
578 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000579
Emil Mikulic2a194d02022-09-29 14:30:59 +1000580 // Block right-click context menu from popping up.
581 elem.addEventListener('contextmenu', (e) => e.preventDefault());
582
583 // Add a handler for pasting with the mouse.
584 elem.addEventListener('mousedown', async (e) => {
585 if (this.term.modes.mouseTrackingMode !== 'none') {
586 // xterm.js is in mouse mode and will handle the event.
587 return;
588 }
589 const MIDDLE = 1;
590 const RIGHT = 2;
591 if (e.button === MIDDLE || (e.button === RIGHT &&
592 this.prefs_.getBoolean('mouse-right-click-paste'))) {
593 // Paste.
594 if (navigator.clipboard && navigator.clipboard.readText) {
595 const text = await navigator.clipboard.readText();
596 this.term.paste(text);
597 }
598 }
599 });
600
Jason Lin2649da22022-10-12 10:16:44 +1100601 await this.scheduleFit_();
Jason Lind3aacef2022-10-12 19:03:37 +1100602 this.a11yButtons_ = new A11yButtons(this.term, elem);
603
Jason Lin8de3d282022-09-01 21:29:05 +1000604 this.onTerminalReady();
605 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000606 }
607
608 /** @override */
609 showOverlay(msg, timeout = 1500) {
Jason Lin34a45322022-10-12 19:10:52 +1100610 this.notificationCenter_?.show(msg, {timeout});
Jason Lin21d854f2022-08-22 14:49:59 +1000611 }
612
613 /** @override */
614 hideOverlay() {
Jason Lin34a45322022-10-12 19:10:52 +1100615 this.notificationCenter_?.hide();
Jason Linca61ffb2022-08-03 19:37:12 +1000616 }
617
618 /** @override */
619 getPrefs() {
620 return this.prefs_;
621 }
622
623 /** @override */
624 getDocument() {
625 return window.document;
626 }
627
Jason Lin21d854f2022-08-22 14:49:59 +1000628 /** @override */
629 reset() {
630 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000631 }
632
633 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000634 setProfile(profileId, callback = undefined) {
635 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000636 }
637
Jason Lin21d854f2022-08-22 14:49:59 +1000638 /** @override */
639 interpret(string) {
640 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000641 }
642
Jason Lin21d854f2022-08-22 14:49:59 +1000643 /** @override */
644 focus() {
645 this.term.focus();
646 }
Jason Linca61ffb2022-08-03 19:37:12 +1000647
648 /** @override */
649 onOpenOptionsPage() {}
650
651 /** @override */
652 onTerminalReady() {}
653
Jason Lind04bab32022-08-22 14:48:39 +1000654 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000655 // This is for this.notificationCenter_.
656 const setHtermCSSVariable = (name, value) => {
657 document.body.style.setProperty(`--hterm-${name}`, value);
658 };
659
660 const setHtermColorCSSVariable = (name, color) => {
661 const css = lib.notNull(lib.colors.normalizeCSS(color));
662 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
663 setHtermCSSVariable(name, rgb);
664 };
665
666 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000667 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000668 setHtermCSSVariable('font-size', `${v}px`);
669 });
670
Jason Linda56aa92022-09-02 13:01:49 +1000671 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000672 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000673 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100674 this.bell_.playAudio = !!v;
675 },
676 'desktop-notification-bell': (v) => {
677 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000678 },
Jason Lind04bab32022-08-22 14:48:39 +1000679 'background-color': (v) => {
680 this.updateTheme_({background: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000681 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000682 },
Jason Lind04bab32022-08-22 14:48:39 +1000683 'color-palette-overrides': (v) => {
684 if (!(v instanceof Array)) {
685 // For terminal, we always expect this to be an array.
686 console.warn('unexpected color palette: ', v);
687 return;
688 }
689 const colors = {};
690 for (let i = 0; i < v.length; ++i) {
691 colors[ANSI_COLOR_NAMES[i]] = v[i];
692 }
693 this.updateTheme_(colors);
694 },
Jason Linda56aa92022-09-02 13:01:49 +1000695 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
696 'cursor-color': (v) => this.updateTheme_({cursor: v}),
697 'cursor-shape': (v) => {
698 let shape;
699 if (v === 'BEAM') {
700 shape = 'bar';
701 } else {
702 shape = v.toLowerCase();
703 }
704 this.updateOption_('cursorStyle', shape, false);
705 },
706 'font-family': (v) => this.updateFont_(v),
707 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000708 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000709 setHtermColorCSSVariable('foreground-color', v);
710 },
Jason Lind04bab32022-08-22 14:48:39 +1000711 });
Jason Lin5690e752022-08-30 15:36:45 +1000712
713 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
714 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
715 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
716 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
717 }
Jason Lind04bab32022-08-22 14:48:39 +1000718 }
719
720 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000721 * Fit the terminal to the containing HTML element.
722 */
723 fit_() {
724 if (!this.inited_) {
725 return;
726 }
727
728 const screenPaddingSize = /** @type {number} */(
729 this.prefs_.get('screen-padding-size'));
730
731 const calc = (size, cellSize) => {
732 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
733 };
734
Jason Lin2649da22022-10-12 10:16:44 +1100735 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
736 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
737 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000738 if (cols >= 0 && rows >= 0) {
739 this.term.resize(cols, rows);
740 }
741 }
742
743 /**
Jason Lind04bab32022-08-22 14:48:39 +1000744 * @param {!Object} theme
745 */
746 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000747 const updateTheme = (target) => {
748 for (const [key, value] of Object.entries(theme)) {
749 target[key] = lib.colors.normalizeCSS(value);
750 }
751 };
752
753 // Must use a new theme object to trigger re-render if we have initialized.
754 if (this.inited_) {
755 const newTheme = {...this.term.options.theme};
756 updateTheme(newTheme);
757 this.term.options.theme = newTheme;
758 return;
Jason Lind04bab32022-08-22 14:48:39 +1000759 }
Jason Lin8de3d282022-09-01 21:29:05 +1000760
761 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000762 }
763
764 /**
Jason Linda56aa92022-09-02 13:01:49 +1000765 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
766 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000767 *
768 * @param {string} key
769 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000770 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000771 */
Jason Linda56aa92022-09-02 13:01:49 +1000772 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000773 // TODO: xterm supports updating multiple options at the same time. We
774 // should probably do that.
775 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000776 if (scheduleFit) {
777 this.scheduleFit_();
778 }
Jason Lind04bab32022-08-22 14:48:39 +1000779 }
Jason Linabad7562022-08-22 14:49:05 +1000780
781 /**
782 * Called when there is a "fontloadingdone" event. We need this because
783 * `FontManager.loadFont()` does not guarantee loading all the font files.
784 */
785 async onFontLoadingDone_() {
786 // If there is a pending font, the font is going to be refresh soon, so we
787 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000788 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000789 this.scheduleRefreshFont_();
790 }
791 }
792
Jason Lin5690e752022-08-30 15:36:45 +1000793 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000794 this.copyString_(this.term.getSelection());
795 }
796
797 /** @param {string} data */
798 copyString_(data) {
799 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000800 return;
801 }
Jason Line9231bc2022-09-01 13:54:02 +1000802 navigator.clipboard?.writeText(data);
Jason Lin6a402a72022-08-25 16:07:02 +1000803 if (!this.copyNotice_) {
804 this.copyNotice_ = document.createElement('terminal-copy-notice');
805 }
806 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200);
807 }
808
Jason Linabad7562022-08-22 14:49:05 +1000809 /**
810 * Refresh xterm rendering for a font related event.
811 */
812 refreshFont_() {
813 // We have to set the fontFamily option to a different string to trigger the
814 // re-rendering. Appending a space at the end seems to be the easiest
815 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
816 // us.
817 //
818 // TODO: Report a bug to xterm.js and ask for exposing a public function for
819 // the refresh so that we don't need to do this hack.
820 this.term.options.fontFamily += ' ';
821 }
822
823 /**
824 * Update a font.
825 *
826 * @param {string} cssFontFamily
827 */
828 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000829 this.pendingFont_ = cssFontFamily;
830 await this.fontManager_.loadFont(cssFontFamily);
831 // Sleep a bit to wait for flushing fontloadingdone events. This is not
832 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
833 // to refresh font unnecessarily in some cases.
834 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000835
Jason Lin6a402a72022-08-25 16:07:02 +1000836 if (this.pendingFont_ !== cssFontFamily) {
837 // `updateFont_()` probably is called again. Abort what we are doing.
838 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
839 ` (expecting ${cssFontFamily})`);
840 return;
841 }
Jason Linabad7562022-08-22 14:49:05 +1000842
Jason Lin6a402a72022-08-25 16:07:02 +1000843 if (this.term.options.fontFamily !== cssFontFamily) {
844 this.term.options.fontFamily = cssFontFamily;
845 } else {
846 // If the font is already the same, refresh font just to be safe.
847 this.refreshFont_();
848 }
849 this.pendingFont_ = null;
850 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000851 }
Jason Lin5690e752022-08-30 15:36:45 +1000852
853 /**
854 * @param {!KeyboardEvent} ev
855 * @return {boolean} Return false if xterm.js should not handle the key event.
856 */
857 customKeyEventHandler_(ev) {
858 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
859 (ev.altKey ? Modifier.Alt : 0) |
860 (ev.ctrlKey ? Modifier.Ctrl : 0) |
861 (ev.metaKey ? Modifier.Meta : 0);
862 const handler = this.keyDownHandlers_.get(
863 encodeKeyCombo(modifiers, ev.keyCode));
864 if (handler) {
865 if (ev.type === 'keydown') {
866 handler(ev);
867 }
868 return false;
869 }
870
871 return true;
872 }
873
874 /**
875 * A keydown handler for zoom-related keys.
876 *
877 * @param {!KeyboardEvent} ev
878 */
879 zoomKeyDownHandler_(ev) {
880 ev.preventDefault();
881
882 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
883 // The only one with a control code.
884 if (ev.keyCode === keyCodes.MINUS) {
885 this.io.onVTKeystroke('\x1f');
886 }
887 return;
888 }
889
890 let newFontSize;
891 switch (ev.keyCode) {
892 case keyCodes.ZERO:
893 newFontSize = this.prefs_.get('font-size');
894 break;
895 case keyCodes.MINUS:
896 newFontSize = this.term.options.fontSize - 1;
897 break;
898 default:
899 newFontSize = this.term.options.fontSize + 1;
900 break;
901 }
902
Jason Linda56aa92022-09-02 13:01:49 +1000903 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +1000904 }
905
906 /** @param {!KeyboardEvent} ev */
907 ctrlCKeyDownHandler_(ev) {
908 ev.preventDefault();
909 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
910 this.term.hasSelection()) {
911 this.copySelection_();
912 return;
913 }
914
915 this.io.onVTKeystroke('\x03');
916 }
917
918 /** @param {!KeyboardEvent} ev */
919 ctrlVKeyDownHandler_(ev) {
920 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
921 // Don't do anything and let the browser handles the key.
922 return;
923 }
924
925 ev.preventDefault();
926 this.io.onVTKeystroke('\x16');
927 }
928
929 resetKeyDownHandlers_() {
930 this.keyDownHandlers_.clear();
931
932 /**
933 * Don't do anything and let the browser handles the key.
934 *
935 * @param {!KeyboardEvent} ev
936 */
937 const noop = (ev) => {};
938
939 /**
940 * @param {number} modifiers
941 * @param {number} keyCode
942 * @param {function(!KeyboardEvent)} func
943 */
944 const set = (modifiers, keyCode, func) => {
945 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
946 func);
947 };
948
949 /**
950 * @param {number} modifiers
951 * @param {number} keyCode
952 * @param {function(!KeyboardEvent)} func
953 */
954 const setWithShiftVersion = (modifiers, keyCode, func) => {
955 set(modifiers, keyCode, func);
956 set(modifiers | Modifier.Shift, keyCode, func);
957 };
958
Jason Lin5690e752022-08-30 15:36:45 +1000959 // Ctrl+/
960 set(Modifier.Ctrl, 191, (ev) => {
961 ev.preventDefault();
962 this.io.onVTKeystroke(ctl('_'));
963 });
964
965 // Settings page.
966 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
967 ev.preventDefault();
968 chrome.terminalPrivate.openOptionsPage(() => {});
969 });
970
971 if (this.prefs_.get('keybindings-os-defaults')) {
972 for (const binding of OS_DEFAULT_BINDINGS) {
973 this.keyDownHandlers_.set(binding, noop);
974 }
975 }
976
977 /** @param {!KeyboardEvent} ev */
978 const newWindow = (ev) => {
979 ev.preventDefault();
980 chrome.terminalPrivate.openWindow();
981 };
982 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
983 if (this.prefs_.get('pass-ctrl-n')) {
984 set(Modifier.Ctrl, keyCodes.N, newWindow);
985 }
986
987 if (this.prefs_.get('pass-ctrl-t')) {
988 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
989 }
990
991 if (this.prefs_.get('pass-ctrl-w')) {
992 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
993 }
994
995 if (this.prefs_.get('pass-ctrl-tab')) {
996 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
997 }
998
999 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
1000
1001 /**
1002 * Set a handler for the key combo ctrl+<number>.
1003 *
1004 * @param {number} number 1 to 9
1005 * @param {string} controlCode The control code to send if we don't want to
1006 * let the browser to handle it.
1007 */
1008 const setCtrlNumberHandler = (number, controlCode) => {
1009 let func = noop;
1010 if (!passCtrlNumber) {
1011 func = (ev) => {
1012 ev.preventDefault();
1013 this.io.onVTKeystroke(controlCode);
1014 };
1015 }
1016 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1017 };
1018
1019 setCtrlNumberHandler(1, '1');
1020 setCtrlNumberHandler(2, ctl('@'));
1021 setCtrlNumberHandler(3, ctl('['));
1022 setCtrlNumberHandler(4, ctl('\\'));
1023 setCtrlNumberHandler(5, ctl(']'));
1024 setCtrlNumberHandler(6, ctl('^'));
1025 setCtrlNumberHandler(7, ctl('_'));
1026 setCtrlNumberHandler(8, '\x7f');
1027 setCtrlNumberHandler(9, '9');
1028
1029 if (this.prefs_.get('pass-alt-number')) {
1030 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1031 set(Modifier.Alt, keyCode, noop);
1032 }
1033 }
1034
1035 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1036 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1037 }
1038
1039 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1040 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1041 }
Jason Linca61ffb2022-08-03 19:37:12 +10001042}
1043
Jason Lind66e6bf2022-08-22 14:47:10 +10001044class HtermTerminal extends hterm.Terminal {
1045 /** @override */
1046 decorate(div) {
1047 super.decorate(div);
1048
1049 const fontManager = new FontManager(this.getDocument());
1050 fontManager.loadPowerlineCSS().then(() => {
1051 const prefs = this.getPrefs();
1052 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1053 prefs.addObserver(
1054 'font-family',
1055 (v) => fontManager.loadFont(/** @type {string} */(v)));
1056 });
1057 }
Jason Lin2649da22022-10-12 10:16:44 +11001058
1059 /**
1060 * Write data to the terminal.
1061 *
1062 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1063 * UTF-8 data
1064 * @param {function()=} callback Optional callback that fires when the data
1065 * was processed by the parser.
1066 */
1067 write(data, callback) {
1068 if (typeof data === 'string') {
1069 this.io.print(data);
1070 } else {
1071 this.io.writeUTF8(data);
1072 }
1073 // Hterm processes the data synchronously, so we can call the callback
1074 // immediately.
1075 if (callback) {
1076 setTimeout(callback);
1077 }
1078 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001079}
1080
Jason Linca61ffb2022-08-03 19:37:12 +10001081/**
1082 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1083 * preference value.
1084 *
1085 * @param {{
1086 * storage: !lib.Storage,
1087 * profileId: string,
1088 * }} args
1089 * @return {!Promise<!hterm.Terminal>}
1090 */
1091export async function createEmulator({storage, profileId}) {
1092 let config = TERMINAL_EMULATORS.get('hterm');
1093
1094 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001095 // TODO: remove the url param logic. This is temporary to make manual
1096 // testing a bit easier, which is also why this is not in
1097 // './js/terminal_info.js'.
1098 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
1099 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +10001100 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001101 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001102 TERMINAL_EMULATORS.values().next().value;
1103 console.log('Terminal emulator config: ', config);
1104 }
1105
1106 switch (config.lib) {
1107 case 'xterm.js':
1108 {
1109 const terminal = new XtermTerminal({
1110 storage,
1111 profileId,
1112 enableWebGL: config.webgl,
1113 });
Jason Linca61ffb2022-08-03 19:37:12 +10001114 return terminal;
1115 }
1116 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001117 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001118 default:
1119 throw new Error('incorrect emulator config');
1120 }
1121}
1122
Jason Lin6a402a72022-08-25 16:07:02 +10001123class TerminalCopyNotice extends LitElement {
1124 /** @override */
1125 static get styles() {
1126 return css`
1127 :host {
1128 display: block;
1129 text-align: center;
1130 }
1131
1132 svg {
1133 fill: currentColor;
1134 }
1135 `;
1136 }
1137
1138 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001139 connectedCallback() {
1140 super.connectedCallback();
1141 if (!this.childNodes.length) {
1142 // This is not visible since we use shadow dom. But this will allow the
1143 // hterm.NotificationCenter to announce the the copy text.
1144 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1145 }
1146 }
1147
1148 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001149 render() {
1150 return html`
1151 ${ICON_COPY}
1152 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1153 `;
1154 }
1155}
1156
1157customElements.define('terminal-copy-notice', TerminalCopyNotice);