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/README.md b/desktop/README.md index 1e3d3dfd..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 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. 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/main.ts b/desktop/main.ts index 2ec9f97b..5ca6d8d9 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,10 @@ const notifications = desktopNotifications({ }); const typeless = typelessControl(); let typelessSending = false; +// 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; function templateLink(url: string) { @@ -68,7 +73,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); } @@ -85,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(); }); @@ -266,6 +273,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/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..4b693330 --- /dev/null +++ b/desktop/window-buttons.ts @@ -0,0 +1,116 @@ +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. +// 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' }; + 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/)) { + // [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] 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'); + continue; + } + // 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 (/\[\$[^\]]*i/.test(entry[2])) 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)); +} +// 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)); +}); + +// 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. +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. 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).catch(() => null), timeout]) + .then(layout => layout ?? fallback).finally(() => clearTimeout(timer)); +} +// 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); + 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. +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..14c42ce2 100644 --- a/scripts/check-appearance.mjs +++ b/scripts/check-appearance.mjs @@ -245,6 +245,63 @@ 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']], + // 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 } }); + 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 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; + }).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..18733c70 100644 --- a/scripts/check-desktop.mjs +++ b/scripts/check-desktop.mjs @@ -20,6 +20,17 @@ 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'); + // 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'); +} const packaged = process.env.PAPILOT_DESKTOP_EXECUTABLE; const packageManaged = process.env.PAPILOT_EXPECT_PACKAGE_MANAGED === '1'; const layerUpdates = Boolean(packaged && !packageManaged); @@ -78,6 +89,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..741c48b1 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:calc(4px + 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..c136bf4f 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) ? [...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; +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..5d95a489 --- /dev/null +++ b/tests/window-buttons.test.ts @@ -0,0 +1,92 @@ +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'; + +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'] }); + // 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(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'] }); +}); + +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 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('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', () => { + // 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'] }); +});