blob: 53752dcb584c149b28e08d3d4ed510a6ef2b1229 [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;
397
Jason Lin83707c92022-09-20 19:09:41 +1000398 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000399 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000400 // The webgl cursor layer also paints the character under the cursor with
401 // this `cursorAccent` color. We use a completely transparent color here
402 // to effectively disable that.
403 cursorAccent: 'rgba(0, 0, 0, 0)',
404 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000405 selectionBackground: 'rgba(174, 203, 250, .6)',
406 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000407 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000408 };
409 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000410 }
411
Jason Linc7afb672022-10-11 15:54:17 +1100412 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100413 setWindowTitle(title) {
414 document.title = title;
415 }
416
417 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100418 ringBell() {
419 this.bell_.ring();
420 }
421
Jason Lin2649da22022-10-12 10:16:44 +1100422 /** @override */
423 print(str) {
424 this.xtermInternal_.print(str);
425 }
426
427 /** @override */
428 wipeContents() {
429 this.term.clear();
430 }
431
432 /** @override */
433 newLine() {
434 this.xtermInternal_.newLine();
435 }
436
437 /** @override */
438 cursorLeft(number) {
439 this.xtermInternal_.cursorLeft(number ?? 1);
440 }
441
Jason Lind3aacef2022-10-12 19:03:37 +1100442 /** @override */
443 setAccessibilityEnabled(enabled) {
444 this.a11yButtons_.setEnabled(enabled);
445 this.htermA11yReader_.setAccessibilityEnabled(enabled);
446 this.term.options.screenReaderMode = enabled;
447 }
448
Jason Linca61ffb2022-08-03 19:37:12 +1000449 /**
450 * Install stubs for stuff that we haven't implemented yet so that the code
451 * still runs.
452 */
453 installUnimplementedStubs_() {
454 this.keyboard = {
455 keyMap: {
456 keyDefs: [],
457 },
458 bindings: {
459 clear: () => {},
460 addBinding: () => {},
461 addBindings: () => {},
462 OsDefaults: {},
463 },
464 };
465 this.keyboard.keyMap.keyDefs[78] = {};
466
467 const methodNames = [
Jason Linca61ffb2022-08-03 19:37:12 +1000468 'setBackgroundImage',
469 'setCursorPosition',
470 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000471 ];
472
473 for (const name of methodNames) {
474 this[name] = () => console.warn(`${name}() is not implemented`);
475 }
476
477 this.contextMenu = {
478 setItems: () => {
479 console.warn('.contextMenu.setItems() is not implemented');
480 },
481 };
Jason Lin21d854f2022-08-22 14:49:59 +1000482
483 this.vt = {
484 resetParseState: () => {
485 console.warn('.vt.resetParseState() is not implemented');
486 },
487 };
Jason Linca61ffb2022-08-03 19:37:12 +1000488 }
489
Jason Line9231bc2022-09-01 13:54:02 +1000490 installEscapeSequenceHandlers_() {
491 // OSC 52 for copy.
492 this.term.parser.registerOscHandler(52, (args) => {
493 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
494 // parameter is used to select which of the X clipboards to address. Since
495 // we're not integrating with X, we treat them all the same.
496 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
497 if (!parsedArgs) {
498 return true;
499 }
500
501 let data;
502 try {
503 data = window.atob(parsedArgs[1]);
504 } catch (e) {
505 // If the user sent us invalid base64 content, silently ignore it.
506 return true;
507 }
508 const decoder = new TextDecoder();
509 const bytes = lib.codec.stringToCodeUnitArray(data);
510 this.copyString_(decoder.decode(bytes));
511
512 return true;
513 });
Jason Lin2649da22022-10-12 10:16:44 +1100514
515 this.xtermInternal_.installTmuxControlModeHandler(
516 (data) => this.onTmuxControlModeLine(data));
517 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000518 }
519
Jason Linca61ffb2022-08-03 19:37:12 +1000520 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000521 * Write data to the terminal.
522 *
523 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
524 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100525 * @param {function()=} callback Optional callback that fires when the data
526 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000527 */
Jason Lin2649da22022-10-12 10:16:44 +1100528 write(data, callback) {
529 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000530 }
531
532 /**
533 * Like `this.write()` but also write a line break.
534 *
535 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100536 * @param {function()=} callback Optional callback that fires when the data
537 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000538 */
Jason Lin2649da22022-10-12 10:16:44 +1100539 writeln(data, callback) {
540 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000541 }
542
Jason Linca61ffb2022-08-03 19:37:12 +1000543 get screenSize() {
544 return new hterm.Size(this.term.cols, this.term.rows);
545 }
546
547 /**
548 * Don't need to do anything.
549 *
550 * @override
551 */
552 installKeyboard() {}
553
554 /**
555 * @override
556 */
557 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000558 this.container_ = elem;
Jason Lin8de3d282022-09-01 21:29:05 +1000559 (async () => {
560 await new Promise((resolve) => this.prefs_.readStorage(resolve));
561 // This will trigger all the observers to set the terminal options before
562 // we call `this.term.open()`.
563 this.prefs_.notifyAll();
564
Jason Linc2504ae2022-09-02 13:03:31 +1000565 const screenPaddingSize = /** @type {number} */(
566 this.prefs_.get('screen-padding-size'));
567 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
568
Jason Lin8de3d282022-09-01 21:29:05 +1000569 this.inited_ = true;
570 this.term.open(elem);
571
Jason Lin8de3d282022-09-01 21:29:05 +1000572 if (this.enableWebGL_) {
573 this.term.loadAddon(new WebglAddon());
574 }
575 this.term.focus();
576 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100577 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
578 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
579 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000580
Emil Mikulic2a194d02022-09-29 14:30:59 +1000581 // Block right-click context menu from popping up.
582 elem.addEventListener('contextmenu', (e) => e.preventDefault());
583
584 // Add a handler for pasting with the mouse.
585 elem.addEventListener('mousedown', async (e) => {
586 if (this.term.modes.mouseTrackingMode !== 'none') {
587 // xterm.js is in mouse mode and will handle the event.
588 return;
589 }
590 const MIDDLE = 1;
591 const RIGHT = 2;
592 if (e.button === MIDDLE || (e.button === RIGHT &&
593 this.prefs_.getBoolean('mouse-right-click-paste'))) {
594 // Paste.
595 if (navigator.clipboard && navigator.clipboard.readText) {
596 const text = await navigator.clipboard.readText();
597 this.term.paste(text);
598 }
599 }
600 });
601
Jason Lin2649da22022-10-12 10:16:44 +1100602 await this.scheduleFit_();
Jason Lind3aacef2022-10-12 19:03:37 +1100603 this.a11yButtons_ = new A11yButtons(this.term, elem);
604
Jason Lin8de3d282022-09-01 21:29:05 +1000605 this.onTerminalReady();
606 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000607 }
608
609 /** @override */
610 showOverlay(msg, timeout = 1500) {
Jason Lin34a45322022-10-12 19:10:52 +1100611 this.notificationCenter_?.show(msg, {timeout});
Jason Lin21d854f2022-08-22 14:49:59 +1000612 }
613
614 /** @override */
615 hideOverlay() {
Jason Lin34a45322022-10-12 19:10:52 +1100616 this.notificationCenter_?.hide();
Jason Linca61ffb2022-08-03 19:37:12 +1000617 }
618
619 /** @override */
620 getPrefs() {
621 return this.prefs_;
622 }
623
624 /** @override */
625 getDocument() {
626 return window.document;
627 }
628
Jason Lin21d854f2022-08-22 14:49:59 +1000629 /** @override */
630 reset() {
631 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000632 }
633
634 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000635 setProfile(profileId, callback = undefined) {
636 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000637 }
638
Jason Lin21d854f2022-08-22 14:49:59 +1000639 /** @override */
640 interpret(string) {
641 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000642 }
643
Jason Lin21d854f2022-08-22 14:49:59 +1000644 /** @override */
645 focus() {
646 this.term.focus();
647 }
Jason Linca61ffb2022-08-03 19:37:12 +1000648
649 /** @override */
650 onOpenOptionsPage() {}
651
652 /** @override */
653 onTerminalReady() {}
654
Jason Lind04bab32022-08-22 14:48:39 +1000655 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000656 // This is for this.notificationCenter_.
657 const setHtermCSSVariable = (name, value) => {
658 document.body.style.setProperty(`--hterm-${name}`, value);
659 };
660
661 const setHtermColorCSSVariable = (name, color) => {
662 const css = lib.notNull(lib.colors.normalizeCSS(color));
663 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
664 setHtermCSSVariable(name, rgb);
665 };
666
667 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000668 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000669 setHtermCSSVariable('font-size', `${v}px`);
670 });
671
Jason Linda56aa92022-09-02 13:01:49 +1000672 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000673 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000674 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100675 this.bell_.playAudio = !!v;
676 },
677 'desktop-notification-bell': (v) => {
678 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000679 },
Jason Lind04bab32022-08-22 14:48:39 +1000680 'background-color': (v) => {
681 this.updateTheme_({background: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000682 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000683 },
Jason Lind04bab32022-08-22 14:48:39 +1000684 'color-palette-overrides': (v) => {
685 if (!(v instanceof Array)) {
686 // For terminal, we always expect this to be an array.
687 console.warn('unexpected color palette: ', v);
688 return;
689 }
690 const colors = {};
691 for (let i = 0; i < v.length; ++i) {
692 colors[ANSI_COLOR_NAMES[i]] = v[i];
693 }
694 this.updateTheme_(colors);
695 },
Jason Linda56aa92022-09-02 13:01:49 +1000696 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
697 'cursor-color': (v) => this.updateTheme_({cursor: v}),
698 'cursor-shape': (v) => {
699 let shape;
700 if (v === 'BEAM') {
701 shape = 'bar';
702 } else {
703 shape = v.toLowerCase();
704 }
705 this.updateOption_('cursorStyle', shape, false);
706 },
707 'font-family': (v) => this.updateFont_(v),
708 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000709 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000710 setHtermColorCSSVariable('foreground-color', v);
711 },
Jason Linc48f7432022-10-13 17:28:30 +1100712 'line-height': (v) => this.updateOption_('lineHeight', v, true),
Jason Lind04bab32022-08-22 14:48:39 +1000713 });
Jason Lin5690e752022-08-30 15:36:45 +1000714
715 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
716 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
717 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
718 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
719 }
Jason Lind04bab32022-08-22 14:48:39 +1000720 }
721
722 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000723 * Fit the terminal to the containing HTML element.
724 */
725 fit_() {
726 if (!this.inited_) {
727 return;
728 }
729
730 const screenPaddingSize = /** @type {number} */(
731 this.prefs_.get('screen-padding-size'));
732
733 const calc = (size, cellSize) => {
734 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
735 };
736
Jason Lin2649da22022-10-12 10:16:44 +1100737 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
738 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
739 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000740 if (cols >= 0 && rows >= 0) {
741 this.term.resize(cols, rows);
742 }
743 }
744
745 /**
Jason Lind04bab32022-08-22 14:48:39 +1000746 * @param {!Object} theme
747 */
748 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000749 const updateTheme = (target) => {
750 for (const [key, value] of Object.entries(theme)) {
751 target[key] = lib.colors.normalizeCSS(value);
752 }
753 };
754
755 // Must use a new theme object to trigger re-render if we have initialized.
756 if (this.inited_) {
757 const newTheme = {...this.term.options.theme};
758 updateTheme(newTheme);
759 this.term.options.theme = newTheme;
760 return;
Jason Lind04bab32022-08-22 14:48:39 +1000761 }
Jason Lin8de3d282022-09-01 21:29:05 +1000762
763 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000764 }
765
766 /**
Jason Linda56aa92022-09-02 13:01:49 +1000767 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
768 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000769 *
770 * @param {string} key
771 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000772 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000773 */
Jason Linda56aa92022-09-02 13:01:49 +1000774 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000775 // TODO: xterm supports updating multiple options at the same time. We
776 // should probably do that.
777 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000778 if (scheduleFit) {
779 this.scheduleFit_();
780 }
Jason Lind04bab32022-08-22 14:48:39 +1000781 }
Jason Linabad7562022-08-22 14:49:05 +1000782
783 /**
784 * Called when there is a "fontloadingdone" event. We need this because
785 * `FontManager.loadFont()` does not guarantee loading all the font files.
786 */
787 async onFontLoadingDone_() {
788 // If there is a pending font, the font is going to be refresh soon, so we
789 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000790 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000791 this.scheduleRefreshFont_();
792 }
793 }
794
Jason Lin5690e752022-08-30 15:36:45 +1000795 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000796 this.copyString_(this.term.getSelection());
797 }
798
799 /** @param {string} data */
800 copyString_(data) {
801 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000802 return;
803 }
Jason Line9231bc2022-09-01 13:54:02 +1000804 navigator.clipboard?.writeText(data);
Jason Lin6a402a72022-08-25 16:07:02 +1000805 if (!this.copyNotice_) {
806 this.copyNotice_ = document.createElement('terminal-copy-notice');
807 }
808 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200);
809 }
810
Jason Linabad7562022-08-22 14:49:05 +1000811 /**
812 * Refresh xterm rendering for a font related event.
813 */
814 refreshFont_() {
815 // We have to set the fontFamily option to a different string to trigger the
816 // re-rendering. Appending a space at the end seems to be the easiest
817 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
818 // us.
819 //
820 // TODO: Report a bug to xterm.js and ask for exposing a public function for
821 // the refresh so that we don't need to do this hack.
822 this.term.options.fontFamily += ' ';
823 }
824
825 /**
826 * Update a font.
827 *
828 * @param {string} cssFontFamily
829 */
830 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000831 this.pendingFont_ = cssFontFamily;
832 await this.fontManager_.loadFont(cssFontFamily);
833 // Sleep a bit to wait for flushing fontloadingdone events. This is not
834 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
835 // to refresh font unnecessarily in some cases.
836 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000837
Jason Lin6a402a72022-08-25 16:07:02 +1000838 if (this.pendingFont_ !== cssFontFamily) {
839 // `updateFont_()` probably is called again. Abort what we are doing.
840 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
841 ` (expecting ${cssFontFamily})`);
842 return;
843 }
Jason Linabad7562022-08-22 14:49:05 +1000844
Jason Lin6a402a72022-08-25 16:07:02 +1000845 if (this.term.options.fontFamily !== cssFontFamily) {
846 this.term.options.fontFamily = cssFontFamily;
847 } else {
848 // If the font is already the same, refresh font just to be safe.
849 this.refreshFont_();
850 }
851 this.pendingFont_ = null;
852 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000853 }
Jason Lin5690e752022-08-30 15:36:45 +1000854
855 /**
856 * @param {!KeyboardEvent} ev
857 * @return {boolean} Return false if xterm.js should not handle the key event.
858 */
859 customKeyEventHandler_(ev) {
860 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
861 (ev.altKey ? Modifier.Alt : 0) |
862 (ev.ctrlKey ? Modifier.Ctrl : 0) |
863 (ev.metaKey ? Modifier.Meta : 0);
864 const handler = this.keyDownHandlers_.get(
865 encodeKeyCombo(modifiers, ev.keyCode));
866 if (handler) {
867 if (ev.type === 'keydown') {
868 handler(ev);
869 }
870 return false;
871 }
872
873 return true;
874 }
875
876 /**
877 * A keydown handler for zoom-related keys.
878 *
879 * @param {!KeyboardEvent} ev
880 */
881 zoomKeyDownHandler_(ev) {
882 ev.preventDefault();
883
884 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
885 // The only one with a control code.
886 if (ev.keyCode === keyCodes.MINUS) {
887 this.io.onVTKeystroke('\x1f');
888 }
889 return;
890 }
891
892 let newFontSize;
893 switch (ev.keyCode) {
894 case keyCodes.ZERO:
895 newFontSize = this.prefs_.get('font-size');
896 break;
897 case keyCodes.MINUS:
898 newFontSize = this.term.options.fontSize - 1;
899 break;
900 default:
901 newFontSize = this.term.options.fontSize + 1;
902 break;
903 }
904
Jason Linda56aa92022-09-02 13:01:49 +1000905 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +1000906 }
907
908 /** @param {!KeyboardEvent} ev */
909 ctrlCKeyDownHandler_(ev) {
910 ev.preventDefault();
911 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
912 this.term.hasSelection()) {
913 this.copySelection_();
914 return;
915 }
916
917 this.io.onVTKeystroke('\x03');
918 }
919
920 /** @param {!KeyboardEvent} ev */
921 ctrlVKeyDownHandler_(ev) {
922 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
923 // Don't do anything and let the browser handles the key.
924 return;
925 }
926
927 ev.preventDefault();
928 this.io.onVTKeystroke('\x16');
929 }
930
931 resetKeyDownHandlers_() {
932 this.keyDownHandlers_.clear();
933
934 /**
935 * Don't do anything and let the browser handles the key.
936 *
937 * @param {!KeyboardEvent} ev
938 */
939 const noop = (ev) => {};
940
941 /**
942 * @param {number} modifiers
943 * @param {number} keyCode
944 * @param {function(!KeyboardEvent)} func
945 */
946 const set = (modifiers, keyCode, func) => {
947 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
948 func);
949 };
950
951 /**
952 * @param {number} modifiers
953 * @param {number} keyCode
954 * @param {function(!KeyboardEvent)} func
955 */
956 const setWithShiftVersion = (modifiers, keyCode, func) => {
957 set(modifiers, keyCode, func);
958 set(modifiers | Modifier.Shift, keyCode, func);
959 };
960
Jason Lin5690e752022-08-30 15:36:45 +1000961 // Ctrl+/
962 set(Modifier.Ctrl, 191, (ev) => {
963 ev.preventDefault();
964 this.io.onVTKeystroke(ctl('_'));
965 });
966
967 // Settings page.
968 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
969 ev.preventDefault();
970 chrome.terminalPrivate.openOptionsPage(() => {});
971 });
972
973 if (this.prefs_.get('keybindings-os-defaults')) {
974 for (const binding of OS_DEFAULT_BINDINGS) {
975 this.keyDownHandlers_.set(binding, noop);
976 }
977 }
978
979 /** @param {!KeyboardEvent} ev */
980 const newWindow = (ev) => {
981 ev.preventDefault();
982 chrome.terminalPrivate.openWindow();
983 };
984 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
985 if (this.prefs_.get('pass-ctrl-n')) {
986 set(Modifier.Ctrl, keyCodes.N, newWindow);
987 }
988
989 if (this.prefs_.get('pass-ctrl-t')) {
990 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
991 }
992
993 if (this.prefs_.get('pass-ctrl-w')) {
994 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
995 }
996
997 if (this.prefs_.get('pass-ctrl-tab')) {
998 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
999 }
1000
1001 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
1002
1003 /**
1004 * Set a handler for the key combo ctrl+<number>.
1005 *
1006 * @param {number} number 1 to 9
1007 * @param {string} controlCode The control code to send if we don't want to
1008 * let the browser to handle it.
1009 */
1010 const setCtrlNumberHandler = (number, controlCode) => {
1011 let func = noop;
1012 if (!passCtrlNumber) {
1013 func = (ev) => {
1014 ev.preventDefault();
1015 this.io.onVTKeystroke(controlCode);
1016 };
1017 }
1018 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1019 };
1020
1021 setCtrlNumberHandler(1, '1');
1022 setCtrlNumberHandler(2, ctl('@'));
1023 setCtrlNumberHandler(3, ctl('['));
1024 setCtrlNumberHandler(4, ctl('\\'));
1025 setCtrlNumberHandler(5, ctl(']'));
1026 setCtrlNumberHandler(6, ctl('^'));
1027 setCtrlNumberHandler(7, ctl('_'));
1028 setCtrlNumberHandler(8, '\x7f');
1029 setCtrlNumberHandler(9, '9');
1030
1031 if (this.prefs_.get('pass-alt-number')) {
1032 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1033 set(Modifier.Alt, keyCode, noop);
1034 }
1035 }
1036
1037 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1038 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1039 }
1040
1041 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1042 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1043 }
Jason Linca61ffb2022-08-03 19:37:12 +10001044}
1045
Jason Lind66e6bf2022-08-22 14:47:10 +10001046class HtermTerminal extends hterm.Terminal {
1047 /** @override */
1048 decorate(div) {
1049 super.decorate(div);
1050
Jason Linc48f7432022-10-13 17:28:30 +11001051 definePrefs(this.getPrefs());
1052
Jason Lind66e6bf2022-08-22 14:47:10 +10001053 const fontManager = new FontManager(this.getDocument());
1054 fontManager.loadPowerlineCSS().then(() => {
1055 const prefs = this.getPrefs();
1056 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1057 prefs.addObserver(
1058 'font-family',
1059 (v) => fontManager.loadFont(/** @type {string} */(v)));
1060 });
1061 }
Jason Lin2649da22022-10-12 10:16:44 +11001062
1063 /**
1064 * Write data to the terminal.
1065 *
1066 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1067 * UTF-8 data
1068 * @param {function()=} callback Optional callback that fires when the data
1069 * was processed by the parser.
1070 */
1071 write(data, callback) {
1072 if (typeof data === 'string') {
1073 this.io.print(data);
1074 } else {
1075 this.io.writeUTF8(data);
1076 }
1077 // Hterm processes the data synchronously, so we can call the callback
1078 // immediately.
1079 if (callback) {
1080 setTimeout(callback);
1081 }
1082 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001083}
1084
Jason Linca61ffb2022-08-03 19:37:12 +10001085/**
1086 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1087 * preference value.
1088 *
1089 * @param {{
1090 * storage: !lib.Storage,
1091 * profileId: string,
1092 * }} args
1093 * @return {!Promise<!hterm.Terminal>}
1094 */
1095export async function createEmulator({storage, profileId}) {
1096 let config = TERMINAL_EMULATORS.get('hterm');
1097
1098 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001099 // TODO: remove the url param logic. This is temporary to make manual
1100 // testing a bit easier, which is also why this is not in
1101 // './js/terminal_info.js'.
1102 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
1103 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +10001104 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001105 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001106 TERMINAL_EMULATORS.values().next().value;
1107 console.log('Terminal emulator config: ', config);
1108 }
1109
1110 switch (config.lib) {
1111 case 'xterm.js':
1112 {
1113 const terminal = new XtermTerminal({
1114 storage,
1115 profileId,
1116 enableWebGL: config.webgl,
1117 });
Jason Linca61ffb2022-08-03 19:37:12 +10001118 return terminal;
1119 }
1120 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001121 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001122 default:
1123 throw new Error('incorrect emulator config');
1124 }
1125}
1126
Jason Lin6a402a72022-08-25 16:07:02 +10001127class TerminalCopyNotice extends LitElement {
1128 /** @override */
1129 static get styles() {
1130 return css`
1131 :host {
1132 display: block;
1133 text-align: center;
1134 }
1135
1136 svg {
1137 fill: currentColor;
1138 }
1139 `;
1140 }
1141
1142 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001143 connectedCallback() {
1144 super.connectedCallback();
1145 if (!this.childNodes.length) {
1146 // This is not visible since we use shadow dom. But this will allow the
1147 // hterm.NotificationCenter to announce the the copy text.
1148 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1149 }
1150 }
1151
1152 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001153 render() {
1154 return html`
1155 ${ICON_COPY}
1156 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1157 `;
1158 }
1159}
1160
1161customElements.define('terminal-copy-notice', TerminalCopyNotice);