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