From 8002587a313c75e9f8dd148926f31b6c3d0fa78d Mon Sep 17 00:00:00 2001 From: drpaulobernardy <198827520+drpaulobernardy@users.noreply.github.com> Date: Sun, 8 Nov 2026 14:58:10 -0300 Subject: [PATCH] Pulse Desktop: run on Linux, macOS path unchanged (#2591) Everything only Linux needs lives in linux.ts. Each app file decides once, with isLinux(process.platform) or isLinux(navigator.platform), and every Linux branch tests that, so macOS and every other platform run the shipped code. The author's lines stay as written except five, where the shipped expression is kept verbatim as the non-Linux arm of a ternary (terminalFile, tmux, env, the menu template wrapper). linux.test.ts reads the accelerators and labels from the app files, so a new shortcut with no Linux key fails there instead of silently in use. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014YTdW6sTViEVVK8c3DeQVC --- LifeOS/install/LIFEOS/PULSE/Desktop/README.md | 4 + LifeOS/install/LIFEOS/PULSE/Desktop/build.ts | 46 +++- .../LIFEOS/PULSE/Desktop/linux.test.ts | 165 +++++++++++++ LifeOS/install/LIFEOS/PULSE/Desktop/linux.ts | 218 ++++++++++++++++++ LifeOS/install/LIFEOS/PULSE/Desktop/main.ts | 37 ++- .../install/LIFEOS/PULSE/Desktop/terminals.ts | 15 +- .../LIFEOS/PULSE/Desktop/workspace.css | 8 + .../install/LIFEOS/PULSE/Desktop/workspace.ts | 20 ++ 8 files changed, 508 insertions(+), 5 deletions(-) create mode 100644 LifeOS/install/LIFEOS/PULSE/Desktop/linux.test.ts create mode 100644 LifeOS/install/LIFEOS/PULSE/Desktop/linux.ts diff --git a/LifeOS/install/LIFEOS/PULSE/Desktop/README.md b/LifeOS/install/LIFEOS/PULSE/Desktop/README.md index dc7883e9c8..b10cdb71de 100644 --- a/LifeOS/install/LIFEOS/PULSE/Desktop/README.md +++ b/LifeOS/install/LIFEOS/PULSE/Desktop/README.md @@ -17,6 +17,10 @@ The app icon defaults to the LifeOS logo the dashboard ships (`../Observability/ The installed app lives at `/Applications/Pulse Desktop.app`. Replacement backups stay in `~/Library/Application Support/LifeOS/App Backups.noindex`, outside application search. The separate menu-bar helper lives in `~/Library/Application Support/LifeOS/Helpers.noindex`. +### Linux + +The same `bun install` and `bun run install-app` build the app for Linux and install it to `~/.local/share/pulse-desktop`, with a `pulse-desktop.desktop` launcher entry in `~/.local/share/applications`; a replaced copy moves to `~/.local/share/LifeOS/app-backups`. It needs tmux from the package manager and Pulse as the systemd user service `com.lifeos.pulse.service`, which the app starts when it is stopped. App shortcuts use Ctrl+Shift where macOS uses ⌘, and Ctrl+Shift+Alt for ⇧⌘; ⌃H / ⌃L stay as they are. Everything only Linux needs lives in `linux.ts`, and every other platform runs the files as written. Tested on Arch Linux with Hyprland (Wayland). + ## Controls - ⌘K opens Commands & shortcuts from any dashboard or terminal. Search actions, pages, or sessions; ↑/↓ selects, Enter runs, and Escape returns to the workspace. “Show keyboard shortcuts” lists bindings with their scope. The sidebar also has a Commands & shortcuts button. diff --git a/LifeOS/install/LIFEOS/PULSE/Desktop/build.ts b/LifeOS/install/LIFEOS/PULSE/Desktop/build.ts index 49746982a0..866eaf8069 100644 --- a/LifeOS/install/LIFEOS/PULSE/Desktop/build.ts +++ b/LifeOS/install/LIFEOS/PULSE/Desktop/build.ts @@ -7,6 +7,11 @@ import {invariant} from '../../TOOLS/Invariant'; import {BUNDLE_ID,DEFAULTS_BIN,pressAndHoldArgs} from './key-repeat'; import {terminalFontFile} from './terminal-font'; import {copyOptionalFonts} from './optional-fonts'; +// Linux: build and install there too; what only Linux needs lives in linux.ts. +import {readdirSync,writeFileSync} from 'node:fs'; +import {isLinux,linuxFontDirs,desktopEntry,linuxShortcutLabel} from './linux'; +const LINUX=isLinux(process.platform); +const subdirs=(dir:string)=>{try{return readdirSync(dir,{withFileTypes:true}).filter(d=>d.isDirectory()).map(d=>join(dir,d.name));}catch(error){if((error as NodeJS.ErrnoException).code==='ENOENT')return [];throw error;}}; const root=import.meta.dir; // The upstream macOS prebuild is distributed without its executable bit. @@ -38,7 +43,8 @@ const bundledFonts=copyOptionalFonts(fonts,assets,{'concourse_t3_regular-webfont if(bundledFonts.length===0)console.warn('No brand fonts found; using system fonts.'); // The terminal font is bundled when kitty.conf names a family whose regular file is installed; otherwise the terminal uses its fixed-width fallback stack. const kittyConf=join(homedir(),'.config/kitty/kitty.conf'); -const terminalFile=terminalFontFile(existsSync(kittyConf)?readFileSync(kittyConf,'utf8'):'',[join(homedir(),'Library/Fonts'),'/Library/Fonts']); +// Linux: look for the kitty font in the Linux font folders. +const terminalFile=LINUX?terminalFontFile(existsSync(kittyConf)?readFileSync(kittyConf,'utf8'):'',linuxFontDirs(homedir(),subdirs)):terminalFontFile(existsSync(kittyConf)?readFileSync(kittyConf,'utf8'):'',[join(homedir(),'Library/Fonts'),'/Library/Fonts']); rmSync(join(assets,'terminal.ttf'),{force:true}); if(terminalFile)copyFileSync(terminalFile,join(assets,'terminal.ttf')); else console.warn('No kitty terminal font file found; using the fallback terminal font.'); @@ -50,8 +56,46 @@ for(const file of ['workspace.html','workspace.css','tmux.conf'])copyFileSync(jo // libghostty-vt: the wasm terminal core (pinned revision in ghostty/VERSION) plus its 112-byte PTY-reply trampoline and the symbols font. Plain read-only assets served through pulse-asset:. mkdirSync(join(dist,'ghostty')); for(const file of ['vendor/ghostty-vt.wasm','vendor/ghostty-write-pty.wasm','fonts/SymbolsNerdFontMono-Regular.woff2','VERSION'])copyFileSync(join(root,'ghostty',file),join(dist,'ghostty',file.split('/').pop()!)); +// Linux: the offline page runs no script, so its shortcut labels are rewritten at build time. copyFileSync(join(root,'offline.html'),join(dist,'offline.html')); +if(LINUX)writeFileSync(join(dist,'offline.html'),linuxShortcutLabel(readFileSync(join(root,'offline.html'),'utf8'))); cpSync(assets,join(dist,'assets'),{recursive:true}); +// Linux: package for linux and install to ~/.local/share/pulse-desktop with a pulse-desktop.desktop launcher entry; a previous copy is moved to ~/.local/share/LifeOS/app-backups. +if(LINUX&&(process.argv.includes('--package')||process.argv.includes('--install'))){ + const stage=join(root,'stage');generatedDir(stage); + cpSync(dist,join(stage,'dist'),{recursive:true}); + const manifest=JSON.parse(readFileSync(join(root,'package.json'),'utf8')); + await Bun.write(join(stage,'package.json'),JSON.stringify({name:manifest.name,productName:manifest.productName,version:manifest.version,main:manifest.main,dependencies:{'node-pty':manifest.dependencies['node-pty']}})); + cpSync(join(root,'node_modules/node-pty'),join(stage,'node_modules/node-pty'),{recursive:true}); + const paths=await packager({dir:stage,name:'Pulse Desktop',executableName:'pulse-desktop',platform:'linux',arch:process.arch as 'arm64'|'x64',electronVersion:manifest.devDependencies.electron,out:join(root,'release'),overwrite:true,prune:false,asar:{unpackDir:'node_modules/node-pty'},extraResource:[join(dist,'tmux.conf')]}); + invariant(paths.length===1,'one app folder produced'); + const built=paths[0]; + invariant(existsSync(join(built,'pulse-desktop')),'packager produced a launchable app'); + console.log(built); + if(process.argv.includes('--install')){ + const share=join(homedir(),'.local/share');const dest=join(share,'pulse-desktop'); + if(existsSync(dest)){ + invariant(realpathSync(dest)===dest,'do not replace a symlinked app'); + invariant(existsSync(join(dest,'pulse-desktop'))&&existsSync(join(dest,'resources/tmux.conf')),'only replace our own app'); + const backups=join(share,'LifeOS/app-backups');mkdirSync(backups,{recursive:true}); + invariant(realpathSync(backups)===backups,'backup directory must not be a symlink'); + const backup=join(backups,`pulse-desktop-${Date.now()}`); + invariant(!existsSync(backup),'backup must not overwrite an existing app'); + renameSync(dest,backup); + } + cpSync(built,dest,{recursive:true,verbatimSymlinks:true}); + copyFileSync(join(assets,'icon.png'),join(dest,'pulse-desktop.png')); + const apps=join(share,'applications');mkdirSync(apps,{recursive:true}); + const entry=join(apps,'pulse-desktop.desktop'); + if(existsSync(entry)){ + invariant(realpathSync(entry)===entry,'do not write through a symlinked launcher entry'); + invariant(readFileSync(entry,'utf8').includes('StartupWMClass=pulse-desktop'),'only replace our own launcher entry'); + } + writeFileSync(entry,desktopEntry(join(dest,'pulse-desktop'),join(dest,'pulse-desktop.png'))); + console.log(`Installed ${dest}`); + } + process.exit(0); +} if(process.argv.includes('--package') || process.argv.includes('--install')) { invariant(process.platform==='darwin','this installer targets macOS'); const packagedIcon=join(assets,'Pulse.icns'); diff --git a/LifeOS/install/LIFEOS/PULSE/Desktop/linux.test.ts b/LifeOS/install/LIFEOS/PULSE/Desktop/linux.test.ts new file mode 100644 index 0000000000..e45a532349 --- /dev/null +++ b/LifeOS/install/LIFEOS/PULSE/Desktop/linux.test.ts @@ -0,0 +1,165 @@ +/** + * Pulse Desktop on Linux: what only Linux needs lives in `linux.ts`, and the app files call it from the branch that is not + * the macOS one. The test reads the accelerators and labels from the app files themselves, so a new shortcut with no + * Linux key fails here instead of silently in use. + */ +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { + desktopEntry, EDIT_ROLES, isEditRole, isLinux, linuxEditCommand, LINUX_PULSE_START, linuxAccelerator, linuxBrowserCommand, linuxMenu, linuxMenuCommand, + linuxShortcutLabel, linuxTerminalSwallows, linuxTmuxConfig, matchesAccelerator, type MenuEntry, +} from "./linux"; + +const DESKTOP = import.meta.dir; +const read = (file: string) => readFileSync(join(DESKTOP, file), "utf8"); +const main = read("main.ts"); + +/** Every accelerator of the author's menu, the page shortcuts (⌘1…⌘3) spelled out. */ +function authorAccelerators(): string[] { + const fixed = [...main.matchAll(/accelerator:'([^']+)'/g)].map(m => m[1]); + const pageLine = read("commands.ts").split("\n").find(l => l.startsWith("const pageShortcuts"))!; + const pages = [...pageLine.matchAll(/'⌘(\d)'/g)].map(m => `CmdOrCtrl+${m[1]}`); + expect(pages.length).toBe(3); + expect(main).toContain("accelerator:`CmdOrCtrl+${p.shortcut!.slice(1)}`"); + return [...fixed, ...pages]; +} + +test("every menu accelerator gets a distinct Ctrl+Shift key on Linux", () => { + const mac = authorAccelerators(); + expect(mac.length).toBeGreaterThan(15); + const added = linuxMenu([{ role: "editMenu" }, { role: "windowMenu" }, { role: "quit" }]) + .flatMap(i => [i, ...(i.submenu ?? [])]).map(i => i.accelerator).filter((a): a is string => !!a); + const linux = [...mac.map(linuxAccelerator), ...added]; + for (const a of linux) expect(a).toMatch(/^Ctrl\+Shift\+/); + expect(new Set(linux).size).toBe(linux.length); + expect(linuxAccelerator("CmdOrCtrl+T")).toBe("Ctrl+Shift+T"); + expect(linuxAccelerator("CmdOrCtrl+Shift+T")).toBe("Ctrl+Shift+Alt+T"); + expect(linuxAccelerator("CmdOrCtrl+Alt+R")).toBe("Ctrl+Shift+F5"); + expect(linuxAccelerator("Control+Command+F")).toBe("Ctrl+Shift+F"); +}); + +test("an accelerator with no Linux key fails loudly", () => { + expect(() => linuxAccelerator("CmdOrCtrl+Alt+T")).toThrow(/linux\.ts/); + expect(() => linuxAccelerator("Ctrl+T")).toThrow(/Command/); + expect(() => linuxAccelerator("Hyper+T")).toThrow(/Unknown modifier/); +}); + +test("the Linux menu drops macOS-only roles and leaves no Ctrl without Shift", () => { + const roles = new Set([...main.matchAll(/role:'(\w+)'/g)].map(m => m[1])); + const template: MenuEntry[] = [ + { label: "Pulse Desktop", submenu: [...roles].filter(r => !["editMenu", "windowMenu", "close"].includes(r)).flatMap(r => [{ role: r }, { type: "separator" }]) }, + { label: "File", submenu: [{ label: "New", accelerator: "CmdOrCtrl+T" }, { role: "close", label: "Close Window", accelerator: "CmdOrCtrl+Shift+W" }] }, + { role: "editMenu" }, + { role: "windowMenu" }, + ]; + const linux = linuxMenu(template); + const flat = (items: MenuEntry[]): MenuEntry[] => items.flatMap(i => [i, ...flat(i.submenu ?? [])]); + const all = flat(linux); + for (const item of all) { + if (item.accelerator) expect(item.accelerator).toMatch(/^Ctrl\+Shift\+/); + if (item.role && !["about", "close"].includes(item.role)) expect(item.accelerator).toBeDefined(); + } + for (const gone of ["services", "hide", "hideOthers", "unhide", "editMenu", "windowMenu"]) expect(all.some(i => i.role === gone)).toBe(false); + expect(all.find(i => i.role === "quit")?.accelerator).toBe("Ctrl+Shift+Q"); + const app = linux[0].submenu!; + for (let i = 1; i < app.length; i++) expect(app[i].type === "separator" && app[i - 1].type === "separator").toBe(false); + expect(() => linuxMenu([{ role: "reload" }])).toThrow(/needs a Linux accelerator/); +}); + +test("letters and digits match by key position, punctuation by character, on any layout", () => { + const key = (code: string, k: string, extra: Partial<{ shift: boolean; alt: boolean }> = {}) => + ({ control: true, shift: true, alt: false, meta: false, code, key: k, ...extra }); + expect(matchesAccelerator("Ctrl+Shift+1", key("Digit1", "!"))).toBe(true); + expect(matchesAccelerator("Ctrl+Shift+T", key("KeyT", "T", { alt: true }))).toBe(false); + expect(matchesAccelerator("Ctrl+Shift+Alt+T", key("KeyT", "T", { alt: true }))).toBe(true); + expect(matchesAccelerator("Ctrl+Shift+T", { ...key("KeyT", "t"), shift: false })).toBe(false); + // US: "[" is BracketLeft. ABNT2 (xkb symbols/br): "[" is the US BracketRight key, "]" the US Backslash key. + expect(matchesAccelerator("Ctrl+Shift+[", key("BracketLeft", "{"))).toBe(true); + expect(matchesAccelerator("Ctrl+Shift+[", key("BracketRight", "{"))).toBe(true); + expect(matchesAccelerator("Ctrl+Shift+]", key("BracketRight", "{"))).toBe(false); + expect(matchesAccelerator("Ctrl+Shift+]", key("Backslash", "}"))).toBe(true); + expect(matchesAccelerator("Ctrl+Shift+Plus", key("Equal", "+"))).toBe(true); + expect(matchesAccelerator("Ctrl+Shift+-", key("Minus", "_"))).toBe(true); +}); + +test("edit commands go to the page, with the role as Electron returns it", () => { + const key = (code: string) => ({ control: true, shift: true, alt: false, meta: false, code, key: code.slice(3) }); + const items = [ + { role: "copy", accelerator: "Ctrl+Shift+C" }, + { role: "selectall", accelerator: "Ctrl+Shift+A" }, + { label: "File", submenu: { items: [{ role: null, accelerator: "Ctrl+Shift+T" }] } }, + ]; + expect(linuxMenuCommand(items, key("KeyC"))).toBeNull(); + expect(linuxMenuCommand(items, key("KeyA"))).toBeNull(); + expect(linuxMenuCommand(items, key("KeyT"))?.accelerator).toBe("Ctrl+Shift+T"); + for (const role of ["undo", "redo", "cut", "copy", "paste", "selectAll", "selectall"]) expect(isEditRole(role)).toBe(true); + const press = (code: string, alt = false) => ({ control: true, shift: true, alt, meta: false, code, key: code.slice(3) }); + expect(["KeyZ", "KeyX", "KeyC", "KeyV", "KeyA"].map(c => linuxEditCommand(press(c)))).toEqual(["undo", "cut", "copy", "paste", "selectAll"]); + expect(linuxEditCommand(press("KeyZ", true))).toBe("redo"); + expect(linuxEditCommand(press("KeyT"))).toBeNull(); + expect(linuxEditCommand({ ...press("KeyC"), shift: false })).toBeNull(); + expect(EDIT_ROLES.size).toBe(6); +}); + +test("in the terminal, Ctrl+Shift edit keys never become ^C, ^X, ^Z or ^A", () => { + const k = (key: string, extra = {}) => ({ ctrlKey: true, shiftKey: true, altKey: false, metaKey: false, key, ...extra }); + for (const key of ["C", "X", "Z", "A"]) expect(linuxTerminalSwallows(k(key), false)).toBe(true); + expect(linuxTerminalSwallows(k("C"), true)).toBe(false); + expect(linuxTerminalSwallows(k("V"), false)).toBe(false); + expect(linuxTerminalSwallows(k("c", { shiftKey: false }), false)).toBe(false); + expect(linuxTerminalSwallows(k("Z", { altKey: true }), false)).toBe(false); +}); + +test("every shortcut the app shows names the Linux key", () => { + const shown = ["workspace.ts", "commands.ts", "workspace.html"].flatMap(f => [...read(f).matchAll(/[⌃⌥⇧]*[⌘⌃][^\s'"<`]/gu)].map(m => m[0])); + expect(shown.length).toBeGreaterThan(15); + for (const label of shown) expect(linuxShortcutLabel(label)).not.toMatch(/[⌘⌃⇧⌥]/u); + // Text the renderer sets after start-up escapes the one-time kbd/title pass. The shipped line stays as written, + // so each such label is followed by its Linux line, which writes the same text through keyLabel. + const code = read("workspace.ts").replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, ""); + const glyphLabels = [...code.matchAll(/\$\('([\w-]+)'\)\.textContent='([^']*[⌘⌃⇧⌥][^']*)'/gu)]; + expect(glyphLabels.length).toBeGreaterThan(0); + for (const [, id, text] of glyphLabels) expect(code).toContain(`if(LINUX)$('${id}').textContent=keyLabel('${text}');`); + expect(linuxShortcutLabel("⇧⌘W")).toBe("Ctrl+Shift+Alt+W"); + expect(linuxShortcutLabel("⌃H / ⌃L")).toBe("Ctrl+H / Ctrl+L"); + expect(linuxShortcutLabel("After ⌘B; Enter selects")).toBe("After Ctrl+Shift+B; Enter selects"); + expect(linuxShortcutLabel("⌘+")).toBe("Ctrl+Shift+Plus"); + // The offline page runs no script: the author's file stays as written, and the Linux build writes the converted copy. + expect(read("offline.html")).not.toContain("Ctrl+"); + expect(linuxShortcutLabel(read("offline.html"))).toContain("Shortcut: Ctrl+Shift+Alt+R."); + expect(read("build.ts")).toContain("linuxShortcutLabel(readFileSync(join(root,'offline.html'),'utf8'))"); +}); + +test("the shipped tmux.conf gets the login shell and wl-copy", () => { + for (const shell of ["/usr/bin/bash", "/usr/bin/zsh", "/bin/zsh", "/usr/local/bin/zsh", "/usr/bin/fish"]) { + const conf = linuxTmuxConfig(read("tmux.conf"), shell); + expect(conf).toContain(`set -g default-shell ${shell}\n`); + expect(conf).toContain(`default-command '${shell} -l'`); + expect(conf.split('copy-pipe-and-cancel "wl-copy"').length - 1).toBe(2); + expect(conf).not.toContain("pbcopy"); + } + expect(() => linuxTmuxConfig(read("tmux.conf"), "/opt/my shell")).toThrow(/spaces/); + expect(() => linuxTmuxConfig(read("tmux.conf"), "bash")).toThrow(/absolute/); + expect(() => linuxTmuxConfig("set -g x 'pbcopy'", "/usr/bin/bash")).toThrow(/changed shape/); +}); + +test("links, Pulse start and the launcher entry", () => { + expect(linuxBrowserCommand("https://example.com")).toEqual(["google-chrome-stable", ["https://example.com"]]); + expect(LINUX_PULSE_START).toEqual(["systemctl", ["--user", "start", "com.lifeos.pulse.service"]]); + const entry = desktopEntry("/home/u/.local/share/pulse-desktop/pulse-desktop", "/home/u/.local/share/pulse-desktop/pulse-desktop.png"); + expect(entry).toContain('Exec="/home/u/.local/share/pulse-desktop/pulse-desktop"'); + expect(entry).toContain("StartupWMClass=pulse-desktop"); + expect(() => desktopEntry('/tmp/a"b', "/i.png")).toThrow(/quotes/); + expect(() => desktopEntry("/tmp/50%/app", "/i.png")).toThrow(/%/); +}); + +test("one platform test picks the Linux path, and only on Linux", () => { + for (const p of ["linux", "Linux x86_64", "Linux aarch64"]) expect(isLinux(p)).toBe(true); + for (const p of ["darwin", "MacIntel", "win32", "Win32", "freebsd", ""]) expect(isLinux(p)).toBe(false); + // Every app file decides by that one test; none branches on "not macOS". + for (const f of ["main.ts", "terminals.ts", "build.ts", "workspace.ts"]) { + expect(read(f)).toMatch(/const LINUX=isLinux\((process|navigator)\.platform\);/); + expect(read(f)).not.toContain("isMacPlatform(navigator.platform)?"); + } +}); diff --git a/LifeOS/install/LIFEOS/PULSE/Desktop/linux.ts b/LifeOS/install/LIFEOS/PULSE/Desktop/linux.ts new file mode 100644 index 0000000000..7d934d81b5 --- /dev/null +++ b/LifeOS/install/LIFEOS/PULSE/Desktop/linux.ts @@ -0,0 +1,218 @@ +/** + * What Pulse Desktop needs on Linux in place of its macOS-only parts. The app was written for macOS; on any other + * platform the author's files call this module from a branch that leaves the macOS path as written. + * + * Keys: the window manager owns Super, and a bare Ctrl chord belongs to the shell, so every app shortcut that uses ⌘ + * on macOS uses Ctrl+Shift here, the way kitty and Chrome do on Linux. ⇧⌘ adds Alt, and ⌥⌘R (reload without cache), + * which would land on ⇧⌘R, becomes Ctrl+Shift+F5. The ⌃H / ⌃L session switches stay as the author made them. + * + * Pure functions only: the workspace renderer imports the label mapping, so nothing here touches Node. + */ + +/** The one platform test: `process.platform` in the main process and the build, `navigator.platform` in the renderer. + * Every Linux branch in the app files tests it, so every other platform runs the shipped code as written. */ +export const isLinux = (platform: string): boolean => /^linux/i.test(platform); + +const COMMAND = new Set(['CmdOrCtrl', 'CommandOrControl', 'Command', 'Cmd']); +const MODIFIERS = new Set([...COMMAND, 'Shift', 'Alt', 'Option', 'Control', 'Ctrl']); + +function linuxChord(shift: boolean, alt: boolean, key: string, source: string): string { + if (alt) { + if (key === 'R' && !shift) return 'Ctrl+Shift+F5'; + throw new Error(`No Linux shortcut for ${source}: add it to linux.ts`); + } + return shift ? `Ctrl+Shift+Alt+${key}` : `Ctrl+Shift+${key}`; +} + +/** The Linux accelerator for one of the app's macOS menu accelerators (Electron syntax). */ +export function linuxAccelerator(mac: string): string { + const parts = mac.split('+'); + const key = parts.pop()!; + for (const part of parts) if (!MODIFIERS.has(part)) throw new Error(`Unknown modifier ${part} in ${mac}`); + if (!parts.some(p => COMMAND.has(p))) throw new Error(`No Linux shortcut for ${mac}: it has no Command key`); + return linuxChord(parts.includes('Shift'), parts.includes('Alt') || parts.includes('Option'), key, mac); +} + +const KEY_NAMES: Record = { '+': 'Plus', '−': 'Minus', '-': 'Minus' }; + +/** A shortcut as the app shows it (⌘T, ⇧⌘W, ⌃H, "After ⌘B; …"), written with the Linux keys. */ +export function linuxShortcutLabel(text: string): string { + return text + .replace(/([⌃⌥⇧]*)⌘(\S)/gu, (whole, mods: string, key: string) => + linuxChord(mods.includes('⇧'), mods.includes('⌥'), KEY_NAMES[key] ?? key, whole)) + .replace(/⌃(\S)/gu, 'Ctrl+$1'); +} + +export type MenuEntry = { + role?: string; + label?: string; + accelerator?: string; + type?: string; + submenu?: MenuEntry[]; + [key: string]: unknown; +}; + +const MAC_ONLY_ROLES = new Set(['services', 'hide', 'hideOthers', 'unhide']); +/** Edit commands stay with the page and the terminal surface (it owns copy and paste); the menu only backs them up. */ +export const EDIT_ROLES = new Set(['undo', 'redo', 'cut', 'copy', 'paste', 'selectall']); +/** Electron lowercases a live MenuItem's role (selectAll → selectall), so roles compare in lowercase. */ +export const isEditRole = (role: string | null | undefined) => !!role && EDIT_ROLES.has(role.toLowerCase()); +const LINUX_EDIT: MenuEntry = { + label: 'Edit', + submenu: [ + { role: 'undo', accelerator: 'Ctrl+Shift+Z' }, + { role: 'redo', accelerator: 'Ctrl+Shift+Alt+Z' }, + { type: 'separator' }, + { role: 'cut', accelerator: 'Ctrl+Shift+X' }, + { role: 'copy', accelerator: 'Ctrl+Shift+C' }, + { role: 'paste', accelerator: 'Ctrl+Shift+V' }, + { role: 'selectAll', accelerator: 'Ctrl+Shift+A' }, + ], +}; +const LINUX_WINDOW: MenuEntry = { label: 'Window', submenu: [{ role: 'minimize', accelerator: 'Ctrl+Shift+M' }] }; +/** Roles that carry no default accelerator; any other role must get an explicit Linux one. */ +const SILENT_ROLES = new Set(['about', 'close']); + +function convert(item: MenuEntry): MenuEntry[] { + if (item.role && MAC_ONLY_ROLES.has(item.role)) return []; + if (item.role === 'editMenu') return [LINUX_EDIT]; + if (item.role === 'windowMenu') return [LINUX_WINDOW]; + if (item.role === 'quit') return [{ ...item, accelerator: 'Ctrl+Shift+Q' }]; + const out: MenuEntry = { ...item }; + if (item.accelerator) out.accelerator = linuxAccelerator(item.accelerator); + else if (item.role && !SILENT_ROLES.has(item.role)) throw new Error(`Menu role ${item.role} needs a Linux accelerator`); + if (item.submenu) { + out.submenu = item.submenu.flatMap(convert) + .filter((entry, i, all) => entry.type !== 'separator' || (i > 0 && all[i - 1].type !== 'separator')); + } + return [out]; +} + +/** The app menu for Linux: macOS-only roles out, explicit Linux accelerators, and none that is a bare Ctrl chord. */ +export function linuxMenu(template: T[]): T[] { + return template.flatMap(convert) as T[]; +} + +/** Punctuation keys sit in different places on each layout (on ABNT2 "]" is the US Backslash key), so they match by the + * character the key types, unshifted or shifted. */ +const PUNCTUATION: Record = { '[': ['[', '{'], ']': [']', '}'], Plus: ['=', '+'], '=': ['=', '+'], '-': ['-', '_'] }; +function keyMatches(key: string, input: KeyInput): boolean { + if (/^[a-z]$/i.test(key)) return input.code === 'Key' + key.toUpperCase(); + if (/^\d$/.test(key)) return input.code === 'Digit' + key; + if (/^F\d{1,2}$/.test(key)) return input.code === key; + const chars = PUNCTUATION[key]; + if (!chars) throw new Error(`No Linux key for ${key}: add it to linux.ts`); + return chars.includes(input.key); +} + +export type KeyInput = { control: boolean; shift: boolean; alt: boolean; meta: boolean; code: string; key: string }; + +/** Whether a key press is this Linux accelerator: letters, digits and F-keys by physical key (Shift turns 1 into !), + * punctuation by the character the layout gives it. */ +export function matchesAccelerator(accelerator: string, input: KeyInput): boolean { + const parts = accelerator.split('+'); + const key = parts.pop()!; + return !input.meta && input.control === parts.includes('Ctrl') && input.shift === parts.includes('Shift') + && input.alt === parts.includes('Alt') && keyMatches(key, input); +} + +export type EditCommand = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'selectAll'; +const EDIT_COMMANDS: Record = { undo: 'undo', redo: 'redo', cut: 'cut', copy: 'copy', paste: 'paste', selectall: 'selectAll' }; + +/** + * The edit command a key press asks for, by the Linux Edit menu. With the menu bar hidden, Electron on Linux does not + * run these from the menu, so the main process runs them on text fields itself (webContents.copy() and the rest). + */ +export function linuxEditCommand(input: KeyInput): EditCommand | null { + for (const item of LINUX_EDIT.submenu!) { + if (item.role && item.accelerator && matchesAccelerator(item.accelerator, input)) return EDIT_COMMANDS[item.role.toLowerCase()]; + } + return null; +} + +/** + * Edit chords the terminal must not encode. The Ghostty surface copies with Ctrl+Shift+C when text is selected and + * pastes with Ctrl+Shift+V; with nothing selected its encoder sends Ctrl+Shift+C as ^C, and Ctrl+Shift+X/Z/A as + * ^X/^Z/^A, so the shown copy key would interrupt the program and the undo key suspend it. Those presses stop here. + */ +export function linuxTerminalSwallows(e: { ctrlKey: boolean; shiftKey: boolean; altKey: boolean; metaKey: boolean; key: string }, hasSelection: boolean): boolean { + if (!e.ctrlKey || !e.shiftKey || e.altKey || e.metaKey) return false; + const key = e.key.toLowerCase(); + return key === 'x' || key === 'z' || key === 'a' || (key === 'c' && !hasSelection); +} + +type LiveItem = { role?: string | null; accelerator?: string | null; submenu?: { items: LiveItem[] } | null }; + +/** + * The menu command a key press runs, edit commands excepted. The main process runs it before the page sees the key, + * so the terminal never encodes an app shortcut as shell input. + */ +export function linuxMenuCommand(items: readonly T[], input: KeyInput): T | null { + for (const item of items) { + if (item.accelerator && !isEditRole(item.role) && matchesAccelerator(item.accelerator, input)) return item; + const found = item.submenu ? linuxMenuCommand(item.submenu.items as T[], input) : null; + if (found) return found; + } + return null; +} + +/** tmux on Linux lives in the system path. */ +export const LINUX_TMUX = ['/usr/bin/tmux', '/usr/local/bin/tmux']; +export const LINUX_TMUX_MISSING = 'tmux is required. Install it with your package manager (for example: sudo pacman -S tmux).'; + +const TMUX_SHELL = 'set -g default-shell /bin/zsh\n'; +const TMUX_COMMAND = "set -g default-command '/bin/zsh -l'\n"; + +/** The author's tmux.conf with the user's login shell for zsh and the Wayland clipboard for pbcopy. The author's lines + * are checked as they are, so a changed tmux.conf fails here instead of starting the wrong shell. */ +export function linuxTmuxConfig(config: string, shell: string): string { + if (!shell.startsWith('/') || /[\s'"]/.test(shell)) throw new Error(`Login shell must be an absolute path without spaces or quotes, got ${shell}`); + const copies = config.split('"pbcopy"').length - 1; + if (!config.includes(TMUX_SHELL) || !config.includes(TMUX_COMMAND) || copies !== 2 || config.replaceAll('"pbcopy"', '').includes('pbcopy')) { + throw new Error('tmux.conf changed shape: update linuxTmuxConfig in linux.ts'); + } + return config.replace(TMUX_SHELL, `set -g default-shell ${shell}\n`) + .replace(TMUX_COMMAND, `set -g default-command '${shell} -l'\n`) + .replaceAll('"pbcopy"', '"wl-copy"'); +} + +/** Where the stable tmux config lives (macOS: ~/Library/Application Support/LifeOS/pulse-terminal). */ +export function linuxTerminalDir(home: string): string { + return `${home}/.local/share/LifeOS/pulse-terminal`; +} + +/** The shell environment with the login shell and the PATH the app started with, without the Homebrew prefix. */ +export function linuxShellEnvironment(env: Record, path: string | undefined, shell: string): Record { + return { ...env, SHELL: shell, PATH: path || '/usr/local/bin:/usr/bin:/bin' }; +} + +/** Font folders for the kitty font file: the user's, then the system's with one level of subfolders (Arch: TTF/, OTF/). */ +export function linuxFontDirs(home: string, subdirs: (dir: string) => string[]): string[] { + const roots = [`${home}/.local/share/fonts`, `${home}/.fonts`, '/usr/local/share/fonts', '/usr/share/fonts']; + return roots.flatMap(root => [root, ...subdirs(root)]); +} + +/** HTTPS links open in Google Chrome, as `open -a "Google Chrome"` does on macOS. */ +export function linuxBrowserCommand(url: string): [string, string[]] { + return ['google-chrome-stable', [url]]; +} + +/** Starts the installed Pulse user service; `start` leaves a running one alone, like `launchctl kickstart` without -k. */ +export const LINUX_PULSE_START: [string, string[]] = ['systemctl', ['--user', 'start', 'com.lifeos.pulse.service']]; + +/** The launcher entry for the installed app. */ +export function desktopEntry(exec: string, icon: string): string { + if (/["\\`$%\n]/.test(exec) || /\n/.test(icon)) throw new Error('Install paths must not hold quotes, backslashes, $, % or newlines'); + return [ + '[Desktop Entry]', + 'Type=Application', + 'Name=Pulse Desktop', + 'Comment=LifeOS Pulse dashboard with persistent terminal sessions', + `Exec="${exec}"`, + `Icon=${icon}`, + 'Terminal=false', + 'Categories=Utility;', + 'StartupWMClass=pulse-desktop', + '', + ].join('\n'); +} diff --git a/LifeOS/install/LIFEOS/PULSE/Desktop/main.ts b/LifeOS/install/LIFEOS/PULSE/Desktop/main.ts index 035e59ed65..5687380ab1 100644 --- a/LifeOS/install/LIFEOS/PULSE/Desktop/main.ts +++ b/LifeOS/install/LIFEOS/PULSE/Desktop/main.ts @@ -15,6 +15,11 @@ import {Terminals} from './terminals'; import {endWithConfirmation} from './session-end'; import {nativeCommandAllowed,pages} from './commands'; import {invariant} from '../../TOOLS/Invariant'; +// Linux support: everything only Linux needs lives in linux.ts; each call below sits in a branch that leaves the macOS path as written. +import {spawn} from 'node:child_process'; +import {Notification} from 'electron'; +import {isLinux,linuxBrowserCommand,LINUX_PULSE_START,linuxMenu,linuxMenuCommand,linuxEditCommand,type MenuEntry} from './linux'; +const LINUX=isLinux(process.platform); const exec=promisify(execFile); const resourceDir=join(app.getAppPath(),'dist'); const workspaceURL=pathToFileURL(join(resourceDir,'workspace.html')).href; @@ -55,6 +60,8 @@ function serveAsset(request:Request){ function trusted(e:IpcMainInvokeEvent|IpcMainEvent){return trustedWorkspace(e.sender.id,win?.webContents.id,e.senderFrame?.url||'',workspaceURL,e.senderFrame===e.sender.mainFrame);} async function external(url:unknown){ if(!win||!isExternalURL(url))return; + // Linux: start Chrome detached, since its process can outlive the app and an awaited exec would never return. + if(LINUX){const [bin,args]=linuxBrowserCommand(url);$1return;} await exec('/usr/bin/open',['-a','Google Chrome',url]); } async function ready(){try{const r=await fetch(ORIGIN+'/healthz',{signal:AbortSignal.timeout(2500),redirect:'error'});return r.ok&&dashboardReady(await r.json());}catch{return false;}} @@ -62,7 +69,9 @@ async function connect(){ const target=dashboard?.webContents;if(!target||connecting.has(target))return; connecting.add(target); try{ + // Linux: Pulse runs as a systemd user service, and `start` leaves a running one alone; a failed start shows a notification instead of only an offline page. if(!(await ready())&&process.platform==='darwin')await exec('/bin/launchctl',['kickstart',`gui/${process.getuid!()}/com.lifeos.pulse`],{timeout:5000}).catch(()=>{}); + if(LINUX&&!(await ready()))await exec(LINUX_PULSE_START[0],LINUX_PULSE_START[1],{timeout:5000}).catch((error:{stderr?:string;message:string})=>{const reason=(error.stderr||error.message).trim();console.error('Pulse did not start:',reason);new Notification({title:'Pulse did not start',body:reason}).show();}); for(let i=0;i<6;i++){ const available=await ready();if(target.isDestroyed())return; if(available){ @@ -93,7 +102,27 @@ function saveState(){ invariant(Number.isFinite(state.width)&&isPulseURL(ORIGIN+state.route),'valid desktop state'); const path=join(app.getPath('userData'),'window.json');writeFileSync(path+'.tmp',JSON.stringify(state),{mode:0o600});renameSync(path+'.tmp',path); } +// Linux: app shortcuts are Ctrl+Shift (linux.ts), and the main process runs them before the key reaches the page, so the terminal never sends them to the shell. +function linuxShortcut(wc:WebContents,e:Electron.Event,input:Electron.Input){ + const key=input.key.toLowerCase(); + if(input.control&&input.shift&&!input.alt&&!input.meta&&input.code==='KeyK'){e.preventDefault();swallowed.add(input.code);if(!input.isAutoRepeat){win?.webContents.focus();send('workspace:palette');}return;} + // Text fields with no terminal (the command menu, the Pulse pages) get the Ctrl+Shift edit keys from here; bare Ctrl + // editing is Chromium's own. The terminal keeps them: its surface copies and pastes, and workspace.ts stops the rest. + const command=(paletteVisible||wc!==win?.webContents)?linuxEditCommand(input):null; + if(command){e.preventDefault();swallowed.add(input.code);wc[command]();return;} + if(paletteVisible){wc.setIgnoreMenuShortcuts(true);return;} + wc.setIgnoreMenuShortcuts(false); + const item=linuxMenuCommand(Menu.getApplicationMenu()?.items??[],input); + if(item){e.preventDefault();swallowed.add(input.code);if(input.isAutoRepeat&&input.code==='KeyW')return;if(item.enabled)item.click(undefined,win!,undefined);return;} + if(input.control&&!input.alt&&!input.meta&&['h','l'].includes(key)){e.preventDefault();swallowed.add(input.code);send('workspace:cycle',key==='h'?-1:1);} +} +/** Keys whose press the main process ran as an app shortcut: their release is held back too, so a terminal program + * that asked for key releases (kitty keyboard protocol) never gets a release for a press it never saw. */ +const swallowed=new Set(); +function linuxRelease(e:Electron.Event,input:Electron.Input){if(swallowed.delete(input.code))e.preventDefault();} function shortcuts(wc:WebContents){wc.on('before-input-event',(e,input)=>{ + // Linux shortcuts branch off here, before the keyDown-only return below, because Linux also holds back the key release. The rest of the function is the macOS path. + if(LINUX){if(input.type==='keyDown')linuxShortcut(wc,e,input);else if(input.type==='keyUp')linuxRelease(e,input);return;} if(input.type!=='keyDown')return; if(input.meta&&!input.control&&!input.alt&&!input.shift&&input.key.toLowerCase()==='k'){e.preventDefault();if(!input.isAutoRepeat){win?.webContents.focus();send('workspace:palette');}return;} if(paletteVisible){ @@ -125,6 +154,8 @@ function createWindow(){ const bounds=restoreWindowBounds(state,screen.getAllDisplays().map(display=>display.workArea),screen.getPrimaryDisplay().workArea); const window=new BrowserWindow({...bounds,minWidth:1000,minHeight:650,title:'Pulse Desktop',backgroundColor:'#050b17',show:false,webPreferences:{...rendererPreferences,backgroundThrottling:false,preload:join(resourceDir,'preload.cjs'),partition:'persist:pulse-workspace'}}); win=window; + // Linux: Electron draws the menu inside the window (macOS shows it in the system bar), so it is hidden; its shortcuts still run through linuxShortcut. + if(LINUX)window.setMenuBarVisibility(false); // When Pulse regains OS focus while a terminal is the active view, route focus to the workspace // webContents (not the hidden dashboard) so its window-focus handler lands the caret in the shell. window.on("focus",()=>{if(!pageVisible)window.webContents.focus();}); @@ -223,14 +254,16 @@ function setupIPC(){ function menu(){ const contents=()=>pageVisible?dashboard?.webContents:win?.webContents; const zoom=(delta:number)=>{if(pageVisible){const c=dashboard?.webContents;if(c)c.setZoomLevel(delta===0?0:Math.max(-3,Math.min(4,c.getZoomLevel()+delta)));}else send('workspace:zoom',delta);}; - Menu.setApplicationMenu(Menu.buildFromTemplate([ + // Linux: the same menu goes through linuxMenu (no macOS-only roles, Linux keys). + const forPlatform=(template:Electron.MenuItemConstructorOptions[])=>LINUX?linuxMenu(template as MenuEntry[]) as Electron.MenuItemConstructorOptions[]:template; + Menu.setApplicationMenu(Menu.buildFromTemplate(forPlatform([ {label:'Pulse Desktop',submenu:[{role:'about'},{type:'separator'},{role:'services'},{type:'separator'},{role:'hide'},{role:'hideOthers'},{role:'unhide'},{type:'separator'},{role:'quit'}]}, {label:'File',submenu:[{label:'New Terminal',accelerator:'CmdOrCtrl+T',click:()=>send('workspace:new')},{label:'New Terminal in Folder…',accelerator:'CmdOrCtrl+Shift+T',click:()=>send('workspace:new',{chooseFolder:true})},{label:'Open Pulse',accelerator:'CmdOrCtrl+N',click:()=>{if(!win)createWindow();else win.show();}},{id:'reconnect',label:'Reconnect to Pulse',accelerator:'CmdOrCtrl+Shift+R',click:()=>void connect()},{type:'separator'},{label:'Close Session…',accelerator:'CmdOrCtrl+W',click:()=>send('workspace:close')},{role:'close',label:'Close Window',accelerator:'CmdOrCtrl+Shift+W'}]}, {role:'editMenu'}, {label:'View',submenu:[{label:'Command Menu…',accelerator:'CmdOrCtrl+K',click:()=>{win?.webContents.focus();send('workspace:palette');}},{id:'reload',label:'Reload',accelerator:'CmdOrCtrl+R',click:()=>contents()?.reload()},{label:'Force Reload',accelerator:'CmdOrCtrl+Alt+R',click:()=>contents()?.reloadIgnoringCache()},{type:'separator'},{id:'zoom-reset',label:'Actual Size',accelerator:'CmdOrCtrl+0',click:()=>zoom(0)},{id:'zoom-in',label:'Zoom In',accelerator:'CmdOrCtrl+Plus',click:()=>zoom(.5)},{id:'zoom-out',label:'Zoom Out',accelerator:'CmdOrCtrl+-',click:()=>zoom(-.5)},{type:'separator'},{id:'fullscreen',label:'Toggle Full Screen',accelerator:'Control+Command+F',click:()=>{if(win)win.setFullScreen(!win.isFullScreen());}}]}, {label:'Navigate',submenu:[{label:'Focus Sessions',accelerator:'CmdOrCtrl+B',click:()=>{win?.webContents.focus();send('workspace:focus');}},{id:'back',label:'Back',accelerator:'CmdOrCtrl+[',click:()=>{if(dashboard?.webContents.navigationHistory.canGoBack())dashboard.webContents.navigationHistory.goBack();}},{id:'forward',label:'Forward',accelerator:'CmdOrCtrl+]',click:()=>{if(dashboard?.webContents.navigationHistory.canGoForward())dashboard.webContents.navigationHistory.goForward();}},...pages.filter(p=>p.shortcut).map(p=>({label:p.title,accelerator:`CmdOrCtrl+${p.shortcut!.slice(1)}`,click:()=>send('workspace:page',p.id)}))]}, {role:'windowMenu'}, - ])); + ]))); } // Talk (LIFEOS/DOCUMENTATION/VoiceMode/VoiceMode.md § Talk): `open -n -a "Pulse Desktop" --args --talk=` // raises a small always-on-top window running the live voice conversation for that Claude Code session. diff --git a/LifeOS/install/LIFEOS/PULSE/Desktop/terminals.ts b/LifeOS/install/LIFEOS/PULSE/Desktop/terminals.ts index a2ada9afcb..4a90d7572e 100644 --- a/LifeOS/install/LIFEOS/PULSE/Desktop/terminals.ts +++ b/LifeOS/install/LIFEOS/PULSE/Desktop/terminals.ts @@ -10,9 +10,15 @@ import {invariant} from '../../TOOLS/Invariant'; import {pulseSessionTitle} from '../../TOOLS/PulseSessionTitle'; import {codexSessionTitle} from '../../CODEX/SessionTitle'; import {claudeModelForTerminal} from './session-transcript'; +// Linux: tmux, the config folder, the shell and the clipboard come from linux.ts. +import {userInfo} from 'node:os'; +import {isLinux,LINUX_TMUX,LINUX_TMUX_MISSING,linuxTmuxConfig,linuxTerminalDir,linuxShellEnvironment} from './linux'; +const LINUX=isLinux(process.platform); const exec=promisify(execFile); -const tmux=['/opt/homebrew/bin/tmux','/usr/local/bin/tmux'].find(existsSync); -const env=shellEnvironment(process.env); +// Linux: the system tmux. +const tmux=LINUX?LINUX_TMUX.find(existsSync):['/opt/homebrew/bin/tmux','/usr/local/bin/tmux'].find(existsSync); +// Linux: the user's login shell, and a PATH without the Homebrew prefix. +const env=LINUX?linuxShellEnvironment(shellEnvironment(process.env),process.env.PATH,userInfo().shell!):shellEnvironment(process.env); export type TerminalInfo={id:string;title:string;command:string;directory:string;decoration?:{sessionName?:string;provider?:"Claude Code"|"Codex"|"LifeOS";model?:string;codexThreadId?:string;inactiveBg:string;inactiveFg:string;activeBg:string;activeFg:string}}; export class Terminals { private clients=new Map(); @@ -29,16 +35,21 @@ export class Terminals { private configPath(){ if(this.stableConfig)return this.stableConfig; if(!existsSync(this.config)){this.stableConfig=this.config;return this.config;} + // Linux: the stable copy lives under ~/.local/share and swaps zsh and pbcopy for the login shell and wl-copy. + if(LINUX){const dir=linuxTerminalDir(homedir());mkdirSync(dir,{recursive:true});const stable=join(dir,'tmux.conf');const next=linuxTmuxConfig(readFileSync(this.config,'utf8'),userInfo().shell!);if(!existsSync(stable)||readFileSync(stable,'utf8')!==next)writeFileSync(stable,next);this.stableConfig=stable;return stable;} const dir=join(homedir(),'Library/Application Support/LifeOS/pulse-terminal');mkdirSync(dir,{recursive:true}); const stable=join(dir,'tmux.conf');const next=readFileSync(this.config,'utf8'); if(!existsSync(stable)||readFileSync(stable,'utf8')!==next)writeFileSync(stable,next); this.stableConfig=stable;return stable; } private async run(args:string[]){ + // Linux: the missing-tmux message names the Linux installer. + if(!tmux&&LINUX)throw new Error(LINUX_TMUX_MISSING.replace(/\.$/,', then reconnect.')); if(!tmux)throw new Error('tmux is required. Install it with brew install tmux, then reconnect.'); return (await exec(tmux,['-L','pulse-desktop','-f',this.configPath(),...args],{env,timeout:5000,maxBuffer:1024*1024})).stdout.trim(); } async list():Promise{ + if(!tmux&&LINUX)throw new Error(LINUX_TMUX_MISSING); if(!tmux)throw new Error('tmux is required. Install it with brew install tmux.'); let text=''; try{text=await this.run(['list-sessions','-F','#{session_name}\t#{@pulse-title}\t#{pane_current_command}\t#{pane_current_path}\t#{@pulse-decoration}\t#{session_id}']);} diff --git a/LifeOS/install/LIFEOS/PULSE/Desktop/workspace.css b/LifeOS/install/LIFEOS/PULSE/Desktop/workspace.css index ab4698ee5b..ddd0f7338e 100644 --- a/LifeOS/install/LIFEOS/PULSE/Desktop/workspace.css +++ b/LifeOS/install/LIFEOS/PULSE/Desktop/workspace.css @@ -78,3 +78,11 @@ footer div span{margin-left:0} footer kbd,.persist{font-size:14px} .persist{margin-top:4px;gap:8px} .persist i{width:6px;height:6px} +/* Linux: shortcuts are spelled out (Ctrl+Shift+T) and do not fit the space of the macOS glyphs, so the button's moves under its name, smaller, and the footer hint wraps when it does not fit beside the keys. */ +.linux-keys .create button:first-child{display:flex;flex-direction:column;align-items:flex-start;gap:3px;white-space:nowrap} +.linux-keys .create kbd{float:none;font-size:11px;white-space:nowrap} +.linux-keys footer #commands kbd{font-size:12px;white-space:nowrap} +.linux-keys footer div{flex-wrap:wrap;column-gap:8px;row-gap:2px} +.linux-keys footer .keys{min-width:0} +.linux-keys footer kbd{font-size:12px;white-space:nowrap} +.linux-keys footer div>span:not(.keys){white-space:nowrap} diff --git a/LifeOS/install/LIFEOS/PULSE/Desktop/workspace.ts b/LifeOS/install/LIFEOS/PULSE/Desktop/workspace.ts index c60928a1ed..812ba56e6d 100644 --- a/LifeOS/install/LIFEOS/PULSE/Desktop/workspace.ts +++ b/LifeOS/install/LIFEOS/PULSE/Desktop/workspace.ts @@ -11,6 +11,15 @@ import {TerminalOutput} from './terminal-output'; import {copyTerminalSelection} from './terminal-copy'; import {selectionAfterRefresh} from './session-selection'; import {backgroundColor,isBackgroundImageURL,type BackgroundImage} from './background-image'; +// Linux: every shortcut shown names the Linux key (linux.ts), in the fixed HTML labels and in the command menu. +import {isLinux,linuxShortcutLabel,linuxTerminalSwallows} from './linux'; +const LINUX=isLinux(navigator.platform); +const keyLabel=(text:string)=>LINUX?linuxShortcutLabel(text):text; +if(LINUX){ + document.documentElement.classList.add('linux-keys'); + document.querySelectorAll('kbd').forEach(k=>{k.textContent=keyLabel(k.textContent||'');}); + document.querySelectorAll('[title]').forEach(el=>{el.title=keyLabel(el.title);}); +} declare global{interface Window{pulseDesktop:{call:(action:string,args?:unknown)=>Promise;input:(id:string,data:string)=>void;ack:(id:string,length:number)=>void;resize:(id:string,cols:number,rows:number)=>void;on:(name:string,cb:(data:any)=>void)=>()=>void}}} const api=window.pulseDesktop; const $=(id:string)=>document.getElementById(id) as T; @@ -53,6 +62,8 @@ function notice(error:unknown){$('notice').textContent=String(error).replace(/^E const attempt=(fn:()=>Promise)=>void fn().catch(notice); function button(label:string,action:()=>void){const b=document.createElement('button');b.type='button';b.textContent=label;b.onclick=action;return b;} pages.forEach(p=>{const b=button('',()=>attempt(()=>select(p.id)));b.dataset.id=p.id;b.append(pageIcon(p.id),Object.assign(document.createElement('span'),{textContent:p.title}),Object.assign(document.createElement('kbd'),{textContent:p.shortcut||''}));$('pages').append(b);}); +// Linux: the page buttons' shortcut labels. +if(LINUX)$('pages').querySelectorAll('kbd').forEach(k=>{k.textContent=keyLabel(k.textContent||'');}); $('pages-back').onclick=()=>$('pages').scrollBy({left:-Math.max(240,$('pages').clientWidth*.7),behavior:'instant'}); $('pages-next').onclick=()=>$('pages').scrollBy({left:Math.max(240,$('pages').clientWidth*.7),behavior:'instant'}); function pageScrollState(){$('pages-back').disabled=$('pages').scrollLeft<1;$('pages-next').disabled=$('pages').scrollLeft+$('pages').clientWidth>=$('pages').scrollWidth-1;} @@ -71,6 +82,8 @@ function terminal(id:string):Pane{ onSelectionChange:()=>{}, beforeKey:e=>{ const current=panes.get(id); + // Linux: edit shortcuts with no effect in the terminal do not reach it as ^C, ^X, ^Z or ^A. + if(LINUX&&e.type==='keydown'&&linuxTerminalSwallows(e,!!current?.surface?.hasSelection()))return false; switch(terminalKeyDecision(e,!!current?.surface?.hasSelection())){ case 'copy':e.preventDefault();e.stopPropagation();attempt(()=>copyTerminalSelection({writeText:text=>api.call('copy',{text})},current!.surface!.getSelection()));return false; case 'newline':e.preventDefault();api.input(id,'\n');return false; @@ -96,6 +109,7 @@ async function select(id:string){ await api.call('page',{path:id.startsWith('/')?id:'/'});return; } $('kind').textContent='TERMINAL';$('title').textContent=item.title;$('detail').textContent=`${item.command} · ${item.directory}`;$('keyhint').textContent='⌃H / ⌃L switch'; + if(LINUX)$('keyhint').textContent=keyLabel('⌃H / ⌃L switch'); await api.call('terminal');if(tick!==switching)return; for(const [key,p] of panes){p.node.hidden=key!==id;if(key!==id)p.surface?.setVisible(false);} try{await document.fonts.load(`${appearance.fontSize}px PulseTerminal`);}catch{/* no bundled terminal font: the fallback stack renders */} @@ -199,7 +213,13 @@ let commandIndex=0; let paletteBusy=false; let shortcutsOnly=false; let priorFocus:HTMLElement|null=null; +// The command menu shows and searches shortcuts through keyLabel; the shipped catalog is authorCatalog. function commandCatalog():Command[]{ + const catalog=authorCatalog(); + if(!LINUX)return catalog; + return catalog.map(c=>({...c,...(c.shortcut?{shortcut:keyLabel(c.shortcut)}:{}),...(c.detail&&c.group==='Shortcuts'?{detail:keyLabel(c.detail)}:{})})); +} +function authorCatalog():Command[]{ const current=sessions.find(s=>s.id===selected); return [ {id:'new',label:'New terminal',group:'Actions',shortcut:'⌘T',run:()=>create()},