CoreDesktop GNOME extension

This commit is contained in:
2026-11-27 12:28:07 -07:00
commit 7d9d2d6239
15 changed files with 1742 additions and 0 deletions
+210
View File
@@ -0,0 +1,210 @@
// Talking to CoreDesktop's command line tools: running them in the background
// to read their output, or in a terminal window for the user to follow.
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
Gio._promisify(Gio.Subprocess.prototype, 'communicate_utf8_async');
Gio._promisify(Gio.File.prototype, 'load_contents_async');
Gio._promisify(Gio.File.prototype, 'enumerate_children_async');
Gio._promisify(Gio.FileEnumerator.prototype, 'next_files_async');
const HOME = GLib.get_home_dir();
export const COREDESKTOP = GLib.build_filenamev([HOME, '.local', 'share', 'coredesktop']);
export const BIN = GLib.build_filenamev([HOME, '.local', 'bin']);
export const STATE = GLib.build_filenamev([HOME, '.local', 'state', 'coredesktop']);
export const LOGS = GLib.build_filenamev([STATE, 'logs']);
export const REBOOT_NEEDED = GLib.build_filenamev([STATE, 'reboot-needed']);
export const PACMAN_UPDATE_LOG = GLib.build_filenamev([STATE, 'pacman-update.log']);
export const STATUS_DIR = GLib.build_filenamev([GLib.get_user_runtime_dir(), 'coredesktop-extension']);
// Terminals and how each runs a command, in the order CoreDesktop's
// system/run-in-terminal tries them
export const TERMINALS = {
'xdg-terminal-exec': [],
'kgx': ['--'],
'ghostty': ['-e'],
'kitty': [],
'ptyxis': ['--new-window', '--'],
'gnome-terminal': ['--'],
'alacritty': ['-e'],
};
export function stripAnsi(text) {
// eslint-disable-next-line no-control-regex
return text.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '').replace(/\r/g, '');
}
export function bin(name) {
return GLib.build_filenamev([BIN, name]);
}
export function isInstalled() {
return GLib.file_test(GLib.build_filenamev([COREDESKTOP, '.git']), GLib.FileTest.EXISTS);
}
// Run argv in the background. Resolves to {status, stdout, stderr}.
export async function run(argv, cancellable = null) {
const launcher = new Gio.SubprocessLauncher({
flags: Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_PIPE,
});
launcher.setenv('PATH', `${BIN}:${GLib.getenv('PATH') ?? '/usr/bin'}`, true);
// Commands such as version show a spinner and ask questions only on a
// terminal; make sure nothing thinks there's one
launcher.unsetenv('COREDESKTOP_TTY');
const proc = launcher.spawnv(argv);
const [stdout, stderr] = await proc.communicate_utf8_async(null, cancellable);
return {status: proc.get_exit_status(), stdout: stdout ?? '', stderr: stderr ?? ''};
}
// The version this machine is on, e.g. 2026.11.26 (01d2432)
export async function localVersion() {
try {
const {status, stdout} = await run(['git', '-C', COREDESKTOP, 'log', '-1',
'--format=%cd (%h)', '--date=format:%Y.%m.%d']);
return status === 0 ? stdout.trim() : null;
} catch {
return null;
}
}
// version --check: {state: 'available', version} | {state: 'current'} | {state: 'unknown'}
export async function checkForUpdate(cancellable) {
try {
const {status, stdout} = await run([bin('version'), '--check'], cancellable);
if (status === 0 && stdout.trim())
return {state: 'available', version: stdout.trim()};
if (status === 1)
return {state: 'current'};
} catch (e) {
if (e.matches?.(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
throw e;
}
return {state: 'unknown'};
}
// configure --list, with each item's description from its configure.d file:
// [{name, title, description, done}]
export async function configureItems() {
const {status, stdout} = await run([bin('configure'), '--list']);
if (status !== 0)
return [];
const descriptions = await configureDescriptions();
const items = [];
for (const line of stdout.split('\n')) {
const m = line.match(/^(done|to do)\s+(\S+)\s+(.*)$/);
if (!m)
continue;
items.push({
done: m[1] === 'done',
name: m[2],
title: m[3].trim(),
description: descriptions.get(m[2]) ?? '',
});
}
return items;
}
async function configureDescriptions() {
const result = new Map();
const dir = Gio.File.new_for_path(GLib.build_filenamev([COREDESKTOP, 'configure.d']));
for (const file of await listFiles(dir)) {
const base = file.get_basename();
if (!base.endsWith('.sh'))
continue;
const name = base.replace(/\.sh$/, '').replace(/^\d\d-/, '');
try {
const [bytes] = await file.load_contents_async(null);
const text = new TextDecoder().decode(bytes);
const m = text.match(/^DESCRIPTION=(["'])(.*)\1\s*$/m);
if (m)
result.set(name, m[2]);
} catch {
// An unreadable item just goes without a description
}
}
return result;
}
export async function listFiles(dir) {
const files = [];
try {
const enumerator = await dir.enumerate_children_async('standard::name,time::modified',
Gio.FileQueryInfoFlags.NONE, GLib.PRIORITY_DEFAULT, null);
for (;;) {
const infos = await enumerator.next_files_async(50, GLib.PRIORITY_DEFAULT, null);
if (infos.length === 0)
break;
for (const info of infos) {
const file = dir.get_child(info.get_name());
file._mtime = info.get_modification_date_time()?.to_unix() ?? 0;
files.push(file);
}
}
} catch {
// A missing directory has no files
}
return files;
}
// The newest update or install log, or null
export async function newestLog() {
const files = (await listFiles(Gio.File.new_for_path(LOGS)))
.filter(f => f.get_basename().endsWith('.log'));
files.sort((a, b) => b._mtime - a._mtime);
return files[0] ?? null;
}
// Seconds since the epoch the file was last modified, or null
export function mtime(path) {
try {
const info = Gio.File.new_for_path(path).query_info('time::modified',
Gio.FileQueryInfoFlags.NONE, null);
return info.get_modification_date_time()?.to_unix() ?? null;
} catch {
return null;
}
}
export function findTerminal(preference) {
if (preference && preference !== 'auto') {
if (GLib.find_program_in_path(preference))
return [preference, ...(TERMINALS[preference] ?? ['-e'])];
}
for (const [name, args] of Object.entries(TERMINALS)) {
if (GLib.find_program_in_path(name))
return [name, ...args];
}
return null;
}
// Open a terminal window running `argv` under run-tracked, which records its
// progress as <name>.status in STATUS_DIR. The terminal runs as its own systemd
// unit so it outlives a GNOME Shell restart. Returns false if there's no terminal.
export function runInTerminal(extensionPath, preference, name, argv) {
const terminal = findTerminal(preference);
if (!terminal)
return false;
const tracked = GLib.build_filenamev([extensionPath, 'bin', 'run-tracked']);
const command = ['systemd-run', '--user', '--quiet', '--collect',
`--unit=coredesktop-${name}-${Date.now()}`, '--',
...terminal, 'bash', tracked, name, ...argv];
GLib.mkdir_with_parents(STATUS_DIR, 0o700);
Gio.Subprocess.new(command, Gio.SubprocessFlags.NONE);
return true;
}
// "just now", "5 minutes ago", "3 hours ago", "2 days ago"
export function timeAgo(unixSeconds) {
if (!unixSeconds)
return null;
const secs = Math.max(0, GLib.get_real_time() / 1e6 - unixSeconds);
const plural = (n, unit) => `${n} ${unit}${n === 1 ? '' : 's'} ago`;
if (secs < 60)
return 'just now';
if (secs < 3600)
return plural(Math.floor(secs / 60), 'minute');
if (secs < 86400)
return plural(Math.floor(secs / 3600), 'hour');
return plural(Math.floor(secs / 86400), 'day');
}
@@ -0,0 +1,267 @@
// Dialogs: the version report, and confirmations that say what a command will
// do before it runs.
import Clutter from 'gi://Clutter';
import Gio from 'gi://Gio';
import GLib from 'gi://GLib';
import GObject from 'gi://GObject';
import Pango from 'gi://Pango';
import St from 'gi://St';
import * as Dialog from 'resource:///org/gnome/shell/ui/dialog.js';
import * as ModalDialog from 'resource:///org/gnome/shell/ui/modalDialog.js';
import * as Cli from './cli.js';
// Everything configure can set up, whether it's done, and a button to set each
// one up. items: [{name, title, description, done, icon, running}]
export const ConfigureDialog = GObject.registerClass(
class ConfigureDialog extends ModalDialog.ModalDialog {
_init({items, onConfigure, onOpenAll}) {
super._init({styleClass: 'coredesktop-dialog coredesktop-configure-dialog'});
const todo = items.filter(i => !i.done).length;
let description;
if (items.length === 0)
description = 'Couldn\'t read what configure can set up. Open it in a terminal instead.';
else if (todo === 0)
description = `All ${items.length} are set up. You can change any of them.`;
else
description = `${todo} of ${items.length} still to set up. Each opens a terminal that walks you through it.`;
this.contentLayout.add_child(new Dialog.MessageDialogContent({title: 'Configure CoreDesktop', description}));
const list = new St.BoxLayout({orientation: Clutter.Orientation.VERTICAL, style_class: 'coredesktop-configure-list'});
const sorted = [...items].sort((a, b) => Number(a.done) - Number(b.done));
for (const item of sorted) {
const row = new St.BoxLayout({style_class: 'coredesktop-configure-row'});
row.add_child(new St.Icon({
icon_name: item.icon,
style_class: 'coredesktop-configure-icon',
y_align: Clutter.ActorAlign.CENTER,
}));
const text = new St.BoxLayout({
orientation: Clutter.Orientation.VERTICAL,
x_expand: true,
y_align: Clutter.ActorAlign.CENTER,
});
text.add_child(new St.Label({text: item.title, style_class: 'coredesktop-item-title'}));
text.add_child(new St.Label({text: item.description, style_class: 'coredesktop-item-description'}));
row.add_child(text);
let state, kind;
if (item.running)
[state, kind] = ['Running…', 'running'];
else if (item.done)
[state, kind] = ['Done', 'success'];
else
[state, kind] = ['To do', 'warning'];
row.add_child(new St.Label({
text: state,
style_class: `coredesktop-pill ${kind}`,
y_align: Clutter.ActorAlign.CENTER,
}));
const button = new St.Button({
label: item.done ? 'Change' : 'Set up',
style_class: `button coredesktop-configure-button${item.done ? '' : ' default'}`,
y_align: Clutter.ActorAlign.CENTER,
can_focus: true,
reactive: !item.running,
});
button.connect('clicked', () => {
this.close();
onConfigure(item);
});
row.add_child(button);
list.add_child(row);
}
const scroll = new St.ScrollView({
style_class: 'coredesktop-configure-scroll',
hscrollbar_policy: St.PolicyType.NEVER,
vscrollbar_policy: St.PolicyType.AUTOMATIC,
overlay_scrollbars: true,
});
scroll.set_child(list);
this.contentLayout.add_child(scroll);
this.setButtons([
{
label: 'Open in terminal',
action: () => {
this.close();
onOpenAll();
},
},
{label: 'Close', action: () => this.close(), key: Clutter.KEY_Escape, default: true},
]);
}
});
// Ask before running something. onConfirm runs if the user agrees.
export const ConfirmDialog = GObject.registerClass(
class ConfirmDialog extends ModalDialog.ModalDialog {
_init({title, description, details = [], confirmLabel, onConfirm}) {
super._init({styleClass: 'coredesktop-dialog'});
const content = new Dialog.MessageDialogContent({title, description});
this.contentLayout.add_child(content);
// What the command does, one line each with an icon, so it's easy to scan
if (details.length > 0) {
const list = new St.BoxLayout({
orientation: Clutter.Orientation.VERTICAL,
style_class: 'coredesktop-detail-list',
});
for (const [iconName, text] of details) {
const row = new St.BoxLayout({style_class: 'coredesktop-detail-row'});
row.add_child(new St.Icon({icon_name: iconName, style_class: 'coredesktop-detail-icon'}));
const label = new St.Label({text, y_align: Clutter.ActorAlign.CENTER, x_expand: true});
label.clutter_text.line_wrap = true;
label.clutter_text.ellipsize = Pango.EllipsizeMode.NONE;
row.add_child(label);
list.add_child(row);
}
this.contentLayout.add_child(list);
}
this.setButtons([
{label: 'Cancel', action: () => this.close(), key: Clutter.KEY_Escape},
{
label: confirmLabel,
action: () => {
this.close();
onConfirm();
},
default: true,
},
]);
}
});
// Runs `version` and shows its report, with a button to update when there's
// something newer
export const VersionDialog = GObject.registerClass(
class VersionDialog extends ModalDialog.ModalDialog {
_init({onUpdate}) {
super._init({styleClass: 'coredesktop-dialog coredesktop-version-dialog'});
this._onUpdate = onUpdate;
this._cancellable = new Gio.Cancellable();
this._output = '';
this._content = new Dialog.MessageDialogContent({
title: 'CoreDesktop version',
description: 'Checking for newer versions of CoreDesktop, the kernel, the video driver and sibling projects…',
});
this.contentLayout.add_child(this._content);
this._report = new St.Label({style_class: 'coredesktop-version-report'});
this._report.clutter_text.line_wrap = false;
this._report.clutter_text.ellipsize = Pango.EllipsizeMode.NONE;
const scroll = new St.ScrollView({
style_class: 'coredesktop-version-scroll',
hscrollbar_policy: St.PolicyType.AUTOMATIC,
vscrollbar_policy: St.PolicyType.AUTOMATIC,
overlay_scrollbars: true,
});
const box = new St.BoxLayout({orientation: Clutter.Orientation.VERTICAL});
box.add_child(this._report);
scroll.set_child(box);
this.contentLayout.add_child(scroll);
this._report.text = 'Checking…';
this._report.ease({
opacity: 100, duration: 700, autoReverse: true, repeatCount: -1,
mode: Clutter.AnimationMode.EASE_IN_OUT_SINE,
});
this._setButtons(false);
this.connect('destroy', () => this._cancellable.cancel());
this._load();
}
_setButtons(updateAvailable) {
const buttons = [];
if (this._output) {
buttons.push({
label: 'Copy',
action: () => {
St.Clipboard.get_default().set_text(St.ClipboardType.CLIPBOARD, this._output);
this._content.description = 'Copied to the clipboard.';
},
});
}
if (updateAvailable) {
buttons.push({
label: 'Update now',
action: () => {
this.close();
this._onUpdate();
},
});
}
buttons.push({label: 'Close', action: () => this.close(), key: Clutter.KEY_Escape, default: true});
this.setButtons(buttons);
}
async _load() {
let text;
try {
const {stdout, stderr} = await Cli.run([Cli.bin('version')], this._cancellable);
text = Cli.stripAnsi(stdout || stderr).trimEnd();
} catch (e) {
if (e.matches?.(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED))
return;
text = `Couldn't run version: ${e.message}`;
}
this._report.remove_all_transitions();
this._report.opacity = 255;
this._output = text;
const available = /is available/.test(text);
const stale = /mirror .* last synced/i.test(text);
this._content.description = available
? 'Newer versions are available. Update to install them.'
: 'Everything is up to date.';
if (stale)
this._content.description += ' Your package mirror is out of date; update switches to a fresher one.';
this._report.clutter_text.set_markup(markup(text));
this._setButtons(available);
}
});
// Bold the "Label value" names and highlight what's newer or needs attention
function markup(text) {
return text.split('\n').map(line => {
// "Video driver" has a single space before its value
let m = line.match(/^(CoreDesktop|Kernel|Video driver|Last update)(\s+)(.*)$/);
if (m)
return `<b>${esc(m[1])}</b>${esc(m[2])}${highlight(m[3])}`;
m = line.match(/^(\s+\S+)(\s{2,})(.*)$/);
if (m)
return `${esc(m[1])}${esc(m[2])}${highlight(m[3])}`;
if (/^Sibling projects$/.test(line))
return `<b>${esc(line)}</b>`;
if (/mirror|newer packages may be missing/.test(line))
return `<span foreground="#e5a50a">${esc(line)}</span>`;
return esc(line);
}).join('\n');
}
function highlight(value) {
// "2026.11.26 (01d2432), 2026.11.27 (abc1234) is available (run update)"
// Commas inside parentheses, as in "(newer kernel installed, reboot to use it)", don't split
const parts = value.split(/,\s*(?![^(]*\))/);
return parts.map(part => {
if (/is available/.test(part))
return `<span foreground="#3584e4" weight="bold">⬆ ${esc(part)}</span>`;
if (/reboot|couldn't check|modified/.test(part))
return `<span foreground="#e5a50a">${esc(part)}</span>`;
return esc(part);
}).join(', ');
}
function esc(s) {
return GLib.markup_escape_text(s, -1);
}