From 34723b006418161e217835e997e07266755539a1 Mon Sep 17 00:00:00 2001 From: Shengyi Jiang Date: Fri, 27 Nov 2026 10:20:41 +0800 Subject: [PATCH 1/5] Follow the desktop's window button layout on Linux Read the button layout from GNOME, Cinnamon and MATE (gsettings), KDE Plasma (kwinrc) and Xfce (xfconf) when the desktop app starts, and show those buttons in that order on that side. Windows keeps its buttons on the right and macOS its traffic lights; neither lets people move them. Lay out the window chrome by side rather than platform, size it by the number of buttons, and keep narrow toolbars clear of the buttons: the phone-width bar on the left, and the chat heading at the 900px minimum window width on the right (also a Windows fix). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + desktop/main.ts | 8 ++++- desktop/preload.cts | 10 ++++++ desktop/window-buttons.ts | 70 ++++++++++++++++++++++++++++++++++++ scripts/check-appearance.mjs | 56 ++++++++++++++++++++++++++++- scripts/check-desktop.mjs | 16 +++++++++ src/web/desktop-chrome.css | 65 +++++++++++++++++---------------- src/web/desktop-chrome.tsx | 44 ++++++++++++++++------- src/web/main.tsx | 2 +- src/web/style.css | 5 ++- tests/window-buttons.test.ts | 41 +++++++++++++++++++++ 11 files changed, 271 insertions(+), 47 deletions(-) create mode 100644 desktop/window-buttons.ts create mode 100644 tests/window-buttons.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f9458cb1..b6c27956 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ Notable changes to Papilot, newest first. The format follows [Keep a Changelog]( ### Changed +- On Linux, the desktop app's window buttons follow your desktop's button layout: the buttons it shows, their order and their side, read from GNOME, Cinnamon, MATE, KDE Plasma or Xfce settings when the app starts. GNOME's default, for example, shows a single close button on the right. Windows keeps its buttons on the right and macOS its traffic lights on the left. - Ctrl/⌘ +, − and 0 now always zoom the whole interface (desktop **Interface size**, or the browser's zoom), including when a PDF or review is shown. Zoom the PDF itself with its toolbar, a pinch or Ctrl/⌘ + scroll. ([#345](https://github.com/PapilotAI/papilot/issues/345)) - Rename **Settings → Check references online** to **Look up references online**. It now also controls PDF downloads. A new **Settings → Zotero** page shows the Zotero library Papilot found on this computer, with its data directory and how many items have a PDF and a citation key, lets you choose another data directory, and holds the **Use PDFs from Zotero** switch; turned off, PDFs from Zotero are no longer used. diff --git a/desktop/main.ts b/desktop/main.ts index 2ec9f97b..135a1b11 100644 --- a/desktop/main.ts +++ b/desktop/main.ts @@ -8,6 +8,7 @@ import { chooseEnvironment } from './environment-window.js'; import { readEnvironment, saveEnvironment, startWsl, linuxPath, type Environment } from './wsl.js'; import { overleafSignIn } from './overleaf-sign-in.js'; import { typelessControl } from './typeless-control.js'; +import { detectWindowButtons, windowButtonsArgument, type WindowButtons } from './window-buttons.js'; const nix = process.env.PAPILOT_INSTALL_METHOD === 'nix'; const packageUpdates = process.env.PAPILOT_DESKTOP_PACKAGE_UPDATES === '1' || @@ -35,6 +36,9 @@ const notifications = desktopNotifications({ }); const typeless = typelessControl(); let typelessSending = false; +// Read the desktop's window button layout while the backend starts. +const windowButtonsLayout = process.platform === 'linux' ? detectWindowButtons() : Promise.resolve(null); +let windowButtons: WindowButtons | null = null; // papilot://new?template=&version= starts a paper from a Universe template. let pendingTemplate: { id: string; version: string } | null = null; function templateLink(url: string) { @@ -68,7 +72,8 @@ function showWindow() { ? path.join(nix && process.env.PAPILOT_DESKTOP_ROOT ? process.env.PAPILOT_DESKTOP_ROOT : app.isPackaged ? process.resourcesPath : path.resolve(fileURLToPath(new URL('../..', import.meta.url))), 'desktop/assets/icon.ico') : process.platform === 'linux' ? path.join(nix && process.env.PAPILOT_DESKTOP_ROOT ? process.env.PAPILOT_DESKTOP_ROOT : app.isPackaged ? process.resourcesPath : path.resolve(fileURLToPath(new URL('../..', import.meta.url))), 'desktop/assets/icon.png') : undefined, show: false, backgroundColor: '#ffffff', webPreferences: { nodeIntegration: false, contextIsolation: true, sandbox: true, - preload: fileURLToPath(new URL('./preload.cjs', import.meta.url)) } }); + preload: fileURLToPath(new URL('./preload.cjs', import.meta.url)), + additionalArguments: windowButtons ? [windowButtonsArgument(windowButtons)] : [] } }); window.webContents.setWindowOpenHandler(({ url }) => { external(url); return { action: 'deny' }; }); window.webContents.on('will-navigate', (event, url) => { if (new URL(url).origin !== origin) { event.preventDefault(); external(url); } @@ -102,6 +107,7 @@ else { void backend.stop().finally(() => { stopped = true; app.quit(); }); }); void app.whenReady().then(async () => { + windowButtons = await windowButtonsLayout; const data = app.getPath('userData'), log = path.join(app.getPath('logs'), 'backend.log'); const wslAssets = app.isPackaged ? path.join(process.resourcesPath, 'wsl') : path.resolve(fileURLToPath(new URL('../wsl', import.meta.url))); const openEnvironment = (error?: string) => chooseEnvironment({ parent: window || undefined, current: readEnvironment(data), assets: wslAssets, root: app.isPackaged ? path.join(process.resourcesPath, 'server') : path.resolve(fileURLToPath(new URL('../..', import.meta.url))), error, diff --git a/desktop/preload.cts b/desktop/preload.cts index 3e8a31c8..443785fc 100644 --- a/desktop/preload.cts +++ b/desktop/preload.cts @@ -7,10 +7,20 @@ const setZoom = (factor: unknown) => { if (typeof factor === 'number' && interfaceSizes.includes(factor)) webFrame.setZoomFactor(factor); }; +// The main process passes the desktop's window button layout (Linux) as an +// argument; see window-buttons.ts. +const windowButtonsArgument = '--papilot-window-buttons='; +let windowButtons: unknown; +try { + const value = process.argv.find(arg => arg.startsWith(windowButtonsArgument)); + if (value) windowButtons = JSON.parse(value.slice(windowButtonsArgument.length)); +} catch { /* the page keeps its default layout */ } + // Expose specific window and user-selected folder actions, not generic IPC or // filesystem access. Papers open in place; their files stay on disk. contextBridge.exposeInMainWorld('papilotDesktop', { platform: process.platform, + windowButtons, typelessStatus: () => ipcRenderer.invoke('papilot:typeless-status'), typelessShortcut: (inputId: string) => ipcRenderer.invoke('papilot:typeless-shortcut', inputId), minimize: () => ipcRenderer.send('papilot:window', 'minimize'), diff --git a/desktop/window-buttons.ts b/desktop/window-buttons.ts new file mode 100644 index 00000000..107b7ed4 --- /dev/null +++ b/desktop/window-buttons.ts @@ -0,0 +1,70 @@ +import { execFile } from 'node:child_process'; +import { readFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; + +// The frameless window draws its own minimize, maximize and close buttons. +// Linux desktops let people choose which buttons appear and on which side, so +// the app reads that choice instead of offering a setting of its own. +export type WindowButton = 'minimize' | 'maximize' | 'close'; +export type WindowButtons = { side: 'left' | 'right'; buttons: WindowButton[] }; +export const WINDOW_BUTTONS_ARGUMENT = '--papilot-window-buttons='; + +function layout(left: WindowButton[], right: WindowButton[]): WindowButtons | null { + const buttons = [...new Set([...left, ...right])]; + if (!buttons.length) return null; + // The controls stay together on the side that holds close, as most layouts + // split only an app menu or title from them. + const side = left.includes('close') ? 'left' : right.includes('close') ? 'right' : left.length >= right.length ? 'left' : 'right'; + return { side, buttons }; +} +const named = (part: string) => part.split(',').map(name => name.trim()).filter((name): name is WindowButton => name === 'minimize' || name === 'maximize' || name === 'close'); +const lettered = (part: string, letters: Record) => [...part].map(letter => letters[letter]).filter(Boolean); + +// GNOME, Cinnamon and MATE: "appmenu:minimize,maximize,close", as gsettings +// prints it in quotes. Names before the colon sit on the left. +export function gtkLayout(value: string): WindowButtons | null { + const [left, right = ''] = value.trim().replace(/^'(.*)'$/, '$1').split(':'); + return layout(named(left), named(right)); +} +// KDE Plasma's kwinrc: ButtonsOnLeft=MS, ButtonsOnRight=HIAX by default. +export function kwinLayout(config: string): WindowButtons | null { + let section = ''; + const values: Record = { ButtonsOnLeft: 'MS', ButtonsOnRight: 'HIAX' }; + for (const line of config.split(/\r?\n/)) { + const header = /^\s*\[(.*)\]\s*$/.exec(line); + if (header) { section = header[1]; continue; } + const entry = /^\s*(ButtonsOnLeft|ButtonsOnRight)\s*=\s*(.*?)\s*$/.exec(line); + if (entry && section === 'org.kde.kdecoration2') values[entry[1]] = entry[2]; + } + const letters = { I: 'minimize', A: 'maximize', X: 'close' } as const; + return layout(lettered(values.ButtonsOnLeft, letters), lettered(values.ButtonsOnRight, letters)); +} +// Xfce's xfwm4 button_layout: "O|HMC", where | is the title. +export function xfwmLayout(value: string): WindowButtons | null { + const [left, right = ''] = value.trim().split('|'); + const letters = { H: 'minimize', M: 'maximize', C: 'close' } as const; + return layout(lettered(left, letters), lettered(right, letters)); +} + +type Run = (command: string, args: string[]) => Promise; +const run: Run = (command, args) => new Promise((resolve, reject) => { + execFile(command, args, { timeout: 2000, encoding: 'utf8' }, (error, stdout) => error ? reject(error) : resolve(stdout)); +}); + +// Resolves to null when the desktop's layout is unknown; the page then keeps +// its own default. +export async function detectWindowButtons({ env = process.env, exec = run, read = (file: string) => readFile(file, 'utf8') }: { env?: NodeJS.ProcessEnv; exec?: Run; read?: (file: string) => Promise } = {}): Promise { + const desktops = (env.XDG_CURRENT_DESKTOP || '').toUpperCase().split(':'); + const gsettings = (schema: string) => exec('gsettings', ['get', schema, 'button-layout']).then(gtkLayout); + try { + if (desktops.includes('KDE')) return kwinLayout(await read(path.join(env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'kwinrc')).catch(() => '')); + if (desktops.includes('XFCE')) return xfwmLayout(await exec('xfconf-query', ['-c', 'xfwm4', '-p', '/general/button_layout']).catch(() => 'O|HMC')); + if (desktops.includes('X-CINNAMON')) return await gsettings('org.cinnamon.desktop.wm.preferences'); + if (desktops.includes('MATE')) return await gsettings('org.mate.Marco.general'); + return await gsettings('org.gnome.desktop.wm.preferences'); + } catch { return null; } +} +// The sandboxed preload cannot import this module; it reads the layout back +// from this argument as JSON. +export const windowButtonsArgument = (layout: WindowButtons) => WINDOW_BUTTONS_ARGUMENT + JSON.stringify(layout); diff --git a/scripts/check-appearance.mjs b/scripts/check-appearance.mjs index 803c2a56..fb680b7a 100644 --- a/scripts/check-appearance.mjs +++ b/scripts/check-appearance.mjs @@ -245,6 +245,60 @@ try { await app.waitForFunction(() => window.zoomCalls.at(-1) === 1); await desktop.close(); + // Window buttons follow the system: Windows on the right, Linux as the + // desktop app reports its desktop's layout, and a left-side close-first + // layout when that is unknown. Toolbar controls never sit under them. + const layouts = [ + ['linux-default', 'linux', undefined, 'left', ['Close window', 'Minimize window', 'Maximize or restore window']], + ['linux-gnome', 'linux', { side: 'right', buttons: ['close'] }, 'right', ['Close window']], + ['linux-right', 'linux', { side: 'right', buttons: ['minimize', 'maximize', 'close'] }, 'right', ['Minimize window', 'Maximize or restore window', 'Close window']], + ['linux-left', 'linux', { side: 'left', buttons: ['close', 'maximize'] }, 'left', ['Close window', 'Maximize or restore window']], + ['windows', 'win32', undefined, 'right', ['Minimize window', 'Maximize or restore window', 'Close window']], + ]; + for (const [name, platform, windowButtons, side, labels] of layouts) { + const chrome = await browser.newContext({ locale: 'en-US', colorScheme: 'light', viewport: { width: 1440, height: 960 } }); + chrome.setDefaultTimeout(15000); + await chrome.addInitScript(([platform, windowButtons]) => { + window.papilotDesktop = { platform, windowButtons, minimize() {}, maximize() {}, close() {} }; + }, [platform, windowButtons]); + await chrome.route('**/api/**', api); + await chrome.route('**/review/**', route => route.fulfill({ contentType: 'text/html', body: '
Review
Paper
' })); + const window = await chrome.newPage(); + window.on('pageerror', error => errors.push(error.message)); + await window.goto(origin); + await window.getByRole('button', { name: /^Refine the introduction/ }).click(); + await expect(window.locator('html')).toHaveAttribute('data-desktop-controls', side); + const buttons = window.locator('.desktop-window-buttons button'); + assert.deepEqual(await buttons.evaluateAll(list => list.map(button => button.getAttribute('aria-label'))), labels, `${name}: buttons and order`); + const clear = async state => { + const result = await window.evaluate(() => { + const controls = document.querySelector('.desktop-window-buttons').getBoundingClientRect(); + const overlaps = [...document.querySelectorAll('button,a,input,select,[role="combobox"]')].filter(element => !element.closest('.desktop-window-buttons')).filter(element => { + const box = element.getBoundingClientRect(); + return box.width > 0 && box.height > 0 && box.top < controls.bottom && box.bottom > controls.top && box.right > controls.left && box.left < controls.right; + }).map(element => element.getAttribute('aria-label') || element.textContent.trim()); + return { left: controls.left, right: controls.right, width: innerWidth, overlaps }; + }); + assert.deepEqual(result.overlaps, [], `${name} (${state}): toolbar controls stay clear of the window buttons`); + if (side === 'right') assert.ok(Math.abs(result.right - result.width) <= 1, `${name} (${state}): buttons reach the right edge`); + else assert.ok(result.left < 20, `${name} (${state}): buttons start at the left edge`); + }; + await clear('sidebar open'); + await window.screenshot({ animations: 'disabled', path: `test-results/window-buttons-${name}.png` }); + await window.getByRole('button', { name: 'Hide task list', exact: true }).click(); + await expect(window.getByRole('button', { name: 'Show task list', exact: true })).toBeVisible(); + await clear('sidebar hidden'); + // Narrow windows show the task list as a drawer over the workspace, so + // check the toolbars with it closed. + for (const width of [900, 680]) { + await window.setViewportSize({ width, height: 700 }); + await window.waitForFunction(() => document.getAnimations().every(animation => animation.playState !== 'running')); + await clear(`${width}px`); + } + await window.screenshot({ animations: 'disabled', path: `test-results/window-buttons-${name}-680.png` }); + await chrome.close(); + } + assert.deepEqual(errors, []); - console.log('Appearance: live colors, iframe sync, validation, per-mode persistence, system mode, cross-tab sync, reset, interface size and responsive layouts passed.'); + console.log('Appearance: live colors, iframe sync, validation, per-mode persistence, system mode, cross-tab sync, reset, interface size, responsive layouts and system window button layouts passed.'); } catch (error) { await page.screenshot({ animations: 'disabled', path: 'test-results/appearance-failure.png' }); console.error(await page.locator('body').innerText()); throw error; } finally { await browser.close(); await server.close(); } diff --git a/scripts/check-desktop.mjs b/scripts/check-desktop.mjs index 2275d01a..6f13eb4d 100644 --- a/scripts/check-desktop.mjs +++ b/scripts/check-desktop.mjs @@ -20,6 +20,15 @@ const data = fs.mkdtempSync(path.join(os.tmpdir(), 'papilot-desktop-test-')); if (process.platform === 'win32') fs.writeFileSync(path.join(data, 'environment.json'), JSON.stringify({ kind: 'native' })); const env = { ...process.env, PAPILOT_DESKTOP_DATA: data, PAPILOT_DESKTOP_NODE: process.execPath, PAPILOT_UPDATE_PROBE: '1', LANG: 'en_US.UTF-8' }; delete env.ELECTRON_RUN_AS_NODE; +// Linux window buttons follow the desktop's layout. Give the app a known one +// (KDE's kwinrc: close, minimize, maximize on the left) so the checks below +// cover reading it. +if (process.platform === 'linux') { + env.XDG_CURRENT_DESKTOP = 'KDE'; + env.XDG_CONFIG_HOME = path.join(data, 'config'); + fs.mkdirSync(env.XDG_CONFIG_HOME); + fs.writeFileSync(path.join(env.XDG_CONFIG_HOME, 'kwinrc'), '[org.kde.kdecoration2]\nButtonsOnLeft=XIA\nButtonsOnRight=\n'); +} const packaged = process.env.PAPILOT_DESKTOP_EXECUTABLE; const packageManaged = process.env.PAPILOT_EXPECT_PACKAGE_MANAGED === '1'; const layerUpdates = Boolean(packaged && !packageManaged); @@ -78,6 +87,13 @@ try { assert.equal(pdf.status, 200); assert.match(Buffer.from(await pdf.arrayBuffer()).subarray(0, 5).toString(), /%PDF-/); assert.equal(await page.locator('.desktop-window-drag').evaluate(element => getComputedStyle(element).getPropertyValue('-webkit-app-region')), 'drag'); assert.equal(await page.evaluate(() => window.papilotDesktop?.platform), process.platform); + if (process.platform === 'linux') { + assert.deepEqual(await page.evaluate(() => window.papilotDesktop?.windowButtons), { side: 'left', buttons: ['close', 'minimize', 'maximize'] }); + const buttons = page.locator('.desktop-window-buttons button'); + await expect(buttons).toHaveCount(3); + await expect(buttons.nth(0)).toHaveAttribute('aria-label', /^(Close window|关闭窗口)$/); + await expect(buttons.nth(1)).toHaveAttribute('aria-label', /^(Minimize window|最小化窗口)$/); + } await expect(page.locator('.pdf-toolbar')).toBeVisible(); // The toolbar can re-render while the paper loads, so read its box until it settles. await expect.poll(async () => (await page.locator('.pdf-toolbar').boundingBox())?.y, { message: 'The content toolbar reaches the top of the window' }).toBe(0); diff --git a/src/web/desktop-chrome.css b/src/web/desktop-chrome.css index a19530cb..43d14d0b 100644 --- a/src/web/desktop-chrome.css +++ b/src/web/desktop-chrome.css @@ -1,15 +1,18 @@ -/* Window controls share the existing toolbar: macOS/Linux on the left, - Windows on the right, with no second title row. */ +/* Window controls share the existing toolbar with no second title row. + macOS keeps them on the left and Windows on the right; Linux follows the + desktop's own button layout. Widths follow the number of buttons. */ .desktop-window-drag{position:fixed;top:0;left:0;width:240px;height:var(--toolbar-height);z-index:20;-webkit-app-region:drag;user-select:none} /* The title row above the sidebar carries the traffic lights; its rule lines up with the toolbars' bottom rules, so the header below needs none. */ -[data-desktop] .sidebar{position:relative;padding-top:var(--toolbar-height);background-image:linear-gradient(var(--line),var(--line));background-size:100% 1px;background-position:0 calc(var(--toolbar-height) - 1px);background-repeat:no-repeat} -[data-desktop] .sidebar-header{border-bottom:0} -[data-desktop] .sidebar-header>.icon-button{position:absolute;top:7px;right:12px;z-index:21;-webkit-app-region:no-drag} +[data-desktop-controls="left"] .sidebar{position:relative;padding-top:var(--toolbar-height);background-image:linear-gradient(var(--line),var(--line));background-size:100% 1px;background-position:0 calc(var(--toolbar-height) - 1px);background-repeat:no-repeat} +[data-desktop-controls="left"] .sidebar-header{border-bottom:0} +[data-desktop-controls="left"] .sidebar-header>.icon-button{position:absolute;top:7px;right:12px;z-index:21;-webkit-app-region:no-drag} +[data-desktop]{--desktop-controls-width:calc(20px + 32px * var(--desktop-window-buttons))} +[data-desktop="win32"]{--desktop-controls-width:calc(46px * var(--desktop-window-buttons))} [data-desktop="darwin"]{--desktop-leading-space:92px} -[data-desktop="linux"]{--desktop-leading-space:112px} -.sidebar-collapsed .desktop-window-drag{width:var(--desktop-leading-space)} -[data-desktop] .sidebar-collapsed .sidebar-toggle{margin-left:var(--desktop-leading-space,0px)} +[data-desktop-controls="left"]:not([data-desktop="darwin"]){--desktop-leading-space:var(--desktop-controls-width)} +[data-desktop-controls="left"] .sidebar-collapsed .desktop-window-drag{width:var(--desktop-leading-space)} +[data-desktop-controls="left"] .sidebar-collapsed .sidebar-toggle{margin-left:var(--desktop-leading-space,0px)} [data-desktop] :is(.pdf-toolbar,.workspace-navigation,.review-placeholder-toolbar,.git-toolbar,.git-details-toolbar,.git-diff-toolbar,.review-host-bar,.panel-heading,.manuscript-side-header){-webkit-app-region:drag} /* Over the changes the host bar lets clicks through to the viewer's own bar, whose controls it marks with these holes. They take no clicks themselves. */ @@ -23,34 +26,36 @@ .desktop-window-buttons button:hover{background:var(--bg-muted);color:var(--text)} .desktop-window-buttons .desktop-window-close:hover{background:var(--red-soft);color:var(--red)} .desktop-window-buttons svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:1.25} -/* Only the panel touching the right edge reserves room for Windows controls. +/* Only the panel touching the right edge reserves room for right-side controls. The review host measures its tools, including this space, for its iframe. */ -[data-desktop="win32"] .desktop-window-drag{left:auto;right:0;width:138px} +[data-desktop-controls="right"] .desktop-window-drag{left:auto;right:0;width:var(--desktop-controls-width)} [data-desktop="win32"] .desktop-window-buttons{gap:0;padding:0;background:var(--bg)} [data-desktop="win32"] .desktop-window-buttons button{width:46px;height:var(--toolbar-height);border-radius:0} [data-desktop="win32"] .desktop-window-close:hover{background:#c42b1c;color:#fff} -[data-desktop="win32"] .sidebar{padding-top:0;background-image:none} -[data-desktop="win32"] .sidebar-header{border-bottom:1px solid var(--line)} -[data-desktop="win32"] .sidebar-header{-webkit-app-region:drag} -[data-desktop="win32"] .sidebar-header>.icon-button{position:static} -[data-desktop="win32"] .sidebar-collapsed .sidebar-toggle{margin-left:0} -[data-desktop="win32"] .main{--desktop-window-space:138px} -[data-desktop="win32"] .manuscript:not(.panel-collapsed)>.manuscript-pages, -[data-desktop="win32"] .task-grid.layout-split>.review-panel{--desktop-window-space:0px} -[data-desktop="win32"] :is(.pdf-toolbar,.workspace-navigation,.review-placeholder-toolbar,.panel-heading,.manuscript-side-header,.git-details-toolbar,.git-diff-toolbar,.review-tools){padding-right:calc(8px + var(--desktop-window-space,0px))} -[data-desktop="win32"] .review-host-bar.pdf-toolbar{padding-right:0} -[data-desktop="win32"] .git-workspace .git-panel{--desktop-window-space:0px} +[data-desktop-controls="right"] .sidebar-header{border-bottom:1px solid var(--line);-webkit-app-region:drag} +[data-desktop-controls="right"] .main{--desktop-window-space:var(--desktop-controls-width)} +[data-desktop-controls="right"] .manuscript:not(.panel-collapsed)>.manuscript-pages, +[data-desktop-controls="right"] .task-grid.layout-split>.review-panel{--desktop-window-space:0px} +[data-desktop-controls="right"] :is(.pdf-toolbar,.workspace-navigation,.review-placeholder-toolbar,.panel-heading,.manuscript-side-header,.git-details-toolbar,.git-diff-toolbar,.review-tools){padding-right:calc(8px + var(--desktop-window-space,0px))} +[data-desktop-controls="right"] .review-host-bar.pdf-toolbar{padding-right:0} +[data-desktop-controls="right"] .git-workspace .git-panel{--desktop-window-space:0px} @media(max-width:680px){ - [data-desktop="win32"] .workspace-navigation>.view-selector>button>span{display:none} - [data-desktop="win32"] .git-workspace .git-panel{--desktop-window-space:138px} - [data-desktop="win32"] .git-toolbar{padding-right:calc(8px + var(--desktop-window-space,0px))} - [data-desktop="win32"] .git-details{--desktop-window-space:0px} + [data-desktop-controls="right"] .workspace-navigation>.view-selector>button>span{display:none} + [data-desktop-controls="right"] .git-workspace .git-panel{--desktop-window-space:var(--desktop-controls-width)} + [data-desktop-controls="right"] .git-toolbar{padding-right:calc(8px + var(--desktop-window-space,0px))} + [data-desktop-controls="right"] .git-details{--desktop-window-space:0px} } -@container (max-width:180px){[data-desktop="win32"] .side-tabs>button .tab-label{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}} +@container (max-width:180px){[data-desktop-controls="right"] .side-tabs>button .tab-label{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}} @media(max-width:900px){ [data-desktop] .sidebar{position:fixed} - [data-desktop]:not([data-desktop="win32"]) .desktop-window-drag{width:var(--desktop-leading-space)} - [data-desktop] .main .sidebar-toggle{margin-left:var(--desktop-leading-space,0px)} - [data-desktop="win32"] .manuscript:not(.panel-collapsed)>.manuscript-pages{--desktop-window-space:138px} - [data-desktop="win32"] .manuscript-side{--desktop-window-space:0px} + [data-desktop-controls="left"] .desktop-window-drag{width:var(--desktop-leading-space)} + [data-desktop-controls="left"] .main .sidebar-toggle{margin-left:var(--desktop-leading-space,0px)} + [data-desktop-controls="right"] .manuscript:not(.panel-collapsed)>.manuscript-pages{--desktop-window-space:var(--desktop-controls-width)} + [data-desktop-controls="right"] .manuscript-side{--desktop-window-space:0px} +} +/* The phone-width bar leads with the manuscript shortcut, so the whole bar + clears left-side controls rather than only the task list toggle. */ +@media(max-width:680px){ + [data-desktop-controls="left"] .workspace-navigation{padding-left:var(--desktop-leading-space)} + [data-desktop-controls="left"] .workspace-navigation>.sidebar-toggle{margin-left:0} } diff --git a/src/web/desktop-chrome.tsx b/src/web/desktop-chrome.tsx index e5486319..3e40b741 100644 --- a/src/web/desktop-chrome.tsx +++ b/src/web/desktop-chrome.tsx @@ -1,12 +1,14 @@ import './desktop-chrome.css'; import { createPortal } from 'react-dom'; +import type { ReactNode } from 'react'; import { t } from './i18n.ts'; import type { TypelessStatus } from '../../desktop/typeless-control.ts'; +import type { WindowButton, WindowButtons } from '../../desktop/window-buttons.ts'; declare global { interface Window { papilotDesktop?: { - platform: string; minimize(): void; maximize(): void; close(): void; + platform: string; windowButtons?: WindowButtons; minimize(): void; maximize(): void; close(): void; typelessStatus?(): Promise; typelessShortcut?(inputId: string): Promise; chooseDirectory?(): Promise; @@ -25,26 +27,42 @@ declare global { } } export const desktopWindow = Boolean(window.papilotDesktop); -if (desktopWindow) document.documentElement.dataset.desktop = window.papilotDesktop!.platform; +// Windows always puts these buttons on the right. Linux desktops choose their +// own buttons and side, which the desktop app reads from the system; without +// it, they keep a GNOME-style close button first on the left. +function windowButtons(): WindowButtons { + const platform = window.papilotDesktop!.platform, system = window.papilotDesktop!.windowButtons; + if (platform === 'win32') return { side: 'right', buttons: ['minimize', 'maximize', 'close'] }; + if (platform === 'darwin') return { side: 'left', buttons: [] }; + const buttons = Array.isArray(system?.buttons) ? system.buttons.filter(button => ['minimize', 'maximize', 'close'].includes(button)) : []; + return (system?.side === 'left' || system?.side === 'right') && buttons.length ? { side: system.side, buttons } : { side: 'left', buttons: ['close', 'minimize', 'maximize'] }; +} +const layout = desktopWindow ? windowButtons() : null; +if (layout) { + const root = document.documentElement; + root.dataset.desktop = window.papilotDesktop!.platform; + root.dataset.desktopControls = layout.side; + root.style.setProperty('--desktop-window-buttons', String(layout.buttons.length)); +} // The desktop app opens papers in place, as folders from the system picker. // Nothing is typed, uploaded or copied. export const nativeFolders = Boolean(window.papilotDesktop?.chooseDirectory); export const chooseDirectory = () => window.papilotDesktop!.chooseDirectory!(); export function DesktopWindowChrome() { - if (!desktopWindow) return null; + if (!layout) return null; const controls = window.papilotDesktop!; - const close = ; + const button: Record = { + minimize: , + maximize: , + close: , + }; const chrome =
- {controls.platform !== 'darwin' &&
- {controls.platform !== 'win32' && close} - - - {controls.platform === 'win32' && close} -
} + {layout.buttons.length > 0 &&
{layout.buttons.map(name => button[name])}
}
; // Windows applies overlapping drag/no-drag rectangles in DOM order, even - // when z-index paints these buttons above a later toolbar. Put its controls - // after the workspace so their no-drag regions win native hit testing. - return controls.platform === 'win32' ? createPortal(chrome, document.body) : chrome; + // when z-index paints these buttons above a later toolbar. Put right-side + // controls after the workspace, whose toolbars they overlap, so their + // no-drag regions win native hit testing. + return layout.side === 'right' ? createPortal(chrome, document.body) : chrome; } diff --git a/src/web/main.tsx b/src/web/main.tsx index 1d8aa7ee..3cd48353 100644 --- a/src/web/main.tsx +++ b/src/web/main.tsx @@ -2533,7 +2533,7 @@ function App() { const countDescription = totalNotes === undefined ? undefined : tn(totalNotes, '{n} annotation', '{n} annotations'); const manuscriptShortcut = !sidebarShown && ; + {t('Manuscript')}{manuscriptCount}; const taskControls = task && <>{taskStateActions}{manuscriptShortcut}{workspaceViews}; // Before the first comparison the task shows the manuscript PDF, so a turn // that stopped (for example on an agent error) builds one from the toolbar. diff --git a/src/web/style.css b/src/web/style.css index fa0d6079..a77abdca 100644 --- a/src/web/style.css +++ b/src/web/style.css @@ -110,7 +110,10 @@ code{font-family:var(--mono);font-variant-ligatures:none} .manuscript-link.active{background:var(--accent-soft);font-weight:500} .manuscript-link.active>svg{color:var(--accent)} .manuscript-note-count { display: inline-grid; place-items: center; min-width: 1.5em; padding: 0 4px; border-radius: 4px; background: var(--bg-muted); color: var(--text-2); font-size: 11px; line-height: 1.5; font-variant-numeric: tabular-nums; } -.manuscript-shortcut { display: inline-flex; align-items: center; gap: 4px; padding: 5px; background: transparent; color: var(--text-2); white-space: nowrap; } +.manuscript-shortcut { display: inline-flex; align-items: center; gap: 4px; padding: 5px; background: transparent; color: var(--text-2); white-space: nowrap; min-width: 0; } +/* In a narrow toolbar the label gives way before the controls beside it. */ +.manuscript-shortcut > svg { flex-shrink: 0; } +.manuscript-shortcut-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; } [data-notes-home="manuscript"].notes-received .manuscript-note-count { animation: task-received .45s var(--ease); } [data-notes-home="manuscript"].notes-received::after { content: none; } .manuscript-link .nav-meta{font-size:11px} diff --git a/tests/window-buttons.test.ts b/tests/window-buttons.test.ts new file mode 100644 index 00000000..6c7256cc --- /dev/null +++ b/tests/window-buttons.test.ts @@ -0,0 +1,41 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { detectWindowButtons, gtkLayout, kwinLayout, windowButtonsArgument, xfwmLayout, WINDOW_BUTTONS_ARGUMENT } from '../desktop/window-buttons.ts'; + +test('GTK button layouts keep the desktop side, buttons and order', () => { + assert.deepEqual(gtkLayout("'appmenu:close'\n"), { side: 'right', buttons: ['close'] }, 'GNOME default'); + assert.deepEqual(gtkLayout("'appmenu:minimize,maximize,close'"), { side: 'right', buttons: ['minimize', 'maximize', 'close'] }); + assert.deepEqual(gtkLayout("'close,minimize,maximize:'"), { side: 'left', buttons: ['close', 'minimize', 'maximize'] }); + assert.deepEqual(gtkLayout("'close:minimize,maximize'"), { side: 'left', buttons: ['close', 'minimize', 'maximize'] }, 'Split buttons gather on the side with close'); + assert.deepEqual(gtkLayout("'menu:minimize,maximize'"), { side: 'right', buttons: ['minimize', 'maximize'] }); + assert.equal(gtkLayout("'appmenu:'"), null, 'No buttons leaves the default'); + assert.equal(gtkLayout(''), null); +}); + +test('KDE and Xfce layouts map their button letters', () => { + assert.deepEqual(kwinLayout(''), { side: 'right', buttons: ['minimize', 'maximize', 'close'] }, 'Plasma default'); + assert.deepEqual(kwinLayout('[Other]\nButtonsOnLeft=X\n[org.kde.kdecoration2]\nButtonsOnLeft=XIA\nButtonsOnRight=\nlibrary=org.kde.breeze\n'), { side: 'left', buttons: ['close', 'minimize', 'maximize'] }); + assert.deepEqual(xfwmLayout('O|HMC\n'), { side: 'right', buttons: ['minimize', 'maximize', 'close'] }, 'Xfce default'); + assert.deepEqual(xfwmLayout('CHM|O'), { side: 'left', buttons: ['close', 'minimize', 'maximize'] }); +}); + +test('detection reads the layout from the current desktop', async () => { + const calls: string[][] = []; + const exec = async (command: string, args: string[]) => { calls.push([command, ...args]); return command === 'xfconf-query' ? 'CMH|O' : "'close,minimize:'"; }; + assert.deepEqual(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'ubuntu:GNOME' }, exec }), { side: 'left', buttons: ['close', 'minimize'] }); + assert.deepEqual(calls.at(-1), ['gsettings', 'get', 'org.gnome.desktop.wm.preferences', 'button-layout']); + await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'X-Cinnamon' }, exec }); + assert.equal(calls.at(-1)?.[2], 'org.cinnamon.desktop.wm.preferences'); + await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'MATE' }, exec }); + assert.equal(calls.at(-1)?.[2], 'org.mate.Marco.general'); + assert.deepEqual(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'XFCE' }, exec }), { side: 'left', buttons: ['close', 'maximize', 'minimize'] }); + const read = async (file: string) => { assert.equal(file, '/config/kwinrc'); return '[org.kde.kdecoration2]\nButtonsOnRight=X\n'; }; + assert.deepEqual(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'KDE', XDG_CONFIG_HOME: '/config' }, exec, read }), { side: 'right', buttons: ['close'] }); + assert.equal(await detectWindowButtons({ env: {}, exec: async () => { throw Error('no gsettings'); } }), null, 'Unknown layouts fall back to the page default'); +}); + +test('the layout reaches the preload as one JSON argument', () => { + const argument = windowButtonsArgument({ side: 'right', buttons: ['close'] }); + assert.ok(argument.startsWith(WINDOW_BUTTONS_ARGUMENT)); + assert.deepEqual(JSON.parse(argument.slice(WINDOW_BUTTONS_ARGUMENT.length)), { side: 'right', buttons: ['close'] }); +}); From a8d3dc23ef972f597a7936c0c29ea3a7e89727da Mon Sep 17 00:00:00 2001 From: Shengyi Jiang Date: Fri, 27 Nov 2026 10:30:27 +0800 Subject: [PATCH 2/5] Read window button layouts only where the desktop sets them Read GNOME's button-layout only on GNOME, Unity, Budgie and Pantheon: other desktops often install its schema without setting it, and its default would leave a single close button. Layer system kwinrc files from XDG_CONFIG_DIRS under the user's, and build those paths with POSIX separators so the tests pass on Windows. Start the backend before waiting for the layout; only the first window waits. Keep the phone-width bar's own inset beside left-side controls, and check macOS's traffic-light space in the browser layout check. Co-Authored-By: Claude Opus 5.5 --- desktop/main.ts | 7 +++++-- desktop/window-buttons.ts | 14 ++++++++++++-- scripts/check-appearance.mjs | 5 ++++- src/web/desktop-chrome.css | 2 +- tests/window-buttons.test.ts | 24 +++++++++++++++++++++--- 5 files changed, 43 insertions(+), 9 deletions(-) diff --git a/desktop/main.ts b/desktop/main.ts index 135a1b11..84a7bf1e 100644 --- a/desktop/main.ts +++ b/desktop/main.ts @@ -36,7 +36,8 @@ const notifications = desktopNotifications({ }); const typeless = typelessControl(); let typelessSending = false; -// Read the desktop's window button layout while the backend starts. +// Read the desktop's window button layout while the backend starts; the +// first window waits for it (see launch). const windowButtonsLayout = process.platform === 'linux' ? detectWindowButtons() : Promise.resolve(null); let windowButtons: WindowButtons | null = null; // papilot://new?template=&version= starts a paper from a Universe template. @@ -107,7 +108,6 @@ else { void backend.stop().finally(() => { stopped = true; app.quit(); }); }); void app.whenReady().then(async () => { - windowButtons = await windowButtonsLayout; const data = app.getPath('userData'), log = path.join(app.getPath('logs'), 'backend.log'); const wslAssets = app.isPackaged ? path.join(process.resourcesPath, 'wsl') : path.resolve(fileURLToPath(new URL('../wsl', import.meta.url))); const openEnvironment = (error?: string) => chooseEnvironment({ parent: window || undefined, current: readEnvironment(data), assets: wslAssets, root: app.isPackaged ? path.join(process.resourcesPath, 'server') : path.resolve(fileURLToPath(new URL('../..', import.meta.url))), error, @@ -272,6 +272,9 @@ else { }); port = Number(new URL(url).port); fs.writeFileSync(portFile, JSON.stringify(port), { mode: 0o600 }); + // A window opens only once the origin is known; by then the layout has + // long been read, so this rarely waits. + windowButtons = await windowButtonsLayout; if (url !== origin) { const moved = Boolean(origin); origin = url; if (moved) void window?.loadURL(origin); } }; // Legacy npm activations (updates/active.json) are never used. diff --git a/desktop/window-buttons.ts b/desktop/window-buttons.ts index 107b7ed4..3a7695c6 100644 --- a/desktop/window-buttons.ts +++ b/desktop/window-buttons.ts @@ -52,17 +52,27 @@ const run: Run = (command, args) => new Promise((resolve, reject) => { execFile(command, args, { timeout: 2000, encoding: 'utf8' }, (error, stdout) => error ? reject(error) : resolve(stdout)); }); +// GNOME's schema is installed on many desktops that never set it, so it is +// read only on desktops that use it; elsewhere the layout is unknown. +const gnomeDesktops = ['GNOME', 'UNITY', 'BUDGIE', 'PANTHEON']; // Resolves to null when the desktop's layout is unknown; the page then keeps // its own default. export async function detectWindowButtons({ env = process.env, exec = run, read = (file: string) => readFile(file, 'utf8') }: { env?: NodeJS.ProcessEnv; exec?: Run; read?: (file: string) => Promise } = {}): Promise { const desktops = (env.XDG_CURRENT_DESKTOP || '').toUpperCase().split(':'); const gsettings = (schema: string) => exec('gsettings', ['get', schema, 'button-layout']).then(gtkLayout); try { - if (desktops.includes('KDE')) return kwinLayout(await read(path.join(env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'kwinrc')).catch(() => '')); + if (desktops.includes('KDE')) { + // KDE layers the user's kwinrc over system ones (XDG_CONFIG_DIRS, most + // important first); later lines win in kwinLayout. + const directories = [...(env.XDG_CONFIG_DIRS || '/etc/xdg').split(':').filter(Boolean).reverse(), env.XDG_CONFIG_HOME || path.posix.join(os.homedir(), '.config')]; + const files = await Promise.all(directories.map(directory => read(path.posix.join(directory, 'kwinrc')).catch(() => ''))); + return kwinLayout(files.join('\n')); + } if (desktops.includes('XFCE')) return xfwmLayout(await exec('xfconf-query', ['-c', 'xfwm4', '-p', '/general/button_layout']).catch(() => 'O|HMC')); if (desktops.includes('X-CINNAMON')) return await gsettings('org.cinnamon.desktop.wm.preferences'); if (desktops.includes('MATE')) return await gsettings('org.mate.Marco.general'); - return await gsettings('org.gnome.desktop.wm.preferences'); + if (desktops.some(desktop => gnomeDesktops.includes(desktop))) return await gsettings('org.gnome.desktop.wm.preferences'); + return null; } catch { return null; } } // The sandboxed preload cannot import this module; it reads the layout back diff --git a/scripts/check-appearance.mjs b/scripts/check-appearance.mjs index fb680b7a..14c42ce2 100644 --- a/scripts/check-appearance.mjs +++ b/scripts/check-appearance.mjs @@ -254,6 +254,8 @@ try { ['linux-right', 'linux', { side: 'right', buttons: ['minimize', 'maximize', 'close'] }, 'right', ['Minimize window', 'Maximize or restore window', 'Close window']], ['linux-left', 'linux', { side: 'left', buttons: ['close', 'maximize'] }, 'left', ['Close window', 'Maximize or restore window']], ['windows', 'win32', undefined, 'right', ['Minimize window', 'Maximize or restore window', 'Close window']], + // macOS draws its own traffic lights in the leading space. + ['macos', 'darwin', undefined, 'left', []], ]; for (const [name, platform, windowButtons, side, labels] of layouts) { const chrome = await browser.newContext({ locale: 'en-US', colorScheme: 'light', viewport: { width: 1440, height: 960 } }); @@ -272,7 +274,8 @@ try { assert.deepEqual(await buttons.evaluateAll(list => list.map(button => button.getAttribute('aria-label'))), labels, `${name}: buttons and order`); const clear = async state => { const result = await window.evaluate(() => { - const controls = document.querySelector('.desktop-window-buttons').getBoundingClientRect(); + const buttons = document.querySelector('.desktop-window-buttons'); + const controls = buttons ? buttons.getBoundingClientRect() : { left: 0, top: 0, right: parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--desktop-leading-space')), bottom: 28 }; const overlaps = [...document.querySelectorAll('button,a,input,select,[role="combobox"]')].filter(element => !element.closest('.desktop-window-buttons')).filter(element => { const box = element.getBoundingClientRect(); return box.width > 0 && box.height > 0 && box.top < controls.bottom && box.bottom > controls.top && box.right > controls.left && box.left < controls.right; diff --git a/src/web/desktop-chrome.css b/src/web/desktop-chrome.css index 43d14d0b..741c48b1 100644 --- a/src/web/desktop-chrome.css +++ b/src/web/desktop-chrome.css @@ -56,6 +56,6 @@ /* The phone-width bar leads with the manuscript shortcut, so the whole bar clears left-side controls rather than only the task list toggle. */ @media(max-width:680px){ - [data-desktop-controls="left"] .workspace-navigation{padding-left:var(--desktop-leading-space)} + [data-desktop-controls="left"] .workspace-navigation{padding-left:calc(4px + var(--desktop-leading-space))} [data-desktop-controls="left"] .workspace-navigation>.sidebar-toggle{margin-left:0} } diff --git a/tests/window-buttons.test.ts b/tests/window-buttons.test.ts index 6c7256cc..37a1a42f 100644 --- a/tests/window-buttons.test.ts +++ b/tests/window-buttons.test.ts @@ -29,9 +29,27 @@ test('detection reads the layout from the current desktop', async () => { await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'MATE' }, exec }); assert.equal(calls.at(-1)?.[2], 'org.mate.Marco.general'); assert.deepEqual(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'XFCE' }, exec }), { side: 'left', buttons: ['close', 'maximize', 'minimize'] }); - const read = async (file: string) => { assert.equal(file, '/config/kwinrc'); return '[org.kde.kdecoration2]\nButtonsOnRight=X\n'; }; - assert.deepEqual(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'KDE', XDG_CONFIG_HOME: '/config' }, exec, read }), { side: 'right', buttons: ['close'] }); - assert.equal(await detectWindowButtons({ env: {}, exec: async () => { throw Error('no gsettings'); } }), null, 'Unknown layouts fall back to the page default'); + const kwinrc: Record = { + '/etc/xdg/kwinrc': '[org.kde.kdecoration2]\nButtonsOnLeft=X\nButtonsOnRight=IA\n', + '/vendor/kwinrc': '[org.kde.kdecoration2]\nButtonsOnLeft=XAI\n', + '/config/kwinrc': '[org.kde.kdecoration2]\nButtonsOnLeft=\nButtonsOnRight=IAX\n', + }; + const read = async (file: string) => { if (file in kwinrc) return kwinrc[file]; throw Error('missing'); }; + assert.deepEqual(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'KDE', XDG_CONFIG_HOME: '/config' }, exec, read }), { side: 'right', buttons: ['minimize', 'maximize', 'close'] }, "The user's kwinrc overrides the system one"); + assert.deepEqual(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'KDE', XDG_CONFIG_HOME: '/none' }, exec, read }), { side: 'left', buttons: ['close', 'minimize', 'maximize'] }, 'A system kwinrc sets the default'); + assert.deepEqual(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'KDE', XDG_CONFIG_HOME: '/none', XDG_CONFIG_DIRS: '/vendor:/etc/xdg' }, exec, read }), { side: 'left', buttons: ['close', 'maximize', 'minimize'] }, 'Earlier XDG_CONFIG_DIRS win'); + // GNOME's schema is often installed but unset elsewhere; its default would + // leave only a close button. + calls.length = 0; + for (const desktop of [undefined, 'LXQt', 'COSMIC', 'sway', 'Hyprland']) { + assert.equal(await detectWindowButtons({ env: desktop ? { XDG_CURRENT_DESKTOP: desktop } : {}, exec }), null, `${desktop ?? 'No desktop'} keeps the page default`); + } + assert.deepEqual(calls, []); + for (const desktop of ['Unity', 'Budgie:GNOME', 'Pantheon']) { + await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: desktop }, exec }); + assert.equal(calls.at(-1)?.[2], 'org.gnome.desktop.wm.preferences', desktop); + } + assert.equal(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'GNOME' }, exec: async () => { throw Error('no gsettings'); } }), null, 'Unreadable layouts fall back to the page default'); }); test('the layout reaches the preload as one JSON argument', () => { From 4fc4ebfd0d41c018fe219d6206c0e9c6cd08eddc Mon Sep 17 00:00:00 2001 From: Shengyi Jiang Date: Fri, 27 Nov 2026 10:39:45 +0800 Subject: [PATCH 3/5] Honor kwinrc locks and read the layout only in the running instance Parse each kwinrc on its own, least important first, so a group from one file never carries into the next, and apply KConfig's [$i] locks on files, groups and keys so an administrator's locked layout wins as it does in KWin. Start the layout lookup only after taking the single-instance lock, and describe the Linux behavior in the desktop README. Co-Authored-By: Claude Opus 5.5 --- desktop/README.md | 2 +- desktop/main.ts | 7 ++++--- desktop/window-buttons.ts | 35 ++++++++++++++++++++++++++--------- tests/window-buttons.test.ts | 8 ++++++++ 4 files changed, 39 insertions(+), 13 deletions(-) diff --git a/desktop/README.md b/desktop/README.md index 1e3d3dfd..bdc8075d 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -32,7 +32,7 @@ The smoke test opens the real app with temporary data, exercises the local API a ## Runtime - On first launch, an editable copy of the Papilot example paper appears with a prebuilt PDF and source mappings. Reading it does not require TeX. Install LaTeX to compile revisions. Updating the app preserves edits; removing the demo does not recreate it on the next launch. -- Mac traffic lights and Linux window buttons sit in the sidebar's drag area. Windows places minimize, maximize and close at the top right, with space reserved in the rightmost toolbar. The existing content toolbar reaches the top of the window without an extra title row. The sandboxed preload exposes window controls and a native directory picker; the main process accepts IPC only from its own top-level app page. +- Mac traffic lights sit in the sidebar's drag area, and Windows places minimize, maximize and close at the top right, with space reserved in the rightmost toolbar. Linux follows the desktop's button layout, read at startup from GNOME, Unity, Budgie and Pantheon (`org.gnome.desktop.wm.preferences`), Cinnamon and MATE (their gsettings schemas), KDE Plasma (`kwinrc`, including system files and `[$i]` locks) or Xfce (`xfconf-query`): the buttons it lists, in its order, on the side that holds close, with space reserved as on Windows when that is the right. Other desktops, and layouts that cannot be read, keep close, minimize and maximize on the left. The existing content toolbar reaches the top of the window without an extra title row. The sandboxed preload exposes window controls and a native directory picker; the main process accepts IPC only from its own top-level app page. - Choose or drop a local paper folder to open it in place. Only its path is sent to the backend, with no upload size or file count limit. Existing configuration and nearby main documents are checked first; compilation starts when you choose **Prepare and compile**. ZIP imports still upload a separate copy. - Compilation runs as fast as latexmk in the paper's folder: each build continues from the previous one, keeping latexmk's state, and the first build continues from the author's own latexmk output in `
/build`. **Recompile PDF** starts clean. See [Compilation performance](../docs/performance.md). - Data: `~/Library/Application Support/Papilot` on macOS, `$XDG_CONFIG_HOME/Papilot` (normally `~/.config/Papilot`) on Linux, `%APPDATA%/Papilot` on Windows, separate from the CLI's `~/.papilot`. Add existing paper repositories through the usual UI. `PAPILOT_DESKTOP_DATA` selects another data directory for testing. diff --git a/desktop/main.ts b/desktop/main.ts index 84a7bf1e..5ca6d8d9 100644 --- a/desktop/main.ts +++ b/desktop/main.ts @@ -36,9 +36,9 @@ const notifications = desktopNotifications({ }); const typeless = typelessControl(); let typelessSending = false; -// Read the desktop's window button layout while the backend starts; the -// first window waits for it (see launch). -const windowButtonsLayout = process.platform === 'linux' ? detectWindowButtons() : Promise.resolve(null); +// The running instance reads the desktop's window button layout while the +// backend starts; the first window waits for it (see launch). +let windowButtonsLayout: Promise = Promise.resolve(null); let windowButtons: WindowButtons | null = null; // papilot://new?template=&version= starts a paper from a Universe template. let pendingTemplate: { id: string; version: string } | null = null; @@ -91,6 +91,7 @@ function showWindow() { if (!app.requestSingleInstanceLock()) app.quit(); else { + if (process.platform === 'linux') windowButtonsLayout = detectWindowButtons(); // macOS delivers links as events; Windows and Linux pass them as arguments. app.on('open-url', (event, url) => { event.preventDefault(); openLink(url); }); app.on('second-instance', (_event, argv) => { if (!openLink(argv.find(arg => arg.startsWith('papilot://')))) showWindow(); }); diff --git a/desktop/window-buttons.ts b/desktop/window-buttons.ts index 3a7695c6..9a687c5a 100644 --- a/desktop/window-buttons.ts +++ b/desktop/window-buttons.ts @@ -28,14 +28,31 @@ export function gtkLayout(value: string): WindowButtons | null { return layout(named(left), named(right)); } // KDE Plasma's kwinrc: ButtonsOnLeft=MS, ButtonsOnRight=HIAX by default. -export function kwinLayout(config: string): WindowButtons | null { - let section = ''; +// Files come least important first (system, then the user's), each read on +// its own. As in KConfig, a group or key marked [$i] in one file is locked: +// later files cannot change it. +export function kwinLayout(files: string | string[]): WindowButtons | null { const values: Record = { ButtonsOnLeft: 'MS', ButtonsOnRight: 'HIAX' }; - for (const line of config.split(/\r?\n/)) { - const header = /^\s*\[(.*)\]\s*$/.exec(line); - if (header) { section = header[1]; continue; } - const entry = /^\s*(ButtonsOnLeft|ButtonsOnRight)\s*=\s*(.*?)\s*$/.exec(line); - if (entry && section === 'org.kde.kdecoration2') values[entry[1]] = entry[2]; + const locked = new Set(); + for (const file of typeof files === 'string' ? [files] : files) { + let group = ''; + const fileLocked = locked.has('*'), lockAfter: string[] = []; + for (const line of file.split(/\r?\n/)) { + const header = /^\s*\[([^\]]*)\]((?:\[[^\]]*\])*)\s*$/.exec(line); + if (header) { + // A lone [$i] before any group locks the whole file. + if (header[1] === '$i' && !group) { locked.add('*'); continue; } + group = header[1]; + // A locked group holds its keys even where this file leaves them out. + if (header[2].includes('[$i]') && group === 'org.kde.kdecoration2') lockAfter.push('ButtonsOnLeft', 'ButtonsOnRight'); + continue; + } + const entry = /^\s*(ButtonsOnLeft|ButtonsOnRight)((?:\[[^\]]*\])*)\s*=\s*(.*?)\s*$/.exec(line); + if (!entry || group !== 'org.kde.kdecoration2' || fileLocked || locked.has(entry[1])) continue; + values[entry[1]] = entry[3]; + if (entry[2].includes('[$i]')) lockAfter.push(entry[1]); + } + for (const key of lockAfter) locked.add(key); } const letters = { I: 'minimize', A: 'maximize', X: 'close' } as const; return layout(lettered(values.ButtonsOnLeft, letters), lettered(values.ButtonsOnRight, letters)); @@ -63,10 +80,10 @@ export async function detectWindowButtons({ env = process.env, exec = run, read try { if (desktops.includes('KDE')) { // KDE layers the user's kwinrc over system ones (XDG_CONFIG_DIRS, most - // important first); later lines win in kwinLayout. + // important first). const directories = [...(env.XDG_CONFIG_DIRS || '/etc/xdg').split(':').filter(Boolean).reverse(), env.XDG_CONFIG_HOME || path.posix.join(os.homedir(), '.config')]; const files = await Promise.all(directories.map(directory => read(path.posix.join(directory, 'kwinrc')).catch(() => ''))); - return kwinLayout(files.join('\n')); + return kwinLayout(files); } if (desktops.includes('XFCE')) return xfwmLayout(await exec('xfconf-query', ['-c', 'xfwm4', '-p', '/general/button_layout']).catch(() => 'O|HMC')); if (desktops.includes('X-CINNAMON')) return await gsettings('org.cinnamon.desktop.wm.preferences'); diff --git a/tests/window-buttons.test.ts b/tests/window-buttons.test.ts index 37a1a42f..ad6ff660 100644 --- a/tests/window-buttons.test.ts +++ b/tests/window-buttons.test.ts @@ -15,6 +15,14 @@ test('GTK button layouts keep the desktop side, buttons and order', () => { test('KDE and Xfce layouts map their button letters', () => { assert.deepEqual(kwinLayout(''), { side: 'right', buttons: ['minimize', 'maximize', 'close'] }, 'Plasma default'); assert.deepEqual(kwinLayout('[Other]\nButtonsOnLeft=X\n[org.kde.kdecoration2]\nButtonsOnLeft=XIA\nButtonsOnRight=\nlibrary=org.kde.breeze\n'), { side: 'left', buttons: ['close', 'minimize', 'maximize'] }); + // Files are read separately, least important first, with KConfig's [$i] locks. + const left = { side: 'left', buttons: ['close', 'minimize', 'maximize'] }; + assert.deepEqual(kwinLayout(['[org.kde.kdecoration2][$i]\nButtonsOnLeft=XIA\nButtonsOnRight=\n', '[org.kde.kdecoration2]\nButtonsOnLeft=\nButtonsOnRight=IAX\n']), left, 'A locked system group wins over the user'); + assert.deepEqual(kwinLayout(['[org.kde.kdecoration2][$i]\nButtonsOnLeft=XIA\n', '[org.kde.kdecoration2]\nButtonsOnRight=X\n']), left, 'A locked group also holds keys it leaves at their defaults'); + assert.deepEqual(kwinLayout(['[org.kde.kdecoration2]\nButtonsOnLeft[$i]=XIA\nButtonsOnRight=\n', '[org.kde.kdecoration2]\nButtonsOnLeft=\nButtonsOnRight=IAX\n']), left, 'A locked key wins over the user'); + assert.deepEqual(kwinLayout(['[$i]\n[org.kde.kdecoration2]\nButtonsOnLeft=XIA\nButtonsOnRight=\n', '[org.kde.kdecoration2]\nButtonsOnLeft=\nButtonsOnRight=IAX\n']), left, 'A locked file wins over the user'); + assert.deepEqual(kwinLayout(['[org.kde.kdecoration2]\nButtonsOnLeft=XIA\nButtonsOnRight=\n', '[org.kde.kdecoration2]\nButtonsOnLeft=\nButtonsOnRight=IAX\n']), { side: 'right', buttons: ['minimize', 'maximize', 'close'] }, 'Without a lock the user wins'); + assert.deepEqual(kwinLayout(['[org.kde.kdecoration2]\nButtonsOnLeft=X\nButtonsOnRight=\n', 'ButtonsOnLeft=IA\n']), { side: 'left', buttons: ['close'] }, "A group does not carry into the next file's ungrouped keys"); assert.deepEqual(xfwmLayout('O|HMC\n'), { side: 'right', buttons: ['minimize', 'maximize', 'close'] }, 'Xfce default'); assert.deepEqual(xfwmLayout('CHM|O'), { side: 'left', buttons: ['close', 'minimize', 'maximize'] }); }); From 569031380226695a52542d13de148c0559d10d49 Mon Sep 17 00:00:00 2001 From: Shengyi Jiang Date: Fri, 27 Nov 2026 10:43:10 +0800 Subject: [PATCH 4/5] Tighten kwinrc parsing and bound the layout lookup Treat [group][subgroup] headers as their own groups and localized keys such as ButtonsOnLeft[fr] as their own entries, as KConfig does. Give the whole layout lookup a two-second limit, file reads included, since the first window waits for it. Check the preload's copy of the argument prefix, and say in the README that KDE and Xfce fall back to their own defaults. Co-Authored-By: Claude Opus 5.5 --- desktop/README.md | 2 +- desktop/window-buttons.ts | 26 +++++++++++++++++++------- tests/window-buttons.test.ts | 12 ++++++++++++ 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/desktop/README.md b/desktop/README.md index bdc8075d..1cad619a 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -32,7 +32,7 @@ The smoke test opens the real app with temporary data, exercises the local API a ## Runtime - On first launch, an editable copy of the Papilot example paper appears with a prebuilt PDF and source mappings. Reading it does not require TeX. Install LaTeX to compile revisions. Updating the app preserves edits; removing the demo does not recreate it on the next launch. -- Mac traffic lights sit in the sidebar's drag area, and Windows places minimize, maximize and close at the top right, with space reserved in the rightmost toolbar. Linux follows the desktop's button layout, read at startup from GNOME, Unity, Budgie and Pantheon (`org.gnome.desktop.wm.preferences`), Cinnamon and MATE (their gsettings schemas), KDE Plasma (`kwinrc`, including system files and `[$i]` locks) or Xfce (`xfconf-query`): the buttons it lists, in its order, on the side that holds close, with space reserved as on Windows when that is the right. Other desktops, and layouts that cannot be read, keep close, minimize and maximize on the left. The existing content toolbar reaches the top of the window without an extra title row. The sandboxed preload exposes window controls and a native directory picker; the main process accepts IPC only from its own top-level app page. +- Mac traffic lights sit in the sidebar's drag area, and Windows places minimize, maximize and close at the top right, with space reserved in the rightmost toolbar. Linux follows the desktop's button layout, read at startup from GNOME, Unity, Budgie and Pantheon (`org.gnome.desktop.wm.preferences`), Cinnamon and MATE (their gsettings schemas), KDE Plasma (`kwinrc`, including system files and `[$i]` locks) or Xfce (`xfconf-query`): the buttons it lists, in its order, on the side that holds close, with space reserved as on Windows when that is the right. Without a readable setting, KDE Plasma and Xfce use their own default layouts (minimize, maximize and close on the right); other desktops, and GNOME-family layouts that cannot be read, keep close, minimize and maximize on the left. The existing content toolbar reaches the top of the window without an extra title row. The sandboxed preload exposes window controls and a native directory picker; the main process accepts IPC only from its own top-level app page. - Choose or drop a local paper folder to open it in place. Only its path is sent to the backend, with no upload size or file count limit. Existing configuration and nearby main documents are checked first; compilation starts when you choose **Prepare and compile**. ZIP imports still upload a separate copy. - Compilation runs as fast as latexmk in the paper's folder: each build continues from the previous one, keeping latexmk's state, and the first build continues from the author's own latexmk output in `
/build`. **Recompile PDF** starts clean. See [Compilation performance](../docs/performance.md). - Data: `~/Library/Application Support/Papilot` on macOS, `$XDG_CONFIG_HOME/Papilot` (normally `~/.config/Papilot`) on Linux, `%APPDATA%/Papilot` on Windows, separate from the CLI's `~/.papilot`. Add existing paper repositories through the usual UI. `PAPILOT_DESKTOP_DATA` selects another data directory for testing. diff --git a/desktop/window-buttons.ts b/desktop/window-buttons.ts index 9a687c5a..805fb379 100644 --- a/desktop/window-buttons.ts +++ b/desktop/window-buttons.ts @@ -38,19 +38,24 @@ export function kwinLayout(files: string | string[]): WindowButtons | null { let group = ''; const fileLocked = locked.has('*'), lockAfter: string[] = []; for (const line of file.split(/\r?\n/)) { - const header = /^\s*\[([^\]]*)\]((?:\[[^\]]*\])*)\s*$/.exec(line); + // [group][subgroup][$i]: the name is every segment but $ flags. + const header = /^\s*((?:\[[^\]]*\])+)\s*$/.exec(line); if (header) { + const segments = header[1].slice(1, -1).split(']['); + const flags = segments.filter(segment => segment.startsWith('$')).join(''); + const name = segments.filter(segment => !segment.startsWith('$')).join('/'); // A lone [$i] before any group locks the whole file. - if (header[1] === '$i' && !group) { locked.add('*'); continue; } - group = header[1]; + if (!name && !group) { if (flags.includes('i')) locked.add('*'); continue; } + group = name; // A locked group holds its keys even where this file leaves them out. - if (header[2].includes('[$i]') && group === 'org.kde.kdecoration2') lockAfter.push('ButtonsOnLeft', 'ButtonsOnRight'); + if (flags.includes('i') && group === 'org.kde.kdecoration2') lockAfter.push('ButtonsOnLeft', 'ButtonsOnRight'); continue; } - const entry = /^\s*(ButtonsOnLeft|ButtonsOnRight)((?:\[[^\]]*\])*)\s*=\s*(.*?)\s*$/.exec(line); + // Key[$i]=value; a localized Key[de]=value is a different entry. + const entry = /^\s*(ButtonsOnLeft|ButtonsOnRight)((?:\[\$[^\]]*\])*)\s*=\s*(.*?)\s*$/.exec(line); if (!entry || group !== 'org.kde.kdecoration2' || fileLocked || locked.has(entry[1])) continue; values[entry[1]] = entry[3]; - if (entry[2].includes('[$i]')) lockAfter.push(entry[1]); + if (/\[\$[^\]]*i/.test(entry[2])) lockAfter.push(entry[1]); } for (const key of lockAfter) locked.add(key); } @@ -74,7 +79,14 @@ const run: Run = (command, args) => new Promise((resolve, reject) => { const gnomeDesktops = ['GNOME', 'UNITY', 'BUDGIE', 'PANTHEON']; // Resolves to null when the desktop's layout is unknown; the page then keeps // its own default. -export async function detectWindowButtons({ env = process.env, exec = run, read = (file: string) => readFile(file, 'utf8') }: { env?: NodeJS.ProcessEnv; exec?: Run; read?: (file: string) => Promise } = {}): Promise { +// The first window waits for this, so a stalled command or file read (a +// hung network home folder) gives up after two seconds. +export function detectWindowButtons(options: { env?: NodeJS.ProcessEnv; exec?: Run; read?: (file: string) => Promise; timeout?: number } = {}): Promise { + let timer: NodeJS.Timeout | undefined; + const timeout = new Promise(resolve => { timer = setTimeout(() => resolve(null), options.timeout ?? 2000); }); + return Promise.race([readWindowButtons(options), timeout]).finally(() => clearTimeout(timer)); +} +async function readWindowButtons({ env = process.env, exec = run, read = (file: string) => readFile(file, 'utf8') }: { env?: NodeJS.ProcessEnv; exec?: Run; read?: (file: string) => Promise }): Promise { const desktops = (env.XDG_CURRENT_DESKTOP || '').toUpperCase().split(':'); const gsettings = (schema: string) => exec('gsettings', ['get', schema, 'button-layout']).then(gtkLayout); try { diff --git a/tests/window-buttons.test.ts b/tests/window-buttons.test.ts index ad6ff660..95b09b95 100644 --- a/tests/window-buttons.test.ts +++ b/tests/window-buttons.test.ts @@ -1,4 +1,5 @@ import test from 'node:test'; +import fs from 'node:fs'; import assert from 'node:assert/strict'; import { detectWindowButtons, gtkLayout, kwinLayout, windowButtonsArgument, xfwmLayout, WINDOW_BUTTONS_ARGUMENT } from '../desktop/window-buttons.ts'; @@ -23,6 +24,9 @@ test('KDE and Xfce layouts map their button letters', () => { assert.deepEqual(kwinLayout(['[$i]\n[org.kde.kdecoration2]\nButtonsOnLeft=XIA\nButtonsOnRight=\n', '[org.kde.kdecoration2]\nButtonsOnLeft=\nButtonsOnRight=IAX\n']), left, 'A locked file wins over the user'); assert.deepEqual(kwinLayout(['[org.kde.kdecoration2]\nButtonsOnLeft=XIA\nButtonsOnRight=\n', '[org.kde.kdecoration2]\nButtonsOnLeft=\nButtonsOnRight=IAX\n']), { side: 'right', buttons: ['minimize', 'maximize', 'close'] }, 'Without a lock the user wins'); assert.deepEqual(kwinLayout(['[org.kde.kdecoration2]\nButtonsOnLeft=X\nButtonsOnRight=\n', 'ButtonsOnLeft=IA\n']), { side: 'left', buttons: ['close'] }, "A group does not carry into the next file's ungrouped keys"); + assert.deepEqual(kwinLayout('[org.kde.kdecoration2]\nButtonsOnLeft=X\nButtonsOnRight=\n[org.kde.kdecoration2][Extra]\nButtonsOnLeft=IA\n'), { side: 'left', buttons: ['close'] }, 'Subgroups are other groups'); + assert.deepEqual(kwinLayout('[org.kde.kdecoration2]\nButtonsOnLeft=X\nButtonsOnRight=\nButtonsOnLeft[fr]=IA\n'), { side: 'left', buttons: ['close'] }, 'Localized entries are other keys'); + assert.deepEqual(kwinLayout(['[org.kde.kdecoration2][Extra][$i]\n', '[org.kde.kdecoration2]\nButtonsOnLeft=X\nButtonsOnRight=\n']), { side: 'left', buttons: ['close'] }, "A locked subgroup does not lock its parent"); assert.deepEqual(xfwmLayout('O|HMC\n'), { side: 'right', buttons: ['minimize', 'maximize', 'close'] }, 'Xfce default'); assert.deepEqual(xfwmLayout('CHM|O'), { side: 'left', buttons: ['close', 'minimize', 'maximize'] }); }); @@ -60,7 +64,15 @@ test('detection reads the layout from the current desktop', async () => { assert.equal(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'GNOME' }, exec: async () => { throw Error('no gsettings'); } }), null, 'Unreadable layouts fall back to the page default'); }); +test('detection gives up on a stalled lookup', async () => { + const stalled = () => new Promise(() => {}); + assert.equal(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'KDE' }, read: stalled, timeout: 10 }), null); + assert.equal(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'GNOME' }, exec: stalled, timeout: 10 }), null); +}); + test('the layout reaches the preload as one JSON argument', () => { + // The sandboxed preload keeps its own copy of the prefix. + assert.ok(fs.readFileSync(new URL('../desktop/preload.cts', import.meta.url), 'utf8').includes(`'${WINDOW_BUTTONS_ARGUMENT}'`)); const argument = windowButtonsArgument({ side: 'right', buttons: ['close'] }); assert.ok(argument.startsWith(WINDOW_BUTTONS_ARGUMENT)); assert.deepEqual(JSON.parse(argument.slice(WINDOW_BUTTONS_ARGUMENT.length)), { side: 'right', buttons: ['close'] }); From 28f02962f0534141053113910aade8c833f58ef1 Mon Sep 17 00:00:00 2001 From: Shengyi Jiang Date: Fri, 27 Nov 2026 10:49:45 +0800 Subject: [PATCH 5/5] Keep KDE and Xfce defaults when the layout lookup stalls A stalled or failed lookup on KDE Plasma or Xfce now falls back to that desktop's own default layout, as the README describes. Ignore relative XDG directories, skip nameless headers inside a kwinrc, dedupe button names in the page, and keep the test machine's system kwinrc out of the Linux smoke test. Co-Authored-By: Claude Opus 5.5 --- desktop/window-buttons.ts | 49 ++++++++++++++++++++---------------- scripts/check-desktop.mjs | 2 ++ src/web/desktop-chrome.tsx | 2 +- tests/window-buttons.test.ts | 21 +++++++++++++--- 4 files changed, 48 insertions(+), 26 deletions(-) diff --git a/desktop/window-buttons.ts b/desktop/window-buttons.ts index 805fb379..4b693330 100644 --- a/desktop/window-buttons.ts +++ b/desktop/window-buttons.ts @@ -44,8 +44,9 @@ export function kwinLayout(files: string | string[]): WindowButtons | null { const segments = header[1].slice(1, -1).split(']['); const flags = segments.filter(segment => segment.startsWith('$')).join(''); const name = segments.filter(segment => !segment.startsWith('$')).join('/'); - // A lone [$i] before any group locks the whole file. - if (!name && !group) { if (flags.includes('i')) locked.add('*'); continue; } + // A lone [$i] at the top locks the whole file; elsewhere a header + // without a name is not a group. + if (!name) { if (!group && flags.includes('i')) locked.add('*'); continue; } group = name; // A locked group holds its keys even where this file leaves them out. if (flags.includes('i') && group === 'org.kde.kdecoration2') lockAfter.push('ButtonsOnLeft', 'ButtonsOnRight'); @@ -79,30 +80,36 @@ const run: Run = (command, args) => new Promise((resolve, reject) => { const gnomeDesktops = ['GNOME', 'UNITY', 'BUDGIE', 'PANTHEON']; // Resolves to null when the desktop's layout is unknown; the page then keeps // its own default. +type Options = { env?: NodeJS.ProcessEnv; exec?: Run; read?: (file: string) => Promise; timeout?: number }; +const desktopsOf = (env: NodeJS.ProcessEnv) => (env.XDG_CURRENT_DESKTOP || '').toUpperCase().split(':'); // The first window waits for this, so a stalled command or file read (a -// hung network home folder) gives up after two seconds. -export function detectWindowButtons(options: { env?: NodeJS.ProcessEnv; exec?: Run; read?: (file: string) => Promise; timeout?: number } = {}): Promise { +// hung network home folder) gives up after two seconds. KDE and Xfce then +// keep their own default layouts; other desktops the page's. +export function detectWindowButtons(options: Options = {}): Promise { + const desktops = desktopsOf(options.env ?? process.env); + const fallback = desktops.includes('KDE') ? kwinLayout('') : desktops.includes('XFCE') ? xfwmLayout('O|HMC') : null; let timer: NodeJS.Timeout | undefined; const timeout = new Promise(resolve => { timer = setTimeout(() => resolve(null), options.timeout ?? 2000); }); - return Promise.race([readWindowButtons(options), timeout]).finally(() => clearTimeout(timer)); + return Promise.race([readWindowButtons(options).catch(() => null), timeout]) + .then(layout => layout ?? fallback).finally(() => clearTimeout(timer)); } -async function readWindowButtons({ env = process.env, exec = run, read = (file: string) => readFile(file, 'utf8') }: { env?: NodeJS.ProcessEnv; exec?: Run; read?: (file: string) => Promise }): Promise { - const desktops = (env.XDG_CURRENT_DESKTOP || '').toUpperCase().split(':'); +// XDG directories must be absolute; others are ignored. +const absolute = (directories: (string | undefined)[]) => directories.filter((directory): directory is string => Boolean(directory && path.posix.isAbsolute(directory))); +async function readWindowButtons({ env = process.env, exec = run, read = (file: string) => readFile(file, 'utf8') }: Options): Promise { + const desktops = desktopsOf(env); const gsettings = (schema: string) => exec('gsettings', ['get', schema, 'button-layout']).then(gtkLayout); - try { - if (desktops.includes('KDE')) { - // KDE layers the user's kwinrc over system ones (XDG_CONFIG_DIRS, most - // important first). - const directories = [...(env.XDG_CONFIG_DIRS || '/etc/xdg').split(':').filter(Boolean).reverse(), env.XDG_CONFIG_HOME || path.posix.join(os.homedir(), '.config')]; - const files = await Promise.all(directories.map(directory => read(path.posix.join(directory, 'kwinrc')).catch(() => ''))); - return kwinLayout(files); - } - if (desktops.includes('XFCE')) return xfwmLayout(await exec('xfconf-query', ['-c', 'xfwm4', '-p', '/general/button_layout']).catch(() => 'O|HMC')); - if (desktops.includes('X-CINNAMON')) return await gsettings('org.cinnamon.desktop.wm.preferences'); - if (desktops.includes('MATE')) return await gsettings('org.mate.Marco.general'); - if (desktops.some(desktop => gnomeDesktops.includes(desktop))) return await gsettings('org.gnome.desktop.wm.preferences'); - return null; - } catch { return null; } + if (desktops.includes('KDE')) { + // KDE layers the user's kwinrc over system ones (XDG_CONFIG_DIRS, most + // important first). + const system = absolute((env.XDG_CONFIG_DIRS || '').split(':')); + const directories = [...(system.length ? system : ['/etc/xdg']).reverse(), absolute([env.XDG_CONFIG_HOME])[0] ?? path.posix.join(os.homedir(), '.config')]; + return kwinLayout(await Promise.all(directories.map(directory => read(path.posix.join(directory, 'kwinrc')).catch(() => '')))); + } + if (desktops.includes('XFCE')) return xfwmLayout(await exec('xfconf-query', ['-c', 'xfwm4', '-p', '/general/button_layout'])); + if (desktops.includes('X-CINNAMON')) return gsettings('org.cinnamon.desktop.wm.preferences'); + if (desktops.includes('MATE')) return gsettings('org.mate.Marco.general'); + if (desktops.some(desktop => gnomeDesktops.includes(desktop))) return gsettings('org.gnome.desktop.wm.preferences'); + return null; } // The sandboxed preload cannot import this module; it reads the layout back // from this argument as JSON. diff --git a/scripts/check-desktop.mjs b/scripts/check-desktop.mjs index 6f13eb4d..18733c70 100644 --- a/scripts/check-desktop.mjs +++ b/scripts/check-desktop.mjs @@ -26,6 +26,8 @@ delete env.ELECTRON_RUN_AS_NODE; if (process.platform === 'linux') { env.XDG_CURRENT_DESKTOP = 'KDE'; env.XDG_CONFIG_HOME = path.join(data, 'config'); + // No system kwinrc from the test machine. + env.XDG_CONFIG_DIRS = path.join(data, 'system-config'); fs.mkdirSync(env.XDG_CONFIG_HOME); fs.writeFileSync(path.join(env.XDG_CONFIG_HOME, 'kwinrc'), '[org.kde.kdecoration2]\nButtonsOnLeft=XIA\nButtonsOnRight=\n'); } diff --git a/src/web/desktop-chrome.tsx b/src/web/desktop-chrome.tsx index 3e40b741..c136bf4f 100644 --- a/src/web/desktop-chrome.tsx +++ b/src/web/desktop-chrome.tsx @@ -34,7 +34,7 @@ function windowButtons(): WindowButtons { const platform = window.papilotDesktop!.platform, system = window.papilotDesktop!.windowButtons; if (platform === 'win32') return { side: 'right', buttons: ['minimize', 'maximize', 'close'] }; if (platform === 'darwin') return { side: 'left', buttons: [] }; - const buttons = Array.isArray(system?.buttons) ? system.buttons.filter(button => ['minimize', 'maximize', 'close'].includes(button)) : []; + const buttons = Array.isArray(system?.buttons) ? [...new Set(system.buttons.filter(button => ['minimize', 'maximize', 'close'].includes(button)))] : []; return (system?.side === 'left' || system?.side === 'right') && buttons.length ? { side: system.side, buttons } : { side: 'left', buttons: ['close', 'minimize', 'maximize'] }; } const layout = desktopWindow ? windowButtons() : null; diff --git a/tests/window-buttons.test.ts b/tests/window-buttons.test.ts index 95b09b95..5d95a489 100644 --- a/tests/window-buttons.test.ts +++ b/tests/window-buttons.test.ts @@ -1,5 +1,7 @@ import test from 'node:test'; import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; import assert from 'node:assert/strict'; import { detectWindowButtons, gtkLayout, kwinLayout, windowButtonsArgument, xfwmLayout, WINDOW_BUTTONS_ARGUMENT } from '../desktop/window-buttons.ts'; @@ -27,6 +29,7 @@ test('KDE and Xfce layouts map their button letters', () => { assert.deepEqual(kwinLayout('[org.kde.kdecoration2]\nButtonsOnLeft=X\nButtonsOnRight=\n[org.kde.kdecoration2][Extra]\nButtonsOnLeft=IA\n'), { side: 'left', buttons: ['close'] }, 'Subgroups are other groups'); assert.deepEqual(kwinLayout('[org.kde.kdecoration2]\nButtonsOnLeft=X\nButtonsOnRight=\nButtonsOnLeft[fr]=IA\n'), { side: 'left', buttons: ['close'] }, 'Localized entries are other keys'); assert.deepEqual(kwinLayout(['[org.kde.kdecoration2][Extra][$i]\n', '[org.kde.kdecoration2]\nButtonsOnLeft=X\nButtonsOnRight=\n']), { side: 'left', buttons: ['close'] }, "A locked subgroup does not lock its parent"); + assert.deepEqual(kwinLayout('[org.kde.kdecoration2]\n[$i]\nButtonsOnLeft=X\nButtonsOnRight=\n'), { side: 'left', buttons: ['close'] }, 'A nameless header inside a file is not a group'); assert.deepEqual(xfwmLayout('O|HMC\n'), { side: 'right', buttons: ['minimize', 'maximize', 'close'] }, 'Xfce default'); assert.deepEqual(xfwmLayout('CHM|O'), { side: 'left', buttons: ['close', 'minimize', 'maximize'] }); }); @@ -64,10 +67,20 @@ test('detection reads the layout from the current desktop', async () => { assert.equal(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'GNOME' }, exec: async () => { throw Error('no gsettings'); } }), null, 'Unreadable layouts fall back to the page default'); }); -test('detection gives up on a stalled lookup', async () => { - const stalled = () => new Promise(() => {}); - assert.equal(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'KDE' }, read: stalled, timeout: 10 }), null); - assert.equal(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'GNOME' }, exec: stalled, timeout: 10 }), null); +test('detection gives up on a stalled or failed lookup', async () => { + const stalled = () => new Promise(() => {}), failed = async () => { throw Error('unavailable'); }; + const plasma = { side: 'right', buttons: ['minimize', 'maximize', 'close'] }; + assert.deepEqual(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'KDE' }, read: stalled, timeout: 10 }), plasma, 'KDE keeps its own default'); + assert.deepEqual(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'XFCE' }, exec: stalled, timeout: 10 }), plasma, 'Xfce keeps its own default'); + assert.deepEqual(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'XFCE' }, exec: failed }), plasma); + assert.equal(await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'GNOME' }, exec: stalled, timeout: 10 }), null, 'Others keep the page default'); +}); + +test('relative XDG directories are ignored', async () => { + const files: string[] = []; + await detectWindowButtons({ env: { XDG_CURRENT_DESKTOP: 'KDE', XDG_CONFIG_HOME: '.config', XDG_CONFIG_DIRS: 'etc:/opt/xdg' }, read: async file => { files.push(file); return ''; } }); + assert.deepEqual(files.slice(0, -1), ['/opt/xdg/kwinrc']); + assert.equal(files.at(-1), path.posix.join(os.homedir(), '.config', 'kwinrc'), 'A relative XDG_CONFIG_HOME falls back to ~/.config'); }); test('the layout reaches the preload as one JSON argument', () => {