blob: 8733d38e8538095f66f6f6fc306d3bc1f5ebfddd [file] [log] [blame]
Jason Lind66e6bf2022-08-22 14:47:10 +10001// Copyright 2022 The Chromium OS Authors. All rights reserved.
2// 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 Lin6a402a72022-08-25 16:07:02 +100012import {LitElement, css, html} from './lit.js';
Jason Lin21d854f2022-08-22 14:49:59 +100013import {FontManager, ORIGINAL_URL, TERMINAL_EMULATORS, delayedScheduler,
14 fontManager, getOSInfo, sleep} from './terminal_common.js';
Jason Lin6a402a72022-08-25 16:07:02 +100015import {ICON_COPY} from './terminal_icons.js';
Jason Lin4de4f382022-09-01 14:10:18 +100016import {FitAddon, Terminal, Unicode11Addon, WebLinksAddon, WebglAddon}
17 from './xterm.js';
Jason Linca61ffb2022-08-03 19:37:12 +100018
Jason Lin5690e752022-08-30 15:36:45 +100019
20/** @enum {number} */
21export const Modifier = {
22 Shift: 1 << 0,
23 Alt: 1 << 1,
24 Ctrl: 1 << 2,
25 Meta: 1 << 3,
26};
27
28// This is just a static map from key names to key codes. It helps make the code
29// a bit more readable.
30const keyCodes = hterm.Parser.identifiers.keyCodes;
31
32/**
33 * Encode a key combo (i.e. modifiers + a normal key) to an unique number.
34 *
35 * @param {number} modifiers
36 * @param {number} keyCode
37 * @return {number}
38 */
39export function encodeKeyCombo(modifiers, keyCode) {
40 return keyCode << 4 | modifiers;
41}
42
43const OS_DEFAULT_BINDINGS = [
44 // Submit feedback.
45 encodeKeyCombo(Modifier.Alt | Modifier.Shift, keyCodes.I),
46 // Toggle chromevox.
47 encodeKeyCombo(Modifier.Ctrl | Modifier.Alt, keyCodes.Z),
48 // Switch input method.
49 encodeKeyCombo(Modifier.Ctrl, keyCodes.SPACE),
50
51 // Dock window left/right.
52 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_LEFT),
53 encodeKeyCombo(Modifier.Alt, keyCodes.BRACKET_RIGHT),
54
55 // Maximize/minimize window.
56 encodeKeyCombo(Modifier.Alt, keyCodes.EQUAL),
57 encodeKeyCombo(Modifier.Alt, keyCodes.MINUS),
58];
59
60
Jason Linca61ffb2022-08-03 19:37:12 +100061const ANSI_COLOR_NAMES = [
62 'black',
63 'red',
64 'green',
65 'yellow',
66 'blue',
67 'magenta',
68 'cyan',
69 'white',
70 'brightBlack',
71 'brightRed',
72 'brightGreen',
73 'brightYellow',
74 'brightBlue',
75 'brightMagenta',
76 'brightCyan',
77 'brightWhite',
78];
79
Jason Linca61ffb2022-08-03 19:37:12 +100080/**
Jason Linabad7562022-08-22 14:49:05 +100081 * @typedef {{
82 * term: !Terminal,
83 * fontManager: !FontManager,
84 * fitAddon: !FitAddon,
85 * }}
86 */
87export let XtermTerminalTestParams;
88
89/**
Jason Lin5690e752022-08-30 15:36:45 +100090 * Compute a control character for a given character.
91 *
92 * @param {string} ch
93 * @return {string}
94 */
95function ctl(ch) {
96 return String.fromCharCode(ch.charCodeAt(0) - 64);
97}
98
99/**
Jason Lin21d854f2022-08-22 14:49:59 +1000100 * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO
101 * because it always convert utf8 data to strings, which is not necessary for
102 * xterm.
103 */
104class XtermTerminalIO extends hterm.Terminal.IO {
105 /** @override */
106 writeUTF8(buffer) {
107 this.terminal_.write(new Uint8Array(buffer));
108 }
109
110 /** @override */
111 writelnUTF8(buffer) {
112 this.terminal_.writeln(new Uint8Array(buffer));
113 }
114
115 /** @override */
116 print(string) {
117 this.terminal_.write(string);
118 }
119
120 /** @override */
121 writeUTF16(string) {
122 this.print(string);
123 }
124
125 /** @override */
126 println(string) {
127 this.terminal_.writeln(string);
128 }
129
130 /** @override */
131 writelnUTF16(string) {
132 this.println(string);
133 }
134}
135
136/**
Jason Linca61ffb2022-08-03 19:37:12 +1000137 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
138 * so that it can be used in existing code.
139 *
Jason Linca61ffb2022-08-03 19:37:12 +1000140 * @extends {hterm.Terminal}
141 * @unrestricted
142 */
Jason Linabad7562022-08-22 14:49:05 +1000143export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +1000144 /**
145 * @param {{
146 * storage: !lib.Storage,
147 * profileId: string,
148 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000149 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000150 * }} args
151 */
Jason Linabad7562022-08-22 14:49:05 +1000152 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin5690e752022-08-30 15:36:45 +1000153 this.ctrlCKeyDownHandler_ = this.ctrlCKeyDownHandler_.bind(this);
154 this.ctrlVKeyDownHandler_ = this.ctrlVKeyDownHandler_.bind(this);
155 this.zoomKeyDownHandler_ = this.zoomKeyDownHandler_.bind(this);
156
Jason Lin8de3d282022-09-01 21:29:05 +1000157 this.inited_ = false;
Jason Lin21d854f2022-08-22 14:49:59 +1000158 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000159 /** @type {!hterm.PreferenceManager} */
160 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
161 this.enableWebGL_ = enableWebGL;
162
Jason Lin5690e752022-08-30 15:36:45 +1000163 // TODO: we should probably pass the initial prefs to the ctor.
Jason Linabad7562022-08-22 14:49:05 +1000164 this.term = testParams?.term || new Terminal();
165 this.fontManager_ = testParams?.fontManager || fontManager;
166 this.fitAddon = testParams?.fitAddon || new FitAddon();
167
Jason Linca61ffb2022-08-03 19:37:12 +1000168 this.term.loadAddon(this.fitAddon);
Jason Lin8de3d282022-09-01 21:29:05 +1000169 this.scheduleFit_ = delayedScheduler(
170 () => {
171 if (this.inited_) {
172 this.fitAddon.fit();
173 }
174 },
Jason Linabad7562022-08-22 14:49:05 +1000175 testParams ? 0 : 250);
176
Jason Lin4de4f382022-09-01 14:10:18 +1000177 this.term.loadAddon(new WebLinksAddon());
178 this.term.loadAddon(new Unicode11Addon());
179 this.term.unicode.activeVersion = '11';
180
Jason Linabad7562022-08-22 14:49:05 +1000181 this.pendingFont_ = null;
182 this.scheduleRefreshFont_ = delayedScheduler(
183 () => this.refreshFont_(), 100);
184 document.fonts.addEventListener('loadingdone',
185 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000186
187 this.installUnimplementedStubs_();
Jason Line9231bc2022-09-01 13:54:02 +1000188 this.installEscapeSequenceHandlers_();
Jason Linca61ffb2022-08-03 19:37:12 +1000189
Jason Lin21d854f2022-08-22 14:49:59 +1000190 this.term.onResize(({cols, rows}) => this.io.onTerminalResize(cols, rows));
191 // We could also use `this.io.sendString()` except for the nassh exit
192 // prompt, which only listens to onVTKeystroke().
193 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin6a402a72022-08-25 16:07:02 +1000194 this.term.onTitleChange((title) => document.title = title);
Jason Lin5690e752022-08-30 15:36:45 +1000195 this.term.onSelectionChange(() => this.copySelection_());
196
197 /**
198 * A mapping from key combo (see encodeKeyCombo()) to a handler function.
199 *
200 * If a key combo is in the map:
201 *
202 * - The handler instead of xterm.js will handle the keydown event.
203 * - Keyup and keypress will be ignored by both us and xterm.js.
204 *
205 * We re-generate this map every time a relevant pref value is changed. This
206 * is ok because pref changes are rare.
207 *
208 * @type {!Map<number, function(!KeyboardEvent)>}
209 */
210 this.keyDownHandlers_ = new Map();
211 this.scheduleResetKeyDownHandlers_ =
212 delayedScheduler(() => this.resetKeyDownHandlers_(), 250);
213
214 this.term.attachCustomKeyEventHandler(
215 this.customKeyEventHandler_.bind(this));
Jason Linca61ffb2022-08-03 19:37:12 +1000216
Jason Lin21d854f2022-08-22 14:49:59 +1000217 this.io = new XtermTerminalIO(this);
218 this.notificationCenter_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000219
220 this.copyNotice_ = null;
221
222 this.term.options.theme = {
223 selection: 'rgba(174, 203, 250, .6)',
224 selectionForeground: 'black',
225 customGlyphs: true,
226 };
227 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000228 }
229
230 /**
231 * Install stubs for stuff that we haven't implemented yet so that the code
232 * still runs.
233 */
234 installUnimplementedStubs_() {
235 this.keyboard = {
236 keyMap: {
237 keyDefs: [],
238 },
239 bindings: {
240 clear: () => {},
241 addBinding: () => {},
242 addBindings: () => {},
243 OsDefaults: {},
244 },
245 };
246 this.keyboard.keyMap.keyDefs[78] = {};
247
248 const methodNames = [
Jason Linca61ffb2022-08-03 19:37:12 +1000249 'setAccessibilityEnabled',
250 'setBackgroundImage',
251 'setCursorPosition',
252 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000253 ];
254
255 for (const name of methodNames) {
256 this[name] = () => console.warn(`${name}() is not implemented`);
257 }
258
259 this.contextMenu = {
260 setItems: () => {
261 console.warn('.contextMenu.setItems() is not implemented');
262 },
263 };
Jason Lin21d854f2022-08-22 14:49:59 +1000264
265 this.vt = {
266 resetParseState: () => {
267 console.warn('.vt.resetParseState() is not implemented');
268 },
269 };
Jason Linca61ffb2022-08-03 19:37:12 +1000270 }
271
Jason Line9231bc2022-09-01 13:54:02 +1000272 installEscapeSequenceHandlers_() {
273 // OSC 52 for copy.
274 this.term.parser.registerOscHandler(52, (args) => {
275 // Args comes in as a single 'clipboard;b64-data' string. The clipboard
276 // parameter is used to select which of the X clipboards to address. Since
277 // we're not integrating with X, we treat them all the same.
278 const parsedArgs = args.match(/^[cps01234567]*;(.*)/);
279 if (!parsedArgs) {
280 return true;
281 }
282
283 let data;
284 try {
285 data = window.atob(parsedArgs[1]);
286 } catch (e) {
287 // If the user sent us invalid base64 content, silently ignore it.
288 return true;
289 }
290 const decoder = new TextDecoder();
291 const bytes = lib.codec.stringToCodeUnitArray(data);
292 this.copyString_(decoder.decode(bytes));
293
294 return true;
295 });
296 }
297
Jason Linca61ffb2022-08-03 19:37:12 +1000298 /**
Jason Lin21d854f2022-08-22 14:49:59 +1000299 * Write data to the terminal.
300 *
301 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
302 * UTF-8 data
303 */
304 write(data) {
305 this.term.write(data);
306 }
307
308 /**
309 * Like `this.write()` but also write a line break.
310 *
311 * @param {string|!Uint8Array} data
312 */
313 writeln(data) {
314 this.term.writeln(data);
315 }
316
Jason Linca61ffb2022-08-03 19:37:12 +1000317 get screenSize() {
318 return new hterm.Size(this.term.cols, this.term.rows);
319 }
320
321 /**
322 * Don't need to do anything.
323 *
324 * @override
325 */
326 installKeyboard() {}
327
328 /**
329 * @override
330 */
331 decorate(elem) {
Jason Lin8de3d282022-09-01 21:29:05 +1000332 (async () => {
333 await new Promise((resolve) => this.prefs_.readStorage(resolve));
334 // This will trigger all the observers to set the terminal options before
335 // we call `this.term.open()`.
336 this.prefs_.notifyAll();
337
338 this.inited_ = true;
339 this.term.open(elem);
340
341 this.scheduleFit_();
342 if (this.enableWebGL_) {
343 this.term.loadAddon(new WebglAddon());
344 }
345 this.term.focus();
346 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
347 // TODO: Make a11y work. Maybe we can just use hterm.AccessibilityReader.
348 this.notificationCenter_ = new hterm.NotificationCenter(document.body);
349
350 this.onTerminalReady();
351 })();
Jason Lin21d854f2022-08-22 14:49:59 +1000352 }
353
354 /** @override */
355 showOverlay(msg, timeout = 1500) {
356 if (this.notificationCenter_) {
357 this.notificationCenter_.show(msg, {timeout});
358 }
359 }
360
361 /** @override */
362 hideOverlay() {
363 if (this.notificationCenter_) {
364 this.notificationCenter_.hide();
365 }
Jason Linca61ffb2022-08-03 19:37:12 +1000366 }
367
368 /** @override */
369 getPrefs() {
370 return this.prefs_;
371 }
372
373 /** @override */
374 getDocument() {
375 return window.document;
376 }
377
Jason Lin21d854f2022-08-22 14:49:59 +1000378 /** @override */
379 reset() {
380 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000381 }
382
383 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000384 setProfile(profileId, callback = undefined) {
385 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000386 }
387
Jason Lin21d854f2022-08-22 14:49:59 +1000388 /** @override */
389 interpret(string) {
390 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000391 }
392
Jason Lin21d854f2022-08-22 14:49:59 +1000393 /** @override */
394 focus() {
395 this.term.focus();
396 }
Jason Linca61ffb2022-08-03 19:37:12 +1000397
398 /** @override */
399 onOpenOptionsPage() {}
400
401 /** @override */
402 onTerminalReady() {}
403
Jason Lind04bab32022-08-22 14:48:39 +1000404 observePrefs_() {
Jason Lin21d854f2022-08-22 14:49:59 +1000405 // This is for this.notificationCenter_.
406 const setHtermCSSVariable = (name, value) => {
407 document.body.style.setProperty(`--hterm-${name}`, value);
408 };
409
410 const setHtermColorCSSVariable = (name, color) => {
411 const css = lib.notNull(lib.colors.normalizeCSS(color));
412 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
413 setHtermCSSVariable(name, rgb);
414 };
415
416 this.prefs_.addObserver('font-size', (v) => {
Jason Linda56aa92022-09-02 13:01:49 +1000417 this.updateOption_('fontSize', v, true);
Jason Lin21d854f2022-08-22 14:49:59 +1000418 setHtermCSSVariable('font-size', `${v}px`);
419 });
420
Jason Linda56aa92022-09-02 13:01:49 +1000421 // TODO(lxj): support option "lineHeight", "scrollback".
Jason Lind04bab32022-08-22 14:48:39 +1000422 this.prefs_.addObservers(null, {
Jason Linda56aa92022-09-02 13:01:49 +1000423 'audible-bell-sound': (v) => {
424 if (v) {
425 this.updateOption_('bellStyle', 'sound', false);
426 this.updateOption_('bellSound', lib.resource.getDataUrl(
427 'hterm/audio/bell'), false);
428 } else {
429 this.updateOption_('bellStyle', 'none', false);
430 }
431 },
Jason Lind04bab32022-08-22 14:48:39 +1000432 'background-color': (v) => {
433 this.updateTheme_({background: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000434 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000435 },
Jason Lind04bab32022-08-22 14:48:39 +1000436 'color-palette-overrides': (v) => {
437 if (!(v instanceof Array)) {
438 // For terminal, we always expect this to be an array.
439 console.warn('unexpected color palette: ', v);
440 return;
441 }
442 const colors = {};
443 for (let i = 0; i < v.length; ++i) {
444 colors[ANSI_COLOR_NAMES[i]] = v[i];
445 }
446 this.updateTheme_(colors);
447 },
Jason Linda56aa92022-09-02 13:01:49 +1000448 'cursor-blink': (v) => this.updateOption_('cursorBlink', v, false),
449 'cursor-color': (v) => this.updateTheme_({cursor: v}),
450 'cursor-shape': (v) => {
451 let shape;
452 if (v === 'BEAM') {
453 shape = 'bar';
454 } else {
455 shape = v.toLowerCase();
456 }
457 this.updateOption_('cursorStyle', shape, false);
458 },
459 'font-family': (v) => this.updateFont_(v),
460 'foreground-color': (v) => {
461 // TODO(lxj): setting the cursorAccent to the foreground color mimics
462 // what hterm does, but I think it is better to expose this option.
463 this.updateTheme_({foreground: v, cursorAccent: v});
464 setHtermColorCSSVariable('foreground-color', v);
465 },
Jason Lind04bab32022-08-22 14:48:39 +1000466 });
Jason Lin5690e752022-08-30 15:36:45 +1000467
468 for (const name of ['keybindings-os-defaults', 'pass-ctrl-n', 'pass-ctrl-t',
469 'pass-ctrl-w', 'pass-ctrl-tab', 'pass-ctrl-number', 'pass-alt-number',
470 'ctrl-plus-minus-zero-zoom', 'ctrl-c-copy', 'ctrl-v-paste']) {
471 this.prefs_.addObserver(name, this.scheduleResetKeyDownHandlers_);
472 }
Jason Lind04bab32022-08-22 14:48:39 +1000473 }
474
475 /**
476 * @param {!Object} theme
477 */
478 updateTheme_(theme) {
Jason Lin8de3d282022-09-01 21:29:05 +1000479 const updateTheme = (target) => {
480 for (const [key, value] of Object.entries(theme)) {
481 target[key] = lib.colors.normalizeCSS(value);
482 }
483 };
484
485 // Must use a new theme object to trigger re-render if we have initialized.
486 if (this.inited_) {
487 const newTheme = {...this.term.options.theme};
488 updateTheme(newTheme);
489 this.term.options.theme = newTheme;
490 return;
Jason Lind04bab32022-08-22 14:48:39 +1000491 }
Jason Lin8de3d282022-09-01 21:29:05 +1000492
493 updateTheme(this.term.options.theme);
Jason Lind04bab32022-08-22 14:48:39 +1000494 }
495
496 /**
Jason Linda56aa92022-09-02 13:01:49 +1000497 * Update one xterm.js option. Use updateTheme_()/updateFont_() for
498 * theme/font.
Jason Lind04bab32022-08-22 14:48:39 +1000499 *
500 * @param {string} key
501 * @param {*} value
Jason Linda56aa92022-09-02 13:01:49 +1000502 * @param {boolean} scheduleFit
Jason Lind04bab32022-08-22 14:48:39 +1000503 */
Jason Linda56aa92022-09-02 13:01:49 +1000504 updateOption_(key, value, scheduleFit) {
Jason Lind04bab32022-08-22 14:48:39 +1000505 // TODO: xterm supports updating multiple options at the same time. We
506 // should probably do that.
507 this.term.options[key] = value;
Jason Linda56aa92022-09-02 13:01:49 +1000508 if (scheduleFit) {
509 this.scheduleFit_();
510 }
Jason Lind04bab32022-08-22 14:48:39 +1000511 }
Jason Linabad7562022-08-22 14:49:05 +1000512
513 /**
514 * Called when there is a "fontloadingdone" event. We need this because
515 * `FontManager.loadFont()` does not guarantee loading all the font files.
516 */
517 async onFontLoadingDone_() {
518 // If there is a pending font, the font is going to be refresh soon, so we
519 // don't need to do anything.
Jason Lin8de3d282022-09-01 21:29:05 +1000520 if (this.inited_ && !this.pendingFont_) {
Jason Linabad7562022-08-22 14:49:05 +1000521 this.scheduleRefreshFont_();
522 }
523 }
524
Jason Lin5690e752022-08-30 15:36:45 +1000525 copySelection_() {
Jason Line9231bc2022-09-01 13:54:02 +1000526 this.copyString_(this.term.getSelection());
527 }
528
529 /** @param {string} data */
530 copyString_(data) {
531 if (!data) {
Jason Lin6a402a72022-08-25 16:07:02 +1000532 return;
533 }
Jason Line9231bc2022-09-01 13:54:02 +1000534 navigator.clipboard?.writeText(data);
Jason Lin6a402a72022-08-25 16:07:02 +1000535 if (!this.copyNotice_) {
536 this.copyNotice_ = document.createElement('terminal-copy-notice');
537 }
538 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200);
539 }
540
Jason Linabad7562022-08-22 14:49:05 +1000541 /**
542 * Refresh xterm rendering for a font related event.
543 */
544 refreshFont_() {
545 // We have to set the fontFamily option to a different string to trigger the
546 // re-rendering. Appending a space at the end seems to be the easiest
547 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
548 // us.
549 //
550 // TODO: Report a bug to xterm.js and ask for exposing a public function for
551 // the refresh so that we don't need to do this hack.
552 this.term.options.fontFamily += ' ';
553 }
554
555 /**
556 * Update a font.
557 *
558 * @param {string} cssFontFamily
559 */
560 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000561 this.pendingFont_ = cssFontFamily;
562 await this.fontManager_.loadFont(cssFontFamily);
563 // Sleep a bit to wait for flushing fontloadingdone events. This is not
564 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
565 // to refresh font unnecessarily in some cases.
566 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000567
Jason Lin6a402a72022-08-25 16:07:02 +1000568 if (this.pendingFont_ !== cssFontFamily) {
569 // `updateFont_()` probably is called again. Abort what we are doing.
570 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
571 ` (expecting ${cssFontFamily})`);
572 return;
573 }
Jason Linabad7562022-08-22 14:49:05 +1000574
Jason Lin6a402a72022-08-25 16:07:02 +1000575 if (this.term.options.fontFamily !== cssFontFamily) {
576 this.term.options.fontFamily = cssFontFamily;
577 } else {
578 // If the font is already the same, refresh font just to be safe.
579 this.refreshFont_();
580 }
581 this.pendingFont_ = null;
582 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000583 }
Jason Lin5690e752022-08-30 15:36:45 +1000584
585 /**
586 * @param {!KeyboardEvent} ev
587 * @return {boolean} Return false if xterm.js should not handle the key event.
588 */
589 customKeyEventHandler_(ev) {
590 const modifiers = (ev.shiftKey ? Modifier.Shift : 0) |
591 (ev.altKey ? Modifier.Alt : 0) |
592 (ev.ctrlKey ? Modifier.Ctrl : 0) |
593 (ev.metaKey ? Modifier.Meta : 0);
594 const handler = this.keyDownHandlers_.get(
595 encodeKeyCombo(modifiers, ev.keyCode));
596 if (handler) {
597 if (ev.type === 'keydown') {
598 handler(ev);
599 }
600 return false;
601 }
602
603 return true;
604 }
605
606 /**
607 * A keydown handler for zoom-related keys.
608 *
609 * @param {!KeyboardEvent} ev
610 */
611 zoomKeyDownHandler_(ev) {
612 ev.preventDefault();
613
614 if (this.prefs_.get('ctrl-plus-minus-zero-zoom') === ev.shiftKey) {
615 // The only one with a control code.
616 if (ev.keyCode === keyCodes.MINUS) {
617 this.io.onVTKeystroke('\x1f');
618 }
619 return;
620 }
621
622 let newFontSize;
623 switch (ev.keyCode) {
624 case keyCodes.ZERO:
625 newFontSize = this.prefs_.get('font-size');
626 break;
627 case keyCodes.MINUS:
628 newFontSize = this.term.options.fontSize - 1;
629 break;
630 default:
631 newFontSize = this.term.options.fontSize + 1;
632 break;
633 }
634
Jason Linda56aa92022-09-02 13:01:49 +1000635 this.updateOption_('fontSize', Math.max(1, newFontSize), true);
Jason Lin5690e752022-08-30 15:36:45 +1000636 }
637
638 /** @param {!KeyboardEvent} ev */
639 ctrlCKeyDownHandler_(ev) {
640 ev.preventDefault();
641 if (this.prefs_.get('ctrl-c-copy') !== ev.shiftKey &&
642 this.term.hasSelection()) {
643 this.copySelection_();
644 return;
645 }
646
647 this.io.onVTKeystroke('\x03');
648 }
649
650 /** @param {!KeyboardEvent} ev */
651 ctrlVKeyDownHandler_(ev) {
652 if (this.prefs_.get('ctrl-v-paste') !== ev.shiftKey) {
653 // Don't do anything and let the browser handles the key.
654 return;
655 }
656
657 ev.preventDefault();
658 this.io.onVTKeystroke('\x16');
659 }
660
661 resetKeyDownHandlers_() {
662 this.keyDownHandlers_.clear();
663
664 /**
665 * Don't do anything and let the browser handles the key.
666 *
667 * @param {!KeyboardEvent} ev
668 */
669 const noop = (ev) => {};
670
671 /**
672 * @param {number} modifiers
673 * @param {number} keyCode
674 * @param {function(!KeyboardEvent)} func
675 */
676 const set = (modifiers, keyCode, func) => {
677 this.keyDownHandlers_.set(encodeKeyCombo(modifiers, keyCode),
678 func);
679 };
680
681 /**
682 * @param {number} modifiers
683 * @param {number} keyCode
684 * @param {function(!KeyboardEvent)} func
685 */
686 const setWithShiftVersion = (modifiers, keyCode, func) => {
687 set(modifiers, keyCode, func);
688 set(modifiers | Modifier.Shift, keyCode, func);
689 };
690
Jason Linf51162f2022-09-01 15:21:55 +1000691 // Temporary shortcut to refresh the rendering in case of rendering errors.
692 // TODO(lxj): remove after this is fixed:
693 // https://github.com/xtermjs/xterm.js/issues/3878
694 set(Modifier.Ctrl | Modifier.Shift, keyCodes.L,
695 /** @suppress {missingProperties} */
696 () => {
697 this.scheduleRefreshFont_();
698 // Refresh the cursor layer.
699 if (this.enableWebGL_) {
700 this.term?._core?._renderService?._renderer?._renderLayers[1]
701 ?._clearAll();
702 }
703 },
704 );
Jason Lin5690e752022-08-30 15:36:45 +1000705
706 // Ctrl+/
707 set(Modifier.Ctrl, 191, (ev) => {
708 ev.preventDefault();
709 this.io.onVTKeystroke(ctl('_'));
710 });
711
712 // Settings page.
713 set(Modifier.Ctrl | Modifier.Shift, keyCodes.P, (ev) => {
714 ev.preventDefault();
715 chrome.terminalPrivate.openOptionsPage(() => {});
716 });
717
718 if (this.prefs_.get('keybindings-os-defaults')) {
719 for (const binding of OS_DEFAULT_BINDINGS) {
720 this.keyDownHandlers_.set(binding, noop);
721 }
722 }
723
724 /** @param {!KeyboardEvent} ev */
725 const newWindow = (ev) => {
726 ev.preventDefault();
727 chrome.terminalPrivate.openWindow();
728 };
729 set(Modifier.Ctrl | Modifier.Shift, keyCodes.N, newWindow);
730 if (this.prefs_.get('pass-ctrl-n')) {
731 set(Modifier.Ctrl, keyCodes.N, newWindow);
732 }
733
734 if (this.prefs_.get('pass-ctrl-t')) {
735 setWithShiftVersion(Modifier.Ctrl, keyCodes.T, noop);
736 }
737
738 if (this.prefs_.get('pass-ctrl-w')) {
739 setWithShiftVersion(Modifier.Ctrl, keyCodes.W, noop);
740 }
741
742 if (this.prefs_.get('pass-ctrl-tab')) {
743 setWithShiftVersion(Modifier.Ctrl, keyCodes.TAB, noop);
744 }
745
746 const passCtrlNumber = this.prefs_.get('pass-ctrl-number');
747
748 /**
749 * Set a handler for the key combo ctrl+<number>.
750 *
751 * @param {number} number 1 to 9
752 * @param {string} controlCode The control code to send if we don't want to
753 * let the browser to handle it.
754 */
755 const setCtrlNumberHandler = (number, controlCode) => {
756 let func = noop;
757 if (!passCtrlNumber) {
758 func = (ev) => {
759 ev.preventDefault();
760 this.io.onVTKeystroke(controlCode);
761 };
762 }
763 set(Modifier.Ctrl, keyCodes.ZERO + number, func);
764 };
765
766 setCtrlNumberHandler(1, '1');
767 setCtrlNumberHandler(2, ctl('@'));
768 setCtrlNumberHandler(3, ctl('['));
769 setCtrlNumberHandler(4, ctl('\\'));
770 setCtrlNumberHandler(5, ctl(']'));
771 setCtrlNumberHandler(6, ctl('^'));
772 setCtrlNumberHandler(7, ctl('_'));
773 setCtrlNumberHandler(8, '\x7f');
774 setCtrlNumberHandler(9, '9');
775
776 if (this.prefs_.get('pass-alt-number')) {
777 for (let keyCode = keyCodes.ZERO; keyCode <= keyCodes.NINE; ++keyCode) {
778 set(Modifier.Alt, keyCode, noop);
779 }
780 }
781
782 for (const keyCode of [keyCodes.ZERO, keyCodes.MINUS, keyCodes.EQUAL]) {
783 setWithShiftVersion(Modifier.Ctrl, keyCode, this.zoomKeyDownHandler_);
784 }
785
786 setWithShiftVersion(Modifier.Ctrl, keyCodes.C, this.ctrlCKeyDownHandler_);
787 setWithShiftVersion(Modifier.Ctrl, keyCodes.V, this.ctrlVKeyDownHandler_);
788 }
Jason Linca61ffb2022-08-03 19:37:12 +1000789}
790
Jason Lind66e6bf2022-08-22 14:47:10 +1000791class HtermTerminal extends hterm.Terminal {
792 /** @override */
793 decorate(div) {
794 super.decorate(div);
795
796 const fontManager = new FontManager(this.getDocument());
797 fontManager.loadPowerlineCSS().then(() => {
798 const prefs = this.getPrefs();
799 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
800 prefs.addObserver(
801 'font-family',
802 (v) => fontManager.loadFont(/** @type {string} */(v)));
803 });
804 }
805}
806
Jason Linca61ffb2022-08-03 19:37:12 +1000807/**
808 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
809 * preference value.
810 *
811 * @param {{
812 * storage: !lib.Storage,
813 * profileId: string,
814 * }} args
815 * @return {!Promise<!hterm.Terminal>}
816 */
817export async function createEmulator({storage, profileId}) {
818 let config = TERMINAL_EMULATORS.get('hterm');
819
820 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +1000821 // TODO: remove the url param logic. This is temporary to make manual
822 // testing a bit easier, which is also why this is not in
823 // './js/terminal_info.js'.
824 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
825 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +1000826 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +1000827 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +1000828 TERMINAL_EMULATORS.values().next().value;
829 console.log('Terminal emulator config: ', config);
830 }
831
832 switch (config.lib) {
833 case 'xterm.js':
834 {
835 const terminal = new XtermTerminal({
836 storage,
837 profileId,
838 enableWebGL: config.webgl,
839 });
Jason Linca61ffb2022-08-03 19:37:12 +1000840 return terminal;
841 }
842 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +1000843 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +1000844 default:
845 throw new Error('incorrect emulator config');
846 }
847}
848
Jason Lin6a402a72022-08-25 16:07:02 +1000849class TerminalCopyNotice extends LitElement {
850 /** @override */
851 static get styles() {
852 return css`
853 :host {
854 display: block;
855 text-align: center;
856 }
857
858 svg {
859 fill: currentColor;
860 }
861 `;
862 }
863
864 /** @override */
865 render() {
866 return html`
867 ${ICON_COPY}
868 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
869 `;
870 }
871}
872
873customElements.define('terminal-copy-notice', TerminalCopyNotice);