blob: 904950892a94e57a59fea1d47281a9fc3ceb7341 [file] [log] [blame]
Mike Frysinger598e8012022-09-07 08:38:34 -04001// Copyright 2022 The ChromiumOS Authors
Jason Lind66e6bf2022-08-22 14:47:10 +10002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Jason Linca61ffb2022-08-03 19:37:12 +10005/**
6 * @fileoverview For supporting xterm.js and the terminal emulator.
7 */
8
9// TODO(b/236205389): add tests. For example, we should enable the test in
10// terminal_tests.js for XtermTerminal.
11
Jason Lin2649da22022-10-12 10:16:44 +110012// TODO(b/236205389): support option smoothScrollDuration?
13
Mike Frysinger75895da2022-10-04 00:42:28 +054514import {hterm, lib} from './deps_local.concat.js';
15
Jason Lin6a402a72022-08-25 16:07:02 +100016import {LitElement, css, html} from './lit.js';
Jason Linc48f7432022-10-13 17:28:30 +110017import {FontManager, ORIGINAL_URL, TERMINAL_EMULATORS, definePrefs,
18 delayedScheduler, fontManager, getOSInfo, sleep} from './terminal_common.js';
Jason 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 Linc2504ae2022-09-02 13:03:31 +100022import {Terminal, Unicode11Addon, WebLinksAddon, WebglAddon}
Jason Lin4de4f382022-09-01 14:10:18 +100023 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.
37const keyCodes = hterm.Parser.identifiers.keyCodes;
38
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 Linabad7562022-08-22 14:49:05 +100088 * @typedef {{
89 * term: !Terminal,
90 * fontManager: !FontManager,
Jason Lin2649da22022-10-12 10:16:44 +110091 * xtermInternal: !XtermInternal,
Jason Linabad7562022-08-22 14:49:05 +100092 * }}
93 */
94export let XtermTerminalTestParams;
95
96/**
Jason Lin5690e752022-08-30 15:36:45 +100097 * Compute a control character for a given character.
98 *
99 * @param {string} ch
100 * @return {string}
101 */
102function ctl(ch) {
103 return String.fromCharCode(ch.charCodeAt(0) - 64);
104}
105
106/**
Jason Lin21d854f2022-08-22 14:49:59 +1000107 * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO
108 * because it always convert utf8 data to strings, which is not necessary for
109 * xterm.
110 */
111class XtermTerminalIO extends hterm.Terminal.IO {
112 /** @override */
113 writeUTF8(buffer) {
114 this.terminal_.write(new Uint8Array(buffer));
115 }
116
117 /** @override */
118 writelnUTF8(buffer) {
119 this.terminal_.writeln(new Uint8Array(buffer));
120 }
121
122 /** @override */
123 print(string) {
124 this.terminal_.write(string);
125 }
126
127 /** @override */
128 writeUTF16(string) {
129 this.print(string);
130 }
131
132 /** @override */
133 println(string) {
134 this.terminal_.writeln(string);
135 }
136
137 /** @override */
138 writelnUTF16(string) {
139 this.println(string);
140 }
141}
142
143/**
Jason Lin83707c92022-09-20 19:09:41 +1000144 * A custom link handler that:
145 *
146 * - Shows a tooltip with the url on a OSC 8 link. This is following what hterm
147 * is doing. Also, showing the tooltip is better for the security of the user
148 * because the link can have arbitrary text.
149 * - Uses our own way to open the window.
150 */
151class LinkHandler {
152 /**
153 * @param {!Terminal} term
154 */
155 constructor(term) {
156 this.term_ = term;
157 /** @type {?TerminalTooltip} */
158 this.tooltip_ = null;
159 }
160
161 /**
162 * @return {!TerminalTooltip}
163 */
164 getTooltip_() {
165 if (!this.tooltip_) {
166 this.tooltip_ = /** @type {!TerminalTooltip} */(
167 document.createElement('terminal-tooltip'));
168 this.tooltip_.classList.add('xterm-hover');
169 lib.notNull(this.term_.element).appendChild(this.tooltip_);
170 }
171 return this.tooltip_;
172 }
173
174 /**
175 * @param {!MouseEvent} ev
176 * @param {string} url
177 * @param {!Object} range
178 */
179 activate(ev, url, range) {
180 lib.f.openWindow(url, '_blank');
181 }
182
183 /**
184 * @param {!MouseEvent} ev
185 * @param {string} url
186 * @param {!Object} range
187 */
188 hover(ev, url, range) {
189 this.getTooltip_().show(url, {x: ev.clientX, y: ev.clientY});
190 }
191
192 /**
193 * @param {!MouseEvent} ev
194 * @param {string} url
195 * @param {!Object} range
196 */
197 leave(ev, url, range) {
198 this.getTooltip_().hide();
199 }
200}
201
Jason Linc7afb672022-10-11 15:54:17 +1100202class Bell {
203 constructor() {
204 this.showNotification = false;
205
206 /** @type {?Audio} */
207 this.audio_ = null;
208 /** @type {?Notification} */
209 this.notification_ = null;
210 this.coolDownUntil_ = 0;
211 }
212
213 /**
214 * Set whether a bell audio should be played.
215 *
216 * @param {boolean} value
217 */
218 set playAudio(value) {
219 this.audio_ = value ?
220 new Audio(lib.resource.getDataUrl('hterm/audio/bell')) : null;
221 }
222
223 ring() {
224 const now = Date.now();
225 if (now < this.coolDownUntil_) {
226 return;
227 }
228 this.coolDownUntil_ = now + 500;
229
230 this.audio_?.play();
231 if (this.showNotification && !document.hasFocus() && !this.notification_) {
232 this.notification_ = new Notification(
233 `\u266A ${document.title} \u266A`,
234 {icon: lib.resource.getDataUrl('hterm/images/icon-96')});
235 // Close the notification after a timeout. Note that this is different
236 // from hterm's behavior, but I think it makes more sense to do so.
237 setTimeout(() => {
238 this.notification_.close();
239 this.notification_ = null;
240 }, 5000);
241 }
242 }
243}
244
Jason Lind3aacef2022-10-12 19:03:37 +1100245const A11Y_BUTTON_STYLE = `
246position: fixed;
247z-index: 10;
248right: 16px;
249`;
250
Jason Lina8adea52022-10-25 13:14:14 +1100251// TODO: we should subscribe to the xterm.js onscroll event, and
252// disable/enable the buttons accordingly. However, xterm.js does not seem to
253// emit the onscroll event when the viewport is scrolled by the mouse. See
254// https://github.com/xtermjs/xterm.js/issues/3864
255export class A11yButtons {
Jason Lind3aacef2022-10-12 19:03:37 +1100256 /**
257 * @param {!Terminal} term
Jason Lina8adea52022-10-25 13:14:14 +1100258 * @param {!hterm.AccessibilityReader} htermA11yReader
Jason Lind3aacef2022-10-12 19:03:37 +1100259 */
Jason Linc0f14fe2022-10-25 15:31:29 +1100260 constructor(term, htermA11yReader) {
Jason Lina8adea52022-10-25 13:14:14 +1100261 this.term_ = term;
262 this.htermA11yReader_ = htermA11yReader;
Jason Linc0f14fe2022-10-25 15:31:29 +1100263 this.pageUpButton = document.createElement('button');
264 this.pageUpButton.style.cssText = A11Y_BUTTON_STYLE;
265 this.pageUpButton.textContent =
Jason Lind3aacef2022-10-12 19:03:37 +1100266 hterm.messageManager.get('HTERM_BUTTON_PAGE_UP');
Jason Linc0f14fe2022-10-25 15:31:29 +1100267 this.pageUpButton.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100268 () => this.scrollPages_(-1));
Jason Lind3aacef2022-10-12 19:03:37 +1100269
Jason Linc0f14fe2022-10-25 15:31:29 +1100270 this.pageDownButton = document.createElement('button');
271 this.pageDownButton.style.cssText = A11Y_BUTTON_STYLE;
272 this.pageDownButton.textContent =
Jason Lind3aacef2022-10-12 19:03:37 +1100273 hterm.messageManager.get('HTERM_BUTTON_PAGE_DOWN');
Jason Linc0f14fe2022-10-25 15:31:29 +1100274 this.pageDownButton.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100275 () => this.scrollPages_(1));
Jason Lind3aacef2022-10-12 19:03:37 +1100276
277 this.resetPos_();
Jason Lind3aacef2022-10-12 19:03:37 +1100278
279 this.onSelectionChange_ = this.onSelectionChange_.bind(this);
280 }
281
282 /**
Jason Lina8adea52022-10-25 13:14:14 +1100283 * @param {number} amount
284 */
285 scrollPages_(amount) {
286 this.term_.scrollPages(amount);
287 this.announceScreenContent_();
288 }
289
290 announceScreenContent_() {
291 const activeBuffer = this.term_.buffer.active;
292
293 let percentScrolled = 100;
294 if (activeBuffer.baseY !== 0) {
295 percentScrolled = Math.round(
296 100 * activeBuffer.viewportY / activeBuffer.baseY);
297 }
298
299 let currentScreenContent = hterm.messageManager.get(
300 'HTERM_ANNOUNCE_CURRENT_SCREEN_HEADER',
301 [percentScrolled],
302 '$1% scrolled,');
303
304 currentScreenContent += '\n';
305
306 const rowEnd = Math.min(activeBuffer.viewportY + this.term_.rows,
307 activeBuffer.length);
308 for (let i = activeBuffer.viewportY; i < rowEnd; ++i) {
309 currentScreenContent +=
310 activeBuffer.getLine(i).translateToString(true) + '\n';
311 }
312 currentScreenContent = currentScreenContent.trim();
313
314 this.htermA11yReader_.assertiveAnnounce(currentScreenContent);
315 }
316
317 /**
Jason Lind3aacef2022-10-12 19:03:37 +1100318 * @param {boolean} enabled
319 */
320 setEnabled(enabled) {
321 if (enabled) {
322 document.addEventListener('selectionchange', this.onSelectionChange_);
323 } else {
324 this.resetPos_();
325 document.removeEventListener('selectionchange', this.onSelectionChange_);
326 }
327 }
328
329 resetPos_() {
Jason Linc0f14fe2022-10-25 15:31:29 +1100330 this.pageUpButton.style.top = '-200px';
331 this.pageDownButton.style.bottom = '-200px';
Jason Lind3aacef2022-10-12 19:03:37 +1100332 }
333
334 onSelectionChange_() {
335 this.resetPos_();
336
Jason Lin36b9fce2022-11-10 16:56:40 +1100337 const selectedElement = document.getSelection().anchorNode?.parentElement;
Jason Linc0f14fe2022-10-25 15:31:29 +1100338 if (selectedElement === this.pageUpButton) {
339 this.pageUpButton.style.top = '16px';
340 } else if (selectedElement === this.pageDownButton) {
341 this.pageDownButton.style.bottom = '16px';
Jason Lind3aacef2022-10-12 19:03:37 +1100342 }
343 }
344}
345
Jason Linee0c1f72022-10-18 17:17:26 +1100346const BACKGROUND_IMAGE_KEY = 'background-image';
347
348class BackgroundImageWatcher {
349 /**
350 * @param {!hterm.PreferenceManager} prefs
351 * @param {function(string)} onChange This is called with the background image
352 * (could be empty) whenever it changes.
353 */
354 constructor(prefs, onChange) {
355 this.prefs_ = prefs;
356 this.onChange_ = onChange;
357 }
358
359 /**
360 * Call once to start watching for background image changes.
361 */
362 watch() {
363 window.addEventListener('storage', (e) => {
364 if (e.key === BACKGROUND_IMAGE_KEY) {
365 this.onChange_(this.getBackgroundImage());
366 }
367 });
368 this.prefs_.addObserver(BACKGROUND_IMAGE_KEY, () => {
369 this.onChange_(this.getBackgroundImage());
370 });
371 }
372
373 getBackgroundImage() {
374 const image = window.localStorage.getItem(BACKGROUND_IMAGE_KEY);
375 if (image) {
376 return `url(${image})`;
377 }
378
379 return this.prefs_.getString(BACKGROUND_IMAGE_KEY);
380 }
381}
382
Jason Linb8f380a2022-10-25 13:15:56 +1100383let xtermTerminalStringsLoaded = false;
384
Jason Lin83707c92022-09-20 19:09:41 +1000385/**
Jason Linca61ffb2022-08-03 19:37:12 +1000386 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
387 * so that it can be used in existing code.
388 *
Jason Linca61ffb2022-08-03 19:37:12 +1000389 * @extends {hterm.Terminal}
390 * @unrestricted
391 */
Jason Linabad7562022-08-22 14:49:05 +1000392export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000393 /**
394 * @param {{
395 * storage: !lib.Storage,
396 * profileId: string,
397 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000398 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000399 * }} args
400 */
Jason Linabad7562022-08-22 14:49:05 +1000401 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000402 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
403 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
404 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
405
Jason Lin8de3d282022-09-01 21:29:05 +1000406 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000407 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000408 /** @type {!hterm.PreferenceManager} */
409 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
Jason Linc48f7432022-10-13 17:28:30 +1100410 definePrefs(this.prefs_);
Jason Linca61ffb2022-08-03 19:37:12 +1000411 this.enableWebGL_ = enableWebGL;
412
Jason Lin5690e752022-08-30 15:36:45 +1000413 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linfc8a3722022-09-07 17:49:18 +1000414 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Lin2649da22022-10-12 10:16:44 +1100415 this.xtermInternal_ = testParams?.xtermInternal ||
416 new XtermInternal(this.term);
Jason Linabad7562022-08-22 14:49:05 +1000417 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000418
Jason Linc2504ae2022-09-02 13:03:31 +1000419 /** @type {?Element} */
420 this.container_;
Jason Linc7afb672022-10-11 15:54:17 +1100421 this.bell_ = new Bell();
Jason Linc2504ae2022-09-02 13:03:31 +1000422 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000423 testParams ? 0 : 250);
424
Jason Lin83707c92022-09-20 19:09:41 +1000425 this.term.loadAddon(
426 new WebLinksAddon((e, uri) => lib.f.openWindow(uri, '_blank')));
Jason Lin4de4f382022-09-01 14:10:18 +1000427 this.term.loadAddon(new Unicode11Addon());
428 this.term.unicode.activeVersion = '11';
429
Jason Linabad7562022-08-22 14:49:05 +1000430 this.pendingFont_ = null;
431 this.scheduleRefreshFont_ = delayedScheduler(
432 () => this.refreshFont_(), 100);
433 document.fonts.addEventListener('loadingdone',
434 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000435
436 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000437 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000438
Jason Lin34a45322022-10-12 19:10:52 +1100439 this.term.onResize(({cols, rows}) => {
440 this.io.onTerminalResize(cols, rows);
441 if (this.prefs_.get('enable-resize-status')) {
442 this.showOverlay(`${cols} × ${rows}`);
443 }
444 });
Jason Lin21d854f2022-08-22 14:49:59 +1000445 // We could also use `this.io.sendString()` except for the nassh exit
446 // prompt, which only listens to onVTKeystroke().
447 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000448 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100449 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin83ef5ba2022-10-13 17:40:30 +1100450 this.term.onSelectionChange(() => {
451 if (this.prefs_.get('copy-on-select')) {
452 this.copySelection_();
453 }
454 });
Jason Linc7afb672022-10-11 15:54:17 +1100455 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000456
457 /**
458 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
459 *
460 * If a key combo is in the map:
461 *
462 * - The handler instead of xterm.js will handle the keydown event.
463 * - Keyup and keypress will be ignored by both us and xterm.js.
464 *
465 * We re-generate this map every time a relevant pref value is changed. This
466 * is ok because pref changes are rare.
467 *
468 * @type {!Map<number, function(!KeyboardEvent)>}
469 */
470 this.keyDownHandlers_ = new Map();
471 this.scheduleResetKeyDownHandlers_ =
472 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
473
474 this.term.attachCustomKeyEventHandler(
475 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000476
Jason Lin21d854f2022-08-22 14:49:59 +1000477 this.io = new XtermTerminalIO(this);
478 this.notificationCenter_ = null;
Jason Lind3aacef2022-10-12 19:03:37 +1100479 this.htermA11yReader_ = null;
Jason Linc0f14fe2022-10-25 15:31:29 +1100480 this.a11yEnabled_ = false;
Jason Lind3aacef2022-10-12 19:03:37 +1100481 this.a11yButtons_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000482 this.copyNotice_ = null;
Jason Lin446f3d92022-10-13 17:34:21 +1100483 this.scrollOnOutputListener_ = null;
Jason Linee0c1f72022-10-18 17:17:26 +1100484 this.backgroundImageWatcher_ = new BackgroundImageWatcher(this.prefs_,
485 this.setBackgroundImage.bind(this));
486 this.webglAddon_ = null;
Jason Lina63d8ba2022-11-02 17:42:38 +1100487 this.userCSSElement_ = null;
488 this.userCSSTextElement_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000489
Jason Lin82ba86c2022-11-09 12:12:27 +1100490 this.contextMenu_ = /** @type {!TerminalContextMenu} */(
491 document.createElement('terminal-context-menu'));
492 this.contextMenu_.style.zIndex = 10;
493 this.contextMenu = {
494 setItems: (items) => this.contextMenu_.items = items,
495 };
496
Jason Lin83707c92022-09-20 19:09:41 +1000497 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000498 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000499 // The webgl cursor layer also paints the character under the cursor with
500 // this `cursorAccent` color. We use a completely transparent color here
501 // to effectively disable that.
502 cursorAccent: 'rgba(0, 0, 0, 0)',
503 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000504 selectionBackground: 'rgba(174, 203, 250, .6)',
505 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000506 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000507 };
508 this.observePrefs_();
Jason Linb8f380a2022-10-25 13:15:56 +1100509 if (!xtermTerminalStringsLoaded) {
510 xtermTerminalStringsLoaded = true;
511 Terminal.strings.promptLabel =
512 hterm.messageManager.get('TERMINAL_INPUT_LABEL');
513 Terminal.strings.tooMuchOutput =
514 hterm.messageManager.get('TERMINAL_TOO_MUCH_OUTPUT_MESSAGE');
515 }
Jason Linca61ffb2022-08-03 19:37:12 +1000516 }
517
Jason Linc7afb672022-10-11 15:54:17 +1100518 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100519 setWindowTitle(title) {
520 document.title = title;
521 }
522
523 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100524 ringBell() {
525 this.bell_.ring();
526 }
527
Jason Lin2649da22022-10-12 10:16:44 +1100528 /** @override */
529 print(str) {
530 this.xtermInternal_.print(str);
531 }
532
533 /** @override */
534 wipeContents() {
535 this.term.clear();
536 }
537
538 /** @override */
539 newLine() {
540 this.xtermInternal_.newLine();
541 }
542
543 /** @override */
544 cursorLeft(number) {
545 this.xtermInternal_.cursorLeft(number ?? 1);
546 }
547
Jason Lind3aacef2022-10-12 19:03:37 +1100548 /** @override */
549 setAccessibilityEnabled(enabled) {
Jason Linc0f14fe2022-10-25 15:31:29 +1100550 if (enabled === this.a11yEnabled_) {
551 return;
552 }
553 this.a11yEnabled_ = enabled;
554
Jason Lind3aacef2022-10-12 19:03:37 +1100555 this.a11yButtons_.setEnabled(enabled);
556 this.htermA11yReader_.setAccessibilityEnabled(enabled);
Jason Linc0f14fe2022-10-25 15:31:29 +1100557
558 if (enabled) {
559 this.xtermInternal_.enableA11y(this.a11yButtons_.pageUpButton,
560 this.a11yButtons_.pageDownButton);
561 } else {
562 this.xtermInternal_.disableA11y();
563 }
Jason Lind3aacef2022-10-12 19:03:37 +1100564 }
565
Jason Linee0c1f72022-10-18 17:17:26 +1100566 hasBackgroundImage() {
567 return !!this.container_.style.backgroundImage;
568 }
569
570 /** @override */
571 setBackgroundImage(image) {
572 this.container_.style.backgroundImage = image || '';
573 this.updateBackgroundColor_(this.prefs_.getString('background-color'));
574 }
575
Jason Linca61ffb2022-08-03 19:37:12 +1000576 /**
577 * Install stubs for stuff that we haven't implemented yet so that the code
578 * still runs.
579 */
580 installUnimplementedStubs_() {
581 this.keyboard = {
582 keyMap: {
583 keyDefs: [],
584 },
585 bindings: {
586 clear: () => {},
587 addBinding: () => {},
588 addBindings: () => {},
589 OsDefaults: {},
590 },
591 };
592 this.keyboard.keyMap.keyDefs[78] = {};
Joel Hockey965ea552023-02-19 22:08:04 -0800593 this.keyboard.keyMap.keyDefs[84] = {};
Jason Linca61ffb2022-08-03 19:37:12 +1000594
595 const methodNames = [
Joel Hockeyb89a9782022-10-16 22:00:12 -0700596 'eraseLine',
Joel Hockeyb89a9782022-10-16 22:00:12 -0700597 'setCursorColumn',
Jason Linca61ffb2022-08-03 19:37:12 +1000598 'setCursorPosition',
599 'setCursorVisible',
Joel Hockeyd78374f2022-11-02 23:05:53 -0700600 'uninstallKeyboard',
Jason Linca61ffb2022-08-03 19:37:12 +1000601 ];
602
603 for (const name of methodNames) {
604 this[name] = () => console.warn(`${name}() is not implemented`);
605 }
606
Jason Lin21d854f2022-08-22 14:49:59 +1000607 this.vt = {
608 resetParseState: () => {
609 console.warn('.vt.resetParseState() is not implemented');
610 },
611 };
Jason Linca61ffb2022-08-03 19:37:12 +1000612 }
613
Jason Line9231bc2022-09-01 13:54:02 +1000614 installEscapeSequenceHandlers_() {
615 // OSC 52 for copy.
616 this.term.parser.registerOscHandler(52, (args) => {
617 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
618 // parameter is used to select which of the X clipboards to address. Since
619 // we're not integrating with X, we treat them all the same.
620 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
621 if (!parsedArgs) {
622 return true;
623 }
624
625 let data;
626 try {
627 data = window.atob(parsedArgs[1]);
628 } catch (e) {
629 // If the user sent us invalid base64 content, silently ignore it.
630 return true;
631 }
632 const decoder = new TextDecoder();
633 const bytes = lib.codec.stringToCodeUnitArray(data);
634 this.copyString_(decoder.decode(bytes));
635
636 return true;
637 });
Jason Lin2649da22022-10-12 10:16:44 +1100638
639 this.xtermInternal_.installTmuxControlModeHandler(
640 (data) => this.onTmuxControlModeLine(data));
641 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000642 }
643
Jason Linca61ffb2022-08-03 19:37:12 +1000644 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000645 * Write data to the terminal.
646 *
647 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
648 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100649 * @param {function()=} callback Optional callback that fires when the data
650 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000651 */
Jason Lin2649da22022-10-12 10:16:44 +1100652 write(data, callback) {
653 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000654 }
655
656 /**
657 * Like `this.write()` but also write a line break.
658 *
659 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100660 * @param {function()=} callback Optional callback that fires when the data
661 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000662 */
Jason Lin2649da22022-10-12 10:16:44 +1100663 writeln(data, callback) {
664 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000665 }
666
Jason Linca61ffb2022-08-03 19:37:12 +1000667 get screenSize() {
668 return new hterm.Size(this.term.cols, this.term.rows);
669 }
670
671 /**
672 * Don't need to do anything.
673 *
674 * @override
675 */
676 installKeyboard() {}
677
678 /**
679 * @override
680 */
681 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000682 this.container_ = elem;
Jason Linee0c1f72022-10-18 17:17:26 +1100683 elem.style.backgroundSize = '100% 100%';
684
Jason Lin8de3d282022-09-01 21:29:05 +1000685 (async () => {
686 await new Promise((resolve) => this.prefs_.readStorage(resolve));
687 // This will trigger all the observers to set the terminal options before
688 // we call `this.term.open()`.
689 this.prefs_.notifyAll();
690
Jason Linc2504ae2022-09-02 13:03:31 +1000691 const screenPaddingSize = /** @type {number} */(
692 this.prefs_.get('screen-padding-size'));
693 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
694
Jason Linee0c1f72022-10-18 17:17:26 +1100695 this.setBackgroundImage(
696 this.backgroundImageWatcher_.getBackgroundImage());
697 this.backgroundImageWatcher_.watch();
698
Jason Lin8de3d282022-09-01 21:29:05 +1000699 this.inited_ = true;
700 this.term.open(elem);
Jason Lin1be92f52023-01-23 23:50:00 +1100701 this.xtermInternal_.addDimensionsObserver(() => this.scheduleFit_());
Jason Lin8de3d282022-09-01 21:29:05 +1000702
Jason Lin8de3d282022-09-01 21:29:05 +1000703 if (this.enableWebGL_) {
Jason Linee0c1f72022-10-18 17:17:26 +1100704 this.reloadWebglAddon_();
Jason Lin8de3d282022-09-01 21:29:05 +1000705 }
706 this.term.focus();
707 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100708 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
709 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
710 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000711
Jason Lin82ba86c2022-11-09 12:12:27 +1100712 elem.appendChild(this.contextMenu_);
713
Jason Lin932b7432022-12-07 16:51:54 +1100714 elem.addEventListener('dragover', (e) => e.preventDefault());
715 elem.addEventListener('drop',
716 (e) => this.onDrop_(/** @type {!DragEvent} */(e)));
717
Jason Lin82ba86c2022-11-09 12:12:27 +1100718 // Block the default context menu from popping up.
Emil Mikulic2a194d02022-09-29 14:30:59 +1000719 elem.addEventListener('contextmenu', (e) => e.preventDefault());
720
721 // Add a handler for pasting with the mouse.
Jason Lin932b7432022-12-07 16:51:54 +1100722 elem.addEventListener('mousedown',
723 (e) => this.onMouseDown_(/** @type {!MouseEvent} */(e)));
Emil Mikulic2a194d02022-09-29 14:30:59 +1000724
Jason Lin2649da22022-10-12 10:16:44 +1100725 await this.scheduleFit_();
Jason Linc0f14fe2022-10-25 15:31:29 +1100726 this.a11yButtons_ = new A11yButtons(this.term, this.htermA11yReader_);
Jason Lind3aacef2022-10-12 19:03:37 +1100727
Jason Lin8de3d282022-09-01 21:29:05 +1000728 this.onTerminalReady();
729 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000730 }
731
732 /** @override */
733 showOverlay(msg, timeout = 1500) {
Jason Lin34a45322022-10-12 19:10:52 +1100734 this.notificationCenter_?.show(msg, {timeout});
Jason Lin21d854f2022-08-22 14:49:59 +1000735 }
736
737 /** @override */
738 hideOverlay() {
Jason Lin34a45322022-10-12 19:10:52 +1100739 this.notificationCenter_?.hide();
Jason Linca61ffb2022-08-03 19:37:12 +1000740 }
741
742 /** @override */
743 getPrefs() {
744 return this.prefs_;
745 }
746
747 /** @override */
748 getDocument() {
749 return window.document;
750 }
751
Jason Lin21d854f2022-08-22 14:49:59 +1000752 /** @override */
753 reset() {
754 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000755 }
756
757 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000758 setProfile(profileId, callback = undefined) {
759 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000760 }
761
Jason Lin21d854f2022-08-22 14:49:59 +1000762 /** @override */
763 interpret(string) {
764 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000765 }
766
Jason Lin21d854f2022-08-22 14:49:59 +1000767 /** @override */
768 focus() {
769 this.term.focus();
770 }
Jason Linca61ffb2022-08-03 19:37:12 +1000771
772 /** @override */
773 onOpenOptionsPage() {}
774
775 /** @override */
776 onTerminalReady() {}
777
Jason Lind04bab32022-08-22 14:48:39 +1000778 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000779 // This is for this.notificationCenter_.
780 const setHtermCSSVariable = (name, value) => {
781 document.body.style.setProperty(`--hterm-${name}`, value);
782 };
783
784 const setHtermColorCSSVariable = (name, color) => {
785 const css = lib.notNull(lib.colors.normalizeCSS(color));
786 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
787 setHtermCSSVariable(name, rgb);
788 };
789
790 this.prefs_.addObserver('font-size', (v) => {
Jason Lin1be92f52023-01-23 23:50:00 +1100791 this.term.options.fontSize = v;
Jason Lin21d854f2022-08-22 14:49:59 +1000792 setHtermCSSVariable('font-size', `${v}px`);
793 });
794
Jason Linda56aa92022-09-02 13:01:49 +1000795 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000796 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000797 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100798 this.bell_.playAudio = !!v;
799 },
800 'desktop-notification-bell': (v) => {
801 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000802 },
Jason Lind04bab32022-08-22 14:48:39 +1000803 'background-color': (v) => {
Jason Linee0c1f72022-10-18 17:17:26 +1100804 this.updateBackgroundColor_(v);
Jason Lin21d854f2022-08-22 14:49:59 +1000805 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000806 },
Jason Lind04bab32022-08-22 14:48:39 +1000807 'color-palette-overrides': (v) => {
808 if (!(v instanceof Array)) {
809 // For terminal, we always expect this to be an array.
810 console.warn('unexpected color palette: ', v);
811 return;
812 }
813 const colors = {};
814 for (let i = 0; i < v.length; ++i) {
815 colors[ANSI_COLOR_NAMES[i]] = v[i];
816 }
817 this.updateTheme_(colors);
818 },
Jason Lin1be92f52023-01-23 23:50:00 +1100819 'cursor-blink': (v) => {
820 this.term.options.cursorBlink = v;
821 },
Jason Linda56aa92022-09-02 13:01:49 +1000822 'cursor-color': (v) => this.updateTheme_({cursor: v}),
823 'cursor-shape': (v) => {
824 let shape;
825 if (v === 'BEAM') {
826 shape = 'bar';
827 } else {
828 shape = v.toLowerCase();
829 }
Jason Lin1be92f52023-01-23 23:50:00 +1100830 this.term.options.cursorStyle = shape;
Jason Linda56aa92022-09-02 13:01:49 +1000831 },
832 'font-family': (v) => this.updateFont_(v),
833 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000834 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000835 setHtermColorCSSVariable('foreground-color', v);
836 },
Jason Lin1be92f52023-01-23 23:50:00 +1100837 'line-height': (v) => {
838 this.term.options.lineHeight = v;
839 },
Jason Lin471e1062022-12-08 15:39:15 +1100840 'scroll-on-keystroke': (v) => {
Jason Lin1be92f52023-01-23 23:50:00 +1100841 this.term.options.scrollOnUserInput = v;
Jason Lin471e1062022-12-08 15:39:15 +1100842 },
Jason Lin446f3d92022-10-13 17:34:21 +1100843 'scroll-on-output': (v) => {
844 if (!v) {
845 this.scrollOnOutputListener_?.dispose();
846 this.scrollOnOutputListener_ = null;
847 return;
848 }
849 if (!this.scrollOnOutputListener_) {
850 this.scrollOnOutputListener_ = this.term.onWriteParsed(
851 () => this.term.scrollToBottom());
852 }
853 },
Jason Lina63d8ba2022-11-02 17:42:38 +1100854 'user-css': (v) => {
855 if (this.userCSSElement_) {
856 this.userCSSElement_.remove();
857 }
858 if (v) {
859 this.userCSSElement_ = document.createElement('link');
860 this.userCSSElement_.setAttribute('rel', 'stylesheet');
861 this.userCSSElement_.setAttribute('href', v);
862 document.head.appendChild(this.userCSSElement_);
863 }
864 },
865 'user-css-text': (v) => {
866 if (!this.userCSSTextElement_) {
867 this.userCSSTextElement_ = document.createElement('style');
868 document.head.appendChild(this.userCSSTextElement_);
869 }
870 this.userCSSTextElement_.textContent = v;
871 },
Jason Lind04bab32022-08-22 14:48:39 +1000872 });
Jason Lin5690e752022-08-30 15:36:45 +1000873
874 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
875 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
876 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
877 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
878 }
Jason Lind04bab32022-08-22 14:48:39 +1000879 }
880
881 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000882 * Fit the terminal to the containing HTML element.
883 */
884 fit_() {
885 if (!this.inited_) {
886 return;
887 }
888
889 const screenPaddingSize = /** @type {number} */(
890 this.prefs_.get('screen-padding-size'));
891
892 const calc = (size, cellSize) => {
893 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
894 };
895
Jason Lin2649da22022-10-12 10:16:44 +1100896 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
897 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
898 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000899 if (cols >= 0 && rows >= 0) {
900 this.term.resize(cols, rows);
901 }
902 }
903
Jason Linee0c1f72022-10-18 17:17:26 +1100904 reloadWebglAddon_() {
905 if (this.webglAddon_) {
906 this.webglAddon_.dispose();
907 }
908 this.webglAddon_ = new WebglAddon();
909 this.term.loadAddon(this.webglAddon_);
910 }
911
912 /**
913 * Update the background color. This will also adjust the transparency based
914 * on whether there is a background image.
915 *
916 * @param {string} color
917 */
918 updateBackgroundColor_(color) {
919 const hasBackgroundImage = this.hasBackgroundImage();
920
921 // We only set allowTransparency when it is necessary becuase 1) xterm.js
922 // documentation states that allowTransparency can affect performance; 2) I
923 // find that the rendering is better with allowTransparency being false.
924 // This could be a bug with xterm.js.
925 if (!!this.term.options.allowTransparency !== hasBackgroundImage) {
926 this.term.options.allowTransparency = hasBackgroundImage;
927 if (this.enableWebGL_ && this.inited_) {
928 // Setting allowTransparency in the middle messes up webgl rendering,
929 // so we need to reload it here.
930 this.reloadWebglAddon_();
931 }
932 }
933
934 if (this.hasBackgroundImage()) {
935 const css = lib.notNull(lib.colors.normalizeCSS(color));
936 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
937 // Note that we still want to set the RGB part correctly even though it is
938 // completely transparent. This is because the background color without
939 // the alpha channel is used in reverse video mode.
940 color = `rgba(${rgb}, 0)`;
941 }
942
943 this.updateTheme_({background: color});
944 }
945
Jason Linc2504ae2022-09-02 13:03:31 +1000946 /**
Jason Lind04bab32022-08-22 14:48:39 +1000947 * @param {!Object} theme
948 */
949 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000950 const updateTheme = (target) => {
951 for (const [key, value] of Object.entries(theme)) {
952 target[key] = lib.colors.normalizeCSS(value);
953 }
954 };
955
956 // Must use a new theme object to trigger re-render if we have initialized.
957 if (this.inited_) {
958 const newTheme = {...this.term.options.theme};
959 updateTheme(newTheme);
960 this.term.options.theme = newTheme;
961 return;
Jason Lind04bab32022-08-22 14:48:39 +1000962 }
Jason Lin8de3d282022-09-01 21:29:05 +1000963
964 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000965 }
966
967 /**
Jason Linabad7562022-08-22 14:49:05 +1000968 * Called when there is a "fontloadingdone" event. We need this because
969 * `FontManager.loadFont()` does not guarantee loading all the font files.
970 */
971 async onFontLoadingDone_() {
972 // If there is a pending font, the font is going to be refresh soon, so we
973 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000974 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000975 this.scheduleRefreshFont_();
976 }
977 }
978
Jason Lin932b7432022-12-07 16:51:54 +1100979 /**
980 * @param {!DragEvent} e
981 */
982 onDrop_(e) {
983 e.preventDefault();
984
985 // If the shift key active, try to find a "rich" text source (but not plain
986 // text). e.g. text/html is OK. This is the same behavior as hterm.
987 if (e.shiftKey) {
988 for (const type of e.dataTransfer.types) {
989 if (type !== 'text/plain' && type.startsWith('text/')) {
990 this.term.paste(e.dataTransfer.getData(type));
991 return;
992 }
993 }
994 }
995
996 this.term.paste(e.dataTransfer.getData('text/plain'));
997 }
998
999 /**
1000 * @param {!MouseEvent} e
1001 */
1002 async onMouseDown_(e) {
Jason Lin932b7432022-12-07 16:51:54 +11001003 if (this.term.modes.mouseTrackingMode !== 'none') {
1004 // xterm.js is in mouse mode and will handle the event.
1005 return;
1006 }
1007 const MIDDLE = 1;
1008 const RIGHT = 2;
1009
1010 if (e.button === RIGHT && e.ctrlKey) {
1011 this.contextMenu_.show({x: e.clientX, y: e.clientY});
1012 return;
1013 }
1014
1015 if (e.button === MIDDLE || (e.button === RIGHT &&
1016 this.prefs_.getBoolean('mouse-right-click-paste'))) {
1017 // Paste.
1018 if (navigator.clipboard && navigator.clipboard.readText) {
1019 const text = await navigator.clipboard.readText();
1020 this.term.paste(text);
1021 }
1022 }
1023 }
1024
Jason Lin5690e752022-08-30 15:36:45 +10001025 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +10001026 this.copyString_(this.term.getSelection());
1027 }
1028
1029 /** @param {string} data */
1030 copyString_(data) {
1031 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +10001032 return;
1033 }
Jason Line9231bc2022-09-01 13:54:02 +10001034 navigator.clipboard?.writeText(data);
Jason Lin83ef5ba2022-10-13 17:40:30 +11001035
1036 if (this.prefs_.get('enable-clipboard-notice')) {
1037 if (!this.copyNotice_) {
1038 this.copyNotice_ = document.createElement('terminal-copy-notice');
1039 }
1040 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500),
1041 200);
Jason Lin6a402a72022-08-25 16:07:02 +10001042 }
Jason Lin6a402a72022-08-25 16:07:02 +10001043 }
1044
Jason Linabad7562022-08-22 14:49:05 +10001045 /**
1046 * Refresh xterm rendering for a font related event.
1047 */
1048 refreshFont_() {
1049 // We have to set the fontFamily option to a different string to trigger the
1050 // re-rendering. Appending a space at the end seems to be the easiest
1051 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
1052 // us.
1053 //
1054 // TODO: Report a bug to xterm.js and ask for exposing a public function for
1055 // the refresh so that we don't need to do this hack.
1056 this.term.options.fontFamily += ' ';
1057 }
1058
1059 /**
1060 * Update a font.
1061 *
1062 * @param {string} cssFontFamily
1063 */
1064 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +10001065 this.pendingFont_ = cssFontFamily;
1066 await this.fontManager_.loadFont(cssFontFamily);
1067 // Sleep a bit to wait for flushing fontloadingdone events. This is not
1068 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
1069 // to refresh font unnecessarily in some cases.
1070 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +10001071
Jason Lin6a402a72022-08-25 16:07:02 +10001072 if (this.pendingFont_ !== cssFontFamily) {
1073 // `updateFont_()` probably is called again. Abort what we are doing.
1074 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
1075 ` (expecting ${cssFontFamily})`);
1076 return;
1077 }
Jason Linabad7562022-08-22 14:49:05 +10001078
Jason Lin6a402a72022-08-25 16:07:02 +10001079 if (this.term.options.fontFamily !== cssFontFamily) {
1080 this.term.options.fontFamily = cssFontFamily;
1081 } else {
1082 // If the font is already the same, refresh font just to be safe.
1083 this.refreshFont_();
1084 }
1085 this.pendingFont_ = null;
Jason Linabad7562022-08-22 14:49:05 +10001086 }
Jason Lin5690e752022-08-30 15:36:45 +10001087
1088 /**
1089 * @param {!KeyboardEvent} ev
1090 * @return {boolean} Return false if xterm.js should not handle the key event.
1091 */
1092 customKeyEventHandler_(ev) {
Jason Lin646dde02023-01-10 22:33:02 +11001093 // Without this, <alt-tab> (or <alt-shift-tab) is consumed by xterm.js
1094 // (instead the OS) when terminal is full screen.
1095 if (ev.altKey && ev.keyCode === 9) {
1096 return false;
1097 }
1098
Jason Lin5690e752022-08-30 15:36:45 +10001099 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
1100 (ev.altKey ? Modifier.Alt : 0) |
1101 (ev.ctrlKey ? Modifier.Ctrl : 0) |
1102 (ev.metaKey ? Modifier.Meta : 0);
1103 const handler = this.keyDownHandlers_.get(
1104 encodeKeyCombo(modifiers, ev.keyCode));
1105 if (handler) {
1106 if (ev.type === 'keydown') {
1107 handler(ev);
1108 }
1109 return false;
1110 }
1111
1112 return true;
1113 }
1114
1115 /**
1116 * A keydown handler for zoom-related keys.
1117 *
1118 * @param {!KeyboardEvent} ev
1119 */
1120 zoomKeyDownHandler_(ev) {
1121 ev.preventDefault();
1122
1123 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
1124 // The only one with a control code.
1125 if (ev.keyCode === keyCodes.MINUS) {
1126 this.io.onVTKeystroke('\x1f');
1127 }
1128 return;
1129 }
1130
1131 let newFontSize;
1132 switch (ev.keyCode) {
1133 case keyCodes.ZERO:
1134 newFontSize = this.prefs_.get('font-size');
1135 break;
1136 case keyCodes.MINUS:
1137 newFontSize = this.term.options.fontSize - 1;
1138 break;
1139 default:
1140 newFontSize = this.term.options.fontSize + 1;
1141 break;
1142 }
1143
Jason Lin1be92f52023-01-23 23:50:00 +11001144 this.term.options.fontSize = Math.max(1, newFontSize);
Jason Lin5690e752022-08-30 15:36:45 +10001145 }
1146
1147 /** @param {!KeyboardEvent} ev */
1148 ctrlCKeyDownHandler_(ev) {
1149 ev.preventDefault();
1150 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
1151 this.term.hasSelection()) {
1152 this.copySelection_();
1153 return;
1154 }
1155
1156 this.io.onVTKeystroke('\x03');
1157 }
1158
1159 /** @param {!KeyboardEvent} ev */
1160 ctrlVKeyDownHandler_(ev) {
1161 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
1162 // Don't do anything and let the browser handles the key.
1163 return;
1164 }
1165
1166 ev.preventDefault();
1167 this.io.onVTKeystroke('\x16');
1168 }
1169
1170 resetKeyDownHandlers_() {
1171 this.keyDownHandlers_.clear();
1172
1173 /**
1174 * Don't do anything and let the browser handles the key.
1175 *
1176 * @param {!KeyboardEvent} ev
1177 */
1178 const noop = (ev) => {};
1179
1180 /**
1181 * @param {number} modifiers
1182 * @param {number} keyCode
1183 * @param {function(!KeyboardEvent)} func
1184 */
1185 const set = (modifiers, keyCode, func) => {
1186 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
1187 func);
1188 };
1189
1190 /**
1191 * @param {number} modifiers
1192 * @param {number} keyCode
1193 * @param {function(!KeyboardEvent)} func
1194 */
1195 const setWithShiftVersion = (modifiers, keyCode, func) => {
1196 set(modifiers, keyCode, func);
1197 set(modifiers | Modifier.Shift, keyCode, func);
1198 };
1199
Jason Lin5690e752022-08-30 15:36:45 +10001200 // Ctrl+/
1201 set(Modifier.Ctrl, 191, (ev) => {
1202 ev.preventDefault();
1203 this.io.onVTKeystroke(ctl('_'));
1204 });
1205
1206 // Settings page.
1207 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
1208 ev.preventDefault();
1209 chrome.terminalPrivate.openOptionsPage(() => {});
1210 });
1211
1212 if (this.prefs_.get('keybindings-os-defaults')) {
1213 for (const binding of OS_DEFAULT_BINDINGS) {
1214 this.keyDownHandlers_.set(binding, noop);
1215 }
1216 }
1217
1218 /** @param {!KeyboardEvent} ev */
1219 const newWindow = (ev) => {
1220 ev.preventDefault();
1221 chrome.terminalPrivate.openWindow();
1222 };
1223 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
1224 if (this.prefs_.get('pass-ctrl-n')) {
1225 set(Modifier.Ctrl, keyCodes.N, newWindow);
1226 }
1227
Joel Hockey965ea552023-02-19 22:08:04 -08001228 /** @param {!KeyboardEvent} ev */
1229 const newTab = (ev) => {
1230 ev.preventDefault();
1231 chrome.terminalPrivate.openWindow(
1232 {asTab: true, url: '/html/terminal.html'});
1233 };
Jason Lin5690e752022-08-30 15:36:45 +10001234 if (this.prefs_.get('pass-ctrl-t')) {
Joel Hockey965ea552023-02-19 22:08:04 -08001235 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, newTab);
Jason Lin5690e752022-08-30 15:36:45 +10001236 }
1237
1238 if (this.prefs_.get('pass-ctrl-w')) {
1239 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
1240 }
1241
1242 if (this.prefs_.get('pass-ctrl-tab')) {
1243 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
1244 }
1245
1246 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
1247
1248 /**
1249 * Set a handler for the key combo ctrl+<number>.
1250 *
1251 * @param {number} number 1 to 9
1252 * @param {string} controlCode The control code to send if we don't want to
1253 * let the browser to handle it.
1254 */
1255 const setCtrlNumberHandler = (number, controlCode) => {
1256 let func = noop;
1257 if (!passCtrlNumber) {
1258 func = (ev) => {
1259 ev.preventDefault();
1260 this.io.onVTKeystroke(controlCode);
1261 };
1262 }
1263 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1264 };
1265
1266 setCtrlNumberHandler(1, '1');
1267 setCtrlNumberHandler(2, ctl('@'));
1268 setCtrlNumberHandler(3, ctl('['));
1269 setCtrlNumberHandler(4, ctl('\\'));
1270 setCtrlNumberHandler(5, ctl(']'));
1271 setCtrlNumberHandler(6, ctl('^'));
1272 setCtrlNumberHandler(7, ctl('_'));
1273 setCtrlNumberHandler(8, '\x7f');
1274 setCtrlNumberHandler(9, '9');
1275
1276 if (this.prefs_.get('pass-alt-number')) {
1277 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1278 set(Modifier.Alt, keyCode, noop);
1279 }
1280 }
1281
1282 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1283 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1284 }
1285
1286 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1287 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1288 }
Jason Linee0c1f72022-10-18 17:17:26 +11001289
1290 handleOnTerminalReady() {}
Jason Linca61ffb2022-08-03 19:37:12 +10001291}
1292
Jason Lind66e6bf2022-08-22 14:47:10 +10001293class HtermTerminal extends hterm.Terminal {
1294 /** @override */
1295 decorate(div) {
1296 super.decorate(div);
1297
Jason Linc48f7432022-10-13 17:28:30 +11001298 definePrefs(this.getPrefs());
Jason Linee0c1f72022-10-18 17:17:26 +11001299 }
Jason Linc48f7432022-10-13 17:28:30 +11001300
Jason Linee0c1f72022-10-18 17:17:26 +11001301 /**
1302 * This needs to be called in the `onTerminalReady()` callback. This is
1303 * awkward, but it is temporary since we will drop support for hterm at some
1304 * point.
1305 */
1306 handleOnTerminalReady() {
Jason Lind66e6bf2022-08-22 14:47:10 +10001307 const fontManager = new FontManager(this.getDocument());
1308 fontManager.loadPowerlineCSS().then(() => {
1309 const prefs = this.getPrefs();
1310 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1311 prefs.addObserver(
1312 'font-family',
1313 (v) => fontManager.loadFont(/** @type {string} */(v)));
1314 });
Jason Linee0c1f72022-10-18 17:17:26 +11001315
1316 const backgroundImageWatcher = new BackgroundImageWatcher(this.getPrefs(),
1317 (image) => this.setBackgroundImage(image));
1318 this.setBackgroundImage(backgroundImageWatcher.getBackgroundImage());
1319 backgroundImageWatcher.watch();
Jason Lind66e6bf2022-08-22 14:47:10 +10001320 }
Jason Lin2649da22022-10-12 10:16:44 +11001321
1322 /**
1323 * Write data to the terminal.
1324 *
1325 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1326 * UTF-8 data
1327 * @param {function()=} callback Optional callback that fires when the data
1328 * was processed by the parser.
1329 */
1330 write(data, callback) {
1331 if (typeof data === 'string') {
1332 this.io.print(data);
1333 } else {
1334 this.io.writeUTF8(data);
1335 }
1336 // Hterm processes the data synchronously, so we can call the callback
1337 // immediately.
1338 if (callback) {
1339 setTimeout(callback);
1340 }
1341 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001342}
1343
Jason Linca61ffb2022-08-03 19:37:12 +10001344/**
1345 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1346 * preference value.
1347 *
1348 * @param {{
1349 * storage: !lib.Storage,
1350 * profileId: string,
1351 * }} args
1352 * @return {!Promise<!hterm.Terminal>}
1353 */
1354export async function createEmulator({storage, profileId}) {
1355 let config = TERMINAL_EMULATORS.get('hterm');
1356
1357 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001358 // TODO: remove the url param logic. This is temporary to make manual
1359 // testing a bit easier, which is also why this is not in
1360 // './js/terminal_info.js'.
Jason Line10d6c42022-11-11 16:04:32 +11001361 const emulator = ORIGINAL_URL.searchParams.get('emulator');
Jason Linca61ffb2022-08-03 19:37:12 +10001362 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001363 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001364 TERMINAL_EMULATORS.values().next().value;
1365 console.log('Terminal emulator config: ', config);
1366 }
1367
1368 switch (config.lib) {
1369 case 'xterm.js':
1370 {
1371 const terminal = new XtermTerminal({
1372 storage,
1373 profileId,
1374 enableWebGL: config.webgl,
1375 });
Jason Linca61ffb2022-08-03 19:37:12 +10001376 return terminal;
1377 }
1378 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001379 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001380 default:
1381 throw new Error('incorrect emulator config');
1382 }
1383}
1384
Jason Lin6a402a72022-08-25 16:07:02 +10001385class TerminalCopyNotice extends LitElement {
1386 /** @override */
1387 static get styles() {
1388 return css`
1389 :host {
1390 display: block;
1391 text-align: center;
1392 }
1393
1394 svg {
1395 fill: currentColor;
1396 }
1397 `;
1398 }
1399
1400 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001401 connectedCallback() {
1402 super.connectedCallback();
1403 if (!this.childNodes.length) {
1404 // This is not visible since we use shadow dom. But this will allow the
1405 // hterm.NotificationCenter to announce the the copy text.
1406 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1407 }
1408 }
1409
1410 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001411 render() {
1412 return html`
1413 ${ICON_COPY}
1414 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1415 `;
1416 }
1417}
1418
1419customElements.define('terminal-copy-notice', TerminalCopyNotice);