blob: a72232ed73c4fd5dff67f4925fd33e47c6868357 [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 Lin6a402a72022-08-25 16:07:02 +100019import {ICON_COPY} from './terminal_icons.js';
Jason Lin83707c92022-09-20 19:09:41 +100020import {TerminalTooltip} from './terminal_tooltip.js';
Jason Linc2504ae2022-09-02 13:03:31 +100021import {Terminal, Unicode11Addon, WebLinksAddon, WebglAddon}
Jason Lin4de4f382022-09-01 14:10:18 +100022 from './xterm.js';
Jason Lin2649da22022-10-12 10:16:44 +110023import {XtermInternal} from './terminal_xterm_internal.js';
Jason Linca61ffb2022-08-03 19:37:12 +100024
Jason Lin5690e752022-08-30 15:36:45 +100025
26/** @enum {number} */
27export const Modifier = {
28 Shift: 1 << 0,
29 Alt: 1 << 1,
30 Ctrl: 1 << 2,
31 Meta: 1 << 3,
32};
33
34// This is just a static map from key names to key codes. It helps make the code
35// a bit more readable.
36const keyCodes = hterm.Parser.identifiers.keyCodes;
37
38/**
39 * Encode a key combo (i.e. modifiers + a normal key) to an unique number.
40 *
41 * @param {number} modifiers
42 * @param {number} keyCode
43 * @return {number}
44 */
45export function encodeKeyCombo(modifiers, keyCode) {
46 return keyCode << 4 | modifiers;
47}
48
49const OS_DEFAULT_BINDINGS = [
50 // Submit feedback.
51 encodeKeyCombo(Modifier.Alt | Modifier.Shift, keyCodes.I),
52 // Toggle chromevox.
53 encodeKeyCombo(Modifier.Ctrl | Modifier.Alt, keyCodes.Z),
54 // Switch input method.
55 encodeKeyCombo(Modifier.Ctrl, keyCodes.SPACE),
56
57 // Dock window left/right.
58 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_LEFT),
59 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_RIGHT),
60
61 // Maximize/minimize window.
62 encodeKeyCombo(Modifier.Alt, keyCodes.EQUAL),
63 encodeKeyCombo(Modifier.Alt, keyCodes.MINUS),
64];
65
66
Jason Linca61ffb2022-08-03 19:37:12 +100067const ANSI_COLOR_NAMES = [
68 'black',
69 'red',
70 'green',
71 'yellow',
72 'blue',
73 'magenta',
74 'cyan',
75 'white',
76 'brightBlack',
77 'brightRed',
78 'brightGreen',
79 'brightYellow',
80 'brightBlue',
81 'brightMagenta',
82 'brightCyan',
83 'brightWhite',
84];
85
Jason Linca61ffb2022-08-03 19:37:12 +100086/**
Jason Linabad7562022-08-22 14:49:05 +100087 * @typedef {{
88 * term: !Terminal,
89 * fontManager: !FontManager,
Jason Lin2649da22022-10-12 10:16:44 +110090 * xtermInternal: !XtermInternal,
Jason Linabad7562022-08-22 14:49:05 +100091 * }}
92 */
93export let XtermTerminalTestParams;
94
95/**
Jason Lin5690e752022-08-30 15:36:45 +100096 * Compute a control character for a given character.
97 *
98 * @param {string} ch
99 * @return {string}
100 */
101function ctl(ch) {
102 return String.fromCharCode(ch.charCodeAt(0) - 64);
103}
104
105/**
Jason Lin21d854f2022-08-22 14:49:59 +1000106 * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO
107 * because it always convert utf8 data to strings, which is not necessary for
108 * xterm.
109 */
110class XtermTerminalIO extends hterm.Terminal.IO {
111 /** @override */
112 writeUTF8(buffer) {
113 this.terminal_.write(new Uint8Array(buffer));
114 }
115
116 /** @override */
117 writelnUTF8(buffer) {
118 this.terminal_.writeln(new Uint8Array(buffer));
119 }
120
121 /** @override */
122 print(string) {
123 this.terminal_.write(string);
124 }
125
126 /** @override */
127 writeUTF16(string) {
128 this.print(string);
129 }
130
131 /** @override */
132 println(string) {
133 this.terminal_.writeln(string);
134 }
135
136 /** @override */
137 writelnUTF16(string) {
138 this.println(string);
139 }
140}
141
142/**
Jason Lin83707c92022-09-20 19:09:41 +1000143 * A custom link handler that:
144 *
145 * - Shows a tooltip with the url on a OSC 8 link. This is following what hterm
146 * is doing. Also, showing the tooltip is better for the security of the user
147 * because the link can have arbitrary text.
148 * - Uses our own way to open the window.
149 */
150class LinkHandler {
151 /**
152 * @param {!Terminal} term
153 */
154 constructor(term) {
155 this.term_ = term;
156 /** @type {?TerminalTooltip} */
157 this.tooltip_ = null;
158 }
159
160 /**
161 * @return {!TerminalTooltip}
162 */
163 getTooltip_() {
164 if (!this.tooltip_) {
165 this.tooltip_ = /** @type {!TerminalTooltip} */(
166 document.createElement('terminal-tooltip'));
167 this.tooltip_.classList.add('xterm-hover');
168 lib.notNull(this.term_.element).appendChild(this.tooltip_);
169 }
170 return this.tooltip_;
171 }
172
173 /**
174 * @param {!MouseEvent} ev
175 * @param {string} url
176 * @param {!Object} range
177 */
178 activate(ev, url, range) {
179 lib.f.openWindow(url, '_blank');
180 }
181
182 /**
183 * @param {!MouseEvent} ev
184 * @param {string} url
185 * @param {!Object} range
186 */
187 hover(ev, url, range) {
188 this.getTooltip_().show(url, {x: ev.clientX, y: ev.clientY});
189 }
190
191 /**
192 * @param {!MouseEvent} ev
193 * @param {string} url
194 * @param {!Object} range
195 */
196 leave(ev, url, range) {
197 this.getTooltip_().hide();
198 }
199}
200
Jason Linc7afb672022-10-11 15:54:17 +1100201class Bell {
202 constructor() {
203 this.showNotification = false;
204
205 /** @type {?Audio} */
206 this.audio_ = null;
207 /** @type {?Notification} */
208 this.notification_ = null;
209 this.coolDownUntil_ = 0;
210 }
211
212 /**
213 * Set whether a bell audio should be played.
214 *
215 * @param {boolean} value
216 */
217 set playAudio(value) {
218 this.audio_ = value ?
219 new Audio(lib.resource.getDataUrl('hterm/audio/bell')) : null;
220 }
221
222 ring() {
223 const now = Date.now();
224 if (now < this.coolDownUntil_) {
225 return;
226 }
227 this.coolDownUntil_ = now + 500;
228
229 this.audio_?.play();
230 if (this.showNotification && !document.hasFocus() && !this.notification_) {
231 this.notification_ = new Notification(
232 `\u266A ${document.title} \u266A`,
233 {icon: lib.resource.getDataUrl('hterm/images/icon-96')});
234 // Close the notification after a timeout. Note that this is different
235 // from hterm's behavior, but I think it makes more sense to do so.
236 setTimeout(() => {
237 this.notification_.close();
238 this.notification_ = null;
239 }, 5000);
240 }
241 }
242}
243
Jason Lind3aacef2022-10-12 19:03:37 +1100244const A11Y_BUTTON_STYLE = `
245position: fixed;
246z-index: 10;
247right: 16px;
248`;
249
Jason Lina8adea52022-10-25 13:14:14 +1100250// TODO: we should subscribe to the xterm.js onscroll event, and
251// disable/enable the buttons accordingly. However, xterm.js does not seem to
252// emit the onscroll event when the viewport is scrolled by the mouse. See
253// https://github.com/xtermjs/xterm.js/issues/3864
254export class A11yButtons {
Jason Lind3aacef2022-10-12 19:03:37 +1100255 /**
256 * @param {!Terminal} term
Jason Lina8adea52022-10-25 13:14:14 +1100257 * @param {!hterm.AccessibilityReader} htermA11yReader
Jason Lind3aacef2022-10-12 19:03:37 +1100258 */
Jason Linc0f14fe2022-10-25 15:31:29 +1100259 constructor(term, htermA11yReader) {
Jason Lina8adea52022-10-25 13:14:14 +1100260 this.term_ = term;
261 this.htermA11yReader_ = htermA11yReader;
Jason Linc0f14fe2022-10-25 15:31:29 +1100262 this.pageUpButton = document.createElement('button');
263 this.pageUpButton.style.cssText = A11Y_BUTTON_STYLE;
264 this.pageUpButton.textContent =
Jason Lind3aacef2022-10-12 19:03:37 +1100265 hterm.messageManager.get('HTERM_BUTTON_PAGE_UP');
Jason Linc0f14fe2022-10-25 15:31:29 +1100266 this.pageUpButton.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100267 () => this.scrollPages_(-1));
Jason Lind3aacef2022-10-12 19:03:37 +1100268
Jason Linc0f14fe2022-10-25 15:31:29 +1100269 this.pageDownButton = document.createElement('button');
270 this.pageDownButton.style.cssText = A11Y_BUTTON_STYLE;
271 this.pageDownButton.textContent =
Jason Lind3aacef2022-10-12 19:03:37 +1100272 hterm.messageManager.get('HTERM_BUTTON_PAGE_DOWN');
Jason Linc0f14fe2022-10-25 15:31:29 +1100273 this.pageDownButton.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100274 () => this.scrollPages_(1));
Jason Lind3aacef2022-10-12 19:03:37 +1100275
276 this.resetPos_();
Jason Lind3aacef2022-10-12 19:03:37 +1100277
278 this.onSelectionChange_ = this.onSelectionChange_.bind(this);
279 }
280
281 /**
Jason Lina8adea52022-10-25 13:14:14 +1100282 * @param {number} amount
283 */
284 scrollPages_(amount) {
285 this.term_.scrollPages(amount);
286 this.announceScreenContent_();
287 }
288
289 announceScreenContent_() {
290 const activeBuffer = this.term_.buffer.active;
291
292 let percentScrolled = 100;
293 if (activeBuffer.baseY !== 0) {
294 percentScrolled = Math.round(
295 100 * activeBuffer.viewportY / activeBuffer.baseY);
296 }
297
298 let currentScreenContent = hterm.messageManager.get(
299 'HTERM_ANNOUNCE_CURRENT_SCREEN_HEADER',
300 [percentScrolled],
301 '$1% scrolled,');
302
303 currentScreenContent += '\n';
304
305 const rowEnd = Math.min(activeBuffer.viewportY + this.term_.rows,
306 activeBuffer.length);
307 for (let i = activeBuffer.viewportY; i < rowEnd; ++i) {
308 currentScreenContent +=
309 activeBuffer.getLine(i).translateToString(true) + '\n';
310 }
311 currentScreenContent = currentScreenContent.trim();
312
313 this.htermA11yReader_.assertiveAnnounce(currentScreenContent);
314 }
315
316 /**
Jason Lind3aacef2022-10-12 19:03:37 +1100317 * @param {boolean} enabled
318 */
319 setEnabled(enabled) {
320 if (enabled) {
321 document.addEventListener('selectionchange', this.onSelectionChange_);
322 } else {
323 this.resetPos_();
324 document.removeEventListener('selectionchange', this.onSelectionChange_);
325 }
326 }
327
328 resetPos_() {
Jason Linc0f14fe2022-10-25 15:31:29 +1100329 this.pageUpButton.style.top = '-200px';
330 this.pageDownButton.style.bottom = '-200px';
Jason Lind3aacef2022-10-12 19:03:37 +1100331 }
332
333 onSelectionChange_() {
334 this.resetPos_();
335
336 const selectedElement = document.getSelection().anchorNode.parentElement;
Jason Linc0f14fe2022-10-25 15:31:29 +1100337 if (selectedElement === this.pageUpButton) {
338 this.pageUpButton.style.top = '16px';
339 } else if (selectedElement === this.pageDownButton) {
340 this.pageDownButton.style.bottom = '16px';
Jason Lind3aacef2022-10-12 19:03:37 +1100341 }
342 }
343}
344
Jason Linee0c1f72022-10-18 17:17:26 +1100345const BACKGROUND_IMAGE_KEY = 'background-image';
346
347class BackgroundImageWatcher {
348 /**
349 * @param {!hterm.PreferenceManager} prefs
350 * @param {function(string)} onChange This is called with the background image
351 * (could be empty) whenever it changes.
352 */
353 constructor(prefs, onChange) {
354 this.prefs_ = prefs;
355 this.onChange_ = onChange;
356 }
357
358 /**
359 * Call once to start watching for background image changes.
360 */
361 watch() {
362 window.addEventListener('storage', (e) => {
363 if (e.key === BACKGROUND_IMAGE_KEY) {
364 this.onChange_(this.getBackgroundImage());
365 }
366 });
367 this.prefs_.addObserver(BACKGROUND_IMAGE_KEY, () => {
368 this.onChange_(this.getBackgroundImage());
369 });
370 }
371
372 getBackgroundImage() {
373 const image = window.localStorage.getItem(BACKGROUND_IMAGE_KEY);
374 if (image) {
375 return `url(${image})`;
376 }
377
378 return this.prefs_.getString(BACKGROUND_IMAGE_KEY);
379 }
380}
381
Jason Linb8f380a2022-10-25 13:15:56 +1100382let xtermTerminalStringsLoaded = false;
383
Jason Lin83707c92022-09-20 19:09:41 +1000384/**
Jason Linca61ffb2022-08-03 19:37:12 +1000385 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
386 * so that it can be used in existing code.
387 *
Jason Linca61ffb2022-08-03 19:37:12 +1000388 * @extends {hterm.Terminal}
389 * @unrestricted
390 */
Jason Linabad7562022-08-22 14:49:05 +1000391export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000392 /**
393 * @param {{
394 * storage: !lib.Storage,
395 * profileId: string,
396 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000397 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000398 * }} args
399 */
Jason Linabad7562022-08-22 14:49:05 +1000400 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000401 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
402 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
403 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
404
Jason Lin8de3d282022-09-01 21:29:05 +1000405 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000406 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000407 /** @type {!hterm.PreferenceManager} */
408 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
Jason Linc48f7432022-10-13 17:28:30 +1100409 definePrefs(this.prefs_);
Jason Linca61ffb2022-08-03 19:37:12 +1000410 this.enableWebGL_ = enableWebGL;
411
Jason Lin5690e752022-08-30 15:36:45 +1000412 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linfc8a3722022-09-07 17:49:18 +1000413 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Lin2649da22022-10-12 10:16:44 +1100414 this.xtermInternal_ = testParams?.xtermInternal ||
415 new XtermInternal(this.term);
Jason Linabad7562022-08-22 14:49:05 +1000416 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000417
Jason Linc2504ae2022-09-02 13:03:31 +1000418 /** @type {?Element} */
419 this.container_;
Jason Linc7afb672022-10-11 15:54:17 +1100420 this.bell_ = new Bell();
Jason Linc2504ae2022-09-02 13:03:31 +1000421 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000422 testParams ? 0 : 250);
423
Jason Lin83707c92022-09-20 19:09:41 +1000424 this.term.loadAddon(
425 new WebLinksAddon((e, uri) => lib.f.openWindow(uri, '_blank')));
Jason Lin4de4f382022-09-01 14:10:18 +1000426 this.term.loadAddon(new Unicode11Addon());
427 this.term.unicode.activeVersion = '11';
428
Jason Linabad7562022-08-22 14:49:05 +1000429 this.pendingFont_ = null;
430 this.scheduleRefreshFont_ = delayedScheduler(
431 () => this.refreshFont_(), 100);
432 document.fonts.addEventListener('loadingdone',
433 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000434
435 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000436 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000437
Jason Lin34a45322022-10-12 19:10:52 +1100438 this.term.onResize(({cols, rows}) => {
439 this.io.onTerminalResize(cols, rows);
440 if (this.prefs_.get('enable-resize-status')) {
441 this.showOverlay(`${cols} × ${rows}`);
442 }
443 });
Jason Lin21d854f2022-08-22 14:49:59 +1000444 // We could also use `this.io.sendString()` except for the nassh exit
445 // prompt, which only listens to onVTKeystroke().
446 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000447 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100448 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin83ef5ba2022-10-13 17:40:30 +1100449 this.term.onSelectionChange(() => {
450 if (this.prefs_.get('copy-on-select')) {
451 this.copySelection_();
452 }
453 });
Jason Linc7afb672022-10-11 15:54:17 +1100454 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000455
456 /**
457 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
458 *
459 * If a key combo is in the map:
460 *
461 * - The handler instead of xterm.js will handle the keydown event.
462 * - Keyup and keypress will be ignored by both us and xterm.js.
463 *
464 * We re-generate this map every time a relevant pref value is changed. This
465 * is ok because pref changes are rare.
466 *
467 * @type {!Map<number, function(!KeyboardEvent)>}
468 */
469 this.keyDownHandlers_ = new Map();
470 this.scheduleResetKeyDownHandlers_ =
471 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
472
473 this.term.attachCustomKeyEventHandler(
474 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000475
Jason Lin21d854f2022-08-22 14:49:59 +1000476 this.io = new XtermTerminalIO(this);
477 this.notificationCenter_ = null;
Jason Lind3aacef2022-10-12 19:03:37 +1100478 this.htermA11yReader_ = null;
Jason Linc0f14fe2022-10-25 15:31:29 +1100479 this.a11yEnabled_ = false;
Jason Lind3aacef2022-10-12 19:03:37 +1100480 this.a11yButtons_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000481 this.copyNotice_ = null;
Jason Lin446f3d92022-10-13 17:34:21 +1100482 this.scrollOnOutputListener_ = null;
Jason Linee0c1f72022-10-18 17:17:26 +1100483 this.backgroundImageWatcher_ = new BackgroundImageWatcher(this.prefs_,
484 this.setBackgroundImage.bind(this));
485 this.webglAddon_ = null;
Jason Lina63d8ba2022-11-02 17:42:38 +1100486 this.userCSSElement_ = null;
487 this.userCSSTextElement_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000488
Jason Lin83707c92022-09-20 19:09:41 +1000489 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000490 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000491 // The webgl cursor layer also paints the character under the cursor with
492 // this `cursorAccent` color. We use a completely transparent color here
493 // to effectively disable that.
494 cursorAccent: 'rgba(0, 0, 0, 0)',
495 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000496 selectionBackground: 'rgba(174, 203, 250, .6)',
497 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000498 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000499 };
500 this.observePrefs_();
Jason Linb8f380a2022-10-25 13:15:56 +1100501 if (!xtermTerminalStringsLoaded) {
502 xtermTerminalStringsLoaded = true;
503 Terminal.strings.promptLabel =
504 hterm.messageManager.get('TERMINAL_INPUT_LABEL');
505 Terminal.strings.tooMuchOutput =
506 hterm.messageManager.get('TERMINAL_TOO_MUCH_OUTPUT_MESSAGE');
507 }
Jason Linca61ffb2022-08-03 19:37:12 +1000508 }
509
Jason Linc7afb672022-10-11 15:54:17 +1100510 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100511 setWindowTitle(title) {
512 document.title = title;
513 }
514
515 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100516 ringBell() {
517 this.bell_.ring();
518 }
519
Jason Lin2649da22022-10-12 10:16:44 +1100520 /** @override */
521 print(str) {
522 this.xtermInternal_.print(str);
523 }
524
525 /** @override */
526 wipeContents() {
527 this.term.clear();
528 }
529
530 /** @override */
531 newLine() {
532 this.xtermInternal_.newLine();
533 }
534
535 /** @override */
536 cursorLeft(number) {
537 this.xtermInternal_.cursorLeft(number ?? 1);
538 }
539
Jason Lind3aacef2022-10-12 19:03:37 +1100540 /** @override */
541 setAccessibilityEnabled(enabled) {
Jason Linc0f14fe2022-10-25 15:31:29 +1100542 if (enabled === this.a11yEnabled_) {
543 return;
544 }
545 this.a11yEnabled_ = enabled;
546
Jason Lind3aacef2022-10-12 19:03:37 +1100547 this.a11yButtons_.setEnabled(enabled);
548 this.htermA11yReader_.setAccessibilityEnabled(enabled);
Jason Linc0f14fe2022-10-25 15:31:29 +1100549
550 if (enabled) {
551 this.xtermInternal_.enableA11y(this.a11yButtons_.pageUpButton,
552 this.a11yButtons_.pageDownButton);
553 } else {
554 this.xtermInternal_.disableA11y();
555 }
Jason Lind3aacef2022-10-12 19:03:37 +1100556 }
557
Jason Linee0c1f72022-10-18 17:17:26 +1100558 hasBackgroundImage() {
559 return !!this.container_.style.backgroundImage;
560 }
561
562 /** @override */
563 setBackgroundImage(image) {
564 this.container_.style.backgroundImage = image || '';
565 this.updateBackgroundColor_(this.prefs_.getString('background-color'));
566 }
567
Jason Linca61ffb2022-08-03 19:37:12 +1000568 /**
569 * Install stubs for stuff that we haven't implemented yet so that the code
570 * still runs.
571 */
572 installUnimplementedStubs_() {
573 this.keyboard = {
574 keyMap: {
575 keyDefs: [],
576 },
577 bindings: {
578 clear: () => {},
579 addBinding: () => {},
580 addBindings: () => {},
581 OsDefaults: {},
582 },
583 };
584 this.keyboard.keyMap.keyDefs[78] = {};
585
586 const methodNames = [
Joel Hockeyb89a9782022-10-16 22:00:12 -0700587 'eraseLine',
Joel Hockeyb89a9782022-10-16 22:00:12 -0700588 'setCursorColumn',
Jason Linca61ffb2022-08-03 19:37:12 +1000589 'setCursorPosition',
590 'setCursorVisible',
Joel Hockeyd78374f2022-11-02 23:05:53 -0700591 'uninstallKeyboard',
Jason Linca61ffb2022-08-03 19:37:12 +1000592 ];
593
594 for (const name of methodNames) {
595 this[name] = () => console.warn(`${name}() is not implemented`);
596 }
597
598 this.contextMenu = {
599 setItems: () => {
600 console.warn('.contextMenu.setItems() is not implemented');
601 },
602 };
Jason Lin21d854f2022-08-22 14:49:59 +1000603
604 this.vt = {
605 resetParseState: () => {
606 console.warn('.vt.resetParseState() is not implemented');
607 },
608 };
Jason Linca61ffb2022-08-03 19:37:12 +1000609 }
610
Jason Line9231bc2022-09-01 13:54:02 +1000611 installEscapeSequenceHandlers_() {
612 // OSC 52 for copy.
613 this.term.parser.registerOscHandler(52, (args) => {
614 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
615 // parameter is used to select which of the X clipboards to address. Since
616 // we're not integrating with X, we treat them all the same.
617 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
618 if (!parsedArgs) {
619 return true;
620 }
621
622 let data;
623 try {
624 data = window.atob(parsedArgs[1]);
625 } catch (e) {
626 // If the user sent us invalid base64 content, silently ignore it.
627 return true;
628 }
629 const decoder = new TextDecoder();
630 const bytes = lib.codec.stringToCodeUnitArray(data);
631 this.copyString_(decoder.decode(bytes));
632
633 return true;
634 });
Jason Lin2649da22022-10-12 10:16:44 +1100635
636 this.xtermInternal_.installTmuxControlModeHandler(
637 (data) => this.onTmuxControlModeLine(data));
638 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000639 }
640
Jason Linca61ffb2022-08-03 19:37:12 +1000641 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000642 * Write data to the terminal.
643 *
644 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
645 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100646 * @param {function()=} callback Optional callback that fires when the data
647 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000648 */
Jason Lin2649da22022-10-12 10:16:44 +1100649 write(data, callback) {
650 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000651 }
652
653 /**
654 * Like `this.write()` but also write a line break.
655 *
656 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100657 * @param {function()=} callback Optional callback that fires when the data
658 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000659 */
Jason Lin2649da22022-10-12 10:16:44 +1100660 writeln(data, callback) {
661 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000662 }
663
Jason Linca61ffb2022-08-03 19:37:12 +1000664 get screenSize() {
665 return new hterm.Size(this.term.cols, this.term.rows);
666 }
667
668 /**
669 * Don't need to do anything.
670 *
671 * @override
672 */
673 installKeyboard() {}
674
675 /**
676 * @override
677 */
678 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000679 this.container_ = elem;
Jason Linee0c1f72022-10-18 17:17:26 +1100680 elem.style.backgroundSize = '100% 100%';
681
Jason Lin8de3d282022-09-01 21:29:05 +1000682 (async () => {
683 await new Promise((resolve) => this.prefs_.readStorage(resolve));
684 // This will trigger all the observers to set the terminal options before
685 // we call `this.term.open()`.
686 this.prefs_.notifyAll();
687
Jason Linc2504ae2022-09-02 13:03:31 +1000688 const screenPaddingSize = /** @type {number} */(
689 this.prefs_.get('screen-padding-size'));
690 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
691
Jason Linee0c1f72022-10-18 17:17:26 +1100692 this.setBackgroundImage(
693 this.backgroundImageWatcher_.getBackgroundImage());
694 this.backgroundImageWatcher_.watch();
695
Jason Lin8de3d282022-09-01 21:29:05 +1000696 this.inited_ = true;
697 this.term.open(elem);
698
Jason Lin8de3d282022-09-01 21:29:05 +1000699 if (this.enableWebGL_) {
Jason Linee0c1f72022-10-18 17:17:26 +1100700 this.reloadWebglAddon_();
Jason Lin8de3d282022-09-01 21:29:05 +1000701 }
702 this.term.focus();
703 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100704 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
705 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
706 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000707
Emil Mikulic2a194d02022-09-29 14:30:59 +1000708 // Block right-click context menu from popping up.
709 elem.addEventListener('contextmenu', (e) => e.preventDefault());
710
711 // Add a handler for pasting with the mouse.
712 elem.addEventListener('mousedown', async (e) => {
713 if (this.term.modes.mouseTrackingMode !== 'none') {
714 // xterm.js is in mouse mode and will handle the event.
715 return;
716 }
717 const MIDDLE = 1;
718 const RIGHT = 2;
719 if (e.button === MIDDLE || (e.button === RIGHT &&
720 this.prefs_.getBoolean('mouse-right-click-paste'))) {
721 // Paste.
722 if (navigator.clipboard && navigator.clipboard.readText) {
723 const text = await navigator.clipboard.readText();
724 this.term.paste(text);
725 }
726 }
727 });
728
Jason Lin2649da22022-10-12 10:16:44 +1100729 await this.scheduleFit_();
Jason Linc0f14fe2022-10-25 15:31:29 +1100730 this.a11yButtons_ = new A11yButtons(this.term, this.htermA11yReader_);
Jason Lind3aacef2022-10-12 19:03:37 +1100731
Jason Lin8de3d282022-09-01 21:29:05 +1000732 this.onTerminalReady();
733 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000734 }
735
736 /** @override */
737 showOverlay(msg, timeout = 1500) {
Jason Lin34a45322022-10-12 19:10:52 +1100738 this.notificationCenter_?.show(msg, {timeout});
Jason Lin21d854f2022-08-22 14:49:59 +1000739 }
740
741 /** @override */
742 hideOverlay() {
Jason Lin34a45322022-10-12 19:10:52 +1100743 this.notificationCenter_?.hide();
Jason Linca61ffb2022-08-03 19:37:12 +1000744 }
745
746 /** @override */
747 getPrefs() {
748 return this.prefs_;
749 }
750
751 /** @override */
752 getDocument() {
753 return window.document;
754 }
755
Jason Lin21d854f2022-08-22 14:49:59 +1000756 /** @override */
757 reset() {
758 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000759 }
760
761 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000762 setProfile(profileId, callback = undefined) {
763 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000764 }
765
Jason Lin21d854f2022-08-22 14:49:59 +1000766 /** @override */
767 interpret(string) {
768 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000769 }
770
Jason Lin21d854f2022-08-22 14:49:59 +1000771 /** @override */
772 focus() {
773 this.term.focus();
774 }
Jason Linca61ffb2022-08-03 19:37:12 +1000775
776 /** @override */
777 onOpenOptionsPage() {}
778
779 /** @override */
780 onTerminalReady() {}
781
Jason Lind04bab32022-08-22 14:48:39 +1000782 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000783 // This is for this.notificationCenter_.
784 const setHtermCSSVariable = (name, value) => {
785 document.body.style.setProperty(`--hterm-${name}`, value);
786 };
787
788 const setHtermColorCSSVariable = (name, color) => {
789 const css = lib.notNull(lib.colors.normalizeCSS(color));
790 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
791 setHtermCSSVariable(name, rgb);
792 };
793
794 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000795 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000796 setHtermCSSVariable('font-size', `${v}px`);
797 });
798
Jason Linda56aa92022-09-02 13:01:49 +1000799 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000800 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000801 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100802 this.bell_.playAudio = !!v;
803 },
804 'desktop-notification-bell': (v) => {
805 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000806 },
Jason Lind04bab32022-08-22 14:48:39 +1000807 'background-color': (v) => {
Jason Linee0c1f72022-10-18 17:17:26 +1100808 this.updateBackgroundColor_(v);
Jason Lin21d854f2022-08-22 14:49:59 +1000809 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000810 },
Jason Lind04bab32022-08-22 14:48:39 +1000811 'color-palette-overrides': (v) => {
812 if (!(v instanceof Array)) {
813 // For terminal, we always expect this to be an array.
814 console.warn('unexpected color palette: ', v);
815 return;
816 }
817 const colors = {};
818 for (let i = 0; i < v.length; ++i) {
819 colors[ANSI_COLOR_NAMES[i]] = v[i];
820 }
821 this.updateTheme_(colors);
822 },
Jason Linda56aa92022-09-02 13:01:49 +1000823 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
824 'cursor-color': (v) => this.updateTheme_({cursor: v}),
825 'cursor-shape': (v) => {
826 let shape;
827 if (v === 'BEAM') {
828 shape = 'bar';
829 } else {
830 shape = v.toLowerCase();
831 }
832 this.updateOption_('cursorStyle', shape, false);
833 },
834 'font-family': (v) => this.updateFont_(v),
835 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000836 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000837 setHtermColorCSSVariable('foreground-color', v);
838 },
Jason Linc48f7432022-10-13 17:28:30 +1100839 'line-height': (v) => this.updateOption_('lineHeight', v, true),
Jason Lin446f3d92022-10-13 17:34:21 +1100840 'scroll-on-output': (v) => {
841 if (!v) {
842 this.scrollOnOutputListener_?.dispose();
843 this.scrollOnOutputListener_ = null;
844 return;
845 }
846 if (!this.scrollOnOutputListener_) {
847 this.scrollOnOutputListener_ = this.term.onWriteParsed(
848 () => this.term.scrollToBottom());
849 }
850 },
Jason Lina63d8ba2022-11-02 17:42:38 +1100851 'user-css': (v) => {
852 if (this.userCSSElement_) {
853 this.userCSSElement_.remove();
854 }
855 if (v) {
856 this.userCSSElement_ = document.createElement('link');
857 this.userCSSElement_.setAttribute('rel', 'stylesheet');
858 this.userCSSElement_.setAttribute('href', v);
859 document.head.appendChild(this.userCSSElement_);
860 }
861 },
862 'user-css-text': (v) => {
863 if (!this.userCSSTextElement_) {
864 this.userCSSTextElement_ = document.createElement('style');
865 document.head.appendChild(this.userCSSTextElement_);
866 }
867 this.userCSSTextElement_.textContent = v;
868 },
Jason Lind04bab32022-08-22 14:48:39 +1000869 });
Jason Lin5690e752022-08-30 15:36:45 +1000870
871 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
872 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
873 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
874 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
875 }
Jason Lind04bab32022-08-22 14:48:39 +1000876 }
877
878 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000879 * Fit the terminal to the containing HTML element.
880 */
881 fit_() {
882 if (!this.inited_) {
883 return;
884 }
885
886 const screenPaddingSize = /** @type {number} */(
887 this.prefs_.get('screen-padding-size'));
888
889 const calc = (size, cellSize) => {
890 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
891 };
892
Jason Lin2649da22022-10-12 10:16:44 +1100893 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
894 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
895 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000896 if (cols >= 0 && rows >= 0) {
897 this.term.resize(cols, rows);
898 }
899 }
900
Jason Linee0c1f72022-10-18 17:17:26 +1100901 reloadWebglAddon_() {
902 if (this.webglAddon_) {
903 this.webglAddon_.dispose();
904 }
905 this.webglAddon_ = new WebglAddon();
906 this.term.loadAddon(this.webglAddon_);
907 }
908
909 /**
910 * Update the background color. This will also adjust the transparency based
911 * on whether there is a background image.
912 *
913 * @param {string} color
914 */
915 updateBackgroundColor_(color) {
916 const hasBackgroundImage = this.hasBackgroundImage();
917
918 // We only set allowTransparency when it is necessary becuase 1) xterm.js
919 // documentation states that allowTransparency can affect performance; 2) I
920 // find that the rendering is better with allowTransparency being false.
921 // This could be a bug with xterm.js.
922 if (!!this.term.options.allowTransparency !== hasBackgroundImage) {
923 this.term.options.allowTransparency = hasBackgroundImage;
924 if (this.enableWebGL_ && this.inited_) {
925 // Setting allowTransparency in the middle messes up webgl rendering,
926 // so we need to reload it here.
927 this.reloadWebglAddon_();
928 }
929 }
930
931 if (this.hasBackgroundImage()) {
932 const css = lib.notNull(lib.colors.normalizeCSS(color));
933 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
934 // Note that we still want to set the RGB part correctly even though it is
935 // completely transparent. This is because the background color without
936 // the alpha channel is used in reverse video mode.
937 color = `rgba(${rgb}, 0)`;
938 }
939
940 this.updateTheme_({background: color});
941 }
942
Jason Linc2504ae2022-09-02 13:03:31 +1000943 /**
Jason Lind04bab32022-08-22 14:48:39 +1000944 * @param {!Object} theme
945 */
946 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000947 const updateTheme = (target) => {
948 for (const [key, value] of Object.entries(theme)) {
949 target[key] = lib.colors.normalizeCSS(value);
950 }
951 };
952
953 // Must use a new theme object to trigger re-render if we have initialized.
954 if (this.inited_) {
955 const newTheme = {...this.term.options.theme};
956 updateTheme(newTheme);
957 this.term.options.theme = newTheme;
958 return;
Jason Lind04bab32022-08-22 14:48:39 +1000959 }
Jason Lin8de3d282022-09-01 21:29:05 +1000960
961 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000962 }
963
964 /**
Jason Linda56aa92022-09-02 13:01:49 +1000965 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
966 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000967 *
968 * @param {string} key
969 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000970 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000971 */
Jason Linda56aa92022-09-02 13:01:49 +1000972 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000973 // TODO: xterm supports updating multiple options at the same time. We
974 // should probably do that.
975 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000976 if (scheduleFit) {
977 this.scheduleFit_();
978 }
Jason Lind04bab32022-08-22 14:48:39 +1000979 }
Jason Linabad7562022-08-22 14:49:05 +1000980
981 /**
982 * Called when there is a "fontloadingdone" event. We need this because
983 * `FontManager.loadFont()` does not guarantee loading all the font files.
984 */
985 async onFontLoadingDone_() {
986 // If there is a pending font, the font is going to be refresh soon, so we
987 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000988 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000989 this.scheduleRefreshFont_();
990 }
991 }
992
Jason Lin5690e752022-08-30 15:36:45 +1000993 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000994 this.copyString_(this.term.getSelection());
995 }
996
997 /** @param {string} data */
998 copyString_(data) {
999 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +10001000 return;
1001 }
Jason Line9231bc2022-09-01 13:54:02 +10001002 navigator.clipboard?.writeText(data);
Jason Lin83ef5ba2022-10-13 17:40:30 +11001003
1004 if (this.prefs_.get('enable-clipboard-notice')) {
1005 if (!this.copyNotice_) {
1006 this.copyNotice_ = document.createElement('terminal-copy-notice');
1007 }
1008 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500),
1009 200);
Jason Lin6a402a72022-08-25 16:07:02 +10001010 }
Jason Lin6a402a72022-08-25 16:07:02 +10001011 }
1012
Jason Linabad7562022-08-22 14:49:05 +10001013 /**
1014 * Refresh xterm rendering for a font related event.
1015 */
1016 refreshFont_() {
1017 // We have to set the fontFamily option to a different string to trigger the
1018 // re-rendering. Appending a space at the end seems to be the easiest
1019 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
1020 // us.
1021 //
1022 // TODO: Report a bug to xterm.js and ask for exposing a public function for
1023 // the refresh so that we don't need to do this hack.
1024 this.term.options.fontFamily += ' ';
1025 }
1026
1027 /**
1028 * Update a font.
1029 *
1030 * @param {string} cssFontFamily
1031 */
1032 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +10001033 this.pendingFont_ = cssFontFamily;
1034 await this.fontManager_.loadFont(cssFontFamily);
1035 // Sleep a bit to wait for flushing fontloadingdone events. This is not
1036 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
1037 // to refresh font unnecessarily in some cases.
1038 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +10001039
Jason Lin6a402a72022-08-25 16:07:02 +10001040 if (this.pendingFont_ !== cssFontFamily) {
1041 // `updateFont_()` probably is called again. Abort what we are doing.
1042 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
1043 ` (expecting ${cssFontFamily})`);
1044 return;
1045 }
Jason Linabad7562022-08-22 14:49:05 +10001046
Jason Lin6a402a72022-08-25 16:07:02 +10001047 if (this.term.options.fontFamily !== cssFontFamily) {
1048 this.term.options.fontFamily = cssFontFamily;
1049 } else {
1050 // If the font is already the same, refresh font just to be safe.
1051 this.refreshFont_();
1052 }
1053 this.pendingFont_ = null;
1054 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +10001055 }
Jason Lin5690e752022-08-30 15:36:45 +10001056
1057 /**
1058 * @param {!KeyboardEvent} ev
1059 * @return {boolean} Return false if xterm.js should not handle the key event.
1060 */
1061 customKeyEventHandler_(ev) {
1062 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
1063 (ev.altKey ? Modifier.Alt : 0) |
1064 (ev.ctrlKey ? Modifier.Ctrl : 0) |
1065 (ev.metaKey ? Modifier.Meta : 0);
1066 const handler = this.keyDownHandlers_.get(
1067 encodeKeyCombo(modifiers, ev.keyCode));
1068 if (handler) {
1069 if (ev.type === 'keydown') {
1070 handler(ev);
1071 }
1072 return false;
1073 }
1074
1075 return true;
1076 }
1077
1078 /**
1079 * A keydown handler for zoom-related keys.
1080 *
1081 * @param {!KeyboardEvent} ev
1082 */
1083 zoomKeyDownHandler_(ev) {
1084 ev.preventDefault();
1085
1086 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
1087 // The only one with a control code.
1088 if (ev.keyCode === keyCodes.MINUS) {
1089 this.io.onVTKeystroke('\x1f');
1090 }
1091 return;
1092 }
1093
1094 let newFontSize;
1095 switch (ev.keyCode) {
1096 case keyCodes.ZERO:
1097 newFontSize = this.prefs_.get('font-size');
1098 break;
1099 case keyCodes.MINUS:
1100 newFontSize = this.term.options.fontSize - 1;
1101 break;
1102 default:
1103 newFontSize = this.term.options.fontSize + 1;
1104 break;
1105 }
1106
Jason Linda56aa92022-09-02 13:01:49 +10001107 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +10001108 }
1109
1110 /** @param {!KeyboardEvent} ev */
1111 ctrlCKeyDownHandler_(ev) {
1112 ev.preventDefault();
1113 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
1114 this.term.hasSelection()) {
1115 this.copySelection_();
1116 return;
1117 }
1118
1119 this.io.onVTKeystroke('\x03');
1120 }
1121
1122 /** @param {!KeyboardEvent} ev */
1123 ctrlVKeyDownHandler_(ev) {
1124 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
1125 // Don't do anything and let the browser handles the key.
1126 return;
1127 }
1128
1129 ev.preventDefault();
1130 this.io.onVTKeystroke('\x16');
1131 }
1132
1133 resetKeyDownHandlers_() {
1134 this.keyDownHandlers_.clear();
1135
1136 /**
1137 * Don't do anything and let the browser handles the key.
1138 *
1139 * @param {!KeyboardEvent} ev
1140 */
1141 const noop = (ev) => {};
1142
1143 /**
1144 * @param {number} modifiers
1145 * @param {number} keyCode
1146 * @param {function(!KeyboardEvent)} func
1147 */
1148 const set = (modifiers, keyCode, func) => {
1149 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
1150 func);
1151 };
1152
1153 /**
1154 * @param {number} modifiers
1155 * @param {number} keyCode
1156 * @param {function(!KeyboardEvent)} func
1157 */
1158 const setWithShiftVersion = (modifiers, keyCode, func) => {
1159 set(modifiers, keyCode, func);
1160 set(modifiers | Modifier.Shift, keyCode, func);
1161 };
1162
Jason Lin5690e752022-08-30 15:36:45 +10001163 // Ctrl+/
1164 set(Modifier.Ctrl, 191, (ev) => {
1165 ev.preventDefault();
1166 this.io.onVTKeystroke(ctl('_'));
1167 });
1168
1169 // Settings page.
1170 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
1171 ev.preventDefault();
1172 chrome.terminalPrivate.openOptionsPage(() => {});
1173 });
1174
1175 if (this.prefs_.get('keybindings-os-defaults')) {
1176 for (const binding of OS_DEFAULT_BINDINGS) {
1177 this.keyDownHandlers_.set(binding, noop);
1178 }
1179 }
1180
1181 /** @param {!KeyboardEvent} ev */
1182 const newWindow = (ev) => {
1183 ev.preventDefault();
1184 chrome.terminalPrivate.openWindow();
1185 };
1186 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
1187 if (this.prefs_.get('pass-ctrl-n')) {
1188 set(Modifier.Ctrl, keyCodes.N, newWindow);
1189 }
1190
1191 if (this.prefs_.get('pass-ctrl-t')) {
1192 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
1193 }
1194
1195 if (this.prefs_.get('pass-ctrl-w')) {
1196 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
1197 }
1198
1199 if (this.prefs_.get('pass-ctrl-tab')) {
1200 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
1201 }
1202
1203 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
1204
1205 /**
1206 * Set a handler for the key combo ctrl+<number>.
1207 *
1208 * @param {number} number 1 to 9
1209 * @param {string} controlCode The control code to send if we don't want to
1210 * let the browser to handle it.
1211 */
1212 const setCtrlNumberHandler = (number, controlCode) => {
1213 let func = noop;
1214 if (!passCtrlNumber) {
1215 func = (ev) => {
1216 ev.preventDefault();
1217 this.io.onVTKeystroke(controlCode);
1218 };
1219 }
1220 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1221 };
1222
1223 setCtrlNumberHandler(1, '1');
1224 setCtrlNumberHandler(2, ctl('@'));
1225 setCtrlNumberHandler(3, ctl('['));
1226 setCtrlNumberHandler(4, ctl('\\'));
1227 setCtrlNumberHandler(5, ctl(']'));
1228 setCtrlNumberHandler(6, ctl('^'));
1229 setCtrlNumberHandler(7, ctl('_'));
1230 setCtrlNumberHandler(8, '\x7f');
1231 setCtrlNumberHandler(9, '9');
1232
1233 if (this.prefs_.get('pass-alt-number')) {
1234 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1235 set(Modifier.Alt, keyCode, noop);
1236 }
1237 }
1238
1239 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1240 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1241 }
1242
1243 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1244 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1245 }
Jason Linee0c1f72022-10-18 17:17:26 +11001246
1247 handleOnTerminalReady() {}
Jason Linca61ffb2022-08-03 19:37:12 +10001248}
1249
Jason Lind66e6bf2022-08-22 14:47:10 +10001250class HtermTerminal extends hterm.Terminal {
1251 /** @override */
1252 decorate(div) {
1253 super.decorate(div);
1254
Jason Linc48f7432022-10-13 17:28:30 +11001255 definePrefs(this.getPrefs());
Jason Linee0c1f72022-10-18 17:17:26 +11001256 }
Jason Linc48f7432022-10-13 17:28:30 +11001257
Jason Linee0c1f72022-10-18 17:17:26 +11001258 /**
1259 * This needs to be called in the `onTerminalReady()` callback. This is
1260 * awkward, but it is temporary since we will drop support for hterm at some
1261 * point.
1262 */
1263 handleOnTerminalReady() {
Jason Lind66e6bf2022-08-22 14:47:10 +10001264 const fontManager = new FontManager(this.getDocument());
1265 fontManager.loadPowerlineCSS().then(() => {
1266 const prefs = this.getPrefs();
1267 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1268 prefs.addObserver(
1269 'font-family',
1270 (v) => fontManager.loadFont(/** @type {string} */(v)));
1271 });
Jason Linee0c1f72022-10-18 17:17:26 +11001272
1273 const backgroundImageWatcher = new BackgroundImageWatcher(this.getPrefs(),
1274 (image) => this.setBackgroundImage(image));
1275 this.setBackgroundImage(backgroundImageWatcher.getBackgroundImage());
1276 backgroundImageWatcher.watch();
Jason Lind66e6bf2022-08-22 14:47:10 +10001277 }
Jason Lin2649da22022-10-12 10:16:44 +11001278
1279 /**
1280 * Write data to the terminal.
1281 *
1282 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1283 * UTF-8 data
1284 * @param {function()=} callback Optional callback that fires when the data
1285 * was processed by the parser.
1286 */
1287 write(data, callback) {
1288 if (typeof data === 'string') {
1289 this.io.print(data);
1290 } else {
1291 this.io.writeUTF8(data);
1292 }
1293 // Hterm processes the data synchronously, so we can call the callback
1294 // immediately.
1295 if (callback) {
1296 setTimeout(callback);
1297 }
1298 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001299}
1300
Jason Linca61ffb2022-08-03 19:37:12 +10001301/**
1302 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1303 * preference value.
1304 *
1305 * @param {{
1306 * storage: !lib.Storage,
1307 * profileId: string,
1308 * }} args
1309 * @return {!Promise<!hterm.Terminal>}
1310 */
1311export async function createEmulator({storage, profileId}) {
1312 let config = TERMINAL_EMULATORS.get('hterm');
1313
1314 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001315 // TODO: remove the url param logic. This is temporary to make manual
1316 // testing a bit easier, which is also why this is not in
1317 // './js/terminal_info.js'.
1318 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
1319 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +10001320 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001321 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001322 TERMINAL_EMULATORS.values().next().value;
1323 console.log('Terminal emulator config: ', config);
1324 }
1325
1326 switch (config.lib) {
1327 case 'xterm.js':
1328 {
1329 const terminal = new XtermTerminal({
1330 storage,
1331 profileId,
1332 enableWebGL: config.webgl,
1333 });
Jason Linca61ffb2022-08-03 19:37:12 +10001334 return terminal;
1335 }
1336 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001337 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001338 default:
1339 throw new Error('incorrect emulator config');
1340 }
1341}
1342
Jason Lin6a402a72022-08-25 16:07:02 +10001343class TerminalCopyNotice extends LitElement {
1344 /** @override */
1345 static get styles() {
1346 return css`
1347 :host {
1348 display: block;
1349 text-align: center;
1350 }
1351
1352 svg {
1353 fill: currentColor;
1354 }
1355 `;
1356 }
1357
1358 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001359 connectedCallback() {
1360 super.connectedCallback();
1361 if (!this.childNodes.length) {
1362 // This is not visible since we use shadow dom. But this will allow the
1363 // hterm.NotificationCenter to announce the the copy text.
1364 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1365 }
1366 }
1367
1368 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001369 render() {
1370 return html`
1371 ${ICON_COPY}
1372 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1373 `;
1374 }
1375}
1376
1377customElements.define('terminal-copy-notice', TerminalCopyNotice);