blob: a84ff8c19b951b0ac71910a592a39e4565c75b1e [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
257 * @param {!Element} elem The container element for the terminal.
Jason Lina8adea52022-10-25 13:14:14 +1100258 * @param {!hterm.AccessibilityReader} htermA11yReader
Jason Lind3aacef2022-10-12 19:03:37 +1100259 */
Jason Lina8adea52022-10-25 13:14:14 +1100260 constructor(term, elem, htermA11yReader) {
261 this.term_ = term;
262 this.htermA11yReader_ = htermA11yReader;
Jason Lind3aacef2022-10-12 19:03:37 +1100263 this.pageUpButton_ = document.createElement('button');
264 this.pageUpButton_.style.cssText = A11Y_BUTTON_STYLE;
265 this.pageUpButton_.textContent =
266 hterm.messageManager.get('HTERM_BUTTON_PAGE_UP');
267 this.pageUpButton_.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100268 () => this.scrollPages_(-1));
Jason Lind3aacef2022-10-12 19:03:37 +1100269
270 this.pageDownButton_ = document.createElement('button');
271 this.pageDownButton_.style.cssText = A11Y_BUTTON_STYLE;
272 this.pageDownButton_.textContent =
273 hterm.messageManager.get('HTERM_BUTTON_PAGE_DOWN');
274 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_();
278 elem.prepend(this.pageUpButton_);
279 elem.append(this.pageDownButton_);
280
281 this.onSelectionChange_ = this.onSelectionChange_.bind(this);
282 }
283
284 /**
Jason Lina8adea52022-10-25 13:14:14 +1100285 * @param {number} amount
286 */
287 scrollPages_(amount) {
288 this.term_.scrollPages(amount);
289 this.announceScreenContent_();
290 }
291
292 announceScreenContent_() {
293 const activeBuffer = this.term_.buffer.active;
294
295 let percentScrolled = 100;
296 if (activeBuffer.baseY !== 0) {
297 percentScrolled = Math.round(
298 100 * activeBuffer.viewportY / activeBuffer.baseY);
299 }
300
301 let currentScreenContent = hterm.messageManager.get(
302 'HTERM_ANNOUNCE_CURRENT_SCREEN_HEADER',
303 [percentScrolled],
304 '$1% scrolled,');
305
306 currentScreenContent += '\n';
307
308 const rowEnd = Math.min(activeBuffer.viewportY + this.term_.rows,
309 activeBuffer.length);
310 for (let i = activeBuffer.viewportY; i < rowEnd; ++i) {
311 currentScreenContent +=
312 activeBuffer.getLine(i).translateToString(true) + '\n';
313 }
314 currentScreenContent = currentScreenContent.trim();
315
316 this.htermA11yReader_.assertiveAnnounce(currentScreenContent);
317 }
318
319 /**
Jason Lind3aacef2022-10-12 19:03:37 +1100320 * @param {boolean} enabled
321 */
322 setEnabled(enabled) {
323 if (enabled) {
324 document.addEventListener('selectionchange', this.onSelectionChange_);
325 } else {
326 this.resetPos_();
327 document.removeEventListener('selectionchange', this.onSelectionChange_);
328 }
329 }
330
331 resetPos_() {
332 this.pageUpButton_.style.top = '-200px';
333 this.pageDownButton_.style.bottom = '-200px';
334 }
335
336 onSelectionChange_() {
337 this.resetPos_();
338
339 const selectedElement = document.getSelection().anchorNode.parentElement;
340 if (selectedElement === this.pageUpButton_) {
341 this.pageUpButton_.style.top = '16px';
342 } else if (selectedElement === this.pageDownButton_) {
343 this.pageDownButton_.style.bottom = '16px';
344 }
345 }
346}
347
Jason Linee0c1f72022-10-18 17:17:26 +1100348const BACKGROUND_IMAGE_KEY = 'background-image';
349
350class BackgroundImageWatcher {
351 /**
352 * @param {!hterm.PreferenceManager} prefs
353 * @param {function(string)} onChange This is called with the background image
354 * (could be empty) whenever it changes.
355 */
356 constructor(prefs, onChange) {
357 this.prefs_ = prefs;
358 this.onChange_ = onChange;
359 }
360
361 /**
362 * Call once to start watching for background image changes.
363 */
364 watch() {
365 window.addEventListener('storage', (e) => {
366 if (e.key === BACKGROUND_IMAGE_KEY) {
367 this.onChange_(this.getBackgroundImage());
368 }
369 });
370 this.prefs_.addObserver(BACKGROUND_IMAGE_KEY, () => {
371 this.onChange_(this.getBackgroundImage());
372 });
373 }
374
375 getBackgroundImage() {
376 const image = window.localStorage.getItem(BACKGROUND_IMAGE_KEY);
377 if (image) {
378 return `url(${image})`;
379 }
380
381 return this.prefs_.getString(BACKGROUND_IMAGE_KEY);
382 }
383}
384
Jason Linb8f380a2022-10-25 13:15:56 +1100385let xtermTerminalStringsLoaded = false;
386
Jason Lin83707c92022-09-20 19:09:41 +1000387/**
Jason Linca61ffb2022-08-03 19:37:12 +1000388 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
389 * so that it can be used in existing code.
390 *
Jason Linca61ffb2022-08-03 19:37:12 +1000391 * @extends {hterm.Terminal}
392 * @unrestricted
393 */
Jason Linabad7562022-08-22 14:49:05 +1000394export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000395 /**
396 * @param {{
397 * storage: !lib.Storage,
398 * profileId: string,
399 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000400 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000401 * }} args
402 */
Jason Linabad7562022-08-22 14:49:05 +1000403 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000404 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
405 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
406 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
407
Jason Lin8de3d282022-09-01 21:29:05 +1000408 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000409 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000410 /** @type {!hterm.PreferenceManager} */
411 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
Jason Linc48f7432022-10-13 17:28:30 +1100412 definePrefs(this.prefs_);
Jason Linca61ffb2022-08-03 19:37:12 +1000413 this.enableWebGL_ = enableWebGL;
414
Jason Lin5690e752022-08-30 15:36:45 +1000415 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linfc8a3722022-09-07 17:49:18 +1000416 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Lin2649da22022-10-12 10:16:44 +1100417 this.xtermInternal_ = testParams?.xtermInternal ||
418 new XtermInternal(this.term);
Jason Linabad7562022-08-22 14:49:05 +1000419 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000420
Jason Linc2504ae2022-09-02 13:03:31 +1000421 /** @type {?Element} */
422 this.container_;
Jason Linc7afb672022-10-11 15:54:17 +1100423 this.bell_ = new Bell();
Jason Linc2504ae2022-09-02 13:03:31 +1000424 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000425 testParams ? 0 : 250);
426
Jason Lin83707c92022-09-20 19:09:41 +1000427 this.term.loadAddon(
428 new WebLinksAddon((e, uri) => lib.f.openWindow(uri, '_blank')));
Jason Lin4de4f382022-09-01 14:10:18 +1000429 this.term.loadAddon(new Unicode11Addon());
430 this.term.unicode.activeVersion = '11';
431
Jason Linabad7562022-08-22 14:49:05 +1000432 this.pendingFont_ = null;
433 this.scheduleRefreshFont_ = delayedScheduler(
434 () => this.refreshFont_(), 100);
435 document.fonts.addEventListener('loadingdone',
436 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000437
438 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000439 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000440
Jason Lin34a45322022-10-12 19:10:52 +1100441 this.term.onResize(({cols, rows}) => {
442 this.io.onTerminalResize(cols, rows);
443 if (this.prefs_.get('enable-resize-status')) {
444 this.showOverlay(`${cols} × ${rows}`);
445 }
446 });
Jason Lin21d854f2022-08-22 14:49:59 +1000447 // We could also use `this.io.sendString()` except for the nassh exit
448 // prompt, which only listens to onVTKeystroke().
449 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000450 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100451 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin83ef5ba2022-10-13 17:40:30 +1100452 this.term.onSelectionChange(() => {
453 if (this.prefs_.get('copy-on-select')) {
454 this.copySelection_();
455 }
456 });
Jason Linc7afb672022-10-11 15:54:17 +1100457 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000458
459 /**
460 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
461 *
462 * If a key combo is in the map:
463 *
464 * - The handler instead of xterm.js will handle the keydown event.
465 * - Keyup and keypress will be ignored by both us and xterm.js.
466 *
467 * We re-generate this map every time a relevant pref value is changed. This
468 * is ok because pref changes are rare.
469 *
470 * @type {!Map<number, function(!KeyboardEvent)>}
471 */
472 this.keyDownHandlers_ = new Map();
473 this.scheduleResetKeyDownHandlers_ =
474 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
475
476 this.term.attachCustomKeyEventHandler(
477 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000478
Jason Lin21d854f2022-08-22 14:49:59 +1000479 this.io = new XtermTerminalIO(this);
480 this.notificationCenter_ = null;
Jason Lind3aacef2022-10-12 19:03:37 +1100481 this.htermA11yReader_ = null;
482 this.a11yButtons_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000483 this.copyNotice_ = null;
Jason Lin446f3d92022-10-13 17:34:21 +1100484 this.scrollOnOutputListener_ = null;
Jason Linee0c1f72022-10-18 17:17:26 +1100485 this.backgroundImageWatcher_ = new BackgroundImageWatcher(this.prefs_,
486 this.setBackgroundImage.bind(this));
487 this.webglAddon_ = 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) {
542 this.a11yButtons_.setEnabled(enabled);
543 this.htermA11yReader_.setAccessibilityEnabled(enabled);
544 this.term.options.screenReaderMode = enabled;
545 }
546
Jason Linee0c1f72022-10-18 17:17:26 +1100547 hasBackgroundImage() {
548 return !!this.container_.style.backgroundImage;
549 }
550
551 /** @override */
552 setBackgroundImage(image) {
553 this.container_.style.backgroundImage = image || '';
554 this.updateBackgroundColor_(this.prefs_.getString('background-color'));
555 }
556
Jason Linca61ffb2022-08-03 19:37:12 +1000557 /**
558 * Install stubs for stuff that we haven't implemented yet so that the code
559 * still runs.
560 */
561 installUnimplementedStubs_() {
562 this.keyboard = {
563 keyMap: {
564 keyDefs: [],
565 },
566 bindings: {
567 clear: () => {},
568 addBinding: () => {},
569 addBindings: () => {},
570 OsDefaults: {},
571 },
572 };
573 this.keyboard.keyMap.keyDefs[78] = {};
574
575 const methodNames = [
Joel Hockeyb89a9782022-10-16 22:00:12 -0700576 'eraseLine',
Joel Hockeyb89a9782022-10-16 22:00:12 -0700577 'setCursorColumn',
Jason Linca61ffb2022-08-03 19:37:12 +1000578 'setCursorPosition',
579 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000580 ];
581
582 for (const name of methodNames) {
583 this[name] = () => console.warn(`${name}() is not implemented`);
584 }
585
586 this.contextMenu = {
587 setItems: () => {
588 console.warn('.contextMenu.setItems() is not implemented');
589 },
590 };
Jason Lin21d854f2022-08-22 14:49:59 +1000591
592 this.vt = {
593 resetParseState: () => {
594 console.warn('.vt.resetParseState() is not implemented');
595 },
596 };
Jason Linca61ffb2022-08-03 19:37:12 +1000597 }
598
Jason Line9231bc2022-09-01 13:54:02 +1000599 installEscapeSequenceHandlers_() {
600 // OSC 52 for copy.
601 this.term.parser.registerOscHandler(52, (args) => {
602 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
603 // parameter is used to select which of the X clipboards to address. Since
604 // we're not integrating with X, we treat them all the same.
605 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
606 if (!parsedArgs) {
607 return true;
608 }
609
610 let data;
611 try {
612 data = window.atob(parsedArgs[1]);
613 } catch (e) {
614 // If the user sent us invalid base64 content, silently ignore it.
615 return true;
616 }
617 const decoder = new TextDecoder();
618 const bytes = lib.codec.stringToCodeUnitArray(data);
619 this.copyString_(decoder.decode(bytes));
620
621 return true;
622 });
Jason Lin2649da22022-10-12 10:16:44 +1100623
624 this.xtermInternal_.installTmuxControlModeHandler(
625 (data) => this.onTmuxControlModeLine(data));
626 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000627 }
628
Jason Linca61ffb2022-08-03 19:37:12 +1000629 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000630 * Write data to the terminal.
631 *
632 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
633 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100634 * @param {function()=} callback Optional callback that fires when the data
635 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000636 */
Jason Lin2649da22022-10-12 10:16:44 +1100637 write(data, callback) {
638 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000639 }
640
641 /**
642 * Like `this.write()` but also write a line break.
643 *
644 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100645 * @param {function()=} callback Optional callback that fires when the data
646 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000647 */
Jason Lin2649da22022-10-12 10:16:44 +1100648 writeln(data, callback) {
649 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000650 }
651
Jason Linca61ffb2022-08-03 19:37:12 +1000652 get screenSize() {
653 return new hterm.Size(this.term.cols, this.term.rows);
654 }
655
656 /**
657 * Don't need to do anything.
658 *
659 * @override
660 */
661 installKeyboard() {}
662
663 /**
664 * @override
665 */
666 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000667 this.container_ = elem;
Jason Linee0c1f72022-10-18 17:17:26 +1100668 elem.style.backgroundSize = '100% 100%';
669
Jason Lin8de3d282022-09-01 21:29:05 +1000670 (async () => {
671 await new Promise((resolve) => this.prefs_.readStorage(resolve));
672 // This will trigger all the observers to set the terminal options before
673 // we call `this.term.open()`.
674 this.prefs_.notifyAll();
675
Jason Linc2504ae2022-09-02 13:03:31 +1000676 const screenPaddingSize = /** @type {number} */(
677 this.prefs_.get('screen-padding-size'));
678 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
679
Jason Linee0c1f72022-10-18 17:17:26 +1100680 this.setBackgroundImage(
681 this.backgroundImageWatcher_.getBackgroundImage());
682 this.backgroundImageWatcher_.watch();
683
Jason Lin8de3d282022-09-01 21:29:05 +1000684 this.inited_ = true;
685 this.term.open(elem);
686
Jason Lin8de3d282022-09-01 21:29:05 +1000687 if (this.enableWebGL_) {
Jason Linee0c1f72022-10-18 17:17:26 +1100688 this.reloadWebglAddon_();
Jason Lin8de3d282022-09-01 21:29:05 +1000689 }
690 this.term.focus();
691 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100692 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
693 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
694 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000695
Emil Mikulic2a194d02022-09-29 14:30:59 +1000696 // Block right-click context menu from popping up.
697 elem.addEventListener('contextmenu', (e) => e.preventDefault());
698
699 // Add a handler for pasting with the mouse.
700 elem.addEventListener('mousedown', async (e) => {
701 if (this.term.modes.mouseTrackingMode !== 'none') {
702 // xterm.js is in mouse mode and will handle the event.
703 return;
704 }
705 const MIDDLE = 1;
706 const RIGHT = 2;
707 if (e.button === MIDDLE || (e.button === RIGHT &&
708 this.prefs_.getBoolean('mouse-right-click-paste'))) {
709 // Paste.
710 if (navigator.clipboard && navigator.clipboard.readText) {
711 const text = await navigator.clipboard.readText();
712 this.term.paste(text);
713 }
714 }
715 });
716
Jason Lin2649da22022-10-12 10:16:44 +1100717 await this.scheduleFit_();
Jason Lina8adea52022-10-25 13:14:14 +1100718 this.a11yButtons_ = new A11yButtons(this.term, elem,
719 this.htermA11yReader_);
Jason Lind3aacef2022-10-12 19:03:37 +1100720
Jason Lin8de3d282022-09-01 21:29:05 +1000721 this.onTerminalReady();
722 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000723 }
724
725 /** @override */
726 showOverlay(msg, timeout = 1500) {
Jason Lin34a45322022-10-12 19:10:52 +1100727 this.notificationCenter_?.show(msg, {timeout});
Jason Lin21d854f2022-08-22 14:49:59 +1000728 }
729
730 /** @override */
731 hideOverlay() {
Jason Lin34a45322022-10-12 19:10:52 +1100732 this.notificationCenter_?.hide();
Jason Linca61ffb2022-08-03 19:37:12 +1000733 }
734
735 /** @override */
736 getPrefs() {
737 return this.prefs_;
738 }
739
740 /** @override */
741 getDocument() {
742 return window.document;
743 }
744
Jason Lin21d854f2022-08-22 14:49:59 +1000745 /** @override */
746 reset() {
747 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000748 }
749
750 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000751 setProfile(profileId, callback = undefined) {
752 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000753 }
754
Jason Lin21d854f2022-08-22 14:49:59 +1000755 /** @override */
756 interpret(string) {
757 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000758 }
759
Jason Lin21d854f2022-08-22 14:49:59 +1000760 /** @override */
761 focus() {
762 this.term.focus();
763 }
Jason Linca61ffb2022-08-03 19:37:12 +1000764
765 /** @override */
766 onOpenOptionsPage() {}
767
768 /** @override */
769 onTerminalReady() {}
770
Jason Lind04bab32022-08-22 14:48:39 +1000771 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000772 // This is for this.notificationCenter_.
773 const setHtermCSSVariable = (name, value) => {
774 document.body.style.setProperty(`--hterm-${name}`, value);
775 };
776
777 const setHtermColorCSSVariable = (name, color) => {
778 const css = lib.notNull(lib.colors.normalizeCSS(color));
779 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
780 setHtermCSSVariable(name, rgb);
781 };
782
783 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000784 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000785 setHtermCSSVariable('font-size', `${v}px`);
786 });
787
Jason Linda56aa92022-09-02 13:01:49 +1000788 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000789 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000790 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100791 this.bell_.playAudio = !!v;
792 },
793 'desktop-notification-bell': (v) => {
794 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000795 },
Jason Lind04bab32022-08-22 14:48:39 +1000796 'background-color': (v) => {
Jason Linee0c1f72022-10-18 17:17:26 +1100797 this.updateBackgroundColor_(v);
Jason Lin21d854f2022-08-22 14:49:59 +1000798 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000799 },
Jason Lind04bab32022-08-22 14:48:39 +1000800 'color-palette-overrides': (v) => {
801 if (!(v instanceof Array)) {
802 // For terminal, we always expect this to be an array.
803 console.warn('unexpected color palette: ', v);
804 return;
805 }
806 const colors = {};
807 for (let i = 0; i < v.length; ++i) {
808 colors[ANSI_COLOR_NAMES[i]] = v[i];
809 }
810 this.updateTheme_(colors);
811 },
Jason Linda56aa92022-09-02 13:01:49 +1000812 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
813 'cursor-color': (v) => this.updateTheme_({cursor: v}),
814 'cursor-shape': (v) => {
815 let shape;
816 if (v === 'BEAM') {
817 shape = 'bar';
818 } else {
819 shape = v.toLowerCase();
820 }
821 this.updateOption_('cursorStyle', shape, false);
822 },
823 'font-family': (v) => this.updateFont_(v),
824 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000825 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000826 setHtermColorCSSVariable('foreground-color', v);
827 },
Jason Linc48f7432022-10-13 17:28:30 +1100828 'line-height': (v) => this.updateOption_('lineHeight', v, true),
Jason Lin446f3d92022-10-13 17:34:21 +1100829 'scroll-on-output': (v) => {
830 if (!v) {
831 this.scrollOnOutputListener_?.dispose();
832 this.scrollOnOutputListener_ = null;
833 return;
834 }
835 if (!this.scrollOnOutputListener_) {
836 this.scrollOnOutputListener_ = this.term.onWriteParsed(
837 () => this.term.scrollToBottom());
838 }
839 },
Jason Lind04bab32022-08-22 14:48:39 +1000840 });
Jason Lin5690e752022-08-30 15:36:45 +1000841
842 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
843 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
844 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
845 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
846 }
Jason Lind04bab32022-08-22 14:48:39 +1000847 }
848
849 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000850 * Fit the terminal to the containing HTML element.
851 */
852 fit_() {
853 if (!this.inited_) {
854 return;
855 }
856
857 const screenPaddingSize = /** @type {number} */(
858 this.prefs_.get('screen-padding-size'));
859
860 const calc = (size, cellSize) => {
861 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
862 };
863
Jason Lin2649da22022-10-12 10:16:44 +1100864 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
865 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
866 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000867 if (cols >= 0 && rows >= 0) {
868 this.term.resize(cols, rows);
869 }
870 }
871
Jason Linee0c1f72022-10-18 17:17:26 +1100872 reloadWebglAddon_() {
873 if (this.webglAddon_) {
874 this.webglAddon_.dispose();
875 }
876 this.webglAddon_ = new WebglAddon();
877 this.term.loadAddon(this.webglAddon_);
878 }
879
880 /**
881 * Update the background color. This will also adjust the transparency based
882 * on whether there is a background image.
883 *
884 * @param {string} color
885 */
886 updateBackgroundColor_(color) {
887 const hasBackgroundImage = this.hasBackgroundImage();
888
889 // We only set allowTransparency when it is necessary becuase 1) xterm.js
890 // documentation states that allowTransparency can affect performance; 2) I
891 // find that the rendering is better with allowTransparency being false.
892 // This could be a bug with xterm.js.
893 if (!!this.term.options.allowTransparency !== hasBackgroundImage) {
894 this.term.options.allowTransparency = hasBackgroundImage;
895 if (this.enableWebGL_ && this.inited_) {
896 // Setting allowTransparency in the middle messes up webgl rendering,
897 // so we need to reload it here.
898 this.reloadWebglAddon_();
899 }
900 }
901
902 if (this.hasBackgroundImage()) {
903 const css = lib.notNull(lib.colors.normalizeCSS(color));
904 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
905 // Note that we still want to set the RGB part correctly even though it is
906 // completely transparent. This is because the background color without
907 // the alpha channel is used in reverse video mode.
908 color = `rgba(${rgb}, 0)`;
909 }
910
911 this.updateTheme_({background: color});
912 }
913
Jason Linc2504ae2022-09-02 13:03:31 +1000914 /**
Jason Lind04bab32022-08-22 14:48:39 +1000915 * @param {!Object} theme
916 */
917 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000918 const updateTheme = (target) => {
919 for (const [key, value] of Object.entries(theme)) {
920 target[key] = lib.colors.normalizeCSS(value);
921 }
922 };
923
924 // Must use a new theme object to trigger re-render if we have initialized.
925 if (this.inited_) {
926 const newTheme = {...this.term.options.theme};
927 updateTheme(newTheme);
928 this.term.options.theme = newTheme;
929 return;
Jason Lind04bab32022-08-22 14:48:39 +1000930 }
Jason Lin8de3d282022-09-01 21:29:05 +1000931
932 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000933 }
934
935 /**
Jason Linda56aa92022-09-02 13:01:49 +1000936 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
937 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000938 *
939 * @param {string} key
940 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000941 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000942 */
Jason Linda56aa92022-09-02 13:01:49 +1000943 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000944 // TODO: xterm supports updating multiple options at the same time. We
945 // should probably do that.
946 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000947 if (scheduleFit) {
948 this.scheduleFit_();
949 }
Jason Lind04bab32022-08-22 14:48:39 +1000950 }
Jason Linabad7562022-08-22 14:49:05 +1000951
952 /**
953 * Called when there is a "fontloadingdone" event. We need this because
954 * `FontManager.loadFont()` does not guarantee loading all the font files.
955 */
956 async onFontLoadingDone_() {
957 // If there is a pending font, the font is going to be refresh soon, so we
958 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000959 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000960 this.scheduleRefreshFont_();
961 }
962 }
963
Jason Lin5690e752022-08-30 15:36:45 +1000964 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000965 this.copyString_(this.term.getSelection());
966 }
967
968 /** @param {string} data */
969 copyString_(data) {
970 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000971 return;
972 }
Jason Line9231bc2022-09-01 13:54:02 +1000973 navigator.clipboard?.writeText(data);
Jason Lin83ef5ba2022-10-13 17:40:30 +1100974
975 if (this.prefs_.get('enable-clipboard-notice')) {
976 if (!this.copyNotice_) {
977 this.copyNotice_ = document.createElement('terminal-copy-notice');
978 }
979 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500),
980 200);
Jason Lin6a402a72022-08-25 16:07:02 +1000981 }
Jason Lin6a402a72022-08-25 16:07:02 +1000982 }
983
Jason Linabad7562022-08-22 14:49:05 +1000984 /**
985 * Refresh xterm rendering for a font related event.
986 */
987 refreshFont_() {
988 // We have to set the fontFamily option to a different string to trigger the
989 // re-rendering. Appending a space at the end seems to be the easiest
990 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
991 // us.
992 //
993 // TODO: Report a bug to xterm.js and ask for exposing a public function for
994 // the refresh so that we don't need to do this hack.
995 this.term.options.fontFamily += ' ';
996 }
997
998 /**
999 * Update a font.
1000 *
1001 * @param {string} cssFontFamily
1002 */
1003 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +10001004 this.pendingFont_ = cssFontFamily;
1005 await this.fontManager_.loadFont(cssFontFamily);
1006 // Sleep a bit to wait for flushing fontloadingdone events. This is not
1007 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
1008 // to refresh font unnecessarily in some cases.
1009 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +10001010
Jason Lin6a402a72022-08-25 16:07:02 +10001011 if (this.pendingFont_ !== cssFontFamily) {
1012 // `updateFont_()` probably is called again. Abort what we are doing.
1013 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
1014 ` (expecting ${cssFontFamily})`);
1015 return;
1016 }
Jason Linabad7562022-08-22 14:49:05 +10001017
Jason Lin6a402a72022-08-25 16:07:02 +10001018 if (this.term.options.fontFamily !== cssFontFamily) {
1019 this.term.options.fontFamily = cssFontFamily;
1020 } else {
1021 // If the font is already the same, refresh font just to be safe.
1022 this.refreshFont_();
1023 }
1024 this.pendingFont_ = null;
1025 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +10001026 }
Jason Lin5690e752022-08-30 15:36:45 +10001027
1028 /**
1029 * @param {!KeyboardEvent} ev
1030 * @return {boolean} Return false if xterm.js should not handle the key event.
1031 */
1032 customKeyEventHandler_(ev) {
1033 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
1034 (ev.altKey ? Modifier.Alt : 0) |
1035 (ev.ctrlKey ? Modifier.Ctrl : 0) |
1036 (ev.metaKey ? Modifier.Meta : 0);
1037 const handler = this.keyDownHandlers_.get(
1038 encodeKeyCombo(modifiers, ev.keyCode));
1039 if (handler) {
1040 if (ev.type === 'keydown') {
1041 handler(ev);
1042 }
1043 return false;
1044 }
1045
1046 return true;
1047 }
1048
1049 /**
1050 * A keydown handler for zoom-related keys.
1051 *
1052 * @param {!KeyboardEvent} ev
1053 */
1054 zoomKeyDownHandler_(ev) {
1055 ev.preventDefault();
1056
1057 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
1058 // The only one with a control code.
1059 if (ev.keyCode === keyCodes.MINUS) {
1060 this.io.onVTKeystroke('\x1f');
1061 }
1062 return;
1063 }
1064
1065 let newFontSize;
1066 switch (ev.keyCode) {
1067 case keyCodes.ZERO:
1068 newFontSize = this.prefs_.get('font-size');
1069 break;
1070 case keyCodes.MINUS:
1071 newFontSize = this.term.options.fontSize - 1;
1072 break;
1073 default:
1074 newFontSize = this.term.options.fontSize + 1;
1075 break;
1076 }
1077
Jason Linda56aa92022-09-02 13:01:49 +10001078 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +10001079 }
1080
1081 /** @param {!KeyboardEvent} ev */
1082 ctrlCKeyDownHandler_(ev) {
1083 ev.preventDefault();
1084 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
1085 this.term.hasSelection()) {
1086 this.copySelection_();
1087 return;
1088 }
1089
1090 this.io.onVTKeystroke('\x03');
1091 }
1092
1093 /** @param {!KeyboardEvent} ev */
1094 ctrlVKeyDownHandler_(ev) {
1095 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
1096 // Don't do anything and let the browser handles the key.
1097 return;
1098 }
1099
1100 ev.preventDefault();
1101 this.io.onVTKeystroke('\x16');
1102 }
1103
1104 resetKeyDownHandlers_() {
1105 this.keyDownHandlers_.clear();
1106
1107 /**
1108 * Don't do anything and let the browser handles the key.
1109 *
1110 * @param {!KeyboardEvent} ev
1111 */
1112 const noop = (ev) => {};
1113
1114 /**
1115 * @param {number} modifiers
1116 * @param {number} keyCode
1117 * @param {function(!KeyboardEvent)} func
1118 */
1119 const set = (modifiers, keyCode, func) => {
1120 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
1121 func);
1122 };
1123
1124 /**
1125 * @param {number} modifiers
1126 * @param {number} keyCode
1127 * @param {function(!KeyboardEvent)} func
1128 */
1129 const setWithShiftVersion = (modifiers, keyCode, func) => {
1130 set(modifiers, keyCode, func);
1131 set(modifiers | Modifier.Shift, keyCode, func);
1132 };
1133
Jason Lin5690e752022-08-30 15:36:45 +10001134 // Ctrl+/
1135 set(Modifier.Ctrl, 191, (ev) => {
1136 ev.preventDefault();
1137 this.io.onVTKeystroke(ctl('_'));
1138 });
1139
1140 // Settings page.
1141 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
1142 ev.preventDefault();
1143 chrome.terminalPrivate.openOptionsPage(() => {});
1144 });
1145
1146 if (this.prefs_.get('keybindings-os-defaults')) {
1147 for (const binding of OS_DEFAULT_BINDINGS) {
1148 this.keyDownHandlers_.set(binding, noop);
1149 }
1150 }
1151
1152 /** @param {!KeyboardEvent} ev */
1153 const newWindow = (ev) => {
1154 ev.preventDefault();
1155 chrome.terminalPrivate.openWindow();
1156 };
1157 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
1158 if (this.prefs_.get('pass-ctrl-n')) {
1159 set(Modifier.Ctrl, keyCodes.N, newWindow);
1160 }
1161
1162 if (this.prefs_.get('pass-ctrl-t')) {
1163 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
1164 }
1165
1166 if (this.prefs_.get('pass-ctrl-w')) {
1167 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
1168 }
1169
1170 if (this.prefs_.get('pass-ctrl-tab')) {
1171 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
1172 }
1173
1174 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
1175
1176 /**
1177 * Set a handler for the key combo ctrl+<number>.
1178 *
1179 * @param {number} number 1 to 9
1180 * @param {string} controlCode The control code to send if we don't want to
1181 * let the browser to handle it.
1182 */
1183 const setCtrlNumberHandler = (number, controlCode) => {
1184 let func = noop;
1185 if (!passCtrlNumber) {
1186 func = (ev) => {
1187 ev.preventDefault();
1188 this.io.onVTKeystroke(controlCode);
1189 };
1190 }
1191 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1192 };
1193
1194 setCtrlNumberHandler(1, '1');
1195 setCtrlNumberHandler(2, ctl('@'));
1196 setCtrlNumberHandler(3, ctl('['));
1197 setCtrlNumberHandler(4, ctl('\\'));
1198 setCtrlNumberHandler(5, ctl(']'));
1199 setCtrlNumberHandler(6, ctl('^'));
1200 setCtrlNumberHandler(7, ctl('_'));
1201 setCtrlNumberHandler(8, '\x7f');
1202 setCtrlNumberHandler(9, '9');
1203
1204 if (this.prefs_.get('pass-alt-number')) {
1205 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1206 set(Modifier.Alt, keyCode, noop);
1207 }
1208 }
1209
1210 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1211 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1212 }
1213
1214 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1215 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1216 }
Jason Linee0c1f72022-10-18 17:17:26 +11001217
1218 handleOnTerminalReady() {}
Jason Linca61ffb2022-08-03 19:37:12 +10001219}
1220
Jason Lind66e6bf2022-08-22 14:47:10 +10001221class HtermTerminal extends hterm.Terminal {
1222 /** @override */
1223 decorate(div) {
1224 super.decorate(div);
1225
Jason Linc48f7432022-10-13 17:28:30 +11001226 definePrefs(this.getPrefs());
Jason Linee0c1f72022-10-18 17:17:26 +11001227 }
Jason Linc48f7432022-10-13 17:28:30 +11001228
Jason Linee0c1f72022-10-18 17:17:26 +11001229 /**
1230 * This needs to be called in the `onTerminalReady()` callback. This is
1231 * awkward, but it is temporary since we will drop support for hterm at some
1232 * point.
1233 */
1234 handleOnTerminalReady() {
Jason Lind66e6bf2022-08-22 14:47:10 +10001235 const fontManager = new FontManager(this.getDocument());
1236 fontManager.loadPowerlineCSS().then(() => {
1237 const prefs = this.getPrefs();
1238 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1239 prefs.addObserver(
1240 'font-family',
1241 (v) => fontManager.loadFont(/** @type {string} */(v)));
1242 });
Jason Linee0c1f72022-10-18 17:17:26 +11001243
1244 const backgroundImageWatcher = new BackgroundImageWatcher(this.getPrefs(),
1245 (image) => this.setBackgroundImage(image));
1246 this.setBackgroundImage(backgroundImageWatcher.getBackgroundImage());
1247 backgroundImageWatcher.watch();
Jason Lind66e6bf2022-08-22 14:47:10 +10001248 }
Jason Lin2649da22022-10-12 10:16:44 +11001249
1250 /**
1251 * Write data to the terminal.
1252 *
1253 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1254 * UTF-8 data
1255 * @param {function()=} callback Optional callback that fires when the data
1256 * was processed by the parser.
1257 */
1258 write(data, callback) {
1259 if (typeof data === 'string') {
1260 this.io.print(data);
1261 } else {
1262 this.io.writeUTF8(data);
1263 }
1264 // Hterm processes the data synchronously, so we can call the callback
1265 // immediately.
1266 if (callback) {
1267 setTimeout(callback);
1268 }
1269 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001270}
1271
Jason Linca61ffb2022-08-03 19:37:12 +10001272/**
1273 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1274 * preference value.
1275 *
1276 * @param {{
1277 * storage: !lib.Storage,
1278 * profileId: string,
1279 * }} args
1280 * @return {!Promise<!hterm.Terminal>}
1281 */
1282export async function createEmulator({storage, profileId}) {
1283 let config = TERMINAL_EMULATORS.get('hterm');
1284
1285 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001286 // TODO: remove the url param logic. This is temporary to make manual
1287 // testing a bit easier, which is also why this is not in
1288 // './js/terminal_info.js'.
1289 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
1290 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +10001291 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001292 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001293 TERMINAL_EMULATORS.values().next().value;
1294 console.log('Terminal emulator config: ', config);
1295 }
1296
1297 switch (config.lib) {
1298 case 'xterm.js':
1299 {
1300 const terminal = new XtermTerminal({
1301 storage,
1302 profileId,
1303 enableWebGL: config.webgl,
1304 });
Jason Linca61ffb2022-08-03 19:37:12 +10001305 return terminal;
1306 }
1307 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001308 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001309 default:
1310 throw new Error('incorrect emulator config');
1311 }
1312}
1313
Jason Lin6a402a72022-08-25 16:07:02 +10001314class TerminalCopyNotice extends LitElement {
1315 /** @override */
1316 static get styles() {
1317 return css`
1318 :host {
1319 display: block;
1320 text-align: center;
1321 }
1322
1323 svg {
1324 fill: currentColor;
1325 }
1326 `;
1327 }
1328
1329 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001330 connectedCallback() {
1331 super.connectedCallback();
1332 if (!this.childNodes.length) {
1333 // This is not visible since we use shadow dom. But this will allow the
1334 // hterm.NotificationCenter to announce the the copy text.
1335 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1336 }
1337 }
1338
1339 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001340 render() {
1341 return html`
1342 ${ICON_COPY}
1343 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1344 `;
1345 }
1346}
1347
1348customElements.define('terminal-copy-notice', TerminalCopyNotice);