Skip to content

Build your personal knowledge base with Trilium Notes

fix(desktop): keep the window position after a crash or display change

Elian Doranca0e34ab905c
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 706aba08ef..847c9ccffc 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -35,7 +35,6 @@
"better-sqlite3": "13.0.3",
"electron-debug": "5.0.0",
"electron-dl": "5.0.0",
- "electron-window-state": "5.0.3",
"sherpa-onnx-node": "1.13.8"
},
"devDependencies": {
diff --git a/apps/desktop/src/services/window.spec.ts b/apps/desktop/src/services/window.spec.ts
index ce82f824c3..8e66411f63 100644
--- a/apps/desktop/src/services/window.spec.ts
+++ b/apps/desktop/src/services/window.spec.ts
@@ -217,8 +217,9 @@ vi.mock("electron", () => ({
globalShortcut: fakeGlobalShortcut
}));
-vi.mock("electron-window-state", () => ({
- default: () => ({ x: 0, y: 0, width: 1200, height: 800, manage: state.windowStateManage })
+// Window state persistence has its own suite (window_state.spec.ts).
+vi.mock("./window_state", () => ({
+ createWindowStateKeeper: () => ({ x: 0, y: 0, width: 1200, height: 800, manage: state.windowStateManage })
}));
// setupWindowing() installs the WebContents security policy; that behaviour has
diff --git a/apps/desktop/src/services/window.ts b/apps/desktop/src/services/window.ts
index 0e46361ebf..f280343554 100644
--- a/apps/desktop/src/services/window.ts
+++ b/apps/desktop/src/services/window.ts
@@ -8,6 +8,7 @@ import path from "path";
import { markStartupMetric } from "./startup_metrics.js";
import { isTriliumAppShellUrl, TRILIUM_APP_BASE_URL } from "./trilium_app_origin.js";
import { setupWebContentsSecurity } from "./web_contents_security.js";
+import { createWindowStateKeeper } from "./window_state.js";
// Preload bundle path. Two layouts:
// - Dev: this file lives at apps/desktop/src/services/window.ts, and the
@@ -122,9 +123,7 @@ async function createMainWindow(startHidden = false) {
]);
}
- const windowStateKeeper = (await import("electron-window-state")).default; // should not be statically imported
-
- const mainWindowState = windowStateKeeper({
+ const mainWindowState = createWindowStateKeeper({
// default window width & height, so it's usable on a 1600 * 900 display (including some extra panels etc.)
defaultWidth: 1200,
defaultHeight: 800
@@ -476,7 +475,7 @@ async function registerGlobalShortcuts() {
}
function showWindow(window: BrowserWindow) {
- // electron-window-state can reveal a hidden maximized window while it restores state.
+ // Restoring the maximized state of a hidden window reveals it.
// Restore immediately before an intentional reveal so the window starts hidden.
deferredWindowStateManagers.get(window)?.();
window.show();
diff --git a/apps/desktop/src/services/window_state.spec.ts b/apps/desktop/src/services/window_state.spec.ts
new file mode 100644
index 0000000000..c1e91a7ccb
--- /dev/null
+++ b/apps/desktop/src/services/window_state.spec.ts
@@ -0,0 +1,168 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+type Handler = (...args: unknown[]) => unknown;
+
+const state = vi.hoisted(() => ({
+ userData: "",
+ displays: [ { workArea: { x: 0, y: 0, width: 1920, height: 1080 } } ]
+}));
+
+vi.mock("electron", () => ({
+ app: { getPath: () => state.userData },
+ screen: { getAllDisplays: () => state.displays }
+}));
+
+vi.mock("@triliumnext/core", () => ({ getLog: () => ({ error: vi.fn() }) }));
+
+const { createWindowStateKeeper } = await import("./window_state.js");
+
+const DEFAULTS = { defaultWidth: 1200, defaultHeight: 800 };
+let tempDir = "";
+
+class FakeWindow {
+ listeners = new Map<string, Handler[]>();
+ normalBounds = { x: 100, y: 50, width: 1000, height: 700 };
+ maximized = false;
+ fullScreen = false;
+ minimized = false;
+ destroyed = false;
+ maximize = vi.fn();
+ setFullScreen = vi.fn();
+ on(event: string, cb: Handler) {
+ this.listeners.set(event, [ ...this.listeners.get(event) ?? [], cb ]);
+ return this;
+ }
+ fire(event: string) {
+ for (const cb of this.listeners.get(event) ?? []) cb();
+ }
+ getNormalBounds() { return this.normalBounds; }
+ isMaximized() { return this.maximized; }
+ isFullScreen() { return this.fullScreen; }
+ isMinimized() { return this.minimized; }
+ isDestroyed() { return this.destroyed; }
+}
+
+function stateFile() {
+ return path.join(state.userData, "window-state.json");
+}
+
+function writeState(value: unknown) {
+ fs.writeFileSync(stateFile(), JSON.stringify(value));
+}
+
+function readState() {
+ return JSON.parse(fs.readFileSync(stateFile(), "utf8"));
+}
+
+beforeEach(() => {
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "window-state-"));
+ state.userData = tempDir;
+ state.displays = [ { workArea: { x: 0, y: 0, width: 1920, height: 1080 } } ];
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ fs.rmSync(tempDir, { recursive: true, force: true });
+});
+
+describe("createWindowStateKeeper", () => {
+ it("uses the defaults without a file, or with an unreadable or invalid one", () => {
+ expect({ ...createWindowStateKeeper(DEFAULTS) }).toMatchObject({ x: undefined, y: undefined, width: 1200, height: 800 });
+
+ fs.writeFileSync(stateFile(), "{ not json");
+ expect(createWindowStateKeeper(DEFAULTS).width).toBe(1200);
+
+ writeState({ x: 1.5, y: 0, width: -3, height: "tall" });
+ expect({ ...createWindowStateKeeper(DEFAULTS) }).toMatchObject({ x: undefined, y: undefined, width: 1200, height: 800 });
+ });
+
+ it("restores the bounds a previous release wrote, displayBounds included", () => {
+ writeState({ x: 10, y: 20, width: 900, height: 600, isMaximized: false, isFullScreen: false,
+ displayBounds: { x: 0, y: 0, width: 1920, height: 1080 } });
+ const keeper = createWindowStateKeeper(DEFAULTS);
+ expect([ keeper.x, keeper.y, keeper.width, keeper.height ]).toEqual([ 10, 20, 900, 600 ]);
+ });
+
+ it("keeps a window that is partly off-screen but drops the position of one no display shows", () => {
+ state.displays = [
+ { workArea: { x: 0, y: 0, width: 1920, height: 1080 } },
+ { workArea: { x: 1920, y: 0, width: 1280, height: 1024 } }
+ ];
+ writeState({ x: 1700, y: -20, width: 1000, height: 700 });
+ expect(createWindowStateKeeper(DEFAULTS).x).toBe(1700);
+
+ writeState({ x: 5000, y: 100, width: 1000, height: 700 });
+ const unplugged = createWindowStateKeeper(DEFAULTS);
+ expect([ unplugged.x, unplugged.y, unplugged.width, unplugged.height ]).toEqual([ undefined, undefined, 1000, 700 ]);
+
+ // A sliver along the edge is not enough to grab the window by.
+ writeState({ x: 1880, y: 1060, width: 1000, height: 700 });
+ state.displays = [ { workArea: { x: 0, y: 0, width: 1920, height: 1080 } } ];
+ expect(createWindowStateKeeper(DEFAULTS).x).toBeUndefined();
+ });
+
+ it("maximizes and enters full screen as the saved state says", () => {
+ writeState({ x: 10, y: 20, width: 900, height: 600, isMaximized: true, isFullScreen: true });
+ const win = new FakeWindow();
+ createWindowStateKeeper(DEFAULTS).manage(win as never);
+ expect(win.maximize).toHaveBeenCalledOnce();
+ expect(win.setFullScreen).toHaveBeenCalledWith(true);
+
+ const plain = new FakeWindow();
+ writeState({ x: 10, y: 20, width: 900, height: 600 });
+ createWindowStateKeeper(DEFAULTS).manage(plain as never);
+ expect(plain.maximize).not.toHaveBeenCalled();
+ expect(plain.setFullScreen).not.toHaveBeenCalled();
+ });
+
+ it("saves the normal bounds shortly after a move or resize, and on close", () => {
+ vi.useFakeTimers();
+ const win = new FakeWindow();
+ createWindowStateKeeper(DEFAULTS).manage(win as never);
+
+ win.fire("move");
+ win.fire("resize");
+ expect(fs.existsSync(stateFile())).toBe(false);
+ vi.runAllTimers();
+ expect(readState()).toEqual({ x: 100, y: 50, width: 1000, height: 700, isMaximized: false, isFullScreen: false });
+
+ // Maximized: the normal bounds are what a restore returns to, so they are kept.
+ win.maximized = true;
+ win.normalBounds = { x: 300, y: 200, width: 800, height: 500 };
+ win.fire("maximize");
+ vi.runAllTimers();
+ expect(readState()).toEqual({ x: 300, y: 200, width: 800, height: 500, isMaximized: true, isFullScreen: false });
+
+ // Minimizing reports the window as not maximized on some platforms; the flags stay as they were.
+ win.minimized = true;
+ win.maximized = false;
+ win.fire("resize");
+ vi.runAllTimers();
+ expect(readState().isMaximized).toBe(true);
+
+ win.minimized = false;
+ win.fullScreen = true;
+ win.fire("close");
+ win.destroyed = true;
+ win.fire("closed");
+ expect(readState()).toMatchObject({ isMaximized: false, isFullScreen: true });
+
+ // Nothing is left scheduled to read a destroyed window.
+ win.fire("move");
+ expect(() => vi.runAllTimers()).not.toThrow();
+ });
+
+ it("creates the user data directory when it is missing", () => {
+ vi.useFakeTimers();
+ state.userData = path.join(state.userData, "nested", "dir");
+ const win = new FakeWindow();
+ createWindowStateKeeper(DEFAULTS).manage(win as never);
+ win.fire("close");
+ win.fire("closed");
+ expect(readState().width).toBe(1000);
+ });
+});
diff --git a/apps/desktop/src/services/window_state.ts b/apps/desktop/src/services/window_state.ts
new file mode 100644
index 0000000000..715f01b824
--- /dev/null
+++ b/apps/desktop/src/services/window_state.ts
@@ -0,0 +1,132 @@
+import { getLog } from "@triliumnext/core";
+import { app, type BrowserWindow, type Rectangle, screen } from "electron";
+import fs from "fs";
+import path from "path";
+
+/** The contents of `window-state.json`, in the shape `electron-window-state` wrote it. */
+interface WindowState {
+ x?: number;
+ y?: number;
+ width: number;
+ height: number;
+ isMaximized?: boolean;
+ isFullScreen?: boolean;
+}
+
+const STATE_FILE_NAME = "window-state.json";
+const SAVE_DELAY_MS = 500;
+/** How much of a saved window, in pixels along each axis, a display must show for the position to be kept. */
+const MIN_VISIBLE_PX = 100;
+
+/**
+ * Remembers the bounds, maximized and full-screen state of the main window across restarts, in
+ * `window-state.json` under the user data directory. `x`, `y`, `width` and `height` are the
+ * bounds to create the window with; `x` and `y` are `undefined` when there is no saved position
+ * or no display shows enough of it, so Electron centers the window. `manage()` applies the
+ * maximized and full-screen state and saves every change to the file.
+ */
+export function createWindowStateKeeper(defaults: { defaultWidth: number; defaultHeight: number }) {
+ const stateFile = path.join(app.getPath("userData"), STATE_FILE_NAME);
+ const state = readState(stateFile) ?? { width: defaults.defaultWidth, height: defaults.defaultHeight };
+ if (!isPositionVisible(state)) {
+ state.x = undefined;
+ state.y = undefined;
+ }
+
+ function manage(win: BrowserWindow) {
+ if (state.isMaximized) {
+ win.maximize();
+ }
+ if (state.isFullScreen) {
+ win.setFullScreen(true);
+ }
+
+ let saveTimer: ReturnType<typeof setTimeout> | undefined;
+ const scheduleSave = () => {
+ clearTimeout(saveTimer);
+ saveTimer = setTimeout(() => {
+ if (!win.isDestroyed()) {
+ updateState(state, win);
+ writeState(stateFile, state);
+ }
+ }, SAVE_DELAY_MS);
+ };
+
+ win.on("move", scheduleSave);
+ win.on("resize", scheduleSave);
+ win.on("maximize", scheduleSave);
+ win.on("unmaximize", scheduleSave);
+ win.on("enter-full-screen", scheduleSave);
+ win.on("leave-full-screen", scheduleSave);
+ // The window can no longer be read once it is closed, so its state is taken on `close`.
+ win.on("close", () => updateState(state, win));
+ win.on("closed", () => {
+ clearTimeout(saveTimer);
+ writeState(stateFile, state);
+ });
+ }
+
+ return { x: state.x, y: state.y, width: state.width, height: state.height, manage };
+}
+
+function readState(stateFile: string): WindowState | null {
+ let parsed: Partial<Record<keyof WindowState, unknown>>;
+ try {
+ parsed = JSON.parse(fs.readFileSync(stateFile, "utf8"));
+ } catch {
+ return null;
+ }
+
+ const { x, y, width, height, isMaximized, isFullScreen } = parsed ?? {};
+ if (!isPositiveInteger(width) || !isPositiveInteger(height)) {
+ return null;
+ }
+ const hasPosition = Number.isInteger(x) && Number.isInteger(y);
+ return {
+ x: hasPosition ? x as number : undefined,
+ y: hasPosition ? y as number : undefined,
+ width,
+ height,
+ isMaximized: isMaximized === true,
+ isFullScreen: isFullScreen === true
+ };
+}
+
+function isPositiveInteger(value: unknown): value is number {
+ return Number.isInteger(value) && (value as number) > 0;
+}
+
+function isPositionVisible({ x, y, width, height }: WindowState) {
+ if (x === undefined || y === undefined) {
+ return false;
+ }
+ return screen.getAllDisplays().some(({ workArea }) =>
+ overlap(x, width, workArea.x, workArea.width) >= MIN_VISIBLE_PX
+ && overlap(y, height, workArea.y, workArea.height) >= MIN_VISIBLE_PX);
+}
+
+function overlap(start: number, length: number, areaStart: number, areaLength: number) {
+ return Math.min(start + length, areaStart + areaLength) - Math.max(start, areaStart);
+}
+
+function updateState(state: WindowState, win: BrowserWindow) {
+ const bounds: Rectangle = win.getNormalBounds();
+ state.x = bounds.x;
+ state.y = bounds.y;
+ state.width = bounds.width;
+ state.height = bounds.height;
+ // Some platforms report a minimized window as neither maximized nor full screen.
+ if (!win.isMinimized()) {
+ state.isMaximized = win.isMaximized();
+ state.isFullScreen = win.isFullScreen();
+ }
+}
+
+function writeState(stateFile: string, state: WindowState) {
+ try {
+ fs.mkdirSync(path.dirname(stateFile), { recursive: true });
+ fs.writeFileSync(stateFile, JSON.stringify(state));
+ } catch (e) {
+ getLog().error(`Could not save the window state to ${stateFile}: ${e}`);
+ }
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ea5de87cc2..ae4337884e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -427,9 +427,6 @@ importers:
electron-dl:
specifier: 5.0.0
version: 5.0.0
- electron-window-state:
- specifier: 5.0.3
- version: 5.0.3
sherpa-onnx-node:
specifier: 1.13.8
version: 1.13.8
@@ -7001,10 +6998,6 @@ packages:
resolution: {integrity: sha512-2Gcq6inCQs/AqfHP3f5ftCzk+pqeW2VlA1LgmPqEj2hfBO8HiZRspNYkD4HzFBe4u6lGqca4BspFr6Ix4Q400g==}
- resolution: {integrity: sha512-1mNTwCfkolXl3kMf50yW3vE2lZj0y92P/HYWFBrb+v2S/pCka5mdwN3cagKm458A7NjndSwijynXgcLWRodsVg==}
- engines: {node: '>=8.0.0'}
-
resolution: {integrity: sha512-j9ETcBGJaXxAY/b6UBpR7LZfjdU4BAO+yvr4ifqHEdyuc3UNCy91PDGkWKY5UQ4coHNYfnwFggrqD6QPeFGAlg==}
engines: {node: '>=8.0.0'}
@@ -18592,11 +18585,6 @@ snapshots:
- dependencies:
- jsonfile: 4.0.0
- mkdirp: 0.5.6
-
dependencies:
'@electron/asar': 3.4.1
@@ -20432,6 +20420,7 @@ snapshots:
optionalDependencies:
graceful-fs: 4.2.11
+ optional: true
dependencies: