blob: 9d51c53a0a1a46bf7e33b844fb0e5f53edba8478 [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 Lin21d854f2022-08-22 14:49:59 +1000357 this.term.onResize(({cols, rows}) => this.io.onTerminalResize(cols, rows));
358 // We could also use `this.io.sendString()` except for the nassh exit
359 // prompt, which only listens to onVTKeystroke().
360 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000361 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100362 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin5690e752022-08-30 15:36:45 +1000363 this.term.onSelectionChange(() => this.copySelection_());
Jason Linc7afb672022-10-11 15:54:17 +1100364 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000365
366 /**
367 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
368 *
369 * If a key combo is in the map:
370 *
371 * - The handler instead of xterm.js will handle the keydown event.
372 * - Keyup and keypress will be ignored by both us and xterm.js.
373 *
374 * We re-generate this map every time a relevant pref value is changed. This
375 * is ok because pref changes are rare.
376 *
377 * @type {!Map<number, function(!KeyboardEvent)>}
378 */
379 this.keyDownHandlers_ = new Map();
380 this.scheduleResetKeyDownHandlers_ =
381 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
382
383 this.term.attachCustomKeyEventHandler(
384 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000385
Jason Lin21d854f2022-08-22 14:49:59 +1000386 this.io = new XtermTerminalIO(this);
387 this.notificationCenter_ = null;
Jason Lind3aacef2022-10-12 19:03:37 +1100388 this.htermA11yReader_ = null;
389 this.a11yButtons_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000390 this.copyNotice_ = null;
391
Jason Lin83707c92022-09-20 19:09:41 +1000392 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000393 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000394 // The webgl cursor layer also paints the character under the cursor with
395 // this `cursorAccent` color. We use a completely transparent color here
396 // to effectively disable that.
397 cursorAccent: 'rgba(0, 0, 0, 0)',
398 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000399 selectionBackground: 'rgba(174, 203, 250, .6)',
400 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000401 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000402 };
403 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000404 }
405
Jason Linc7afb672022-10-11 15:54:17 +1100406 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100407 setWindowTitle(title) {
408 document.title = title;
409 }
410
411 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100412 ringBell() {
413 this.bell_.ring();
414 }
415
Jason Lin2649da22022-10-12 10:16:44 +1100416 /** @override */
417 print(str) {
418 this.xtermInternal_.print(str);
419 }
420
421 /** @override */
422 wipeContents() {
423 this.term.clear();
424 }
425
426 /** @override */
427 newLine() {
428 this.xtermInternal_.newLine();
429 }
430
431 /** @override */
432 cursorLeft(number) {
433 this.xtermInternal_.cursorLeft(number ?? 1);
434 }
435
Jason Lind3aacef2022-10-12 19:03:37 +1100436 /** @override */
437 setAccessibilityEnabled(enabled) {
438 this.a11yButtons_.setEnabled(enabled);
439 this.htermA11yReader_.setAccessibilityEnabled(enabled);
440 this.term.options.screenReaderMode = enabled;
441 }
442
Jason Linca61ffb2022-08-03 19:37:12 +1000443 /**
444 * Install stubs for stuff that we haven't implemented yet so that the code
445 * still runs.
446 */
447 installUnimplementedStubs_() {
448 this.keyboard = {
449 keyMap: {
450 keyDefs: [],
451 },
452 bindings: {
453 clear: () => {},
454 addBinding: () => {},
455 addBindings: () => {},
456 OsDefaults: {},
457 },
458 };
459 this.keyboard.keyMap.keyDefs[78] = {};
460
461 const methodNames = [
Jason Linca61ffb2022-08-03 19:37:12 +1000462 'setBackgroundImage',
463 'setCursorPosition',
464 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000465 ];
466
467 for (const name of methodNames) {
468 this[name] = () => console.warn(`${name}() is not implemented`);
469 }
470
471 this.contextMenu = {
472 setItems: () => {
473 console.warn('.contextMenu.setItems() is not implemented');
474 },
475 };
Jason Lin21d854f2022-08-22 14:49:59 +1000476
477 this.vt = {
478 resetParseState: () => {
479 console.warn('.vt.resetParseState() is not implemented');
480 },
481 };
Jason Linca61ffb2022-08-03 19:37:12 +1000482 }
483
Jason Line9231bc2022-09-01 13:54:02 +1000484 installEscapeSequenceHandlers_() {
485 // OSC 52 for copy.
486 this.term.parser.registerOscHandler(52, (args) => {
487 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
488 // parameter is used to select which of the X clipboards to address. Since
489 // we're not integrating with X, we treat them all the same.
490 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
491 if (!parsedArgs) {
492 return true;
493 }
494
495 let data;
496 try {
497 data = window.atob(parsedArgs[1]);
498 } catch (e) {
499 // If the user sent us invalid base64 content, silently ignore it.
500 return true;
501 }
502 const decoder = new TextDecoder();
503 const bytes = lib.codec.stringToCodeUnitArray(data);
504 this.copyString_(decoder.decode(bytes));
505
506 return true;
507 });
Jason Lin2649da22022-10-12 10:16:44 +1100508
509 this.xtermInternal_.installTmuxControlModeHandler(
510 (data) => this.onTmuxControlModeLine(data));
511 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000512 }
513
Jason Linca61ffb2022-08-03 19:37:12 +1000514 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000515 * Write data to the terminal.
516 *
517 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
518 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100519 * @param {function()=} callback Optional callback that fires when the data
520 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000521 */
Jason Lin2649da22022-10-12 10:16:44 +1100522 write(data, callback) {
523 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000524 }
525
526 /**
527 * Like `this.write()` but also write a line break.
528 *
529 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100530 * @param {function()=} callback Optional callback that fires when the data
531 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000532 */
Jason Lin2649da22022-10-12 10:16:44 +1100533 writeln(data, callback) {
534 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000535 }
536
Jason Linca61ffb2022-08-03 19:37:12 +1000537 get screenSize() {
538 return new hterm.Size(this.term.cols, this.term.rows);
539 }
540
541 /**
542 * Don't need to do anything.
543 *
544 * @override
545 */
546 installKeyboard() {}
547
548 /**
549 * @override
550 */
551 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000552 this.container_ = elem;
Jason Lin8de3d282022-09-01 21:29:05 +1000553 (async () => {
554 await new Promise((resolve) => this.prefs_.readStorage(resolve));
555 // This will trigger all the observers to set the terminal options before
556 // we call `this.term.open()`.
557 this.prefs_.notifyAll();
558
Jason Linc2504ae2022-09-02 13:03:31 +1000559 const screenPaddingSize = /** @type {number} */(
560 this.prefs_.get('screen-padding-size'));
561 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
562
Jason Lin8de3d282022-09-01 21:29:05 +1000563 this.inited_ = true;
564 this.term.open(elem);
565
Jason Lin8de3d282022-09-01 21:29:05 +1000566 if (this.enableWebGL_) {
567 this.term.loadAddon(new WebglAddon());
568 }
569 this.term.focus();
570 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100571 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
572 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
573 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000574
Emil Mikulic2a194d02022-09-29 14:30:59 +1000575 // Block right-click context menu from popping up.
576 elem.addEventListener('contextmenu', (e) => e.preventDefault());
577
578 // Add a handler for pasting with the mouse.
579 elem.addEventListener('mousedown', async (e) => {
580 if (this.term.modes.mouseTrackingMode !== 'none') {
581 // xterm.js is in mouse mode and will handle the event.
582 return;
583 }
584 const MIDDLE = 1;
585 const RIGHT = 2;
586 if (e.button === MIDDLE || (e.button === RIGHT &&
587 this.prefs_.getBoolean('mouse-right-click-paste'))) {
588 // Paste.
589 if (navigator.clipboard && navigator.clipboard.readText) {
590 const text = await navigator.clipboard.readText();
591 this.term.paste(text);
592 }
593 }
594 });
595
Jason Lin2649da22022-10-12 10:16:44 +1100596 await this.scheduleFit_();
Jason Lind3aacef2022-10-12 19:03:37 +1100597 this.a11yButtons_ = new A11yButtons(this.term, elem);
598
Jason Lin8de3d282022-09-01 21:29:05 +1000599 this.onTerminalReady();
600 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000601 }
602
603 /** @override */
604 showOverlay(msg, timeout = 1500) {
605 if (this.notificationCenter_) {
606 this.notificationCenter_.show(msg, {timeout});
607 }
608 }
609
610 /** @override */
611 hideOverlay() {
612 if (this.notificationCenter_) {
613 this.notificationCenter_.hide();
614 }
Jason Linca61ffb2022-08-03 19:37:12 +1000615 }
616
617 /** @override */
618 getPrefs() {
619 return this.prefs_;
620 }
621
622 /** @override */
623 getDocument() {
624 return window.document;
625 }
626
Jason Lin21d854f2022-08-22 14:49:59 +1000627 /** @override */
628 reset() {
629 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000630 }
631
632 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000633 setProfile(profileId, callback = undefined) {
634 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000635 }
636
Jason Lin21d854f2022-08-22 14:49:59 +1000637 /** @override */
638 interpret(string) {
639 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000640 }
641
Jason Lin21d854f2022-08-22 14:49:59 +1000642 /** @override */
643 focus() {
644 this.term.focus();
645 }
Jason Linca61ffb2022-08-03 19:37:12 +1000646
647 /** @override */
648 onOpenOptionsPage() {}
649
650 /** @override */
651 onTerminalReady() {}
652
Jason Lind04bab32022-08-22 14:48:39 +1000653 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000654 // This is for this.notificationCenter_.
655 const setHtermCSSVariable = (name, value) => {
656 document.body.style.setProperty(`--hterm-${name}`, value);
657 };
658
659 const setHtermColorCSSVariable = (name, color) => {
660 const css = lib.notNull(lib.colors.normalizeCSS(color));
661 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
662 setHtermCSSVariable(name, rgb);
663 };
664
665 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000666 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000667 setHtermCSSVariable('font-size', `${v}px`);
668 });
669
Jason Linda56aa92022-09-02 13:01:49 +1000670 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000671 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000672 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100673 this.bell_.playAudio = !!v;
674 },
675 'desktop-notification-bell': (v) => {
676 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000677 },
Jason Lind04bab32022-08-22 14:48:39 +1000678 'background-color': (v) => {
679 this.updateTheme_({background: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000680 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000681 },
Jason Lind04bab32022-08-22 14:48:39 +1000682 'color-palette-overrides': (v) => {
683 if (!(v instanceof Array)) {
684 // For terminal, we always expect this to be an array.
685 console.warn('unexpected color palette: ', v);
686 return;
687 }
688 const colors = {};
689 for (let i = 0; i < v.length; ++i) {
690 colors[ANSI_COLOR_NAMES[i]] = v[i];
691 }
692 this.updateTheme_(colors);
693 },
Jason Linda56aa92022-09-02 13:01:49 +1000694 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
695 'cursor-color': (v) => this.updateTheme_({cursor: v}),
696 'cursor-shape': (v) => {
697 let shape;
698 if (v === 'BEAM') {
699 shape = 'bar';
700 } else {
701 shape = v.toLowerCase();
702 }
703 this.updateOption_('cursorStyle', shape, false);
704 },
705 'font-family': (v) => this.updateFont_(v),
706 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000707 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000708 setHtermColorCSSVariable('foreground-color', v);
709 },
Jason Lind04bab32022-08-22 14:48:39 +1000710 });
Jason Lin5690e752022-08-30 15:36:45 +1000711
712 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
713 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
714 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
715 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
716 }
Jason Lind04bab32022-08-22 14:48:39 +1000717 }
718
719 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000720 * Fit the terminal to the containing HTML element.
721 */
722 fit_() {
723 if (!this.inited_) {
724 return;
725 }
726
727 const screenPaddingSize = /** @type {number} */(
728 this.prefs_.get('screen-padding-size'));
729
730 const calc = (size, cellSize) => {
731 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
732 };
733
Jason Lin2649da22022-10-12 10:16:44 +1100734 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
735 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
736 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000737 if (cols >= 0 && rows >= 0) {
738 this.term.resize(cols, rows);
739 }
740 }
741
742 /**
Jason Lind04bab32022-08-22 14:48:39 +1000743 * @param {!Object} theme
744 */
745 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000746 const updateTheme = (target) => {
747 for (const [key, value] of Object.entries(theme)) {
748 target[key] = lib.colors.normalizeCSS(value);
749 }
750 };
751
752 // Must use a new theme object to trigger re-render if we have initialized.
753 if (this.inited_) {
754 const newTheme = {...this.term.options.theme};
755 updateTheme(newTheme);
756 this.term.options.theme = newTheme;
757 return;
Jason Lind04bab32022-08-22 14:48:39 +1000758 }
Jason Lin8de3d282022-09-01 21:29:05 +1000759
760 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000761 }
762
763 /**
Jason Linda56aa92022-09-02 13:01:49 +1000764 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
765 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000766 *
767 * @param {string} key
768 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000769 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000770 */
Jason Linda56aa92022-09-02 13:01:49 +1000771 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000772 // TODO: xterm supports updating multiple options at the same time. We
773 // should probably do that.
774 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000775 if (scheduleFit) {
776 this.scheduleFit_();
777 }
Jason Lind04bab32022-08-22 14:48:39 +1000778 }
Jason Linabad7562022-08-22 14:49:05 +1000779
780 /**
781 * Called when there is a "fontloadingdone" event. We need this because
782 * `FontManager.loadFont()` does not guarantee loading all the font files.
783 */
784 async onFontLoadingDone_() {
785 // If there is a pending font, the font is going to be refresh soon, so we
786 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000787 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000788 this.scheduleRefreshFont_();
789 }
790 }
791
Jason Lin5690e752022-08-30 15:36:45 +1000792 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000793 this.copyString_(this.term.getSelection());
794 }
795
796 /** @param {string} data */
797 copyString_(data) {
798 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000799 return;
800 }
Jason Line9231bc2022-09-01 13:54:02 +1000801 navigator.clipboard?.writeText(data);
Jason Lin6a402a72022-08-25 16:07:02 +1000802 if (!this.copyNotice_) {
803 this.copyNotice_ = document.createElement('terminal-copy-notice');
804 }
805 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200);
806 }
807
Jason Linabad7562022-08-22 14:49:05 +1000808 /**
809 * Refresh xterm rendering for a font related event.
810 */
811 refreshFont_() {
812 // We have to set the fontFamily option to a different string to trigger the
813 // re-rendering. Appending a space at the end seems to be the easiest
814 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
815 // us.
816 //
817 // TODO: Report a bug to xterm.js and ask for exposing a public function for
818 // the refresh so that we don't need to do this hack.
819 this.term.options.fontFamily += ' ';
820 }
821
822 /**
823 * Update a font.
824 *
825 * @param {string} cssFontFamily
826 */
827 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000828 this.pendingFont_ = cssFontFamily;
829 await this.fontManager_.loadFont(cssFontFamily);
830 // Sleep a bit to wait for flushing fontloadingdone events. This is not
831 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
832 // to refresh font unnecessarily in some cases.
833 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000834
Jason Lin6a402a72022-08-25 16:07:02 +1000835 if (this.pendingFont_ !== cssFontFamily) {
836 // `updateFont_()` probably is called again. Abort what we are doing.
837 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
838 ` (expecting ${cssFontFamily})`);
839 return;
840 }
Jason Linabad7562022-08-22 14:49:05 +1000841
Jason Lin6a402a72022-08-25 16:07:02 +1000842 if (this.term.options.fontFamily !== cssFontFamily) {
843 this.term.options.fontFamily = cssFontFamily;
844 } else {
845 // If the font is already the same, refresh font just to be safe.
846 this.refreshFont_();
847 }
848 this.pendingFont_ = null;
849 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000850 }
Jason Lin5690e752022-08-30 15:36:45 +1000851
852 /**
853 * @param {!KeyboardEvent} ev
854 * @return {boolean} Return false if xterm.js should not handle the key event.
855 */
856 customKeyEventHandler_(ev) {
857 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
858 (ev.altKey ? Modifier.Alt : 0) |
859 (ev.ctrlKey ? Modifier.Ctrl : 0) |
860 (ev.metaKey ? Modifier.Meta : 0);
861 const handler = this.keyDownHandlers_.get(
862 encodeKeyCombo(modifiers, ev.keyCode));
863 if (handler) {
864 if (ev.type === 'keydown') {
865 handler(ev);
866 }
867 return false;
868 }
869
870 return true;
871 }
872
873 /**
874 * A keydown handler for zoom-related keys.
875 *
876 * @param {!KeyboardEvent} ev
877 */
878 zoomKeyDownHandler_(ev) {
879 ev.preventDefault();
880
881 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
882 // The only one with a control code.
883 if (ev.keyCode === keyCodes.MINUS) {
884 this.io.onVTKeystroke('\x1f');
885 }
886 return;
887 }
888
889 let newFontSize;
890 switch (ev.keyCode) {
891 case keyCodes.ZERO:
892 newFontSize = this.prefs_.get('font-size');
893 break;
894 case keyCodes.MINUS:
895 newFontSize = this.term.options.fontSize - 1;
896 break;
897 default:
898 newFontSize = this.term.options.fontSize + 1;
899 break;
900 }
901
Jason Linda56aa92022-09-02 13:01:49 +1000902 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +1000903 }
904
905 /** @param {!KeyboardEvent} ev */
906 ctrlCKeyDownHandler_(ev) {
907 ev.preventDefault();
908 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
909 this.term.hasSelection()) {
910 this.copySelection_();
911 return;
912 }
913
914 this.io.onVTKeystroke('\x03');
915 }
916
917 /** @param {!KeyboardEvent} ev */
918 ctrlVKeyDownHandler_(ev) {
919 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
920 // Don't do anything and let the browser handles the key.
921 return;
922 }
923
924 ev.preventDefault();
925 this.io.onVTKeystroke('\x16');
926 }
927
928 resetKeyDownHandlers_() {
929 this.keyDownHandlers_.clear();
930
931 /**
932 * Don't do anything and let the browser handles the key.
933 *
934 * @param {!KeyboardEvent} ev
935 */
936 const noop = (ev) => {};
937
938 /**
939 * @param {number} modifiers
940 * @param {number} keyCode
941 * @param {function(!KeyboardEvent)} func
942 */
943 const set = (modifiers, keyCode, func) => {
944 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
945 func);
946 };
947
948 /**
949 * @param {number} modifiers
950 * @param {number} keyCode
951 * @param {function(!KeyboardEvent)} func
952 */
953 const setWithShiftVersion = (modifiers, keyCode, func) => {
954 set(modifiers, keyCode, func);
955 set(modifiers | Modifier.Shift, keyCode, func);
956 };
957
Jason Lin5690e752022-08-30 15:36:45 +1000958 // Ctrl+/
959 set(Modifier.Ctrl, 191, (ev) => {
960 ev.preventDefault();
961 this.io.onVTKeystroke(ctl('_'));
962 });
963
964 // Settings page.
965 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
966 ev.preventDefault();
967 chrome.terminalPrivate.openOptionsPage(() => {});
968 });
969
970 if (this.prefs_.get('keybindings-os-defaults')) {
971 for (const binding of OS_DEFAULT_BINDINGS) {
972 this.keyDownHandlers_.set(binding, noop);
973 }
974 }
975
976 /** @param {!KeyboardEvent} ev */
977 const newWindow = (ev) => {
978 ev.preventDefault();
979 chrome.terminalPrivate.openWindow();
980 };
981 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
982 if (this.prefs_.get('pass-ctrl-n')) {
983 set(Modifier.Ctrl, keyCodes.N, newWindow);
984 }
985
986 if (this.prefs_.get('pass-ctrl-t')) {
987 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
988 }
989
990 if (this.prefs_.get('pass-ctrl-w')) {
991 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
992 }
993
994 if (this.prefs_.get('pass-ctrl-tab')) {
995 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
996 }
997
998 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
999
1000 /**
1001 * Set a handler for the key combo ctrl+<number>.
1002 *
1003 * @param {number} number 1 to 9
1004 * @param {string} controlCode The control code to send if we don't want to
1005 * let the browser to handle it.
1006 */
1007 const setCtrlNumberHandler = (number, controlCode) => {
1008 let func = noop;
1009 if (!passCtrlNumber) {
1010 func = (ev) => {
1011 ev.preventDefault();
1012 this.io.onVTKeystroke(controlCode);
1013 };
1014 }
1015 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1016 };
1017
1018 setCtrlNumberHandler(1, '1');
1019 setCtrlNumberHandler(2, ctl('@'));
1020 setCtrlNumberHandler(3, ctl('['));
1021 setCtrlNumberHandler(4, ctl('\\'));
1022 setCtrlNumberHandler(5, ctl(']'));
1023 setCtrlNumberHandler(6, ctl('^'));
1024 setCtrlNumberHandler(7, ctl('_'));
1025 setCtrlNumberHandler(8, '\x7f');
1026 setCtrlNumberHandler(9, '9');
1027
1028 if (this.prefs_.get('pass-alt-number')) {
1029 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1030 set(Modifier.Alt, keyCode, noop);
1031 }
1032 }
1033
1034 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1035 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1036 }
1037
1038 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1039 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1040 }
Jason Linca61ffb2022-08-03 19:37:12 +10001041}
1042
Jason Lind66e6bf2022-08-22 14:47:10 +10001043class HtermTerminal extends hterm.Terminal {
1044 /** @override */
1045 decorate(div) {
1046 super.decorate(div);
1047
1048 const fontManager = new FontManager(this.getDocument());
1049 fontManager.loadPowerlineCSS().then(() => {
1050 const prefs = this.getPrefs();
1051 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1052 prefs.addObserver(
1053 'font-family',
1054 (v) => fontManager.loadFont(/** @type {string} */(v)));
1055 });
1056 }
Jason Lin2649da22022-10-12 10:16:44 +11001057
1058 /**
1059 * Write data to the terminal.
1060 *
1061 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1062 * UTF-8 data
1063 * @param {function()=} callback Optional callback that fires when the data
1064 * was processed by the parser.
1065 */
1066 write(data, callback) {
1067 if (typeof data === 'string') {
1068 this.io.print(data);
1069 } else {
1070 this.io.writeUTF8(data);
1071 }
1072 // Hterm processes the data synchronously, so we can call the callback
1073 // immediately.
1074 if (callback) {
1075 setTimeout(callback);
1076 }
1077 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001078}
1079
Jason Linca61ffb2022-08-03 19:37:12 +10001080/**
1081 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1082 * preference value.
1083 *
1084 * @param {{
1085 * storage: !lib.Storage,
1086 * profileId: string,
1087 * }} args
1088 * @return {!Promise<!hterm.Terminal>}
1089 */
1090export async function createEmulator({storage, profileId}) {
1091 let config = TERMINAL_EMULATORS.get('hterm');
1092
1093 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001094 // TODO: remove the url param logic. This is temporary to make manual
1095 // testing a bit easier, which is also why this is not in
1096 // './js/terminal_info.js'.
1097 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
1098 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +10001099 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001100 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001101 TERMINAL_EMULATORS.values().next().value;
1102 console.log('Terminal emulator config: ', config);
1103 }
1104
1105 switch (config.lib) {
1106 case 'xterm.js':
1107 {
1108 const terminal = new XtermTerminal({
1109 storage,
1110 profileId,
1111 enableWebGL: config.webgl,
1112 });
Jason Linca61ffb2022-08-03 19:37:12 +10001113 return terminal;
1114 }
1115 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001116 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001117 default:
1118 throw new Error('incorrect emulator config');
1119 }
1120}
1121
Jason Lin6a402a72022-08-25 16:07:02 +10001122class TerminalCopyNotice extends LitElement {
1123 /** @override */
1124 static get styles() {
1125 return css`
1126 :host {
1127 display: block;
1128 text-align: center;
1129 }
1130
1131 svg {
1132 fill: currentColor;
1133 }
1134 `;
1135 }
1136
1137 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001138 connectedCallback() {
1139 super.connectedCallback();
1140 if (!this.childNodes.length) {
1141 // This is not visible since we use shadow dom. But this will allow the
1142 // hterm.NotificationCenter to announce the the copy text.
1143 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1144 }
1145 }
1146
1147 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001148 render() {
1149 return html`
1150 ${ICON_COPY}
1151 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1152 `;
1153 }
1154}
1155
1156customElements.define('terminal-copy-notice', TerminalCopyNotice);