blob: 0b74c7239998435f5a51f1153e21a3fbf7bce06d [file] [log] [blame]
Mike Frysinger598e8012022-09-07 08:38:34 -04001// Copyright 2022 The ChromiumOS Authors
Jason Lind66e6bf2022-08-22 14:47:10 +10002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Jason Linca61ffb2022-08-03 19:37:12 +10005/**
6 * @fileoverview For supporting xterm.js and the terminal emulator.
7 */
8
9// TODO(b/236205389): add tests. For example, we should enable the test in
10// terminal_tests.js for XtermTerminal.
11
Jason Lin2649da22022-10-12 10:16:44 +110012// TODO(b/236205389): support option smoothScrollDuration?
13
Mike Frysinger75895da2022-10-04 00:42:28 +054514import {hterm, lib} from './deps_local.concat.js';
15
Jason Lin6a402a72022-08-25 16:07:02 +100016import {LitElement, css, html} from './lit.js';
Jason Linc80a23d2023-04-18 14:56:32 +100017import {FontManager, ORIGINAL_URL, backgroundImageLocalStorageKey, definePrefs,
18 delayedScheduler, fontManager, getOSInfo, sleep} from './terminal_common.js';
Jason Lin82ba86c2022-11-09 12:12:27 +110019import {TerminalContextMenu} from './terminal_context_menu.js';
Jason Lin6a402a72022-08-25 16:07:02 +100020import {ICON_COPY} from './terminal_icons.js';
Jason Lin83707c92022-09-20 19:09:41 +100021import {TerminalTooltip} from './terminal_tooltip.js';
Jason Linc80a23d2023-04-18 14:56:32 +100022import {Terminal, CanvasAddon, Unicode11Addon, WebLinksAddon, WebglAddon}
Joel Hockey0e164f02023-03-26 15:58:12 -070023 from './xterm.js';
Jason Lin2649da22022-10-12 10:16:44 +110024import {XtermInternal} from './terminal_xterm_internal.js';
Jason Linca61ffb2022-08-03 19:37:12 +100025
Jason Lin5690e752022-08-30 15:36:45 +100026
27/** @enum {number} */
28export const Modifier = {
29 Shift: 1 << 0,
30 Alt: 1 << 1,
31 Ctrl: 1 << 2,
32 Meta: 1 << 3,
33};
34
35// This is just a static map from key names to key codes. It helps make the code
36// a bit more readable.
Jason Lin97a04282023-03-06 10:36:56 +110037export const keyCodes = hterm.Parser.identifiers.keyCodes;
Jason Lin5690e752022-08-30 15:36:45 +100038
39/**
40 * Encode a key combo (i.e. modifiers + a normal key) to an unique number.
41 *
42 * @param {number} modifiers
43 * @param {number} keyCode
44 * @return {number}
45 */
46export function encodeKeyCombo(modifiers, keyCode) {
47 return keyCode << 4 | modifiers;
48}
49
50const OS_DEFAULT_BINDINGS = [
51 // Submit feedback.
52 encodeKeyCombo(Modifier.Alt | Modifier.Shift, keyCodes.I),
53 // Toggle chromevox.
54 encodeKeyCombo(Modifier.Ctrl | Modifier.Alt, keyCodes.Z),
55 // Switch input method.
56 encodeKeyCombo(Modifier.Ctrl, keyCodes.SPACE),
57
58 // Dock window left/right.
59 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_LEFT),
60 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_RIGHT),
61
62 // Maximize/minimize window.
63 encodeKeyCombo(Modifier.Alt, keyCodes.EQUAL),
64 encodeKeyCombo(Modifier.Alt, keyCodes.MINUS),
65];
66
67
Jason Linca61ffb2022-08-03 19:37:12 +100068const ANSI_COLOR_NAMES = [
69 'black',
70 'red',
71 'green',
72 'yellow',
73 'blue',
74 'magenta',
75 'cyan',
76 'white',
77 'brightBlack',
78 'brightRed',
79 'brightGreen',
80 'brightYellow',
81 'brightBlue',
82 'brightMagenta',
83 'brightCyan',
84 'brightWhite',
85];
86
Jason Linca61ffb2022-08-03 19:37:12 +100087/**
Jason Lin97a04282023-03-06 10:36:56 +110088 * The value is the CSI code to send when no modifier keys are pressed.
89 *
90 * @type {!Map<number, string>}
91 */
92const ARROW_AND_SIX_PACK_KEYS = new Map([
93 [keyCodes.UP, '\x1b[A'],
94 [keyCodes.DOWN, '\x1b[B'],
95 [keyCodes.RIGHT, '\x1b[C'],
96 [keyCodes.LEFT, '\x1b[D'],
97 // 6-pack keys.
98 [keyCodes.INSERT, '\x1b[2~'],
99 [keyCodes.DEL, '\x1b[3~'],
100 [keyCodes.HOME, '\x1b[H'],
101 [keyCodes.END, '\x1b[F'],
102 [keyCodes.PAGE_UP, '\x1b[5~'],
103 [keyCodes.PAGE_DOWN, '\x1b[6~'],
104]);
105
106/**
Jason Linabad7562022-08-22 14:49:05 +1000107 * @typedef {{
108 * term: !Terminal,
109 * fontManager: !FontManager,
Jason Lin2649da22022-10-12 10:16:44 +1100110 * xtermInternal: !XtermInternal,
Jason Linabad7562022-08-22 14:49:05 +1000111 * }}
112 */
113export let XtermTerminalTestParams;
114
115/**
Jason Lin5690e752022-08-30 15:36:45 +1000116 * Compute a control character for a given character.
117 *
118 * @param {string} ch
119 * @return {string}
120 */
121function ctl(ch) {
122 return String.fromCharCode(ch.charCodeAt(0) - 64);
123}
124
125/**
Jason Line99299a2023-03-31 13:36:35 +1100126 * Create a notification following hterm's style.
127 *
128 * @param {string} title
129 * @param {?string=} body
130 * @return {!Notification}
131 */
132function createNotification(title, body) {
133 const options = {icon: lib.resource.getDataUrl('hterm/images/icon-96')};
134 if (body) {
135 options.body = body;
136 }
137 return new Notification(`\u266A ${title} \u266A`, options);
138}
139
140/**
Jason Lin21d854f2022-08-22 14:49:59 +1000141 * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO
142 * because it always convert utf8 data to strings, which is not necessary for
143 * xterm.
144 */
145class XtermTerminalIO extends hterm.Terminal.IO {
146 /** @override */
147 writeUTF8(buffer) {
148 this.terminal_.write(new Uint8Array(buffer));
149 }
150
151 /** @override */
152 writelnUTF8(buffer) {
153 this.terminal_.writeln(new Uint8Array(buffer));
154 }
155
156 /** @override */
157 print(string) {
158 this.terminal_.write(string);
159 }
160
161 /** @override */
162 writeUTF16(string) {
163 this.print(string);
164 }
165
166 /** @override */
167 println(string) {
168 this.terminal_.writeln(string);
169 }
170
171 /** @override */
172 writelnUTF16(string) {
173 this.println(string);
174 }
175}
176
177/**
Jason Lin83707c92022-09-20 19:09:41 +1000178 * A custom link handler that:
179 *
180 * - Shows a tooltip with the url on a OSC 8 link. This is following what hterm
181 * is doing. Also, showing the tooltip is better for the security of the user
182 * because the link can have arbitrary text.
183 * - Uses our own way to open the window.
184 */
185class LinkHandler {
186 /**
187 * @param {!Terminal} term
188 */
189 constructor(term) {
190 this.term_ = term;
191 /** @type {?TerminalTooltip} */
192 this.tooltip_ = null;
193 }
194
195 /**
196 * @return {!TerminalTooltip}
197 */
198 getTooltip_() {
199 if (!this.tooltip_) {
200 this.tooltip_ = /** @type {!TerminalTooltip} */(
201 document.createElement('terminal-tooltip'));
202 this.tooltip_.classList.add('xterm-hover');
203 lib.notNull(this.term_.element).appendChild(this.tooltip_);
204 }
205 return this.tooltip_;
206 }
207
208 /**
209 * @param {!MouseEvent} ev
210 * @param {string} url
211 * @param {!Object} range
212 */
213 activate(ev, url, range) {
214 lib.f.openWindow(url, '_blank');
215 }
216
217 /**
218 * @param {!MouseEvent} ev
219 * @param {string} url
220 * @param {!Object} range
221 */
222 hover(ev, url, range) {
223 this.getTooltip_().show(url, {x: ev.clientX, y: ev.clientY});
224 }
225
226 /**
227 * @param {!MouseEvent} ev
228 * @param {string} url
229 * @param {!Object} range
230 */
231 leave(ev, url, range) {
232 this.getTooltip_().hide();
233 }
234}
235
Jason Linc7afb672022-10-11 15:54:17 +1100236class Bell {
237 constructor() {
238 this.showNotification = false;
239
240 /** @type {?Audio} */
241 this.audio_ = null;
242 /** @type {?Notification} */
243 this.notification_ = null;
244 this.coolDownUntil_ = 0;
245 }
246
247 /**
248 * Set whether a bell audio should be played.
249 *
250 * @param {boolean} value
251 */
252 set playAudio(value) {
253 this.audio_ = value ?
254 new Audio(lib.resource.getDataUrl('hterm/audio/bell')) : null;
255 }
256
257 ring() {
258 const now = Date.now();
259 if (now < this.coolDownUntil_) {
260 return;
261 }
262 this.coolDownUntil_ = now + 500;
263
264 this.audio_?.play();
265 if (this.showNotification && !document.hasFocus() && !this.notification_) {
Jason Line99299a2023-03-31 13:36:35 +1100266 this.notification_ = createNotification(document.title);
Jason Linc7afb672022-10-11 15:54:17 +1100267 // Close the notification after a timeout. Note that this is different
268 // from hterm's behavior, but I think it makes more sense to do so.
269 setTimeout(() => {
270 this.notification_.close();
271 this.notification_ = null;
272 }, 5000);
273 }
274 }
275}
276
Jason Lind3aacef2022-10-12 19:03:37 +1100277const A11Y_BUTTON_STYLE = `
278position: fixed;
279z-index: 10;
280right: 16px;
281`;
282
Jason Lina8adea52022-10-25 13:14:14 +1100283// TODO: we should subscribe to the xterm.js onscroll event, and
284// disable/enable the buttons accordingly. However, xterm.js does not seem to
285// emit the onscroll event when the viewport is scrolled by the mouse. See
286// https://github.com/xtermjs/xterm.js/issues/3864
287export class A11yButtons {
Jason Lind3aacef2022-10-12 19:03:37 +1100288 /**
289 * @param {!Terminal} term
Jason Lina8adea52022-10-25 13:14:14 +1100290 * @param {!hterm.AccessibilityReader} htermA11yReader
Jason Lind3aacef2022-10-12 19:03:37 +1100291 */
Jason Linc0f14fe2022-10-25 15:31:29 +1100292 constructor(term, htermA11yReader) {
Jason Lina8adea52022-10-25 13:14:14 +1100293 this.term_ = term;
294 this.htermA11yReader_ = htermA11yReader;
Jason Linc0f14fe2022-10-25 15:31:29 +1100295 this.pageUpButton = document.createElement('button');
296 this.pageUpButton.style.cssText = A11Y_BUTTON_STYLE;
297 this.pageUpButton.textContent =
Jason Lind3aacef2022-10-12 19:03:37 +1100298 hterm.messageManager.get('HTERM_BUTTON_PAGE_UP');
Jason Linc0f14fe2022-10-25 15:31:29 +1100299 this.pageUpButton.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100300 () => this.scrollPages_(-1));
Jason Lind3aacef2022-10-12 19:03:37 +1100301
Jason Linc0f14fe2022-10-25 15:31:29 +1100302 this.pageDownButton = document.createElement('button');
303 this.pageDownButton.style.cssText = A11Y_BUTTON_STYLE;
304 this.pageDownButton.textContent =
Jason Lind3aacef2022-10-12 19:03:37 +1100305 hterm.messageManager.get('HTERM_BUTTON_PAGE_DOWN');
Jason Linc0f14fe2022-10-25 15:31:29 +1100306 this.pageDownButton.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100307 () => this.scrollPages_(1));
Jason Lind3aacef2022-10-12 19:03:37 +1100308
309 this.resetPos_();
Jason Lind3aacef2022-10-12 19:03:37 +1100310
311 this.onSelectionChange_ = this.onSelectionChange_.bind(this);
312 }
313
314 /**
Jason Lina8adea52022-10-25 13:14:14 +1100315 * @param {number} amount
316 */
317 scrollPages_(amount) {
318 this.term_.scrollPages(amount);
319 this.announceScreenContent_();
320 }
321
322 announceScreenContent_() {
323 const activeBuffer = this.term_.buffer.active;
324
325 let percentScrolled = 100;
326 if (activeBuffer.baseY !== 0) {
327 percentScrolled = Math.round(
328 100 * activeBuffer.viewportY / activeBuffer.baseY);
329 }
330
331 let currentScreenContent = hterm.messageManager.get(
332 'HTERM_ANNOUNCE_CURRENT_SCREEN_HEADER',
333 [percentScrolled],
334 '$1% scrolled,');
335
336 currentScreenContent += '\n';
337
338 const rowEnd = Math.min(activeBuffer.viewportY + this.term_.rows,
339 activeBuffer.length);
340 for (let i = activeBuffer.viewportY; i < rowEnd; ++i) {
341 currentScreenContent +=
342 activeBuffer.getLine(i).translateToString(true) + '\n';
343 }
344 currentScreenContent = currentScreenContent.trim();
345
346 this.htermA11yReader_.assertiveAnnounce(currentScreenContent);
347 }
348
349 /**
Jason Lind3aacef2022-10-12 19:03:37 +1100350 * @param {boolean} enabled
351 */
352 setEnabled(enabled) {
353 if (enabled) {
354 document.addEventListener('selectionchange', this.onSelectionChange_);
355 } else {
356 this.resetPos_();
357 document.removeEventListener('selectionchange', this.onSelectionChange_);
358 }
359 }
360
361 resetPos_() {
Jason Linc0f14fe2022-10-25 15:31:29 +1100362 this.pageUpButton.style.top = '-200px';
363 this.pageDownButton.style.bottom = '-200px';
Jason Lind3aacef2022-10-12 19:03:37 +1100364 }
365
366 onSelectionChange_() {
367 this.resetPos_();
368
Jason Lin36b9fce2022-11-10 16:56:40 +1100369 const selectedElement = document.getSelection().anchorNode?.parentElement;
Jason Linc0f14fe2022-10-25 15:31:29 +1100370 if (selectedElement === this.pageUpButton) {
371 this.pageUpButton.style.top = '16px';
372 } else if (selectedElement === this.pageDownButton) {
373 this.pageDownButton.style.bottom = '16px';
Jason Lind3aacef2022-10-12 19:03:37 +1100374 }
375 }
376}
377
Jason Linee0c1f72022-10-18 17:17:26 +1100378const BACKGROUND_IMAGE_KEY = 'background-image';
379
380class BackgroundImageWatcher {
381 /**
382 * @param {!hterm.PreferenceManager} prefs
383 * @param {function(string)} onChange This is called with the background image
384 * (could be empty) whenever it changes.
385 */
386 constructor(prefs, onChange) {
387 this.prefs_ = prefs;
388 this.onChange_ = onChange;
Joel Hockey0e164f02023-03-26 15:58:12 -0700389 this.localStorageKey_ = backgroundImageLocalStorageKey(prefs);
Jason Linee0c1f72022-10-18 17:17:26 +1100390 }
391
392 /**
393 * Call once to start watching for background image changes.
394 */
395 watch() {
396 window.addEventListener('storage', (e) => {
Joel Hockey0e164f02023-03-26 15:58:12 -0700397 if (e.key === this.localStorageKey_) {
Jason Linee0c1f72022-10-18 17:17:26 +1100398 this.onChange_(this.getBackgroundImage());
399 }
400 });
401 this.prefs_.addObserver(BACKGROUND_IMAGE_KEY, () => {
402 this.onChange_(this.getBackgroundImage());
403 });
404 }
405
406 getBackgroundImage() {
Joel Hockey0e164f02023-03-26 15:58:12 -0700407 const image = window.localStorage.getItem(this.localStorageKey_);
Jason Linee0c1f72022-10-18 17:17:26 +1100408 if (image) {
409 return `url(${image})`;
410 }
411
412 return this.prefs_.getString(BACKGROUND_IMAGE_KEY);
413 }
414}
415
Jason Linb8f380a2022-10-25 13:15:56 +1100416let xtermTerminalStringsLoaded = false;
417
Jason Lin83707c92022-09-20 19:09:41 +1000418/**
Jason Linca61ffb2022-08-03 19:37:12 +1000419 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
420 * so that it can be used in existing code.
421 *
Jason Linca61ffb2022-08-03 19:37:12 +1000422 * @extends {hterm.Terminal}
423 * @unrestricted
424 */
Jason Linabad7562022-08-22 14:49:05 +1000425export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000426 /**
427 * @param {{
428 * storage: !lib.Storage,
429 * profileId: string,
Jason Linabad7562022-08-22 14:49:05 +1000430 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000431 * }} args
432 */
Jason Linc80a23d2023-04-18 14:56:32 +1000433 constructor({storage, profileId, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000434 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
435 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
436 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
437
Jason Lin8de3d282022-09-01 21:29:05 +1000438 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000439 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000440 /** @type {!hterm.PreferenceManager} */
441 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
Jason Linc48f7432022-10-13 17:28:30 +1100442 definePrefs(this.prefs_);
Jason Linca61ffb2022-08-03 19:37:12 +1000443
Jason Lin5690e752022-08-30 15:36:45 +1000444 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linfc8a3722022-09-07 17:49:18 +1000445 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Lin2649da22022-10-12 10:16:44 +1100446 this.xtermInternal_ = testParams?.xtermInternal ||
447 new XtermInternal(this.term);
Jason Linabad7562022-08-22 14:49:05 +1000448 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000449
Jason Linc80a23d2023-04-18 14:56:32 +1000450 this.renderAddonType_ = WebglAddon;
451 if (!document.createElement('canvas').getContext('webgl')) {
452 console.warn('Webgl is not supported. Fall back to canvas renderer');
453 this.renderAddonType_ = CanvasAddon;
454 }
455
Jason Linc2504ae2022-09-02 13:03:31 +1000456 /** @type {?Element} */
457 this.container_;
Jason Linc7afb672022-10-11 15:54:17 +1100458 this.bell_ = new Bell();
Jason Linc2504ae2022-09-02 13:03:31 +1000459 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000460 testParams ? 0 : 250);
461
Jason Lin83707c92022-09-20 19:09:41 +1000462 this.term.loadAddon(
463 new WebLinksAddon((e, uri) => lib.f.openWindow(uri, '_blank')));
Jason Lin4de4f382022-09-01 14:10:18 +1000464 this.term.loadAddon(new Unicode11Addon());
465 this.term.unicode.activeVersion = '11';
466
Jason Linabad7562022-08-22 14:49:05 +1000467 this.pendingFont_ = null;
468 this.scheduleRefreshFont_ = delayedScheduler(
469 () => this.refreshFont_(), 100);
470 document.fonts.addEventListener('loadingdone',
471 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000472
473 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000474 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000475
Jason Lin34a45322022-10-12 19:10:52 +1100476 this.term.onResize(({cols, rows}) => {
477 this.io.onTerminalResize(cols, rows);
478 if (this.prefs_.get('enable-resize-status')) {
479 this.showOverlay(`${cols} × ${rows}`);
480 }
481 });
Jason Lin21d854f2022-08-22 14:49:59 +1000482 // We could also use `this.io.sendString()` except for the nassh exit
483 // prompt, which only listens to onVTKeystroke().
484 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000485 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100486 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin83ef5ba2022-10-13 17:40:30 +1100487 this.term.onSelectionChange(() => {
488 if (this.prefs_.get('copy-on-select')) {
489 this.copySelection_();
490 }
491 });
Jason Linc7afb672022-10-11 15:54:17 +1100492 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000493
494 /**
495 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
496 *
497 * If a key combo is in the map:
498 *
499 * - The handler instead of xterm.js will handle the keydown event.
500 * - Keyup and keypress will be ignored by both us and xterm.js.
501 *
502 * We re-generate this map every time a relevant pref value is changed. This
503 * is ok because pref changes are rare.
504 *
505 * @type {!Map<number, function(!KeyboardEvent)>}
506 */
507 this.keyDownHandlers_ = new Map();
508 this.scheduleResetKeyDownHandlers_ =
509 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
510
Jason Lin97a04282023-03-06 10:36:56 +1100511 this.term.attachCustomKeyEventHandler((ev) => !this.handleKeyEvent_(ev));
Jason Linca61ffb2022-08-03 19:37:12 +1000512
Jason Lin21d854f2022-08-22 14:49:59 +1000513 this.io = new XtermTerminalIO(this);
514 this.notificationCenter_ = null;
Jason Lind3aacef2022-10-12 19:03:37 +1100515 this.htermA11yReader_ = null;
Jason Linc0f14fe2022-10-25 15:31:29 +1100516 this.a11yEnabled_ = false;
Jason Lind3aacef2022-10-12 19:03:37 +1100517 this.a11yButtons_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000518 this.copyNotice_ = null;
Jason Lin446f3d92022-10-13 17:34:21 +1100519 this.scrollOnOutputListener_ = null;
Jason Linee0c1f72022-10-18 17:17:26 +1100520 this.backgroundImageWatcher_ = new BackgroundImageWatcher(this.prefs_,
521 this.setBackgroundImage.bind(this));
Jason Linc80a23d2023-04-18 14:56:32 +1000522 this.renderAddon_ = null;
Jason Lina63d8ba2022-11-02 17:42:38 +1100523 this.userCSSElement_ = null;
524 this.userCSSTextElement_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000525
Jason Lin82ba86c2022-11-09 12:12:27 +1100526 this.contextMenu_ = /** @type {!TerminalContextMenu} */(
527 document.createElement('terminal-context-menu'));
528 this.contextMenu_.style.zIndex = 10;
529 this.contextMenu = {
530 setItems: (items) => this.contextMenu_.items = items,
531 };
532
Jason Lin83707c92022-09-20 19:09:41 +1000533 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000534 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000535 // The webgl cursor layer also paints the character under the cursor with
536 // this `cursorAccent` color. We use a completely transparent color here
537 // to effectively disable that.
538 cursorAccent: 'rgba(0, 0, 0, 0)',
539 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000540 selectionBackground: 'rgba(174, 203, 250, .6)',
541 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000542 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000543 };
544 this.observePrefs_();
Jason Linb8f380a2022-10-25 13:15:56 +1100545 if (!xtermTerminalStringsLoaded) {
546 xtermTerminalStringsLoaded = true;
547 Terminal.strings.promptLabel =
548 hterm.messageManager.get('TERMINAL_INPUT_LABEL');
549 Terminal.strings.tooMuchOutput =
550 hterm.messageManager.get('TERMINAL_TOO_MUCH_OUTPUT_MESSAGE');
551 }
Jason Linca61ffb2022-08-03 19:37:12 +1000552 }
553
Jason Linc7afb672022-10-11 15:54:17 +1100554 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100555 setWindowTitle(title) {
556 document.title = title;
557 }
558
559 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100560 ringBell() {
561 this.bell_.ring();
562 }
563
Jason Lin2649da22022-10-12 10:16:44 +1100564 /** @override */
565 print(str) {
566 this.xtermInternal_.print(str);
567 }
568
569 /** @override */
570 wipeContents() {
571 this.term.clear();
572 }
573
574 /** @override */
575 newLine() {
576 this.xtermInternal_.newLine();
577 }
578
579 /** @override */
580 cursorLeft(number) {
581 this.xtermInternal_.cursorLeft(number ?? 1);
582 }
583
Jason Lind3aacef2022-10-12 19:03:37 +1100584 /** @override */
585 setAccessibilityEnabled(enabled) {
Jason Linc0f14fe2022-10-25 15:31:29 +1100586 if (enabled === this.a11yEnabled_) {
587 return;
588 }
589 this.a11yEnabled_ = enabled;
590
Jason Lind3aacef2022-10-12 19:03:37 +1100591 this.a11yButtons_.setEnabled(enabled);
592 this.htermA11yReader_.setAccessibilityEnabled(enabled);
Jason Linc0f14fe2022-10-25 15:31:29 +1100593
594 if (enabled) {
595 this.xtermInternal_.enableA11y(this.a11yButtons_.pageUpButton,
596 this.a11yButtons_.pageDownButton);
597 } else {
598 this.xtermInternal_.disableA11y();
599 }
Jason Lind3aacef2022-10-12 19:03:37 +1100600 }
601
Jason Linee0c1f72022-10-18 17:17:26 +1100602 hasBackgroundImage() {
603 return !!this.container_.style.backgroundImage;
604 }
605
606 /** @override */
607 setBackgroundImage(image) {
608 this.container_.style.backgroundImage = image || '';
609 this.updateBackgroundColor_(this.prefs_.getString('background-color'));
610 }
611
Jason Linca61ffb2022-08-03 19:37:12 +1000612 /**
613 * Install stubs for stuff that we haven't implemented yet so that the code
614 * still runs.
615 */
616 installUnimplementedStubs_() {
617 this.keyboard = {
618 keyMap: {
619 keyDefs: [],
620 },
621 bindings: {
622 clear: () => {},
623 addBinding: () => {},
624 addBindings: () => {},
625 OsDefaults: {},
626 },
627 };
628 this.keyboard.keyMap.keyDefs[78] = {};
Joel Hockey965ea552023-02-19 22:08:04 -0800629 this.keyboard.keyMap.keyDefs[84] = {};
Jason Linca61ffb2022-08-03 19:37:12 +1000630
631 const methodNames = [
Joel Hockeyb89a9782022-10-16 22:00:12 -0700632 'eraseLine',
Joel Hockeyb89a9782022-10-16 22:00:12 -0700633 'setCursorColumn',
Jason Linca61ffb2022-08-03 19:37:12 +1000634 'setCursorPosition',
635 'setCursorVisible',
Joel Hockeyd78374f2022-11-02 23:05:53 -0700636 'uninstallKeyboard',
Jason Linca61ffb2022-08-03 19:37:12 +1000637 ];
638
639 for (const name of methodNames) {
640 this[name] = () => console.warn(`${name}() is not implemented`);
641 }
642
Jason Lin21d854f2022-08-22 14:49:59 +1000643 this.vt = {
644 resetParseState: () => {
645 console.warn('.vt.resetParseState() is not implemented');
646 },
647 };
Jason Linca61ffb2022-08-03 19:37:12 +1000648 }
649
Jason Line9231bc2022-09-01 13:54:02 +1000650 installEscapeSequenceHandlers_() {
651 // OSC 52 for copy.
652 this.term.parser.registerOscHandler(52, (args) => {
653 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
654 // parameter is used to select which of the X clipboards to address. Since
655 // we're not integrating with X, we treat them all the same.
656 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
657 if (!parsedArgs) {
658 return true;
659 }
660
661 let data;
662 try {
663 data = window.atob(parsedArgs[1]);
664 } catch (e) {
665 // If the user sent us invalid base64 content, silently ignore it.
666 return true;
667 }
668 const decoder = new TextDecoder();
669 const bytes = lib.codec.stringToCodeUnitArray(data);
670 this.copyString_(decoder.decode(bytes));
671
672 return true;
673 });
Jason Lin2649da22022-10-12 10:16:44 +1100674
Jason Line99299a2023-03-31 13:36:35 +1100675 // URxvt perl modules. We only support "notify".
676 this.term.parser.registerOscHandler(777, (args) => {
677 // Match 'notify;<title>[;<message>]'.
678 const match = args.match(/^notify;([^;]*)(?:;(.*))?$/);
679 if (match) {
680 createNotification(match[1], match[2]);
681 }
682
683 return true;
684 });
685
Jason Lin2649da22022-10-12 10:16:44 +1100686 this.xtermInternal_.installTmuxControlModeHandler(
687 (data) => this.onTmuxControlModeLine(data));
688 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000689 }
690
Jason Linca61ffb2022-08-03 19:37:12 +1000691 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000692 * Write data to the terminal.
693 *
694 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
695 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100696 * @param {function()=} callback Optional callback that fires when the data
697 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000698 */
Jason Lin2649da22022-10-12 10:16:44 +1100699 write(data, callback) {
700 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000701 }
702
703 /**
704 * Like `this.write()` but also write a line break.
705 *
706 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100707 * @param {function()=} callback Optional callback that fires when the data
708 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000709 */
Jason Lin2649da22022-10-12 10:16:44 +1100710 writeln(data, callback) {
711 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000712 }
713
Jason Linca61ffb2022-08-03 19:37:12 +1000714 get screenSize() {
715 return new hterm.Size(this.term.cols, this.term.rows);
716 }
717
718 /**
719 * Don't need to do anything.
720 *
721 * @override
722 */
723 installKeyboard() {}
724
725 /**
726 * @override
727 */
728 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000729 this.container_ = elem;
Jason Linee0c1f72022-10-18 17:17:26 +1100730 elem.style.backgroundSize = '100% 100%';
731
Jason Lin8de3d282022-09-01 21:29:05 +1000732 (async () => {
733 await new Promise((resolve) => this.prefs_.readStorage(resolve));
734 // This will trigger all the observers to set the terminal options before
735 // we call `this.term.open()`.
736 this.prefs_.notifyAll();
737
Jason Linc2504ae2022-09-02 13:03:31 +1000738 const screenPaddingSize = /** @type {number} */(
739 this.prefs_.get('screen-padding-size'));
740 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
741
Jason Linee0c1f72022-10-18 17:17:26 +1100742 this.setBackgroundImage(
743 this.backgroundImageWatcher_.getBackgroundImage());
744 this.backgroundImageWatcher_.watch();
745
Jason Lin8de3d282022-09-01 21:29:05 +1000746 this.inited_ = true;
747 this.term.open(elem);
Jason Lin1be92f52023-01-23 23:50:00 +1100748 this.xtermInternal_.addDimensionsObserver(() => this.scheduleFit_());
Jason Lin8de3d282022-09-01 21:29:05 +1000749
Jason Linc80a23d2023-04-18 14:56:32 +1000750 this.reloadRenderAddon_();
Jason Lin8de3d282022-09-01 21:29:05 +1000751 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 Linc80a23d2023-04-18 14:56:32 +1000955 reloadRenderAddon_() {
956 if (this.renderAddon_) {
957 this.renderAddon_.dispose();
Jason Linee0c1f72022-10-18 17:17:26 +1100958 }
Jason Linc80a23d2023-04-18 14:56:32 +1000959 this.renderAddon_ = new this.renderAddonType_();
960 this.term.loadAddon(this.renderAddon_);
Jason Linee0c1f72022-10-18 17:17:26 +1100961 }
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;
Jason Linc80a23d2023-04-18 14:56:32 +1000978 if (this.inited_) {
979 // Setting allowTransparency in the middle messes up rendering, so we
980 // need to reload it here.
981 this.reloadRenderAddon_();
Jason Linee0c1f72022-10-18 17:17:26 +1100982 }
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}) {
Jason Linc80a23d2023-04-18 14:56:32 +10001483 let emulator_type = 'hterm';
Jason Linca61ffb2022-08-03 19:37:12 +10001484
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
Jason Linc80a23d2023-04-18 14:56:32 +10001487 // testing a bit easier.
1488 if (ORIGINAL_URL.searchParams.get('emulator') !== 'hterm') {
1489 emulator_type = 'xterm.js';
1490 }
1491 console.log('Terminal emulator type: ', emulator_type);
Jason Linca61ffb2022-08-03 19:37:12 +10001492 }
1493
Jason Linc80a23d2023-04-18 14:56:32 +10001494 if (emulator_type === 'hterm') {
1495 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001496 }
Jason Linc80a23d2023-04-18 14:56:32 +10001497
1498 return new XtermTerminal({
1499 storage,
1500 profileId,
1501 });
Jason Linca61ffb2022-08-03 19:37:12 +10001502}
1503
Jason Lin6a402a72022-08-25 16:07:02 +10001504class TerminalCopyNotice extends LitElement {
1505 /** @override */
1506 static get styles() {
1507 return css`
1508 :host {
1509 display: block;
1510 text-align: center;
1511 }
1512
1513 svg {
1514 fill: currentColor;
1515 }
1516 `;
1517 }
1518
1519 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001520 connectedCallback() {
1521 super.connectedCallback();
1522 if (!this.childNodes.length) {
1523 // This is not visible since we use shadow dom. But this will allow the
1524 // hterm.NotificationCenter to announce the the copy text.
1525 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1526 }
1527 }
1528
1529 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001530 render() {
1531 return html`
1532 ${ICON_COPY}
1533 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1534 `;
1535 }
1536}
1537
1538customElements.define('terminal-copy-notice', TerminalCopyNotice);