blob: a7875f157dd9a7dfb745a38909c44d49a928e0d9 [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
Mike Frysinger75895da2022-10-04 00:42:28 +054514import {hterm, lib} from './deps_local.concat.js';
15
Jason Lin6a402a72022-08-25 16:07:02 +100016import {LitElement, css, html} from './lit.js';
Jason Linc48f7432022-10-13 17:28:30 +110017import {FontManager, ORIGINAL_URL, TERMINAL_EMULATORS, definePrefs,
18 delayedScheduler, fontManager, getOSInfo, sleep} from './terminal_common.js';
Jason Lin6a402a72022-08-25 16:07:02 +100019import {ICON_COPY} from './terminal_icons.js';
Jason Lin83707c92022-09-20 19:09:41 +100020import {TerminalTooltip} from './terminal_tooltip.js';
Jason Linc2504ae2022-09-02 13:03:31 +100021import {Terminal, Unicode11Addon, WebLinksAddon, WebglAddon}
Jason Lin4de4f382022-09-01 14:10:18 +100022 from './xterm.js';
Jason Lin2649da22022-10-12 10:16:44 +110023import {XtermInternal} from './terminal_xterm_internal.js';
Jason Linca61ffb2022-08-03 19:37:12 +100024
Jason Lin5690e752022-08-30 15:36:45 +100025
26/** @enum {number} */
27export const Modifier = {
28 Shift: 1 << 0,
29 Alt: 1 << 1,
30 Ctrl: 1 << 2,
31 Meta: 1 << 3,
32};
33
34// This is just a static map from key names to key codes. It helps make the code
35// a bit more readable.
36const keyCodes = hterm.Parser.identifiers.keyCodes;
37
38/**
39 * Encode a key combo (i.e. modifiers + a normal key) to an unique number.
40 *
41 * @param {number} modifiers
42 * @param {number} keyCode
43 * @return {number}
44 */
45export function encodeKeyCombo(modifiers, keyCode) {
46 return keyCode << 4 | modifiers;
47}
48
49const OS_DEFAULT_BINDINGS = [
50 // Submit feedback.
51 encodeKeyCombo(Modifier.Alt | Modifier.Shift, keyCodes.I),
52 // Toggle chromevox.
53 encodeKeyCombo(Modifier.Ctrl | Modifier.Alt, keyCodes.Z),
54 // Switch input method.
55 encodeKeyCombo(Modifier.Ctrl, keyCodes.SPACE),
56
57 // Dock window left/right.
58 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_LEFT),
59 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_RIGHT),
60
61 // Maximize/minimize window.
62 encodeKeyCombo(Modifier.Alt, keyCodes.EQUAL),
63 encodeKeyCombo(Modifier.Alt, keyCodes.MINUS),
64];
65
66
Jason Linca61ffb2022-08-03 19:37:12 +100067const ANSI_COLOR_NAMES = [
68 'black',
69 'red',
70 'green',
71 'yellow',
72 'blue',
73 'magenta',
74 'cyan',
75 'white',
76 'brightBlack',
77 'brightRed',
78 'brightGreen',
79 'brightYellow',
80 'brightBlue',
81 'brightMagenta',
82 'brightCyan',
83 'brightWhite',
84];
85
Jason Linca61ffb2022-08-03 19:37:12 +100086/**
Jason Linabad7562022-08-22 14:49:05 +100087 * @typedef {{
88 * term: !Terminal,
89 * fontManager: !FontManager,
Jason Lin2649da22022-10-12 10:16:44 +110090 * xtermInternal: !XtermInternal,
Jason Linabad7562022-08-22 14:49:05 +100091 * }}
92 */
93export let XtermTerminalTestParams;
94
95/**
Jason Lin5690e752022-08-30 15:36:45 +100096 * Compute a control character for a given character.
97 *
98 * @param {string} ch
99 * @return {string}
100 */
101function ctl(ch) {
102 return String.fromCharCode(ch.charCodeAt(0) - 64);
103}
104
105/**
Jason Lin21d854f2022-08-22 14:49:59 +1000106 * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO
107 * because it always convert utf8 data to strings, which is not necessary for
108 * xterm.
109 */
110class XtermTerminalIO extends hterm.Terminal.IO {
111 /** @override */
112 writeUTF8(buffer) {
113 this.terminal_.write(new Uint8Array(buffer));
114 }
115
116 /** @override */
117 writelnUTF8(buffer) {
118 this.terminal_.writeln(new Uint8Array(buffer));
119 }
120
121 /** @override */
122 print(string) {
123 this.terminal_.write(string);
124 }
125
126 /** @override */
127 writeUTF16(string) {
128 this.print(string);
129 }
130
131 /** @override */
132 println(string) {
133 this.terminal_.writeln(string);
134 }
135
136 /** @override */
137 writelnUTF16(string) {
138 this.println(string);
139 }
140}
141
142/**
Jason Lin83707c92022-09-20 19:09:41 +1000143 * A custom link handler that:
144 *
145 * - Shows a tooltip with the url on a OSC 8 link. This is following what hterm
146 * is doing. Also, showing the tooltip is better for the security of the user
147 * because the link can have arbitrary text.
148 * - Uses our own way to open the window.
149 */
150class LinkHandler {
151 /**
152 * @param {!Terminal} term
153 */
154 constructor(term) {
155 this.term_ = term;
156 /** @type {?TerminalTooltip} */
157 this.tooltip_ = null;
158 }
159
160 /**
161 * @return {!TerminalTooltip}
162 */
163 getTooltip_() {
164 if (!this.tooltip_) {
165 this.tooltip_ = /** @type {!TerminalTooltip} */(
166 document.createElement('terminal-tooltip'));
167 this.tooltip_.classList.add('xterm-hover');
168 lib.notNull(this.term_.element).appendChild(this.tooltip_);
169 }
170 return this.tooltip_;
171 }
172
173 /**
174 * @param {!MouseEvent} ev
175 * @param {string} url
176 * @param {!Object} range
177 */
178 activate(ev, url, range) {
179 lib.f.openWindow(url, '_blank');
180 }
181
182 /**
183 * @param {!MouseEvent} ev
184 * @param {string} url
185 * @param {!Object} range
186 */
187 hover(ev, url, range) {
188 this.getTooltip_().show(url, {x: ev.clientX, y: ev.clientY});
189 }
190
191 /**
192 * @param {!MouseEvent} ev
193 * @param {string} url
194 * @param {!Object} range
195 */
196 leave(ev, url, range) {
197 this.getTooltip_().hide();
198 }
199}
200
Jason Linc7afb672022-10-11 15:54:17 +1100201class Bell {
202 constructor() {
203 this.showNotification = false;
204
205 /** @type {?Audio} */
206 this.audio_ = null;
207 /** @type {?Notification} */
208 this.notification_ = null;
209 this.coolDownUntil_ = 0;
210 }
211
212 /**
213 * Set whether a bell audio should be played.
214 *
215 * @param {boolean} value
216 */
217 set playAudio(value) {
218 this.audio_ = value ?
219 new Audio(lib.resource.getDataUrl('hterm/audio/bell')) : null;
220 }
221
222 ring() {
223 const now = Date.now();
224 if (now < this.coolDownUntil_) {
225 return;
226 }
227 this.coolDownUntil_ = now + 500;
228
229 this.audio_?.play();
230 if (this.showNotification && !document.hasFocus() && !this.notification_) {
231 this.notification_ = new Notification(
232 `\u266A ${document.title} \u266A`,
233 {icon: lib.resource.getDataUrl('hterm/images/icon-96')});
234 // Close the notification after a timeout. Note that this is different
235 // from hterm's behavior, but I think it makes more sense to do so.
236 setTimeout(() => {
237 this.notification_.close();
238 this.notification_ = null;
239 }, 5000);
240 }
241 }
242}
243
Jason Lind3aacef2022-10-12 19:03:37 +1100244const A11Y_BUTTON_STYLE = `
245position: fixed;
246z-index: 10;
247right: 16px;
248`;
249
250class A11yButtons {
251 /**
252 * @param {!Terminal} term
253 * @param {!Element} elem The container element for the terminal.
254 */
255 constructor(term, elem) {
256 this.pageUpButton_ = document.createElement('button');
257 this.pageUpButton_.style.cssText = A11Y_BUTTON_STYLE;
258 this.pageUpButton_.textContent =
259 hterm.messageManager.get('HTERM_BUTTON_PAGE_UP');
260 this.pageUpButton_.addEventListener('click',
261 () => term.scrollPages(-1));
262
263 this.pageDownButton_ = document.createElement('button');
264 this.pageDownButton_.style.cssText = A11Y_BUTTON_STYLE;
265 this.pageDownButton_.textContent =
266 hterm.messageManager.get('HTERM_BUTTON_PAGE_DOWN');
267 this.pageDownButton_.addEventListener('click',
268 () => term.scrollPages(1));
269
270 this.resetPos_();
271 elem.prepend(this.pageUpButton_);
272 elem.append(this.pageDownButton_);
273
274 this.onSelectionChange_ = this.onSelectionChange_.bind(this);
275 }
276
277 /**
278 * @param {boolean} enabled
279 */
280 setEnabled(enabled) {
281 if (enabled) {
282 document.addEventListener('selectionchange', this.onSelectionChange_);
283 } else {
284 this.resetPos_();
285 document.removeEventListener('selectionchange', this.onSelectionChange_);
286 }
287 }
288
289 resetPos_() {
290 this.pageUpButton_.style.top = '-200px';
291 this.pageDownButton_.style.bottom = '-200px';
292 }
293
294 onSelectionChange_() {
295 this.resetPos_();
296
297 const selectedElement = document.getSelection().anchorNode.parentElement;
298 if (selectedElement === this.pageUpButton_) {
299 this.pageUpButton_.style.top = '16px';
300 } else if (selectedElement === this.pageDownButton_) {
301 this.pageDownButton_.style.bottom = '16px';
302 }
303 }
304}
305
Jason Linee0c1f72022-10-18 17:17:26 +1100306const BACKGROUND_IMAGE_KEY = 'background-image';
307
308class BackgroundImageWatcher {
309 /**
310 * @param {!hterm.PreferenceManager} prefs
311 * @param {function(string)} onChange This is called with the background image
312 * (could be empty) whenever it changes.
313 */
314 constructor(prefs, onChange) {
315 this.prefs_ = prefs;
316 this.onChange_ = onChange;
317 }
318
319 /**
320 * Call once to start watching for background image changes.
321 */
322 watch() {
323 window.addEventListener('storage', (e) => {
324 if (e.key === BACKGROUND_IMAGE_KEY) {
325 this.onChange_(this.getBackgroundImage());
326 }
327 });
328 this.prefs_.addObserver(BACKGROUND_IMAGE_KEY, () => {
329 this.onChange_(this.getBackgroundImage());
330 });
331 }
332
333 getBackgroundImage() {
334 const image = window.localStorage.getItem(BACKGROUND_IMAGE_KEY);
335 if (image) {
336 return `url(${image})`;
337 }
338
339 return this.prefs_.getString(BACKGROUND_IMAGE_KEY);
340 }
341}
342
Jason Lin83707c92022-09-20 19:09:41 +1000343/**
Jason Linca61ffb2022-08-03 19:37:12 +1000344 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
345 * so that it can be used in existing code.
346 *
Jason Linca61ffb2022-08-03 19:37:12 +1000347 * @extends {hterm.Terminal}
348 * @unrestricted
349 */
Jason Linabad7562022-08-22 14:49:05 +1000350export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000351 /**
352 * @param {{
353 * storage: !lib.Storage,
354 * profileId: string,
355 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000356 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000357 * }} args
358 */
Jason Linabad7562022-08-22 14:49:05 +1000359 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000360 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
361 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
362 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
363
Jason Lin8de3d282022-09-01 21:29:05 +1000364 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000365 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000366 /** @type {!hterm.PreferenceManager} */
367 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
Jason Linc48f7432022-10-13 17:28:30 +1100368 definePrefs(this.prefs_);
Jason Linca61ffb2022-08-03 19:37:12 +1000369 this.enableWebGL_ = enableWebGL;
370
Jason Lin5690e752022-08-30 15:36:45 +1000371 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linfc8a3722022-09-07 17:49:18 +1000372 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Lin2649da22022-10-12 10:16:44 +1100373 this.xtermInternal_ = testParams?.xtermInternal ||
374 new XtermInternal(this.term);
Jason Linabad7562022-08-22 14:49:05 +1000375 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000376
Jason Linc2504ae2022-09-02 13:03:31 +1000377 /** @type {?Element} */
378 this.container_;
Jason Linc7afb672022-10-11 15:54:17 +1100379 this.bell_ = new Bell();
Jason Linc2504ae2022-09-02 13:03:31 +1000380 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000381 testParams ? 0 : 250);
382
Jason Lin83707c92022-09-20 19:09:41 +1000383 this.term.loadAddon(
384 new WebLinksAddon((e, uri) => lib.f.openWindow(uri, '_blank')));
Jason Lin4de4f382022-09-01 14:10:18 +1000385 this.term.loadAddon(new Unicode11Addon());
386 this.term.unicode.activeVersion = '11';
387
Jason Linabad7562022-08-22 14:49:05 +1000388 this.pendingFont_ = null;
389 this.scheduleRefreshFont_ = delayedScheduler(
390 () => this.refreshFont_(), 100);
391 document.fonts.addEventListener('loadingdone',
392 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000393
394 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000395 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000396
Jason Lin34a45322022-10-12 19:10:52 +1100397 this.term.onResize(({cols, rows}) => {
398 this.io.onTerminalResize(cols, rows);
399 if (this.prefs_.get('enable-resize-status')) {
400 this.showOverlay(`${cols} × ${rows}`);
401 }
402 });
Jason Lin21d854f2022-08-22 14:49:59 +1000403 // We could also use `this.io.sendString()` except for the nassh exit
404 // prompt, which only listens to onVTKeystroke().
405 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000406 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100407 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin83ef5ba2022-10-13 17:40:30 +1100408 this.term.onSelectionChange(() => {
409 if (this.prefs_.get('copy-on-select')) {
410 this.copySelection_();
411 }
412 });
Jason Linc7afb672022-10-11 15:54:17 +1100413 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000414
415 /**
416 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
417 *
418 * If a key combo is in the map:
419 *
420 * - The handler instead of xterm.js will handle the keydown event.
421 * - Keyup and keypress will be ignored by both us and xterm.js.
422 *
423 * We re-generate this map every time a relevant pref value is changed. This
424 * is ok because pref changes are rare.
425 *
426 * @type {!Map<number, function(!KeyboardEvent)>}
427 */
428 this.keyDownHandlers_ = new Map();
429 this.scheduleResetKeyDownHandlers_ =
430 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
431
432 this.term.attachCustomKeyEventHandler(
433 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000434
Jason Lin21d854f2022-08-22 14:49:59 +1000435 this.io = new XtermTerminalIO(this);
436 this.notificationCenter_ = null;
Jason Lind3aacef2022-10-12 19:03:37 +1100437 this.htermA11yReader_ = null;
438 this.a11yButtons_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000439 this.copyNotice_ = null;
Jason Lin446f3d92022-10-13 17:34:21 +1100440 this.scrollOnOutputListener_ = null;
Jason Linee0c1f72022-10-18 17:17:26 +1100441 this.backgroundImageWatcher_ = new BackgroundImageWatcher(this.prefs_,
442 this.setBackgroundImage.bind(this));
443 this.webglAddon_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000444
Jason Lin83707c92022-09-20 19:09:41 +1000445 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000446 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000447 // The webgl cursor layer also paints the character under the cursor with
448 // this `cursorAccent` color. We use a completely transparent color here
449 // to effectively disable that.
450 cursorAccent: 'rgba(0, 0, 0, 0)',
451 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000452 selectionBackground: 'rgba(174, 203, 250, .6)',
453 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000454 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000455 };
456 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000457 }
458
Jason Linc7afb672022-10-11 15:54:17 +1100459 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100460 setWindowTitle(title) {
461 document.title = title;
462 }
463
464 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100465 ringBell() {
466 this.bell_.ring();
467 }
468
Jason Lin2649da22022-10-12 10:16:44 +1100469 /** @override */
470 print(str) {
471 this.xtermInternal_.print(str);
472 }
473
474 /** @override */
475 wipeContents() {
476 this.term.clear();
477 }
478
479 /** @override */
480 newLine() {
481 this.xtermInternal_.newLine();
482 }
483
484 /** @override */
485 cursorLeft(number) {
486 this.xtermInternal_.cursorLeft(number ?? 1);
487 }
488
Jason Lind3aacef2022-10-12 19:03:37 +1100489 /** @override */
490 setAccessibilityEnabled(enabled) {
491 this.a11yButtons_.setEnabled(enabled);
492 this.htermA11yReader_.setAccessibilityEnabled(enabled);
493 this.term.options.screenReaderMode = enabled;
494 }
495
Jason Linee0c1f72022-10-18 17:17:26 +1100496 hasBackgroundImage() {
497 return !!this.container_.style.backgroundImage;
498 }
499
500 /** @override */
501 setBackgroundImage(image) {
502 this.container_.style.backgroundImage = image || '';
503 this.updateBackgroundColor_(this.prefs_.getString('background-color'));
504 }
505
Jason Linca61ffb2022-08-03 19:37:12 +1000506 /**
507 * Install stubs for stuff that we haven't implemented yet so that the code
508 * still runs.
509 */
510 installUnimplementedStubs_() {
511 this.keyboard = {
512 keyMap: {
513 keyDefs: [],
514 },
515 bindings: {
516 clear: () => {},
517 addBinding: () => {},
518 addBindings: () => {},
519 OsDefaults: {},
520 },
521 };
522 this.keyboard.keyMap.keyDefs[78] = {};
523
524 const methodNames = [
Joel Hockeyb89a9782022-10-16 22:00:12 -0700525 'eraseLine',
Joel Hockeyb89a9782022-10-16 22:00:12 -0700526 'setCursorColumn',
Jason Linca61ffb2022-08-03 19:37:12 +1000527 'setCursorPosition',
528 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000529 ];
530
531 for (const name of methodNames) {
532 this[name] = () => console.warn(`${name}() is not implemented`);
533 }
534
535 this.contextMenu = {
536 setItems: () => {
537 console.warn('.contextMenu.setItems() is not implemented');
538 },
539 };
Jason Lin21d854f2022-08-22 14:49:59 +1000540
541 this.vt = {
542 resetParseState: () => {
543 console.warn('.vt.resetParseState() is not implemented');
544 },
545 };
Jason Linca61ffb2022-08-03 19:37:12 +1000546 }
547
Jason Line9231bc2022-09-01 13:54:02 +1000548 installEscapeSequenceHandlers_() {
549 // OSC 52 for copy.
550 this.term.parser.registerOscHandler(52, (args) => {
551 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
552 // parameter is used to select which of the X clipboards to address. Since
553 // we're not integrating with X, we treat them all the same.
554 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
555 if (!parsedArgs) {
556 return true;
557 }
558
559 let data;
560 try {
561 data = window.atob(parsedArgs[1]);
562 } catch (e) {
563 // If the user sent us invalid base64 content, silently ignore it.
564 return true;
565 }
566 const decoder = new TextDecoder();
567 const bytes = lib.codec.stringToCodeUnitArray(data);
568 this.copyString_(decoder.decode(bytes));
569
570 return true;
571 });
Jason Lin2649da22022-10-12 10:16:44 +1100572
573 this.xtermInternal_.installTmuxControlModeHandler(
574 (data) => this.onTmuxControlModeLine(data));
575 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000576 }
577
Jason Linca61ffb2022-08-03 19:37:12 +1000578 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000579 * Write data to the terminal.
580 *
581 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
582 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100583 * @param {function()=} callback Optional callback that fires when the data
584 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000585 */
Jason Lin2649da22022-10-12 10:16:44 +1100586 write(data, callback) {
587 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000588 }
589
590 /**
591 * Like `this.write()` but also write a line break.
592 *
593 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100594 * @param {function()=} callback Optional callback that fires when the data
595 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000596 */
Jason Lin2649da22022-10-12 10:16:44 +1100597 writeln(data, callback) {
598 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000599 }
600
Jason Linca61ffb2022-08-03 19:37:12 +1000601 get screenSize() {
602 return new hterm.Size(this.term.cols, this.term.rows);
603 }
604
605 /**
606 * Don't need to do anything.
607 *
608 * @override
609 */
610 installKeyboard() {}
611
612 /**
613 * @override
614 */
615 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000616 this.container_ = elem;
Jason Linee0c1f72022-10-18 17:17:26 +1100617 elem.style.backgroundSize = '100% 100%';
618
Jason Lin8de3d282022-09-01 21:29:05 +1000619 (async () => {
620 await new Promise((resolve) => this.prefs_.readStorage(resolve));
621 // This will trigger all the observers to set the terminal options before
622 // we call `this.term.open()`.
623 this.prefs_.notifyAll();
624
Jason Linc2504ae2022-09-02 13:03:31 +1000625 const screenPaddingSize = /** @type {number} */(
626 this.prefs_.get('screen-padding-size'));
627 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
628
Jason Linee0c1f72022-10-18 17:17:26 +1100629 this.setBackgroundImage(
630 this.backgroundImageWatcher_.getBackgroundImage());
631 this.backgroundImageWatcher_.watch();
632
Jason Lin8de3d282022-09-01 21:29:05 +1000633 this.inited_ = true;
634 this.term.open(elem);
635
Jason Lin8de3d282022-09-01 21:29:05 +1000636 if (this.enableWebGL_) {
Jason Linee0c1f72022-10-18 17:17:26 +1100637 this.reloadWebglAddon_();
Jason Lin8de3d282022-09-01 21:29:05 +1000638 }
639 this.term.focus();
640 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100641 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
642 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
643 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000644
Emil Mikulic2a194d02022-09-29 14:30:59 +1000645 // Block right-click context menu from popping up.
646 elem.addEventListener('contextmenu', (e) => e.preventDefault());
647
648 // Add a handler for pasting with the mouse.
649 elem.addEventListener('mousedown', async (e) => {
650 if (this.term.modes.mouseTrackingMode !== 'none') {
651 // xterm.js is in mouse mode and will handle the event.
652 return;
653 }
654 const MIDDLE = 1;
655 const RIGHT = 2;
656 if (e.button === MIDDLE || (e.button === RIGHT &&
657 this.prefs_.getBoolean('mouse-right-click-paste'))) {
658 // Paste.
659 if (navigator.clipboard && navigator.clipboard.readText) {
660 const text = await navigator.clipboard.readText();
661 this.term.paste(text);
662 }
663 }
664 });
665
Jason Lin2649da22022-10-12 10:16:44 +1100666 await this.scheduleFit_();
Jason Lind3aacef2022-10-12 19:03:37 +1100667 this.a11yButtons_ = new A11yButtons(this.term, elem);
668
Jason Lin8de3d282022-09-01 21:29:05 +1000669 this.onTerminalReady();
670 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000671 }
672
673 /** @override */
674 showOverlay(msg, timeout = 1500) {
Jason Lin34a45322022-10-12 19:10:52 +1100675 this.notificationCenter_?.show(msg, {timeout});
Jason Lin21d854f2022-08-22 14:49:59 +1000676 }
677
678 /** @override */
679 hideOverlay() {
Jason Lin34a45322022-10-12 19:10:52 +1100680 this.notificationCenter_?.hide();
Jason Linca61ffb2022-08-03 19:37:12 +1000681 }
682
683 /** @override */
684 getPrefs() {
685 return this.prefs_;
686 }
687
688 /** @override */
689 getDocument() {
690 return window.document;
691 }
692
Jason Lin21d854f2022-08-22 14:49:59 +1000693 /** @override */
694 reset() {
695 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000696 }
697
698 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000699 setProfile(profileId, callback = undefined) {
700 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000701 }
702
Jason Lin21d854f2022-08-22 14:49:59 +1000703 /** @override */
704 interpret(string) {
705 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000706 }
707
Jason Lin21d854f2022-08-22 14:49:59 +1000708 /** @override */
709 focus() {
710 this.term.focus();
711 }
Jason Linca61ffb2022-08-03 19:37:12 +1000712
713 /** @override */
714 onOpenOptionsPage() {}
715
716 /** @override */
717 onTerminalReady() {}
718
Jason Lind04bab32022-08-22 14:48:39 +1000719 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000720 // This is for this.notificationCenter_.
721 const setHtermCSSVariable = (name, value) => {
722 document.body.style.setProperty(`--hterm-${name}`, value);
723 };
724
725 const setHtermColorCSSVariable = (name, color) => {
726 const css = lib.notNull(lib.colors.normalizeCSS(color));
727 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
728 setHtermCSSVariable(name, rgb);
729 };
730
731 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000732 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000733 setHtermCSSVariable('font-size', `${v}px`);
734 });
735
Jason Linda56aa92022-09-02 13:01:49 +1000736 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000737 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000738 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100739 this.bell_.playAudio = !!v;
740 },
741 'desktop-notification-bell': (v) => {
742 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000743 },
Jason Lind04bab32022-08-22 14:48:39 +1000744 'background-color': (v) => {
Jason Linee0c1f72022-10-18 17:17:26 +1100745 this.updateBackgroundColor_(v);
Jason Lin21d854f2022-08-22 14:49:59 +1000746 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000747 },
Jason Lind04bab32022-08-22 14:48:39 +1000748 'color-palette-overrides': (v) => {
749 if (!(v instanceof Array)) {
750 // For terminal, we always expect this to be an array.
751 console.warn('unexpected color palette: ', v);
752 return;
753 }
754 const colors = {};
755 for (let i = 0; i < v.length; ++i) {
756 colors[ANSI_COLOR_NAMES[i]] = v[i];
757 }
758 this.updateTheme_(colors);
759 },
Jason Linda56aa92022-09-02 13:01:49 +1000760 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
761 'cursor-color': (v) => this.updateTheme_({cursor: v}),
762 'cursor-shape': (v) => {
763 let shape;
764 if (v === 'BEAM') {
765 shape = 'bar';
766 } else {
767 shape = v.toLowerCase();
768 }
769 this.updateOption_('cursorStyle', shape, false);
770 },
771 'font-family': (v) => this.updateFont_(v),
772 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000773 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000774 setHtermColorCSSVariable('foreground-color', v);
775 },
Jason Linc48f7432022-10-13 17:28:30 +1100776 'line-height': (v) => this.updateOption_('lineHeight', v, true),
Jason Lin446f3d92022-10-13 17:34:21 +1100777 'scroll-on-output': (v) => {
778 if (!v) {
779 this.scrollOnOutputListener_?.dispose();
780 this.scrollOnOutputListener_ = null;
781 return;
782 }
783 if (!this.scrollOnOutputListener_) {
784 this.scrollOnOutputListener_ = this.term.onWriteParsed(
785 () => this.term.scrollToBottom());
786 }
787 },
Jason Lind04bab32022-08-22 14:48:39 +1000788 });
Jason Lin5690e752022-08-30 15:36:45 +1000789
790 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
791 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
792 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
793 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
794 }
Jason Lind04bab32022-08-22 14:48:39 +1000795 }
796
797 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000798 * Fit the terminal to the containing HTML element.
799 */
800 fit_() {
801 if (!this.inited_) {
802 return;
803 }
804
805 const screenPaddingSize = /** @type {number} */(
806 this.prefs_.get('screen-padding-size'));
807
808 const calc = (size, cellSize) => {
809 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
810 };
811
Jason Lin2649da22022-10-12 10:16:44 +1100812 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
813 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
814 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000815 if (cols >= 0 && rows >= 0) {
816 this.term.resize(cols, rows);
817 }
818 }
819
Jason Linee0c1f72022-10-18 17:17:26 +1100820 reloadWebglAddon_() {
821 if (this.webglAddon_) {
822 this.webglAddon_.dispose();
823 }
824 this.webglAddon_ = new WebglAddon();
825 this.term.loadAddon(this.webglAddon_);
826 }
827
828 /**
829 * Update the background color. This will also adjust the transparency based
830 * on whether there is a background image.
831 *
832 * @param {string} color
833 */
834 updateBackgroundColor_(color) {
835 const hasBackgroundImage = this.hasBackgroundImage();
836
837 // We only set allowTransparency when it is necessary becuase 1) xterm.js
838 // documentation states that allowTransparency can affect performance; 2) I
839 // find that the rendering is better with allowTransparency being false.
840 // This could be a bug with xterm.js.
841 if (!!this.term.options.allowTransparency !== hasBackgroundImage) {
842 this.term.options.allowTransparency = hasBackgroundImage;
843 if (this.enableWebGL_ && this.inited_) {
844 // Setting allowTransparency in the middle messes up webgl rendering,
845 // so we need to reload it here.
846 this.reloadWebglAddon_();
847 }
848 }
849
850 if (this.hasBackgroundImage()) {
851 const css = lib.notNull(lib.colors.normalizeCSS(color));
852 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
853 // Note that we still want to set the RGB part correctly even though it is
854 // completely transparent. This is because the background color without
855 // the alpha channel is used in reverse video mode.
856 color = `rgba(${rgb}, 0)`;
857 }
858
859 this.updateTheme_({background: color});
860 }
861
Jason Linc2504ae2022-09-02 13:03:31 +1000862 /**
Jason Lind04bab32022-08-22 14:48:39 +1000863 * @param {!Object} theme
864 */
865 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000866 const updateTheme = (target) => {
867 for (const [key, value] of Object.entries(theme)) {
868 target[key] = lib.colors.normalizeCSS(value);
869 }
870 };
871
872 // Must use a new theme object to trigger re-render if we have initialized.
873 if (this.inited_) {
874 const newTheme = {...this.term.options.theme};
875 updateTheme(newTheme);
876 this.term.options.theme = newTheme;
877 return;
Jason Lind04bab32022-08-22 14:48:39 +1000878 }
Jason Lin8de3d282022-09-01 21:29:05 +1000879
880 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000881 }
882
883 /**
Jason Linda56aa92022-09-02 13:01:49 +1000884 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
885 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000886 *
887 * @param {string} key
888 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000889 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000890 */
Jason Linda56aa92022-09-02 13:01:49 +1000891 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000892 // TODO: xterm supports updating multiple options at the same time. We
893 // should probably do that.
894 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000895 if (scheduleFit) {
896 this.scheduleFit_();
897 }
Jason Lind04bab32022-08-22 14:48:39 +1000898 }
Jason Linabad7562022-08-22 14:49:05 +1000899
900 /**
901 * Called when there is a "fontloadingdone" event. We need this because
902 * `FontManager.loadFont()` does not guarantee loading all the font files.
903 */
904 async onFontLoadingDone_() {
905 // If there is a pending font, the font is going to be refresh soon, so we
906 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000907 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000908 this.scheduleRefreshFont_();
909 }
910 }
911
Jason Lin5690e752022-08-30 15:36:45 +1000912 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000913 this.copyString_(this.term.getSelection());
914 }
915
916 /** @param {string} data */
917 copyString_(data) {
918 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000919 return;
920 }
Jason Line9231bc2022-09-01 13:54:02 +1000921 navigator.clipboard?.writeText(data);
Jason Lin83ef5ba2022-10-13 17:40:30 +1100922
923 if (this.prefs_.get('enable-clipboard-notice')) {
924 if (!this.copyNotice_) {
925 this.copyNotice_ = document.createElement('terminal-copy-notice');
926 }
927 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500),
928 200);
Jason Lin6a402a72022-08-25 16:07:02 +1000929 }
Jason Lin6a402a72022-08-25 16:07:02 +1000930 }
931
Jason Linabad7562022-08-22 14:49:05 +1000932 /**
933 * Refresh xterm rendering for a font related event.
934 */
935 refreshFont_() {
936 // We have to set the fontFamily option to a different string to trigger the
937 // re-rendering. Appending a space at the end seems to be the easiest
938 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
939 // us.
940 //
941 // TODO: Report a bug to xterm.js and ask for exposing a public function for
942 // the refresh so that we don't need to do this hack.
943 this.term.options.fontFamily += ' ';
944 }
945
946 /**
947 * Update a font.
948 *
949 * @param {string} cssFontFamily
950 */
951 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000952 this.pendingFont_ = cssFontFamily;
953 await this.fontManager_.loadFont(cssFontFamily);
954 // Sleep a bit to wait for flushing fontloadingdone events. This is not
955 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
956 // to refresh font unnecessarily in some cases.
957 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000958
Jason Lin6a402a72022-08-25 16:07:02 +1000959 if (this.pendingFont_ !== cssFontFamily) {
960 // `updateFont_()` probably is called again. Abort what we are doing.
961 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
962 ` (expecting ${cssFontFamily})`);
963 return;
964 }
Jason Linabad7562022-08-22 14:49:05 +1000965
Jason Lin6a402a72022-08-25 16:07:02 +1000966 if (this.term.options.fontFamily !== cssFontFamily) {
967 this.term.options.fontFamily = cssFontFamily;
968 } else {
969 // If the font is already the same, refresh font just to be safe.
970 this.refreshFont_();
971 }
972 this.pendingFont_ = null;
973 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000974 }
Jason Lin5690e752022-08-30 15:36:45 +1000975
976 /**
977 * @param {!KeyboardEvent} ev
978 * @return {boolean} Return false if xterm.js should not handle the key event.
979 */
980 customKeyEventHandler_(ev) {
981 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
982 (ev.altKey ? Modifier.Alt : 0) |
983 (ev.ctrlKey ? Modifier.Ctrl : 0) |
984 (ev.metaKey ? Modifier.Meta : 0);
985 const handler = this.keyDownHandlers_.get(
986 encodeKeyCombo(modifiers, ev.keyCode));
987 if (handler) {
988 if (ev.type === 'keydown') {
989 handler(ev);
990 }
991 return false;
992 }
993
994 return true;
995 }
996
997 /**
998 * A keydown handler for zoom-related keys.
999 *
1000 * @param {!KeyboardEvent} ev
1001 */
1002 zoomKeyDownHandler_(ev) {
1003 ev.preventDefault();
1004
1005 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
1006 // The only one with a control code.
1007 if (ev.keyCode === keyCodes.MINUS) {
1008 this.io.onVTKeystroke('\x1f');
1009 }
1010 return;
1011 }
1012
1013 let newFontSize;
1014 switch (ev.keyCode) {
1015 case keyCodes.ZERO:
1016 newFontSize = this.prefs_.get('font-size');
1017 break;
1018 case keyCodes.MINUS:
1019 newFontSize = this.term.options.fontSize - 1;
1020 break;
1021 default:
1022 newFontSize = this.term.options.fontSize + 1;
1023 break;
1024 }
1025
Jason Linda56aa92022-09-02 13:01:49 +10001026 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +10001027 }
1028
1029 /** @param {!KeyboardEvent} ev */
1030 ctrlCKeyDownHandler_(ev) {
1031 ev.preventDefault();
1032 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
1033 this.term.hasSelection()) {
1034 this.copySelection_();
1035 return;
1036 }
1037
1038 this.io.onVTKeystroke('\x03');
1039 }
1040
1041 /** @param {!KeyboardEvent} ev */
1042 ctrlVKeyDownHandler_(ev) {
1043 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
1044 // Don't do anything and let the browser handles the key.
1045 return;
1046 }
1047
1048 ev.preventDefault();
1049 this.io.onVTKeystroke('\x16');
1050 }
1051
1052 resetKeyDownHandlers_() {
1053 this.keyDownHandlers_.clear();
1054
1055 /**
1056 * Don't do anything and let the browser handles the key.
1057 *
1058 * @param {!KeyboardEvent} ev
1059 */
1060 const noop = (ev) => {};
1061
1062 /**
1063 * @param {number} modifiers
1064 * @param {number} keyCode
1065 * @param {function(!KeyboardEvent)} func
1066 */
1067 const set = (modifiers, keyCode, func) => {
1068 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
1069 func);
1070 };
1071
1072 /**
1073 * @param {number} modifiers
1074 * @param {number} keyCode
1075 * @param {function(!KeyboardEvent)} func
1076 */
1077 const setWithShiftVersion = (modifiers, keyCode, func) => {
1078 set(modifiers, keyCode, func);
1079 set(modifiers | Modifier.Shift, keyCode, func);
1080 };
1081
Jason Lin5690e752022-08-30 15:36:45 +10001082 // Ctrl+/
1083 set(Modifier.Ctrl, 191, (ev) => {
1084 ev.preventDefault();
1085 this.io.onVTKeystroke(ctl('_'));
1086 });
1087
1088 // Settings page.
1089 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
1090 ev.preventDefault();
1091 chrome.terminalPrivate.openOptionsPage(() => {});
1092 });
1093
1094 if (this.prefs_.get('keybindings-os-defaults')) {
1095 for (const binding of OS_DEFAULT_BINDINGS) {
1096 this.keyDownHandlers_.set(binding, noop);
1097 }
1098 }
1099
1100 /** @param {!KeyboardEvent} ev */
1101 const newWindow = (ev) => {
1102 ev.preventDefault();
1103 chrome.terminalPrivate.openWindow();
1104 };
1105 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
1106 if (this.prefs_.get('pass-ctrl-n')) {
1107 set(Modifier.Ctrl, keyCodes.N, newWindow);
1108 }
1109
1110 if (this.prefs_.get('pass-ctrl-t')) {
1111 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
1112 }
1113
1114 if (this.prefs_.get('pass-ctrl-w')) {
1115 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
1116 }
1117
1118 if (this.prefs_.get('pass-ctrl-tab')) {
1119 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
1120 }
1121
1122 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
1123
1124 /**
1125 * Set a handler for the key combo ctrl+<number>.
1126 *
1127 * @param {number} number 1 to 9
1128 * @param {string} controlCode The control code to send if we don't want to
1129 * let the browser to handle it.
1130 */
1131 const setCtrlNumberHandler = (number, controlCode) => {
1132 let func = noop;
1133 if (!passCtrlNumber) {
1134 func = (ev) => {
1135 ev.preventDefault();
1136 this.io.onVTKeystroke(controlCode);
1137 };
1138 }
1139 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1140 };
1141
1142 setCtrlNumberHandler(1, '1');
1143 setCtrlNumberHandler(2, ctl('@'));
1144 setCtrlNumberHandler(3, ctl('['));
1145 setCtrlNumberHandler(4, ctl('\\'));
1146 setCtrlNumberHandler(5, ctl(']'));
1147 setCtrlNumberHandler(6, ctl('^'));
1148 setCtrlNumberHandler(7, ctl('_'));
1149 setCtrlNumberHandler(8, '\x7f');
1150 setCtrlNumberHandler(9, '9');
1151
1152 if (this.prefs_.get('pass-alt-number')) {
1153 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1154 set(Modifier.Alt, keyCode, noop);
1155 }
1156 }
1157
1158 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1159 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1160 }
1161
1162 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1163 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1164 }
Jason Linee0c1f72022-10-18 17:17:26 +11001165
1166 handleOnTerminalReady() {}
Jason Linca61ffb2022-08-03 19:37:12 +10001167}
1168
Jason Lind66e6bf2022-08-22 14:47:10 +10001169class HtermTerminal extends hterm.Terminal {
1170 /** @override */
1171 decorate(div) {
1172 super.decorate(div);
1173
Jason Linc48f7432022-10-13 17:28:30 +11001174 definePrefs(this.getPrefs());
Jason Linee0c1f72022-10-18 17:17:26 +11001175 }
Jason Linc48f7432022-10-13 17:28:30 +11001176
Jason Linee0c1f72022-10-18 17:17:26 +11001177 /**
1178 * This needs to be called in the `onTerminalReady()` callback. This is
1179 * awkward, but it is temporary since we will drop support for hterm at some
1180 * point.
1181 */
1182 handleOnTerminalReady() {
Jason Lind66e6bf2022-08-22 14:47:10 +10001183 const fontManager = new FontManager(this.getDocument());
1184 fontManager.loadPowerlineCSS().then(() => {
1185 const prefs = this.getPrefs();
1186 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1187 prefs.addObserver(
1188 'font-family',
1189 (v) => fontManager.loadFont(/** @type {string} */(v)));
1190 });
Jason Linee0c1f72022-10-18 17:17:26 +11001191
1192 const backgroundImageWatcher = new BackgroundImageWatcher(this.getPrefs(),
1193 (image) => this.setBackgroundImage(image));
1194 this.setBackgroundImage(backgroundImageWatcher.getBackgroundImage());
1195 backgroundImageWatcher.watch();
Jason Lind66e6bf2022-08-22 14:47:10 +10001196 }
Jason Lin2649da22022-10-12 10:16:44 +11001197
1198 /**
1199 * Write data to the terminal.
1200 *
1201 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1202 * UTF-8 data
1203 * @param {function()=} callback Optional callback that fires when the data
1204 * was processed by the parser.
1205 */
1206 write(data, callback) {
1207 if (typeof data === 'string') {
1208 this.io.print(data);
1209 } else {
1210 this.io.writeUTF8(data);
1211 }
1212 // Hterm processes the data synchronously, so we can call the callback
1213 // immediately.
1214 if (callback) {
1215 setTimeout(callback);
1216 }
1217 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001218}
1219
Jason Linca61ffb2022-08-03 19:37:12 +10001220/**
1221 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1222 * preference value.
1223 *
1224 * @param {{
1225 * storage: !lib.Storage,
1226 * profileId: string,
1227 * }} args
1228 * @return {!Promise<!hterm.Terminal>}
1229 */
1230export async function createEmulator({storage, profileId}) {
1231 let config = TERMINAL_EMULATORS.get('hterm');
1232
1233 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001234 // TODO: remove the url param logic. This is temporary to make manual
1235 // testing a bit easier, which is also why this is not in
1236 // './js/terminal_info.js'.
1237 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
1238 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +10001239 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001240 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001241 TERMINAL_EMULATORS.values().next().value;
1242 console.log('Terminal emulator config: ', config);
1243 }
1244
1245 switch (config.lib) {
1246 case 'xterm.js':
1247 {
1248 const terminal = new XtermTerminal({
1249 storage,
1250 profileId,
1251 enableWebGL: config.webgl,
1252 });
Jason Linca61ffb2022-08-03 19:37:12 +10001253 return terminal;
1254 }
1255 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001256 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001257 default:
1258 throw new Error('incorrect emulator config');
1259 }
1260}
1261
Jason Lin6a402a72022-08-25 16:07:02 +10001262class TerminalCopyNotice extends LitElement {
1263 /** @override */
1264 static get styles() {
1265 return css`
1266 :host {
1267 display: block;
1268 text-align: center;
1269 }
1270
1271 svg {
1272 fill: currentColor;
1273 }
1274 `;
1275 }
1276
1277 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001278 connectedCallback() {
1279 super.connectedCallback();
1280 if (!this.childNodes.length) {
1281 // This is not visible since we use shadow dom. But this will allow the
1282 // hterm.NotificationCenter to announce the the copy text.
1283 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1284 }
1285 }
1286
1287 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001288 render() {
1289 return html`
1290 ${ICON_COPY}
1291 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1292 `;
1293 }
1294}
1295
1296customElements.define('terminal-copy-notice', TerminalCopyNotice);