blob: 190961b0bd2119808959242606b6b530f480930a [file] [log] [blame]
Mike Frysinger598e8012022-09-07 08:38:34 -04001// Copyright 2022 The ChromiumOS Authors
Jason Lind66e6bf2022-08-22 14:47:10 +10002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Jason Linca61ffb2022-08-03 19:37:12 +10005/**
6 * @fileoverview For supporting xterm.js and the terminal emulator.
7 */
8
9// TODO(b/236205389): add tests. For example, we should enable the test in
10// terminal_tests.js for XtermTerminal.
11
Jason Lin2649da22022-10-12 10:16:44 +110012// TODO(b/236205389): support option smoothScrollDuration?
13
Mike Frysinger75895da2022-10-04 00:42:28 +054514import {hterm, lib} from './deps_local.concat.js';
15
Jason Lin6a402a72022-08-25 16:07:02 +100016import {LitElement, css, html} from './lit.js';
Jason Linc48f7432022-10-13 17:28:30 +110017import {FontManager, ORIGINAL_URL, TERMINAL_EMULATORS, definePrefs,
18 delayedScheduler, fontManager, getOSInfo, sleep} from './terminal_common.js';
Jason Lin82ba86c2022-11-09 12:12:27 +110019import {TerminalContextMenu} from './terminal_context_menu.js';
Jason Lin6a402a72022-08-25 16:07:02 +100020import {ICON_COPY} from './terminal_icons.js';
Jason Lin83707c92022-09-20 19:09:41 +100021import {TerminalTooltip} from './terminal_tooltip.js';
Jason Linc2504ae2022-09-02 13:03:31 +100022import {Terminal, Unicode11Addon, WebLinksAddon, WebglAddon}
Jason Lin4de4f382022-09-01 14:10:18 +100023 from './xterm.js';
Jason Lin2649da22022-10-12 10:16:44 +110024import {XtermInternal} from './terminal_xterm_internal.js';
Jason Linca61ffb2022-08-03 19:37:12 +100025
Jason Lin5690e752022-08-30 15:36:45 +100026
27/** @enum {number} */
28export const Modifier = {
29 Shift: 1 << 0,
30 Alt: 1 << 1,
31 Ctrl: 1 << 2,
32 Meta: 1 << 3,
33};
34
35// This is just a static map from key names to key codes. It helps make the code
36// a bit more readable.
37const keyCodes = hterm.Parser.identifiers.keyCodes;
38
39/**
40 * Encode a key combo (i.e. modifiers + a normal key) to an unique number.
41 *
42 * @param {number} modifiers
43 * @param {number} keyCode
44 * @return {number}
45 */
46export function encodeKeyCombo(modifiers, keyCode) {
47 return keyCode << 4 | modifiers;
48}
49
50const OS_DEFAULT_BINDINGS = [
51 // Submit feedback.
52 encodeKeyCombo(Modifier.Alt | Modifier.Shift, keyCodes.I),
53 // Toggle chromevox.
54 encodeKeyCombo(Modifier.Ctrl | Modifier.Alt, keyCodes.Z),
55 // Switch input method.
56 encodeKeyCombo(Modifier.Ctrl, keyCodes.SPACE),
57
58 // Dock window left/right.
59 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_LEFT),
60 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_RIGHT),
61
62 // Maximize/minimize window.
63 encodeKeyCombo(Modifier.Alt, keyCodes.EQUAL),
64 encodeKeyCombo(Modifier.Alt, keyCodes.MINUS),
65];
66
67
Jason Linca61ffb2022-08-03 19:37:12 +100068const ANSI_COLOR_NAMES = [
69 'black',
70 'red',
71 'green',
72 'yellow',
73 'blue',
74 'magenta',
75 'cyan',
76 'white',
77 'brightBlack',
78 'brightRed',
79 'brightGreen',
80 'brightYellow',
81 'brightBlue',
82 'brightMagenta',
83 'brightCyan',
84 'brightWhite',
85];
86
Jason Linca61ffb2022-08-03 19:37:12 +100087/**
Jason Linabad7562022-08-22 14:49:05 +100088 * @typedef {{
89 * term: !Terminal,
90 * fontManager: !FontManager,
Jason Lin2649da22022-10-12 10:16:44 +110091 * xtermInternal: !XtermInternal,
Jason Linabad7562022-08-22 14:49:05 +100092 * }}
93 */
94export let XtermTerminalTestParams;
95
96/**
Jason Lin5690e752022-08-30 15:36:45 +100097 * Compute a control character for a given character.
98 *
99 * @param {string} ch
100 * @return {string}
101 */
102function ctl(ch) {
103 return String.fromCharCode(ch.charCodeAt(0) - 64);
104}
105
106/**
Jason Lin21d854f2022-08-22 14:49:59 +1000107 * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO
108 * because it always convert utf8 data to strings, which is not necessary for
109 * xterm.
110 */
111class XtermTerminalIO extends hterm.Terminal.IO {
112 /** @override */
113 writeUTF8(buffer) {
114 this.terminal_.write(new Uint8Array(buffer));
115 }
116
117 /** @override */
118 writelnUTF8(buffer) {
119 this.terminal_.writeln(new Uint8Array(buffer));
120 }
121
122 /** @override */
123 print(string) {
124 this.terminal_.write(string);
125 }
126
127 /** @override */
128 writeUTF16(string) {
129 this.print(string);
130 }
131
132 /** @override */
133 println(string) {
134 this.terminal_.writeln(string);
135 }
136
137 /** @override */
138 writelnUTF16(string) {
139 this.println(string);
140 }
141}
142
143/**
Jason Lin83707c92022-09-20 19:09:41 +1000144 * A custom link handler that:
145 *
146 * - Shows a tooltip with the url on a OSC 8 link. This is following what hterm
147 * is doing. Also, showing the tooltip is better for the security of the user
148 * because the link can have arbitrary text.
149 * - Uses our own way to open the window.
150 */
151class LinkHandler {
152 /**
153 * @param {!Terminal} term
154 */
155 constructor(term) {
156 this.term_ = term;
157 /** @type {?TerminalTooltip} */
158 this.tooltip_ = null;
159 }
160
161 /**
162 * @return {!TerminalTooltip}
163 */
164 getTooltip_() {
165 if (!this.tooltip_) {
166 this.tooltip_ = /** @type {!TerminalTooltip} */(
167 document.createElement('terminal-tooltip'));
168 this.tooltip_.classList.add('xterm-hover');
169 lib.notNull(this.term_.element).appendChild(this.tooltip_);
170 }
171 return this.tooltip_;
172 }
173
174 /**
175 * @param {!MouseEvent} ev
176 * @param {string} url
177 * @param {!Object} range
178 */
179 activate(ev, url, range) {
180 lib.f.openWindow(url, '_blank');
181 }
182
183 /**
184 * @param {!MouseEvent} ev
185 * @param {string} url
186 * @param {!Object} range
187 */
188 hover(ev, url, range) {
189 this.getTooltip_().show(url, {x: ev.clientX, y: ev.clientY});
190 }
191
192 /**
193 * @param {!MouseEvent} ev
194 * @param {string} url
195 * @param {!Object} range
196 */
197 leave(ev, url, range) {
198 this.getTooltip_().hide();
199 }
200}
201
Jason Linc7afb672022-10-11 15:54:17 +1100202class Bell {
203 constructor() {
204 this.showNotification = false;
205
206 /** @type {?Audio} */
207 this.audio_ = null;
208 /** @type {?Notification} */
209 this.notification_ = null;
210 this.coolDownUntil_ = 0;
211 }
212
213 /**
214 * Set whether a bell audio should be played.
215 *
216 * @param {boolean} value
217 */
218 set playAudio(value) {
219 this.audio_ = value ?
220 new Audio(lib.resource.getDataUrl('hterm/audio/bell')) : null;
221 }
222
223 ring() {
224 const now = Date.now();
225 if (now < this.coolDownUntil_) {
226 return;
227 }
228 this.coolDownUntil_ = now + 500;
229
230 this.audio_?.play();
231 if (this.showNotification && !document.hasFocus() && !this.notification_) {
232 this.notification_ = new Notification(
233 `\u266A ${document.title} \u266A`,
234 {icon: lib.resource.getDataUrl('hterm/images/icon-96')});
235 // Close the notification after a timeout. Note that this is different
236 // from hterm's behavior, but I think it makes more sense to do so.
237 setTimeout(() => {
238 this.notification_.close();
239 this.notification_ = null;
240 }, 5000);
241 }
242 }
243}
244
Jason Lind3aacef2022-10-12 19:03:37 +1100245const A11Y_BUTTON_STYLE = `
246position: fixed;
247z-index: 10;
248right: 16px;
249`;
250
Jason Lina8adea52022-10-25 13:14:14 +1100251// TODO: we should subscribe to the xterm.js onscroll event, and
252// disable/enable the buttons accordingly. However, xterm.js does not seem to
253// emit the onscroll event when the viewport is scrolled by the mouse. See
254// https://github.com/xtermjs/xterm.js/issues/3864
255export class A11yButtons {
Jason Lind3aacef2022-10-12 19:03:37 +1100256 /**
257 * @param {!Terminal} term
Jason Lina8adea52022-10-25 13:14:14 +1100258 * @param {!hterm.AccessibilityReader} htermA11yReader
Jason Lind3aacef2022-10-12 19:03:37 +1100259 */
Jason Linc0f14fe2022-10-25 15:31:29 +1100260 constructor(term, htermA11yReader) {
Jason Lina8adea52022-10-25 13:14:14 +1100261 this.term_ = term;
262 this.htermA11yReader_ = htermA11yReader;
Jason Linc0f14fe2022-10-25 15:31:29 +1100263 this.pageUpButton = document.createElement('button');
264 this.pageUpButton.style.cssText = A11Y_BUTTON_STYLE;
265 this.pageUpButton.textContent =
Jason Lind3aacef2022-10-12 19:03:37 +1100266 hterm.messageManager.get('HTERM_BUTTON_PAGE_UP');
Jason Linc0f14fe2022-10-25 15:31:29 +1100267 this.pageUpButton.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100268 () => this.scrollPages_(-1));
Jason Lind3aacef2022-10-12 19:03:37 +1100269
Jason Linc0f14fe2022-10-25 15:31:29 +1100270 this.pageDownButton = document.createElement('button');
271 this.pageDownButton.style.cssText = A11Y_BUTTON_STYLE;
272 this.pageDownButton.textContent =
Jason Lind3aacef2022-10-12 19:03:37 +1100273 hterm.messageManager.get('HTERM_BUTTON_PAGE_DOWN');
Jason Linc0f14fe2022-10-25 15:31:29 +1100274 this.pageDownButton.addEventListener('click',
Jason Lina8adea52022-10-25 13:14:14 +1100275 () => this.scrollPages_(1));
Jason Lind3aacef2022-10-12 19:03:37 +1100276
277 this.resetPos_();
Jason Lind3aacef2022-10-12 19:03:37 +1100278
279 this.onSelectionChange_ = this.onSelectionChange_.bind(this);
280 }
281
282 /**
Jason Lina8adea52022-10-25 13:14:14 +1100283 * @param {number} amount
284 */
285 scrollPages_(amount) {
286 this.term_.scrollPages(amount);
287 this.announceScreenContent_();
288 }
289
290 announceScreenContent_() {
291 const activeBuffer = this.term_.buffer.active;
292
293 let percentScrolled = 100;
294 if (activeBuffer.baseY !== 0) {
295 percentScrolled = Math.round(
296 100 * activeBuffer.viewportY / activeBuffer.baseY);
297 }
298
299 let currentScreenContent = hterm.messageManager.get(
300 'HTERM_ANNOUNCE_CURRENT_SCREEN_HEADER',
301 [percentScrolled],
302 '$1% scrolled,');
303
304 currentScreenContent += '\n';
305
306 const rowEnd = Math.min(activeBuffer.viewportY + this.term_.rows,
307 activeBuffer.length);
308 for (let i = activeBuffer.viewportY; i < rowEnd; ++i) {
309 currentScreenContent +=
310 activeBuffer.getLine(i).translateToString(true) + '\n';
311 }
312 currentScreenContent = currentScreenContent.trim();
313
314 this.htermA11yReader_.assertiveAnnounce(currentScreenContent);
315 }
316
317 /**
Jason Lind3aacef2022-10-12 19:03:37 +1100318 * @param {boolean} enabled
319 */
320 setEnabled(enabled) {
321 if (enabled) {
322 document.addEventListener('selectionchange', this.onSelectionChange_);
323 } else {
324 this.resetPos_();
325 document.removeEventListener('selectionchange', this.onSelectionChange_);
326 }
327 }
328
329 resetPos_() {
Jason Linc0f14fe2022-10-25 15:31:29 +1100330 this.pageUpButton.style.top = '-200px';
331 this.pageDownButton.style.bottom = '-200px';
Jason Lind3aacef2022-10-12 19:03:37 +1100332 }
333
334 onSelectionChange_() {
335 this.resetPos_();
336
Jason Lin36b9fce2022-11-10 16:56:40 +1100337 const selectedElement = document.getSelection().anchorNode?.parentElement;
Jason Linc0f14fe2022-10-25 15:31:29 +1100338 if (selectedElement === this.pageUpButton) {
339 this.pageUpButton.style.top = '16px';
340 } else if (selectedElement === this.pageDownButton) {
341 this.pageDownButton.style.bottom = '16px';
Jason Lind3aacef2022-10-12 19:03:37 +1100342 }
343 }
344}
345
Jason Linee0c1f72022-10-18 17:17:26 +1100346const BACKGROUND_IMAGE_KEY = 'background-image';
347
348class BackgroundImageWatcher {
349 /**
350 * @param {!hterm.PreferenceManager} prefs
351 * @param {function(string)} onChange This is called with the background image
352 * (could be empty) whenever it changes.
353 */
354 constructor(prefs, onChange) {
355 this.prefs_ = prefs;
356 this.onChange_ = onChange;
357 }
358
359 /**
360 * Call once to start watching for background image changes.
361 */
362 watch() {
363 window.addEventListener('storage', (e) => {
364 if (e.key === BACKGROUND_IMAGE_KEY) {
365 this.onChange_(this.getBackgroundImage());
366 }
367 });
368 this.prefs_.addObserver(BACKGROUND_IMAGE_KEY, () => {
369 this.onChange_(this.getBackgroundImage());
370 });
371 }
372
373 getBackgroundImage() {
374 const image = window.localStorage.getItem(BACKGROUND_IMAGE_KEY);
375 if (image) {
376 return `url(${image})`;
377 }
378
379 return this.prefs_.getString(BACKGROUND_IMAGE_KEY);
380 }
381}
382
Jason Linb8f380a2022-10-25 13:15:56 +1100383let xtermTerminalStringsLoaded = false;
384
Jason Lin83707c92022-09-20 19:09:41 +1000385/**
Jason Linca61ffb2022-08-03 19:37:12 +1000386 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
387 * so that it can be used in existing code.
388 *
Jason Linca61ffb2022-08-03 19:37:12 +1000389 * @extends {hterm.Terminal}
390 * @unrestricted
391 */
Jason Linabad7562022-08-22 14:49:05 +1000392export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000393 /**
394 * @param {{
395 * storage: !lib.Storage,
396 * profileId: string,
397 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000398 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000399 * }} args
400 */
Jason Linabad7562022-08-22 14:49:05 +1000401 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000402 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
403 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
404 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
405
Jason Lin8de3d282022-09-01 21:29:05 +1000406 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000407 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000408 /** @type {!hterm.PreferenceManager} */
409 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
Jason Linc48f7432022-10-13 17:28:30 +1100410 definePrefs(this.prefs_);
Jason Linca61ffb2022-08-03 19:37:12 +1000411 this.enableWebGL_ = enableWebGL;
412
Jason Lin5690e752022-08-30 15:36:45 +1000413 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linfc8a3722022-09-07 17:49:18 +1000414 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Lin2649da22022-10-12 10:16:44 +1100415 this.xtermInternal_ = testParams?.xtermInternal ||
416 new XtermInternal(this.term);
Jason Linabad7562022-08-22 14:49:05 +1000417 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000418
Jason Linc2504ae2022-09-02 13:03:31 +1000419 /** @type {?Element} */
420 this.container_;
Jason Linc7afb672022-10-11 15:54:17 +1100421 this.bell_ = new Bell();
Jason Linc2504ae2022-09-02 13:03:31 +1000422 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000423 testParams ? 0 : 250);
424
Jason Lin83707c92022-09-20 19:09:41 +1000425 this.term.loadAddon(
426 new WebLinksAddon((e, uri) => lib.f.openWindow(uri, '_blank')));
Jason Lin4de4f382022-09-01 14:10:18 +1000427 this.term.loadAddon(new Unicode11Addon());
428 this.term.unicode.activeVersion = '11';
429
Jason Linabad7562022-08-22 14:49:05 +1000430 this.pendingFont_ = null;
431 this.scheduleRefreshFont_ = delayedScheduler(
432 () => this.refreshFont_(), 100);
433 document.fonts.addEventListener('loadingdone',
434 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000435
436 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000437 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000438
Jason Lin34a45322022-10-12 19:10:52 +1100439 this.term.onResize(({cols, rows}) => {
440 this.io.onTerminalResize(cols, rows);
441 if (this.prefs_.get('enable-resize-status')) {
442 this.showOverlay(`${cols} × ${rows}`);
443 }
444 });
Jason Lin21d854f2022-08-22 14:49:59 +1000445 // We could also use `this.io.sendString()` except for the nassh exit
446 // prompt, which only listens to onVTKeystroke().
447 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000448 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100449 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin83ef5ba2022-10-13 17:40:30 +1100450 this.term.onSelectionChange(() => {
451 if (this.prefs_.get('copy-on-select')) {
452 this.copySelection_();
453 }
454 });
Jason Linc7afb672022-10-11 15:54:17 +1100455 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000456
457 /**
458 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
459 *
460 * If a key combo is in the map:
461 *
462 * - The handler instead of xterm.js will handle the keydown event.
463 * - Keyup and keypress will be ignored by both us and xterm.js.
464 *
465 * We re-generate this map every time a relevant pref value is changed. This
466 * is ok because pref changes are rare.
467 *
468 * @type {!Map<number, function(!KeyboardEvent)>}
469 */
470 this.keyDownHandlers_ = new Map();
471 this.scheduleResetKeyDownHandlers_ =
472 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
473
474 this.term.attachCustomKeyEventHandler(
475 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000476
Jason Lin21d854f2022-08-22 14:49:59 +1000477 this.io = new XtermTerminalIO(this);
478 this.notificationCenter_ = null;
Jason Lind3aacef2022-10-12 19:03:37 +1100479 this.htermA11yReader_ = null;
Jason Linc0f14fe2022-10-25 15:31:29 +1100480 this.a11yEnabled_ = false;
Jason Lind3aacef2022-10-12 19:03:37 +1100481 this.a11yButtons_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000482 this.copyNotice_ = null;
Jason Lin446f3d92022-10-13 17:34:21 +1100483 this.scrollOnOutputListener_ = null;
Jason Linee0c1f72022-10-18 17:17:26 +1100484 this.backgroundImageWatcher_ = new BackgroundImageWatcher(this.prefs_,
485 this.setBackgroundImage.bind(this));
486 this.webglAddon_ = null;
Jason Lina63d8ba2022-11-02 17:42:38 +1100487 this.userCSSElement_ = null;
488 this.userCSSTextElement_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000489
Jason Lin82ba86c2022-11-09 12:12:27 +1100490 this.contextMenu_ = /** @type {!TerminalContextMenu} */(
491 document.createElement('terminal-context-menu'));
492 this.contextMenu_.style.zIndex = 10;
493 this.contextMenu = {
494 setItems: (items) => this.contextMenu_.items = items,
495 };
496
Jason Lin83707c92022-09-20 19:09:41 +1000497 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000498 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000499 // The webgl cursor layer also paints the character under the cursor with
500 // this `cursorAccent` color. We use a completely transparent color here
501 // to effectively disable that.
502 cursorAccent: 'rgba(0, 0, 0, 0)',
503 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000504 selectionBackground: 'rgba(174, 203, 250, .6)',
505 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000506 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000507 };
508 this.observePrefs_();
Jason Linb8f380a2022-10-25 13:15:56 +1100509 if (!xtermTerminalStringsLoaded) {
510 xtermTerminalStringsLoaded = true;
511 Terminal.strings.promptLabel =
512 hterm.messageManager.get('TERMINAL_INPUT_LABEL');
513 Terminal.strings.tooMuchOutput =
514 hterm.messageManager.get('TERMINAL_TOO_MUCH_OUTPUT_MESSAGE');
515 }
Jason Linca61ffb2022-08-03 19:37:12 +1000516 }
517
Jason Linc7afb672022-10-11 15:54:17 +1100518 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100519 setWindowTitle(title) {
520 document.title = title;
521 }
522
523 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100524 ringBell() {
525 this.bell_.ring();
526 }
527
Jason Lin2649da22022-10-12 10:16:44 +1100528 /** @override */
529 print(str) {
530 this.xtermInternal_.print(str);
531 }
532
533 /** @override */
534 wipeContents() {
535 this.term.clear();
536 }
537
538 /** @override */
539 newLine() {
540 this.xtermInternal_.newLine();
541 }
542
543 /** @override */
544 cursorLeft(number) {
545 this.xtermInternal_.cursorLeft(number ?? 1);
546 }
547
Jason Lind3aacef2022-10-12 19:03:37 +1100548 /** @override */
549 setAccessibilityEnabled(enabled) {
Jason Linc0f14fe2022-10-25 15:31:29 +1100550 if (enabled === this.a11yEnabled_) {
551 return;
552 }
553 this.a11yEnabled_ = enabled;
554
Jason Lind3aacef2022-10-12 19:03:37 +1100555 this.a11yButtons_.setEnabled(enabled);
556 this.htermA11yReader_.setAccessibilityEnabled(enabled);
Jason Linc0f14fe2022-10-25 15:31:29 +1100557
558 if (enabled) {
559 this.xtermInternal_.enableA11y(this.a11yButtons_.pageUpButton,
560 this.a11yButtons_.pageDownButton);
561 } else {
562 this.xtermInternal_.disableA11y();
563 }
Jason Lind3aacef2022-10-12 19:03:37 +1100564 }
565
Jason Linee0c1f72022-10-18 17:17:26 +1100566 hasBackgroundImage() {
567 return !!this.container_.style.backgroundImage;
568 }
569
570 /** @override */
571 setBackgroundImage(image) {
572 this.container_.style.backgroundImage = image || '';
573 this.updateBackgroundColor_(this.prefs_.getString('background-color'));
574 }
575
Jason Linca61ffb2022-08-03 19:37:12 +1000576 /**
577 * Install stubs for stuff that we haven't implemented yet so that the code
578 * still runs.
579 */
580 installUnimplementedStubs_() {
581 this.keyboard = {
582 keyMap: {
583 keyDefs: [],
584 },
585 bindings: {
586 clear: () => {},
587 addBinding: () => {},
588 addBindings: () => {},
589 OsDefaults: {},
590 },
591 };
592 this.keyboard.keyMap.keyDefs[78] = {};
593
594 const methodNames = [
Joel Hockeyb89a9782022-10-16 22:00:12 -0700595 'eraseLine',
Joel Hockeyb89a9782022-10-16 22:00:12 -0700596 'setCursorColumn',
Jason Linca61ffb2022-08-03 19:37:12 +1000597 'setCursorPosition',
598 'setCursorVisible',
Joel Hockeyd78374f2022-11-02 23:05:53 -0700599 'uninstallKeyboard',
Jason Linca61ffb2022-08-03 19:37:12 +1000600 ];
601
602 for (const name of methodNames) {
603 this[name] = () => console.warn(`${name}() is not implemented`);
604 }
605
Jason Lin21d854f2022-08-22 14:49:59 +1000606 this.vt = {
607 resetParseState: () => {
608 console.warn('.vt.resetParseState() is not implemented');
609 },
610 };
Jason Linca61ffb2022-08-03 19:37:12 +1000611 }
612
Jason Line9231bc2022-09-01 13:54:02 +1000613 installEscapeSequenceHandlers_() {
614 // OSC 52 for copy.
615 this.term.parser.registerOscHandler(52, (args) => {
616 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
617 // parameter is used to select which of the X clipboards to address. Since
618 // we're not integrating with X, we treat them all the same.
619 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
620 if (!parsedArgs) {
621 return true;
622 }
623
624 let data;
625 try {
626 data = window.atob(parsedArgs[1]);
627 } catch (e) {
628 // If the user sent us invalid base64 content, silently ignore it.
629 return true;
630 }
631 const decoder = new TextDecoder();
632 const bytes = lib.codec.stringToCodeUnitArray(data);
633 this.copyString_(decoder.decode(bytes));
634
635 return true;
636 });
Jason Lin2649da22022-10-12 10:16:44 +1100637
638 this.xtermInternal_.installTmuxControlModeHandler(
639 (data) => this.onTmuxControlModeLine(data));
640 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000641 }
642
Jason Linca61ffb2022-08-03 19:37:12 +1000643 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000644 * Write data to the terminal.
645 *
646 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
647 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100648 * @param {function()=} callback Optional callback that fires when the data
649 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000650 */
Jason Lin2649da22022-10-12 10:16:44 +1100651 write(data, callback) {
652 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000653 }
654
655 /**
656 * Like `this.write()` but also write a line break.
657 *
658 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100659 * @param {function()=} callback Optional callback that fires when the data
660 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000661 */
Jason Lin2649da22022-10-12 10:16:44 +1100662 writeln(data, callback) {
663 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000664 }
665
Jason Linca61ffb2022-08-03 19:37:12 +1000666 get screenSize() {
667 return new hterm.Size(this.term.cols, this.term.rows);
668 }
669
670 /**
671 * Don't need to do anything.
672 *
673 * @override
674 */
675 installKeyboard() {}
676
677 /**
678 * @override
679 */
680 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000681 this.container_ = elem;
Jason Linee0c1f72022-10-18 17:17:26 +1100682 elem.style.backgroundSize = '100% 100%';
683
Jason Lin8de3d282022-09-01 21:29:05 +1000684 (async () => {
685 await new Promise((resolve) => this.prefs_.readStorage(resolve));
686 // This will trigger all the observers to set the terminal options before
687 // we call `this.term.open()`.
688 this.prefs_.notifyAll();
689
Jason Linc2504ae2022-09-02 13:03:31 +1000690 const screenPaddingSize = /** @type {number} */(
691 this.prefs_.get('screen-padding-size'));
692 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
693
Jason Linee0c1f72022-10-18 17:17:26 +1100694 this.setBackgroundImage(
695 this.backgroundImageWatcher_.getBackgroundImage());
696 this.backgroundImageWatcher_.watch();
697
Jason Lin8de3d282022-09-01 21:29:05 +1000698 this.inited_ = true;
699 this.term.open(elem);
700
Jason Lin8de3d282022-09-01 21:29:05 +1000701 if (this.enableWebGL_) {
Jason Linee0c1f72022-10-18 17:17:26 +1100702 this.reloadWebglAddon_();
Jason Lin8de3d282022-09-01 21:29:05 +1000703 }
704 this.term.focus();
705 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lind3aacef2022-10-12 19:03:37 +1100706 this.htermA11yReader_ = new hterm.AccessibilityReader(elem);
707 this.notificationCenter_ = new hterm.NotificationCenter(document.body,
708 this.htermA11yReader_);
Jason Lin8de3d282022-09-01 21:29:05 +1000709
Jason Lin82ba86c2022-11-09 12:12:27 +1100710 elem.appendChild(this.contextMenu_);
711
712 // Block the default context menu from popping up.
Emil Mikulic2a194d02022-09-29 14:30:59 +1000713 elem.addEventListener('contextmenu', (e) => e.preventDefault());
714
715 // Add a handler for pasting with the mouse.
716 elem.addEventListener('mousedown', async (e) => {
Jason Lin82ba86c2022-11-09 12:12:27 +1100717 this.contextMenu_.hide();
Emil Mikulic2a194d02022-09-29 14:30:59 +1000718 if (this.term.modes.mouseTrackingMode !== 'none') {
719 // xterm.js is in mouse mode and will handle the event.
720 return;
721 }
722 const MIDDLE = 1;
723 const RIGHT = 2;
Jason Lin82ba86c2022-11-09 12:12:27 +1100724
725 if (e.button === RIGHT && e.ctrlKey) {
726 this.contextMenu_.show({x: e.clientX, y: e.clientY});
727 return;
728 }
729
Emil Mikulic2a194d02022-09-29 14:30:59 +1000730 if (e.button === MIDDLE || (e.button === RIGHT &&
731 this.prefs_.getBoolean('mouse-right-click-paste'))) {
732 // Paste.
733 if (navigator.clipboard && navigator.clipboard.readText) {
734 const text = await navigator.clipboard.readText();
735 this.term.paste(text);
736 }
737 }
738 });
739
Jason Lin2649da22022-10-12 10:16:44 +1100740 await this.scheduleFit_();
Jason Linc0f14fe2022-10-25 15:31:29 +1100741 this.a11yButtons_ = new A11yButtons(this.term, this.htermA11yReader_);
Jason Lind3aacef2022-10-12 19:03:37 +1100742
Jason Lin8de3d282022-09-01 21:29:05 +1000743 this.onTerminalReady();
744 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000745 }
746
747 /** @override */
748 showOverlay(msg, timeout = 1500) {
Jason Lin34a45322022-10-12 19:10:52 +1100749 this.notificationCenter_?.show(msg, {timeout});
Jason Lin21d854f2022-08-22 14:49:59 +1000750 }
751
752 /** @override */
753 hideOverlay() {
Jason Lin34a45322022-10-12 19:10:52 +1100754 this.notificationCenter_?.hide();
Jason Linca61ffb2022-08-03 19:37:12 +1000755 }
756
757 /** @override */
758 getPrefs() {
759 return this.prefs_;
760 }
761
762 /** @override */
763 getDocument() {
764 return window.document;
765 }
766
Jason Lin21d854f2022-08-22 14:49:59 +1000767 /** @override */
768 reset() {
769 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000770 }
771
772 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000773 setProfile(profileId, callback = undefined) {
774 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000775 }
776
Jason Lin21d854f2022-08-22 14:49:59 +1000777 /** @override */
778 interpret(string) {
779 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000780 }
781
Jason Lin21d854f2022-08-22 14:49:59 +1000782 /** @override */
783 focus() {
784 this.term.focus();
785 }
Jason Linca61ffb2022-08-03 19:37:12 +1000786
787 /** @override */
788 onOpenOptionsPage() {}
789
790 /** @override */
791 onTerminalReady() {}
792
Jason Lind04bab32022-08-22 14:48:39 +1000793 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000794 // This is for this.notificationCenter_.
795 const setHtermCSSVariable = (name, value) => {
796 document.body.style.setProperty(`--hterm-${name}`, value);
797 };
798
799 const setHtermColorCSSVariable = (name, color) => {
800 const css = lib.notNull(lib.colors.normalizeCSS(color));
801 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
802 setHtermCSSVariable(name, rgb);
803 };
804
805 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000806 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000807 setHtermCSSVariable('font-size', `${v}px`);
808 });
809
Jason Linda56aa92022-09-02 13:01:49 +1000810 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000811 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000812 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100813 this.bell_.playAudio = !!v;
814 },
815 'desktop-notification-bell': (v) => {
816 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000817 },
Jason Lind04bab32022-08-22 14:48:39 +1000818 'background-color': (v) => {
Jason Linee0c1f72022-10-18 17:17:26 +1100819 this.updateBackgroundColor_(v);
Jason Lin21d854f2022-08-22 14:49:59 +1000820 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000821 },
Jason Lind04bab32022-08-22 14:48:39 +1000822 'color-palette-overrides': (v) => {
823 if (!(v instanceof Array)) {
824 // For terminal, we always expect this to be an array.
825 console.warn('unexpected color palette: ', v);
826 return;
827 }
828 const colors = {};
829 for (let i = 0; i < v.length; ++i) {
830 colors[ANSI_COLOR_NAMES[i]] = v[i];
831 }
832 this.updateTheme_(colors);
833 },
Jason Linda56aa92022-09-02 13:01:49 +1000834 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
835 'cursor-color': (v) => this.updateTheme_({cursor: v}),
836 'cursor-shape': (v) => {
837 let shape;
838 if (v === 'BEAM') {
839 shape = 'bar';
840 } else {
841 shape = v.toLowerCase();
842 }
843 this.updateOption_('cursorStyle', shape, false);
844 },
845 'font-family': (v) => this.updateFont_(v),
846 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000847 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000848 setHtermColorCSSVariable('foreground-color', v);
849 },
Jason Linc48f7432022-10-13 17:28:30 +1100850 'line-height': (v) => this.updateOption_('lineHeight', v, true),
Jason Lin446f3d92022-10-13 17:34:21 +1100851 'scroll-on-output': (v) => {
852 if (!v) {
853 this.scrollOnOutputListener_?.dispose();
854 this.scrollOnOutputListener_ = null;
855 return;
856 }
857 if (!this.scrollOnOutputListener_) {
858 this.scrollOnOutputListener_ = this.term.onWriteParsed(
859 () => this.term.scrollToBottom());
860 }
861 },
Jason Lina63d8ba2022-11-02 17:42:38 +1100862 'user-css': (v) => {
863 if (this.userCSSElement_) {
864 this.userCSSElement_.remove();
865 }
866 if (v) {
867 this.userCSSElement_ = document.createElement('link');
868 this.userCSSElement_.setAttribute('rel', 'stylesheet');
869 this.userCSSElement_.setAttribute('href', v);
870 document.head.appendChild(this.userCSSElement_);
871 }
872 },
873 'user-css-text': (v) => {
874 if (!this.userCSSTextElement_) {
875 this.userCSSTextElement_ = document.createElement('style');
876 document.head.appendChild(this.userCSSTextElement_);
877 }
878 this.userCSSTextElement_.textContent = v;
879 },
Jason Lind04bab32022-08-22 14:48:39 +1000880 });
Jason Lin5690e752022-08-30 15:36:45 +1000881
882 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
883 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
884 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
885 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
886 }
Jason Lind04bab32022-08-22 14:48:39 +1000887 }
888
889 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000890 * Fit the terminal to the containing HTML element.
891 */
892 fit_() {
893 if (!this.inited_) {
894 return;
895 }
896
897 const screenPaddingSize = /** @type {number} */(
898 this.prefs_.get('screen-padding-size'));
899
900 const calc = (size, cellSize) => {
901 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
902 };
903
Jason Lin2649da22022-10-12 10:16:44 +1100904 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
905 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
906 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000907 if (cols >= 0 && rows >= 0) {
908 this.term.resize(cols, rows);
909 }
910 }
911
Jason Linee0c1f72022-10-18 17:17:26 +1100912 reloadWebglAddon_() {
913 if (this.webglAddon_) {
914 this.webglAddon_.dispose();
915 }
916 this.webglAddon_ = new WebglAddon();
917 this.term.loadAddon(this.webglAddon_);
918 }
919
920 /**
921 * Update the background color. This will also adjust the transparency based
922 * on whether there is a background image.
923 *
924 * @param {string} color
925 */
926 updateBackgroundColor_(color) {
927 const hasBackgroundImage = this.hasBackgroundImage();
928
929 // We only set allowTransparency when it is necessary becuase 1) xterm.js
930 // documentation states that allowTransparency can affect performance; 2) I
931 // find that the rendering is better with allowTransparency being false.
932 // This could be a bug with xterm.js.
933 if (!!this.term.options.allowTransparency !== hasBackgroundImage) {
934 this.term.options.allowTransparency = hasBackgroundImage;
935 if (this.enableWebGL_ && this.inited_) {
936 // Setting allowTransparency in the middle messes up webgl rendering,
937 // so we need to reload it here.
938 this.reloadWebglAddon_();
939 }
940 }
941
942 if (this.hasBackgroundImage()) {
943 const css = lib.notNull(lib.colors.normalizeCSS(color));
944 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
945 // Note that we still want to set the RGB part correctly even though it is
946 // completely transparent. This is because the background color without
947 // the alpha channel is used in reverse video mode.
948 color = `rgba(${rgb}, 0)`;
949 }
950
951 this.updateTheme_({background: color});
952 }
953
Jason Linc2504ae2022-09-02 13:03:31 +1000954 /**
Jason Lind04bab32022-08-22 14:48:39 +1000955 * @param {!Object} theme
956 */
957 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000958 const updateTheme = (target) => {
959 for (const [key, value] of Object.entries(theme)) {
960 target[key] = lib.colors.normalizeCSS(value);
961 }
962 };
963
964 // Must use a new theme object to trigger re-render if we have initialized.
965 if (this.inited_) {
966 const newTheme = {...this.term.options.theme};
967 updateTheme(newTheme);
968 this.term.options.theme = newTheme;
969 return;
Jason Lind04bab32022-08-22 14:48:39 +1000970 }
Jason Lin8de3d282022-09-01 21:29:05 +1000971
972 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000973 }
974
975 /**
Jason Linda56aa92022-09-02 13:01:49 +1000976 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
977 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000978 *
979 * @param {string} key
980 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000981 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000982 */
Jason Linda56aa92022-09-02 13:01:49 +1000983 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000984 // TODO: xterm supports updating multiple options at the same time. We
985 // should probably do that.
986 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000987 if (scheduleFit) {
988 this.scheduleFit_();
989 }
Jason Lind04bab32022-08-22 14:48:39 +1000990 }
Jason Linabad7562022-08-22 14:49:05 +1000991
992 /**
993 * Called when there is a "fontloadingdone" event. We need this because
994 * `FontManager.loadFont()` does not guarantee loading all the font files.
995 */
996 async onFontLoadingDone_() {
997 // If there is a pending font, the font is going to be refresh soon, so we
998 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000999 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +10001000 this.scheduleRefreshFont_();
1001 }
1002 }
1003
Jason Lin5690e752022-08-30 15:36:45 +10001004 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +10001005 this.copyString_(this.term.getSelection());
1006 }
1007
1008 /** @param {string} data */
1009 copyString_(data) {
1010 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +10001011 return;
1012 }
Jason Line9231bc2022-09-01 13:54:02 +10001013 navigator.clipboard?.writeText(data);
Jason Lin83ef5ba2022-10-13 17:40:30 +11001014
1015 if (this.prefs_.get('enable-clipboard-notice')) {
1016 if (!this.copyNotice_) {
1017 this.copyNotice_ = document.createElement('terminal-copy-notice');
1018 }
1019 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500),
1020 200);
Jason Lin6a402a72022-08-25 16:07:02 +10001021 }
Jason Lin6a402a72022-08-25 16:07:02 +10001022 }
1023
Jason Linabad7562022-08-22 14:49:05 +10001024 /**
1025 * Refresh xterm rendering for a font related event.
1026 */
1027 refreshFont_() {
1028 // We have to set the fontFamily option to a different string to trigger the
1029 // re-rendering. Appending a space at the end seems to be the easiest
1030 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
1031 // us.
1032 //
1033 // TODO: Report a bug to xterm.js and ask for exposing a public function for
1034 // the refresh so that we don't need to do this hack.
1035 this.term.options.fontFamily += ' ';
1036 }
1037
1038 /**
1039 * Update a font.
1040 *
1041 * @param {string} cssFontFamily
1042 */
1043 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +10001044 this.pendingFont_ = cssFontFamily;
1045 await this.fontManager_.loadFont(cssFontFamily);
1046 // Sleep a bit to wait for flushing fontloadingdone events. This is not
1047 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
1048 // to refresh font unnecessarily in some cases.
1049 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +10001050
Jason Lin6a402a72022-08-25 16:07:02 +10001051 if (this.pendingFont_ !== cssFontFamily) {
1052 // `updateFont_()` probably is called again. Abort what we are doing.
1053 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
1054 ` (expecting ${cssFontFamily})`);
1055 return;
1056 }
Jason Linabad7562022-08-22 14:49:05 +10001057
Jason Lin6a402a72022-08-25 16:07:02 +10001058 if (this.term.options.fontFamily !== cssFontFamily) {
1059 this.term.options.fontFamily = cssFontFamily;
1060 } else {
1061 // If the font is already the same, refresh font just to be safe.
1062 this.refreshFont_();
1063 }
1064 this.pendingFont_ = null;
1065 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +10001066 }
Jason Lin5690e752022-08-30 15:36:45 +10001067
1068 /**
1069 * @param {!KeyboardEvent} ev
1070 * @return {boolean} Return false if xterm.js should not handle the key event.
1071 */
1072 customKeyEventHandler_(ev) {
1073 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
1074 (ev.altKey ? Modifier.Alt : 0) |
1075 (ev.ctrlKey ? Modifier.Ctrl : 0) |
1076 (ev.metaKey ? Modifier.Meta : 0);
1077 const handler = this.keyDownHandlers_.get(
1078 encodeKeyCombo(modifiers, ev.keyCode));
1079 if (handler) {
1080 if (ev.type === 'keydown') {
1081 handler(ev);
1082 }
1083 return false;
1084 }
1085
1086 return true;
1087 }
1088
1089 /**
1090 * A keydown handler for zoom-related keys.
1091 *
1092 * @param {!KeyboardEvent} ev
1093 */
1094 zoomKeyDownHandler_(ev) {
1095 ev.preventDefault();
1096
1097 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
1098 // The only one with a control code.
1099 if (ev.keyCode === keyCodes.MINUS) {
1100 this.io.onVTKeystroke('\x1f');
1101 }
1102 return;
1103 }
1104
1105 let newFontSize;
1106 switch (ev.keyCode) {
1107 case keyCodes.ZERO:
1108 newFontSize = this.prefs_.get('font-size');
1109 break;
1110 case keyCodes.MINUS:
1111 newFontSize = this.term.options.fontSize - 1;
1112 break;
1113 default:
1114 newFontSize = this.term.options.fontSize + 1;
1115 break;
1116 }
1117
Jason Linda56aa92022-09-02 13:01:49 +10001118 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +10001119 }
1120
1121 /** @param {!KeyboardEvent} ev */
1122 ctrlCKeyDownHandler_(ev) {
1123 ev.preventDefault();
1124 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
1125 this.term.hasSelection()) {
1126 this.copySelection_();
1127 return;
1128 }
1129
1130 this.io.onVTKeystroke('\x03');
1131 }
1132
1133 /** @param {!KeyboardEvent} ev */
1134 ctrlVKeyDownHandler_(ev) {
1135 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
1136 // Don't do anything and let the browser handles the key.
1137 return;
1138 }
1139
1140 ev.preventDefault();
1141 this.io.onVTKeystroke('\x16');
1142 }
1143
1144 resetKeyDownHandlers_() {
1145 this.keyDownHandlers_.clear();
1146
1147 /**
1148 * Don't do anything and let the browser handles the key.
1149 *
1150 * @param {!KeyboardEvent} ev
1151 */
1152 const noop = (ev) => {};
1153
1154 /**
1155 * @param {number} modifiers
1156 * @param {number} keyCode
1157 * @param {function(!KeyboardEvent)} func
1158 */
1159 const set = (modifiers, keyCode, func) => {
1160 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
1161 func);
1162 };
1163
1164 /**
1165 * @param {number} modifiers
1166 * @param {number} keyCode
1167 * @param {function(!KeyboardEvent)} func
1168 */
1169 const setWithShiftVersion = (modifiers, keyCode, func) => {
1170 set(modifiers, keyCode, func);
1171 set(modifiers | Modifier.Shift, keyCode, func);
1172 };
1173
Jason Lin5690e752022-08-30 15:36:45 +10001174 // Ctrl+/
1175 set(Modifier.Ctrl, 191, (ev) => {
1176 ev.preventDefault();
1177 this.io.onVTKeystroke(ctl('_'));
1178 });
1179
1180 // Settings page.
1181 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
1182 ev.preventDefault();
1183 chrome.terminalPrivate.openOptionsPage(() => {});
1184 });
1185
1186 if (this.prefs_.get('keybindings-os-defaults')) {
1187 for (const binding of OS_DEFAULT_BINDINGS) {
1188 this.keyDownHandlers_.set(binding, noop);
1189 }
1190 }
1191
1192 /** @param {!KeyboardEvent} ev */
1193 const newWindow = (ev) => {
1194 ev.preventDefault();
1195 chrome.terminalPrivate.openWindow();
1196 };
1197 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
1198 if (this.prefs_.get('pass-ctrl-n')) {
1199 set(Modifier.Ctrl, keyCodes.N, newWindow);
1200 }
1201
1202 if (this.prefs_.get('pass-ctrl-t')) {
1203 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
1204 }
1205
1206 if (this.prefs_.get('pass-ctrl-w')) {
1207 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
1208 }
1209
1210 if (this.prefs_.get('pass-ctrl-tab')) {
1211 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
1212 }
1213
1214 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
1215
1216 /**
1217 * Set a handler for the key combo ctrl+<number>.
1218 *
1219 * @param {number} number 1 to 9
1220 * @param {string} controlCode The control code to send if we don't want to
1221 * let the browser to handle it.
1222 */
1223 const setCtrlNumberHandler = (number, controlCode) => {
1224 let func = noop;
1225 if (!passCtrlNumber) {
1226 func = (ev) => {
1227 ev.preventDefault();
1228 this.io.onVTKeystroke(controlCode);
1229 };
1230 }
1231 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
1232 };
1233
1234 setCtrlNumberHandler(1, '1');
1235 setCtrlNumberHandler(2, ctl('@'));
1236 setCtrlNumberHandler(3, ctl('['));
1237 setCtrlNumberHandler(4, ctl('\\'));
1238 setCtrlNumberHandler(5, ctl(']'));
1239 setCtrlNumberHandler(6, ctl('^'));
1240 setCtrlNumberHandler(7, ctl('_'));
1241 setCtrlNumberHandler(8, '\x7f');
1242 setCtrlNumberHandler(9, '9');
1243
1244 if (this.prefs_.get('pass-alt-number')) {
1245 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
1246 set(Modifier.Alt, keyCode, noop);
1247 }
1248 }
1249
1250 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
1251 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
1252 }
1253
1254 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
1255 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
1256 }
Jason Linee0c1f72022-10-18 17:17:26 +11001257
1258 handleOnTerminalReady() {}
Jason Linca61ffb2022-08-03 19:37:12 +10001259}
1260
Jason Lind66e6bf2022-08-22 14:47:10 +10001261class HtermTerminal extends hterm.Terminal {
1262 /** @override */
1263 decorate(div) {
1264 super.decorate(div);
1265
Jason Linc48f7432022-10-13 17:28:30 +11001266 definePrefs(this.getPrefs());
Jason Linee0c1f72022-10-18 17:17:26 +11001267 }
Jason Linc48f7432022-10-13 17:28:30 +11001268
Jason Linee0c1f72022-10-18 17:17:26 +11001269 /**
1270 * This needs to be called in the `onTerminalReady()` callback. This is
1271 * awkward, but it is temporary since we will drop support for hterm at some
1272 * point.
1273 */
1274 handleOnTerminalReady() {
Jason Lind66e6bf2022-08-22 14:47:10 +10001275 const fontManager = new FontManager(this.getDocument());
1276 fontManager.loadPowerlineCSS().then(() => {
1277 const prefs = this.getPrefs();
1278 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
1279 prefs.addObserver(
1280 'font-family',
1281 (v) => fontManager.loadFont(/** @type {string} */(v)));
1282 });
Jason Linee0c1f72022-10-18 17:17:26 +11001283
1284 const backgroundImageWatcher = new BackgroundImageWatcher(this.getPrefs(),
1285 (image) => this.setBackgroundImage(image));
1286 this.setBackgroundImage(backgroundImageWatcher.getBackgroundImage());
1287 backgroundImageWatcher.watch();
Jason Lind66e6bf2022-08-22 14:47:10 +10001288 }
Jason Lin2649da22022-10-12 10:16:44 +11001289
1290 /**
1291 * Write data to the terminal.
1292 *
1293 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
1294 * UTF-8 data
1295 * @param {function()=} callback Optional callback that fires when the data
1296 * was processed by the parser.
1297 */
1298 write(data, callback) {
1299 if (typeof data === 'string') {
1300 this.io.print(data);
1301 } else {
1302 this.io.writeUTF8(data);
1303 }
1304 // Hterm processes the data synchronously, so we can call the callback
1305 // immediately.
1306 if (callback) {
1307 setTimeout(callback);
1308 }
1309 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001310}
1311
Jason Linca61ffb2022-08-03 19:37:12 +10001312/**
1313 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1314 * preference value.
1315 *
1316 * @param {{
1317 * storage: !lib.Storage,
1318 * profileId: string,
1319 * }} args
1320 * @return {!Promise<!hterm.Terminal>}
1321 */
1322export async function createEmulator({storage, profileId}) {
1323 let config = TERMINAL_EMULATORS.get('hterm');
1324
1325 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001326 // TODO: remove the url param logic. This is temporary to make manual
1327 // testing a bit easier, which is also why this is not in
1328 // './js/terminal_info.js'.
Jason Line10d6c42022-11-11 16:04:32 +11001329 const emulator = ORIGINAL_URL.searchParams.get('emulator');
Jason Linca61ffb2022-08-03 19:37:12 +10001330 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001331 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001332 TERMINAL_EMULATORS.values().next().value;
1333 console.log('Terminal emulator config: ', config);
1334 }
1335
1336 switch (config.lib) {
1337 case 'xterm.js':
1338 {
1339 const terminal = new XtermTerminal({
1340 storage,
1341 profileId,
1342 enableWebGL: config.webgl,
1343 });
Jason Linca61ffb2022-08-03 19:37:12 +10001344 return terminal;
1345 }
1346 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001347 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001348 default:
1349 throw new Error('incorrect emulator config');
1350 }
1351}
1352
Jason Lin6a402a72022-08-25 16:07:02 +10001353class TerminalCopyNotice extends LitElement {
1354 /** @override */
1355 static get styles() {
1356 return css`
1357 :host {
1358 display: block;
1359 text-align: center;
1360 }
1361
1362 svg {
1363 fill: currentColor;
1364 }
1365 `;
1366 }
1367
1368 /** @override */
Jason Lind3aacef2022-10-12 19:03:37 +11001369 connectedCallback() {
1370 super.connectedCallback();
1371 if (!this.childNodes.length) {
1372 // This is not visible since we use shadow dom. But this will allow the
1373 // hterm.NotificationCenter to announce the the copy text.
1374 this.append(hterm.messageManager.get('HTERM_NOTIFY_COPY'));
1375 }
1376 }
1377
1378 /** @override */
Jason Lin6a402a72022-08-25 16:07:02 +10001379 render() {
1380 return html`
1381 ${ICON_COPY}
1382 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1383 `;
1384 }
1385}
1386
1387customElements.define('terminal-copy-notice', TerminalCopyNotice);