blob: 0d32bbfcee47e72c68623585721aac32e9b4c928 [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 Line99299a2023-03-31 13:36:35 +1100128 * Create a notification following hterm's style.
129 *
130 * @param {string} title
131 * @param {?string=} body
132 * @return {!Notification}
133 */
134function createNotification(title, body) {
135 const options = {icon: lib.resource.getDataUrl('hterm/images/icon-96')};
136 if (body) {
137 options.body = body;
138 }
139 return new Notification(`\u266A ${title} \u266A`, options);
140}
141
142/**
Jason Lin21d854f2022-08-22 14:49:59 +1000143 * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO
144 * because it always convert utf8 data to strings, which is not necessary for
145 * xterm.
146 */
147class XtermTerminalIO extends hterm.Terminal.IO {
148 /** @override */
149 writeUTF8(buffer) {
150 this.terminal_.write(new Uint8Array(buffer));
151 }
152
153 /** @override */
154 writelnUTF8(buffer) {
155 this.terminal_.writeln(new Uint8Array(buffer));
156 }
157
158 /** @override */
159 print(string) {
160 this.terminal_.write(string);
161 }
162
163 /** @override */
164 writeUTF16(string) {
165 this.print(string);
166 }
167
168 /** @override */
169 println(string) {
170 this.terminal_.writeln(string);
171 }
172
173 /** @override */
174 writelnUTF16(string) {
175 this.println(string);
176 }
177}
178
179/**
Jason Lin83707c92022-09-20 19:09:41 +1000180 * A custom link handler that:
181 *
182 * - Shows a tooltip with the url on a OSC 8 link. This is following what hterm
183 * is doing. Also, showing the tooltip is better for the security of the user
184 * because the link can have arbitrary text.
185 * - Uses our own way to open the window.
186 */
187class LinkHandler {
188 /**
189 * @param {!Terminal} term
190 */
191 constructor(term) {
192 this.term_ = term;
193 /** @type {?TerminalTooltip} */
194 this.tooltip_ = null;
195 }
196
197 /**
198 * @return {!TerminalTooltip}
199 */
200 getTooltip_() {
201 if (!this.tooltip_) {
202 this.tooltip_ = /** @type {!TerminalTooltip} */(
203 document.createElement('terminal-tooltip'));
204 this.tooltip_.classList.add('xterm-hover');
205 lib.notNull(this.term_.element).appendChild(this.tooltip_);
206 }
207 return this.tooltip_;
208 }
209
210 /**
211 * @param {!MouseEvent} ev
212 * @param {string} url
213 * @param {!Object} range
214 */
215 activate(ev, url, range) {
216 lib.f.openWindow(url, '_blank');
217 }
218
219 /**
220 * @param {!MouseEvent} ev
221 * @param {string} url
222 * @param {!Object} range
223 */
224 hover(ev, url, range) {
225 this.getTooltip_().show(url, {x: ev.clientX, y: ev.clientY});
226 }
227
228 /**
229 * @param {!MouseEvent} ev
230 * @param {string} url
231 * @param {!Object} range
232 */
233 leave(ev, url, range) {
234 this.getTooltip_().hide();
235 }
236}
237
Jason Linc7afb672022-10-11 15:54:17 +1100238class Bell {
239 constructor() {
240 this.showNotification = false;
241
242 /** @type {?Audio} */
243 this.audio_ = null;
244 /** @type {?Notification} */
245 this.notification_ = null;
246 this.coolDownUntil_ = 0;
247 }
248
249 /**
250 * Set whether a bell audio should be played.
251 *
252 * @param {boolean} value
253 */
254 set playAudio(value) {
255 this.audio_ = value ?
256 new Audio(lib.resource.getDataUrl('hterm/audio/bell')) : null;
257 }
258
259 ring() {
260 const now = Date.now();
261 if (now < this.coolDownUntil_) {
262 return;
263 }
264 this.coolDownUntil_ = now + 500;
265
266 this.audio_?.play();
267 if (this.showNotification && !document.hasFocus() && !this.notification_) {
Jason Line99299a2023-03-31 13:36:35 +1100268 this.notification_ = createNotification(document.title);
Jason Linc7afb672022-10-11 15:54:17 +1100269 // Close the notification after a timeout. Note that this is different
270 // from hterm's behavior, but I think it makes more sense to do so.
271 setTimeout(() => {
272 this.notification_.close();
273 this.notification_ = null;
274 }, 5000);
275 }
276 }
277}
278
Jason Lind3aacef2022-10-12 19:03:37 +1100279const A11Y_BUTTON_STYLE = `
280position: fixed;
281z-index: 10;
282right: 16px;
283`;
284
Jason Lina8adea52022-10-25 13:14:14 +1100285// TODO: we should subscribe to the xterm.js onscroll event, and
286// disable/enable the buttons accordingly. However, xterm.js does not seem to
287// emit the onscroll event when the viewport is scrolled by the mouse. See
288// https://github.com/xtermjs/xterm.js/issues/3864
289export class A11yButtons {
Jason Lind3aacef2022-10-12 19:03:37 +1100290 /**
291 * @param {!Terminal} term
Jason Lina8adea52022-10-25 13:14:14 +1100292 * @param {!hterm.AccessibilityReader} htermA11yReader
Jason Lind3aacef2022-10-12 19:03:37 +1100293 */
Jason Linc0f14fe2022-10-25 15:31:29 +1100294 constructor(term, htermA11yReader) {
Jason Lina8adea52022-10-25 13:14:14 +1100295 this.term_ = term;
296 this.htermA11yReader_ = htermA11yReader;
Jason Linc0f14fe2022-10-25 15:31:29 +1100297 this.pageUpButton = document.createElement('button');
298 this.pageUpButton.style.cssText = A11Y_BUTTON_STYLE;
299 this.pageUpButton.textContent =
Jason Lind3aacef2022-10-12 19:03:37 +1100300 hterm.messageManager.get('HTERM_BUTTON_PAGE_UP');
Jason Linc0f14fe2022-10-25 15:31:29 +1100301 this.pageUpButton.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100302 () => this.scrollPages_(-1));
Jason Lind3aacef2022-10-12 19:03:37 +1100303
Jason Linc0f14fe2022-10-25 15:31:29 +1100304 this.pageDownButton = document.createElement('button');
305 this.pageDownButton.style.cssText = A11Y_BUTTON_STYLE;
306 this.pageDownButton.textContent =
Jason Lind3aacef2022-10-12 19:03:37 +1100307 hterm.messageManager.get('HTERM_BUTTON_PAGE_DOWN');
Jason Linc0f14fe2022-10-25 15:31:29 +1100308 this.pageDownButton.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100309 () => this.scrollPages_(1));
Jason Lind3aacef2022-10-12 19:03:37 +1100310
311 this.resetPos_();
Jason Lind3aacef2022-10-12 19:03:37 +1100312
313 this.onSelectionChange_ = this.onSelectionChange_.bind(this);
314 }
315
316 /**
Jason Lina8adea52022-10-25 13:14:14 +1100317 * @param {number} amount
318 */
319 scrollPages_(amount) {
320 this.term_.scrollPages(amount);
321 this.announceScreenContent_();
322 }
323
324 announceScreenContent_() {
325 const activeBuffer = this.term_.buffer.active;
326
327 let percentScrolled = 100;
328 if (activeBuffer.baseY !== 0) {
329 percentScrolled = Math.round(
330 100 * activeBuffer.viewportY / activeBuffer.baseY);
331 }
332
333 let currentScreenContent = hterm.messageManager.get(
334 'HTERM_ANNOUNCE_CURRENT_SCREEN_HEADER',
335 [percentScrolled],
336 '$1% scrolled,');
337
338 currentScreenContent += '\n';
339
340 const rowEnd = Math.min(activeBuffer.viewportY + this.term_.rows,
341 activeBuffer.length);
342 for (let i = activeBuffer.viewportY; i < rowEnd; ++i) {
343 currentScreenContent +=
344 activeBuffer.getLine(i).translateToString(true) + '\n';
345 }
346 currentScreenContent = currentScreenContent.trim();
347
348 this.htermA11yReader_.assertiveAnnounce(currentScreenContent);
349 }
350
351 /**
Jason Lind3aacef2022-10-12 19:03:37 +1100352 * @param {boolean} enabled
353 */
354 setEnabled(enabled) {
355 if (enabled) {
356 document.addEventListener('selectionchange', this.onSelectionChange_);
357 } else {
358 this.resetPos_();
359 document.removeEventListener('selectionchange', this.onSelectionChange_);
360 }
361 }
362
363 resetPos_() {
Jason Linc0f14fe2022-10-25 15:31:29 +1100364 this.pageUpButton.style.top = '-200px';
365 this.pageDownButton.style.bottom = '-200px';
Jason Lind3aacef2022-10-12 19:03:37 +1100366 }
367
368 onSelectionChange_() {
369 this.resetPos_();
370
Jason Lin36b9fce2022-11-10 16:56:40 +1100371 const selectedElement = document.getSelection().anchorNode?.parentElement;
Jason Linc0f14fe2022-10-25 15:31:29 +1100372 if (selectedElement === this.pageUpButton) {
373 this.pageUpButton.style.top = '16px';
374 } else if (selectedElement === this.pageDownButton) {
375 this.pageDownButton.style.bottom = '16px';
Jason Lind3aacef2022-10-12 19:03:37 +1100376 }
377 }
378}
379
Jason Linee0c1f72022-10-18 17:17:26 +1100380const BACKGROUND_IMAGE_KEY = 'background-image';
381
382class BackgroundImageWatcher {
383 /**
384 * @param {!hterm.PreferenceManager} prefs
385 * @param {function(string)} onChange This is called with the background image
386 * (could be empty) whenever it changes.
387 */
388 constructor(prefs, onChange) {
389 this.prefs_ = prefs;
390 this.onChange_ = onChange;
Joel Hockey0e164f02023-03-26 15:58:12 -0700391 this.localStorageKey_ = backgroundImageLocalStorageKey(prefs);
Jason Linee0c1f72022-10-18 17:17:26 +1100392 }
393
394 /**
395 * Call once to start watching for background image changes.
396 */
397 watch() {
398 window.addEventListener('storage', (e) => {
Joel Hockey0e164f02023-03-26 15:58:12 -0700399 if (e.key === this.localStorageKey_) {
Jason Linee0c1f72022-10-18 17:17:26 +1100400 this.onChange_(this.getBackgroundImage());
401 }
402 });
403 this.prefs_.addObserver(BACKGROUND_IMAGE_KEY, () => {
404 this.onChange_(this.getBackgroundImage());
405 });
406 }
407
408 getBackgroundImage() {
Joel Hockey0e164f02023-03-26 15:58:12 -0700409 const image = window.localStorage.getItem(this.localStorageKey_);
Jason Linee0c1f72022-10-18 17:17:26 +1100410 if (image) {
411 return `url(${image})`;
412 }
413
414 return this.prefs_.getString(BACKGROUND_IMAGE_KEY);
415 }
416}
417
Jason Linb8f380a2022-10-25 13:15:56 +1100418let xtermTerminalStringsLoaded = false;
419
Jason Lin83707c92022-09-20 19:09:41 +1000420/**
Jason Linca61ffb2022-08-03 19:37:12 +1000421 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
422 * so that it can be used in existing code.
423 *
Jason Linca61ffb2022-08-03 19:37:12 +1000424 * @extends {hterm.Terminal}
425 * @unrestricted
426 */
Jason Linabad7562022-08-22 14:49:05 +1000427export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000428 /**
429 * @param {{
430 * storage: !lib.Storage,
431 * profileId: string,
432 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000433 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000434 * }} args
435 */
Jason Linabad7562022-08-22 14:49:05 +1000436 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000437 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
438 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
439 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
440
Jason Lin8de3d282022-09-01 21:29:05 +1000441 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000442 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000443 /** @type {!hterm.PreferenceManager} */
444 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
Jason Linc48f7432022-10-13 17:28:30 +1100445 definePrefs(this.prefs_);
Jason Linca61ffb2022-08-03 19:37:12 +1000446 this.enableWebGL_ = enableWebGL;
447
Jason Lin5690e752022-08-30 15:36:45 +1000448 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linfc8a3722022-09-07 17:49:18 +1000449 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Lin2649da22022-10-12 10:16:44 +1100450 this.xtermInternal_ = testParams?.xtermInternal ||
451 new XtermInternal(this.term);
Jason Linabad7562022-08-22 14:49:05 +1000452 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000453
Jason Linc2504ae2022-09-02 13:03:31 +1000454 /** @type {?Element} */
455 this.container_;
Jason Linc7afb672022-10-11 15:54:17 +1100456 this.bell_ = new Bell();
Jason Linc2504ae2022-09-02 13:03:31 +1000457 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000458 testParams ? 0 : 250);
459
Jason Lin83707c92022-09-20 19:09:41 +1000460 this.term.loadAddon(
461 new WebLinksAddon((e, uri) => lib.f.openWindow(uri, '_blank')));
Jason Lin4de4f382022-09-01 14:10:18 +1000462 this.term.loadAddon(new Unicode11Addon());
463 this.term.unicode.activeVersion = '11';
464
Jason Linabad7562022-08-22 14:49:05 +1000465 this.pendingFont_ = null;
466 this.scheduleRefreshFont_ = delayedScheduler(
467 () => this.refreshFont_(), 100);
468 document.fonts.addEventListener('loadingdone',
469 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000470
471 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000472 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000473
Jason Lin34a45322022-10-12 19:10:52 +1100474 this.term.onResize(({cols, rows}) => {
475 this.io.onTerminalResize(cols, rows);
476 if (this.prefs_.get('enable-resize-status')) {
477 this.showOverlay(`${cols} × ${rows}`);
478 }
479 });
Jason Lin21d854f2022-08-22 14:49:59 +1000480 // We could also use `this.io.sendString()` except for the nassh exit
481 // prompt, which only listens to onVTKeystroke().
482 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000483 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100484 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin83ef5ba2022-10-13 17:40:30 +1100485 this.term.onSelectionChange(() => {
486 if (this.prefs_.get('copy-on-select')) {
487 this.copySelection_();
488 }
489 });
Jason Linc7afb672022-10-11 15:54:17 +1100490 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000491
492 /**
493 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
494 *
495 * If a key combo is in the map:
496 *
497 * - The handler instead of xterm.js will handle the keydown event.
498 * - Keyup and keypress will be ignored by both us and xterm.js.
499 *
500 * We re-generate this map every time a relevant pref value is changed. This
501 * is ok because pref changes are rare.
502 *
503 * @type {!Map<number, function(!KeyboardEvent)>}
504 */
505 this.keyDownHandlers_ = new Map();
506 this.scheduleResetKeyDownHandlers_ =
507 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
508
Jason Lin97a04282023-03-06 10:36:56 +1100509 this.term.attachCustomKeyEventHandler((ev) => !this.handleKeyEvent_(ev));
Jason Linca61ffb2022-08-03 19:37:12 +1000510
Jason Lin21d854f2022-08-22 14:49:59 +1000511 this.io = new XtermTerminalIO(this);
512 this.notificationCenter_ = null;
Jason Lind3aacef2022-10-12 19:03:37 +1100513 this.htermA11yReader_ = null;
Jason Linc0f14fe2022-10-25 15:31:29 +1100514 this.a11yEnabled_ = false;
Jason Lind3aacef2022-10-12 19:03:37 +1100515 this.a11yButtons_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000516 this.copyNotice_ = null;
Jason Lin446f3d92022-10-13 17:34:21 +1100517 this.scrollOnOutputListener_ = null;
Jason Linee0c1f72022-10-18 17:17:26 +1100518 this.backgroundImageWatcher_ = new BackgroundImageWatcher(this.prefs_,
519 this.setBackgroundImage.bind(this));
520 this.webglAddon_ = null;
Jason Lina63d8ba2022-11-02 17:42:38 +1100521 this.userCSSElement_ = null;
522 this.userCSSTextElement_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000523
Jason Lin82ba86c2022-11-09 12:12:27 +1100524 this.contextMenu_ = /** @type {!TerminalContextMenu} */(
525 document.createElement('terminal-context-menu'));
526 this.contextMenu_.style.zIndex = 10;
527 this.contextMenu = {
528 setItems: (items) => this.contextMenu_.items = items,
529 };
530
Jason Lin83707c92022-09-20 19:09:41 +1000531 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000532 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000533 // The webgl cursor layer also paints the character under the cursor with
534 // this `cursorAccent` color. We use a completely transparent color here
535 // to effectively disable that.
536 cursorAccent: 'rgba(0, 0, 0, 0)',
537 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000538 selectionBackground: 'rgba(174, 203, 250, .6)',
539 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000540 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000541 };
542 this.observePrefs_();
Jason Linb8f380a2022-10-25 13:15:56 +1100543 if (!xtermTerminalStringsLoaded) {
544 xtermTerminalStringsLoaded = true;
545 Terminal.strings.promptLabel =
546 hterm.messageManager.get('TERMINAL_INPUT_LABEL');
547 Terminal.strings.tooMuchOutput =
548 hterm.messageManager.get('TERMINAL_TOO_MUCH_OUTPUT_MESSAGE');
549 }
Jason Linca61ffb2022-08-03 19:37:12 +1000550 }
551
Jason Linc7afb672022-10-11 15:54:17 +1100552 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100553 setWindowTitle(title) {
554 document.title = title;
555 }
556
557 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100558 ringBell() {
559 this.bell_.ring();
560 }
561
Jason Lin2649da22022-10-12 10:16:44 +1100562 /** @override */
563 print(str) {
564 this.xtermInternal_.print(str);
565 }
566
567 /** @override */
568 wipeContents() {
569 this.term.clear();
570 }
571
572 /** @override */
573 newLine() {
574 this.xtermInternal_.newLine();
575 }
576
577 /** @override */
578 cursorLeft(number) {
579 this.xtermInternal_.cursorLeft(number ?? 1);
580 }
581
Jason Lind3aacef2022-10-12 19:03:37 +1100582 /** @override */
583 setAccessibilityEnabled(enabled) {
Jason Linc0f14fe2022-10-25 15:31:29 +1100584 if (enabled === this.a11yEnabled_) {
585 return;
586 }
587 this.a11yEnabled_ = enabled;
588
Jason Lind3aacef2022-10-12 19:03:37 +1100589 this.a11yButtons_.setEnabled(enabled);
590 this.htermA11yReader_.setAccessibilityEnabled(enabled);
Jason Linc0f14fe2022-10-25 15:31:29 +1100591
592 if (enabled) {
593 this.xtermInternal_.enableA11y(this.a11yButtons_.pageUpButton,
594 this.a11yButtons_.pageDownButton);
595 } else {
596 this.xtermInternal_.disableA11y();
597 }
Jason Lind3aacef2022-10-12 19:03:37 +1100598 }
599
Jason Linee0c1f72022-10-18 17:17:26 +1100600 hasBackgroundImage() {
601 return !!this.container_.style.backgroundImage;
602 }
603
604 /** @override */
605 setBackgroundImage(image) {
606 this.container_.style.backgroundImage = image || '';
607 this.updateBackgroundColor_(this.prefs_.getString('background-color'));
608 }
609
Jason Linca61ffb2022-08-03 19:37:12 +1000610 /**
611 * Install stubs for stuff that we haven't implemented yet so that the code
612 * still runs.
613 */
614 installUnimplementedStubs_() {
615 this.keyboard = {
616 keyMap: {
617 keyDefs: [],
618 },
619 bindings: {
620 clear: () => {},
621 addBinding: () => {},
622 addBindings: () => {},
623 OsDefaults: {},
624 },
625 };
626 this.keyboard.keyMap.keyDefs[78] = {};
Joel Hockey965ea552023-02-19 22:08:04 -0800627 this.keyboard.keyMap.keyDefs[84] = {};
Jason Linca61ffb2022-08-03 19:37:12 +1000628
629 const methodNames = [
Joel Hockeyb89a9782022-10-16 22:00:12 -0700630 'eraseLine',
Joel Hockeyb89a9782022-10-16 22:00:12 -0700631 'setCursorColumn',
Jason Linca61ffb2022-08-03 19:37:12 +1000632 'setCursorPosition',
633 'setCursorVisible',
Joel Hockeyd78374f2022-11-02 23:05:53 -0700634 'uninstallKeyboard',
Jason Linca61ffb2022-08-03 19:37:12 +1000635 ];
636
637 for (const name of methodNames) {
638 this[name] = () => console.warn(`${name}() is not implemented`);
639 }
640
Jason Lin21d854f2022-08-22 14:49:59 +1000641 this.vt = {
642 resetParseState: () => {
643 console.warn('.vt.resetParseState() is not implemented');
644 },
645 };
Jason Linca61ffb2022-08-03 19:37:12 +1000646 }
647
Jason Line9231bc2022-09-01 13:54:02 +1000648 installEscapeSequenceHandlers_() {
649 // OSC 52 for copy.
650 this.term.parser.registerOscHandler(52, (args) => {
651 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
652 // parameter is used to select which of the X clipboards to address. Since
653 // we're not integrating with X, we treat them all the same.
654 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
655 if (!parsedArgs) {
656 return true;
657 }
658
659 let data;
660 try {
661 data = window.atob(parsedArgs[1]);
662 } catch (e) {
663 // If the user sent us invalid base64 content, silently ignore it.
664 return true;
665 }
666 const decoder = new TextDecoder();
667 const bytes = lib.codec.stringToCodeUnitArray(data);
668 this.copyString_(decoder.decode(bytes));
669
670 return true;
671 });
Jason Lin2649da22022-10-12 10:16:44 +1100672
Jason Line99299a2023-03-31 13:36:35 +1100673 // URxvt perl modules. We only support "notify".
674 this.term.parser.registerOscHandler(777, (args) => {
675 // Match 'notify;<title>[;<message>]'.
676 const match = args.match(/^notify;([^;]*)(?:;(.*))?$/);
677 if (match) {
678 createNotification(match[1], match[2]);
679 }
680
681 return true;
682 });
683
Jason Lin2649da22022-10-12 10:16:44 +1100684 this.xtermInternal_.installTmuxControlModeHandler(
685 (data) => this.onTmuxControlModeLine(data));
686 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000687 }
688
Jason Linca61ffb2022-08-03 19:37:12 +1000689 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000690 * Write data to the terminal.
691 *
692 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
693 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100694 * @param {function()=} callback Optional callback that fires when the data
695 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000696 */
Jason Lin2649da22022-10-12 10:16:44 +1100697 write(data, callback) {
698 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000699 }
700
701 /**
702 * Like `this.write()` but also write a line break.
703 *
704 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100705 * @param {function()=} callback Optional callback that fires when the data
706 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000707 */
Jason Lin2649da22022-10-12 10:16:44 +1100708 writeln(data, callback) {
709 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000710 }
711
Jason Linca61ffb2022-08-03 19:37:12 +1000712 get screenSize() {
713 return new hterm.Size(this.term.cols, this.term.rows);
714 }
715
716 /**
717 * Don't need to do anything.
718 *
719 * @override
720 */
721 installKeyboard() {}
722
723 /**
724 * @override
725 */
726 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000727 this.container_ = elem;
Jason Linee0c1f72022-10-18 17:17:26 +1100728 elem.style.backgroundSize = '100% 100%';
729
Jason Lin8de3d282022-09-01 21:29:05 +1000730 (async () => {
731 await new Promise((resolve) => this.prefs_.readStorage(resolve));
732 // This will trigger all the observers to set the terminal options before
733 // we call `this.term.open()`.
734 this.prefs_.notifyAll();
735
Jason Linc2504ae2022-09-02 13:03:31 +1000736 const screenPaddingSize = /** @type {number} */(
737 this.prefs_.get('screen-padding-size'));
738 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
739
Jason Linee0c1f72022-10-18 17:17:26 +1100740 this.setBackgroundImage(
741 this.backgroundImageWatcher_.getBackgroundImage());
742 this.backgroundImageWatcher_.watch();
743
Jason Lin8de3d282022-09-01 21:29:05 +1000744 this.inited_ = true;
745 this.term.open(elem);
Jason Lin1be92f52023-01-23 23:50:00 +1100746 this.xtermInternal_.addDimensionsObserver(() => this.scheduleFit_());
Jason Lin8de3d282022-09-01 21:29:05 +1000747
Jason Lin8de3d282022-09-01 21:29:05 +1000748 if (this.enableWebGL_) {
Jason Linee0c1f72022-10-18 17:17:26 +1100749 this.reloadWebglAddon_();
Jason Lin8de3d282022-09-01 21:29:05 +1000750 }
751 this.term.focus();
752 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100753 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
754 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
755 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000756
Jason Lin82ba86c2022-11-09 12:12:27 +1100757 elem.appendChild(this.contextMenu_);
758
Jason Lin932b7432022-12-07 16:51:54 +1100759 elem.addEventListener('dragover', (e) => e.preventDefault());
760 elem.addEventListener('drop',
761 (e) => this.onDrop_(/** @type {!DragEvent} */(e)));
762
Jason Lin82ba86c2022-11-09 12:12:27 +1100763 // Block the default context menu from popping up.
Emil Mikulic2a194d02022-09-29 14:30:59 +1000764 elem.addEventListener('contextmenu', (e) => e.preventDefault());
765
766 // Add a handler for pasting with the mouse.
Jason Lin932b7432022-12-07 16:51:54 +1100767 elem.addEventListener('mousedown',
768 (e) => this.onMouseDown_(/** @type {!MouseEvent} */(e)));
Emil Mikulic2a194d02022-09-29 14:30:59 +1000769
Jason Lin2649da22022-10-12 10:16:44 +1100770 await this.scheduleFit_();
Jason Linc0f14fe2022-10-25 15:31:29 +1100771 this.a11yButtons_ = new A11yButtons(this.term, this.htermA11yReader_);
Jason Lin23b4cef2023-03-06 10:25:29 +1100772 if (!this.prefs_.get('scrollbar-visible')) {
773 this.xtermInternal_.setScrollbarVisible(false);
774 }
Jason Lind3aacef2022-10-12 19:03:37 +1100775
Jason Lin8de3d282022-09-01 21:29:05 +1000776 this.onTerminalReady();
777 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000778 }
779
780 /** @override */
781 showOverlay(msg, timeout = 1500) {
Jason Lin34a45322022-10-12 19:10:52 +1100782 this.notificationCenter_?.show(msg, {timeout});
Jason Lin21d854f2022-08-22 14:49:59 +1000783 }
784
785 /** @override */
786 hideOverlay() {
Jason Lin34a45322022-10-12 19:10:52 +1100787 this.notificationCenter_?.hide();
Jason Linca61ffb2022-08-03 19:37:12 +1000788 }
789
790 /** @override */
791 getPrefs() {
792 return this.prefs_;
793 }
794
795 /** @override */
796 getDocument() {
797 return window.document;
798 }
799
Jason Lin21d854f2022-08-22 14:49:59 +1000800 /** @override */
801 reset() {
802 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000803 }
804
805 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000806 setProfile(profileId, callback = undefined) {
807 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000808 }
809
Jason Lin21d854f2022-08-22 14:49:59 +1000810 /** @override */
811 interpret(string) {
812 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000813 }
814
Jason Lin21d854f2022-08-22 14:49:59 +1000815 /** @override */
816 focus() {
817 this.term.focus();
818 }
Jason Linca61ffb2022-08-03 19:37:12 +1000819
820 /** @override */
821 onOpenOptionsPage() {}
822
823 /** @override */
824 onTerminalReady() {}
825
Jason Lind04bab32022-08-22 14:48:39 +1000826 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000827 // This is for this.notificationCenter_.
828 const setHtermCSSVariable = (name, value) => {
829 document.body.style.setProperty(`--hterm-${name}`, value);
830 };
831
832 const setHtermColorCSSVariable = (name, color) => {
833 const css = lib.notNull(lib.colors.normalizeCSS(color));
834 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
835 setHtermCSSVariable(name, rgb);
836 };
837
838 this.prefs_.addObserver('font-size', (v) => {
Jason Lin1be92f52023-01-23 23:50:00 +1100839 this.term.options.fontSize = v;
Jason Lin21d854f2022-08-22 14:49:59 +1000840 setHtermCSSVariable('font-size', `${v}px`);
841 });
842
Jason Linda56aa92022-09-02 13:01:49 +1000843 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000844 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000845 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100846 this.bell_.playAudio = !!v;
847 },
848 'desktop-notification-bell': (v) => {
849 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000850 },
Jason Lind04bab32022-08-22 14:48:39 +1000851 'background-color': (v) => {
Jason Linee0c1f72022-10-18 17:17:26 +1100852 this.updateBackgroundColor_(v);
Jason Lin21d854f2022-08-22 14:49:59 +1000853 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000854 },
Jason Lind04bab32022-08-22 14:48:39 +1000855 'color-palette-overrides': (v) => {
856 if (!(v instanceof Array)) {
857 // For terminal, we always expect this to be an array.
858 console.warn('unexpected color palette: ', v);
859 return;
860 }
861 const colors = {};
862 for (let i = 0; i < v.length; ++i) {
863 colors[ANSI_COLOR_NAMES[i]] = v[i];
864 }
865 this.updateTheme_(colors);
866 },
Jason Lin1be92f52023-01-23 23:50:00 +1100867 'cursor-blink': (v) => {
868 this.term.options.cursorBlink = v;
869 },
Jason Linda56aa92022-09-02 13:01:49 +1000870 'cursor-color': (v) => this.updateTheme_({cursor: v}),
871 'cursor-shape': (v) => {
872 let shape;
873 if (v === 'BEAM') {
874 shape = 'bar';
875 } else {
876 shape = v.toLowerCase();
877 }
Jason Lin1be92f52023-01-23 23:50:00 +1100878 this.term.options.cursorStyle = shape;
Jason Linda56aa92022-09-02 13:01:49 +1000879 },
880 'font-family': (v) => this.updateFont_(v),
881 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000882 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000883 setHtermColorCSSVariable('foreground-color', v);
884 },
Jason Lin1be92f52023-01-23 23:50:00 +1100885 'line-height': (v) => {
886 this.term.options.lineHeight = v;
887 },
Jason Lin471e1062022-12-08 15:39:15 +1100888 'scroll-on-keystroke': (v) => {
Jason Lin1be92f52023-01-23 23:50:00 +1100889 this.term.options.scrollOnUserInput = v;
Jason Lin471e1062022-12-08 15:39:15 +1100890 },
Jason Lin446f3d92022-10-13 17:34:21 +1100891 'scroll-on-output': (v) => {
892 if (!v) {
893 this.scrollOnOutputListener_?.dispose();
894 this.scrollOnOutputListener_ = null;
895 return;
896 }
897 if (!this.scrollOnOutputListener_) {
898 this.scrollOnOutputListener_ = this.term.onWriteParsed(
899 () => this.term.scrollToBottom());
900 }
901 },
Jason Lin23b4cef2023-03-06 10:25:29 +1100902 'scrollbar-visible': (v) => {
903 this.xtermInternal_.setScrollbarVisible(v);
904 },
Jason Lina63d8ba2022-11-02 17:42:38 +1100905 'user-css': (v) => {
906 if (this.userCSSElement_) {
907 this.userCSSElement_.remove();
908 }
909 if (v) {
910 this.userCSSElement_ = document.createElement('link');
911 this.userCSSElement_.setAttribute('rel', 'stylesheet');
912 this.userCSSElement_.setAttribute('href', v);
913 document.head.appendChild(this.userCSSElement_);
914 }
915 },
916 'user-css-text': (v) => {
917 if (!this.userCSSTextElement_) {
918 this.userCSSTextElement_ = document.createElement('style');
919 document.head.appendChild(this.userCSSTextElement_);
920 }
921 this.userCSSTextElement_.textContent = v;
922 },
Jason Lind04bab32022-08-22 14:48:39 +1000923 });
Jason Lin5690e752022-08-30 15:36:45 +1000924
925 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
926 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
927 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
928 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
929 }
Jason Lind04bab32022-08-22 14:48:39 +1000930 }
931
932 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000933 * Fit the terminal to the containing HTML element.
934 */
935 fit_() {
936 if (!this.inited_) {
937 return;
938 }
939
940 const screenPaddingSize = /** @type {number} */(
941 this.prefs_.get('screen-padding-size'));
942
943 const calc = (size, cellSize) => {
944 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
945 };
946
Jason Lin2649da22022-10-12 10:16:44 +1100947 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
948 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
949 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000950 if (cols >= 0 && rows >= 0) {
951 this.term.resize(cols, rows);
952 }
953 }
954
Jason Linee0c1f72022-10-18 17:17:26 +1100955 reloadWebglAddon_() {
956 if (this.webglAddon_) {
957 this.webglAddon_.dispose();
958 }
959 this.webglAddon_ = new WebglAddon();
960 this.term.loadAddon(this.webglAddon_);
961 }
962
963 /**
964 * Update the background color. This will also adjust the transparency based
965 * on whether there is a background image.
966 *
967 * @param {string} color
968 */
969 updateBackgroundColor_(color) {
970 const hasBackgroundImage = this.hasBackgroundImage();
971
972 // We only set allowTransparency when it is necessary becuase 1) xterm.js
973 // documentation states that allowTransparency can affect performance; 2) I
974 // find that the rendering is better with allowTransparency being false.
975 // This could be a bug with xterm.js.
976 if (!!this.term.options.allowTransparency !== hasBackgroundImage) {
977 this.term.options.allowTransparency = hasBackgroundImage;
978 if (this.enableWebGL_ && this.inited_) {
979 // Setting allowTransparency in the middle messes up webgl rendering,
980 // so we need to reload it here.
981 this.reloadWebglAddon_();
982 }
983 }
984
985 if (this.hasBackgroundImage()) {
986 const css = lib.notNull(lib.colors.normalizeCSS(color));
987 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
988 // Note that we still want to set the RGB part correctly even though it is
989 // completely transparent. This is because the background color without
990 // the alpha channel is used in reverse video mode.
991 color = `rgba(${rgb}, 0)`;
992 }
993
994 this.updateTheme_({background: color});
995 }
996
Jason Linc2504ae2022-09-02 13:03:31 +1000997 /**
Jason Lind04bab32022-08-22 14:48:39 +1000998 * @param {!Object} theme
999 */
1000 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +10001001 const updateTheme = (target) => {
1002 for (const [key, value] of Object.entries(theme)) {
1003 target[key] = lib.colors.normalizeCSS(value);
1004 }
1005 };
1006
1007 // Must use a new theme object to trigger re-render if we have initialized.
1008 if (this.inited_) {
1009 const newTheme = {...this.term.options.theme};
1010 updateTheme(newTheme);
1011 this.term.options.theme = newTheme;
1012 return;
Jason Lind04bab32022-08-22 14:48:39 +10001013 }
Jason Lin8de3d282022-09-01 21:29:05 +10001014
1015 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +10001016 }
1017
1018 /**
Jason Linabad7562022-08-22 14:49:05 +10001019 * Called when there is a "fontloadingdone" event. We need this because
1020 * `FontManager.loadFont()` does not guarantee loading all the font files.
1021 */
1022 async onFontLoadingDone_() {
1023 // If there is a pending font, the font is going to be refresh soon, so we
1024 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +10001025 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +10001026 this.scheduleRefreshFont_();
1027 }
1028 }
1029
Jason Lin932b7432022-12-07 16:51:54 +11001030 /**
1031 * @param {!DragEvent} e
1032 */
1033 onDrop_(e) {
1034 e.preventDefault();
1035
1036 // If the shift key active, try to find a "rich" text source (but not plain
1037 // text). e.g. text/html is OK. This is the same behavior as hterm.
1038 if (e.shiftKey) {
1039 for (const type of e.dataTransfer.types) {
1040 if (type !== 'text/plain' && type.startsWith('text/')) {
1041 this.term.paste(e.dataTransfer.getData(type));
1042 return;
1043 }
1044 }
1045 }
1046
1047 this.term.paste(e.dataTransfer.getData('text/plain'));
1048 }
1049
1050 /**
1051 * @param {!MouseEvent} e
1052 */
Jason Lin97a04282023-03-06 10:36:56 +11001053 onMouseDown_(e) {
Jason Lin932b7432022-12-07 16:51:54 +11001054 if (this.term.modes.mouseTrackingMode !== 'none') {
1055 // xterm.js is in mouse mode and will handle the event.
1056 return;
1057 }
1058 const MIDDLE = 1;
1059 const RIGHT = 2;
1060
1061 if (e.button === RIGHT && e.ctrlKey) {
1062 this.contextMenu_.show({x: e.clientX, y: e.clientY});
1063 return;
1064 }
1065
1066 if (e.button === MIDDLE || (e.button === RIGHT &&
1067 this.prefs_.getBoolean('mouse-right-click-paste'))) {
Jason Lin97a04282023-03-06 10:36:56 +11001068 this.pasteFromClipboard_();
1069 }
1070 }
1071
1072 async pasteFromClipboard_() {
1073 const text = await navigator.clipboard?.readText?.();
1074 if (text) {
1075 this.term.paste(text);
Jason Lin932b7432022-12-07 16:51:54 +11001076 }
1077 }
1078
Jason Lin5690e752022-08-30 15:36:45 +10001079 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +10001080 this.copyString_(this.term.getSelection());
1081 }
1082
1083 /** @param {string} data */
1084 copyString_(data) {
1085 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +10001086 return;
1087 }
Jason Line9231bc2022-09-01 13:54:02 +10001088 navigator.clipboard?.writeText(data);
Jason Lin83ef5ba2022-10-13 17:40:30 +11001089
1090 if (this.prefs_.get('enable-clipboard-notice')) {
1091 if (!this.copyNotice_) {
1092 this.copyNotice_ = document.createElement('terminal-copy-notice');
1093 }
1094 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500),
1095 200);
Jason Lin6a402a72022-08-25 16:07:02 +10001096 }
Jason Lin6a402a72022-08-25 16:07:02 +10001097 }
1098
Jason Linabad7562022-08-22 14:49:05 +10001099 /**
1100 * Refresh xterm rendering for a font related event.
1101 */
1102 refreshFont_() {
1103 // We have to set the fontFamily option to a different string to trigger the
1104 // re-rendering. Appending a space at the end seems to be the easiest
1105 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
1106 // us.
1107 //
1108 // TODO: Report a bug to xterm.js and ask for exposing a public function for
1109 // the refresh so that we don't need to do this hack.
1110 this.term.options.fontFamily += ' ';
1111 }
1112
1113 /**
1114 * Update a font.
1115 *
1116 * @param {string} cssFontFamily
1117 */
1118 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +10001119 this.pendingFont_ = cssFontFamily;
1120 await this.fontManager_.loadFont(cssFontFamily);
1121 // Sleep a bit to wait for flushing fontloadingdone events. This is not
1122 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
1123 // to refresh font unnecessarily in some cases.
1124 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +10001125
Jason Lin6a402a72022-08-25 16:07:02 +10001126 if (this.pendingFont_ !== cssFontFamily) {
1127 // `updateFont_()` probably is called again. Abort what we are doing.
1128 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
1129 ` (expecting ${cssFontFamily})`);
1130 return;
1131 }
Jason Linabad7562022-08-22 14:49:05 +10001132
Jason Lin6a402a72022-08-25 16:07:02 +10001133 if (this.term.options.fontFamily !== cssFontFamily) {
1134 this.term.options.fontFamily = cssFontFamily;
1135 } else {
1136 // If the font is already the same, refresh font just to be safe.
1137 this.refreshFont_();
1138 }
1139 this.pendingFont_ = null;
Jason Linabad7562022-08-22 14:49:05 +10001140 }
Jason Lin5690e752022-08-30 15:36:45 +10001141
1142 /**
1143 * @param {!KeyboardEvent} ev
Jason Lin97a04282023-03-06 10:36:56 +11001144 * @return {boolean} Return true if the key event is handled.
Jason Lin5690e752022-08-30 15:36:45 +10001145 */
Jason Lin97a04282023-03-06 10:36:56 +11001146 handleKeyEvent_(ev) {
Jason Lin646dde02023-01-10 22:33:02 +11001147 // Without this, <alt-tab> (or <alt-shift-tab) is consumed by xterm.js
Jason Lin97a04282023-03-06 10:36:56 +11001148 // (instead of the OS) when terminal is full screen.
Jason Lin646dde02023-01-10 22:33:02 +11001149 if (ev.altKey && ev.keyCode === 9) {
Jason Lin97a04282023-03-06 10:36:56 +11001150 return true;
Jason Lin646dde02023-01-10 22:33:02 +11001151 }
1152
Jason Lin5690e752022-08-30 15:36:45 +10001153 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
1154 (ev.altKey ? Modifier.Alt : 0) |
1155 (ev.ctrlKey ? Modifier.Ctrl : 0) |
1156 (ev.metaKey ? Modifier.Meta : 0);
Jason Lin97a04282023-03-06 10:36:56 +11001157
1158 if (this.handleArrowAndSixPackKeys_(ev, modifiers)) {
1159 ev.preventDefault();
1160 ev.stopPropagation();
1161 return true;
1162 }
1163
Jason Lin5690e752022-08-30 15:36:45 +10001164 const handler = this.keyDownHandlers_.get(
1165 encodeKeyCombo(modifiers, ev.keyCode));
1166 if (handler) {
1167 if (ev.type === 'keydown') {
1168 handler(ev);
1169 }
Jason Lin97a04282023-03-06 10:36:56 +11001170 return true;
1171 }
1172
1173 return false;
1174 }
1175
1176 /**
1177 * Handle arrow keys and the "six pack keys" (e.g. home, insert...) because
1178 * xterm.js does not always handle them correctly with modifier keys.
1179 *
1180 * The behavior here is mostly the same as hterm, but there are some
1181 * differences. For example, we send a code instead of scrolling the screen
1182 * with shift+up/down to follow the behavior of xterm and other popular
1183 * terminals (e.g. gnome-terminal).
1184 *
1185 * We don't use `this.keyDownHandlers_` for this because it needs one entry
1186 * per modifier combination.
1187 *
1188 * @param {!KeyboardEvent} ev
1189 * @param {number} modifiers
1190 * @return {boolean} Return true if the key event is handled.
1191 */
1192 handleArrowAndSixPackKeys_(ev, modifiers) {
1193 let code = ARROW_AND_SIX_PACK_KEYS.get(ev.keyCode);
1194 if (!code) {
Jason Lin5690e752022-08-30 15:36:45 +10001195 return false;
1196 }
1197
Jason Lin97a04282023-03-06 10:36:56 +11001198 // For this case, we need to consider the "application cursor mode". We will
1199 // just let xterm.js handle it.
1200 if (modifiers === 0) {
1201 return false;
1202 }
1203
1204 if (ev.type !== 'keydown') {
1205 // Do nothing for non-keydown event, and also don't let xterm.js handle
1206 // it.
1207 return true;
1208 }
1209
1210 // Special handling if only shift is depressed.
1211 if (modifiers === Modifier.Shift) {
1212 switch (ev.keyCode) {
1213 case keyCodes.INSERT:
1214 this.pasteFromClipboard_();
1215 return true;
1216 case keyCodes.PAGE_UP:
1217 this.term.scrollPages(-1);
1218 return true;
1219 case keyCodes.PAGE_DOWN:
1220 this.term.scrollPages(1);
1221 return true;
1222 case keyCodes.HOME:
1223 this.term.scrollToTop();
1224 return true;
1225 case keyCodes.END:
1226 this.term.scrollToBottom();
1227 return true;
1228 }
1229 }
1230
1231 const mod = `;${modifiers + 1}`;
1232 if (code.length === 3) {
1233 // Convert code from "CSI x" to "CSI 1 mod x";
1234 code = '\x1b[1' + mod + code[2];
1235 } else {
1236 // Convert code from "CSI ... ~" to "CSI ... mod ~";
1237 code = code.slice(0, -1) + mod + '~';
1238 }
1239 this.io.onVTKeystroke(code);
Jason Lin5690e752022-08-30 15:36:45 +10001240 return true;
1241 }
1242
1243 /**
1244 * A keydown handler for zoom-related keys.
1245 *
1246 * @param {!KeyboardEvent} ev
1247 */
1248 zoomKeyDownHandler_(ev) {
1249 ev.preventDefault();
1250
1251 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
1252 // The only one with a control code.
1253 if (ev.keyCode === keyCodes.MINUS) {
1254 this.io.onVTKeystroke('\x1f');
1255 }
1256 return;
1257 }
1258
1259 let newFontSize;
1260 switch (ev.keyCode) {
1261 case keyCodes.ZERO:
1262 newFontSize = this.prefs_.get('font-size');
1263 break;
1264 case keyCodes.MINUS:
1265 newFontSize = this.term.options.fontSize - 1;
1266 break;
1267 default:
1268 newFontSize = this.term.options.fontSize + 1;
1269 break;
1270 }
1271
Jason Lin1be92f52023-01-23 23:50:00 +11001272 this.term.options.fontSize = Math.max(1, newFontSize);
Jason Lin5690e752022-08-30 15:36:45 +10001273 }
1274
1275 /** @param {!KeyboardEvent} ev */
1276 ctrlCKeyDownHandler_(ev) {
1277 ev.preventDefault();
1278 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
1279 this.term.hasSelection()) {
1280 this.copySelection_();
1281 return;
1282 }
1283
1284 this.io.onVTKeystroke('\x03');
1285 }
1286
1287 /** @param {!KeyboardEvent} ev */
1288 ctrlVKeyDownHandler_(ev) {
1289 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
1290 // Don't do anything and let the browser handles the key.
1291 return;
1292 }
1293
1294 ev.preventDefault();
1295 this.io.onVTKeystroke('\x16');
1296 }
1297
1298 resetKeyDownHandlers_() {
1299 this.keyDownHandlers_.clear();
1300
1301 /**
1302 * Don't do anything and let the browser handles the key.
1303 *
1304 * @param {!KeyboardEvent} ev
1305 */
1306 const noop = (ev) => {};
1307
1308 /**
1309 * @param {number} modifiers
1310 * @param {number} keyCode
1311 * @param {function(!KeyboardEvent)} func
1312 */
1313 const set = (modifiers, keyCode, func) => {
1314 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
1315 func);
1316 };
1317
1318 /**
1319 * @param {number} modifiers
1320 * @param {number} keyCode
1321 * @param {function(!KeyboardEvent)} func
1322 */
1323 const setWithShiftVersion = (modifiers, keyCode, func) => {
1324 set(modifiers, keyCode, func);
1325 set(modifiers | Modifier.Shift, keyCode, func);
1326 };
1327
Jason Lin5690e752022-08-30 15:36:45 +10001328 // Ctrl+/
1329 set(Modifier.Ctrl, 191, (ev) => {
1330 ev.preventDefault();
1331 this.io.onVTKeystroke(ctl('_'));
1332 });
1333
1334 // Settings page.
1335 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
1336 ev.preventDefault();
1337 chrome.terminalPrivate.openOptionsPage(() => {});
1338 });
1339
1340 if (this.prefs_.get('keybindings-os-defaults')) {
1341 for (const binding of OS_DEFAULT_BINDINGS) {
1342 this.keyDownHandlers_.set(binding, noop);
1343 }
1344 }
1345
1346 /** @param {!KeyboardEvent} ev */
1347 const newWindow = (ev) => {
1348 ev.preventDefault();
1349 chrome.terminalPrivate.openWindow();
1350 };
1351 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
1352 if (this.prefs_.get('pass-ctrl-n')) {
1353 set(Modifier.Ctrl, keyCodes.N, newWindow);
1354 }
1355
Joel Hockey965ea552023-02-19 22:08:04 -08001356 /** @param {!KeyboardEvent} ev */
1357 const newTab = (ev) => {
1358 ev.preventDefault();
1359 chrome.terminalPrivate.openWindow(
1360 {asTab: true, url: '/html/terminal.html'});
1361 };
Jason Lin5690e752022-08-30 15:36:45 +10001362 if (this.prefs_.get('pass-ctrl-t')) {
Joel Hockey965ea552023-02-19 22:08:04 -08001363 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, newTab);
Jason Lin5690e752022-08-30 15:36:45 +10001364 }
1365
1366 if (this.prefs_.get('pass-ctrl-w')) {
1367 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
1368 }
1369
1370 if (this.prefs_.get('pass-ctrl-tab')) {
1371 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
1372 }
1373
1374 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
1375
1376 /**
1377 * Set a handler for the key combo ctrl+<number>.
1378 *
1379 * @param {number} number 1 to 9
1380 * @param {string} controlCode The control code to send if we don't want to
1381 * let the browser to handle it.
1382 */
1383 const setCtrlNumberHandler = (number, controlCode) => {
1384 let func = noop;
1385 if (!passCtrlNumber) {
1386 func = (ev) => {
1387 ev.preventDefault();
1388 this.io.onVTKeystroke(controlCode);
1389 };
1390 }
1391 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1392 };
1393
1394 setCtrlNumberHandler(1, '1');
1395 setCtrlNumberHandler(2, ctl('@'));
1396 setCtrlNumberHandler(3, ctl('['));
1397 setCtrlNumberHandler(4, ctl('\\'));
1398 setCtrlNumberHandler(5, ctl(']'));
1399 setCtrlNumberHandler(6, ctl('^'));
1400 setCtrlNumberHandler(7, ctl('_'));
1401 setCtrlNumberHandler(8, '\x7f');
1402 setCtrlNumberHandler(9, '9');
1403
1404 if (this.prefs_.get('pass-alt-number')) {
1405 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1406 set(Modifier.Alt, keyCode, noop);
1407 }
1408 }
1409
1410 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1411 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1412 }
1413
1414 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1415 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1416 }
Jason Linee0c1f72022-10-18 17:17:26 +11001417
1418 handleOnTerminalReady() {}
Jason Linca61ffb2022-08-03 19:37:12 +10001419}
1420
Jason Lind66e6bf2022-08-22 14:47:10 +10001421class HtermTerminal extends hterm.Terminal {
1422 /** @override */
1423 decorate(div) {
1424 super.decorate(div);
1425
Jason Linc48f7432022-10-13 17:28:30 +11001426 definePrefs(this.getPrefs());
Jason Linee0c1f72022-10-18 17:17:26 +11001427 }
Jason Linc48f7432022-10-13 17:28:30 +11001428
Jason Linee0c1f72022-10-18 17:17:26 +11001429 /**
1430 * This needs to be called in the `onTerminalReady()` callback. This is
1431 * awkward, but it is temporary since we will drop support for hterm at some
1432 * point.
1433 */
1434 handleOnTerminalReady() {
Jason Lind66e6bf2022-08-22 14:47:10 +10001435 const fontManager = new FontManager(this.getDocument());
1436 fontManager.loadPowerlineCSS().then(() => {
1437 const prefs = this.getPrefs();
1438 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1439 prefs.addObserver(
1440 'font-family',
1441 (v) => fontManager.loadFont(/** @type {string} */(v)));
1442 });
Jason Linee0c1f72022-10-18 17:17:26 +11001443
1444 const backgroundImageWatcher = new BackgroundImageWatcher(this.getPrefs(),
1445 (image) => this.setBackgroundImage(image));
1446 this.setBackgroundImage(backgroundImageWatcher.getBackgroundImage());
1447 backgroundImageWatcher.watch();
Jason Lind66e6bf2022-08-22 14:47:10 +10001448 }
Jason Lin2649da22022-10-12 10:16:44 +11001449
1450 /**
1451 * Write data to the terminal.
1452 *
1453 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1454 * UTF-8 data
1455 * @param {function()=} callback Optional callback that fires when the data
1456 * was processed by the parser.
1457 */
1458 write(data, callback) {
1459 if (typeof data === 'string') {
1460 this.io.print(data);
1461 } else {
1462 this.io.writeUTF8(data);
1463 }
1464 // Hterm processes the data synchronously, so we can call the callback
1465 // immediately.
1466 if (callback) {
1467 setTimeout(callback);
1468 }
1469 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001470}
1471
Jason Linca61ffb2022-08-03 19:37:12 +10001472/**
1473 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1474 * preference value.
1475 *
1476 * @param {{
1477 * storage: !lib.Storage,
1478 * profileId: string,
1479 * }} args
1480 * @return {!Promise<!hterm.Terminal>}
1481 */
1482export async function createEmulator({storage, profileId}) {
1483 let config = TERMINAL_EMULATORS.get('hterm');
1484
1485 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001486 // TODO: remove the url param logic. This is temporary to make manual
1487 // testing a bit easier, which is also why this is not in
1488 // './js/terminal_info.js'.
Jason Line10d6c42022-11-11 16:04:32 +11001489 const emulator = ORIGINAL_URL.searchParams.get('emulator');
Jason Linca61ffb2022-08-03 19:37:12 +10001490 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001491 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001492 TERMINAL_EMULATORS.values().next().value;
1493 console.log('Terminal emulator config: ', config);
1494 }
1495
1496 switch (config.lib) {
1497 case 'xterm.js':
1498 {
1499 const terminal = new XtermTerminal({
1500 storage,
1501 profileId,
1502 enableWebGL: config.webgl,
1503 });
Jason Linca61ffb2022-08-03 19:37:12 +10001504 return terminal;
1505 }
1506 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001507 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001508 default:
1509 throw new Error('incorrect emulator config');
1510 }
1511}
1512
Jason Lin6a402a72022-08-25 16:07:02 +10001513class TerminalCopyNotice extends LitElement {
1514 /** @override */
1515 static get styles() {
1516 return css`
1517 :host {
1518 display: block;
1519 text-align: center;
1520 }
1521
1522 svg {
1523 fill: currentColor;
1524 }
1525 `;
1526 }
1527
1528 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001529 connectedCallback() {
1530 super.connectedCallback();
1531 if (!this.childNodes.length) {
1532 // This is not visible since we use shadow dom. But this will allow the
1533 // hterm.NotificationCenter to announce the the copy text.
1534 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1535 }
1536 }
1537
1538 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001539 render() {
1540 return html`
1541 ${ICON_COPY}
1542 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1543 `;
1544 }
1545}
1546
1547customElements.define('terminal-copy-notice', TerminalCopyNotice);