Skip to content

LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.

Session: Restart… and Shut Down… in the crown menu and the Classic start menu

Federico Pereira10a0282c2138
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5392edc..0c3e8e5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -43,6 +43,12 @@ of the matching [GitHub release](https://github.com/lordbasex/LordOS/releases),
shutdown and restart from the hypervisor, time sync and the guest's IP address. Its services only
run under VMware. Shared clipboard and automatic screen resize are not supported yet
([docs/ISO.md](docs/ISO.md#firmware-and-displays)).
+- **Restart… and Shut Down… in the crown menu** (and behind a Power button in the Classic theme's
+ start menu); before, they were only on the login screen. Each opens a confirmation that does it
+ by itself after 60 seconds unless cancelled, lists the apps still open and warns when other users
+ are logged in. The session asks `lord-sessiond`, which only accepts those two words: any user may
+ do it alone, and only an administrator while other users have sessions open
+ ([docs/SESSIONS.md](docs/SESSIONS.md#restart-and-shut-down-from-a-session)).
### Changed
diff --git a/assets/locales/en/shell.json b/assets/locales/en/shell.json
index c17421f..876f38c 100644
--- a/assets/locales/en/shell.json
+++ b/assets/locales/en/shell.json
@@ -132,5 +132,31 @@
"trash.empty": "Empty Trash",
"trash.confirmTitle": "Empty the Trash?",
"trash.confirmDetail": "Everything in the Trash will be deleted permanently. You can’t undo this action.",
- "trash.cancel": "Cancel"
+ "trash.cancel": "Cancel",
+ "menu.restart": "Restart…",
+ "menu.shutdown": "Shut Down…",
+ "menu.power": "Power",
+ "power.restartTitle": "Restart the computer now?",
+ "power.shutdownTitle": "Shut down the computer now?",
+ "power.restartCountdown": {
+ "one": "If you do nothing, the computer will restart in {count} second.",
+ "other": "If you do nothing, the computer will restart in {count} seconds."
+ },
+ "power.shutdownCountdown": {
+ "one": "If you do nothing, the computer will shut down in {count} second.",
+ "other": "If you do nothing, the computer will shut down in {count} seconds."
+ },
+ "power.apps": "Open apps: {list}. They will be closed: save your work first.",
+ "power.others": {
+ "one": "{list} is also logged in and may lose unsaved work.",
+ "other": "{count} other users are logged in ({list}) and may lose unsaved work."
+ },
+ "power.needAdminRestart": "Only an administrator can restart the computer while other users are logged in.",
+ "power.needAdminShutdown": "Only an administrator can shut down the computer while other users are logged in.",
+ "power.unavailable": "This session can’t restart or shut down the computer.",
+ "power.restarting": "Restarting…",
+ "power.shuttingDown": "Shutting down…",
+ "power.restart": "Restart",
+ "power.shutdown": "Shut Down",
+ "power.cancel": "Cancel"
}
diff --git a/assets/locales/es/shell.json b/assets/locales/es/shell.json
index e2b66a6..12c054e 100644
--- a/assets/locales/es/shell.json
+++ b/assets/locales/es/shell.json
@@ -132,5 +132,31 @@
"trash.empty": "Vaciar Papelera",
"trash.confirmTitle": "¿Vaciar la Papelera?",
"trash.confirmDetail": "Todo lo que hay en la Papelera se borrará para siempre. No se puede deshacer.",
- "trash.cancel": "Cancelar"
+ "trash.cancel": "Cancelar",
+ "menu.restart": "Reiniciar…",
+ "menu.shutdown": "Apagar…",
+ "menu.power": "Apagar",
+ "power.restartTitle": "¿Reiniciar la computadora ahora?",
+ "power.shutdownTitle": "¿Apagar la computadora ahora?",
+ "power.restartCountdown": {
+ "one": "Si no hacés nada, la computadora se reiniciará en {count} segundo.",
+ "other": "Si no hacés nada, la computadora se reiniciará en {count} segundos."
+ },
+ "power.shutdownCountdown": {
+ "one": "Si no hacés nada, la computadora se apagará en {count} segundo.",
+ "other": "Si no hacés nada, la computadora se apagará en {count} segundos."
+ },
+ "power.apps": "Apps abiertas: {list}. Se van a cerrar: guardá tu trabajo antes.",
+ "power.others": {
+ "one": "{list} también tiene la sesión abierta y puede perder trabajo sin guardar.",
+ "other": "Hay {count} usuarios más con la sesión abierta ({list}) que pueden perder trabajo sin guardar."
+ },
+ "power.needAdminRestart": "Solo un administrador puede reiniciar la computadora mientras otros usuarios tienen la sesión abierta.",
+ "power.needAdminShutdown": "Solo un administrador puede apagar la computadora mientras otros usuarios tienen la sesión abierta.",
+ "power.unavailable": "Esta sesión no puede reiniciar ni apagar la computadora.",
+ "power.restarting": "Reiniciando…",
+ "power.shuttingDown": "Apagando…",
+ "power.restart": "Reiniciar",
+ "power.shutdown": "Apagar",
+ "power.cancel": "Cancelar"
}
diff --git a/assets/locales/pt/shell.json b/assets/locales/pt/shell.json
index e574cbd..019b067 100644
--- a/assets/locales/pt/shell.json
+++ b/assets/locales/pt/shell.json
@@ -132,5 +132,31 @@
"trash.empty": "Esvaziar Lixo",
"trash.confirmTitle": "Esvaziar o Lixo?",
"trash.confirmDetail": "Tudo o que está no Lixo será apagado permanentemente. Não é possível desfazer.",
- "trash.cancel": "Cancelar"
+ "trash.cancel": "Cancelar",
+ "menu.restart": "Reiniciar…",
+ "menu.shutdown": "Desligar…",
+ "menu.power": "Energia",
+ "power.restartTitle": "Reiniciar o computador agora?",
+ "power.shutdownTitle": "Desligar o computador agora?",
+ "power.restartCountdown": {
+ "one": "Se você não fizer nada, o computador será reiniciado em {count} segundo.",
+ "other": "Se você não fizer nada, o computador será reiniciado em {count} segundos."
+ },
+ "power.shutdownCountdown": {
+ "one": "Se você não fizer nada, o computador será desligado em {count} segundo.",
+ "other": "Se você não fizer nada, o computador será desligado em {count} segundos."
+ },
+ "power.apps": "Apps abertos: {list}. Eles serão fechados: salve seu trabalho antes.",
+ "power.others": {
+ "one": "{list} também tem uma sessão aberta e pode perder trabalho não salvo.",
+ "other": "Há mais {count} usuários com sessão aberta ({list}) que podem perder trabalho não salvo."
+ },
+ "power.needAdminRestart": "Só um administrador pode reiniciar o computador enquanto outros usuários têm sessão aberta.",
+ "power.needAdminShutdown": "Só um administrador pode desligar o computador enquanto outros usuários têm sessão aberta.",
+ "power.unavailable": "Esta sessão não pode reiniciar nem desligar o computador.",
+ "power.restarting": "Reiniciando…",
+ "power.shuttingDown": "Desligando…",
+ "power.restart": "Reiniciar",
+ "power.shutdown": "Desligar",
+ "power.cancel": "Cancelar"
}
diff --git a/docs/LAYERS.md b/docs/LAYERS.md
index f34f03d..f69f6e9 100644
--- a/docs/LAYERS.md
+++ b/docs/LAYERS.md
@@ -42,7 +42,7 @@ in it, so an empty part of a layer lets the click through to whatever is below.
| `floating` | 30 | fullscreen and picture-in-picture windows |
| `overlay` | 40 | the app launcher, search |
| `popover` | 50 | menus, context menus, the Dock's menus, the Control Center, select lists, popovers, the clipboard and emoji panels, the Classic start menu |
-| `modal` | 60 | shell sheets and confirmations (Empty Trash), the print dialog |
+| `modal` | 60 | shell sheets and confirmations (Empty Trash, Restart…, Shut Down…), the print dialog |
| `notification` | 70 | notification banners, the clipboard toast, the remote desktop badge |
| `tooltip` | 80 | tooltips (the Dock's names) |
| `drag` | 90 | drag images, the Dock's «poof» |
diff --git a/docs/SESSIONS.md b/docs/SESSIONS.md
index 10f0234..f1fd031 100644
--- a/docs/SESSIONS.md
+++ b/docs/SESSIONS.md
@@ -216,6 +216,41 @@ after that the wait is 1, 2, 4… seconds, up to 5 minutes.
In the SDK: `session.lock()`, `session.switchUser()` and `session.managed()`. The `default` and
`classic` themes show those items only if `managed()` is true.
+### Restart and Shut Down from a session
+
+Since 0.8.1 the crown menu ends with **Restart…** and **Shut Down…**, after Lock Screen, Switch
+User… and Log Out; the Classic theme has them behind a **Power** button at the bottom of its start
+menu. Before, they were only on the login screen. Sleep is not offered: suspend and resume with the
+card lent to a session has not been tested on real hardware yet.
+
+| | |
+|---|---|
+| ![crown menu](session-power-menu-light.png) | ![crown menu, dark](session-power-menu-dark.png) |
+| ![restart confirmation](session-power-restart-light.png) | ![restart confirmation, dark](session-power-restart-dark.png) |
+| ![Classic start menu, Power](session-power-classic-light.png) | ![Classic, dark](session-power-classic-dark.png) |
+
+- **The confirmation** (`sdk/power.jsx`, `<PowerDialog>`, in the `modal` layer; a theme renders it
+ inside its `ThemeProvider`) says what will happen and counts down 60 seconds; at zero it does it,
+ as if confirmed. Cancel, Escape or a click outside stops it. It lists the apps that are open
+ (they are closed; there is no "unsaved changes" signal to read yet) and the other users with a
+ session open.
+- **The request:** `session.restart()` / `session.shutdown()` → `lord.session.power('reboot'|'poweroff')`
+ (`js_sys.c`), which only knows those two words and sends a fixed `RP_SESSION`
+ `{"a":"power","p":"reboot"|"poweroff"}`. lord-server runs nothing.
+- **The decision is lord-sessiond's** (`session_power` in `sessiond.c`), and only for the session
+ that is on the monitor (its connection is the only one it reads requests from):
+ - the user is alone (no other user has a session): any user may restart or shut down;
+ - other users have sessions open: only an administrator (`sudo`, `admin` or `wheel`, the same
+ rule as the admin actions in `admin.c`). The sheet says so beforehand and hides the button; if
+ it changed in between, lord-sessiond answers `{t:'power', ok:false, why:'admin'}` over the login
+ screen's channel (`RP_GREETER_IN`) and the sheet shows the refusal.
+ - then the same closed path as the login screen: `systemctl reboot` or `poweroff`, fixed path,
+ fixed environment, logged as `reboot requested by <user> (<n> other session(s) open)`.
+- **Tested on VM 122:** the menu items, the sheet in light and dark, the countdown, Cancel and
+ Escape (no restart after the minute), the Classic Power button, a real Shut Down (`qm start` back
+ to the login screen) and a real Restart (back to the login screen). The refusal with other users
+ logged in was checked in the code path only: it needs a second account's password on the VM.
+
## cgroups: one subtree per session
Each app in a session goes into its own cgroup v2 (a «scope») so monitoring can attribute traffic
@@ -316,7 +351,7 @@ session. Everything that changes something goes through closed `admin.c` actions
| Process | Runs as | What it can do |
|-----------------------------------|-----------------|------------------------------------------------------------------|
-| `lord-sessiond` (main) | root | reads shadow, opens and lends the card and input, creates sessions, reboots; doesn't read pixels |
+| `lord-sessiond` (main) | root | reads shadow, opens and lends the card and input, creates sessions, reboots or shuts down (login screen, or the monitor's session under the rule above); doesn't read pixels |
| `lord-netd` | root | only the `net-*` actions of `admin.c` (NETWORK.md); talks only to the sessions' root helpers (`netd.sock` 0600) |
| login screen | `lordos-greeter` | draw and request; no admin helper and no access to homes |
| session | the user | the usual (the `admin.c` helper with its closed list); the card and input only while it's on the monitor |
diff --git a/docs/session-power-classic-dark.png b/docs/session-power-classic-dark.png
new file mode 100644
index 0000000..a268994
Binary files /dev/null and b/docs/session-power-classic-dark.png differ
diff --git a/docs/session-power-classic-light.png b/docs/session-power-classic-light.png
new file mode 100644
index 0000000..1ff69be
Binary files /dev/null and b/docs/session-power-classic-light.png differ
diff --git a/docs/session-power-menu-dark.png b/docs/session-power-menu-dark.png
new file mode 100644
index 0000000..5c70421
Binary files /dev/null and b/docs/session-power-menu-dark.png differ
diff --git a/docs/session-power-menu-light.png b/docs/session-power-menu-light.png
new file mode 100644
index 0000000..29e227c
Binary files /dev/null and b/docs/session-power-menu-light.png differ
diff --git a/docs/session-power-restart-dark.png b/docs/session-power-restart-dark.png
new file mode 100644
index 0000000..ccecf6c
Binary files /dev/null and b/docs/session-power-restart-dark.png differ
diff --git a/docs/session-power-restart-light.png b/docs/session-power-restart-light.png
new file mode 100644
index 0000000..b6afd9b
Binary files /dev/null and b/docs/session-power-restart-light.png differ
diff --git a/sdk/index.js b/sdk/index.js
index bf98736..7e3d444 100644
--- a/sdk/index.js
+++ b/sdk/index.js
@@ -32,6 +32,8 @@ export { archive } from './archive.js';
export { print, queueName } from './print.js';
export { emoji, Grid as EmojiGrid, ToneBar as EmojiToneBar } from './emoji.jsx';
import { PrintDialog } from './printdialog.jsx';
+import { askPower, canPower } from './power.jsx';
+export { PowerDialog, powerAsk, POWER_SECONDS } from './power.jsx';
import { EmojiPanel } from './emoji.jsx';
export { admin } from './admin.js';
export { errorText, statusText, codeError, parseCode } from './errors.js';
@@ -137,6 +139,11 @@ export const session = {
managed: () => typeof lord.session !== 'undefined' && lord.session.managed(),
lock: () => typeof lord.session !== 'undefined' && lord.session.lock(),
switchUser: () => typeof lord.session !== 'undefined' && lord.session.switchUser(),
+ // Restart… and Shut Down… (0.8.1): a confirmation with a 60 s countdown (sdk/power.jsx), then
+ // lord-sessiond decides. canPower(): only in a session lord-sessiond shows on the monitor.
+ canPower,
+ restart: () => askPower('reboot'),
+ shutdown: () => askPower('poweroff'),
};
// ❖L or ❖Ctrl+Q lock the screen.
diff --git a/sdk/power.jsx b/sdk/power.jsx
new file mode 100644
index 0000000..74aed7d
--- /dev/null
+++ b/sdk/power.jsx
@@ -0,0 +1,138 @@
+// power.jsx — Restart… and Shut Down… from the session (0.8.1; docs/SESSIONS.md, "Restart and Shut
+// Down from a session").
+//
+// session.restart() / session.shutdown() open <PowerDialog>, which a theme renders in the «modal»
+// layer inside its ThemeProvider (so the sheet takes the theme's colors; default and classic do):
+// what will happen, a 60 s countdown that does it if nobody cancels, the apps still open and the
+// other users logged in. Confirming asks lord-sessiond
+// (root) through lord.session.power('reboot'|'poweroff'); lord-server runs nothing. The policy is
+// decided there: alone, any user; with other users' sessions open, only an administrator. The sheet
+// shows the same rule beforehand, and a refusal from lord-sessiond comes back as
+// {t:'power', ok:false, why:'admin'}.
+import { createElement as h, useEffect, useState } from 'react';
+import { View, Text, addListener, mainDisplay } from '@lordos/runtime';
+import { createStore, useStore } from './store.js';
+import { t } from './i18n.js';
+import { useTheme } from './theme.js';
+import { spacing, typeScale, controlSize } from './controls.jsx';
+import { windows } from './windows.js';
+import { windowAppName } from './apps.js';
+import { remote } from './remote.js';
+
+export const POWER_SECONDS = 60;
+// null, or { action: 'reboot'|'poweroff', until (ms), state: 'ask'|'sent'|'denied'|'unavailable' }
+export const powerAsk = createStore(null);
+
+export const canPower = () => typeof lord.session !== 'undefined' && typeof lord.session.power === 'function' && lord.session.managed();
+
+export function askPower(action) {
+ if (action !== 'reboot' && action !== 'poweroff') return;
+ powerAsk.set({ action, until: Date.now() + POWER_SECONDS * 1000, state: 'ask' });
+}
+
+// lord-sessiond's answers reach the session through the login screen's channel (RP_GREETER_IN);
+// the login screen theme has its own handler, so this one is only set in a user session.
+if (typeof lord.greeter === 'undefined') {
+ globalThis.__lordGreeter = (json) => {
+ let m = null;
+ try { m = JSON.parse(json); } catch (e) { return; }
+ if (m && m.t === 'power' && m.ok === false && powerAsk.get()) powerAsk.set((p) => (p ? { ...p, state: 'denied' } : p));
+ };
+}
+
+// Who else is logged in, and may this user do it with them there?
+function sessionInfo() {
+ let me = null;
+ try { me = (typeof lord.users !== 'undefined' ? lord.users.list().users : []).find((u) => u.self) || null; } catch (e) { me = null; }
+ const st = remote.status();
+ const others = [...new Set((st.sessions || []).map((s) => s.user).filter((u) => u && u !== me?.name))];
+ return { others, admin: !!me?.admin };
+}
+
+function openApps(list) {
+ const names = [];
+ for (const w of list) {
+ const n = windowAppName(w);
+ if (n && !names.includes(n)) names.push(n);
+ }
+ return names;
+}
+
+function Button({ th, label, onClick, primary, disabled }) {
+ const [hover, setHover] = useState(false);
+ const bg = primary ? '#e5483f' : th.control;
+ return h(View, {
+ onClick: disabled ? undefined : onClick, onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false),
+ style: { height: controlSize.regular, paddingHorizontal: 14, borderRadius: controlSize.radius, justifyContent: 'center', alignItems: 'center',
+ backgroundColor: bg, opacity: disabled ? 0.45 : hover ? 0.85 : 1 },
+ }, h(Text, { style: { fontSize: typeScale.body, fontWeight: 500, color: primary ? '#fff' : th.text, whiteSpace: 'nowrap' } }, label));
+}
+
+export function PowerDialog() {
+ const ask = useStore(powerAsk);
+ const list = useStore(windows);
+ const th = useTheme();
+ const [, tick] = useState(0);
+ const [info, setInfo] = useState(null);
+ const open = !!ask;
+ useEffect(() => { setInfo(open ? sessionInfo() : null); }, [open, ask?.action]);
+ const blocked = !!(info && info.others.length && !info.admin);
+ const counting = open && ask.state === 'ask' && info && !blocked;
+
+ const cancel = () => powerAsk.set(null);
+ const confirm = () => {
+ const p = powerAsk.get();
+ if (!p || p.state !== 'ask' || blocked) return;
+ const sent = canPower() && lord.session.power(p.action);
+ powerAsk.set({ ...p, state: sent ? 'sent' : 'unavailable' });
+ };
+
+ useEffect(() => {
+ if (!counting) return undefined;
+ const id = setInterval(() => {
+ if (Date.now() >= powerAsk.get()?.until) { clearInterval(id); confirm(); } else tick((n) => n + 1);
+ }, 250);
+ return () => clearInterval(id);
+ }, [counting, ask?.until]);
+
+ useEffect(() => {
+ if (!open) return undefined;
+ return addListener('keydown', (e) => {
+ if (e.key === 'Escape') cancel();
+ else if (e.key === 'Enter') confirm();
+ });
+ }, [open, blocked]);
+
+ if (!ask) return null;
+ const reboot = ask.action === 'reboot';
+ const left = Math.max(0, Math.ceil((ask.until - Date.now()) / 1000));
+ const apps = openApps(list);
+ const a = mainDisplay();
+ const lines = [];
+ const say = (text, color) => lines.push(h(Text, { key: lines.length, style: { fontSize: typeScale.body, color: color || th.textDim, lineHeight: 1.4, textAlign: 'start' } }, text));
+ if (ask.state === 'sent') say(t(reboot ? 'shell.power.restarting' : 'shell.power.shuttingDown'));
+ else if (ask.state === 'unavailable') say(t('shell.power.unavailable'), '#e5483f');
+ else if (ask.state === 'denied' || blocked) {
+ if (info?.others.length) say(t('shell.power.others', { count: info.others.length, list: info.others.join(', ') }));
+ say(t(reboot ? 'shell.power.needAdminRestart' : 'shell.power.needAdminShutdown'), '#e5483f');
+ } else {
+ say(t(reboot ? 'shell.power.restartCountdown' : 'shell.power.shutdownCountdown', { count: left }));
+ if (apps.length) say(t('shell.power.apps', { list: apps.join(', ') }));
+ if (info?.others.length) say(t('shell.power.others', { count: info.others.length, list: info.others.join(', ') }));
+ }
+ const asking = ask.state === 'ask' && !blocked;
+ return h(View, {
+ onClick: ask.state === 'sent' ? undefined : cancel,
+ style: { position: 'absolute', left: a.x, top: a.y, width: a.w, height: a.h, backgroundColor: 'rgba(0,0,0,0.3)', alignItems: 'center', justifyContent: 'center' },
+ }, h(View, {
+ onClick: (e) => e.stopPropagation(),
+ style: { width: 400, padding: spacing.xl, gap: spacing.s, borderRadius: 12, backgroundColor: th.windowBg, border: `1px solid ${th.separator}`,
+ boxShadow: '0 14px 36px rgba(0,0,0,0.45)' },
+ },
+ h(Text, { style: { fontSize: typeScale.headline, fontWeight: 600, color: th.text, textAlign: 'start' } },
+ t(reboot ? 'shell.power.restartTitle' : 'shell.power.shutdownTitle')),
+ ...lines,
+ ask.state === 'sent' ? null : h(View, { style: { flexDirection: 'row', justifyContent: 'flex-end', gap: spacing.s, marginTop: spacing.m } },
+ h(Button, { th, label: t('shell.power.cancel'), onClick: cancel }),
+ asking ? h(Button, { th, primary: true, label: t(reboot ? 'shell.power.restart' : 'shell.power.shutdown'), onClick: confirm }) : null)));
+}
diff --git a/server/src/remote/sessiond.c b/server/src/remote/sessiond.c
index 7f592d7..3f68b3d 100644
--- a/server/src/remote/sessiond.c
+++ b/server/src/remote/sessiond.c
@@ -498,10 +498,10 @@ static void show_greeter(const char *mode, const char *user) {
if (start_worker(W_GREETER, NULL, NULL)) pending = W_GREETER;
}
-static void power(const char *what) {
+static void power(const char *what, const char *who) {
const char *verb = !strcmp(what, "reboot") ? "reboot" : !strcmp(what, "poweroff") ? "poweroff" : NULL;
if (!verb) return;
- sd_log("%s requested from the login screen", verb);
+ sd_log("%s requested %s", verb, who);
pid_t pid = fork();
if (pid == 0) {
const char *const a[] = { "/usr/bin/systemctl", verb, NULL };
@@ -623,11 +623,49 @@ static void from_worker(void) {
if (!strncmp(buf, "greeter-in ", 11) && shown == 'g') sd_mon_greeter(buf + 11);
}
-/* Requests from the session being shown: lock or switch user; from the login screen:
+/* Restart or shut down from the session on the monitor (0.8.1: the crown menu, the Classic start
+ * menu; docs/SESSIONS.md, "Restart and Shut Down from a session"). Only "reboot" or "poweroff",
+ * through the same closed path as the login screen. Policy, decided here as root: the user on the
+ * monitor may do it alone; while other users have sessions open, only an administrator (sudo,
+ * admin or wheel, as for the admin actions). A refusal goes back to that session. */
+static int other_sessions(uid_t me) {
+ int n = 0;
+ rd_lock();
+ for (int i = 0; i < SD_MAX_SESSIONS; i++) {
+ SdSession *x = &rd_shared->sessions[i];
+ if (x->pid && x->uid != me && kill(x->pid, 0) == 0) n++;
+ }
+ rd_unlock();
+ return n;
+}
+
+static void session_power(const char *j) {
+ char what[16] = "";
+ jstr(j, "p", what, sizeof what);
+ if (strcmp(what, "reboot") && strcmp(what, "poweroff")) return;
+ struct passwd *pw = sd_valid_username(shown_user) ? getpwnam(shown_user) : NULL;
+ if (!pw) return;
+ int others = other_sessions(pw->pw_uid);
+ if (others && !is_admin(pw)) {
+ sd_log("%s asked to %s with %d other session(s) open: not an administrator, refused", shown_user, what, others);
+ char r[96];
+ snprintf(r, sizeof r, "{\"t\":\"power\",\"ok\":false,\"why\":\"admin\",\"others\":%d}", others);
+ sd_mon_greeter(r);
+ return;
+ }
+ char who[96];
+ snprintf(who, sizeof who, "by %s (%d other session(s) open)", shown_user, others);
+ power(what, who);
+}
+
+/* Requests from the session being shown: lock, switch user, restart or shut down; from the login screen:
* log in, restart or shut down. */
static void from_shown(int type, const char *j) {
if (type == RP_SHOWN) { first_frame(); return; }
if (type == RP_SESSION && shown == 'u') {
+ char a[16] = "";
+ jstr(j, "a", a, sizeof a);
+ if (!strcmp(a, "power")) { session_power(j); return; }
if (strstr(j, "\"lock\"")) { sd_log("%s locked the screen", shown_user); show_greeter("lock", shown_user); }
else if (strstr(j, "\"switch\"")) { sd_log("%s is switching user", shown_user); show_greeter("switch", shown_user); }
return;
@@ -645,7 +683,7 @@ static void from_shown(int type, const char *j) {
} else if (!strcmp(t, "power")) {
char what[16] = "";
jstr(j, "a", what, sizeof what);
- power(what);
+ power(what, "from the login screen");
}
}
diff --git a/server/src/ui/js_sys.c b/server/src/ui/js_sys.c
index 47c7b78..93db63e 100644
--- a/server/src/ui/js_sys.c
+++ b/server/src/ui/js_sys.c
@@ -1892,8 +1892,24 @@ static JSValue f_session_switch(JSContext *c, JSValueConst this_val, int argc, J
return JS_NewBool(c, mirror_has_seat());
}
+/* lord.session.power('reboot'|'poweroff'): asks lord-sessiond (root), which decides (docs/SESSIONS.md,
+ * "Restart and Shut Down from a session"). Only those two words, sent as a fixed message; lord-server
+ * runs nothing. false if no lord-sessiond drives this session's monitor. */
+static JSValue f_session_power(JSContext *c, JSValueConst this_val, int argc, JSValueConst *argv) {
+ (void)this_val;
+ const char *w = argc ? JS_ToCString(c, argv[0]) : NULL;
+ if (!w) return JS_EXCEPTION;
+ const char *msg = !strcmp(w, "reboot") ? "{\"a\":\"power\",\"p\":\"reboot\"}"
+ : !strcmp(w, "poweroff") ? "{\"a\":\"power\",\"p\":\"poweroff\"}" : NULL;
+ JS_FreeCString(c, w);
+ if (!msg || greeter_mode || !mirror_has_seat()) return JS_FALSE;
+ mirror_session(msg);
+ return JS_TRUE;
+}
+
static const JSCFunctionListEntry session_funcs[] = {
JS_CFUNC_DEF("managed", 0, f_session_managed),
+ JS_CFUNC_DEF("power", 1, f_session_power),
JS_CFUNC_DEF("lock", 0, f_session_lock),
JS_CFUNC_DEF("switchUser", 0, f_session_switch),
};
diff --git a/themes/classic/index.jsx b/themes/classic/index.jsx
index 50975d7..af6044d 100644
--- a/themes/classic/index.jsx
+++ b/themes/classic/index.jsx
@@ -10,7 +10,7 @@ import {
ScrollView, useLauncherApps, launchApp, windowIcon, APP_CATEGORIES, appCategory, useDockEntries, dockActivate, dockMenu,
DesktopWidgets, PrivacyIndicators, registerGestureActions, WindowShell, StatusItems, dockPrefs, mainDisplay,
useStore, dock, dockIdOf, dockDrag, dockPoof, beginDockDrag, registerDockTarget, dockDragJustEnded, useTrash, openTrash, emptyTrash, trashMenu,
- refreshTrash, ConfirmDialog, takeTextFocus, releaseTextFocus, Layer,
+ refreshTrash, ConfirmDialog, takeTextFocus, releaseTextFocus, Layer, PowerDialog,
} from '@lordos/sdk';
import { apps } from '@lordos/apps';
import { useEffect, useRef, useState } from 'react';
@@ -122,12 +122,35 @@ function Window({ win, t, focused }) {
// ---- 3. taskbar + start menu ----
+// The power symbol, drawn (it doesn't depend on the font having ⏻)
+function PowerGlyph({ color, bg }) {
+ return (
+ <View style={{ width: 14, height: 14 }}>
+ <View style={{ position: 'absolute', left: 1, top: 2, width: 12, height: 12, borderRadius: 6, border: `1.6px solid ${color}` }} />
+ <View style={{ position: 'absolute', left: 4, top: 0, width: 6, height: 5, backgroundColor: bg }} />
+ <View style={{ position: 'absolute', left: 6.2, top: 0, width: 1.6, height: 7, borderRadius: 1, backgroundColor: color }} />
+ </View>
+ );
+}
+
+// A choice under the power button (Restart…, Shut Down…)
+function PowerRow({ t, label, onClick }) {
+ const [hover, setHover] = useState(false);
+ return (
+ <View onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
+ style={{ padding: 8, paddingLeft: 30, backgroundColor: hover ? t.hover : 'transparent' }}>
+ <Text style={{ fontSize: 13, color: t.text }}>{label}</Text>
+ </View>
+ );
+}
+
// An app is pinned by dragging it onto the bar (the menu closes when the drag starts) or with a
// right click → Pin to taskbar.
function StartMenu({ t, onClose, pos }) {
const ref = useRef(null);
const list = useLauncherApps();
const [ctx, setCtx] = useState(null); // { app, x }
+ const [power, setPower] = useState(false); // the power button's menu (Restart…, Shut Down…)
const groups = APP_CATEGORIES.map((c) => [c, list.filter((a) => appCategory(a) === c)]).filter(([, items]) => items.length);
useEffect(() => addListener('pointerdown', (e) => {
for (let n = e.target; n; n = n.parent) if (n === ref.current) return;
@@ -137,7 +160,8 @@ function StartMenu({ t, onClose, pos }) {
<View ref={ref} style={{ position: 'absolute', ...nextToBar(pos, 6), width: 280, padding: 8, direction: 'ltr',
backgroundColor: t.bar, border: `1px solid ${t.separator}`, boxShadow: '0 10px 30px rgba(0,0,0,0.4)' }}>
<Text style={{ fontSize: 11, fontWeight: 600, color: t.textDim, margin: 6 }}>{tr('shell.start.apps')}</Text>
- <ScrollView style={{ height: Math.min(list.length * 40 + groups.length * 26, screen.height - BAR_H - 120) }}>
+ {/* the list leaves room for the footer (lock, switch user, log out, power and its two choices) */}
+ <ScrollView style={{ height: Math.min(list.length * 40 + groups.length * 26, screen.height - BAR_H - 200 - (power ? 72 : 0)) }}>
{groups.map(([c, items]) => (
<View key={c}>
<Text style={{ fontSize: 10, fontWeight: 700, color: t.textDim, marginLeft: 6, marginTop: 8, marginBottom: 2 }}>{tr(`shell.category.${c}`)}</Text>
@@ -160,7 +184,19 @@ function StartMenu({ t, onClose, pos }) {
{session.managed() ? (
<View onClick={() => { onClose(); session.switchUser(); }} style={{ padding: 8 }}><Text style={{ fontSize: 13, color: t.text }}>{tr('shell.menu.switchUser')}</Text></View>
) : null}
- <View onClick={() => session.quit()} style={{ padding: 8 }}><Text style={{ fontSize: 13, color: t.text }}>{tr('shell.menu.logout')}</Text></View>
+ <View style={{ flexDirection: 'row', alignItems: 'center' }}>
+ <View onClick={() => session.quit()} style={{ flex: 1, padding: 8 }}><Text style={{ fontSize: 13, color: t.text }}>{tr('shell.menu.logout')}</Text></View>
+ {session.canPower() ? (
+ <View onClick={() => setPower((v) => !v)} style={{ flexDirection: 'row', alignItems: 'center', gap: 6, paddingVertical: 6,
+ paddingHorizontal: 10, borderRadius: 4, backgroundColor: power ? t.hover : 'transparent' }}>
+ <PowerGlyph color={t.text} bg={power ? t.hover : t.bar} />
+ <Text style={{ fontSize: 13, color: t.text }}>{tr('shell.menu.power')}</Text>
+ </View>
+ ) : null}
+ </View>
+ {power ? [['restart', () => session.restart()], ['shutdown', () => session.shutdown()]].map(([k, go]) => (
+ <PowerRow key={k} t={t} label={tr(`shell.menu.${k}`)} onClick={() => { onClose(); go(); }} />
+ )) : null}
{ctx && (
<PopupMenu t={t} pos={pos} x={ctx.x} onClose={() => setCtx(null)} items={[
{ label: tr('shell.dock.open'), onClick: () => { onClose(); launchApp(ctx.app.id); } },
@@ -440,6 +476,7 @@ function App() {
<DragGhost t={t} />
<PoofFade />
</Layer>
+ <Layer name="modal"><PowerDialog /></Layer> {/* Restart…, Shut Down… (sdk/power.jsx) */}
{askEmpty && (
<Layer name="modal">
<ConfirmDialog title={tr('shell.trash.confirmTitle')} detail={tr('shell.trash.confirmDetail')} okLabel={tr('shell.trash.empty')}
diff --git a/themes/default/components/MenuBar.jsx b/themes/default/components/MenuBar.jsx
index 91f91c0..b8f8738 100644
--- a/themes/default/components/MenuBar.jsx
+++ b/themes/default/components/MenuBar.jsx
@@ -62,6 +62,11 @@ export function MenuBar({ t, height, focused, onLaunchpad, onControlCenter, cont
{ label: tr('shell.menu.switchUser'), onClick: () => session.switchUser() },
] : []),
{ label: tr('shell.menu.logout'), onClick: () => session.quit() },
+ ...(session.canPower() ? [
+ '-',
+ { label: tr('shell.menu.restart'), onClick: () => session.restart() },
+ { label: tr('shell.menu.shutdown'), onClick: () => session.shutdown() },
+ ] : []),
] },
window: { items: [
{ label: tr('shell.window.minimize'), disabled: !app, onClick: () => wm.minimize(focused) },
diff --git a/themes/default/index.jsx b/themes/default/index.jsx
index e87911b..c85d5cf 100644
--- a/themes/default/index.jsx
+++ b/themes/default/index.jsx
@@ -5,7 +5,7 @@ import {
startShell, View, Text, Image, screen, ThemeProvider, useSettings, useWindows, configureWindows, getApp, wm, addListener, t as tr,
useLauncherApps, launchApp, useDockEntries, dockActivate, dockMenu, dockPrefs, DOCK_LAUNCHER,
useTrash, openTrash, emptyTrash, trashMenu, ConfirmDialog,
- DesktopWidgets, registerGestureActions, screenDisplays, mainDisplay, settings, Layer,
+ DesktopWidgets, registerGestureActions, screenDisplays, mainDisplay, settings, Layer, PowerDialog,
} from '@lordos/sdk';
import { apps } from '@lordos/apps';
import { useEffect, useRef, useState } from 'react';
@@ -166,6 +166,8 @@ function App() {
onCancel={() => setAskEmpty(false)} onOk={() => { setAskEmpty(false); emptyTrash(); }} />
</Layer>
)}
+ {/* Restart… and Shut Down… (sdk/power.jsx): inside the ThemeProvider, so it takes the theme's colors */}
+ <Layer name="modal"><PowerDialog /></Layer>
{control && <Layer name="popover"><ControlCenter t={t} top={MENU_H} area={control} onClose={() => setControl(null)} /></Layer>}
{context && (
<Menu x={context.x} y={context.y} onClose={() => setContext(null)} items={[