blob: ed7d19a4aec09a76c8786f58905aa8e871fee0c1 [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 Linee0c1f72022-10-18 17:17:26 +1100304const BACKGROUND_IMAGE_KEY = 'background-image';
305
306class BackgroundImageWatcher {
307 /**
308 * @param {!hterm.PreferenceManager} prefs
309 * @param {function(string)} onChange This is called with the background image
310 * (could be empty) whenever it changes.
311 */
312 constructor(prefs, onChange) {
313 this.prefs_ = prefs;
314 this.onChange_ = onChange;
315 }
316
317 /**
318 * Call once to start watching for background image changes.
319 */
320 watch() {
321 window.addEventListener('storage', (e) => {
322 if (e.key === BACKGROUND_IMAGE_KEY) {
323 this.onChange_(this.getBackgroundImage());
324 }
325 });
326 this.prefs_.addObserver(BACKGROUND_IMAGE_KEY, () => {
327 this.onChange_(this.getBackgroundImage());
328 });
329 }
330
331 getBackgroundImage() {
332 const image = window.localStorage.getItem(BACKGROUND_IMAGE_KEY);
333 if (image) {
334 return `url(${image})`;
335 }
336
337 return this.prefs_.getString(BACKGROUND_IMAGE_KEY);
338 }
339}
340
Jason Lin83707c92022-09-20 19:09:41 +1000341/**
Jason Linca61ffb2022-08-03 19:37:12 +1000342 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
343 * so that it can be used in existing code.
344 *
Jason Linca61ffb2022-08-03 19:37:12 +1000345 * @extends {hterm.Terminal}
346 * @unrestricted
347 */
Jason Linabad7562022-08-22 14:49:05 +1000348export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000349 /**
350 * @param {{
351 * storage: !lib.Storage,
352 * profileId: string,
353 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000354 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000355 * }} args
356 */
Jason Linabad7562022-08-22 14:49:05 +1000357 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000358 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
359 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
360 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
361
Jason Lin8de3d282022-09-01 21:29:05 +1000362 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000363 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000364 /** @type {!hterm.PreferenceManager} */
365 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
Jason Linc48f7432022-10-13 17:28:30 +1100366 definePrefs(this.prefs_);
Jason Linca61ffb2022-08-03 19:37:12 +1000367 this.enableWebGL_ = enableWebGL;
368
Jason Lin5690e752022-08-30 15:36:45 +1000369 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linfc8a3722022-09-07 17:49:18 +1000370 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Lin2649da22022-10-12 10:16:44 +1100371 this.xtermInternal_ = testParams?.xtermInternal ||
372 new XtermInternal(this.term);
Jason Linabad7562022-08-22 14:49:05 +1000373 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000374
Jason Linc2504ae2022-09-02 13:03:31 +1000375 /** @type {?Element} */
376 this.container_;
Jason Linc7afb672022-10-11 15:54:17 +1100377 this.bell_ = new Bell();
Jason Linc2504ae2022-09-02 13:03:31 +1000378 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000379 testParams ? 0 : 250);
380
Jason Lin83707c92022-09-20 19:09:41 +1000381 this.term.loadAddon(
382 new WebLinksAddon((e, uri) => lib.f.openWindow(uri, '_blank')));
Jason Lin4de4f382022-09-01 14:10:18 +1000383 this.term.loadAddon(new Unicode11Addon());
384 this.term.unicode.activeVersion = '11';
385
Jason Linabad7562022-08-22 14:49:05 +1000386 this.pendingFont_ = null;
387 this.scheduleRefreshFont_ = delayedScheduler(
388 () => this.refreshFont_(), 100);
389 document.fonts.addEventListener('loadingdone',
390 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000391
392 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000393 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000394
Jason Lin34a45322022-10-12 19:10:52 +1100395 this.term.onResize(({cols, rows}) => {
396 this.io.onTerminalResize(cols, rows);
397 if (this.prefs_.get('enable-resize-status')) {
398 this.showOverlay(`${cols} × ${rows}`);
399 }
400 });
Jason Lin21d854f2022-08-22 14:49:59 +1000401 // We could also use `this.io.sendString()` except for the nassh exit
402 // prompt, which only listens to onVTKeystroke().
403 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000404 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100405 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin83ef5ba2022-10-13 17:40:30 +1100406 this.term.onSelectionChange(() => {
407 if (this.prefs_.get('copy-on-select')) {
408 this.copySelection_();
409 }
410 });
Jason Linc7afb672022-10-11 15:54:17 +1100411 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000412
413 /**
414 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
415 *
416 * If a key combo is in the map:
417 *
418 * - The handler instead of xterm.js will handle the keydown event.
419 * - Keyup and keypress will be ignored by both us and xterm.js.
420 *
421 * We re-generate this map every time a relevant pref value is changed. This
422 * is ok because pref changes are rare.
423 *
424 * @type {!Map<number, function(!KeyboardEvent)>}
425 */
426 this.keyDownHandlers_ = new Map();
427 this.scheduleResetKeyDownHandlers_ =
428 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
429
430 this.term.attachCustomKeyEventHandler(
431 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000432
Jason Lin21d854f2022-08-22 14:49:59 +1000433 this.io = new XtermTerminalIO(this);
434 this.notificationCenter_ = null;
Jason Lind3aacef2022-10-12 19:03:37 +1100435 this.htermA11yReader_ = null;
436 this.a11yButtons_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000437 this.copyNotice_ = null;
Jason Lin446f3d92022-10-13 17:34:21 +1100438 this.scrollOnOutputListener_ = null;
Jason Linee0c1f72022-10-18 17:17:26 +1100439 this.backgroundImageWatcher_ = new BackgroundImageWatcher(this.prefs_,
440 this.setBackgroundImage.bind(this));
441 this.webglAddon_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000442
Jason Lin83707c92022-09-20 19:09:41 +1000443 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000444 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000445 // The webgl cursor layer also paints the character under the cursor with
446 // this `cursorAccent` color. We use a completely transparent color here
447 // to effectively disable that.
448 cursorAccent: 'rgba(0, 0, 0, 0)',
449 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000450 selectionBackground: 'rgba(174, 203, 250, .6)',
451 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000452 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000453 };
454 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000455 }
456
Jason Linc7afb672022-10-11 15:54:17 +1100457 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100458 setWindowTitle(title) {
459 document.title = title;
460 }
461
462 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100463 ringBell() {
464 this.bell_.ring();
465 }
466
Jason Lin2649da22022-10-12 10:16:44 +1100467 /** @override */
468 print(str) {
469 this.xtermInternal_.print(str);
470 }
471
472 /** @override */
473 wipeContents() {
474 this.term.clear();
475 }
476
477 /** @override */
478 newLine() {
479 this.xtermInternal_.newLine();
480 }
481
482 /** @override */
483 cursorLeft(number) {
484 this.xtermInternal_.cursorLeft(number ?? 1);
485 }
486
Jason Lind3aacef2022-10-12 19:03:37 +1100487 /** @override */
488 setAccessibilityEnabled(enabled) {
489 this.a11yButtons_.setEnabled(enabled);
490 this.htermA11yReader_.setAccessibilityEnabled(enabled);
491 this.term.options.screenReaderMode = enabled;
492 }
493
Jason Linee0c1f72022-10-18 17:17:26 +1100494 hasBackgroundImage() {
495 return !!this.container_.style.backgroundImage;
496 }
497
498 /** @override */
499 setBackgroundImage(image) {
500 this.container_.style.backgroundImage = image || '';
501 this.updateBackgroundColor_(this.prefs_.getString('background-color'));
502 }
503
Jason Linca61ffb2022-08-03 19:37:12 +1000504 /**
505 * Install stubs for stuff that we haven't implemented yet so that the code
506 * still runs.
507 */
508 installUnimplementedStubs_() {
509 this.keyboard = {
510 keyMap: {
511 keyDefs: [],
512 },
513 bindings: {
514 clear: () => {},
515 addBinding: () => {},
516 addBindings: () => {},
517 OsDefaults: {},
518 },
519 };
520 this.keyboard.keyMap.keyDefs[78] = {};
521
522 const methodNames = [
Joel Hockeyb89a9782022-10-16 22:00:12 -0700523 'eraseLine',
Joel Hockeyb89a9782022-10-16 22:00:12 -0700524 'setCursorColumn',
Jason Linca61ffb2022-08-03 19:37:12 +1000525 'setCursorPosition',
526 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000527 ];
528
529 for (const name of methodNames) {
530 this[name] = () => console.warn(`${name}() is not implemented`);
531 }
532
533 this.contextMenu = {
534 setItems: () => {
535 console.warn('.contextMenu.setItems() is not implemented');
536 },
537 };
Jason Lin21d854f2022-08-22 14:49:59 +1000538
539 this.vt = {
540 resetParseState: () => {
541 console.warn('.vt.resetParseState() is not implemented');
542 },
543 };
Jason Linca61ffb2022-08-03 19:37:12 +1000544 }
545
Jason Line9231bc2022-09-01 13:54:02 +1000546 installEscapeSequenceHandlers_() {
547 // OSC 52 for copy.
548 this.term.parser.registerOscHandler(52, (args) => {
549 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
550 // parameter is used to select which of the X clipboards to address. Since
551 // we're not integrating with X, we treat them all the same.
552 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
553 if (!parsedArgs) {
554 return true;
555 }
556
557 let data;
558 try {
559 data = window.atob(parsedArgs[1]);
560 } catch (e) {
561 // If the user sent us invalid base64 content, silently ignore it.
562 return true;
563 }
564 const decoder = new TextDecoder();
565 const bytes = lib.codec.stringToCodeUnitArray(data);
566 this.copyString_(decoder.decode(bytes));
567
568 return true;
569 });
Jason Lin2649da22022-10-12 10:16:44 +1100570
571 this.xtermInternal_.installTmuxControlModeHandler(
572 (data) => this.onTmuxControlModeLine(data));
573 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000574 }
575
Jason Linca61ffb2022-08-03 19:37:12 +1000576 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000577 * Write data to the terminal.
578 *
579 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
580 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100581 * @param {function()=} callback Optional callback that fires when the data
582 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000583 */
Jason Lin2649da22022-10-12 10:16:44 +1100584 write(data, callback) {
585 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000586 }
587
588 /**
589 * Like `this.write()` but also write a line break.
590 *
591 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100592 * @param {function()=} callback Optional callback that fires when the data
593 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000594 */
Jason Lin2649da22022-10-12 10:16:44 +1100595 writeln(data, callback) {
596 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000597 }
598
Jason Linca61ffb2022-08-03 19:37:12 +1000599 get screenSize() {
600 return new hterm.Size(this.term.cols, this.term.rows);
601 }
602
603 /**
604 * Don't need to do anything.
605 *
606 * @override
607 */
608 installKeyboard() {}
609
610 /**
611 * @override
612 */
613 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000614 this.container_ = elem;
Jason Linee0c1f72022-10-18 17:17:26 +1100615 elem.style.backgroundSize = '100% 100%';
616
Jason Lin8de3d282022-09-01 21:29:05 +1000617 (async () => {
618 await new Promise((resolve) => this.prefs_.readStorage(resolve));
619 // This will trigger all the observers to set the terminal options before
620 // we call `this.term.open()`.
621 this.prefs_.notifyAll();
622
Jason Linc2504ae2022-09-02 13:03:31 +1000623 const screenPaddingSize = /** @type {number} */(
624 this.prefs_.get('screen-padding-size'));
625 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
626
Jason Linee0c1f72022-10-18 17:17:26 +1100627 this.setBackgroundImage(
628 this.backgroundImageWatcher_.getBackgroundImage());
629 this.backgroundImageWatcher_.watch();
630
Jason Lin8de3d282022-09-01 21:29:05 +1000631 this.inited_ = true;
632 this.term.open(elem);
633
Jason Lin8de3d282022-09-01 21:29:05 +1000634 if (this.enableWebGL_) {
Jason Linee0c1f72022-10-18 17:17:26 +1100635 this.reloadWebglAddon_();
Jason Lin8de3d282022-09-01 21:29:05 +1000636 }
637 this.term.focus();
638 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100639 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
640 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
641 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000642
Emil Mikulic2a194d02022-09-29 14:30:59 +1000643 // Block right-click context menu from popping up.
644 elem.addEventListener('contextmenu', (e) => e.preventDefault());
645
646 // Add a handler for pasting with the mouse.
647 elem.addEventListener('mousedown', async (e) => {
648 if (this.term.modes.mouseTrackingMode !== 'none') {
649 // xterm.js is in mouse mode and will handle the event.
650 return;
651 }
652 const MIDDLE = 1;
653 const RIGHT = 2;
654 if (e.button === MIDDLE || (e.button === RIGHT &&
655 this.prefs_.getBoolean('mouse-right-click-paste'))) {
656 // Paste.
657 if (navigator.clipboard && navigator.clipboard.readText) {
658 const text = await navigator.clipboard.readText();
659 this.term.paste(text);
660 }
661 }
662 });
663
Jason Lin2649da22022-10-12 10:16:44 +1100664 await this.scheduleFit_();
Jason Lind3aacef2022-10-12 19:03:37 +1100665 this.a11yButtons_ = new A11yButtons(this.term, elem);
666
Jason Lin8de3d282022-09-01 21:29:05 +1000667 this.onTerminalReady();
668 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000669 }
670
671 /** @override */
672 showOverlay(msg, timeout = 1500) {
Jason Lin34a45322022-10-12 19:10:52 +1100673 this.notificationCenter_?.show(msg, {timeout});
Jason Lin21d854f2022-08-22 14:49:59 +1000674 }
675
676 /** @override */
677 hideOverlay() {
Jason Lin34a45322022-10-12 19:10:52 +1100678 this.notificationCenter_?.hide();
Jason Linca61ffb2022-08-03 19:37:12 +1000679 }
680
681 /** @override */
682 getPrefs() {
683 return this.prefs_;
684 }
685
686 /** @override */
687 getDocument() {
688 return window.document;
689 }
690
Jason Lin21d854f2022-08-22 14:49:59 +1000691 /** @override */
692 reset() {
693 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000694 }
695
696 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000697 setProfile(profileId, callback = undefined) {
698 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000699 }
700
Jason Lin21d854f2022-08-22 14:49:59 +1000701 /** @override */
702 interpret(string) {
703 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000704 }
705
Jason Lin21d854f2022-08-22 14:49:59 +1000706 /** @override */
707 focus() {
708 this.term.focus();
709 }
Jason Linca61ffb2022-08-03 19:37:12 +1000710
711 /** @override */
712 onOpenOptionsPage() {}
713
714 /** @override */
715 onTerminalReady() {}
716
Jason Lind04bab32022-08-22 14:48:39 +1000717 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000718 // This is for this.notificationCenter_.
719 const setHtermCSSVariable = (name, value) => {
720 document.body.style.setProperty(`--hterm-${name}`, value);
721 };
722
723 const setHtermColorCSSVariable = (name, color) => {
724 const css = lib.notNull(lib.colors.normalizeCSS(color));
725 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
726 setHtermCSSVariable(name, rgb);
727 };
728
729 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000730 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000731 setHtermCSSVariable('font-size', `${v}px`);
732 });
733
Jason Linda56aa92022-09-02 13:01:49 +1000734 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000735 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000736 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100737 this.bell_.playAudio = !!v;
738 },
739 'desktop-notification-bell': (v) => {
740 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000741 },
Jason Lind04bab32022-08-22 14:48:39 +1000742 'background-color': (v) => {
Jason Linee0c1f72022-10-18 17:17:26 +1100743 this.updateBackgroundColor_(v);
Jason Lin21d854f2022-08-22 14:49:59 +1000744 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000745 },
Jason Lind04bab32022-08-22 14:48:39 +1000746 'color-palette-overrides': (v) => {
747 if (!(v instanceof Array)) {
748 // For terminal, we always expect this to be an array.
749 console.warn('unexpected color palette: ', v);
750 return;
751 }
752 const colors = {};
753 for (let i = 0; i < v.length; ++i) {
754 colors[ANSI_COLOR_NAMES[i]] = v[i];
755 }
756 this.updateTheme_(colors);
757 },
Jason Linda56aa92022-09-02 13:01:49 +1000758 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
759 'cursor-color': (v) => this.updateTheme_({cursor: v}),
760 'cursor-shape': (v) => {
761 let shape;
762 if (v === 'BEAM') {
763 shape = 'bar';
764 } else {
765 shape = v.toLowerCase();
766 }
767 this.updateOption_('cursorStyle', shape, false);
768 },
769 'font-family': (v) => this.updateFont_(v),
770 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000771 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000772 setHtermColorCSSVariable('foreground-color', v);
773 },
Jason Linc48f7432022-10-13 17:28:30 +1100774 'line-height': (v) => this.updateOption_('lineHeight', v, true),
Jason Lin446f3d92022-10-13 17:34:21 +1100775 'scroll-on-output': (v) => {
776 if (!v) {
777 this.scrollOnOutputListener_?.dispose();
778 this.scrollOnOutputListener_ = null;
779 return;
780 }
781 if (!this.scrollOnOutputListener_) {
782 this.scrollOnOutputListener_ = this.term.onWriteParsed(
783 () => this.term.scrollToBottom());
784 }
785 },
Jason Lind04bab32022-08-22 14:48:39 +1000786 });
Jason Lin5690e752022-08-30 15:36:45 +1000787
788 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
789 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
790 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
791 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
792 }
Jason Lind04bab32022-08-22 14:48:39 +1000793 }
794
795 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000796 * Fit the terminal to the containing HTML element.
797 */
798 fit_() {
799 if (!this.inited_) {
800 return;
801 }
802
803 const screenPaddingSize = /** @type {number} */(
804 this.prefs_.get('screen-padding-size'));
805
806 const calc = (size, cellSize) => {
807 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
808 };
809
Jason Lin2649da22022-10-12 10:16:44 +1100810 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
811 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
812 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000813 if (cols >= 0 && rows >= 0) {
814 this.term.resize(cols, rows);
815 }
816 }
817
Jason Linee0c1f72022-10-18 17:17:26 +1100818 reloadWebglAddon_() {
819 if (this.webglAddon_) {
820 this.webglAddon_.dispose();
821 }
822 this.webglAddon_ = new WebglAddon();
823 this.term.loadAddon(this.webglAddon_);
824 }
825
826 /**
827 * Update the background color. This will also adjust the transparency based
828 * on whether there is a background image.
829 *
830 * @param {string} color
831 */
832 updateBackgroundColor_(color) {
833 const hasBackgroundImage = this.hasBackgroundImage();
834
835 // We only set allowTransparency when it is necessary becuase 1) xterm.js
836 // documentation states that allowTransparency can affect performance; 2) I
837 // find that the rendering is better with allowTransparency being false.
838 // This could be a bug with xterm.js.
839 if (!!this.term.options.allowTransparency !== hasBackgroundImage) {
840 this.term.options.allowTransparency = hasBackgroundImage;
841 if (this.enableWebGL_ && this.inited_) {
842 // Setting allowTransparency in the middle messes up webgl rendering,
843 // so we need to reload it here.
844 this.reloadWebglAddon_();
845 }
846 }
847
848 if (this.hasBackgroundImage()) {
849 const css = lib.notNull(lib.colors.normalizeCSS(color));
850 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
851 // Note that we still want to set the RGB part correctly even though it is
852 // completely transparent. This is because the background color without
853 // the alpha channel is used in reverse video mode.
854 color = `rgba(${rgb}, 0)`;
855 }
856
857 this.updateTheme_({background: color});
858 }
859
Jason Linc2504ae2022-09-02 13:03:31 +1000860 /**
Jason Lind04bab32022-08-22 14:48:39 +1000861 * @param {!Object} theme
862 */
863 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000864 const updateTheme = (target) => {
865 for (const [key, value] of Object.entries(theme)) {
866 target[key] = lib.colors.normalizeCSS(value);
867 }
868 };
869
870 // Must use a new theme object to trigger re-render if we have initialized.
871 if (this.inited_) {
872 const newTheme = {...this.term.options.theme};
873 updateTheme(newTheme);
874 this.term.options.theme = newTheme;
875 return;
Jason Lind04bab32022-08-22 14:48:39 +1000876 }
Jason Lin8de3d282022-09-01 21:29:05 +1000877
878 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000879 }
880
881 /**
Jason Linda56aa92022-09-02 13:01:49 +1000882 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
883 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000884 *
885 * @param {string} key
886 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000887 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000888 */
Jason Linda56aa92022-09-02 13:01:49 +1000889 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000890 // TODO: xterm supports updating multiple options at the same time. We
891 // should probably do that.
892 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000893 if (scheduleFit) {
894 this.scheduleFit_();
895 }
Jason Lind04bab32022-08-22 14:48:39 +1000896 }
Jason Linabad7562022-08-22 14:49:05 +1000897
898 /**
899 * Called when there is a "fontloadingdone" event. We need this because
900 * `FontManager.loadFont()` does not guarantee loading all the font files.
901 */
902 async onFontLoadingDone_() {
903 // If there is a pending font, the font is going to be refresh soon, so we
904 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000905 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000906 this.scheduleRefreshFont_();
907 }
908 }
909
Jason Lin5690e752022-08-30 15:36:45 +1000910 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000911 this.copyString_(this.term.getSelection());
912 }
913
914 /** @param {string} data */
915 copyString_(data) {
916 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000917 return;
918 }
Jason Line9231bc2022-09-01 13:54:02 +1000919 navigator.clipboard?.writeText(data);
Jason Lin83ef5ba2022-10-13 17:40:30 +1100920
921 if (this.prefs_.get('enable-clipboard-notice')) {
922 if (!this.copyNotice_) {
923 this.copyNotice_ = document.createElement('terminal-copy-notice');
924 }
925 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500),
926 200);
Jason Lin6a402a72022-08-25 16:07:02 +1000927 }
Jason Lin6a402a72022-08-25 16:07:02 +1000928 }
929
Jason Linabad7562022-08-22 14:49:05 +1000930 /**
931 * Refresh xterm rendering for a font related event.
932 */
933 refreshFont_() {
934 // We have to set the fontFamily option to a different string to trigger the
935 // re-rendering. Appending a space at the end seems to be the easiest
936 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
937 // us.
938 //
939 // TODO: Report a bug to xterm.js and ask for exposing a public function for
940 // the refresh so that we don't need to do this hack.
941 this.term.options.fontFamily += ' ';
942 }
943
944 /**
945 * Update a font.
946 *
947 * @param {string} cssFontFamily
948 */
949 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000950 this.pendingFont_ = cssFontFamily;
951 await this.fontManager_.loadFont(cssFontFamily);
952 // Sleep a bit to wait for flushing fontloadingdone events. This is not
953 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
954 // to refresh font unnecessarily in some cases.
955 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000956
Jason Lin6a402a72022-08-25 16:07:02 +1000957 if (this.pendingFont_ !== cssFontFamily) {
958 // `updateFont_()` probably is called again. Abort what we are doing.
959 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
960 ` (expecting ${cssFontFamily})`);
961 return;
962 }
Jason Linabad7562022-08-22 14:49:05 +1000963
Jason Lin6a402a72022-08-25 16:07:02 +1000964 if (this.term.options.fontFamily !== cssFontFamily) {
965 this.term.options.fontFamily = cssFontFamily;
966 } else {
967 // If the font is already the same, refresh font just to be safe.
968 this.refreshFont_();
969 }
970 this.pendingFont_ = null;
971 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000972 }
Jason Lin5690e752022-08-30 15:36:45 +1000973
974 /**
975 * @param {!KeyboardEvent} ev
976 * @return {boolean} Return false if xterm.js should not handle the key event.
977 */
978 customKeyEventHandler_(ev) {
979 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
980 (ev.altKey ? Modifier.Alt : 0) |
981 (ev.ctrlKey ? Modifier.Ctrl : 0) |
982 (ev.metaKey ? Modifier.Meta : 0);
983 const handler = this.keyDownHandlers_.get(
984 encodeKeyCombo(modifiers, ev.keyCode));
985 if (handler) {
986 if (ev.type === 'keydown') {
987 handler(ev);
988 }
989 return false;
990 }
991
992 return true;
993 }
994
995 /**
996 * A keydown handler for zoom-related keys.
997 *
998 * @param {!KeyboardEvent} ev
999 */
1000 zoomKeyDownHandler_(ev) {
1001 ev.preventDefault();
1002
1003 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
1004 // The only one with a control code.
1005 if (ev.keyCode === keyCodes.MINUS) {
1006 this.io.onVTKeystroke('\x1f');
1007 }
1008 return;
1009 }
1010
1011 let newFontSize;
1012 switch (ev.keyCode) {
1013 case keyCodes.ZERO:
1014 newFontSize = this.prefs_.get('font-size');
1015 break;
1016 case keyCodes.MINUS:
1017 newFontSize = this.term.options.fontSize - 1;
1018 break;
1019 default:
1020 newFontSize = this.term.options.fontSize + 1;
1021 break;
1022 }
1023
Jason Linda56aa92022-09-02 13:01:49 +10001024 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +10001025 }
1026
1027 /** @param {!KeyboardEvent} ev */
1028 ctrlCKeyDownHandler_(ev) {
1029 ev.preventDefault();
1030 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
1031 this.term.hasSelection()) {
1032 this.copySelection_();
1033 return;
1034 }
1035
1036 this.io.onVTKeystroke('\x03');
1037 }
1038
1039 /** @param {!KeyboardEvent} ev */
1040 ctrlVKeyDownHandler_(ev) {
1041 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
1042 // Don't do anything and let the browser handles the key.
1043 return;
1044 }
1045
1046 ev.preventDefault();
1047 this.io.onVTKeystroke('\x16');
1048 }
1049
1050 resetKeyDownHandlers_() {
1051 this.keyDownHandlers_.clear();
1052
1053 /**
1054 * Don't do anything and let the browser handles the key.
1055 *
1056 * @param {!KeyboardEvent} ev
1057 */
1058 const noop = (ev) => {};
1059
1060 /**
1061 * @param {number} modifiers
1062 * @param {number} keyCode
1063 * @param {function(!KeyboardEvent)} func
1064 */
1065 const set = (modifiers, keyCode, func) => {
1066 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
1067 func);
1068 };
1069
1070 /**
1071 * @param {number} modifiers
1072 * @param {number} keyCode
1073 * @param {function(!KeyboardEvent)} func
1074 */
1075 const setWithShiftVersion = (modifiers, keyCode, func) => {
1076 set(modifiers, keyCode, func);
1077 set(modifiers | Modifier.Shift, keyCode, func);
1078 };
1079
Jason Lin5690e752022-08-30 15:36:45 +10001080 // Ctrl+/
1081 set(Modifier.Ctrl, 191, (ev) => {
1082 ev.preventDefault();
1083 this.io.onVTKeystroke(ctl('_'));
1084 });
1085
1086 // Settings page.
1087 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
1088 ev.preventDefault();
1089 chrome.terminalPrivate.openOptionsPage(() => {});
1090 });
1091
1092 if (this.prefs_.get('keybindings-os-defaults')) {
1093 for (const binding of OS_DEFAULT_BINDINGS) {
1094 this.keyDownHandlers_.set(binding, noop);
1095 }
1096 }
1097
1098 /** @param {!KeyboardEvent} ev */
1099 const newWindow = (ev) => {
1100 ev.preventDefault();
1101 chrome.terminalPrivate.openWindow();
1102 };
1103 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
1104 if (this.prefs_.get('pass-ctrl-n')) {
1105 set(Modifier.Ctrl, keyCodes.N, newWindow);
1106 }
1107
1108 if (this.prefs_.get('pass-ctrl-t')) {
1109 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
1110 }
1111
1112 if (this.prefs_.get('pass-ctrl-w')) {
1113 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
1114 }
1115
1116 if (this.prefs_.get('pass-ctrl-tab')) {
1117 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
1118 }
1119
1120 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
1121
1122 /**
1123 * Set a handler for the key combo ctrl+<number>.
1124 *
1125 * @param {number} number 1 to 9
1126 * @param {string} controlCode The control code to send if we don't want to
1127 * let the browser to handle it.
1128 */
1129 const setCtrlNumberHandler = (number, controlCode) => {
1130 let func = noop;
1131 if (!passCtrlNumber) {
1132 func = (ev) => {
1133 ev.preventDefault();
1134 this.io.onVTKeystroke(controlCode);
1135 };
1136 }
1137 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1138 };
1139
1140 setCtrlNumberHandler(1, '1');
1141 setCtrlNumberHandler(2, ctl('@'));
1142 setCtrlNumberHandler(3, ctl('['));
1143 setCtrlNumberHandler(4, ctl('\\'));
1144 setCtrlNumberHandler(5, ctl(']'));
1145 setCtrlNumberHandler(6, ctl('^'));
1146 setCtrlNumberHandler(7, ctl('_'));
1147 setCtrlNumberHandler(8, '\x7f');
1148 setCtrlNumberHandler(9, '9');
1149
1150 if (this.prefs_.get('pass-alt-number')) {
1151 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1152 set(Modifier.Alt, keyCode, noop);
1153 }
1154 }
1155
1156 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1157 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1158 }
1159
1160 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1161 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1162 }
Jason Linee0c1f72022-10-18 17:17:26 +11001163
1164 handleOnTerminalReady() {}
Jason Linca61ffb2022-08-03 19:37:12 +10001165}
1166
Jason Lind66e6bf2022-08-22 14:47:10 +10001167class HtermTerminal extends hterm.Terminal {
1168 /** @override */
1169 decorate(div) {
1170 super.decorate(div);
1171
Jason Linc48f7432022-10-13 17:28:30 +11001172 definePrefs(this.getPrefs());
Jason Linee0c1f72022-10-18 17:17:26 +11001173 }
Jason Linc48f7432022-10-13 17:28:30 +11001174
Jason Linee0c1f72022-10-18 17:17:26 +11001175 /**
1176 * This needs to be called in the `onTerminalReady()` callback. This is
1177 * awkward, but it is temporary since we will drop support for hterm at some
1178 * point.
1179 */
1180 handleOnTerminalReady() {
Jason Lind66e6bf2022-08-22 14:47:10 +10001181 const fontManager = new FontManager(this.getDocument());
1182 fontManager.loadPowerlineCSS().then(() => {
1183 const prefs = this.getPrefs();
1184 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1185 prefs.addObserver(
1186 'font-family',
1187 (v) => fontManager.loadFont(/** @type {string} */(v)));
1188 });
Jason Linee0c1f72022-10-18 17:17:26 +11001189
1190 const backgroundImageWatcher = new BackgroundImageWatcher(this.getPrefs(),
1191 (image) => this.setBackgroundImage(image));
1192 this.setBackgroundImage(backgroundImageWatcher.getBackgroundImage());
1193 backgroundImageWatcher.watch();
Jason Lind66e6bf2022-08-22 14:47:10 +10001194 }
Jason Lin2649da22022-10-12 10:16:44 +11001195
1196 /**
1197 * Write data to the terminal.
1198 *
1199 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1200 * UTF-8 data
1201 * @param {function()=} callback Optional callback that fires when the data
1202 * was processed by the parser.
1203 */
1204 write(data, callback) {
1205 if (typeof data === 'string') {
1206 this.io.print(data);
1207 } else {
1208 this.io.writeUTF8(data);
1209 }
1210 // Hterm processes the data synchronously, so we can call the callback
1211 // immediately.
1212 if (callback) {
1213 setTimeout(callback);
1214 }
1215 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001216}
1217
Jason Linca61ffb2022-08-03 19:37:12 +10001218/**
1219 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1220 * preference value.
1221 *
1222 * @param {{
1223 * storage: !lib.Storage,
1224 * profileId: string,
1225 * }} args
1226 * @return {!Promise<!hterm.Terminal>}
1227 */
1228export async function createEmulator({storage, profileId}) {
1229 let config = TERMINAL_EMULATORS.get('hterm');
1230
1231 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001232 // TODO: remove the url param logic. This is temporary to make manual
1233 // testing a bit easier, which is also why this is not in
1234 // './js/terminal_info.js'.
1235 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
1236 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +10001237 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001238 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001239 TERMINAL_EMULATORS.values().next().value;
1240 console.log('Terminal emulator config: ', config);
1241 }
1242
1243 switch (config.lib) {
1244 case 'xterm.js':
1245 {
1246 const terminal = new XtermTerminal({
1247 storage,
1248 profileId,
1249 enableWebGL: config.webgl,
1250 });
Jason Linca61ffb2022-08-03 19:37:12 +10001251 return terminal;
1252 }
1253 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001254 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001255 default:
1256 throw new Error('incorrect emulator config');
1257 }
1258}
1259
Jason Lin6a402a72022-08-25 16:07:02 +10001260class TerminalCopyNotice extends LitElement {
1261 /** @override */
1262 static get styles() {
1263 return css`
1264 :host {
1265 display: block;
1266 text-align: center;
1267 }
1268
1269 svg {
1270 fill: currentColor;
1271 }
1272 `;
1273 }
1274
1275 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001276 connectedCallback() {
1277 super.connectedCallback();
1278 if (!this.childNodes.length) {
1279 // This is not visible since we use shadow dom. But this will allow the
1280 // hterm.NotificationCenter to announce the the copy text.
1281 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1282 }
1283 }
1284
1285 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001286 render() {
1287 return html`
1288 ${ICON_COPY}
1289 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1290 `;
1291 }
1292}
1293
1294customElements.define('terminal-copy-notice', TerminalCopyNotice);