Debian Codegraph @

pkg/systemd/terminal.jsx

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 import cockpit from "cockpit";
3 import 'cockpit-dark-theme'; // once per page
4 import '../lib/patternfly/patternfly-6-cockpit.scss';
5
6 import React from "react";
7 import { createRoot } from "react-dom/client";
8 import { FormSelect, FormSelectOption } from "@patternfly/react-core/dist/esm/components/FormSelect/index.js";
9 import { NumberInput } from "@patternfly/react-core/dist/esm/components/NumberInput/index.js";
10 import { Toolbar, ToolbarContent, ToolbarGroup, ToolbarItem } from "@patternfly/react-core/dist/esm/components/Toolbar/index.js";
11 import { Alert, AlertActionCloseButton, AlertActionLink } from "@patternfly/react-core/dist/esm/components/Alert/index.js";
12 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
13 import { Page, PageSection } from "@patternfly/react-core/dist/esm/components/Page/index.js";
14 import { fsinfo } from "cockpit/fsinfo";
15
16 import "./terminal.scss";
17
18 import { Terminal } from "cockpit-components-terminal.jsx";
19 import { EmptyStatePanel } from "cockpit-components-empty-state";
20
21 const _ = cockpit.gettext;
22
23 (function() {
24 cockpit.translate();
25
26 /*
27 * A terminal component for the cockpit user.
28 *
29 * Uses the Terminal component from base1 internally, but adds a header
30 * with title and Reset button.
31 *
32 * Spawns the user's shell in the user's home directory.
33 */
34 class UserTerminal extends React.Component {
35 createChannel(user, dir) {
36 const ch = cockpit.channel({
37 payload: "stream",
38 spawn: [user.shell || "/bin/bash"],
39 environ: [
40 "TERM=xterm-256color",
41 ],
42 directory: dir || user.home || "/",
43 pty: true,
44 binary: true,
45 });
46 ch.addEventListener("ready", (_, msg) => this.setState({ pid: msg.pid }));
47 ch.addEventListener("close", () => this.setState({ pid: null }));
48 return ch;
49 }
50
51 constructor(props) {
52 super(props);
53
54 const theme = localStorage.getItem('terminal:theme');
55 const size = localStorage.getItem('terminal:font-size');
56
57 // Check if WebGL2 is available
58 // Only checking if WebGL2RenderingContext is defined is not sufficient, in Firefox tests it is defined
59 // as WebGL is enabled but it is not available in headless mode.
60 this.webglAvailable = !!document.createElement("canvas").getContext("webgl2");
61
62 this.state = {
63 title: 'Terminal',
64 theme: theme || "black-theme",
65 size: parseInt(size) || 16,
66 changePathBusy: false,
67 pathError: null,
68 pid: null,
69 user: null,
70 };
71 this.onTitleChanged = this.onTitleChanged.bind(this);
72 this.onResetClick = this.onResetClick.bind(this);
73 this.onThemeChanged = this.onThemeChanged.bind(this);
74 this.onPlus = this.onPlus.bind(this);
75 this.onMinus = this.onMinus.bind(this);
76 this.forceChangeDirectory = this.forceChangeDirectory.bind(this);
77 this.onNavigate = this.onNavigate.bind(this);
78 this.dismiss = this.dismiss.bind(this);
79
80 this.terminalRef = React.createRef();
81 this.resetButtonRef = React.createRef();
82
83 this.minSize = 6;
84 this.maxSize = 40;
85 }
86
87 async componentDidMount() {
88 cockpit.addEventListener("locationchanged", this.onNavigate);
89
90 let dir;
91 if (cockpit.location.options.path) {
92 const validPath = await this.readyPath();
93 if (validPath) {
94 dir = cockpit.location.options.path;
95 }
96 }
97 const user = await cockpit.user();
98 this.setState({ user, channel: this.createChannel(user, dir) });
99 }
100
101 componentWillUnmount() {
102 cockpit.removeEventListener("locationchanged", this.onNavigate);
103 }
104
105 onTitleChanged(title) {
106 this.setState({ title });
107 }
108
109 forceChangeDirectory() {
110 this.setState(prevState => ({
111 channel: this.createChannel(prevState.user, cockpit.location.options.path),
112 changePathBusy: false,
113 }));
114 this.terminalRef.current.focus();
115 }
116
117 dismiss() {
118 this.setState({
119 pathError: null,
120 changePathBusy: false,
121 });
122 cockpit.location.replace("");
123 this.terminalRef.current.focus();
124 }
125
126 async onNavigate() {
127 // Clear old path errors
128 this.setState({
129 pathError: null,
130 changePathBusy: false,
131 });
132
133 // If there's no path to change to, then we're done here
134 if (!cockpit.location.options.path) {
135 return;
136 }
137 const changeNow = await this.readyPath();
138 if (changeNow) {
139 const user = await cockpit.user();
140 this.setState({ channel: this.createChannel(user, cockpit.location.options.path) });
141 this.terminalRef.current.focus();
142 }
143 }
144
145 async readyPath() {
146 // Check if path we're changing to exists
147 try {
148 const info = await fsinfo(String(cockpit.location.options.path), ['type']);
149 if (info.type !== "dir") {
150 this.setState({ pathError: cockpit.format(_("$0 is not a directory"), cockpit.location.options.path) });
151 return false;
152 }
153 } catch (err) {
154 this.setState({ pathError: cockpit.format(_("$0 does not exist"), cockpit.location.options.path) });
155 return false;
156 }
157
158 if (this.state.pid !== null) {
159 // Check if current shell has a process running in it, ie it's busy
160 const command = "grep -qr '^PPid:[[:space:]]*" + this.state.pid + "$' /proc/*/status";
161 try {
162 await cockpit.script(command, [], { err: "message" });
163 this.setState({ changePathBusy: true });
164 return false;
165 } catch {
166 return true;
167 }
168 }
169 return true;
170 }
171
172 onPlus() {
173 this.setState((state, _) => {
174 localStorage.setItem('terminal:font-size', state.size + 1);
175 return { size: state.size + 1 };
176 });
177 this.terminalRef.current.focus();
178 }
179
180 onMinus() {
181 this.setState((state, _) => {
182 localStorage.setItem('terminal:font-size', state.size - 1);
183 return { size: state.size - 1 };
184 });
185 this.terminalRef.current.focus();
186 }
187
188 onThemeChanged(_, value) {
189 this.setState({ theme: value });
190 localStorage.setItem('terminal:theme', value);
191 this.terminalRef.current.focus();
192 }
193
194 onResetClick(event) {
195 if (event.button !== 0)
196 return;
197
198 if (!this.state.channel.valid && this.state.user)
199 this.setState(prevState => ({ channel: this.createChannel(prevState.user) }));
200 else
201 this.terminalRef.current.reset();
202
203 // don't focus the button, but keep it on the terminal
204 this.resetButtonRef.current.blur();
205 this.terminalRef.current.focus();
206 }
207
208 render() {
209 const terminal = this.state.channel
210 ? <Terminal ref={this.terminalRef}
211 channel={this.state.channel}
212 theme={this.state.theme}
213 fontSize={this.state.size}
214 parentId="cockpit-terminal"
215 onTitleChanged={this.onTitleChanged} />
216 : <span>Loading...</span>;
217
218 return (
219 <Page className="pf-m-no-sidebar">
220 <PageSection hasShadowBottom>
221 <div className="terminal-group">
222 <code className="terminal-title">{this.state.title}</code>
223 <Toolbar id="toolbar">
224 <ToolbarContent>
225 <ToolbarGroup>
226 <ToolbarItem variant="label" id="size-select">
227 {_("Font size")}
228 </ToolbarItem>
229 <ToolbarItem>
230 <NumberInput
231 className="font-size"
232 value={this.state.size}
233 min={this.minSize}
234 max={this.maxSize}
235 onMinus={this.onMinus}
236 onPlus={this.onPlus}
237 inputAriaLabel={_("Font size")}
238 minusBtnAriaLabel={_("Decrease by one")}
239 plusBtnAriaLabel={_("Increase by one")}
240 widthChars={2}
241 />
242 </ToolbarItem>
243 </ToolbarGroup>
244 <ToolbarGroup>
245 <ToolbarItem variant="label" id="theme-select">
246 {_("Appearance")}
247 </ToolbarItem>
248 <ToolbarItem>
249 <FormSelect onChange={this.onThemeChanged}
250 aria-labelledby="theme-select"
251 value={this.state.theme}>
252 <FormSelectOption value='black-theme' label={_("Black")} />
253 <FormSelectOption value='dark-theme' label={_("Dark")} />
254 <FormSelectOption value='light-theme' label={_("Light")} />
255 <FormSelectOption value='white-theme' label={_("White")} />
256 </FormSelect>
257 </ToolbarItem>
258 </ToolbarGroup>
259 <ToolbarItem>
260 <button ref={this.resetButtonRef}
261 disabled={!this.webglAvailable}
262 className="pf-v6-c-button pf-m-secondary terminal-reset"
263 onClick={this.onResetClick}>{_("Reset")}</button>
264 </ToolbarItem>
265 </ToolbarContent>
266 </Toolbar>
267 </div>
268 </PageSection>
269 <PageSection className="console-ct-container" isFilled hasBodyWrapper={false} padding={{ default: 'noPadding' }}>
270 <div className="ct-terminal-dir-alert">
271 {this.state.pathError && <Alert isInline
272 title={_("Unable to open directory")}
273 variant="warning"
274 actionClose={<AlertActionCloseButton onClose={this.dismiss} />}>
275 <p>{_(this.state.pathError)}</p>
276 </Alert>
277 }
278
279 {this.state.changePathBusy && <Alert isInline
280 title={_("Running process prevents directory change")}
281 variant="danger"
282 actionClose={<AlertActionCloseButton onClose={() =>
283 this.setState({ changePathBusy: false })} />}
284 actionLinks={
285 <>
286 <Button variant="danger" size="sm" onClick={this.forceChangeDirectory}>{_("Change directory")}</Button>
287 <AlertActionLink onClick={this.dismiss}>{_("Cancel")}</AlertActionLink>
288 </>
289 }>
290 {_("Changing the directory will forcefully stop the currently running process. The process can also be stopped manually in the terminal before continuing.")}
291 </Alert>
292 }
293 </div>
294 {this.webglAvailable
295 ? (<div className={"terminal-body " + this.state.theme} id="cockpit-terminal">
296 {terminal}
297 </div>)
298 : <EmptyStatePanel title={_("Terminal not available")} paragraph={_("This browser does not support WebGL2.")} />}
299 </PageSection>
300 </Page>
301 );
302 }
303 }
304 UserTerminal.displayName = "UserTerminal";
305
306 const root = createRoot(document.getElementById('terminal'));
307 root.render(<UserTerminal />);
308
309 /* And show the body */
310 document.body.removeAttribute("hidden");
311 }());