blob: 0cb0d4876be509a3db7edc4af68030dd0277443d [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] = {};
593
594 const methodNames = [
Joel Hockeyb89a9782022-10-16 22:00:12 -0700595 'eraseLine',
Joel Hockeyb89a9782022-10-16 22:00:12 -0700596 'setCursorColumn',
Jason Linca61ffb2022-08-03 19:37:12 +1000597 'setCursorPosition',
598 'setCursorVisible',
Joel Hockeyd78374f2022-11-02 23:05:53 -0700599 'uninstallKeyboard',
Jason Linca61ffb2022-08-03 19:37:12 +1000600 ];
601
602 for (const name of methodNames) {
603 this[name] = () => console.warn(`${name}() is not implemented`);
604 }
605
Jason Lin21d854f2022-08-22 14:49:59 +1000606 this.vt = {
607 resetParseState: () => {
608 console.warn('.vt.resetParseState() is not implemented');
609 },
610 };
Jason Linca61ffb2022-08-03 19:37:12 +1000611 }
612
Jason Line9231bc2022-09-01 13:54:02 +1000613 installEscapeSequenceHandlers_() {
614 // OSC 52 for copy.
615 this.term.parser.registerOscHandler(52, (args) => {
616 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
617 // parameter is used to select which of the X clipboards to address. Since
618 // we're not integrating with X, we treat them all the same.
619 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
620 if (!parsedArgs) {
621 return true;
622 }
623
624 let data;
625 try {
626 data = window.atob(parsedArgs[1]);
627 } catch (e) {
628 // If the user sent us invalid base64 content, silently ignore it.
629 return true;
630 }
631 const decoder = new TextDecoder();
632 const bytes = lib.codec.stringToCodeUnitArray(data);
633 this.copyString_(decoder.decode(bytes));
634
635 return true;
636 });
Jason Lin2649da22022-10-12 10:16:44 +1100637
638 this.xtermInternal_.installTmuxControlModeHandler(
639 (data) => this.onTmuxControlModeLine(data));
640 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000641 }
642
Jason Linca61ffb2022-08-03 19:37:12 +1000643 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000644 * Write data to the terminal.
645 *
646 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
647 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100648 * @param {function()=} callback Optional callback that fires when the data
649 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000650 */
Jason Lin2649da22022-10-12 10:16:44 +1100651 write(data, callback) {
652 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000653 }
654
655 /**
656 * Like `this.write()` but also write a line break.
657 *
658 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100659 * @param {function()=} callback Optional callback that fires when the data
660 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000661 */
Jason Lin2649da22022-10-12 10:16:44 +1100662 writeln(data, callback) {
663 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000664 }
665
Jason Linca61ffb2022-08-03 19:37:12 +1000666 get screenSize() {
667 return new hterm.Size(this.term.cols, this.term.rows);
668 }
669
670 /**
671 * Don't need to do anything.
672 *
673 * @override
674 */
675 installKeyboard() {}
676
677 /**
678 * @override
679 */
680 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000681 this.container_ = elem;
Jason Linee0c1f72022-10-18 17:17:26 +1100682 elem.style.backgroundSize = '100% 100%';
683
Jason Lin8de3d282022-09-01 21:29:05 +1000684 (async () => {
685 await new Promise((resolve) => this.prefs_.readStorage(resolve));
686 // This will trigger all the observers to set the terminal options before
687 // we call `this.term.open()`.
688 this.prefs_.notifyAll();
689
Jason Linc2504ae2022-09-02 13:03:31 +1000690 const screenPaddingSize = /** @type {number} */(
691 this.prefs_.get('screen-padding-size'));
692 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
693
Jason Linee0c1f72022-10-18 17:17:26 +1100694 this.setBackgroundImage(
695 this.backgroundImageWatcher_.getBackgroundImage());
696 this.backgroundImageWatcher_.watch();
697
Jason Lin8de3d282022-09-01 21:29:05 +1000698 this.inited_ = true;
699 this.term.open(elem);
700
Jason Lin8de3d282022-09-01 21:29:05 +1000701 if (this.enableWebGL_) {
Jason Linee0c1f72022-10-18 17:17:26 +1100702 this.reloadWebglAddon_();
Jason Lin8de3d282022-09-01 21:29:05 +1000703 }
704 this.term.focus();
705 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100706 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
707 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
708 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000709
Jason Lin82ba86c2022-11-09 12:12:27 +1100710 elem.appendChild(this.contextMenu_);
711
Jason Lin932b7432022-12-07 16:51:54 +1100712 elem.addEventListener('dragover', (e) => e.preventDefault());
713 elem.addEventListener('drop',
714 (e) => this.onDrop_(/** @type {!DragEvent} */(e)));
715
Jason Lin82ba86c2022-11-09 12:12:27 +1100716 // Block the default context menu from popping up.
Emil Mikulic2a194d02022-09-29 14:30:59 +1000717 elem.addEventListener('contextmenu', (e) => e.preventDefault());
718
719 // Add a handler for pasting with the mouse.
Jason Lin932b7432022-12-07 16:51:54 +1100720 elem.addEventListener('mousedown',
721 (e) => this.onMouseDown_(/** @type {!MouseEvent} */(e)));
Emil Mikulic2a194d02022-09-29 14:30:59 +1000722
Jason Lin2649da22022-10-12 10:16:44 +1100723 await this.scheduleFit_();
Jason Linc0f14fe2022-10-25 15:31:29 +1100724 this.a11yButtons_ = new A11yButtons(this.term, this.htermA11yReader_);
Jason Lind3aacef2022-10-12 19:03:37 +1100725
Jason Lin8de3d282022-09-01 21:29:05 +1000726 this.onTerminalReady();
727 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000728 }
729
730 /** @override */
731 showOverlay(msg, timeout = 1500) {
Jason Lin34a45322022-10-12 19:10:52 +1100732 this.notificationCenter_?.show(msg, {timeout});
Jason Lin21d854f2022-08-22 14:49:59 +1000733 }
734
735 /** @override */
736 hideOverlay() {
Jason Lin34a45322022-10-12 19:10:52 +1100737 this.notificationCenter_?.hide();
Jason Linca61ffb2022-08-03 19:37:12 +1000738 }
739
740 /** @override */
741 getPrefs() {
742 return this.prefs_;
743 }
744
745 /** @override */
746 getDocument() {
747 return window.document;
748 }
749
Jason Lin21d854f2022-08-22 14:49:59 +1000750 /** @override */
751 reset() {
752 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000753 }
754
755 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000756 setProfile(profileId, callback = undefined) {
757 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000758 }
759
Jason Lin21d854f2022-08-22 14:49:59 +1000760 /** @override */
761 interpret(string) {
762 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000763 }
764
Jason Lin21d854f2022-08-22 14:49:59 +1000765 /** @override */
766 focus() {
767 this.term.focus();
768 }
Jason Linca61ffb2022-08-03 19:37:12 +1000769
770 /** @override */
771 onOpenOptionsPage() {}
772
773 /** @override */
774 onTerminalReady() {}
775
Jason Lind04bab32022-08-22 14:48:39 +1000776 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000777 // This is for this.notificationCenter_.
778 const setHtermCSSVariable = (name, value) => {
779 document.body.style.setProperty(`--hterm-${name}`, value);
780 };
781
782 const setHtermColorCSSVariable = (name, color) => {
783 const css = lib.notNull(lib.colors.normalizeCSS(color));
784 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
785 setHtermCSSVariable(name, rgb);
786 };
787
788 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000789 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000790 setHtermCSSVariable('font-size', `${v}px`);
791 });
792
Jason Linda56aa92022-09-02 13:01:49 +1000793 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000794 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000795 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100796 this.bell_.playAudio = !!v;
797 },
798 'desktop-notification-bell': (v) => {
799 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000800 },
Jason Lind04bab32022-08-22 14:48:39 +1000801 'background-color': (v) => {
Jason Linee0c1f72022-10-18 17:17:26 +1100802 this.updateBackgroundColor_(v);
Jason Lin21d854f2022-08-22 14:49:59 +1000803 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000804 },
Jason Lind04bab32022-08-22 14:48:39 +1000805 'color-palette-overrides': (v) => {
806 if (!(v instanceof Array)) {
807 // For terminal, we always expect this to be an array.
808 console.warn('unexpected color palette: ', v);
809 return;
810 }
811 const colors = {};
812 for (let i = 0; i < v.length; ++i) {
813 colors[ANSI_COLOR_NAMES[i]] = v[i];
814 }
815 this.updateTheme_(colors);
816 },
Jason Linda56aa92022-09-02 13:01:49 +1000817 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
818 'cursor-color': (v) => this.updateTheme_({cursor: v}),
819 'cursor-shape': (v) => {
820 let shape;
821 if (v === 'BEAM') {
822 shape = 'bar';
823 } else {
824 shape = v.toLowerCase();
825 }
826 this.updateOption_('cursorStyle', shape, false);
827 },
828 'font-family': (v) => this.updateFont_(v),
829 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000830 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000831 setHtermColorCSSVariable('foreground-color', v);
832 },
Jason Linc48f7432022-10-13 17:28:30 +1100833 'line-height': (v) => this.updateOption_('lineHeight', v, true),
Jason Lin471e1062022-12-08 15:39:15 +1100834 'scroll-on-keystroke': (v) => {
835 this.updateOption_('scrollOnUserInput', v, false);
836 },
Jason Lin446f3d92022-10-13 17:34:21 +1100837 'scroll-on-output': (v) => {
838 if (!v) {
839 this.scrollOnOutputListener_?.dispose();
840 this.scrollOnOutputListener_ = null;
841 return;
842 }
843 if (!this.scrollOnOutputListener_) {
844 this.scrollOnOutputListener_ = this.term.onWriteParsed(
845 () => this.term.scrollToBottom());
846 }
847 },
Jason Lina63d8ba2022-11-02 17:42:38 +1100848 'user-css': (v) => {
849 if (this.userCSSElement_) {
850 this.userCSSElement_.remove();
851 }
852 if (v) {
853 this.userCSSElement_ = document.createElement('link');
854 this.userCSSElement_.setAttribute('rel', 'stylesheet');
855 this.userCSSElement_.setAttribute('href', v);
856 document.head.appendChild(this.userCSSElement_);
857 }
858 },
859 'user-css-text': (v) => {
860 if (!this.userCSSTextElement_) {
861 this.userCSSTextElement_ = document.createElement('style');
862 document.head.appendChild(this.userCSSTextElement_);
863 }
864 this.userCSSTextElement_.textContent = v;
865 },
Jason Lind04bab32022-08-22 14:48:39 +1000866 });
Jason Lin5690e752022-08-30 15:36:45 +1000867
868 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
869 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
870 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
871 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
872 }
Jason Lind04bab32022-08-22 14:48:39 +1000873 }
874
875 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000876 * Fit the terminal to the containing HTML element.
877 */
878 fit_() {
879 if (!this.inited_) {
880 return;
881 }
882
883 const screenPaddingSize = /** @type {number} */(
884 this.prefs_.get('screen-padding-size'));
885
886 const calc = (size, cellSize) => {
887 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
888 };
889
Jason Lin2649da22022-10-12 10:16:44 +1100890 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
891 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
892 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000893 if (cols >= 0 && rows >= 0) {
894 this.term.resize(cols, rows);
895 }
896 }
897
Jason Linee0c1f72022-10-18 17:17:26 +1100898 reloadWebglAddon_() {
899 if (this.webglAddon_) {
900 this.webglAddon_.dispose();
901 }
902 this.webglAddon_ = new WebglAddon();
903 this.term.loadAddon(this.webglAddon_);
904 }
905
906 /**
907 * Update the background color. This will also adjust the transparency based
908 * on whether there is a background image.
909 *
910 * @param {string} color
911 */
912 updateBackgroundColor_(color) {
913 const hasBackgroundImage = this.hasBackgroundImage();
914
915 // We only set allowTransparency when it is necessary becuase 1) xterm.js
916 // documentation states that allowTransparency can affect performance; 2) I
917 // find that the rendering is better with allowTransparency being false.
918 // This could be a bug with xterm.js.
919 if (!!this.term.options.allowTransparency !== hasBackgroundImage) {
920 this.term.options.allowTransparency = hasBackgroundImage;
921 if (this.enableWebGL_ && this.inited_) {
922 // Setting allowTransparency in the middle messes up webgl rendering,
923 // so we need to reload it here.
924 this.reloadWebglAddon_();
925 }
926 }
927
928 if (this.hasBackgroundImage()) {
929 const css = lib.notNull(lib.colors.normalizeCSS(color));
930 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
931 // Note that we still want to set the RGB part correctly even though it is
932 // completely transparent. This is because the background color without
933 // the alpha channel is used in reverse video mode.
934 color = `rgba(${rgb}, 0)`;
935 }
936
937 this.updateTheme_({background: color});
938 }
939
Jason Linc2504ae2022-09-02 13:03:31 +1000940 /**
Jason Lind04bab32022-08-22 14:48:39 +1000941 * @param {!Object} theme
942 */
943 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000944 const updateTheme = (target) => {
945 for (const [key, value] of Object.entries(theme)) {
946 target[key] = lib.colors.normalizeCSS(value);
947 }
948 };
949
950 // Must use a new theme object to trigger re-render if we have initialized.
951 if (this.inited_) {
952 const newTheme = {...this.term.options.theme};
953 updateTheme(newTheme);
954 this.term.options.theme = newTheme;
955 return;
Jason Lind04bab32022-08-22 14:48:39 +1000956 }
Jason Lin8de3d282022-09-01 21:29:05 +1000957
958 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000959 }
960
961 /**
Jason Linda56aa92022-09-02 13:01:49 +1000962 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
963 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000964 *
965 * @param {string} key
966 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000967 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000968 */
Jason Linda56aa92022-09-02 13:01:49 +1000969 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000970 // TODO: xterm supports updating multiple options at the same time. We
971 // should probably do that.
972 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000973 if (scheduleFit) {
974 this.scheduleFit_();
975 }
Jason Lind04bab32022-08-22 14:48:39 +1000976 }
Jason Linabad7562022-08-22 14:49:05 +1000977
978 /**
979 * Called when there is a "fontloadingdone" event. We need this because
980 * `FontManager.loadFont()` does not guarantee loading all the font files.
981 */
982 async onFontLoadingDone_() {
983 // If there is a pending font, the font is going to be refresh soon, so we
984 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000985 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000986 this.scheduleRefreshFont_();
987 }
988 }
989
Jason Lin932b7432022-12-07 16:51:54 +1100990 /**
991 * @param {!DragEvent} e
992 */
993 onDrop_(e) {
994 e.preventDefault();
995
996 // If the shift key active, try to find a "rich" text source (but not plain
997 // text). e.g. text/html is OK. This is the same behavior as hterm.
998 if (e.shiftKey) {
999 for (const type of e.dataTransfer.types) {
1000 if (type !== 'text/plain' && type.startsWith('text/')) {
1001 this.term.paste(e.dataTransfer.getData(type));
1002 return;
1003 }
1004 }
1005 }
1006
1007 this.term.paste(e.dataTransfer.getData('text/plain'));
1008 }
1009
1010 /**
1011 * @param {!MouseEvent} e
1012 */
1013 async onMouseDown_(e) {
1014 this.contextMenu_.hide();
1015 if (this.term.modes.mouseTrackingMode !== 'none') {
1016 // xterm.js is in mouse mode and will handle the event.
1017 return;
1018 }
1019 const MIDDLE = 1;
1020 const RIGHT = 2;
1021
1022 if (e.button === RIGHT && e.ctrlKey) {
1023 this.contextMenu_.show({x: e.clientX, y: e.clientY});
1024 return;
1025 }
1026
1027 if (e.button === MIDDLE || (e.button === RIGHT &&
1028 this.prefs_.getBoolean('mouse-right-click-paste'))) {
1029 // Paste.
1030 if (navigator.clipboard && navigator.clipboard.readText) {
1031 const text = await navigator.clipboard.readText();
1032 this.term.paste(text);
1033 }
1034 }
1035 }
1036
Jason Lin5690e752022-08-30 15:36:45 +10001037 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +10001038 this.copyString_(this.term.getSelection());
1039 }
1040
1041 /** @param {string} data */
1042 copyString_(data) {
1043 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +10001044 return;
1045 }
Jason Line9231bc2022-09-01 13:54:02 +10001046 navigator.clipboard?.writeText(data);
Jason Lin83ef5ba2022-10-13 17:40:30 +11001047
1048 if (this.prefs_.get('enable-clipboard-notice')) {
1049 if (!this.copyNotice_) {
1050 this.copyNotice_ = document.createElement('terminal-copy-notice');
1051 }
1052 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500),
1053 200);
Jason Lin6a402a72022-08-25 16:07:02 +10001054 }
Jason Lin6a402a72022-08-25 16:07:02 +10001055 }
1056
Jason Linabad7562022-08-22 14:49:05 +10001057 /**
1058 * Refresh xterm rendering for a font related event.
1059 */
1060 refreshFont_() {
1061 // We have to set the fontFamily option to a different string to trigger the
1062 // re-rendering. Appending a space at the end seems to be the easiest
1063 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
1064 // us.
1065 //
1066 // TODO: Report a bug to xterm.js and ask for exposing a public function for
1067 // the refresh so that we don't need to do this hack.
1068 this.term.options.fontFamily += ' ';
1069 }
1070
1071 /**
1072 * Update a font.
1073 *
1074 * @param {string} cssFontFamily
1075 */
1076 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +10001077 this.pendingFont_ = cssFontFamily;
1078 await this.fontManager_.loadFont(cssFontFamily);
1079 // Sleep a bit to wait for flushing fontloadingdone events. This is not
1080 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
1081 // to refresh font unnecessarily in some cases.
1082 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +10001083
Jason Lin6a402a72022-08-25 16:07:02 +10001084 if (this.pendingFont_ !== cssFontFamily) {
1085 // `updateFont_()` probably is called again. Abort what we are doing.
1086 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
1087 ` (expecting ${cssFontFamily})`);
1088 return;
1089 }
Jason Linabad7562022-08-22 14:49:05 +10001090
Jason Lin6a402a72022-08-25 16:07:02 +10001091 if (this.term.options.fontFamily !== cssFontFamily) {
1092 this.term.options.fontFamily = cssFontFamily;
1093 } else {
1094 // If the font is already the same, refresh font just to be safe.
1095 this.refreshFont_();
1096 }
1097 this.pendingFont_ = null;
1098 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +10001099 }
Jason Lin5690e752022-08-30 15:36:45 +10001100
1101 /**
1102 * @param {!KeyboardEvent} ev
1103 * @return {boolean} Return false if xterm.js should not handle the key event.
1104 */
1105 customKeyEventHandler_(ev) {
1106 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
1107 (ev.altKey ? Modifier.Alt : 0) |
1108 (ev.ctrlKey ? Modifier.Ctrl : 0) |
1109 (ev.metaKey ? Modifier.Meta : 0);
1110 const handler = this.keyDownHandlers_.get(
1111 encodeKeyCombo(modifiers, ev.keyCode));
1112 if (handler) {
1113 if (ev.type === 'keydown') {
1114 handler(ev);
1115 }
1116 return false;
1117 }
1118
1119 return true;
1120 }
1121
1122 /**
1123 * A keydown handler for zoom-related keys.
1124 *
1125 * @param {!KeyboardEvent} ev
1126 */
1127 zoomKeyDownHandler_(ev) {
1128 ev.preventDefault();
1129
1130 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
1131 // The only one with a control code.
1132 if (ev.keyCode === keyCodes.MINUS) {
1133 this.io.onVTKeystroke('\x1f');
1134 }
1135 return;
1136 }
1137
1138 let newFontSize;
1139 switch (ev.keyCode) {
1140 case keyCodes.ZERO:
1141 newFontSize = this.prefs_.get('font-size');
1142 break;
1143 case keyCodes.MINUS:
1144 newFontSize = this.term.options.fontSize - 1;
1145 break;
1146 default:
1147 newFontSize = this.term.options.fontSize + 1;
1148 break;
1149 }
1150
Jason Linda56aa92022-09-02 13:01:49 +10001151 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +10001152 }
1153
1154 /** @param {!KeyboardEvent} ev */
1155 ctrlCKeyDownHandler_(ev) {
1156 ev.preventDefault();
1157 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
1158 this.term.hasSelection()) {
1159 this.copySelection_();
1160 return;
1161 }
1162
1163 this.io.onVTKeystroke('\x03');
1164 }
1165
1166 /** @param {!KeyboardEvent} ev */
1167 ctrlVKeyDownHandler_(ev) {
1168 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
1169 // Don't do anything and let the browser handles the key.
1170 return;
1171 }
1172
1173 ev.preventDefault();
1174 this.io.onVTKeystroke('\x16');
1175 }
1176
1177 resetKeyDownHandlers_() {
1178 this.keyDownHandlers_.clear();
1179
1180 /**
1181 * Don't do anything and let the browser handles the key.
1182 *
1183 * @param {!KeyboardEvent} ev
1184 */
1185 const noop = (ev) => {};
1186
1187 /**
1188 * @param {number} modifiers
1189 * @param {number} keyCode
1190 * @param {function(!KeyboardEvent)} func
1191 */
1192 const set = (modifiers, keyCode, func) => {
1193 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
1194 func);
1195 };
1196
1197 /**
1198 * @param {number} modifiers
1199 * @param {number} keyCode
1200 * @param {function(!KeyboardEvent)} func
1201 */
1202 const setWithShiftVersion = (modifiers, keyCode, func) => {
1203 set(modifiers, keyCode, func);
1204 set(modifiers | Modifier.Shift, keyCode, func);
1205 };
1206
Jason Lin5690e752022-08-30 15:36:45 +10001207 // Ctrl+/
1208 set(Modifier.Ctrl, 191, (ev) => {
1209 ev.preventDefault();
1210 this.io.onVTKeystroke(ctl('_'));
1211 });
1212
1213 // Settings page.
1214 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
1215 ev.preventDefault();
1216 chrome.terminalPrivate.openOptionsPage(() => {});
1217 });
1218
1219 if (this.prefs_.get('keybindings-os-defaults')) {
1220 for (const binding of OS_DEFAULT_BINDINGS) {
1221 this.keyDownHandlers_.set(binding, noop);
1222 }
1223 }
1224
1225 /** @param {!KeyboardEvent} ev */
1226 const newWindow = (ev) => {
1227 ev.preventDefault();
1228 chrome.terminalPrivate.openWindow();
1229 };
1230 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
1231 if (this.prefs_.get('pass-ctrl-n')) {
1232 set(Modifier.Ctrl, keyCodes.N, newWindow);
1233 }
1234
1235 if (this.prefs_.get('pass-ctrl-t')) {
1236 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
1237 }
1238
1239 if (this.prefs_.get('pass-ctrl-w')) {
1240 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
1241 }
1242
1243 if (this.prefs_.get('pass-ctrl-tab')) {
1244 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
1245 }
1246
1247 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
1248
1249 /**
1250 * Set a handler for the key combo ctrl+<number>.
1251 *
1252 * @param {number} number 1 to 9
1253 * @param {string} controlCode The control code to send if we don't want to
1254 * let the browser to handle it.
1255 */
1256 const setCtrlNumberHandler = (number, controlCode) => {
1257 let func = noop;
1258 if (!passCtrlNumber) {
1259 func = (ev) => {
1260 ev.preventDefault();
1261 this.io.onVTKeystroke(controlCode);
1262 };
1263 }
1264 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1265 };
1266
1267 setCtrlNumberHandler(1, '1');
1268 setCtrlNumberHandler(2, ctl('@'));
1269 setCtrlNumberHandler(3, ctl('['));
1270 setCtrlNumberHandler(4, ctl('\\'));
1271 setCtrlNumberHandler(5, ctl(']'));
1272 setCtrlNumberHandler(6, ctl('^'));
1273 setCtrlNumberHandler(7, ctl('_'));
1274 setCtrlNumberHandler(8, '\x7f');
1275 setCtrlNumberHandler(9, '9');
1276
1277 if (this.prefs_.get('pass-alt-number')) {
1278 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1279 set(Modifier.Alt, keyCode, noop);
1280 }
1281 }
1282
1283 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1284 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1285 }
1286
1287 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1288 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1289 }
Jason Linee0c1f72022-10-18 17:17:26 +11001290
1291 handleOnTerminalReady() {}
Jason Linca61ffb2022-08-03 19:37:12 +10001292}
1293
Jason Lind66e6bf2022-08-22 14:47:10 +10001294class HtermTerminal extends hterm.Terminal {
1295 /** @override */
1296 decorate(div) {
1297 super.decorate(div);
1298
Jason Linc48f7432022-10-13 17:28:30 +11001299 definePrefs(this.getPrefs());
Jason Linee0c1f72022-10-18 17:17:26 +11001300 }
Jason Linc48f7432022-10-13 17:28:30 +11001301
Jason Linee0c1f72022-10-18 17:17:26 +11001302 /**
1303 * This needs to be called in the `onTerminalReady()` callback. This is
1304 * awkward, but it is temporary since we will drop support for hterm at some
1305 * point.
1306 */
1307 handleOnTerminalReady() {
Jason Lind66e6bf2022-08-22 14:47:10 +10001308 const fontManager = new FontManager(this.getDocument());
1309 fontManager.loadPowerlineCSS().then(() => {
1310 const prefs = this.getPrefs();
1311 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1312 prefs.addObserver(
1313 'font-family',
1314 (v) => fontManager.loadFont(/** @type {string} */(v)));
1315 });
Jason Linee0c1f72022-10-18 17:17:26 +11001316
1317 const backgroundImageWatcher = new BackgroundImageWatcher(this.getPrefs(),
1318 (image) => this.setBackgroundImage(image));
1319 this.setBackgroundImage(backgroundImageWatcher.getBackgroundImage());
1320 backgroundImageWatcher.watch();
Jason Lind66e6bf2022-08-22 14:47:10 +10001321 }
Jason Lin2649da22022-10-12 10:16:44 +11001322
1323 /**
1324 * Write data to the terminal.
1325 *
1326 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1327 * UTF-8 data
1328 * @param {function()=} callback Optional callback that fires when the data
1329 * was processed by the parser.
1330 */
1331 write(data, callback) {
1332 if (typeof data === 'string') {
1333 this.io.print(data);
1334 } else {
1335 this.io.writeUTF8(data);
1336 }
1337 // Hterm processes the data synchronously, so we can call the callback
1338 // immediately.
1339 if (callback) {
1340 setTimeout(callback);
1341 }
1342 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001343}
1344
Jason Linca61ffb2022-08-03 19:37:12 +10001345/**
1346 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1347 * preference value.
1348 *
1349 * @param {{
1350 * storage: !lib.Storage,
1351 * profileId: string,
1352 * }} args
1353 * @return {!Promise<!hterm.Terminal>}
1354 */
1355export async function createEmulator({storage, profileId}) {
1356 let config = TERMINAL_EMULATORS.get('hterm');
1357
1358 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001359 // TODO: remove the url param logic. This is temporary to make manual
1360 // testing a bit easier, which is also why this is not in
1361 // './js/terminal_info.js'.
Jason Line10d6c42022-11-11 16:04:32 +11001362 const emulator = ORIGINAL_URL.searchParams.get('emulator');
Jason Linca61ffb2022-08-03 19:37:12 +10001363 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001364 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001365 TERMINAL_EMULATORS.values().next().value;
1366 console.log('Terminal emulator config: ', config);
1367 }
1368
1369 switch (config.lib) {
1370 case 'xterm.js':
1371 {
1372 const terminal = new XtermTerminal({
1373 storage,
1374 profileId,
1375 enableWebGL: config.webgl,
1376 });
Jason Linca61ffb2022-08-03 19:37:12 +10001377 return terminal;
1378 }
1379 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001380 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001381 default:
1382 throw new Error('incorrect emulator config');
1383 }
1384}
1385
Jason Lin6a402a72022-08-25 16:07:02 +10001386class TerminalCopyNotice extends LitElement {
1387 /** @override */
1388 static get styles() {
1389 return css`
1390 :host {
1391 display: block;
1392 text-align: center;
1393 }
1394
1395 svg {
1396 fill: currentColor;
1397 }
1398 `;
1399 }
1400
1401 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001402 connectedCallback() {
1403 super.connectedCallback();
1404 if (!this.childNodes.length) {
1405 // This is not visible since we use shadow dom. But this will allow the
1406 // hterm.NotificationCenter to announce the the copy text.
1407 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1408 }
1409 }
1410
1411 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001412 render() {
1413 return html`
1414 ${ICON_COPY}
1415 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1416 `;
1417 }
1418}
1419
1420customElements.define('terminal-copy-notice', TerminalCopyNotice);