blob: b763c0e04adcd2bfff79be07e8e909a8fbd31535 [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';
16import {Terminal, FitAddon, WebglAddon} from './xterm.js';
Jason Linca61ffb2022-08-03 19:37:12 +100017
18const ANSI_COLOR_NAMES = [
19 'black',
20 'red',
21 'green',
22 'yellow',
23 'blue',
24 'magenta',
25 'cyan',
26 'white',
27 'brightBlack',
28 'brightRed',
29 'brightGreen',
30 'brightYellow',
31 'brightBlue',
32 'brightMagenta',
33 'brightCyan',
34 'brightWhite',
35];
36
37const PrefToXtermOptions = {
38 'font-family': 'fontFamily',
Jason Linca61ffb2022-08-03 19:37:12 +100039};
40
41/**
Jason Linabad7562022-08-22 14:49:05 +100042 * @typedef {{
43 * term: !Terminal,
44 * fontManager: !FontManager,
45 * fitAddon: !FitAddon,
46 * }}
47 */
48export let XtermTerminalTestParams;
49
50/**
Jason Lin21d854f2022-08-22 14:49:59 +100051 * A "terminal io" class for xterm. We don't want the vanilla hterm.Terminal.IO
52 * because it always convert utf8 data to strings, which is not necessary for
53 * xterm.
54 */
55class XtermTerminalIO extends hterm.Terminal.IO {
56 /** @override */
57 writeUTF8(buffer) {
58 this.terminal_.write(new Uint8Array(buffer));
59 }
60
61 /** @override */
62 writelnUTF8(buffer) {
63 this.terminal_.writeln(new Uint8Array(buffer));
64 }
65
66 /** @override */
67 print(string) {
68 this.terminal_.write(string);
69 }
70
71 /** @override */
72 writeUTF16(string) {
73 this.print(string);
74 }
75
76 /** @override */
77 println(string) {
78 this.terminal_.writeln(string);
79 }
80
81 /** @override */
82 writelnUTF16(string) {
83 this.println(string);
84 }
85}
86
87/**
Jason Linca61ffb2022-08-03 19:37:12 +100088 * A terminal class that 1) uses xterm.js and 2) behaves like a `hterm.Terminal`
89 * so that it can be used in existing code.
90 *
Jason Linca61ffb2022-08-03 19:37:12 +100091 * @extends {hterm.Terminal}
92 * @unrestricted
93 */
Jason Linabad7562022-08-22 14:49:05 +100094export class XtermTerminal {
Jason Linca61ffb2022-08-03 19:37:12 +100095 /**
96 * @param {{
97 * storage: !lib.Storage,
98 * profileId: string,
99 * enableWebGL: boolean,
Jason Linabad7562022-08-22 14:49:05 +1000100 * testParams: (!XtermTerminalTestParams|undefined),
Jason Linca61ffb2022-08-03 19:37:12 +1000101 * }} args
102 */
Jason Linabad7562022-08-22 14:49:05 +1000103 constructor({storage, profileId, enableWebGL, testParams}) {
Jason Lin21d854f2022-08-22 14:49:59 +1000104 this.profileId_ = profileId;
Jason Linca61ffb2022-08-03 19:37:12 +1000105 /** @type {!hterm.PreferenceManager} */
106 this.prefs_ = new hterm.PreferenceManager(storage, profileId);
107 this.enableWebGL_ = enableWebGL;
108
Jason Linabad7562022-08-22 14:49:05 +1000109 this.term = testParams?.term || new Terminal();
110 this.fontManager_ = testParams?.fontManager || fontManager;
111 this.fitAddon = testParams?.fitAddon || new FitAddon();
112
Jason Linca61ffb2022-08-03 19:37:12 +1000113 this.term.loadAddon(this.fitAddon);
Jason Linabad7562022-08-22 14:49:05 +1000114 this.scheduleFit_ = delayedScheduler(() => this.fitAddon.fit(),
115 testParams ? 0 : 250);
116
117 this.pendingFont_ = null;
118 this.scheduleRefreshFont_ = delayedScheduler(
119 () => this.refreshFont_(), 100);
120 document.fonts.addEventListener('loadingdone',
121 () => this.onFontLoadingDone_());
Jason Linca61ffb2022-08-03 19:37:12 +1000122
123 this.installUnimplementedStubs_();
124
Jason Lin21d854f2022-08-22 14:49:59 +1000125 this.term.onResize(({cols, rows}) => this.io.onTerminalResize(cols, rows));
126 // We could also use `this.io.sendString()` except for the nassh exit
127 // prompt, which only listens to onVTKeystroke().
128 this.term.onData((data) => this.io.onVTKeystroke(data));
Jason Lin6a402a72022-08-25 16:07:02 +1000129 this.term.onTitleChange((title) => document.title = title);
130 this.term.onSelectionChange(() => this.onSelectionChange_());
Jason Linca61ffb2022-08-03 19:37:12 +1000131
Jason Lin21d854f2022-08-22 14:49:59 +1000132 this.io = new XtermTerminalIO(this);
133 this.notificationCenter_ = null;
Jason Lin6a402a72022-08-25 16:07:02 +1000134
135 this.copyNotice_ = null;
136
137 this.term.options.theme = {
138 selection: 'rgba(174, 203, 250, .6)',
139 selectionForeground: 'black',
140 customGlyphs: true,
141 };
142 this.observePrefs_();
Jason Linca61ffb2022-08-03 19:37:12 +1000143 }
144
145 /**
146 * Install stubs for stuff that we haven't implemented yet so that the code
147 * still runs.
148 */
149 installUnimplementedStubs_() {
150 this.keyboard = {
151 keyMap: {
152 keyDefs: [],
153 },
154 bindings: {
155 clear: () => {},
156 addBinding: () => {},
157 addBindings: () => {},
158 OsDefaults: {},
159 },
160 };
161 this.keyboard.keyMap.keyDefs[78] = {};
162
163 const methodNames = [
Jason Linca61ffb2022-08-03 19:37:12 +1000164 'setAccessibilityEnabled',
165 'setBackgroundImage',
166 'setCursorPosition',
167 'setCursorVisible',
Jason Linca61ffb2022-08-03 19:37:12 +1000168 ];
169
170 for (const name of methodNames) {
171 this[name] = () => console.warn(`${name}() is not implemented`);
172 }
173
174 this.contextMenu = {
175 setItems: () => {
176 console.warn('.contextMenu.setItems() is not implemented');
177 },
178 };
Jason Lin21d854f2022-08-22 14:49:59 +1000179
180 this.vt = {
181 resetParseState: () => {
182 console.warn('.vt.resetParseState() is not implemented');
183 },
184 };
Jason Linca61ffb2022-08-03 19:37:12 +1000185 }
186
187 /**
188 * One-time initialization at the beginning.
189 */
190 async init() {
191 await new Promise((resolve) => this.prefs_.readStorage(resolve));
192 this.prefs_.notifyAll();
193 this.onTerminalReady();
194 }
195
Jason Lin21d854f2022-08-22 14:49:59 +1000196 /**
197 * Write data to the terminal.
198 *
199 * @param {string|!Uint8Array} data string for UTF-16 data, Uint8Array for
200 * UTF-8 data
201 */
202 write(data) {
203 this.term.write(data);
204 }
205
206 /**
207 * Like `this.write()` but also write a line break.
208 *
209 * @param {string|!Uint8Array} data
210 */
211 writeln(data) {
212 this.term.writeln(data);
213 }
214
Jason Linca61ffb2022-08-03 19:37:12 +1000215 get screenSize() {
216 return new hterm.Size(this.term.cols, this.term.rows);
217 }
218
219 /**
220 * Don't need to do anything.
221 *
222 * @override
223 */
224 installKeyboard() {}
225
226 /**
227 * @override
228 */
229 decorate(elem) {
230 this.term.open(elem);
Jason Lind04bab32022-08-22 14:48:39 +1000231 this.scheduleFit_();
Jason Linca61ffb2022-08-03 19:37:12 +1000232 if (this.enableWebGL_) {
233 this.term.loadAddon(new WebglAddon());
234 }
Jason Lin21d854f2022-08-22 14:49:59 +1000235 this.term.focus();
Jason Lind04bab32022-08-22 14:48:39 +1000236 (new ResizeObserver(() => this.scheduleFit_())).observe(elem);
Jason Lin21d854f2022-08-22 14:49:59 +1000237 // TODO: Make a11y work. Maybe we can just use `hterm.AccessibilityReader`.
238 this.notificationCenter_ = new hterm.NotificationCenter(document.body);
239 }
240
241 /** @override */
242 showOverlay(msg, timeout = 1500) {
243 if (this.notificationCenter_) {
244 this.notificationCenter_.show(msg, {timeout});
245 }
246 }
247
248 /** @override */
249 hideOverlay() {
250 if (this.notificationCenter_) {
251 this.notificationCenter_.hide();
252 }
Jason Linca61ffb2022-08-03 19:37:12 +1000253 }
254
255 /** @override */
256 getPrefs() {
257 return this.prefs_;
258 }
259
260 /** @override */
261 getDocument() {
262 return window.document;
263 }
264
Jason Lin21d854f2022-08-22 14:49:59 +1000265 /** @override */
266 reset() {
267 this.term.reset();
Jason Linca61ffb2022-08-03 19:37:12 +1000268 }
269
270 /** @override */
Jason Lin21d854f2022-08-22 14:49:59 +1000271 setProfile(profileId, callback = undefined) {
272 this.prefs_.setProfile(profileId, callback);
Jason Linca61ffb2022-08-03 19:37:12 +1000273 }
274
Jason Lin21d854f2022-08-22 14:49:59 +1000275 /** @override */
276 interpret(string) {
277 this.term.write(string);
Jason Linca61ffb2022-08-03 19:37:12 +1000278 }
279
Jason Lin21d854f2022-08-22 14:49:59 +1000280 /** @override */
281 focus() {
282 this.term.focus();
283 }
Jason Linca61ffb2022-08-03 19:37:12 +1000284
285 /** @override */
286 onOpenOptionsPage() {}
287
288 /** @override */
289 onTerminalReady() {}
290
Jason Lind04bab32022-08-22 14:48:39 +1000291 observePrefs_() {
292 for (const pref in PrefToXtermOptions) {
293 this.prefs_.addObserver(pref, (v) => {
294 this.updateOption_(PrefToXtermOptions[pref], v);
295 });
296 }
297
Jason Lin21d854f2022-08-22 14:49:59 +1000298 // This is for this.notificationCenter_.
299 const setHtermCSSVariable = (name, value) => {
300 document.body.style.setProperty(`--hterm-${name}`, value);
301 };
302
303 const setHtermColorCSSVariable = (name, color) => {
304 const css = lib.notNull(lib.colors.normalizeCSS(color));
305 const rgb = lib.colors.crackRGB(css).slice(0, 3).join(',');
306 setHtermCSSVariable(name, rgb);
307 };
308
309 this.prefs_.addObserver('font-size', (v) => {
310 this.updateOption_('fontSize', v);
311 setHtermCSSVariable('font-size', `${v}px`);
312 });
313
Jason Lind04bab32022-08-22 14:48:39 +1000314 // Theme-related preference items.
315 this.prefs_.addObservers(null, {
316 'background-color': (v) => {
317 this.updateTheme_({background: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000318 setHtermColorCSSVariable('background-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000319 },
320 'foreground-color': (v) => {
321 this.updateTheme_({foreground: v});
Jason Lin21d854f2022-08-22 14:49:59 +1000322 setHtermColorCSSVariable('foreground-color', v);
Jason Lind04bab32022-08-22 14:48:39 +1000323 },
324 'cursor-color': (v) => {
325 this.updateTheme_({cursor: v});
326 },
327 'color-palette-overrides': (v) => {
328 if (!(v instanceof Array)) {
329 // For terminal, we always expect this to be an array.
330 console.warn('unexpected color palette: ', v);
331 return;
332 }
333 const colors = {};
334 for (let i = 0; i < v.length; ++i) {
335 colors[ANSI_COLOR_NAMES[i]] = v[i];
336 }
337 this.updateTheme_(colors);
338 },
339 });
340 }
341
342 /**
343 * @param {!Object} theme
344 */
345 updateTheme_(theme) {
346 const newTheme = {...this.term.options.theme};
347 for (const key in theme) {
348 newTheme[key] = lib.colors.normalizeCSS(theme[key]);
349 }
350 this.updateOption_('theme', newTheme);
351 }
352
353 /**
354 * Update one xterm.js option.
355 *
356 * @param {string} key
357 * @param {*} value
358 */
359 updateOption_(key, value) {
Jason Linabad7562022-08-22 14:49:05 +1000360 if (key === 'fontFamily') {
361 this.updateFont_(/** @type {string} */(value));
362 return;
363 }
Jason Lind04bab32022-08-22 14:48:39 +1000364 // TODO: xterm supports updating multiple options at the same time. We
365 // should probably do that.
366 this.term.options[key] = value;
367 this.scheduleFit_();
368 }
Jason Linabad7562022-08-22 14:49:05 +1000369
370 /**
371 * Called when there is a "fontloadingdone" event. We need this because
372 * `FontManager.loadFont()` does not guarantee loading all the font files.
373 */
374 async onFontLoadingDone_() {
375 // If there is a pending font, the font is going to be refresh soon, so we
376 // don't need to do anything.
377 if (!this.pendingFont_) {
378 this.scheduleRefreshFont_();
379 }
380 }
381
Jason Lin6a402a72022-08-25 16:07:02 +1000382 onSelectionChange_() {
383 const selection = this.term.getSelection();
384 if (!selection) {
385 return;
386 }
387 navigator.clipboard?.writeText(selection);
388 if (!this.copyNotice_) {
389 this.copyNotice_ = document.createElement('terminal-copy-notice');
390 }
391 setTimeout(() => this.showOverlay(lib.notNull(this.copyNotice_), 500), 200);
392 }
393
Jason Linabad7562022-08-22 14:49:05 +1000394 /**
395 * Refresh xterm rendering for a font related event.
396 */
397 refreshFont_() {
398 // We have to set the fontFamily option to a different string to trigger the
399 // re-rendering. Appending a space at the end seems to be the easiest
400 // solution. Note that `clearTextureAtlas()` and `refresh()` do not work for
401 // us.
402 //
403 // TODO: Report a bug to xterm.js and ask for exposing a public function for
404 // the refresh so that we don't need to do this hack.
405 this.term.options.fontFamily += ' ';
406 }
407
408 /**
409 * Update a font.
410 *
411 * @param {string} cssFontFamily
412 */
413 async updateFont_(cssFontFamily) {
Jason Lin6a402a72022-08-25 16:07:02 +1000414 this.pendingFont_ = cssFontFamily;
415 await this.fontManager_.loadFont(cssFontFamily);
416 // Sleep a bit to wait for flushing fontloadingdone events. This is not
417 // strictly necessary, but it should prevent `this.onFontLoadingDone_()`
418 // to refresh font unnecessarily in some cases.
419 await sleep(30);
Jason Linabad7562022-08-22 14:49:05 +1000420
Jason Lin6a402a72022-08-25 16:07:02 +1000421 if (this.pendingFont_ !== cssFontFamily) {
422 // `updateFont_()` probably is called again. Abort what we are doing.
423 console.log(`pendingFont_ (${this.pendingFont_}) is changed` +
424 ` (expecting ${cssFontFamily})`);
425 return;
426 }
Jason Linabad7562022-08-22 14:49:05 +1000427
Jason Lin6a402a72022-08-25 16:07:02 +1000428 if (this.term.options.fontFamily !== cssFontFamily) {
429 this.term.options.fontFamily = cssFontFamily;
430 } else {
431 // If the font is already the same, refresh font just to be safe.
432 this.refreshFont_();
433 }
434 this.pendingFont_ = null;
435 this.scheduleFit_();
Jason Linabad7562022-08-22 14:49:05 +1000436 }
Jason Linca61ffb2022-08-03 19:37:12 +1000437}
438
Jason Lind66e6bf2022-08-22 14:47:10 +1000439class HtermTerminal extends hterm.Terminal {
440 /** @override */
441 decorate(div) {
442 super.decorate(div);
443
444 const fontManager = new FontManager(this.getDocument());
445 fontManager.loadPowerlineCSS().then(() => {
446 const prefs = this.getPrefs();
447 fontManager.loadFont(/** @type {string} */(prefs.get('font-family')));
448 prefs.addObserver(
449 'font-family',
450 (v) => fontManager.loadFont(/** @type {string} */(v)));
451 });
452 }
453}
454
Jason Linca61ffb2022-08-03 19:37:12 +1000455/**
456 * Constructs and returns a `hterm.Terminal` or a compatible one based on the
457 * preference value.
458 *
459 * @param {{
460 * storage: !lib.Storage,
461 * profileId: string,
462 * }} args
463 * @return {!Promise<!hterm.Terminal>}
464 */
465export async function createEmulator({storage, profileId}) {
466 let config = TERMINAL_EMULATORS.get('hterm');
467
468 if (getOSInfo().alternative_emulator) {
Jason Lin21d854f2022-08-22 14:49:59 +1000469 // TODO: remove the url param logic. This is temporary to make manual
470 // testing a bit easier, which is also why this is not in
471 // './js/terminal_info.js'.
472 const emulator = ORIGINAL_URL.searchParams.get('emulator') ||
473 await storage.getItem(`/hterm/profiles/${profileId}/terminal-emulator`);
Jason Linca61ffb2022-08-03 19:37:12 +1000474 // Use the default (i.e. first) one if the pref is not set or invalid.
Jason Lin21d854f2022-08-22 14:49:59 +1000475 config = TERMINAL_EMULATORS.get(emulator) ||
Jason Linca61ffb2022-08-03 19:37:12 +1000476 TERMINAL_EMULATORS.values().next().value;
477 console.log('Terminal emulator config: ', config);
478 }
479
480 switch (config.lib) {
481 case 'xterm.js':
482 {
483 const terminal = new XtermTerminal({
484 storage,
485 profileId,
486 enableWebGL: config.webgl,
487 });
488 // Don't await it so that the caller can override
489 // `terminal.onTerminalReady()` before the terminal is ready.
490 terminal.init();
491 return terminal;
492 }
493 case 'hterm':
Jason Lind66e6bf2022-08-22 14:47:10 +1000494 return new HtermTerminal({profileId, storage});
Jason Linca61ffb2022-08-03 19:37:12 +1000495 default:
496 throw new Error('incorrect emulator config');
497 }
498}
499
Jason Lin6a402a72022-08-25 16:07:02 +1000500class TerminalCopyNotice extends LitElement {
501 /** @override */
502 static get styles() {
503 return css`
504 :host {
505 display: block;
506 text-align: center;
507 }
508
509 svg {
510 fill: currentColor;
511 }
512 `;
513 }
514
515 /** @override */
516 render() {
517 return html`
518 ${ICON_COPY}
519 <div>${hterm.messageManager.get('HTERM_NOTIFY_COPY')}</div>
520 `;
521 }
522}
523
524customElements.define('terminal-copy-notice', TerminalCopyNotice);