blob: 294e2543066d42e97b3d02ab2432ae683673077f [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 Linc48f7432022-10-13 17:28:30 +110015import {FontManager, ORIGINAL_URL, TERMINAL_EMULATORS, definePrefs,
16 delayedScheduler, 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);
Jason Linc48f7432022-10-13 17:28:30 +1100329 definePrefs(this.prefs_);
Jason Linca61ffb2022-08-03 19:37:12 +1000330 this.enableWebGL_ = enableWebGL;
331
Jason Lin5690e752022-08-30 15:36:45 +1000332 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linfc8a3722022-09-07 17:49:18 +1000333 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Lin2649da22022-10-12 10:16:44 +1100334 this.xtermInternal_ = testParams?.xtermInternal ||
335 new XtermInternal(this.term);
Jason Linabad7562022-08-22 14:49:05 +1000336 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000337
Jason Linc2504ae2022-09-02 13:03:31 +1000338 /** @type {?Element} */
339 this.container_;
Jason Linc7afb672022-10-11 15:54:17 +1100340 this.bell_ = new Bell();
Jason Linc2504ae2022-09-02 13:03:31 +1000341 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000342 testParams ? 0 : 250);
343
Jason Lin83707c92022-09-20 19:09:41 +1000344 this.term.loadAddon(
345 new WebLinksAddon((e, uri) => lib.f.openWindow(uri, '_blank')));
Jason Lin4de4f382022-09-01 14:10:18 +1000346 this.term.loadAddon(new Unicode11Addon());
347 this.term.unicode.activeVersion = '11';
348
Jason Linabad7562022-08-22 14:49:05 +1000349 this.pendingFont_ = null;
350 this.scheduleRefreshFont_ = delayedScheduler(
351 () => this.refreshFont_(), 100);
352 document.fonts.addEventListener('loadingdone',
353 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000354
355 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000356 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000357
Jason Lin34a45322022-10-12 19:10:52 +1100358 this.term.onResize(({cols, rows}) => {
359 this.io.onTerminalResize(cols, rows);
360 if (this.prefs_.get('enable-resize-status')) {
361 this.showOverlay(`${cols} × ${rows}`);
362 }
363 });
Jason Lin21d854f2022-08-22 14:49:59 +1000364 // We could also use `this.io.sendString()` except for the nassh exit
365 // prompt, which only listens to onVTKeystroke().
366 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000367 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100368 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin5690e752022-08-30 15:36:45 +1000369 this.term.onSelectionChange(() => this.copySelection_());
Jason Linc7afb672022-10-11 15:54:17 +1100370 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000371
372 /**
373 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
374 *
375 * If a key combo is in the map:
376 *
377 * - The handler instead of xterm.js will handle the keydown event.
378 * - Keyup and keypress will be ignored by both us and xterm.js.
379 *
380 * We re-generate this map every time a relevant pref value is changed. This
381 * is ok because pref changes are rare.
382 *
383 * @type {!Map<number, function(!KeyboardEvent)>}
384 */
385 this.keyDownHandlers_ = new Map();
386 this.scheduleResetKeyDownHandlers_ =
387 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
388
389 this.term.attachCustomKeyEventHandler(
390 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000391
Jason Lin21d854f2022-08-22 14:49:59 +1000392 this.io = new XtermTerminalIO(this);
393 this.notificationCenter_ = null;
Jason Lind3aacef2022-10-12 19:03:37 +1100394 this.htermA11yReader_ = null;
395 this.a11yButtons_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000396 this.copyNotice_ = null;
Jason Lin446f3d92022-10-13 17:34:21 +1100397 this.scrollOnOutputListener_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000398
Jason Lin83707c92022-09-20 19:09:41 +1000399 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000400 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000401 // The webgl cursor layer also paints the character under the cursor with
402 // this `cursorAccent` color. We use a completely transparent color here
403 // to effectively disable that.
404 cursorAccent: 'rgba(0, 0, 0, 0)',
405 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000406 selectionBackground: 'rgba(174, 203, 250, .6)',
407 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000408 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000409 };
410 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000411 }
412
Jason Linc7afb672022-10-11 15:54:17 +1100413 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100414 setWindowTitle(title) {
415 document.title = title;
416 }
417
418 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100419 ringBell() {
420 this.bell_.ring();
421 }
422
Jason Lin2649da22022-10-12 10:16:44 +1100423 /** @override */
424 print(str) {
425 this.xtermInternal_.print(str);
426 }
427
428 /** @override */
429 wipeContents() {
430 this.term.clear();
431 }
432
433 /** @override */
434 newLine() {
435 this.xtermInternal_.newLine();
436 }
437
438 /** @override */
439 cursorLeft(number) {
440 this.xtermInternal_.cursorLeft(number ?? 1);
441 }
442
Jason Lind3aacef2022-10-12 19:03:37 +1100443 /** @override */
444 setAccessibilityEnabled(enabled) {
445 this.a11yButtons_.setEnabled(enabled);
446 this.htermA11yReader_.setAccessibilityEnabled(enabled);
447 this.term.options.screenReaderMode = enabled;
448 }
449
Jason Linca61ffb2022-08-03 19:37:12 +1000450 /**
451 * Install stubs for stuff that we haven't implemented yet so that the code
452 * still runs.
453 */
454 installUnimplementedStubs_() {
455 this.keyboard = {
456 keyMap: {
457 keyDefs: [],
458 },
459 bindings: {
460 clear: () => {},
461 addBinding: () => {},
462 addBindings: () => {},
463 OsDefaults: {},
464 },
465 };
466 this.keyboard.keyMap.keyDefs[78] = {};
467
468 const methodNames = [
Jason Linca61ffb2022-08-03 19:37:12 +1000469 'setBackgroundImage',
470 'setCursorPosition',
471 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000472 ];
473
474 for (const name of methodNames) {
475 this[name] = () => console.warn(`${name}() is not implemented`);
476 }
477
478 this.contextMenu = {
479 setItems: () => {
480 console.warn('.contextMenu.setItems() is not implemented');
481 },
482 };
Jason Lin21d854f2022-08-22 14:49:59 +1000483
484 this.vt = {
485 resetParseState: () => {
486 console.warn('.vt.resetParseState() is not implemented');
487 },
488 };
Jason Linca61ffb2022-08-03 19:37:12 +1000489 }
490
Jason Line9231bc2022-09-01 13:54:02 +1000491 installEscapeSequenceHandlers_() {
492 // OSC 52 for copy.
493 this.term.parser.registerOscHandler(52, (args) => {
494 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
495 // parameter is used to select which of the X clipboards to address. Since
496 // we're not integrating with X, we treat them all the same.
497 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
498 if (!parsedArgs) {
499 return true;
500 }
501
502 let data;
503 try {
504 data = window.atob(parsedArgs[1]);
505 } catch (e) {
506 // If the user sent us invalid base64 content, silently ignore it.
507 return true;
508 }
509 const decoder = new TextDecoder();
510 const bytes = lib.codec.stringToCodeUnitArray(data);
511 this.copyString_(decoder.decode(bytes));
512
513 return true;
514 });
Jason Lin2649da22022-10-12 10:16:44 +1100515
516 this.xtermInternal_.installTmuxControlModeHandler(
517 (data) => this.onTmuxControlModeLine(data));
518 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000519 }
520
Jason Linca61ffb2022-08-03 19:37:12 +1000521 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000522 * Write data to the terminal.
523 *
524 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
525 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100526 * @param {function()=} callback Optional callback that fires when the data
527 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000528 */
Jason Lin2649da22022-10-12 10:16:44 +1100529 write(data, callback) {
530 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000531 }
532
533 /**
534 * Like `this.write()` but also write a line break.
535 *
536 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100537 * @param {function()=} callback Optional callback that fires when the data
538 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000539 */
Jason Lin2649da22022-10-12 10:16:44 +1100540 writeln(data, callback) {
541 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000542 }
543
Jason Linca61ffb2022-08-03 19:37:12 +1000544 get screenSize() {
545 return new hterm.Size(this.term.cols, this.term.rows);
546 }
547
548 /**
549 * Don't need to do anything.
550 *
551 * @override
552 */
553 installKeyboard() {}
554
555 /**
556 * @override
557 */
558 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000559 this.container_ = elem;
Jason Lin8de3d282022-09-01 21:29:05 +1000560 (async () => {
561 await new Promise((resolve) => this.prefs_.readStorage(resolve));
562 // This will trigger all the observers to set the terminal options before
563 // we call `this.term.open()`.
564 this.prefs_.notifyAll();
565
Jason Linc2504ae2022-09-02 13:03:31 +1000566 const screenPaddingSize = /** @type {number} */(
567 this.prefs_.get('screen-padding-size'));
568 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
569
Jason Lin8de3d282022-09-01 21:29:05 +1000570 this.inited_ = true;
571 this.term.open(elem);
572
Jason Lin8de3d282022-09-01 21:29:05 +1000573 if (this.enableWebGL_) {
574 this.term.loadAddon(new WebglAddon());
575 }
576 this.term.focus();
577 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100578 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
579 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
580 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000581
Emil Mikulic2a194d02022-09-29 14:30:59 +1000582 // Block right-click context menu from popping up.
583 elem.addEventListener('contextmenu', (e) => e.preventDefault());
584
585 // Add a handler for pasting with the mouse.
586 elem.addEventListener('mousedown', async (e) => {
587 if (this.term.modes.mouseTrackingMode !== 'none') {
588 // xterm.js is in mouse mode and will handle the event.
589 return;
590 }
591 const MIDDLE = 1;
592 const RIGHT = 2;
593 if (e.button === MIDDLE || (e.button === RIGHT &&
594 this.prefs_.getBoolean('mouse-right-click-paste'))) {
595 // Paste.
596 if (navigator.clipboard && navigator.clipboard.readText) {
597 const text = await navigator.clipboard.readText();
598 this.term.paste(text);
599 }
600 }
601 });
602
Jason Lin2649da22022-10-12 10:16:44 +1100603 await this.scheduleFit_();
Jason Lind3aacef2022-10-12 19:03:37 +1100604 this.a11yButtons_ = new A11yButtons(this.term, elem);
605
Jason Lin8de3d282022-09-01 21:29:05 +1000606 this.onTerminalReady();
607 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000608 }
609
610 /** @override */
611 showOverlay(msg, timeout = 1500) {
Jason Lin34a45322022-10-12 19:10:52 +1100612 this.notificationCenter_?.show(msg, {timeout});
Jason Lin21d854f2022-08-22 14:49:59 +1000613 }
614
615 /** @override */
616 hideOverlay() {
Jason Lin34a45322022-10-12 19:10:52 +1100617 this.notificationCenter_?.hide();
Jason Linca61ffb2022-08-03 19:37:12 +1000618 }
619
620 /** @override */
621 getPrefs() {
622 return this.prefs_;
623 }
624
625 /** @override */
626 getDocument() {
627 return window.document;
628 }
629
Jason Lin21d854f2022-08-22 14:49:59 +1000630 /** @override */
631 reset() {
632 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000633 }
634
635 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000636 setProfile(profileId, callback = undefined) {
637 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000638 }
639
Jason Lin21d854f2022-08-22 14:49:59 +1000640 /** @override */
641 interpret(string) {
642 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000643 }
644
Jason Lin21d854f2022-08-22 14:49:59 +1000645 /** @override */
646 focus() {
647 this.term.focus();
648 }
Jason Linca61ffb2022-08-03 19:37:12 +1000649
650 /** @override */
651 onOpenOptionsPage() {}
652
653 /** @override */
654 onTerminalReady() {}
655
Jason Lind04bab32022-08-22 14:48:39 +1000656 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000657 // This is for this.notificationCenter_.
658 const setHtermCSSVariable = (name, value) => {
659 document.body.style.setProperty(`--hterm-${name}`, value);
660 };
661
662 const setHtermColorCSSVariable = (name, color) => {
663 const css = lib.notNull(lib.colors.normalizeCSS(color));
664 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
665 setHtermCSSVariable(name, rgb);
666 };
667
668 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000669 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000670 setHtermCSSVariable('font-size', `${v}px`);
671 });
672
Jason Linda56aa92022-09-02 13:01:49 +1000673 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000674 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000675 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100676 this.bell_.playAudio = !!v;
677 },
678 'desktop-notification-bell': (v) => {
679 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000680 },
Jason Lind04bab32022-08-22 14:48:39 +1000681 'background-color': (v) => {
682 this.updateTheme_({background: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000683 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000684 },
Jason Lind04bab32022-08-22 14:48:39 +1000685 'color-palette-overrides': (v) => {
686 if (!(v instanceof Array)) {
687 // For terminal, we always expect this to be an array.
688 console.warn('unexpected color palette: ', v);
689 return;
690 }
691 const colors = {};
692 for (let i = 0; i < v.length; ++i) {
693 colors[ANSI_COLOR_NAMES[i]] = v[i];
694 }
695 this.updateTheme_(colors);
696 },
Jason Linda56aa92022-09-02 13:01:49 +1000697 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
698 'cursor-color': (v) => this.updateTheme_({cursor: v}),
699 'cursor-shape': (v) => {
700 let shape;
701 if (v === 'BEAM') {
702 shape = 'bar';
703 } else {
704 shape = v.toLowerCase();
705 }
706 this.updateOption_('cursorStyle', shape, false);
707 },
708 'font-family': (v) => this.updateFont_(v),
709 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000710 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000711 setHtermColorCSSVariable('foreground-color', v);
712 },
Jason Linc48f7432022-10-13 17:28:30 +1100713 'line-height': (v) => this.updateOption_('lineHeight', v, true),
Jason Lin446f3d92022-10-13 17:34:21 +1100714 'scroll-on-output': (v) => {
715 if (!v) {
716 this.scrollOnOutputListener_?.dispose();
717 this.scrollOnOutputListener_ = null;
718 return;
719 }
720 if (!this.scrollOnOutputListener_) {
721 this.scrollOnOutputListener_ = this.term.onWriteParsed(
722 () => this.term.scrollToBottom());
723 }
724 },
Jason Lind04bab32022-08-22 14:48:39 +1000725 });
Jason Lin5690e752022-08-30 15:36:45 +1000726
727 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
728 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
729 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
730 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
731 }
Jason Lind04bab32022-08-22 14:48:39 +1000732 }
733
734 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000735 * Fit the terminal to the containing HTML element.
736 */
737 fit_() {
738 if (!this.inited_) {
739 return;
740 }
741
742 const screenPaddingSize = /** @type {number} */(
743 this.prefs_.get('screen-padding-size'));
744
745 const calc = (size, cellSize) => {
746 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
747 };
748
Jason Lin2649da22022-10-12 10:16:44 +1100749 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
750 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
751 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000752 if (cols >= 0 && rows >= 0) {
753 this.term.resize(cols, rows);
754 }
755 }
756
757 /**
Jason Lind04bab32022-08-22 14:48:39 +1000758 * @param {!Object} theme
759 */
760 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000761 const updateTheme = (target) => {
762 for (const [key, value] of Object.entries(theme)) {
763 target[key] = lib.colors.normalizeCSS(value);
764 }
765 };
766
767 // Must use a new theme object to trigger re-render if we have initialized.
768 if (this.inited_) {
769 const newTheme = {...this.term.options.theme};
770 updateTheme(newTheme);
771 this.term.options.theme = newTheme;
772 return;
Jason Lind04bab32022-08-22 14:48:39 +1000773 }
Jason Lin8de3d282022-09-01 21:29:05 +1000774
775 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000776 }
777
778 /**
Jason Linda56aa92022-09-02 13:01:49 +1000779 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
780 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000781 *
782 * @param {string} key
783 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000784 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000785 */
Jason Linda56aa92022-09-02 13:01:49 +1000786 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000787 // TODO: xterm supports updating multiple options at the same time. We
788 // should probably do that.
789 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000790 if (scheduleFit) {
791 this.scheduleFit_();
792 }
Jason Lind04bab32022-08-22 14:48:39 +1000793 }
Jason Linabad7562022-08-22 14:49:05 +1000794
795 /**
796 * Called when there is a "fontloadingdone" event. We need this because
797 * `FontManager.loadFont()` does not guarantee loading all the font files.
798 */
799 async onFontLoadingDone_() {
800 // If there is a pending font, the font is going to be refresh soon, so we
801 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000802 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000803 this.scheduleRefreshFont_();
804 }
805 }
806
Jason Lin5690e752022-08-30 15:36:45 +1000807 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000808 this.copyString_(this.term.getSelection());
809 }
810
811 /** @param {string} data */
812 copyString_(data) {
813 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000814 return;
815 }
Jason Line9231bc2022-09-01 13:54:02 +1000816 navigator.clipboard?.writeText(data);
Jason Lin6a402a72022-08-25 16:07:02 +1000817 if (!this.copyNotice_) {
818 this.copyNotice_ = document.createElement('terminal-copy-notice');
819 }
820 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200);
821 }
822
Jason Linabad7562022-08-22 14:49:05 +1000823 /**
824 * Refresh xterm rendering for a font related event.
825 */
826 refreshFont_() {
827 // We have to set the fontFamily option to a different string to trigger the
828 // re-rendering. Appending a space at the end seems to be the easiest
829 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
830 // us.
831 //
832 // TODO: Report a bug to xterm.js and ask for exposing a public function for
833 // the refresh so that we don't need to do this hack.
834 this.term.options.fontFamily += ' ';
835 }
836
837 /**
838 * Update a font.
839 *
840 * @param {string} cssFontFamily
841 */
842 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000843 this.pendingFont_ = cssFontFamily;
844 await this.fontManager_.loadFont(cssFontFamily);
845 // Sleep a bit to wait for flushing fontloadingdone events. This is not
846 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
847 // to refresh font unnecessarily in some cases.
848 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000849
Jason Lin6a402a72022-08-25 16:07:02 +1000850 if (this.pendingFont_ !== cssFontFamily) {
851 // `updateFont_()` probably is called again. Abort what we are doing.
852 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
853 ` (expecting ${cssFontFamily})`);
854 return;
855 }
Jason Linabad7562022-08-22 14:49:05 +1000856
Jason Lin6a402a72022-08-25 16:07:02 +1000857 if (this.term.options.fontFamily !== cssFontFamily) {
858 this.term.options.fontFamily = cssFontFamily;
859 } else {
860 // If the font is already the same, refresh font just to be safe.
861 this.refreshFont_();
862 }
863 this.pendingFont_ = null;
864 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000865 }
Jason Lin5690e752022-08-30 15:36:45 +1000866
867 /**
868 * @param {!KeyboardEvent} ev
869 * @return {boolean} Return false if xterm.js should not handle the key event.
870 */
871 customKeyEventHandler_(ev) {
872 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
873 (ev.altKey ? Modifier.Alt : 0) |
874 (ev.ctrlKey ? Modifier.Ctrl : 0) |
875 (ev.metaKey ? Modifier.Meta : 0);
876 const handler = this.keyDownHandlers_.get(
877 encodeKeyCombo(modifiers, ev.keyCode));
878 if (handler) {
879 if (ev.type === 'keydown') {
880 handler(ev);
881 }
882 return false;
883 }
884
885 return true;
886 }
887
888 /**
889 * A keydown handler for zoom-related keys.
890 *
891 * @param {!KeyboardEvent} ev
892 */
893 zoomKeyDownHandler_(ev) {
894 ev.preventDefault();
895
896 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
897 // The only one with a control code.
898 if (ev.keyCode === keyCodes.MINUS) {
899 this.io.onVTKeystroke('\x1f');
900 }
901 return;
902 }
903
904 let newFontSize;
905 switch (ev.keyCode) {
906 case keyCodes.ZERO:
907 newFontSize = this.prefs_.get('font-size');
908 break;
909 case keyCodes.MINUS:
910 newFontSize = this.term.options.fontSize - 1;
911 break;
912 default:
913 newFontSize = this.term.options.fontSize + 1;
914 break;
915 }
916
Jason Linda56aa92022-09-02 13:01:49 +1000917 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +1000918 }
919
920 /** @param {!KeyboardEvent} ev */
921 ctrlCKeyDownHandler_(ev) {
922 ev.preventDefault();
923 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
924 this.term.hasSelection()) {
925 this.copySelection_();
926 return;
927 }
928
929 this.io.onVTKeystroke('\x03');
930 }
931
932 /** @param {!KeyboardEvent} ev */
933 ctrlVKeyDownHandler_(ev) {
934 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
935 // Don't do anything and let the browser handles the key.
936 return;
937 }
938
939 ev.preventDefault();
940 this.io.onVTKeystroke('\x16');
941 }
942
943 resetKeyDownHandlers_() {
944 this.keyDownHandlers_.clear();
945
946 /**
947 * Don't do anything and let the browser handles the key.
948 *
949 * @param {!KeyboardEvent} ev
950 */
951 const noop = (ev) => {};
952
953 /**
954 * @param {number} modifiers
955 * @param {number} keyCode
956 * @param {function(!KeyboardEvent)} func
957 */
958 const set = (modifiers, keyCode, func) => {
959 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
960 func);
961 };
962
963 /**
964 * @param {number} modifiers
965 * @param {number} keyCode
966 * @param {function(!KeyboardEvent)} func
967 */
968 const setWithShiftVersion = (modifiers, keyCode, func) => {
969 set(modifiers, keyCode, func);
970 set(modifiers | Modifier.Shift, keyCode, func);
971 };
972
Jason Lin5690e752022-08-30 15:36:45 +1000973 // Ctrl+/
974 set(Modifier.Ctrl, 191, (ev) => {
975 ev.preventDefault();
976 this.io.onVTKeystroke(ctl('_'));
977 });
978
979 // Settings page.
980 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
981 ev.preventDefault();
982 chrome.terminalPrivate.openOptionsPage(() => {});
983 });
984
985 if (this.prefs_.get('keybindings-os-defaults')) {
986 for (const binding of OS_DEFAULT_BINDINGS) {
987 this.keyDownHandlers_.set(binding, noop);
988 }
989 }
990
991 /** @param {!KeyboardEvent} ev */
992 const newWindow = (ev) => {
993 ev.preventDefault();
994 chrome.terminalPrivate.openWindow();
995 };
996 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
997 if (this.prefs_.get('pass-ctrl-n')) {
998 set(Modifier.Ctrl, keyCodes.N, newWindow);
999 }
1000
1001 if (this.prefs_.get('pass-ctrl-t')) {
1002 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
1003 }
1004
1005 if (this.prefs_.get('pass-ctrl-w')) {
1006 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
1007 }
1008
1009 if (this.prefs_.get('pass-ctrl-tab')) {
1010 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
1011 }
1012
1013 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
1014
1015 /**
1016 * Set a handler for the key combo ctrl+<number>.
1017 *
1018 * @param {number} number 1 to 9
1019 * @param {string} controlCode The control code to send if we don't want to
1020 * let the browser to handle it.
1021 */
1022 const setCtrlNumberHandler = (number, controlCode) => {
1023 let func = noop;
1024 if (!passCtrlNumber) {
1025 func = (ev) => {
1026 ev.preventDefault();
1027 this.io.onVTKeystroke(controlCode);
1028 };
1029 }
1030 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1031 };
1032
1033 setCtrlNumberHandler(1, '1');
1034 setCtrlNumberHandler(2, ctl('@'));
1035 setCtrlNumberHandler(3, ctl('['));
1036 setCtrlNumberHandler(4, ctl('\\'));
1037 setCtrlNumberHandler(5, ctl(']'));
1038 setCtrlNumberHandler(6, ctl('^'));
1039 setCtrlNumberHandler(7, ctl('_'));
1040 setCtrlNumberHandler(8, '\x7f');
1041 setCtrlNumberHandler(9, '9');
1042
1043 if (this.prefs_.get('pass-alt-number')) {
1044 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1045 set(Modifier.Alt, keyCode, noop);
1046 }
1047 }
1048
1049 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1050 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1051 }
1052
1053 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1054 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1055 }
Jason Linca61ffb2022-08-03 19:37:12 +10001056}
1057
Jason Lind66e6bf2022-08-22 14:47:10 +10001058class HtermTerminal extends hterm.Terminal {
1059 /** @override */
1060 decorate(div) {
1061 super.decorate(div);
1062
Jason Linc48f7432022-10-13 17:28:30 +11001063 definePrefs(this.getPrefs());
1064
Jason Lind66e6bf2022-08-22 14:47:10 +10001065 const fontManager = new FontManager(this.getDocument());
1066 fontManager.loadPowerlineCSS().then(() => {
1067 const prefs = this.getPrefs();
1068 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1069 prefs.addObserver(
1070 'font-family',
1071 (v) => fontManager.loadFont(/** @type {string} */(v)));
1072 });
1073 }
Jason Lin2649da22022-10-12 10:16:44 +11001074
1075 /**
1076 * Write data to the terminal.
1077 *
1078 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1079 * UTF-8 data
1080 * @param {function()=} callback Optional callback that fires when the data
1081 * was processed by the parser.
1082 */
1083 write(data, callback) {
1084 if (typeof data === 'string') {
1085 this.io.print(data);
1086 } else {
1087 this.io.writeUTF8(data);
1088 }
1089 // Hterm processes the data synchronously, so we can call the callback
1090 // immediately.
1091 if (callback) {
1092 setTimeout(callback);
1093 }
1094 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001095}
1096
Jason Linca61ffb2022-08-03 19:37:12 +10001097/**
1098 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1099 * preference value.
1100 *
1101 * @param {{
1102 * storage: !lib.Storage,
1103 * profileId: string,
1104 * }} args
1105 * @return {!Promise<!hterm.Terminal>}
1106 */
1107export async function createEmulator({storage, profileId}) {
1108 let config = TERMINAL_EMULATORS.get('hterm');
1109
1110 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001111 // TODO: remove the url param logic. This is temporary to make manual
1112 // testing a bit easier, which is also why this is not in
1113 // './js/terminal_info.js'.
1114 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
1115 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +10001116 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001117 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001118 TERMINAL_EMULATORS.values().next().value;
1119 console.log('Terminal emulator config: ', config);
1120 }
1121
1122 switch (config.lib) {
1123 case 'xterm.js':
1124 {
1125 const terminal = new XtermTerminal({
1126 storage,
1127 profileId,
1128 enableWebGL: config.webgl,
1129 });
Jason Linca61ffb2022-08-03 19:37:12 +10001130 return terminal;
1131 }
1132 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001133 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001134 default:
1135 throw new Error('incorrect emulator config');
1136 }
1137}
1138
Jason Lin6a402a72022-08-25 16:07:02 +10001139class TerminalCopyNotice extends LitElement {
1140 /** @override */
1141 static get styles() {
1142 return css`
1143 :host {
1144 display: block;
1145 text-align: center;
1146 }
1147
1148 svg {
1149 fill: currentColor;
1150 }
1151 `;
1152 }
1153
1154 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001155 connectedCallback() {
1156 super.connectedCallback();
1157 if (!this.childNodes.length) {
1158 // This is not visible since we use shadow dom. But this will allow the
1159 // hterm.NotificationCenter to announce the the copy text.
1160 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1161 }
1162 }
1163
1164 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001165 render() {
1166 return html`
1167 ${ICON_COPY}
1168 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1169 `;
1170 }
1171}
1172
1173customElements.define('terminal-copy-notice', TerminalCopyNotice);