blob: d25a2af8399ef65ec06c9184c2e79dde56146fc5 [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
Jason Lin6a402a72022-08-25 16:07:02 +100014import {LitElement, css, html} from './lit.js';
Jason Lin21d854f2022-08-22 14:49:59 +100015import {FontManager, ORIGINAL_URL, TERMINAL_EMULATORS, delayedScheduler,
16 fontManager, getOSInfo, sleep} from './terminal_common.js';
Jason Lin6a402a72022-08-25 16:07:02 +100017import {ICON_COPY} from './terminal_icons.js';
Jason Lin83707c92022-09-20 19:09:41 +100018import {TerminalTooltip} from './terminal_tooltip.js';
Jason Linc2504ae2022-09-02 13:03:31 +100019import {Terminal, Unicode11Addon, WebLinksAddon, WebglAddon}
Jason Lin4de4f382022-09-01 14:10:18 +100020 from './xterm.js';
Jason Lin2649da22022-10-12 10:16:44 +110021import {XtermInternal} from './terminal_xterm_internal.js';
Jason Linca61ffb2022-08-03 19:37:12 +100022
Jason Lin5690e752022-08-30 15:36:45 +100023
24/** @enum {number} */
25export const Modifier = {
26 Shift: 1 << 0,
27 Alt: 1 << 1,
28 Ctrl: 1 << 2,
29 Meta: 1 << 3,
30};
31
32// This is just a static map from key names to key codes. It helps make the code
33// a bit more readable.
34const keyCodes = hterm.Parser.identifiers.keyCodes;
35
36/**
37 * Encode a key combo (i.e. modifiers + a normal key) to an unique number.
38 *
39 * @param {number} modifiers
40 * @param {number} keyCode
41 * @return {number}
42 */
43export function encodeKeyCombo(modifiers, keyCode) {
44 return keyCode << 4 | modifiers;
45}
46
47const OS_DEFAULT_BINDINGS = [
48 // Submit feedback.
49 encodeKeyCombo(Modifier.Alt | Modifier.Shift, keyCodes.I),
50 // Toggle chromevox.
51 encodeKeyCombo(Modifier.Ctrl | Modifier.Alt, keyCodes.Z),
52 // Switch input method.
53 encodeKeyCombo(Modifier.Ctrl, keyCodes.SPACE),
54
55 // Dock window left/right.
56 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_LEFT),
57 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_RIGHT),
58
59 // Maximize/minimize window.
60 encodeKeyCombo(Modifier.Alt, keyCodes.EQUAL),
61 encodeKeyCombo(Modifier.Alt, keyCodes.MINUS),
62];
63
64
Jason Linca61ffb2022-08-03 19:37:12 +100065const ANSI_COLOR_NAMES = [
66 'black',
67 'red',
68 'green',
69 'yellow',
70 'blue',
71 'magenta',
72 'cyan',
73 'white',
74 'brightBlack',
75 'brightRed',
76 'brightGreen',
77 'brightYellow',
78 'brightBlue',
79 'brightMagenta',
80 'brightCyan',
81 'brightWhite',
82];
83
Jason Linca61ffb2022-08-03 19:37:12 +100084/**
Jason Linabad7562022-08-22 14:49:05 +100085 * @typedef {{
86 * term: !Terminal,
87 * fontManager: !FontManager,
Jason Lin2649da22022-10-12 10:16:44 +110088 * xtermInternal: !XtermInternal,
Jason Linabad7562022-08-22 14:49:05 +100089 * }}
90 */
91export let XtermTerminalTestParams;
92
93/**
Jason Lin5690e752022-08-30 15:36:45 +100094 * Compute a control character for a given character.
95 *
96 * @param {string} ch
97 * @return {string}
98 */
99function ctl(ch) {
100 return String.fromCharCode(ch.charCodeAt(0) - 64);
101}
102
103/**
Jason Lin21d854f2022-08-22 14:49:59 +1000104 * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO
105 * because it always convert utf8 data to strings, which is not necessary for
106 * xterm.
107 */
108class XtermTerminalIO extends hterm.Terminal.IO {
109 /** @override */
110 writeUTF8(buffer) {
111 this.terminal_.write(new Uint8Array(buffer));
112 }
113
114 /** @override */
115 writelnUTF8(buffer) {
116 this.terminal_.writeln(new Uint8Array(buffer));
117 }
118
119 /** @override */
120 print(string) {
121 this.terminal_.write(string);
122 }
123
124 /** @override */
125 writeUTF16(string) {
126 this.print(string);
127 }
128
129 /** @override */
130 println(string) {
131 this.terminal_.writeln(string);
132 }
133
134 /** @override */
135 writelnUTF16(string) {
136 this.println(string);
137 }
138}
139
140/**
Jason Lin83707c92022-09-20 19:09:41 +1000141 * A custom link handler that:
142 *
143 * - Shows a tooltip with the url on a OSC 8 link. This is following what hterm
144 * is doing. Also, showing the tooltip is better for the security of the user
145 * because the link can have arbitrary text.
146 * - Uses our own way to open the window.
147 */
148class LinkHandler {
149 /**
150 * @param {!Terminal} term
151 */
152 constructor(term) {
153 this.term_ = term;
154 /** @type {?TerminalTooltip} */
155 this.tooltip_ = null;
156 }
157
158 /**
159 * @return {!TerminalTooltip}
160 */
161 getTooltip_() {
162 if (!this.tooltip_) {
163 this.tooltip_ = /** @type {!TerminalTooltip} */(
164 document.createElement('terminal-tooltip'));
165 this.tooltip_.classList.add('xterm-hover');
166 lib.notNull(this.term_.element).appendChild(this.tooltip_);
167 }
168 return this.tooltip_;
169 }
170
171 /**
172 * @param {!MouseEvent} ev
173 * @param {string} url
174 * @param {!Object} range
175 */
176 activate(ev, url, range) {
177 lib.f.openWindow(url, '_blank');
178 }
179
180 /**
181 * @param {!MouseEvent} ev
182 * @param {string} url
183 * @param {!Object} range
184 */
185 hover(ev, url, range) {
186 this.getTooltip_().show(url, {x: ev.clientX, y: ev.clientY});
187 }
188
189 /**
190 * @param {!MouseEvent} ev
191 * @param {string} url
192 * @param {!Object} range
193 */
194 leave(ev, url, range) {
195 this.getTooltip_().hide();
196 }
197}
198
Jason Linc7afb672022-10-11 15:54:17 +1100199class Bell {
200 constructor() {
201 this.showNotification = false;
202
203 /** @type {?Audio} */
204 this.audio_ = null;
205 /** @type {?Notification} */
206 this.notification_ = null;
207 this.coolDownUntil_ = 0;
208 }
209
210 /**
211 * Set whether a bell audio should be played.
212 *
213 * @param {boolean} value
214 */
215 set playAudio(value) {
216 this.audio_ = value ?
217 new Audio(lib.resource.getDataUrl('hterm/audio/bell')) : null;
218 }
219
220 ring() {
221 const now = Date.now();
222 if (now < this.coolDownUntil_) {
223 return;
224 }
225 this.coolDownUntil_ = now + 500;
226
227 this.audio_?.play();
228 if (this.showNotification && !document.hasFocus() && !this.notification_) {
229 this.notification_ = new Notification(
230 `\u266A ${document.title} \u266A`,
231 {icon: lib.resource.getDataUrl('hterm/images/icon-96')});
232 // Close the notification after a timeout. Note that this is different
233 // from hterm's behavior, but I think it makes more sense to do so.
234 setTimeout(() => {
235 this.notification_.close();
236 this.notification_ = null;
237 }, 5000);
238 }
239 }
240}
241
Jason Lin83707c92022-09-20 19:09:41 +1000242/**
Jason Linca61ffb2022-08-03 19:37:12 +1000243 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
244 * so that it can be used in existing code.
245 *
Jason Linca61ffb2022-08-03 19:37:12 +1000246 * @extends {hterm.Terminal}
247 * @unrestricted
248 */
Jason Linabad7562022-08-22 14:49:05 +1000249export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000250 /**
251 * @param {{
252 * storage: !lib.Storage,
253 * profileId: string,
254 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000255 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000256 * }} args
257 */
Jason Linabad7562022-08-22 14:49:05 +1000258 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000259 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
260 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
261 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
262
Jason Lin8de3d282022-09-01 21:29:05 +1000263 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000264 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000265 /** @type {!hterm.PreferenceManager} */
266 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
267 this.enableWebGL_ = enableWebGL;
268
Jason Lin5690e752022-08-30 15:36:45 +1000269 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linfc8a3722022-09-07 17:49:18 +1000270 this.term = testParams?.term || new Terminal({allowProposedApi: true});
Jason Lin2649da22022-10-12 10:16:44 +1100271 this.xtermInternal_ = testParams?.xtermInternal ||
272 new XtermInternal(this.term);
Jason Linabad7562022-08-22 14:49:05 +1000273 this.fontManager_ = testParams?.fontManager || fontManager;
Jason Linabad7562022-08-22 14:49:05 +1000274
Jason Linc2504ae2022-09-02 13:03:31 +1000275 /** @type {?Element} */
276 this.container_;
Jason Linc7afb672022-10-11 15:54:17 +1100277 this.bell_ = new Bell();
Jason Linc2504ae2022-09-02 13:03:31 +1000278 this.scheduleFit_ = delayedScheduler(() => this.fit_(),
Jason Linabad7562022-08-22 14:49:05 +1000279 testParams ? 0 : 250);
280
Jason Lin83707c92022-09-20 19:09:41 +1000281 this.term.loadAddon(
282 new WebLinksAddon((e, uri) => lib.f.openWindow(uri, '_blank')));
Jason Lin4de4f382022-09-01 14:10:18 +1000283 this.term.loadAddon(new Unicode11Addon());
284 this.term.unicode.activeVersion = '11';
285
Jason Linabad7562022-08-22 14:49:05 +1000286 this.pendingFont_ = null;
287 this.scheduleRefreshFont_ = delayedScheduler(
288 () => this.refreshFont_(), 100);
289 document.fonts.addEventListener('loadingdone',
290 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000291
292 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000293 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000294
Jason Lin21d854f2022-08-22 14:49:59 +1000295 this.term.onResize(({cols, rows}) => this.io.onTerminalResize(cols, rows));
296 // We could also use `this.io.sendString()` except for the nassh exit
297 // prompt, which only listens to onVTKeystroke().
298 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin80e69132022-09-02 16:31:43 +1000299 this.term.onBinary((data) => this.io.onVTKeystroke(data));
Jason Lin2649da22022-10-12 10:16:44 +1100300 this.term.onTitleChange((title) => this.setWindowTitle(title));
Jason Lin5690e752022-08-30 15:36:45 +1000301 this.term.onSelectionChange(() => this.copySelection_());
Jason Linc7afb672022-10-11 15:54:17 +1100302 this.term.onBell(() => this.ringBell());
Jason Lin5690e752022-08-30 15:36:45 +1000303
304 /**
305 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
306 *
307 * If a key combo is in the map:
308 *
309 * - The handler instead of xterm.js will handle the keydown event.
310 * - Keyup and keypress will be ignored by both us and xterm.js.
311 *
312 * We re-generate this map every time a relevant pref value is changed. This
313 * is ok because pref changes are rare.
314 *
315 * @type {!Map<number, function(!KeyboardEvent)>}
316 */
317 this.keyDownHandlers_ = new Map();
318 this.scheduleResetKeyDownHandlers_ =
319 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
320
321 this.term.attachCustomKeyEventHandler(
322 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000323
Jason Lin21d854f2022-08-22 14:49:59 +1000324 this.io = new XtermTerminalIO(this);
325 this.notificationCenter_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000326
327 this.copyNotice_ = null;
328
Jason Lin83707c92022-09-20 19:09:41 +1000329 this.term.options.linkHandler = new LinkHandler(this.term);
Jason Lin6a402a72022-08-25 16:07:02 +1000330 this.term.options.theme = {
Jason Lin461ca562022-09-07 13:53:08 +1000331 // The webgl cursor layer also paints the character under the cursor with
332 // this `cursorAccent` color. We use a completely transparent color here
333 // to effectively disable that.
334 cursorAccent: 'rgba(0, 0, 0, 0)',
335 customGlyphs: true,
Jason Lin2edc25d2022-09-16 15:06:48 +1000336 selectionBackground: 'rgba(174, 203, 250, .6)',
337 selectionInactiveBackground: 'rgba(218, 220, 224, .6)',
Jason Lin6a402a72022-08-25 16:07:02 +1000338 selectionForeground: 'black',
Jason Lin6a402a72022-08-25 16:07:02 +1000339 };
340 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000341 }
342
Jason Linc7afb672022-10-11 15:54:17 +1100343 /** @override */
Jason Lin2649da22022-10-12 10:16:44 +1100344 setWindowTitle(title) {
345 document.title = title;
346 }
347
348 /** @override */
Jason Linc7afb672022-10-11 15:54:17 +1100349 ringBell() {
350 this.bell_.ring();
351 }
352
Jason Lin2649da22022-10-12 10:16:44 +1100353 /** @override */
354 print(str) {
355 this.xtermInternal_.print(str);
356 }
357
358 /** @override */
359 wipeContents() {
360 this.term.clear();
361 }
362
363 /** @override */
364 newLine() {
365 this.xtermInternal_.newLine();
366 }
367
368 /** @override */
369 cursorLeft(number) {
370 this.xtermInternal_.cursorLeft(number ?? 1);
371 }
372
Jason Linca61ffb2022-08-03 19:37:12 +1000373 /**
374 * Install stubs for stuff that we haven't implemented yet so that the code
375 * still runs.
376 */
377 installUnimplementedStubs_() {
378 this.keyboard = {
379 keyMap: {
380 keyDefs: [],
381 },
382 bindings: {
383 clear: () => {},
384 addBinding: () => {},
385 addBindings: () => {},
386 OsDefaults: {},
387 },
388 };
389 this.keyboard.keyMap.keyDefs[78] = {};
390
391 const methodNames = [
Jason Linca61ffb2022-08-03 19:37:12 +1000392 'setAccessibilityEnabled',
393 'setBackgroundImage',
394 'setCursorPosition',
395 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000396 ];
397
398 for (const name of methodNames) {
399 this[name] = () => console.warn(`${name}() is not implemented`);
400 }
401
402 this.contextMenu = {
403 setItems: () => {
404 console.warn('.contextMenu.setItems() is not implemented');
405 },
406 };
Jason Lin21d854f2022-08-22 14:49:59 +1000407
408 this.vt = {
409 resetParseState: () => {
410 console.warn('.vt.resetParseState() is not implemented');
411 },
412 };
Jason Linca61ffb2022-08-03 19:37:12 +1000413 }
414
Jason Line9231bc2022-09-01 13:54:02 +1000415 installEscapeSequenceHandlers_() {
416 // OSC 52 for copy.
417 this.term.parser.registerOscHandler(52, (args) => {
418 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
419 // parameter is used to select which of the X clipboards to address. Since
420 // we're not integrating with X, we treat them all the same.
421 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
422 if (!parsedArgs) {
423 return true;
424 }
425
426 let data;
427 try {
428 data = window.atob(parsedArgs[1]);
429 } catch (e) {
430 // If the user sent us invalid base64 content, silently ignore it.
431 return true;
432 }
433 const decoder = new TextDecoder();
434 const bytes = lib.codec.stringToCodeUnitArray(data);
435 this.copyString_(decoder.decode(bytes));
436
437 return true;
438 });
Jason Lin2649da22022-10-12 10:16:44 +1100439
440 this.xtermInternal_.installTmuxControlModeHandler(
441 (data) => this.onTmuxControlModeLine(data));
442 this.xtermInternal_.installEscKHandler();
Jason Line9231bc2022-09-01 13:54:02 +1000443 }
444
Jason Linca61ffb2022-08-03 19:37:12 +1000445 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000446 * Write data to the terminal.
447 *
448 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
449 * UTF-8 data
Jason Lin2649da22022-10-12 10:16:44 +1100450 * @param {function()=} callback Optional callback that fires when the data
451 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000452 */
Jason Lin2649da22022-10-12 10:16:44 +1100453 write(data, callback) {
454 this.term.write(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000455 }
456
457 /**
458 * Like `this.write()` but also write a line break.
459 *
460 * @param {string|!Uint8Array} data
Jason Lin2649da22022-10-12 10:16:44 +1100461 * @param {function()=} callback Optional callback that fires when the data
462 * was processed by the parser.
Jason Lin21d854f2022-08-22 14:49:59 +1000463 */
Jason Lin2649da22022-10-12 10:16:44 +1100464 writeln(data, callback) {
465 this.term.writeln(data, callback);
Jason Lin21d854f2022-08-22 14:49:59 +1000466 }
467
Jason Linca61ffb2022-08-03 19:37:12 +1000468 get screenSize() {
469 return new hterm.Size(this.term.cols, this.term.rows);
470 }
471
472 /**
473 * Don't need to do anything.
474 *
475 * @override
476 */
477 installKeyboard() {}
478
479 /**
480 * @override
481 */
482 decorate(elem) {
Jason Linc2504ae2022-09-02 13:03:31 +1000483 this.container_ = elem;
Jason Lin8de3d282022-09-01 21:29:05 +1000484 (async () => {
485 await new Promise((resolve) => this.prefs_.readStorage(resolve));
486 // This will trigger all the observers to set the terminal options before
487 // we call `this.term.open()`.
488 this.prefs_.notifyAll();
489
Jason Linc2504ae2022-09-02 13:03:31 +1000490 const screenPaddingSize = /** @type {number} */(
491 this.prefs_.get('screen-padding-size'));
492 elem.style.paddingTop = elem.style.paddingLeft = `${screenPaddingSize}px`;
493
Jason Lin8de3d282022-09-01 21:29:05 +1000494 this.inited_ = true;
495 this.term.open(elem);
496
Jason Lin8de3d282022-09-01 21:29:05 +1000497 if (this.enableWebGL_) {
498 this.term.loadAddon(new WebglAddon());
499 }
500 this.term.focus();
501 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
502 // TODO: Make a11y work. Maybe we can just use hterm.AccessibilityReader.
503 this.notificationCenter_ = new hterm.NotificationCenter(document.body);
504
Emil Mikulic2a194d02022-09-29 14:30:59 +1000505 // Block right-click context menu from popping up.
506 elem.addEventListener('contextmenu', (e) => e.preventDefault());
507
508 // Add a handler for pasting with the mouse.
509 elem.addEventListener('mousedown', async (e) => {
510 if (this.term.modes.mouseTrackingMode !== 'none') {
511 // xterm.js is in mouse mode and will handle the event.
512 return;
513 }
514 const MIDDLE = 1;
515 const RIGHT = 2;
516 if (e.button === MIDDLE || (e.button === RIGHT &&
517 this.prefs_.getBoolean('mouse-right-click-paste'))) {
518 // Paste.
519 if (navigator.clipboard && navigator.clipboard.readText) {
520 const text = await navigator.clipboard.readText();
521 this.term.paste(text);
522 }
523 }
524 });
525
Jason Lin2649da22022-10-12 10:16:44 +1100526 await this.scheduleFit_();
Jason Lin8de3d282022-09-01 21:29:05 +1000527 this.onTerminalReady();
528 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000529 }
530
531 /** @override */
532 showOverlay(msg, timeout = 1500) {
533 if (this.notificationCenter_) {
534 this.notificationCenter_.show(msg, {timeout});
535 }
536 }
537
538 /** @override */
539 hideOverlay() {
540 if (this.notificationCenter_) {
541 this.notificationCenter_.hide();
542 }
Jason Linca61ffb2022-08-03 19:37:12 +1000543 }
544
545 /** @override */
546 getPrefs() {
547 return this.prefs_;
548 }
549
550 /** @override */
551 getDocument() {
552 return window.document;
553 }
554
Jason Lin21d854f2022-08-22 14:49:59 +1000555 /** @override */
556 reset() {
557 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000558 }
559
560 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000561 setProfile(profileId, callback = undefined) {
562 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000563 }
564
Jason Lin21d854f2022-08-22 14:49:59 +1000565 /** @override */
566 interpret(string) {
567 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000568 }
569
Jason Lin21d854f2022-08-22 14:49:59 +1000570 /** @override */
571 focus() {
572 this.term.focus();
573 }
Jason Linca61ffb2022-08-03 19:37:12 +1000574
575 /** @override */
576 onOpenOptionsPage() {}
577
578 /** @override */
579 onTerminalReady() {}
580
Jason Lind04bab32022-08-22 14:48:39 +1000581 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000582 // This is for this.notificationCenter_.
583 const setHtermCSSVariable = (name, value) => {
584 document.body.style.setProperty(`--hterm-${name}`, value);
585 };
586
587 const setHtermColorCSSVariable = (name, color) => {
588 const css = lib.notNull(lib.colors.normalizeCSS(color));
589 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
590 setHtermCSSVariable(name, rgb);
591 };
592
593 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000594 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000595 setHtermCSSVariable('font-size', `${v}px`);
596 });
597
Jason Linda56aa92022-09-02 13:01:49 +1000598 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000599 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000600 'audible-bell-sound': (v) => {
Jason Linc7afb672022-10-11 15:54:17 +1100601 this.bell_.playAudio = !!v;
602 },
603 'desktop-notification-bell': (v) => {
604 this.bell_.showNotification = v;
Jason Linda56aa92022-09-02 13:01:49 +1000605 },
Jason Lind04bab32022-08-22 14:48:39 +1000606 'background-color': (v) => {
607 this.updateTheme_({background: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000608 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000609 },
Jason Lind04bab32022-08-22 14:48:39 +1000610 'color-palette-overrides': (v) => {
611 if (!(v instanceof Array)) {
612 // For terminal, we always expect this to be an array.
613 console.warn('unexpected color palette: ', v);
614 return;
615 }
616 const colors = {};
617 for (let i = 0; i < v.length; ++i) {
618 colors[ANSI_COLOR_NAMES[i]] = v[i];
619 }
620 this.updateTheme_(colors);
621 },
Jason Linda56aa92022-09-02 13:01:49 +1000622 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
623 'cursor-color': (v) => this.updateTheme_({cursor: v}),
624 'cursor-shape': (v) => {
625 let shape;
626 if (v === 'BEAM') {
627 shape = 'bar';
628 } else {
629 shape = v.toLowerCase();
630 }
631 this.updateOption_('cursorStyle', shape, false);
632 },
633 'font-family': (v) => this.updateFont_(v),
634 'foreground-color': (v) => {
Jason Lin461ca562022-09-07 13:53:08 +1000635 this.updateTheme_({foreground: v});
Jason Linda56aa92022-09-02 13:01:49 +1000636 setHtermColorCSSVariable('foreground-color', v);
637 },
Jason Lind04bab32022-08-22 14:48:39 +1000638 });
Jason Lin5690e752022-08-30 15:36:45 +1000639
640 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
641 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
642 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
643 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
644 }
Jason Lind04bab32022-08-22 14:48:39 +1000645 }
646
647 /**
Jason Linc2504ae2022-09-02 13:03:31 +1000648 * Fit the terminal to the containing HTML element.
649 */
650 fit_() {
651 if (!this.inited_) {
652 return;
653 }
654
655 const screenPaddingSize = /** @type {number} */(
656 this.prefs_.get('screen-padding-size'));
657
658 const calc = (size, cellSize) => {
659 return Math.floor((size - 2 * screenPaddingSize) / cellSize);
660 };
661
Jason Lin2649da22022-10-12 10:16:44 +1100662 const cellDimensions = this.xtermInternal_.getActualCellDimensions();
663 const cols = calc(this.container_.offsetWidth, cellDimensions.width);
664 const rows = calc(this.container_.offsetHeight, cellDimensions.height);
Jason Linc2504ae2022-09-02 13:03:31 +1000665 if (cols >= 0 && rows >= 0) {
666 this.term.resize(cols, rows);
667 }
668 }
669
670 /**
Jason Lind04bab32022-08-22 14:48:39 +1000671 * @param {!Object} theme
672 */
673 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000674 const updateTheme = (target) => {
675 for (const [key, value] of Object.entries(theme)) {
676 target[key] = lib.colors.normalizeCSS(value);
677 }
678 };
679
680 // Must use a new theme object to trigger re-render if we have initialized.
681 if (this.inited_) {
682 const newTheme = {...this.term.options.theme};
683 updateTheme(newTheme);
684 this.term.options.theme = newTheme;
685 return;
Jason Lind04bab32022-08-22 14:48:39 +1000686 }
Jason Lin8de3d282022-09-01 21:29:05 +1000687
688 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000689 }
690
691 /**
Jason Linda56aa92022-09-02 13:01:49 +1000692 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
693 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000694 *
695 * @param {string} key
696 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000697 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000698 */
Jason Linda56aa92022-09-02 13:01:49 +1000699 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000700 // TODO: xterm supports updating multiple options at the same time. We
701 // should probably do that.
702 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000703 if (scheduleFit) {
704 this.scheduleFit_();
705 }
Jason Lind04bab32022-08-22 14:48:39 +1000706 }
Jason Linabad7562022-08-22 14:49:05 +1000707
708 /**
709 * Called when there is a "fontloadingdone" event. We need this because
710 * `FontManager.loadFont()` does not guarantee loading all the font files.
711 */
712 async onFontLoadingDone_() {
713 // If there is a pending font, the font is going to be refresh soon, so we
714 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000715 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000716 this.scheduleRefreshFont_();
717 }
718 }
719
Jason Lin5690e752022-08-30 15:36:45 +1000720 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000721 this.copyString_(this.term.getSelection());
722 }
723
724 /** @param {string} data */
725 copyString_(data) {
726 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000727 return;
728 }
Jason Line9231bc2022-09-01 13:54:02 +1000729 navigator.clipboard?.writeText(data);
Jason Lin6a402a72022-08-25 16:07:02 +1000730 if (!this.copyNotice_) {
731 this.copyNotice_ = document.createElement('terminal-copy-notice');
732 }
733 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200);
734 }
735
Jason Linabad7562022-08-22 14:49:05 +1000736 /**
737 * Refresh xterm rendering for a font related event.
738 */
739 refreshFont_() {
740 // We have to set the fontFamily option to a different string to trigger the
741 // re-rendering. Appending a space at the end seems to be the easiest
742 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
743 // us.
744 //
745 // TODO: Report a bug to xterm.js and ask for exposing a public function for
746 // the refresh so that we don't need to do this hack.
747 this.term.options.fontFamily += ' ';
748 }
749
750 /**
751 * Update a font.
752 *
753 * @param {string} cssFontFamily
754 */
755 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000756 this.pendingFont_ = cssFontFamily;
757 await this.fontManager_.loadFont(cssFontFamily);
758 // Sleep a bit to wait for flushing fontloadingdone events. This is not
759 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
760 // to refresh font unnecessarily in some cases.
761 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000762
Jason Lin6a402a72022-08-25 16:07:02 +1000763 if (this.pendingFont_ !== cssFontFamily) {
764 // `updateFont_()` probably is called again. Abort what we are doing.
765 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
766 ` (expecting ${cssFontFamily})`);
767 return;
768 }
Jason Linabad7562022-08-22 14:49:05 +1000769
Jason Lin6a402a72022-08-25 16:07:02 +1000770 if (this.term.options.fontFamily !== cssFontFamily) {
771 this.term.options.fontFamily = cssFontFamily;
772 } else {
773 // If the font is already the same, refresh font just to be safe.
774 this.refreshFont_();
775 }
776 this.pendingFont_ = null;
777 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000778 }
Jason Lin5690e752022-08-30 15:36:45 +1000779
780 /**
781 * @param {!KeyboardEvent} ev
782 * @return {boolean} Return false if xterm.js should not handle the key event.
783 */
784 customKeyEventHandler_(ev) {
785 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
786 (ev.altKey ? Modifier.Alt : 0) |
787 (ev.ctrlKey ? Modifier.Ctrl : 0) |
788 (ev.metaKey ? Modifier.Meta : 0);
789 const handler = this.keyDownHandlers_.get(
790 encodeKeyCombo(modifiers, ev.keyCode));
791 if (handler) {
792 if (ev.type === 'keydown') {
793 handler(ev);
794 }
795 return false;
796 }
797
798 return true;
799 }
800
801 /**
802 * A keydown handler for zoom-related keys.
803 *
804 * @param {!KeyboardEvent} ev
805 */
806 zoomKeyDownHandler_(ev) {
807 ev.preventDefault();
808
809 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
810 // The only one with a control code.
811 if (ev.keyCode === keyCodes.MINUS) {
812 this.io.onVTKeystroke('\x1f');
813 }
814 return;
815 }
816
817 let newFontSize;
818 switch (ev.keyCode) {
819 case keyCodes.ZERO:
820 newFontSize = this.prefs_.get('font-size');
821 break;
822 case keyCodes.MINUS:
823 newFontSize = this.term.options.fontSize - 1;
824 break;
825 default:
826 newFontSize = this.term.options.fontSize + 1;
827 break;
828 }
829
Jason Linda56aa92022-09-02 13:01:49 +1000830 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +1000831 }
832
833 /** @param {!KeyboardEvent} ev */
834 ctrlCKeyDownHandler_(ev) {
835 ev.preventDefault();
836 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
837 this.term.hasSelection()) {
838 this.copySelection_();
839 return;
840 }
841
842 this.io.onVTKeystroke('\x03');
843 }
844
845 /** @param {!KeyboardEvent} ev */
846 ctrlVKeyDownHandler_(ev) {
847 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
848 // Don't do anything and let the browser handles the key.
849 return;
850 }
851
852 ev.preventDefault();
853 this.io.onVTKeystroke('\x16');
854 }
855
856 resetKeyDownHandlers_() {
857 this.keyDownHandlers_.clear();
858
859 /**
860 * Don't do anything and let the browser handles the key.
861 *
862 * @param {!KeyboardEvent} ev
863 */
864 const noop = (ev) => {};
865
866 /**
867 * @param {number} modifiers
868 * @param {number} keyCode
869 * @param {function(!KeyboardEvent)} func
870 */
871 const set = (modifiers, keyCode, func) => {
872 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
873 func);
874 };
875
876 /**
877 * @param {number} modifiers
878 * @param {number} keyCode
879 * @param {function(!KeyboardEvent)} func
880 */
881 const setWithShiftVersion = (modifiers, keyCode, func) => {
882 set(modifiers, keyCode, func);
883 set(modifiers | Modifier.Shift, keyCode, func);
884 };
885
Jason Lin5690e752022-08-30 15:36:45 +1000886 // Ctrl+/
887 set(Modifier.Ctrl, 191, (ev) => {
888 ev.preventDefault();
889 this.io.onVTKeystroke(ctl('_'));
890 });
891
892 // Settings page.
893 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
894 ev.preventDefault();
895 chrome.terminalPrivate.openOptionsPage(() => {});
896 });
897
898 if (this.prefs_.get('keybindings-os-defaults')) {
899 for (const binding of OS_DEFAULT_BINDINGS) {
900 this.keyDownHandlers_.set(binding, noop);
901 }
902 }
903
904 /** @param {!KeyboardEvent} ev */
905 const newWindow = (ev) => {
906 ev.preventDefault();
907 chrome.terminalPrivate.openWindow();
908 };
909 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
910 if (this.prefs_.get('pass-ctrl-n')) {
911 set(Modifier.Ctrl, keyCodes.N, newWindow);
912 }
913
914 if (this.prefs_.get('pass-ctrl-t')) {
915 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
916 }
917
918 if (this.prefs_.get('pass-ctrl-w')) {
919 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
920 }
921
922 if (this.prefs_.get('pass-ctrl-tab')) {
923 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
924 }
925
926 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
927
928 /**
929 * Set a handler for the key combo ctrl+<number>.
930 *
931 * @param {number} number 1 to 9
932 * @param {string} controlCode The control code to send if we don't want to
933 * let the browser to handle it.
934 */
935 const setCtrlNumberHandler = (number, controlCode) => {
936 let func = noop;
937 if (!passCtrlNumber) {
938 func = (ev) => {
939 ev.preventDefault();
940 this.io.onVTKeystroke(controlCode);
941 };
942 }
943 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
944 };
945
946 setCtrlNumberHandler(1, '1');
947 setCtrlNumberHandler(2, ctl('@'));
948 setCtrlNumberHandler(3, ctl('['));
949 setCtrlNumberHandler(4, ctl('\\'));
950 setCtrlNumberHandler(5, ctl(']'));
951 setCtrlNumberHandler(6, ctl('^'));
952 setCtrlNumberHandler(7, ctl('_'));
953 setCtrlNumberHandler(8, '\x7f');
954 setCtrlNumberHandler(9, '9');
955
956 if (this.prefs_.get('pass-alt-number')) {
957 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
958 set(Modifier.Alt, keyCode, noop);
959 }
960 }
961
962 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
963 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
964 }
965
966 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
967 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
968 }
Jason Linca61ffb2022-08-03 19:37:12 +1000969}
970
Jason Lind66e6bf2022-08-22 14:47:10 +1000971class HtermTerminal extends hterm.Terminal {
972 /** @override */
973 decorate(div) {
974 super.decorate(div);
975
976 const fontManager = new FontManager(this.getDocument());
977 fontManager.loadPowerlineCSS().then(() => {
978 const prefs = this.getPrefs();
979 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
980 prefs.addObserver(
981 'font-family',
982 (v) => fontManager.loadFont(/** @type {string} */(v)));
983 });
984 }
Jason Lin2649da22022-10-12 10:16:44 +1100985
986 /**
987 * Write data to the terminal.
988 *
989 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
990 * UTF-8 data
991 * @param {function()=} callback Optional callback that fires when the data
992 * was processed by the parser.
993 */
994 write(data, callback) {
995 if (typeof data === 'string') {
996 this.io.print(data);
997 } else {
998 this.io.writeUTF8(data);
999 }
1000 // Hterm processes the data synchronously, so we can call the callback
1001 // immediately.
1002 if (callback) {
1003 setTimeout(callback);
1004 }
1005 }
Jason Lind66e6bf2022-08-22 14:47:10 +10001006}
1007
Jason Linca61ffb2022-08-03 19:37:12 +10001008/**
1009 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
1010 * preference value.
1011 *
1012 * @param {{
1013 * storage: !lib.Storage,
1014 * profileId: string,
1015 * }} args
1016 * @return {!Promise<!hterm.Terminal>}
1017 */
1018export async function createEmulator({storage, profileId}) {
1019 let config = TERMINAL_EMULATORS.get('hterm');
1020
1021 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +10001022 // TODO: remove the url param logic. This is temporary to make manual
1023 // testing a bit easier, which is also why this is not in
1024 // './js/terminal_info.js'.
1025 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
1026 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +10001027 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +10001028 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +10001029 TERMINAL_EMULATORS.values().next().value;
1030 console.log('Terminal emulator config: ', config);
1031 }
1032
1033 switch (config.lib) {
1034 case 'xterm.js':
1035 {
1036 const terminal = new XtermTerminal({
1037 storage,
1038 profileId,
1039 enableWebGL: config.webgl,
1040 });
Jason Linca61ffb2022-08-03 19:37:12 +10001041 return terminal;
1042 }
1043 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +10001044 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +10001045 default:
1046 throw new Error('incorrect emulator config');
1047 }
1048}
1049
Jason Lin6a402a72022-08-25 16:07:02 +10001050class TerminalCopyNotice extends LitElement {
1051 /** @override */
1052 static get styles() {
1053 return css`
1054 :host {
1055 display: block;
1056 text-align: center;
1057 }
1058
1059 svg {
1060 fill: currentColor;
1061 }
1062 `;
1063 }
1064
1065 /** @override */
1066 render() {
1067 return html`
1068 ${ICON_COPY}
1069 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
1070 `;
1071 }
1072}
1073
1074customElements.define('terminal-copy-notice', TerminalCopyNotice);