Debian Codegraph @

pkg/lib/cockpit-components-terminal.tsx

raw
1 /*
2 * Copyright (C) 2016 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import React from "react";
7 import {
8 Modal, ModalBody, ModalFooter, ModalHeader
9 } from '@patternfly/react-core/dist/esm/components/Modal/index.js';
10 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
11 import { MenuList, MenuItem } from "@patternfly/react-core/dist/esm/components/Menu";
12 import { WebglAddon } from '@xterm/addon-webgl';
13 import { Terminal as Term } from "@xterm/xterm";
14
15 import { ContextMenu } from "cockpit-components-context-menu.jsx";
16 import cockpit from "cockpit";
17
18 import "console.css";
19
20 const _ = cockpit.gettext;
21
22 const theme_core = {
23 yellow: "#b58900",
24 brightRed: "#cb4b16",
25 red: "#dc322f",
26 magenta: "#d33682",
27 brightMagenta: "#6c71c4",
28 blue: "#268bd2",
29 cyan: "#2aa198",
30 green: "#859900"
31 };
32
33 const themes = {
34 "black-theme": {
35 background: "#000000",
36 foreground: "#ffffff"
37 },
38 "dark-theme": Object.assign({}, theme_core, {
39 background: "#002b36",
40 foreground: "#fdf6e3",
41 cursor: "#eee8d5",
42 selection: "#ffffff77",
43 brightBlack: "#002b36",
44 black: "#073642",
45 brightGreen: "#586e75",
46 brightYellow: "#657b83",
47 brightBlue: "#839496",
48 brightCyan: "#93a1a1",
49 white: "#eee8d5",
50 brightWhite: "#fdf6e3"
51 }),
52 "light-theme": Object.assign({}, theme_core, {
53 background: "#fdf6e3",
54 foreground: "#002b36",
55 cursor: "#073642",
56 selection: "#00000044",
57 brightWhite: "#002b36",
58 white: "#073642",
59 brightCyan: "#586e75",
60 brightBlue: "#657b83",
61 brightYellow: "#839496",
62 brightGreen: "#93a1a1",
63 black: "#eee8d5",
64 brightBlack: "#fdf6e3"
65 }),
66 "white-theme": {
67 background: "#ffffff",
68 foreground: "#000000",
69 selection: "#00000044",
70 cursor: "#000000",
71 },
72 };
73
74 export type TerminalTheme = keyof typeof themes;
75
76 /*
77 * A terminal component that communicates over a cockpit channel.
78 *
79 * The state of a terminal component can be managed separately from
80 * it. This allows a terminal to stay alive and keep its content while
81 * it is not actually part of the DOM.
82 *
83 * This is done by creating a TerminalState object for the channel,
84 * and then passing this object into a Terminal component via the
85 * "state" property. You can dispose of the TerminalState object by
86 * calling its close() method. This will also close the channel.
87 *
88 * (So instead of managing the lifetime of a Cockpit channel, you
89 * manage the lifetime of a TerminalState wrapper for the channel, in
90 * exactly the same way.)
91 *
92 * If you don't need to keep a terminal alive while it is not part of
93 * the DOM, you can pass the channel directly into the Terminal
94 * component via the "channel" property. The Terminal component will
95 * then maintain a internal TerminalState wrapper for the channel.
96 *
97 * The "state" and "channel" properties are of course mutually
98 * exclusive: You can only use one of them for a given Terminal
99 * component. Also, switching from one to the other over the lifetime
100 * of a Terminal component is not supported.
101 *
102 * The size of the terminal can be set with the 'rows' and 'cols'
103 * properties. If those properties are not given, the terminal will
104 * fill its container.
105 *
106 * If the 'onTitleChanged' callback property is set, it will be called
107 * whenever the title of the terminal changes.
108 *
109 * Call focus() on the Terminal component to set the input focus on
110 * the terminal, or reset() to clear it.
111 *
112 * Also it is possible to set up theme by property 'theme'.
113 */
114
115 export class TerminalState {
116 terminal: Term;
117 wrapper_element: HTMLDivElement;
118 channel: cockpit.Channel<string>;
119
120 constructor(channel: cockpit.Channel<string>) {
121 this.terminal = new Term({
122 cols: 80,
123 rows: 1,
124 cursorBlink: true,
125 fontSize: 16,
126 fontFamily: 'Menlo, Monaco, Consolas, monospace',
127 screenReaderMode: true,
128 });
129 this.terminal.loadAddon(new WebglAddon());
130 this.wrapper_element = document.createElement("div");
131 this.channel = channel;
132 this.#connectChannel(channel);
133 }
134
135 #connectChannel(channel: cockpit.Channel<string>) {
136 channel.addEventListener('message', (_event, data) => {
137 this.terminal.write(data);
138 });
139
140 this.terminal.onData(data => {
141 if (channel.valid) {
142 /* HACK: Ctrl+Space (and possibly other
143 * characters) is a disaster: While it is U+00A0
144 * in unicode, with an UTF-8 representation of
145 * 0xC2A0, the "visible" string in JS is 0x00
146 * (with TextEncoder, btoa(), and string
147 * comparison). The internal representation
148 * retains half of it, and trying to send it to
149 * the websocket would result in a single 0xA0,
150 * which is invalid UTF-8 (and causes the session
151 * to crash). So intercept and ignore such broken
152 * chars. See
153 * https://github.com/cockpit-project/cockpit/issues/21213 */
154 if (data === '\x00') {
155 console.log("terminal: ignoring invalid input", data);
156 return;
157 }
158 channel.send(data);
159 }
160 });
161
162 channel.addEventListener('close', (_event, options) => {
163 const term = this.terminal;
164 term.write('\x1b[31m' + (options.problem || 'disconnected') + '\x1b[m\r\n');
165 term.refresh(term.rows, term.rows);
166 });
167 }
168
169 resetChannel(channel: cockpit.Channel<string>) {
170 this.channel.close();
171 this.terminal.reset();
172 this.channel = channel;
173 this.#connectChannel(channel);
174 }
175
176 close() {
177 this.channel.close();
178 this.terminal.dispose();
179 }
180 }
181
182 interface TerminalComponentProps {
183 parentId: string;
184 state?: TerminalState;
185 channel?: cockpit.Channel<string>;
186 onTitleChanged?: (title: string) => void;
187 fontSize?: number;
188 rows?: number;
189 cols?: number;
190 theme?: TerminalTheme;
191 }
192
193 interface TerminalComponentState {
194 showPastingModal: boolean,
195 cols: number,
196 rows: number
197 }
198
199 export class Terminal extends React.Component<TerminalComponentProps, TerminalComponentState> {
200 terminal_state: TerminalState;
201 terminalRef: React.RefObject<HTMLDivElement>;
202 terminal: Term;
203
204 constructor(props: TerminalComponentProps) {
205 super(props);
206 this.reset = this.reset.bind(this);
207 this.focus = this.focus.bind(this);
208 this.onWindowResize = this.onWindowResize.bind(this);
209 this.resizeTerminal = this.resizeTerminal.bind(this);
210 this.onFocusIn = this.onFocusIn.bind(this);
211 this.onFocusOut = this.onFocusOut.bind(this);
212 this.setText = this.setText.bind(this);
213 this.getText = this.getText.bind(this);
214 this.setTerminalTheme = this.setTerminalTheme.bind(this);
215
216 if (this.props.state) {
217 cockpit.assert(!this.props.channel);
218 this.terminal_state = this.props.state;
219 } else {
220 cockpit.assert(this.props.channel);
221 this.terminal_state = new TerminalState(this.props.channel);
222 }
223
224 const term = this.terminal_state.terminal;
225
226 this.terminalRef = React.createRef<HTMLDivElement>();
227
228 if (props.onTitleChanged)
229 term.onTitleChange(props.onTitleChanged);
230
231 this.terminal = term;
232 this.state = {
233 showPastingModal: false,
234 cols: term.cols,
235 rows: term.rows
236 };
237 }
238
239 mountTerminal(state: TerminalState) {
240 this.terminal = state.terminal;
241 this.terminalRef.current?.appendChild(state.wrapper_element);
242 this.terminal.open(state.wrapper_element);
243
244 if (this.props.fontSize)
245 this.terminal.options.fontSize = this.props.fontSize;
246
247 if (this.props.cols && this.props.rows) {
248 this.resizeTerminal(this.props.cols, this.props.rows);
249 }
250
251 this.setTerminalTheme(this.props.theme || 'black-theme');
252 this.terminal.focus();
253 }
254
255 unmountTerminal(state: TerminalState) {
256 this.terminalRef.current?.removeChild(state.wrapper_element);
257 // This makes sure that the terminal will not cause its new
258 // container to grow when it is reattached later.
259 if (!this.props.rows)
260 this.resizeTerminal(80, 1);
261 }
262
263 componentDidMount() {
264 this.mountTerminal(this.terminal_state);
265 if (!this.props.rows) {
266 window.addEventListener('resize', this.onWindowResize);
267 this.onWindowResize();
268 }
269 }
270
271 resizeTerminal(cols: number, rows: number) {
272 this.terminal.resize(cols, rows);
273 if (this.terminal_state.channel) {
274 this.terminal_state.channel.control({
275 window: {
276 rows,
277 cols
278 }
279 } as cockpit.JsonObject as cockpit.ControlMessage);
280 }
281 }
282
283 componentDidUpdate(prevProps: TerminalComponentProps, prevState: TerminalComponentState) {
284 const hadFocus = this.terminal_state.wrapper_element.matches(":focus-within");
285
286 if (this.props.state && prevProps.state !== this.props.state) {
287 cockpit.assert(!this.props.channel);
288 cockpit.assert(prevProps.state);
289 this.unmountTerminal(prevProps.state);
290 this.terminal_state = this.props.state;
291 this.mountTerminal(this.terminal_state);
292 if (!this.props.cols || !this.props.rows)
293 this.resizeTerminal(this.state.cols, this.state.rows);
294 }
295
296 if (this.props.channel && prevProps.channel !== this.props.channel) {
297 cockpit.assert(!this.props.state);
298 this.terminal_state.resetChannel(this.props.channel);
299 if (!this.props.cols || !this.props.rows)
300 this.resizeTerminal(this.state.cols, this.state.rows);
301 }
302
303 if (this.props.fontSize && prevProps.fontSize !== this.props.fontSize) {
304 this.terminal.options.fontSize = this.props.fontSize;
305
306 // After font size is changed, resize needs to be triggered
307 const dimensions = this.calculateDimensions();
308 if (dimensions.cols !== this.state.cols || dimensions.rows !== this.state.rows) {
309 this.onWindowResize();
310 } else {
311 // When font size changes but dimensions are the same, we need to force `resize`
312 this.resizeTerminal(dimensions.cols - 1, dimensions.rows);
313 }
314 }
315
316 if (prevState.cols !== this.state.cols || prevState.rows !== this.state.rows)
317 this.resizeTerminal(this.state.cols, this.state.rows);
318
319 if (this.props.theme && prevProps.theme !== this.props.theme)
320 this.setTerminalTheme(this.props.theme);
321
322 if (hadFocus)
323 this.terminal.focus();
324 }
325
326 render() {
327 const contextMenuList = (
328 <MenuList>
329 <MenuItem className="contextMenuOption" onClick={this.getText}>
330 <div className="contextMenuName"> { _("Copy") } </div>
331 <div className="contextMenuShortcut">{ _("Ctrl+Insert") }</div>
332 </MenuItem>
333 <MenuItem className="contextMenuOption" onClick={this.setText}>
334 <div className="contextMenuName"> { _("Paste") } </div>
335 <div className="contextMenuShortcut">{ _("Shift+Insert") }</div>
336 </MenuItem>
337 </MenuList>
338 );
339
340 return (
341 <>
342 <Modal position="top"
343 variant="small"
344 isOpen={this.state.showPastingModal}
345 onClose={() => this.setState({ showPastingModal: false })}>
346 <ModalHeader title={_("Paste error")} />
347 <ModalBody>
348 {_("Your browser does not allow paste from the context menu. You can use Shift+Insert.")}
349 </ModalBody>
350 <ModalFooter>
351 <Button key="cancel" variant="secondary" onClick={() => this.setState({ showPastingModal: false })}>
352 {_("Close")}
353 </Button>
354 </ModalFooter>
355 </Modal>
356 <div ref={this.terminalRef}
357 className="console-ct"
358 onFocus={this.onFocusIn}
359 onBlur={this.onFocusOut} />
360 <ContextMenu parentId={this.props.parentId}>
361 {contextMenuList}
362 </ContextMenu>
363 </>
364 );
365 }
366
367 componentWillUnmount() {
368 window.removeEventListener('resize', this.onWindowResize);
369 this.onFocusOut();
370 this.unmountTerminal(this.terminal_state);
371 if (!this.props.state)
372 this.terminal_state.close();
373 }
374
375 setText() {
376 try {
377 navigator.clipboard.readText()
378 .then(text => this.terminal_state.channel?.send(text))
379 .catch(() => this.setState({ showPastingModal: true }))
380 .finally(() => this.terminal.focus());
381 } catch {
382 this.setState({ showPastingModal: true });
383 }
384 }
385
386 getText() {
387 try {
388 navigator.clipboard.writeText(this.terminal.getSelection())
389 .catch(e => console.error('Text could not be copied, use Ctrl+Insert ', e ? e.toString() : ""))
390 .finally(() => this.terminal.focus());
391 } catch (error) {
392 console.error('Text could not be copied, use Ctrl+Insert:', String(error));
393 }
394 }
395
396 reset() {
397 this.terminal.reset();
398 this.terminal_state.channel?.send(String.fromCharCode(12)); // Send SIGWINCH to show prompt on attaching
399 }
400
401 focus() {
402 if (this.terminal)
403 this.terminal.focus();
404 }
405
406 calculateDimensions() {
407 const padding = 10; // Leave a bit of space around terminal
408 // @ts-expect-error: we are accessing internals here...
409 const core = this.terminal._core;
410 const realHeight = core._renderService.dimensions.css.cell.height;
411 const realWidth = core._renderService.dimensions.css.cell.width;
412 const parentHeight = this.terminalRef.current?.parentElement?.clientHeight;
413 const parentWidth = this.terminalRef.current?.parentElement?.clientWidth;
414 if (realHeight && realWidth && realWidth !== 0 && realHeight !== 0 && parentHeight && parentWidth)
415 return {
416 // it can happen that parent{Width,Height} are not yet initialized (0), avoid negative values
417 rows: Math.max(Math.floor((parentHeight - padding) / realHeight), 1),
418 cols: Math.max(Math.floor((parentWidth - padding - 12) / realWidth), 1) // Remove 12px for scrollbar
419 };
420
421 return { rows: this.state.rows, cols: this.state.cols };
422 }
423
424 onWindowResize() {
425 this.setState(this.calculateDimensions());
426 }
427
428 setTerminalTheme(theme: TerminalTheme) {
429 this.terminal.options.theme = themes[theme];
430 }
431
432 onBeforeUnload(event: Event) {
433 // Firefox requires this when the page is in an iframe
434 event.preventDefault();
435
436 // Included for legacy support, e.g. Chrome/Edge < 119
437 event.returnValue = true;
438 }
439
440 onFocusIn() {
441 window.addEventListener('beforeunload', this.onBeforeUnload);
442 }
443
444 onFocusOut() {
445 window.removeEventListener('beforeunload', this.onBeforeUnload);
446 }
447 }