blob: 83583a07d1b5fabd67bc218af6da2921de02a90c [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';
Joel Hockey0e164f02023-03-26 15:58:12 -070017import {FontManager, ORIGINAL_URL, TERMINAL_EMULATORS,
18 backgroundImageLocalStorageKey, definePrefs, delayedScheduler, fontManager,
19 getOSInfo, sleep}
20 from './terminal_common.js';
Jason Lin82ba86c2022-11-09 12:12:27 +110021import {TerminalContextMenu} from './terminal_context_menu.js';
Jason Lin6a402a72022-08-25 16:07:02 +100022import {ICON_COPY} from './terminal_icons.js';
Jason Lin83707c92022-09-20 19:09:41 +100023import {TerminalTooltip} from './terminal_tooltip.js';
Jason Linc2504ae2022-09-02 13:03:31 +100024import {Terminal, Unicode11Addon, WebLinksAddon, WebglAddon}
Joel Hockey0e164f02023-03-26 15:58:12 -070025 from './xterm.js';
Jason Lin2649da22022-10-12 10:16:44 +110026import {XtermInternal} from './terminal_xterm_internal.js';
Jason Linca61ffb2022-08-03 19:37:12 +100027
Jason Lin5690e752022-08-30 15:36:45 +100028
29/** @enum {number} */
30export const Modifier = {
31 Shift: 1 << 0,
32 Alt: 1 << 1,
33 Ctrl: 1 << 2,
34 Meta: 1 << 3,
35};
36
37// This is just a static map from key names to key codes. It helps make the code
38// a bit more readable.
Jason Lin97a04282023-03-06 10:36:56 +110039export const keyCodes = hterm.Parser.identifiers.keyCodes;
Jason Lin5690e752022-08-30 15:36:45 +100040
41/**
42 * Encode a key combo (i.e. modifiers + a normal key) to an unique number.
43 *
44 * @param {number} modifiers
45 * @param {number} keyCode
46 * @return {number}
47 */
48export function encodeKeyCombo(modifiers, keyCode) {
49 return keyCode << 4 | modifiers;
50}
51
52const OS_DEFAULT_BINDINGS = [
53 // Submit feedback.
54 encodeKeyCombo(Modifier.Alt | Modifier.Shift, keyCodes.I),
55 // Toggle chromevox.
56 encodeKeyCombo(Modifier.Ctrl | Modifier.Alt, keyCodes.Z),
57 // Switch input method.
58 encodeKeyCombo(Modifier.Ctrl, keyCodes.SPACE),
59
60 // Dock window left/right.
61 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_LEFT),
62 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_RIGHT),
63
64 // Maximize/minimize window.
65 encodeKeyCombo(Modifier.Alt, keyCodes.EQUAL),
66 encodeKeyCombo(Modifier.Alt, keyCodes.MINUS),
67];
68
69
Jason Linca61ffb2022-08-03 19:37:12 +100070const ANSI_COLOR_NAMES = [
71 'black',
72 'red',
73 'green',
74 'yellow',
75 'blue',
76 'magenta',
77 'cyan',
78 'white',
79 'brightBlack',
80 'brightRed',
81 'brightGreen',
82 'brightYellow',
83 'brightBlue',
84 'brightMagenta',
85 'brightCyan',
86 'brightWhite',
87];
88
Jason Linca61ffb2022-08-03 19:37:12 +100089/**
Jason Lin97a04282023-03-06 10:36:56 +110090 * The value is the CSI code to send when no modifier keys are pressed.
91 *
92 * @type {!Map<number, string>}
93 */
94const ARROW_AND_SIX_PACK_KEYS = new Map([
95 [keyCodes.UP, '\x1b[A'],
96 [keyCodes.DOWN, '\x1b[B'],
97 [keyCodes.RIGHT, '\x1b[C'],
98 [keyCodes.LEFT, '\x1b[D'],
99 // 6-pack keys.
100 [keyCodes.INSERT, '\x1b[2~'],
101 [keyCodes.DEL, '\x1b[3~'],
102 [keyCodes.HOME, '\x1b[H'],
103 [keyCodes.END, '\x1b[F'],
104 [keyCodes.PAGE_UP, '\x1b[5~'],
105 [keyCodes.PAGE_DOWN, '\x1b[6~'],
106]);
107
108/**
Jason Linabad7562022-08-22 14:49:05 +1000109 * @typedef {{
110 * term: !Terminal,
111 * fontManager: !FontManager,
Jason Lin2649da22022-10-12 10:16:44 +1100112 * xtermInternal: !XtermInternal,
Jason Linabad7562022-08-22 14:49:05 +1000113 * }}
114 */
115export let XtermTerminalTestParams;
116
117/**
Jason Lin5690e752022-08-30 15:36:45 +1000118 * Compute a control character for a given character.
119 *
120 * @param {string} ch
121 * @return {string}
122 */
123function ctl(ch) {
124 return String.fromCharCode(ch.charCodeAt(0) - 64);
125}
126
127/**
Jason Lin21d854f2022-08-22 14:49:59 +1000128 * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO
129 * because it always convert utf8 data to strings, which is not necessary for
130 * xterm.
131 */
132class XtermTerminalIO extends hterm.Terminal.IO {
133 /** @override */
134 writeUTF8(buffer) {
135 this.terminal_.write(new Uint8Array(buffer));
136 }
137
138 /** @override */
139 writelnUTF8(buffer) {
140 this.terminal_.writeln(new Uint8Array(buffer));
141 }
142
143 /** @override */
144 print(string) {
145 this.terminal_.write(string);
146 }
147
148 /** @override */
149 writeUTF16(string) {
150 this.print(string);
151 }
152
153 /** @override */
154 println(string) {
155 this.terminal_.writeln(string);
156 }
157
158 /** @override */
159 writelnUTF16(string) {
160 this.println(string);
161 }
162}
163
164/**
Jason Lin83707c92022-09-20 19:09:41 +1000165 * A custom link handler that:
166 *
167 * - Shows a tooltip with the url on a OSC 8 link. This is following what hterm
168 * is doing. Also, showing the tooltip is better for the security of the user
169 * because the link can have arbitrary text.
170 * - Uses our own way to open the window.
171 */
172class LinkHandler {
173 /**
174 * @param {!Terminal} term
175 */
176 constructor(term) {
177 this.term_ = term;
178 /** @type {?TerminalTooltip} */
179 this.tooltip_ = null;
180 }
181
182 /**
183 * @return {!TerminalTooltip}
184 */
185 getTooltip_() {
186 if (!this.tooltip_) {
187 this.tooltip_ = /** @type {!TerminalTooltip} */(
188 document.createElement('terminal-tooltip'));
189 this.tooltip_.classList.add('xterm-hover');
190 lib.notNull(this.term_.element).appendChild(this.tooltip_);
191 }
192 return this.tooltip_;
193 }
194
195 /**
196 * @param {!MouseEvent} ev
197 * @param {string} url
198 * @param {!Object} range
199 */
200 activate(ev, url, range) {
201 lib.f.openWindow(url, '_blank');
202 }
203
204 /**
205 * @param {!MouseEvent} ev
206 * @param {string} url
207 * @param {!Object} range
208 */
209 hover(ev, url, range) {
210 this.getTooltip_().show(url, {x: ev.clientX, y: ev.clientY});
211 }
212
213 /**
214 * @param {!MouseEvent} ev
215 * @param {string} url
216 * @param {!Object} range
217 */
218 leave(ev, url, range) {
219 this.getTooltip_().hide();
220 }
221}
222
Jason Linc7afb672022-10-11 15:54:17 +1100223class Bell {
224 constructor() {
225 this.showNotification = false;
226
227 /** @type {?Audio} */
228 this.audio_ = null;
229 /** @type {?Notification} */
230 this.notification_ = null;
231 this.coolDownUntil_ = 0;
232 }
233
234 /**
235 * Set whether a bell audio should be played.
236 *
237 * @param {boolean} value
238 */
239 set playAudio(value) {
240 this.audio_ = value ?
241 new Audio(lib.resource.getDataUrl('hterm/audio/bell')) : null;
242 }
243
244 ring() {
245 const now = Date.now();
246 if (now < this.coolDownUntil_) {
247 return;
248 }
249 this.coolDownUntil_ = now + 500;
250
251 this.audio_?.play();
252 if (this.showNotification && !document.hasFocus() && !this.notification_) {
253 this.notification_ = new Notification(
254 `\u266A ${document.title} \u266A`,
255 {icon: lib.resource.getDataUrl('hterm/images/icon-96')});
256 // Close the notification after a timeout. Note that this is different
257 // from hterm's behavior, but I think it makes more sense to do so.
258 setTimeout(() => {
259 this.notification_.close();
260 this.notification_ = null;
261 }, 5000);
262 }
263 }
264}
265
Jason Lind3aacef2022-10-12 19:03:37 +1100266const A11Y_BUTTON_STYLE = `
267position: fixed;
268z-index: 10;
269right: 16px;
270`;
271
Jason Lina8adea52022-10-25 13:14:14 +1100272// TODO: we should subscribe to the xterm.js onscroll event, and
273// disable/enable the buttons accordingly. However, xterm.js does not seem to
274// emit the onscroll event when the viewport is scrolled by the mouse. See
275// https://github.com/xtermjs/xterm.js/issues/3864
276export class A11yButtons {
Jason Lind3aacef2022-10-12 19:03:37 +1100277 /**
278 * @param {!Terminal} term
Jason Lina8adea52022-10-25 13:14:14 +1100279 * @param {!hterm.AccessibilityReader} htermA11yReader
Jason Lind3aacef2022-10-12 19:03:37 +1100280 */
Jason Linc0f14fe2022-10-25 15:31:29 +1100281 constructor(term, htermA11yReader) {
Jason Lina8adea52022-10-25 13:14:14 +1100282 this.term_ = term;
283 this.htermA11yReader_ = htermA11yReader;
Jason Linc0f14fe2022-10-25 15:31:29 +1100284 this.pageUpButton = document.createElement('button');
285 this.pageUpButton.style.cssText = A11Y_BUTTON_STYLE;
286 this.pageUpButton.textContent =
Jason Lind3aacef2022-10-12 19:03:37 +1100287 hterm.messageManager.get('HTERM_BUTTON_PAGE_UP');
Jason Linc0f14fe2022-10-25 15:31:29 +1100288 this.pageUpButton.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100289 () => this.scrollPages_(-1));
Jason Lind3aacef2022-10-12 19:03:37 +1100290
Jason Linc0f14fe2022-10-25 15:31:29 +1100291 this.pageDownButton = document.createElement('button');
292 this.pageDownButton.style.cssText = A11Y_BUTTON_STYLE;
293 this.pageDownButton.textContent =
Jason Lind3aacef2022-10-12 19:03:37 +1100294 hterm.messageManager.get('HTERM_BUTTON_PAGE_DOWN');
Jason Linc0f14fe2022-10-25 15:31:29 +1100295 this.pageDownButton.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100296 () => this.scrollPages_(1));
Jason Lind3aacef2022-10-12 19:03:37 +1100297
298 this.resetPos_();
Jason Lind3aacef2022-10-12 19:03:37 +1100299
300 this.onSelectionChange_ = this.onSelectionChange_.bind(this);
301 }
302
303 /**
Jason Lina8adea52022-10-25 13:14:14 +1100304 * @param {number} amount
305 */
306 scrollPages_(amount) {
307 this.term_.scrollPages(amount);
308 this.announceScreenContent_();
309 }
310
311 announceScreenContent_() {
312 const activeBuffer = this.term_.buffer.active;
313
314 let percentScrolled = 100;
315 if (activeBuffer.baseY !== 0) {
316 percentScrolled = Math.round(
317 100 * activeBuffer.viewportY / activeBuffer.baseY);
318 }
319
320 let currentScreenContent = hterm.messageManager.get(
321 'HTERM_ANNOUNCE_CURRENT_SCREEN_HEADER',
322 [percentScrolled],
323 '$1% scrolled,');
324
325 currentScreenContent += '\n';
326
327 const rowEnd = Math.min(activeBuffer.viewportY + this.term_.rows,
328 activeBuffer.length);
329 for (let i = activeBuffer.viewportY; i < rowEnd; ++i) {
330 currentScreenContent +=
331 activeBuffer.getLine(i).translateToString(true) + '\n';
332 }
333 currentScreenContent = currentScreenContent.trim();
334
335 this.htermA11yReader_.assertiveAnnounce(currentScreenContent);
336 }
337
338 /**
Jason Lind3aacef2022-10-12 19:03:37 +1100339 * @param {boolean} enabled
340 */
341 setEnabled(enabled) {
342 if (enabled) {
343 document.addEventListener('selectionchange', this.onSelectionChange_);
344 } else {
345 this.resetPos_();
346 document.removeEventListener('selectionchange', this.onSelectionChange_);
347 }
348 }
349
350 resetPos_() {
Jason Linc0f14fe2022-10-25 15:31:29 +1100351 this.pageUpButton.style.top = '-200px';
352 this.pageDownButton.style.bottom = '-200px';
Jason Lind3aacef2022-10-12 19:03:37 +1100353 }
354
355 onSelectionChange_() {
356 this.resetPos_();
357
Jason Lin36b9fce2022-11-10 16:56:40 +1100358 const selectedElement = document.getSelection().anchorNode?.parentElement;
Jason Linc0f14fe2022-10-25 15:31:29 +1100359 if (selectedElement === this.pageUpButton) {
360 this.pageUpButton.style.top = '16px';
361 } else if (selectedElement === this.pageDownButton) {
362 this.pageDownButton.style.bottom = '16px';
Jason Lind3aacef2022-10-12 19:03:37 +1100363 }
364 }
365}
366
Jason Linee0c1f72022-10-18 17:17:26 +1100367const BACKGROUND_IMAGE_KEY = 'background-image';
368
369class BackgroundImageWatcher {
370 /**
371 * @param {!hterm.PreferenceManager} prefs
372 * @param {function(string)} onChange This is called with the background image
373 * (could be empty) whenever it changes.
374 */
375 constructor(prefs, onChange) {
376 this.prefs_ = prefs;
377 this.onChange_ = onChange;
Joel Hockey0e164f02023-03-26 15:58:12 -0700378 this.localStorageKey_ = backgroundImageLocalStorageKey(prefs);
Jason Linee0c1f72022-10-18 17:17:26 +1100379 }
380
381 /**
382 * Call once to start watching for background image changes.
383 */
384 watch() {
385 window.addEventListener('storage', (e) => {
Joel Hockey0e164f02023-03-26 15:58:12 -0700386 if (e.key === this.localStorageKey_) {
Jason Linee0c1f72022-10-18 17:17:26 +1100387 this.onChange_(this.getBackgroundImage());
388 }
389 });
390 this.prefs_.addObserver(BACKGROUND_IMAGE_KEY, () => {
391 this.onChange_(this.getBackgroundImage());
392 });
393 }
394
395 getBackgroundImage() {
Joel Hockey0e164f02023-03-26 15:58:12 -0700396 const image = window.localStorage.getItem(this.localStorageKey_);
Jason Linee0c1f72022-10-18 17:17:26 +1100397 if (image) {
398 return `url(${image})`;
399 }
400
401 return this.prefs_.getString(BACKGROUND_IMAGE_KEY);
402 }
403}
404
Jason Linb8f380a2022-10-25 13:15:56 +1100405let xtermTerminalStringsLoaded = false;
406
Jason Lin83707c92022-09-20 19:09:41 +1000407/**
Jason Linca61ffb2022-08-03 19:37:12 +1000408 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
409 * so that it can be used in existing code.
410 *
Jason Linca61ffb2022-08-03 19:37:12 +1000411 * @extends {hterm.Terminal}
412 * @unrestricted
413 */
Jason Linabad7562022-08-22 14:49:05 +1000414export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000415 /**
416 * @param {{
417 * storage: !lib.Storage,
418 * profileId: string,
419 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000420 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000421 * }} args
422 */
Jason Linabad7562022-08-22 14:49:05 +1000423 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000424 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
425 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
426 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
427
Jason Lin8de3d282022-09-01 21:29:05 +1000428 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000429 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000430 /** @type {!hterm.PreferenceManager} */
431 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
Jason Linc48f7432022-10-13 17:28:30 +1100432 definePrefs(this.prefs_);
Jason Linca61ffb2022-08-03 19:37:12 +1000433 this.enableWebGL_ = enableWebGL;
434
Jason Lin5690e752022-08-30 15:36:45 +1000435 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linfc8a3722022-09-07 17:49:18 +1000436 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Lin2649da22022-10-12 10:16:44 +1100437 this.xtermInternal_ = testParams?.xtermInternal ||
438 new XtermInternal(this.term);
Jason Linabad7562022-08-22 14:49:05 +1000439 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000440
Jason Linc2504ae2022-09-02 13:03:31 +1000441 /** @type {?Element} */
442 this.container_;
Jason Linc7afb672022-10-11 15:54:17 +1100443 this.bell_ = new Bell();
Jason Linc2504ae2022-09-02 13:03:31 +1000444 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000445 testParams ? 0 : 250);
446
Jason Lin83707c92022-09-20 19:09:41 +1000447 this.term.loadAddon(
448 new WebLinksAddon((e, uri) => lib.f.openWindow(uri, '_blank')));
Jason Lin4de4f382022-09-01 14:10:18 +1000449 this.term.loadAddon(new Unicode11Addon());
450 this.term.unicode.activeVersion = '11';
451
Jason Linabad7562022-08-22 14:49:05 +1000452 this.pendingFont_ = null;
453 this.scheduleRefreshFont_ = delayedScheduler(
454 () => this.refreshFont_(), 100);
455 document.fonts.addEventListener('loadingdone',
456 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000457
458 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000459 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000460
Jason Lin34a45322022-10-12 19:10:52 +1100461 this.term.onResize(({cols, rows}) => {
462 this.io.onTerminalResize(cols, rows);
463 if (this.prefs_.get('enable-resize-status')) {
464 this.showOverlay(`${cols} × ${rows}`);
465 }
466 });
Jason Lin21d854f2022-08-22 14:49:59 +1000467 // We could also use `this.io.sendString()` except for the nassh exit
468 // prompt, which only listens to onVTKeystroke().
469 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000470 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100471 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin83ef5ba2022-10-13 17:40:30 +1100472 this.term.onSelectionChange(() => {
473 if (this.prefs_.get('copy-on-select')) {
474 this.copySelection_();
475 }
476 });
Jason Linc7afb672022-10-11 15:54:17 +1100477 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000478
479 /**
480 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
481 *
482 * If a key combo is in the map:
483 *
484 * - The handler instead of xterm.js will handle the keydown event.
485 * - Keyup and keypress will be ignored by both us and xterm.js.
486 *
487 * We re-generate this map every time a relevant pref value is changed. This
488 * is ok because pref changes are rare.
489 *
490 * @type {!Map<number, function(!KeyboardEvent)>}
491 */
492 this.keyDownHandlers_ = new Map();
493 this.scheduleResetKeyDownHandlers_ =
494 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
495
Jason Lin97a04282023-03-06 10:36:56 +1100496 this.term.attachCustomKeyEventHandler((ev) => !this.handleKeyEvent_(ev));
Jason Linca61ffb2022-08-03 19:37:12 +1000497
Jason Lin21d854f2022-08-22 14:49:59 +1000498 this.io = new XtermTerminalIO(this);
499 this.notificationCenter_ = null;
Jason Lind3aacef2022-10-12 19:03:37 +1100500 this.htermA11yReader_ = null;
Jason Linc0f14fe2022-10-25 15:31:29 +1100501 this.a11yEnabled_ = false;
Jason Lind3aacef2022-10-12 19:03:37 +1100502 this.a11yButtons_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000503 this.copyNotice_ = null;
Jason Lin446f3d92022-10-13 17:34:21 +1100504 this.scrollOnOutputListener_ = null;
Jason Linee0c1f72022-10-18 17:17:26 +1100505 this.backgroundImageWatcher_ = new BackgroundImageWatcher(this.prefs_,
506 this.setBackgroundImage.bind(this));
507 this.webglAddon_ = null;
Jason Lina63d8ba2022-11-02 17:42:38 +1100508 this.userCSSElement_ = null;
509 this.userCSSTextElement_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000510
Jason Lin82ba86c2022-11-09 12:12:27 +1100511 this.contextMenu_ = /** @type {!TerminalContextMenu} */(
512 document.createElement('terminal-context-menu'));
513 this.contextMenu_.style.zIndex = 10;
514 this.contextMenu = {
515 setItems: (items) => this.contextMenu_.items = items,
516 };
517
Jason Lin83707c92022-09-20 19:09:41 +1000518 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000519 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000520 // The webgl cursor layer also paints the character under the cursor with
521 // this `cursorAccent` color. We use a completely transparent color here
522 // to effectively disable that.
523 cursorAccent: 'rgba(0, 0, 0, 0)',
524 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000525 selectionBackground: 'rgba(174, 203, 250, .6)',
526 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000527 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000528 };
529 this.observePrefs_();
Jason Linb8f380a2022-10-25 13:15:56 +1100530 if (!xtermTerminalStringsLoaded) {
531 xtermTerminalStringsLoaded = true;
532 Terminal.strings.promptLabel =
533 hterm.messageManager.get('TERMINAL_INPUT_LABEL');
534 Terminal.strings.tooMuchOutput =
535 hterm.messageManager.get('TERMINAL_TOO_MUCH_OUTPUT_MESSAGE');
536 }
Jason Linca61ffb2022-08-03 19:37:12 +1000537 }
538
Jason Linc7afb672022-10-11 15:54:17 +1100539 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100540 setWindowTitle(title) {
541 document.title = title;
542 }
543
544 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100545 ringBell() {
546 this.bell_.ring();
547 }
548
Jason Lin2649da22022-10-12 10:16:44 +1100549 /** @override */
550 print(str) {
551 this.xtermInternal_.print(str);
552 }
553
554 /** @override */
555 wipeContents() {
556 this.term.clear();
557 }
558
559 /** @override */
560 newLine() {
561 this.xtermInternal_.newLine();
562 }
563
564 /** @override */
565 cursorLeft(number) {
566 this.xtermInternal_.cursorLeft(number ?? 1);
567 }
568
Jason Lind3aacef2022-10-12 19:03:37 +1100569 /** @override */
570 setAccessibilityEnabled(enabled) {
Jason Linc0f14fe2022-10-25 15:31:29 +1100571 if (enabled === this.a11yEnabled_) {
572 return;
573 }
574 this.a11yEnabled_ = enabled;
575
Jason Lind3aacef2022-10-12 19:03:37 +1100576 this.a11yButtons_.setEnabled(enabled);
577 this.htermA11yReader_.setAccessibilityEnabled(enabled);
Jason Linc0f14fe2022-10-25 15:31:29 +1100578
579 if (enabled) {
580 this.xtermInternal_.enableA11y(this.a11yButtons_.pageUpButton,
581 this.a11yButtons_.pageDownButton);
582 } else {
583 this.xtermInternal_.disableA11y();
584 }
Jason Lind3aacef2022-10-12 19:03:37 +1100585 }
586
Jason Linee0c1f72022-10-18 17:17:26 +1100587 hasBackgroundImage() {
588 return !!this.container_.style.backgroundImage;
589 }
590
591 /** @override */
592 setBackgroundImage(image) {
593 this.container_.style.backgroundImage = image || '';
594 this.updateBackgroundColor_(this.prefs_.getString('background-color'));
595 }
596
Jason Linca61ffb2022-08-03 19:37:12 +1000597 /**
598 * Install stubs for stuff that we haven't implemented yet so that the code
599 * still runs.
600 */
601 installUnimplementedStubs_() {
602 this.keyboard = {
603 keyMap: {
604 keyDefs: [],
605 },
606 bindings: {
607 clear: () => {},
608 addBinding: () => {},
609 addBindings: () => {},
610 OsDefaults: {},
611 },
612 };
613 this.keyboard.keyMap.keyDefs[78] = {};
Joel Hockey965ea552023-02-19 22:08:04 -0800614 this.keyboard.keyMap.keyDefs[84] = {};
Jason Linca61ffb2022-08-03 19:37:12 +1000615
616 const methodNames = [
Joel Hockeyb89a9782022-10-16 22:00:12 -0700617 'eraseLine',
Joel Hockeyb89a9782022-10-16 22:00:12 -0700618 'setCursorColumn',
Jason Linca61ffb2022-08-03 19:37:12 +1000619 'setCursorPosition',
620 'setCursorVisible',
Joel Hockeyd78374f2022-11-02 23:05:53 -0700621 'uninstallKeyboard',
Jason Linca61ffb2022-08-03 19:37:12 +1000622 ];
623
624 for (const name of methodNames) {
625 this[name] = () => console.warn(`${name}() is not implemented`);
626 }
627
Jason Lin21d854f2022-08-22 14:49:59 +1000628 this.vt = {
629 resetParseState: () => {
630 console.warn('.vt.resetParseState() is not implemented');
631 },
632 };
Jason Linca61ffb2022-08-03 19:37:12 +1000633 }
634
Jason Line9231bc2022-09-01 13:54:02 +1000635 installEscapeSequenceHandlers_() {
636 // OSC 52 for copy.
637 this.term.parser.registerOscHandler(52, (args) => {
638 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
639 // parameter is used to select which of the X clipboards to address. Since
640 // we're not integrating with X, we treat them all the same.
641 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
642 if (!parsedArgs) {
643 return true;
644 }
645
646 let data;
647 try {
648 data = window.atob(parsedArgs[1]);
649 } catch (e) {
650 // If the user sent us invalid base64 content, silently ignore it.
651 return true;
652 }
653 const decoder = new TextDecoder();
654 const bytes = lib.codec.stringToCodeUnitArray(data);
655 this.copyString_(decoder.decode(bytes));
656
657 return true;
658 });
Jason Lin2649da22022-10-12 10:16:44 +1100659
660 this.xtermInternal_.installTmuxControlModeHandler(
661 (data) => this.onTmuxControlModeLine(data));
662 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000663 }
664
Jason Linca61ffb2022-08-03 19:37:12 +1000665 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000666 * Write data to the terminal.
667 *
668 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
669 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100670 * @param {function()=} callback Optional callback that fires when the data
671 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000672 */
Jason Lin2649da22022-10-12 10:16:44 +1100673 write(data, callback) {
674 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000675 }
676
677 /**
678 * Like `this.write()` but also write a line break.
679 *
680 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100681 * @param {function()=} callback Optional callback that fires when the data
682 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000683 */
Jason Lin2649da22022-10-12 10:16:44 +1100684 writeln(data, callback) {
685 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000686 }
687
Jason Linca61ffb2022-08-03 19:37:12 +1000688 get screenSize() {
689 return new hterm.Size(this.term.cols, this.term.rows);
690 }
691
692 /**
693 * Don't need to do anything.
694 *
695 * @override
696 */
697 installKeyboard() {}
698
699 /**
700 * @override
701 */
702 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000703 this.container_ = elem;
Jason Linee0c1f72022-10-18 17:17:26 +1100704 elem.style.backgroundSize = '100% 100%';
705
Jason Lin8de3d282022-09-01 21:29:05 +1000706 (async () => {
707 await new Promise((resolve) => this.prefs_.readStorage(resolve));
708 // This will trigger all the observers to set the terminal options before
709 // we call `this.term.open()`.
710 this.prefs_.notifyAll();
711
Jason Linc2504ae2022-09-02 13:03:31 +1000712 const screenPaddingSize = /** @type {number} */(
713 this.prefs_.get('screen-padding-size'));
714 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
715
Jason Linee0c1f72022-10-18 17:17:26 +1100716 this.setBackgroundImage(
717 this.backgroundImageWatcher_.getBackgroundImage());
718 this.backgroundImageWatcher_.watch();
719
Jason Lin8de3d282022-09-01 21:29:05 +1000720 this.inited_ = true;
721 this.term.open(elem);
Jason Lin1be92f52023-01-23 23:50:00 +1100722 this.xtermInternal_.addDimensionsObserver(() => this.scheduleFit_());
Jason Lin8de3d282022-09-01 21:29:05 +1000723
Jason Lin8de3d282022-09-01 21:29:05 +1000724 if (this.enableWebGL_) {
Jason Linee0c1f72022-10-18 17:17:26 +1100725 this.reloadWebglAddon_();
Jason Lin8de3d282022-09-01 21:29:05 +1000726 }
727 this.term.focus();
728 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100729 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
730 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
731 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000732
Jason Lin82ba86c2022-11-09 12:12:27 +1100733 elem.appendChild(this.contextMenu_);
734
Jason Lin932b7432022-12-07 16:51:54 +1100735 elem.addEventListener('dragover', (e) => e.preventDefault());
736 elem.addEventListener('drop',
737 (e) => this.onDrop_(/** @type {!DragEvent} */(e)));
738
Jason Lin82ba86c2022-11-09 12:12:27 +1100739 // Block the default context menu from popping up.
Emil Mikulic2a194d02022-09-29 14:30:59 +1000740 elem.addEventListener('contextmenu', (e) => e.preventDefault());
741
742 // Add a handler for pasting with the mouse.
Jason Lin932b7432022-12-07 16:51:54 +1100743 elem.addEventListener('mousedown',
744 (e) => this.onMouseDown_(/** @type {!MouseEvent} */(e)));
Emil Mikulic2a194d02022-09-29 14:30:59 +1000745
Jason Lin2649da22022-10-12 10:16:44 +1100746 await this.scheduleFit_();
Jason Linc0f14fe2022-10-25 15:31:29 +1100747 this.a11yButtons_ = new A11yButtons(this.term, this.htermA11yReader_);
Jason Lin23b4cef2023-03-06 10:25:29 +1100748 if (!this.prefs_.get('scrollbar-visible')) {
749 this.xtermInternal_.setScrollbarVisible(false);
750 }
Jason Lind3aacef2022-10-12 19:03:37 +1100751
Jason Lin8de3d282022-09-01 21:29:05 +1000752 this.onTerminalReady();
753 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000754 }
755
756 /** @override */
757 showOverlay(msg, timeout = 1500) {
Jason Lin34a45322022-10-12 19:10:52 +1100758 this.notificationCenter_?.show(msg, {timeout});
Jason Lin21d854f2022-08-22 14:49:59 +1000759 }
760
761 /** @override */
762 hideOverlay() {
Jason Lin34a45322022-10-12 19:10:52 +1100763 this.notificationCenter_?.hide();
Jason Linca61ffb2022-08-03 19:37:12 +1000764 }
765
766 /** @override */
767 getPrefs() {
768 return this.prefs_;
769 }
770
771 /** @override */
772 getDocument() {
773 return window.document;
774 }
775
Jason Lin21d854f2022-08-22 14:49:59 +1000776 /** @override */
777 reset() {
778 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000779 }
780
781 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000782 setProfile(profileId, callback = undefined) {
783 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000784 }
785
Jason Lin21d854f2022-08-22 14:49:59 +1000786 /** @override */
787 interpret(string) {
788 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000789 }
790
Jason Lin21d854f2022-08-22 14:49:59 +1000791 /** @override */
792 focus() {
793 this.term.focus();
794 }
Jason Linca61ffb2022-08-03 19:37:12 +1000795
796 /** @override */
797 onOpenOptionsPage() {}
798
799 /** @override */
800 onTerminalReady() {}
801
Jason Lind04bab32022-08-22 14:48:39 +1000802 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000803 // This is for this.notificationCenter_.
804 const setHtermCSSVariable = (name, value) => {
805 document.body.style.setProperty(`--hterm-${name}`, value);
806 };
807
808 const setHtermColorCSSVariable = (name, color) => {
809 const css = lib.notNull(lib.colors.normalizeCSS(color));
810 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
811 setHtermCSSVariable(name, rgb);
812 };
813
814 this.prefs_.addObserver('font-size', (v) => {
Jason Lin1be92f52023-01-23 23:50:00 +1100815 this.term.options.fontSize = v;
Jason Lin21d854f2022-08-22 14:49:59 +1000816 setHtermCSSVariable('font-size', `${v}px`);
817 });
818
Jason Linda56aa92022-09-02 13:01:49 +1000819 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000820 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000821 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100822 this.bell_.playAudio = !!v;
823 },
824 'desktop-notification-bell': (v) => {
825 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000826 },
Jason Lind04bab32022-08-22 14:48:39 +1000827 'background-color': (v) => {
Jason Linee0c1f72022-10-18 17:17:26 +1100828 this.updateBackgroundColor_(v);
Jason Lin21d854f2022-08-22 14:49:59 +1000829 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000830 },
Jason Lind04bab32022-08-22 14:48:39 +1000831 'color-palette-overrides': (v) => {
832 if (!(v instanceof Array)) {
833 // For terminal, we always expect this to be an array.
834 console.warn('unexpected color palette: ', v);
835 return;
836 }
837 const colors = {};
838 for (let i = 0; i < v.length; ++i) {
839 colors[ANSI_COLOR_NAMES[i]] = v[i];
840 }
841 this.updateTheme_(colors);
842 },
Jason Lin1be92f52023-01-23 23:50:00 +1100843 'cursor-blink': (v) => {
844 this.term.options.cursorBlink = v;
845 },
Jason Linda56aa92022-09-02 13:01:49 +1000846 'cursor-color': (v) => this.updateTheme_({cursor: v}),
847 'cursor-shape': (v) => {
848 let shape;
849 if (v === 'BEAM') {
850 shape = 'bar';
851 } else {
852 shape = v.toLowerCase();
853 }
Jason Lin1be92f52023-01-23 23:50:00 +1100854 this.term.options.cursorStyle = shape;
Jason Linda56aa92022-09-02 13:01:49 +1000855 },
856 'font-family': (v) => this.updateFont_(v),
857 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000858 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000859 setHtermColorCSSVariable('foreground-color', v);
860 },
Jason Lin1be92f52023-01-23 23:50:00 +1100861 'line-height': (v) => {
862 this.term.options.lineHeight = v;
863 },
Jason Lin471e1062022-12-08 15:39:15 +1100864 'scroll-on-keystroke': (v) => {
Jason Lin1be92f52023-01-23 23:50:00 +1100865 this.term.options.scrollOnUserInput = v;
Jason Lin471e1062022-12-08 15:39:15 +1100866 },
Jason Lin446f3d92022-10-13 17:34:21 +1100867 'scroll-on-output': (v) => {
868 if (!v) {
869 this.scrollOnOutputListener_?.dispose();
870 this.scrollOnOutputListener_ = null;
871 return;
872 }
873 if (!this.scrollOnOutputListener_) {
874 this.scrollOnOutputListener_ = this.term.onWriteParsed(
875 () => this.term.scrollToBottom());
876 }
877 },
Jason Lin23b4cef2023-03-06 10:25:29 +1100878 'scrollbar-visible': (v) => {
879 this.xtermInternal_.setScrollbarVisible(v);
880 },
Jason Lina63d8ba2022-11-02 17:42:38 +1100881 'user-css': (v) => {
882 if (this.userCSSElement_) {
883 this.userCSSElement_.remove();
884 }
885 if (v) {
886 this.userCSSElement_ = document.createElement('link');
887 this.userCSSElement_.setAttribute('rel', 'stylesheet');
888 this.userCSSElement_.setAttribute('href', v);
889 document.head.appendChild(this.userCSSElement_);
890 }
891 },
892 'user-css-text': (v) => {
893 if (!this.userCSSTextElement_) {
894 this.userCSSTextElement_ = document.createElement('style');
895 document.head.appendChild(this.userCSSTextElement_);
896 }
897 this.userCSSTextElement_.textContent = v;
898 },
Jason Lind04bab32022-08-22 14:48:39 +1000899 });
Jason Lin5690e752022-08-30 15:36:45 +1000900
901 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
902 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
903 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
904 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
905 }
Jason Lind04bab32022-08-22 14:48:39 +1000906 }
907
908 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000909 * Fit the terminal to the containing HTML element.
910 */
911 fit_() {
912 if (!this.inited_) {
913 return;
914 }
915
916 const screenPaddingSize = /** @type {number} */(
917 this.prefs_.get('screen-padding-size'));
918
919 const calc = (size, cellSize) => {
920 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
921 };
922
Jason Lin2649da22022-10-12 10:16:44 +1100923 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
924 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
925 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000926 if (cols >= 0 && rows >= 0) {
927 this.term.resize(cols, rows);
928 }
929 }
930
Jason Linee0c1f72022-10-18 17:17:26 +1100931 reloadWebglAddon_() {
932 if (this.webglAddon_) {
933 this.webglAddon_.dispose();
934 }
935 this.webglAddon_ = new WebglAddon();
936 this.term.loadAddon(this.webglAddon_);
937 }
938
939 /**
940 * Update the background color. This will also adjust the transparency based
941 * on whether there is a background image.
942 *
943 * @param {string} color
944 */
945 updateBackgroundColor_(color) {
946 const hasBackgroundImage = this.hasBackgroundImage();
947
948 // We only set allowTransparency when it is necessary becuase 1) xterm.js
949 // documentation states that allowTransparency can affect performance; 2) I
950 // find that the rendering is better with allowTransparency being false.
951 // This could be a bug with xterm.js.
952 if (!!this.term.options.allowTransparency !== hasBackgroundImage) {
953 this.term.options.allowTransparency = hasBackgroundImage;
954 if (this.enableWebGL_ && this.inited_) {
955 // Setting allowTransparency in the middle messes up webgl rendering,
956 // so we need to reload it here.
957 this.reloadWebglAddon_();
958 }
959 }
960
961 if (this.hasBackgroundImage()) {
962 const css = lib.notNull(lib.colors.normalizeCSS(color));
963 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
964 // Note that we still want to set the RGB part correctly even though it is
965 // completely transparent. This is because the background color without
966 // the alpha channel is used in reverse video mode.
967 color = `rgba(${rgb}, 0)`;
968 }
969
970 this.updateTheme_({background: color});
971 }
972
Jason Linc2504ae2022-09-02 13:03:31 +1000973 /**
Jason Lind04bab32022-08-22 14:48:39 +1000974 * @param {!Object} theme
975 */
976 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000977 const updateTheme = (target) => {
978 for (const [key, value] of Object.entries(theme)) {
979 target[key] = lib.colors.normalizeCSS(value);
980 }
981 };
982
983 // Must use a new theme object to trigger re-render if we have initialized.
984 if (this.inited_) {
985 const newTheme = {...this.term.options.theme};
986 updateTheme(newTheme);
987 this.term.options.theme = newTheme;
988 return;
Jason Lind04bab32022-08-22 14:48:39 +1000989 }
Jason Lin8de3d282022-09-01 21:29:05 +1000990
991 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000992 }
993
994 /**
Jason Linabad7562022-08-22 14:49:05 +1000995 * Called when there is a "fontloadingdone" event. We need this because
996 * `FontManager.loadFont()` does not guarantee loading all the font files.
997 */
998 async onFontLoadingDone_() {
999 // If there is a pending font, the font is going to be refresh soon, so we
1000 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +10001001 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +10001002 this.scheduleRefreshFont_();
1003 }
1004 }
1005
Jason Lin932b7432022-12-07 16:51:54 +11001006 /**
1007 * @param {!DragEvent} e
1008 */
1009 onDrop_(e) {
1010 e.preventDefault();
1011
1012 // If the shift key active, try to find a "rich" text source (but not plain
1013 // text). e.g. text/html is OK. This is the same behavior as hterm.
1014 if (e.shiftKey) {
1015 for (const type of e.dataTransfer.types) {
1016 if (type !== 'text/plain' && type.startsWith('text/')) {
1017 this.term.paste(e.dataTransfer.getData(type));
1018 return;
1019 }
1020 }
1021 }
1022
1023 this.term.paste(e.dataTransfer.getData('text/plain'));
1024 }
1025
1026 /**
1027 * @param {!MouseEvent} e
1028 */
Jason Lin97a04282023-03-06 10:36:56 +11001029 onMouseDown_(e) {
Jason Lin932b7432022-12-07 16:51:54 +11001030 if (this.term.modes.mouseTrackingMode !== 'none') {
1031 // xterm.js is in mouse mode and will handle the event.
1032 return;
1033 }
1034 const MIDDLE = 1;
1035 const RIGHT = 2;
1036
1037 if (e.button === RIGHT && e.ctrlKey) {
1038 this.contextMenu_.show({x: e.clientX, y: e.clientY});
1039 return;
1040 }
1041
1042 if (e.button === MIDDLE || (e.button === RIGHT &&
1043 this.prefs_.getBoolean('mouse-right-click-paste'))) {
Jason Lin97a04282023-03-06 10:36:56 +11001044 this.pasteFromClipboard_();
1045 }
1046 }
1047
1048 async pasteFromClipboard_() {
1049 const text = await navigator.clipboard?.readText?.();
1050 if (text) {
1051 this.term.paste(text);
Jason Lin932b7432022-12-07 16:51:54 +11001052 }
1053 }
1054
Jason Lin5690e752022-08-30 15:36:45 +10001055 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +10001056 this.copyString_(this.term.getSelection());
1057 }
1058
1059 /** @param {string} data */
1060 copyString_(data) {
1061 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +10001062 return;
1063 }
Jason Line9231bc2022-09-01 13:54:02 +10001064 navigator.clipboard?.writeText(data);
Jason Lin83ef5ba2022-10-13 17:40:30 +11001065
1066 if (this.prefs_.get('enable-clipboard-notice')) {
1067 if (!this.copyNotice_) {
1068 this.copyNotice_ = document.createElement('terminal-copy-notice');
1069 }
1070 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500),
1071 200);
Jason Lin6a402a72022-08-25 16:07:02 +10001072 }
Jason Lin6a402a72022-08-25 16:07:02 +10001073 }
1074
Jason Linabad7562022-08-22 14:49:05 +10001075 /**
1076 * Refresh xterm rendering for a font related event.
1077 */
1078 refreshFont_() {
1079 // We have to set the fontFamily option to a different string to trigger the
1080 // re-rendering. Appending a space at the end seems to be the easiest
1081 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
1082 // us.
1083 //
1084 // TODO: Report a bug to xterm.js and ask for exposing a public function for
1085 // the refresh so that we don't need to do this hack.
1086 this.term.options.fontFamily += ' ';
1087 }
1088
1089 /**
1090 * Update a font.
1091 *
1092 * @param {string} cssFontFamily
1093 */
1094 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +10001095 this.pendingFont_ = cssFontFamily;
1096 await this.fontManager_.loadFont(cssFontFamily);
1097 // Sleep a bit to wait for flushing fontloadingdone events. This is not
1098 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
1099 // to refresh font unnecessarily in some cases.
1100 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +10001101
Jason Lin6a402a72022-08-25 16:07:02 +10001102 if (this.pendingFont_ !== cssFontFamily) {
1103 // `updateFont_()` probably is called again. Abort what we are doing.
1104 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
1105 ` (expecting ${cssFontFamily})`);
1106 return;
1107 }
Jason Linabad7562022-08-22 14:49:05 +10001108
Jason Lin6a402a72022-08-25 16:07:02 +10001109 if (this.term.options.fontFamily !== cssFontFamily) {
1110 this.term.options.fontFamily = cssFontFamily;
1111 } else {
1112 // If the font is already the same, refresh font just to be safe.
1113 this.refreshFont_();
1114 }
1115 this.pendingFont_ = null;
Jason Linabad7562022-08-22 14:49:05 +10001116 }
Jason Lin5690e752022-08-30 15:36:45 +10001117
1118 /**
1119 * @param {!KeyboardEvent} ev
Jason Lin97a04282023-03-06 10:36:56 +11001120 * @return {boolean} Return true if the key event is handled.
Jason Lin5690e752022-08-30 15:36:45 +10001121 */
Jason Lin97a04282023-03-06 10:36:56 +11001122 handleKeyEvent_(ev) {
Jason Lin646dde02023-01-10 22:33:02 +11001123 // Without this, <alt-tab> (or <alt-shift-tab) is consumed by xterm.js
Jason Lin97a04282023-03-06 10:36:56 +11001124 // (instead of the OS) when terminal is full screen.
Jason Lin646dde02023-01-10 22:33:02 +11001125 if (ev.altKey && ev.keyCode === 9) {
Jason Lin97a04282023-03-06 10:36:56 +11001126 return true;
Jason Lin646dde02023-01-10 22:33:02 +11001127 }
1128
Jason Lin5690e752022-08-30 15:36:45 +10001129 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
1130 (ev.altKey ? Modifier.Alt : 0) |
1131 (ev.ctrlKey ? Modifier.Ctrl : 0) |
1132 (ev.metaKey ? Modifier.Meta : 0);
Jason Lin97a04282023-03-06 10:36:56 +11001133
1134 if (this.handleArrowAndSixPackKeys_(ev, modifiers)) {
1135 ev.preventDefault();
1136 ev.stopPropagation();
1137 return true;
1138 }
1139
Jason Lin5690e752022-08-30 15:36:45 +10001140 const handler = this.keyDownHandlers_.get(
1141 encodeKeyCombo(modifiers, ev.keyCode));
1142 if (handler) {
1143 if (ev.type === 'keydown') {
1144 handler(ev);
1145 }
Jason Lin97a04282023-03-06 10:36:56 +11001146 return true;
1147 }
1148
1149 return false;
1150 }
1151
1152 /**
1153 * Handle arrow keys and the "six pack keys" (e.g. home, insert...) because
1154 * xterm.js does not always handle them correctly with modifier keys.
1155 *
1156 * The behavior here is mostly the same as hterm, but there are some
1157 * differences. For example, we send a code instead of scrolling the screen
1158 * with shift+up/down to follow the behavior of xterm and other popular
1159 * terminals (e.g. gnome-terminal).
1160 *
1161 * We don't use `this.keyDownHandlers_` for this because it needs one entry
1162 * per modifier combination.
1163 *
1164 * @param {!KeyboardEvent} ev
1165 * @param {number} modifiers
1166 * @return {boolean} Return true if the key event is handled.
1167 */
1168 handleArrowAndSixPackKeys_(ev, modifiers) {
1169 let code = ARROW_AND_SIX_PACK_KEYS.get(ev.keyCode);
1170 if (!code) {
Jason Lin5690e752022-08-30 15:36:45 +10001171 return false;
1172 }
1173
Jason Lin97a04282023-03-06 10:36:56 +11001174 // For this case, we need to consider the "application cursor mode". We will
1175 // just let xterm.js handle it.
1176 if (modifiers === 0) {
1177 return false;
1178 }
1179
1180 if (ev.type !== 'keydown') {
1181 // Do nothing for non-keydown event, and also don't let xterm.js handle
1182 // it.
1183 return true;
1184 }
1185
1186 // Special handling if only shift is depressed.
1187 if (modifiers === Modifier.Shift) {
1188 switch (ev.keyCode) {
1189 case keyCodes.INSERT:
1190 this.pasteFromClipboard_();
1191 return true;
1192 case keyCodes.PAGE_UP:
1193 this.term.scrollPages(-1);
1194 return true;
1195 case keyCodes.PAGE_DOWN:
1196 this.term.scrollPages(1);
1197 return true;
1198 case keyCodes.HOME:
1199 this.term.scrollToTop();
1200 return true;
1201 case keyCodes.END:
1202 this.term.scrollToBottom();
1203 return true;
1204 }
1205 }
1206
1207 const mod = `;${modifiers + 1}`;
1208 if (code.length === 3) {
1209 // Convert code from "CSI x" to "CSI 1 mod x";
1210 code = '\x1b[1' + mod + code[2];
1211 } else {
1212 // Convert code from "CSI ... ~" to "CSI ... mod ~";
1213 code = code.slice(0, -1) + mod + '~';
1214 }
1215 this.io.onVTKeystroke(code);
Jason Lin5690e752022-08-30 15:36:45 +10001216 return true;
1217 }
1218
1219 /**
1220 * A keydown handler for zoom-related keys.
1221 *
1222 * @param {!KeyboardEvent} ev
1223 */
1224 zoomKeyDownHandler_(ev) {
1225 ev.preventDefault();
1226
1227 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
1228 // The only one with a control code.
1229 if (ev.keyCode === keyCodes.MINUS) {
1230 this.io.onVTKeystroke('\x1f');
1231 }
1232 return;
1233 }
1234
1235 let newFontSize;
1236 switch (ev.keyCode) {
1237 case keyCodes.ZERO:
1238 newFontSize = this.prefs_.get('font-size');
1239 break;
1240 case keyCodes.MINUS:
1241 newFontSize = this.term.options.fontSize - 1;
1242 break;
1243 default:
1244 newFontSize = this.term.options.fontSize + 1;
1245 break;
1246 }
1247
Jason Lin1be92f52023-01-23 23:50:00 +11001248 this.term.options.fontSize = Math.max(1, newFontSize);
Jason Lin5690e752022-08-30 15:36:45 +10001249 }
1250
1251 /** @param {!KeyboardEvent} ev */
1252 ctrlCKeyDownHandler_(ev) {
1253 ev.preventDefault();
1254 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
1255 this.term.hasSelection()) {
1256 this.copySelection_();
1257 return;
1258 }
1259
1260 this.io.onVTKeystroke('\x03');
1261 }
1262
1263 /** @param {!KeyboardEvent} ev */
1264 ctrlVKeyDownHandler_(ev) {
1265 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
1266 // Don't do anything and let the browser handles the key.
1267 return;
1268 }
1269
1270 ev.preventDefault();
1271 this.io.onVTKeystroke('\x16');
1272 }
1273
1274 resetKeyDownHandlers_() {
1275 this.keyDownHandlers_.clear();
1276
1277 /**
1278 * Don't do anything and let the browser handles the key.
1279 *
1280 * @param {!KeyboardEvent} ev
1281 */
1282 const noop = (ev) => {};
1283
1284 /**
1285 * @param {number} modifiers
1286 * @param {number} keyCode
1287 * @param {function(!KeyboardEvent)} func
1288 */
1289 const set = (modifiers, keyCode, func) => {
1290 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
1291 func);
1292 };
1293
1294 /**
1295 * @param {number} modifiers
1296 * @param {number} keyCode
1297 * @param {function(!KeyboardEvent)} func
1298 */
1299 const setWithShiftVersion = (modifiers, keyCode, func) => {
1300 set(modifiers, keyCode, func);
1301 set(modifiers | Modifier.Shift, keyCode, func);
1302 };
1303
Jason Lin5690e752022-08-30 15:36:45 +10001304 // Ctrl+/
1305 set(Modifier.Ctrl, 191, (ev) => {
1306 ev.preventDefault();
1307 this.io.onVTKeystroke(ctl('_'));
1308 });
1309
1310 // Settings page.
1311 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
1312 ev.preventDefault();
1313 chrome.terminalPrivate.openOptionsPage(() => {});
1314 });
1315
1316 if (this.prefs_.get('keybindings-os-defaults')) {
1317 for (const binding of OS_DEFAULT_BINDINGS) {
1318 this.keyDownHandlers_.set(binding, noop);
1319 }
1320 }
1321
1322 /** @param {!KeyboardEvent} ev */
1323 const newWindow = (ev) => {
1324 ev.preventDefault();
1325 chrome.terminalPrivate.openWindow();
1326 };
1327 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
1328 if (this.prefs_.get('pass-ctrl-n')) {
1329 set(Modifier.Ctrl, keyCodes.N, newWindow);
1330 }
1331
Joel Hockey965ea552023-02-19 22:08:04 -08001332 /** @param {!KeyboardEvent} ev */
1333 const newTab = (ev) => {
1334 ev.preventDefault();
1335 chrome.terminalPrivate.openWindow(
1336 {asTab: true, url: '/html/terminal.html'});
1337 };
Jason Lin5690e752022-08-30 15:36:45 +10001338 if (this.prefs_.get('pass-ctrl-t')) {
Joel Hockey965ea552023-02-19 22:08:04 -08001339 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, newTab);
Jason Lin5690e752022-08-30 15:36:45 +10001340 }
1341
1342 if (this.prefs_.get('pass-ctrl-w')) {
1343 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
1344 }
1345
1346 if (this.prefs_.get('pass-ctrl-tab')) {
1347 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
1348 }
1349
1350 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
1351
1352 /**
1353 * Set a handler for the key combo ctrl+<number>.
1354 *
1355 * @param {number} number 1 to 9
1356 * @param {string} controlCode The control code to send if we don't want to
1357 * let the browser to handle it.
1358 */
1359 const setCtrlNumberHandler = (number, controlCode) => {
1360 let func = noop;
1361 if (!passCtrlNumber) {
1362 func = (ev) => {
1363 ev.preventDefault();
1364 this.io.onVTKeystroke(controlCode);
1365 };
1366 }
1367 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1368 };
1369
1370 setCtrlNumberHandler(1, '1');
1371 setCtrlNumberHandler(2, ctl('@'));
1372 setCtrlNumberHandler(3, ctl('['));
1373 setCtrlNumberHandler(4, ctl('\\'));
1374 setCtrlNumberHandler(5, ctl(']'));
1375 setCtrlNumberHandler(6, ctl('^'));
1376 setCtrlNumberHandler(7, ctl('_'));
1377 setCtrlNumberHandler(8, '\x7f');
1378 setCtrlNumberHandler(9, '9');
1379
1380 if (this.prefs_.get('pass-alt-number')) {
1381 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1382 set(Modifier.Alt, keyCode, noop);
1383 }
1384 }
1385
1386 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1387 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1388 }
1389
1390 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1391 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1392 }
Jason Linee0c1f72022-10-18 17:17:26 +11001393
1394 handleOnTerminalReady() {}
Jason Linca61ffb2022-08-03 19:37:12 +10001395}
1396
Jason Lind66e6bf2022-08-22 14:47:10 +10001397class HtermTerminal extends hterm.Terminal {
1398 /** @override */
1399 decorate(div) {
1400 super.decorate(div);
1401
Jason Linc48f7432022-10-13 17:28:30 +11001402 definePrefs(this.getPrefs());
Jason Linee0c1f72022-10-18 17:17:26 +11001403 }
Jason Linc48f7432022-10-13 17:28:30 +11001404
Jason Linee0c1f72022-10-18 17:17:26 +11001405 /**
1406 * This needs to be called in the `onTerminalReady()` callback. This is
1407 * awkward, but it is temporary since we will drop support for hterm at some
1408 * point.
1409 */
1410 handleOnTerminalReady() {
Jason Lind66e6bf2022-08-22 14:47:10 +10001411 const fontManager = new FontManager(this.getDocument());
1412 fontManager.loadPowerlineCSS().then(() => {
1413 const prefs = this.getPrefs();
1414 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1415 prefs.addObserver(
1416 'font-family',
1417 (v) => fontManager.loadFont(/** @type {string} */(v)));
1418 });
Jason Linee0c1f72022-10-18 17:17:26 +11001419
1420 const backgroundImageWatcher = new BackgroundImageWatcher(this.getPrefs(),
1421 (image) => this.setBackgroundImage(image));
1422 this.setBackgroundImage(backgroundImageWatcher.getBackgroundImage());
1423 backgroundImageWatcher.watch();
Jason Lind66e6bf2022-08-22 14:47:10 +10001424 }
Jason Lin2649da22022-10-12 10:16:44 +11001425
1426 /**
1427 * Write data to the terminal.
1428 *
1429 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1430 * UTF-8 data
1431 * @param {function()=} callback Optional callback that fires when the data
1432 * was processed by the parser.
1433 */
1434 write(data, callback) {
1435 if (typeof data === 'string') {
1436 this.io.print(data);
1437 } else {
1438 this.io.writeUTF8(data);
1439 }
1440 // Hterm processes the data synchronously, so we can call the callback
1441 // immediately.
1442 if (callback) {
1443 setTimeout(callback);
1444 }
1445 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001446}
1447
Jason Linca61ffb2022-08-03 19:37:12 +10001448/**
1449 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1450 * preference value.
1451 *
1452 * @param {{
1453 * storage: !lib.Storage,
1454 * profileId: string,
1455 * }} args
1456 * @return {!Promise<!hterm.Terminal>}
1457 */
1458export async function createEmulator({storage, profileId}) {
1459 let config = TERMINAL_EMULATORS.get('hterm');
1460
1461 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001462 // TODO: remove the url param logic. This is temporary to make manual
1463 // testing a bit easier, which is also why this is not in
1464 // './js/terminal_info.js'.
Jason Line10d6c42022-11-11 16:04:32 +11001465 const emulator = ORIGINAL_URL.searchParams.get('emulator');
Jason Linca61ffb2022-08-03 19:37:12 +10001466 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001467 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001468 TERMINAL_EMULATORS.values().next().value;
1469 console.log('Terminal emulator config: ', config);
1470 }
1471
1472 switch (config.lib) {
1473 case 'xterm.js':
1474 {
1475 const terminal = new XtermTerminal({
1476 storage,
1477 profileId,
1478 enableWebGL: config.webgl,
1479 });
Jason Linca61ffb2022-08-03 19:37:12 +10001480 return terminal;
1481 }
1482 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001483 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001484 default:
1485 throw new Error('incorrect emulator config');
1486 }
1487}
1488
Jason Lin6a402a72022-08-25 16:07:02 +10001489class TerminalCopyNotice extends LitElement {
1490 /** @override */
1491 static get styles() {
1492 return css`
1493 :host {
1494 display: block;
1495 text-align: center;
1496 }
1497
1498 svg {
1499 fill: currentColor;
1500 }
1501 `;
1502 }
1503
1504 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001505 connectedCallback() {
1506 super.connectedCallback();
1507 if (!this.childNodes.length) {
1508 // This is not visible since we use shadow dom. But this will allow the
1509 // hterm.NotificationCenter to announce the the copy text.
1510 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1511 }
1512 }
1513
1514 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001515 render() {
1516 return html`
1517 ${ICON_COPY}
1518 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1519 `;
1520 }
1521}
1522
1523customElements.define('terminal-copy-notice', TerminalCopyNotice);