Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion desktop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<main folder>/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.
Expand Down
12 changes: 11 additions & 1 deletion desktop/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' ||
Expand Down Expand Up @@ -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<WindowButtons | null> = Promise.resolve(null);
let windowButtons: WindowButtons | null = null;
// papilot://new?template=<id>&version=<version> starts a paper from a Universe template.
let pendingTemplate: { id: string; version: string } | null = null;
function templateLink(url: string) {
Expand Down Expand Up @@ -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); }
Expand All @@ -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(); });
Expand Down Expand Up @@ -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.
Expand Down
10 changes: 10 additions & 0 deletions desktop/preload.cts
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand Down
116 changes: 116 additions & 0 deletions desktop/window-buttons.ts
Original file line number Diff line number Diff line change
@@ -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<string, WindowButton>) => [...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<string, string> = { ButtonsOnLeft: 'MS', ButtonsOnRight: 'HIAX' };
const locked = new Set<string>();
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<string>;
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<string>; 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<WindowButtons | null> {
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<null>(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<WindowButtons | null> {
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);
Loading
Loading