blob: fbdce6c35f978824d4a9ea27fc2f3be711b46fb6 [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
Jason Lina8adea52022-10-25 13:14:14 +1100250// TODO: we should subscribe to the xterm.js onscroll event, and
251// disable/enable the buttons accordingly. However, xterm.js does not seem to
252// emit the onscroll event when the viewport is scrolled by the mouse. See
253// https://github.com/xtermjs/xterm.js/issues/3864
254export class A11yButtons {
Jason Lind3aacef2022-10-12 19:03:37 +1100255 /**
256 * @param {!Terminal} term
257 * @param {!Element} elem The container element for the terminal.
Jason Lina8adea52022-10-25 13:14:14 +1100258 * @param {!hterm.AccessibilityReader} htermA11yReader
Jason Lind3aacef2022-10-12 19:03:37 +1100259 */
Jason Lina8adea52022-10-25 13:14:14 +1100260 constructor(term, elem, htermA11yReader) {
261 this.term_ = term;
262 this.htermA11yReader_ = htermA11yReader;
Jason Lind3aacef2022-10-12 19:03:37 +1100263 this.pageUpButton_ = document.createElement('button');
264 this.pageUpButton_.style.cssText = A11Y_BUTTON_STYLE;
265 this.pageUpButton_.textContent =
266 hterm.messageManager.get('HTERM_BUTTON_PAGE_UP');
267 this.pageUpButton_.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100268 () => this.scrollPages_(-1));
Jason Lind3aacef2022-10-12 19:03:37 +1100269
270 this.pageDownButton_ = document.createElement('button');
271 this.pageDownButton_.style.cssText = A11Y_BUTTON_STYLE;
272 this.pageDownButton_.textContent =
273 hterm.messageManager.get('HTERM_BUTTON_PAGE_DOWN');
274 this.pageDownButton_.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100275 () => this.scrollPages_(1));
Jason Lind3aacef2022-10-12 19:03:37 +1100276
277 this.resetPos_();
278 elem.prepend(this.pageUpButton_);
279 elem.append(this.pageDownButton_);
280
281 this.onSelectionChange_ = this.onSelectionChange_.bind(this);
282 }
283
284 /**
Jason Lina8adea52022-10-25 13:14:14 +1100285 * @param {number} amount
286 */
287 scrollPages_(amount) {
288 this.term_.scrollPages(amount);
289 this.announceScreenContent_();
290 }
291
292 announceScreenContent_() {
293 const activeBuffer = this.term_.buffer.active;
294
295 let percentScrolled = 100;
296 if (activeBuffer.baseY !== 0) {
297 percentScrolled = Math.round(
298 100 * activeBuffer.viewportY / activeBuffer.baseY);
299 }
300
301 let currentScreenContent = hterm.messageManager.get(
302 'HTERM_ANNOUNCE_CURRENT_SCREEN_HEADER',
303 [percentScrolled],
304 '$1% scrolled,');
305
306 currentScreenContent += '\n';
307
308 const rowEnd = Math.min(activeBuffer.viewportY + this.term_.rows,
309 activeBuffer.length);
310 for (let i = activeBuffer.viewportY; i < rowEnd; ++i) {
311 currentScreenContent +=
312 activeBuffer.getLine(i).translateToString(true) + '\n';
313 }
314 currentScreenContent = currentScreenContent.trim();
315
316 this.htermA11yReader_.assertiveAnnounce(currentScreenContent);
317 }
318
319 /**
Jason Lind3aacef2022-10-12 19:03:37 +1100320 * @param {boolean} enabled
321 */
322 setEnabled(enabled) {
323 if (enabled) {
324 document.addEventListener('selectionchange', this.onSelectionChange_);
325 } else {
326 this.resetPos_();
327 document.removeEventListener('selectionchange', this.onSelectionChange_);
328 }
329 }
330
331 resetPos_() {
332 this.pageUpButton_.style.top = '-200px';
333 this.pageDownButton_.style.bottom = '-200px';
334 }
335
336 onSelectionChange_() {
337 this.resetPos_();
338
339 const selectedElement = document.getSelection().anchorNode.parentElement;
340 if (selectedElement === this.pageUpButton_) {
341 this.pageUpButton_.style.top = '16px';
342 } else if (selectedElement === this.pageDownButton_) {
343 this.pageDownButton_.style.bottom = '16px';
344 }
345 }
346}
347
Jason Linee0c1f72022-10-18 17:17:26 +1100348const BACKGROUND_IMAGE_KEY = 'background-image';
349
350class BackgroundImageWatcher {
351 /**
352 * @param {!hterm.PreferenceManager} prefs
353 * @param {function(string)} onChange This is called with the background image
354 * (could be empty) whenever it changes.
355 */
356 constructor(prefs, onChange) {
357 this.prefs_ = prefs;
358 this.onChange_ = onChange;
359 }
360
361 /**
362 * Call once to start watching for background image changes.
363 */
364 watch() {
365 window.addEventListener('storage', (e) => {
366 if (e.key === BACKGROUND_IMAGE_KEY) {
367 this.onChange_(this.getBackgroundImage());
368 }
369 });
370 this.prefs_.addObserver(BACKGROUND_IMAGE_KEY, () => {
371 this.onChange_(this.getBackgroundImage());
372 });
373 }
374
375 getBackgroundImage() {
376 const image = window.localStorage.getItem(BACKGROUND_IMAGE_KEY);
377 if (image) {
378 return `url(${image})`;
379 }
380
381 return this.prefs_.getString(BACKGROUND_IMAGE_KEY);
382 }
383}
384
Jason Lin83707c92022-09-20 19:09:41 +1000385/**
Jason Linca61ffb2022-08-03 19:37:12 +1000386 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
387 * so that it can be used in existing code.
388 *
Jason Linca61ffb2022-08-03 19:37:12 +1000389 * @extends {hterm.Terminal}
390 * @unrestricted
391 */
Jason Linabad7562022-08-22 14:49:05 +1000392export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000393 /**
394 * @param {{
395 * storage: !lib.Storage,
396 * profileId: string,
397 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000398 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000399 * }} args
400 */
Jason Linabad7562022-08-22 14:49:05 +1000401 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000402 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
403 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
404 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
405
Jason Lin8de3d282022-09-01 21:29:05 +1000406 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000407 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000408 /** @type {!hterm.PreferenceManager} */
409 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
Jason Linc48f7432022-10-13 17:28:30 +1100410 definePrefs(this.prefs_);
Jason Linca61ffb2022-08-03 19:37:12 +1000411 this.enableWebGL_ = enableWebGL;
412
Jason Lin5690e752022-08-30 15:36:45 +1000413 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linfc8a3722022-09-07 17:49:18 +1000414 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Lin2649da22022-10-12 10:16:44 +1100415 this.xtermInternal_ = testParams?.xtermInternal ||
416 new XtermInternal(this.term);
Jason Linabad7562022-08-22 14:49:05 +1000417 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000418
Jason Linc2504ae2022-09-02 13:03:31 +1000419 /** @type {?Element} */
420 this.container_;
Jason Linc7afb672022-10-11 15:54:17 +1100421 this.bell_ = new Bell();
Jason Linc2504ae2022-09-02 13:03:31 +1000422 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000423 testParams ? 0 : 250);
424
Jason Lin83707c92022-09-20 19:09:41 +1000425 this.term.loadAddon(
426 new WebLinksAddon((e, uri) => lib.f.openWindow(uri, '_blank')));
Jason Lin4de4f382022-09-01 14:10:18 +1000427 this.term.loadAddon(new Unicode11Addon());
428 this.term.unicode.activeVersion = '11';
429
Jason Linabad7562022-08-22 14:49:05 +1000430 this.pendingFont_ = null;
431 this.scheduleRefreshFont_ = delayedScheduler(
432 () => this.refreshFont_(), 100);
433 document.fonts.addEventListener('loadingdone',
434 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000435
436 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000437 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000438
Jason Lin34a45322022-10-12 19:10:52 +1100439 this.term.onResize(({cols, rows}) => {
440 this.io.onTerminalResize(cols, rows);
441 if (this.prefs_.get('enable-resize-status')) {
442 this.showOverlay(`${cols} × ${rows}`);
443 }
444 });
Jason Lin21d854f2022-08-22 14:49:59 +1000445 // We could also use `this.io.sendString()` except for the nassh exit
446 // prompt, which only listens to onVTKeystroke().
447 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000448 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100449 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin83ef5ba2022-10-13 17:40:30 +1100450 this.term.onSelectionChange(() => {
451 if (this.prefs_.get('copy-on-select')) {
452 this.copySelection_();
453 }
454 });
Jason Linc7afb672022-10-11 15:54:17 +1100455 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000456
457 /**
458 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
459 *
460 * If a key combo is in the map:
461 *
462 * - The handler instead of xterm.js will handle the keydown event.
463 * - Keyup and keypress will be ignored by both us and xterm.js.
464 *
465 * We re-generate this map every time a relevant pref value is changed. This
466 * is ok because pref changes are rare.
467 *
468 * @type {!Map<number, function(!KeyboardEvent)>}
469 */
470 this.keyDownHandlers_ = new Map();
471 this.scheduleResetKeyDownHandlers_ =
472 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
473
474 this.term.attachCustomKeyEventHandler(
475 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000476
Jason Lin21d854f2022-08-22 14:49:59 +1000477 this.io = new XtermTerminalIO(this);
478 this.notificationCenter_ = null;
Jason Lind3aacef2022-10-12 19:03:37 +1100479 this.htermA11yReader_ = null;
480 this.a11yButtons_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000481 this.copyNotice_ = null;
Jason Lin446f3d92022-10-13 17:34:21 +1100482 this.scrollOnOutputListener_ = null;
Jason Linee0c1f72022-10-18 17:17:26 +1100483 this.backgroundImageWatcher_ = new BackgroundImageWatcher(this.prefs_,
484 this.setBackgroundImage.bind(this));
485 this.webglAddon_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000486
Jason Lin83707c92022-09-20 19:09:41 +1000487 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000488 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000489 // The webgl cursor layer also paints the character under the cursor with
490 // this `cursorAccent` color. We use a completely transparent color here
491 // to effectively disable that.
492 cursorAccent: 'rgba(0, 0, 0, 0)',
493 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000494 selectionBackground: 'rgba(174, 203, 250, .6)',
495 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000496 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000497 };
498 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000499 }
500
Jason Linc7afb672022-10-11 15:54:17 +1100501 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100502 setWindowTitle(title) {
503 document.title = title;
504 }
505
506 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100507 ringBell() {
508 this.bell_.ring();
509 }
510
Jason Lin2649da22022-10-12 10:16:44 +1100511 /** @override */
512 print(str) {
513 this.xtermInternal_.print(str);
514 }
515
516 /** @override */
517 wipeContents() {
518 this.term.clear();
519 }
520
521 /** @override */
522 newLine() {
523 this.xtermInternal_.newLine();
524 }
525
526 /** @override */
527 cursorLeft(number) {
528 this.xtermInternal_.cursorLeft(number ?? 1);
529 }
530
Jason Lind3aacef2022-10-12 19:03:37 +1100531 /** @override */
532 setAccessibilityEnabled(enabled) {
533 this.a11yButtons_.setEnabled(enabled);
534 this.htermA11yReader_.setAccessibilityEnabled(enabled);
535 this.term.options.screenReaderMode = enabled;
536 }
537
Jason Linee0c1f72022-10-18 17:17:26 +1100538 hasBackgroundImage() {
539 return !!this.container_.style.backgroundImage;
540 }
541
542 /** @override */
543 setBackgroundImage(image) {
544 this.container_.style.backgroundImage = image || '';
545 this.updateBackgroundColor_(this.prefs_.getString('background-color'));
546 }
547
Jason Linca61ffb2022-08-03 19:37:12 +1000548 /**
549 * Install stubs for stuff that we haven't implemented yet so that the code
550 * still runs.
551 */
552 installUnimplementedStubs_() {
553 this.keyboard = {
554 keyMap: {
555 keyDefs: [],
556 },
557 bindings: {
558 clear: () => {},
559 addBinding: () => {},
560 addBindings: () => {},
561 OsDefaults: {},
562 },
563 };
564 this.keyboard.keyMap.keyDefs[78] = {};
565
566 const methodNames = [
Joel Hockeyb89a9782022-10-16 22:00:12 -0700567 'eraseLine',
Joel Hockeyb89a9782022-10-16 22:00:12 -0700568 'setCursorColumn',
Jason Linca61ffb2022-08-03 19:37:12 +1000569 'setCursorPosition',
570 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000571 ];
572
573 for (const name of methodNames) {
574 this[name] = () => console.warn(`${name}() is not implemented`);
575 }
576
577 this.contextMenu = {
578 setItems: () => {
579 console.warn('.contextMenu.setItems() is not implemented');
580 },
581 };
Jason Lin21d854f2022-08-22 14:49:59 +1000582
583 this.vt = {
584 resetParseState: () => {
585 console.warn('.vt.resetParseState() is not implemented');
586 },
587 };
Jason Linca61ffb2022-08-03 19:37:12 +1000588 }
589
Jason Line9231bc2022-09-01 13:54:02 +1000590 installEscapeSequenceHandlers_() {
591 // OSC 52 for copy.
592 this.term.parser.registerOscHandler(52, (args) => {
593 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
594 // parameter is used to select which of the X clipboards to address. Since
595 // we're not integrating with X, we treat them all the same.
596 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
597 if (!parsedArgs) {
598 return true;
599 }
600
601 let data;
602 try {
603 data = window.atob(parsedArgs[1]);
604 } catch (e) {
605 // If the user sent us invalid base64 content, silently ignore it.
606 return true;
607 }
608 const decoder = new TextDecoder();
609 const bytes = lib.codec.stringToCodeUnitArray(data);
610 this.copyString_(decoder.decode(bytes));
611
612 return true;
613 });
Jason Lin2649da22022-10-12 10:16:44 +1100614
615 this.xtermInternal_.installTmuxControlModeHandler(
616 (data) => this.onTmuxControlModeLine(data));
617 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000618 }
619
Jason Linca61ffb2022-08-03 19:37:12 +1000620 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000621 * Write data to the terminal.
622 *
623 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
624 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100625 * @param {function()=} callback Optional callback that fires when the data
626 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000627 */
Jason Lin2649da22022-10-12 10:16:44 +1100628 write(data, callback) {
629 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000630 }
631
632 /**
633 * Like `this.write()` but also write a line break.
634 *
635 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100636 * @param {function()=} callback Optional callback that fires when the data
637 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000638 */
Jason Lin2649da22022-10-12 10:16:44 +1100639 writeln(data, callback) {
640 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000641 }
642
Jason Linca61ffb2022-08-03 19:37:12 +1000643 get screenSize() {
644 return new hterm.Size(this.term.cols, this.term.rows);
645 }
646
647 /**
648 * Don't need to do anything.
649 *
650 * @override
651 */
652 installKeyboard() {}
653
654 /**
655 * @override
656 */
657 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000658 this.container_ = elem;
Jason Linee0c1f72022-10-18 17:17:26 +1100659 elem.style.backgroundSize = '100% 100%';
660
Jason Lin8de3d282022-09-01 21:29:05 +1000661 (async () => {
662 await new Promise((resolve) => this.prefs_.readStorage(resolve));
663 // This will trigger all the observers to set the terminal options before
664 // we call `this.term.open()`.
665 this.prefs_.notifyAll();
666
Jason Linc2504ae2022-09-02 13:03:31 +1000667 const screenPaddingSize = /** @type {number} */(
668 this.prefs_.get('screen-padding-size'));
669 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
670
Jason Linee0c1f72022-10-18 17:17:26 +1100671 this.setBackgroundImage(
672 this.backgroundImageWatcher_.getBackgroundImage());
673 this.backgroundImageWatcher_.watch();
674
Jason Lin8de3d282022-09-01 21:29:05 +1000675 this.inited_ = true;
676 this.term.open(elem);
677
Jason Lin8de3d282022-09-01 21:29:05 +1000678 if (this.enableWebGL_) {
Jason Linee0c1f72022-10-18 17:17:26 +1100679 this.reloadWebglAddon_();
Jason Lin8de3d282022-09-01 21:29:05 +1000680 }
681 this.term.focus();
682 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100683 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
684 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
685 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000686
Emil Mikulic2a194d02022-09-29 14:30:59 +1000687 // Block right-click context menu from popping up.
688 elem.addEventListener('contextmenu', (e) => e.preventDefault());
689
690 // Add a handler for pasting with the mouse.
691 elem.addEventListener('mousedown', async (e) => {
692 if (this.term.modes.mouseTrackingMode !== 'none') {
693 // xterm.js is in mouse mode and will handle the event.
694 return;
695 }
696 const MIDDLE = 1;
697 const RIGHT = 2;
698 if (e.button === MIDDLE || (e.button === RIGHT &&
699 this.prefs_.getBoolean('mouse-right-click-paste'))) {
700 // Paste.
701 if (navigator.clipboard && navigator.clipboard.readText) {
702 const text = await navigator.clipboard.readText();
703 this.term.paste(text);
704 }
705 }
706 });
707
Jason Lin2649da22022-10-12 10:16:44 +1100708 await this.scheduleFit_();
Jason Lina8adea52022-10-25 13:14:14 +1100709 this.a11yButtons_ = new A11yButtons(this.term, elem,
710 this.htermA11yReader_);
Jason Lind3aacef2022-10-12 19:03:37 +1100711
Jason Lin8de3d282022-09-01 21:29:05 +1000712 this.onTerminalReady();
713 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000714 }
715
716 /** @override */
717 showOverlay(msg, timeout = 1500) {
Jason Lin34a45322022-10-12 19:10:52 +1100718 this.notificationCenter_?.show(msg, {timeout});
Jason Lin21d854f2022-08-22 14:49:59 +1000719 }
720
721 /** @override */
722 hideOverlay() {
Jason Lin34a45322022-10-12 19:10:52 +1100723 this.notificationCenter_?.hide();
Jason Linca61ffb2022-08-03 19:37:12 +1000724 }
725
726 /** @override */
727 getPrefs() {
728 return this.prefs_;
729 }
730
731 /** @override */
732 getDocument() {
733 return window.document;
734 }
735
Jason Lin21d854f2022-08-22 14:49:59 +1000736 /** @override */
737 reset() {
738 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000739 }
740
741 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000742 setProfile(profileId, callback = undefined) {
743 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000744 }
745
Jason Lin21d854f2022-08-22 14:49:59 +1000746 /** @override */
747 interpret(string) {
748 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000749 }
750
Jason Lin21d854f2022-08-22 14:49:59 +1000751 /** @override */
752 focus() {
753 this.term.focus();
754 }
Jason Linca61ffb2022-08-03 19:37:12 +1000755
756 /** @override */
757 onOpenOptionsPage() {}
758
759 /** @override */
760 onTerminalReady() {}
761
Jason Lind04bab32022-08-22 14:48:39 +1000762 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000763 // This is for this.notificationCenter_.
764 const setHtermCSSVariable = (name, value) => {
765 document.body.style.setProperty(`--hterm-${name}`, value);
766 };
767
768 const setHtermColorCSSVariable = (name, color) => {
769 const css = lib.notNull(lib.colors.normalizeCSS(color));
770 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
771 setHtermCSSVariable(name, rgb);
772 };
773
774 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000775 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000776 setHtermCSSVariable('font-size', `${v}px`);
777 });
778
Jason Linda56aa92022-09-02 13:01:49 +1000779 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000780 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000781 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100782 this.bell_.playAudio = !!v;
783 },
784 'desktop-notification-bell': (v) => {
785 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000786 },
Jason Lind04bab32022-08-22 14:48:39 +1000787 'background-color': (v) => {
Jason Linee0c1f72022-10-18 17:17:26 +1100788 this.updateBackgroundColor_(v);
Jason Lin21d854f2022-08-22 14:49:59 +1000789 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000790 },
Jason Lind04bab32022-08-22 14:48:39 +1000791 'color-palette-overrides': (v) => {
792 if (!(v instanceof Array)) {
793 // For terminal, we always expect this to be an array.
794 console.warn('unexpected color palette: ', v);
795 return;
796 }
797 const colors = {};
798 for (let i = 0; i < v.length; ++i) {
799 colors[ANSI_COLOR_NAMES[i]] = v[i];
800 }
801 this.updateTheme_(colors);
802 },
Jason Linda56aa92022-09-02 13:01:49 +1000803 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
804 'cursor-color': (v) => this.updateTheme_({cursor: v}),
805 'cursor-shape': (v) => {
806 let shape;
807 if (v === 'BEAM') {
808 shape = 'bar';
809 } else {
810 shape = v.toLowerCase();
811 }
812 this.updateOption_('cursorStyle', shape, false);
813 },
814 'font-family': (v) => this.updateFont_(v),
815 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000816 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000817 setHtermColorCSSVariable('foreground-color', v);
818 },
Jason Linc48f7432022-10-13 17:28:30 +1100819 'line-height': (v) => this.updateOption_('lineHeight', v, true),
Jason Lin446f3d92022-10-13 17:34:21 +1100820 'scroll-on-output': (v) => {
821 if (!v) {
822 this.scrollOnOutputListener_?.dispose();
823 this.scrollOnOutputListener_ = null;
824 return;
825 }
826 if (!this.scrollOnOutputListener_) {
827 this.scrollOnOutputListener_ = this.term.onWriteParsed(
828 () => this.term.scrollToBottom());
829 }
830 },
Jason Lind04bab32022-08-22 14:48:39 +1000831 });
Jason Lin5690e752022-08-30 15:36:45 +1000832
833 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
834 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
835 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
836 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
837 }
Jason Lind04bab32022-08-22 14:48:39 +1000838 }
839
840 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000841 * Fit the terminal to the containing HTML element.
842 */
843 fit_() {
844 if (!this.inited_) {
845 return;
846 }
847
848 const screenPaddingSize = /** @type {number} */(
849 this.prefs_.get('screen-padding-size'));
850
851 const calc = (size, cellSize) => {
852 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
853 };
854
Jason Lin2649da22022-10-12 10:16:44 +1100855 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
856 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
857 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000858 if (cols >= 0 && rows >= 0) {
859 this.term.resize(cols, rows);
860 }
861 }
862
Jason Linee0c1f72022-10-18 17:17:26 +1100863 reloadWebglAddon_() {
864 if (this.webglAddon_) {
865 this.webglAddon_.dispose();
866 }
867 this.webglAddon_ = new WebglAddon();
868 this.term.loadAddon(this.webglAddon_);
869 }
870
871 /**
872 * Update the background color. This will also adjust the transparency based
873 * on whether there is a background image.
874 *
875 * @param {string} color
876 */
877 updateBackgroundColor_(color) {
878 const hasBackgroundImage = this.hasBackgroundImage();
879
880 // We only set allowTransparency when it is necessary becuase 1) xterm.js
881 // documentation states that allowTransparency can affect performance; 2) I
882 // find that the rendering is better with allowTransparency being false.
883 // This could be a bug with xterm.js.
884 if (!!this.term.options.allowTransparency !== hasBackgroundImage) {
885 this.term.options.allowTransparency = hasBackgroundImage;
886 if (this.enableWebGL_ && this.inited_) {
887 // Setting allowTransparency in the middle messes up webgl rendering,
888 // so we need to reload it here.
889 this.reloadWebglAddon_();
890 }
891 }
892
893 if (this.hasBackgroundImage()) {
894 const css = lib.notNull(lib.colors.normalizeCSS(color));
895 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
896 // Note that we still want to set the RGB part correctly even though it is
897 // completely transparent. This is because the background color without
898 // the alpha channel is used in reverse video mode.
899 color = `rgba(${rgb}, 0)`;
900 }
901
902 this.updateTheme_({background: color});
903 }
904
Jason Linc2504ae2022-09-02 13:03:31 +1000905 /**
Jason Lind04bab32022-08-22 14:48:39 +1000906 * @param {!Object} theme
907 */
908 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000909 const updateTheme = (target) => {
910 for (const [key, value] of Object.entries(theme)) {
911 target[key] = lib.colors.normalizeCSS(value);
912 }
913 };
914
915 // Must use a new theme object to trigger re-render if we have initialized.
916 if (this.inited_) {
917 const newTheme = {...this.term.options.theme};
918 updateTheme(newTheme);
919 this.term.options.theme = newTheme;
920 return;
Jason Lind04bab32022-08-22 14:48:39 +1000921 }
Jason Lin8de3d282022-09-01 21:29:05 +1000922
923 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000924 }
925
926 /**
Jason Linda56aa92022-09-02 13:01:49 +1000927 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
928 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000929 *
930 * @param {string} key
931 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000932 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000933 */
Jason Linda56aa92022-09-02 13:01:49 +1000934 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000935 // TODO: xterm supports updating multiple options at the same time. We
936 // should probably do that.
937 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000938 if (scheduleFit) {
939 this.scheduleFit_();
940 }
Jason Lind04bab32022-08-22 14:48:39 +1000941 }
Jason Linabad7562022-08-22 14:49:05 +1000942
943 /**
944 * Called when there is a "fontloadingdone" event. We need this because
945 * `FontManager.loadFont()` does not guarantee loading all the font files.
946 */
947 async onFontLoadingDone_() {
948 // If there is a pending font, the font is going to be refresh soon, so we
949 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000950 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000951 this.scheduleRefreshFont_();
952 }
953 }
954
Jason Lin5690e752022-08-30 15:36:45 +1000955 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000956 this.copyString_(this.term.getSelection());
957 }
958
959 /** @param {string} data */
960 copyString_(data) {
961 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000962 return;
963 }
Jason Line9231bc2022-09-01 13:54:02 +1000964 navigator.clipboard?.writeText(data);
Jason Lin83ef5ba2022-10-13 17:40:30 +1100965
966 if (this.prefs_.get('enable-clipboard-notice')) {
967 if (!this.copyNotice_) {
968 this.copyNotice_ = document.createElement('terminal-copy-notice');
969 }
970 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500),
971 200);
Jason Lin6a402a72022-08-25 16:07:02 +1000972 }
Jason Lin6a402a72022-08-25 16:07:02 +1000973 }
974
Jason Linabad7562022-08-22 14:49:05 +1000975 /**
976 * Refresh xterm rendering for a font related event.
977 */
978 refreshFont_() {
979 // We have to set the fontFamily option to a different string to trigger the
980 // re-rendering. Appending a space at the end seems to be the easiest
981 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
982 // us.
983 //
984 // TODO: Report a bug to xterm.js and ask for exposing a public function for
985 // the refresh so that we don't need to do this hack.
986 this.term.options.fontFamily += ' ';
987 }
988
989 /**
990 * Update a font.
991 *
992 * @param {string} cssFontFamily
993 */
994 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000995 this.pendingFont_ = cssFontFamily;
996 await this.fontManager_.loadFont(cssFontFamily);
997 // Sleep a bit to wait for flushing fontloadingdone events. This is not
998 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
999 // to refresh font unnecessarily in some cases.
1000 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +10001001
Jason Lin6a402a72022-08-25 16:07:02 +10001002 if (this.pendingFont_ !== cssFontFamily) {
1003 // `updateFont_()` probably is called again. Abort what we are doing.
1004 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
1005 ` (expecting ${cssFontFamily})`);
1006 return;
1007 }
Jason Linabad7562022-08-22 14:49:05 +10001008
Jason Lin6a402a72022-08-25 16:07:02 +10001009 if (this.term.options.fontFamily !== cssFontFamily) {
1010 this.term.options.fontFamily = cssFontFamily;
1011 } else {
1012 // If the font is already the same, refresh font just to be safe.
1013 this.refreshFont_();
1014 }
1015 this.pendingFont_ = null;
1016 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +10001017 }
Jason Lin5690e752022-08-30 15:36:45 +10001018
1019 /**
1020 * @param {!KeyboardEvent} ev
1021 * @return {boolean} Return false if xterm.js should not handle the key event.
1022 */
1023 customKeyEventHandler_(ev) {
1024 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
1025 (ev.altKey ? Modifier.Alt : 0) |
1026 (ev.ctrlKey ? Modifier.Ctrl : 0) |
1027 (ev.metaKey ? Modifier.Meta : 0);
1028 const handler = this.keyDownHandlers_.get(
1029 encodeKeyCombo(modifiers, ev.keyCode));
1030 if (handler) {
1031 if (ev.type === 'keydown') {
1032 handler(ev);
1033 }
1034 return false;
1035 }
1036
1037 return true;
1038 }
1039
1040 /**
1041 * A keydown handler for zoom-related keys.
1042 *
1043 * @param {!KeyboardEvent} ev
1044 */
1045 zoomKeyDownHandler_(ev) {
1046 ev.preventDefault();
1047
1048 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
1049 // The only one with a control code.
1050 if (ev.keyCode === keyCodes.MINUS) {
1051 this.io.onVTKeystroke('\x1f');
1052 }
1053 return;
1054 }
1055
1056 let newFontSize;
1057 switch (ev.keyCode) {
1058 case keyCodes.ZERO:
1059 newFontSize = this.prefs_.get('font-size');
1060 break;
1061 case keyCodes.MINUS:
1062 newFontSize = this.term.options.fontSize - 1;
1063 break;
1064 default:
1065 newFontSize = this.term.options.fontSize + 1;
1066 break;
1067 }
1068
Jason Linda56aa92022-09-02 13:01:49 +10001069 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +10001070 }
1071
1072 /** @param {!KeyboardEvent} ev */
1073 ctrlCKeyDownHandler_(ev) {
1074 ev.preventDefault();
1075 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
1076 this.term.hasSelection()) {
1077 this.copySelection_();
1078 return;
1079 }
1080
1081 this.io.onVTKeystroke('\x03');
1082 }
1083
1084 /** @param {!KeyboardEvent} ev */
1085 ctrlVKeyDownHandler_(ev) {
1086 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
1087 // Don't do anything and let the browser handles the key.
1088 return;
1089 }
1090
1091 ev.preventDefault();
1092 this.io.onVTKeystroke('\x16');
1093 }
1094
1095 resetKeyDownHandlers_() {
1096 this.keyDownHandlers_.clear();
1097
1098 /**
1099 * Don't do anything and let the browser handles the key.
1100 *
1101 * @param {!KeyboardEvent} ev
1102 */
1103 const noop = (ev) => {};
1104
1105 /**
1106 * @param {number} modifiers
1107 * @param {number} keyCode
1108 * @param {function(!KeyboardEvent)} func
1109 */
1110 const set = (modifiers, keyCode, func) => {
1111 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
1112 func);
1113 };
1114
1115 /**
1116 * @param {number} modifiers
1117 * @param {number} keyCode
1118 * @param {function(!KeyboardEvent)} func
1119 */
1120 const setWithShiftVersion = (modifiers, keyCode, func) => {
1121 set(modifiers, keyCode, func);
1122 set(modifiers | Modifier.Shift, keyCode, func);
1123 };
1124
Jason Lin5690e752022-08-30 15:36:45 +10001125 // Ctrl+/
1126 set(Modifier.Ctrl, 191, (ev) => {
1127 ev.preventDefault();
1128 this.io.onVTKeystroke(ctl('_'));
1129 });
1130
1131 // Settings page.
1132 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
1133 ev.preventDefault();
1134 chrome.terminalPrivate.openOptionsPage(() => {});
1135 });
1136
1137 if (this.prefs_.get('keybindings-os-defaults')) {
1138 for (const binding of OS_DEFAULT_BINDINGS) {
1139 this.keyDownHandlers_.set(binding, noop);
1140 }
1141 }
1142
1143 /** @param {!KeyboardEvent} ev */
1144 const newWindow = (ev) => {
1145 ev.preventDefault();
1146 chrome.terminalPrivate.openWindow();
1147 };
1148 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
1149 if (this.prefs_.get('pass-ctrl-n')) {
1150 set(Modifier.Ctrl, keyCodes.N, newWindow);
1151 }
1152
1153 if (this.prefs_.get('pass-ctrl-t')) {
1154 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
1155 }
1156
1157 if (this.prefs_.get('pass-ctrl-w')) {
1158 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
1159 }
1160
1161 if (this.prefs_.get('pass-ctrl-tab')) {
1162 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
1163 }
1164
1165 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
1166
1167 /**
1168 * Set a handler for the key combo ctrl+<number>.
1169 *
1170 * @param {number} number 1 to 9
1171 * @param {string} controlCode The control code to send if we don't want to
1172 * let the browser to handle it.
1173 */
1174 const setCtrlNumberHandler = (number, controlCode) => {
1175 let func = noop;
1176 if (!passCtrlNumber) {
1177 func = (ev) => {
1178 ev.preventDefault();
1179 this.io.onVTKeystroke(controlCode);
1180 };
1181 }
1182 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1183 };
1184
1185 setCtrlNumberHandler(1, '1');
1186 setCtrlNumberHandler(2, ctl('@'));
1187 setCtrlNumberHandler(3, ctl('['));
1188 setCtrlNumberHandler(4, ctl('\\'));
1189 setCtrlNumberHandler(5, ctl(']'));
1190 setCtrlNumberHandler(6, ctl('^'));
1191 setCtrlNumberHandler(7, ctl('_'));
1192 setCtrlNumberHandler(8, '\x7f');
1193 setCtrlNumberHandler(9, '9');
1194
1195 if (this.prefs_.get('pass-alt-number')) {
1196 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1197 set(Modifier.Alt, keyCode, noop);
1198 }
1199 }
1200
1201 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1202 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1203 }
1204
1205 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1206 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1207 }
Jason Linee0c1f72022-10-18 17:17:26 +11001208
1209 handleOnTerminalReady() {}
Jason Linca61ffb2022-08-03 19:37:12 +10001210}
1211
Jason Lind66e6bf2022-08-22 14:47:10 +10001212class HtermTerminal extends hterm.Terminal {
1213 /** @override */
1214 decorate(div) {
1215 super.decorate(div);
1216
Jason Linc48f7432022-10-13 17:28:30 +11001217 definePrefs(this.getPrefs());
Jason Linee0c1f72022-10-18 17:17:26 +11001218 }
Jason Linc48f7432022-10-13 17:28:30 +11001219
Jason Linee0c1f72022-10-18 17:17:26 +11001220 /**
1221 * This needs to be called in the `onTerminalReady()` callback. This is
1222 * awkward, but it is temporary since we will drop support for hterm at some
1223 * point.
1224 */
1225 handleOnTerminalReady() {
Jason Lind66e6bf2022-08-22 14:47:10 +10001226 const fontManager = new FontManager(this.getDocument());
1227 fontManager.loadPowerlineCSS().then(() => {
1228 const prefs = this.getPrefs();
1229 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1230 prefs.addObserver(
1231 'font-family',
1232 (v) => fontManager.loadFont(/** @type {string} */(v)));
1233 });
Jason Linee0c1f72022-10-18 17:17:26 +11001234
1235 const backgroundImageWatcher = new BackgroundImageWatcher(this.getPrefs(),
1236 (image) => this.setBackgroundImage(image));
1237 this.setBackgroundImage(backgroundImageWatcher.getBackgroundImage());
1238 backgroundImageWatcher.watch();
Jason Lind66e6bf2022-08-22 14:47:10 +10001239 }
Jason Lin2649da22022-10-12 10:16:44 +11001240
1241 /**
1242 * Write data to the terminal.
1243 *
1244 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1245 * UTF-8 data
1246 * @param {function()=} callback Optional callback that fires when the data
1247 * was processed by the parser.
1248 */
1249 write(data, callback) {
1250 if (typeof data === 'string') {
1251 this.io.print(data);
1252 } else {
1253 this.io.writeUTF8(data);
1254 }
1255 // Hterm processes the data synchronously, so we can call the callback
1256 // immediately.
1257 if (callback) {
1258 setTimeout(callback);
1259 }
1260 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001261}
1262
Jason Linca61ffb2022-08-03 19:37:12 +10001263/**
1264 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1265 * preference value.
1266 *
1267 * @param {{
1268 * storage: !lib.Storage,
1269 * profileId: string,
1270 * }} args
1271 * @return {!Promise<!hterm.Terminal>}
1272 */
1273export async function createEmulator({storage, profileId}) {
1274 let config = TERMINAL_EMULATORS.get('hterm');
1275
1276 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001277 // TODO: remove the url param logic. This is temporary to make manual
1278 // testing a bit easier, which is also why this is not in
1279 // './js/terminal_info.js'.
1280 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
1281 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +10001282 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001283 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001284 TERMINAL_EMULATORS.values().next().value;
1285 console.log('Terminal emulator config: ', config);
1286 }
1287
1288 switch (config.lib) {
1289 case 'xterm.js':
1290 {
1291 const terminal = new XtermTerminal({
1292 storage,
1293 profileId,
1294 enableWebGL: config.webgl,
1295 });
Jason Linca61ffb2022-08-03 19:37:12 +10001296 return terminal;
1297 }
1298 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001299 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001300 default:
1301 throw new Error('incorrect emulator config');
1302 }
1303}
1304
Jason Lin6a402a72022-08-25 16:07:02 +10001305class TerminalCopyNotice extends LitElement {
1306 /** @override */
1307 static get styles() {
1308 return css`
1309 :host {
1310 display: block;
1311 text-align: center;
1312 }
1313
1314 svg {
1315 fill: currentColor;
1316 }
1317 `;
1318 }
1319
1320 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001321 connectedCallback() {
1322 super.connectedCallback();
1323 if (!this.childNodes.length) {
1324 // This is not visible since we use shadow dom. But this will allow the
1325 // hterm.NotificationCenter to announce the the copy text.
1326 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1327 }
1328 }
1329
1330 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001331 render() {
1332 return html`
1333 ${ICON_COPY}
1334 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1335 `;
1336 }
1337}
1338
1339customElements.define('terminal-copy-notice', TerminalCopyNotice);