Skip to content

Build your personal knowledge base with Trilium Notes

30.9 KB
Raw Blame
import { app_info, cls, events, getLog, isSetupRequested, keyboard_actions as keyboardActionsService, options as optionService, sql_init, utils as coreUtils } from "@triliumnext/core";
import { RESOURCE_DIR } from "@triliumnext/server/src/services/resource_dir.js";
import { supportsBackgroundMaterial } from "@triliumnext/server/src/services/utils.js";
import { type BrowserWindow, type BrowserWindowConstructorOptions, default as electron, type Session, type WebContents } from "electron";
import { t } from "i18next";
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
//     preload bundle is one level up at apps/desktop/src/preload.compiled.cjs
//     (built in place by scripts/electron-start.mts).
//   - Prod: this file is bundled into apps/desktop/dist/main.mjs, with
//     preload.cjs sitting next to it in dist/ (NOT one level up — getting
//     this wrong leaves the renderer without `window.electronApi`).
//
// Lazy: `coreUtils.isDev()` calls `getPlatform()` which throws until
// `initializeCore()` has run; module load happens before that.
let preloadScriptCache: string | undefined;
function getPreloadScript(): string {
    if (preloadScriptCache === undefined) {
        /* v8 ignore next 5 -- prod preload arm is cache-once (only the first ternary evaluation counts); covered by the production build, not unit tests */
        preloadScriptCache = path.resolve(
            coreUtils.isDev()
                ? path.join(__dirname, "..", "preload.compiled.cjs")
                : path.join(__dirname, "preload.cjs")
        );
    }
    return preloadScriptCache;
}

// Prevent the window being garbage collected
let mainWindow: BrowserWindow | null;
let setupWindow: BrowserWindow | null;
let allWindows: BrowserWindow[] = []; // Used to store all windows, sorted by the order of focus.
const loadedSpellcheckSessions = new WeakSet<Session>();
const exportRevealSessions = new WeakSet<Session>();
const deferredWindowStateManagers = new WeakMap<BrowserWindow, () => void>();

// Set to `true` once the app is genuinely quitting (via `before-quit`, which fires
// for every real quit path: Cmd+Q, the tray "Quit" item, the app menu, OS shutdown).
// The close-to-tray interceptor checks this so a true quit isn't swallowed into a hide.
let isQuitting = false;

function trackWindowFocus(win: BrowserWindow) {
    // We need to get the last focused window from allWindows. If the last window is closed, we return the previous window.
    // Therefore, we need to push the window into the allWindows array every time it gets focused.
    win.on("focus", () => {
        allWindows = allWindows.filter(w => !w.isDestroyed() && w !== win);
        allWindows.push(win);
        if (!optionService.getOptionBool("disableTray")) {
            electron.ipcMain.emit("reload-tray");
        }
    });

    win.on("closed", () => {
        allWindows = allWindows.filter(w => !w.isDestroyed());
        if (!optionService.getOptionBool("disableTray")) {
            electron.ipcMain.emit("reload-tray");
        }
    });
}

/**
 * Opens an extra window from the main process, for callers with no renderer to
 * open it from (the `--new-window` command line). The client opens its own
 * extra windows through `window.open`, which `installWindowOpenPolicy` turns
 * into a window in the opener's renderer process; both paths end in
 * `adoptExtraWindow()`.
 */
async function createExtraWindow(extraWindowHash: string) {
    const { BrowserWindow } = await import("electron");

    const win = new BrowserWindow(getExtraWindowOptions());
    win.loadURL(`${TRILIUM_APP_BASE_URL}?extraWindow=1${extraWindowHash}`);
    adoptExtraWindow(win);
}

/** Constructor options shared by both ways an extra window is created. */
function getExtraWindowOptions(): BrowserWindowConstructorOptions {
    return {
        width: 1000,
        height: 800,
        title: "Trilium Notes",
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: getPreloadScript(),
            // Always attach Chromium's spell-check subsystem so it can be toggled at
            // runtime via session.setSpellCheckerEnabled(); the actual on/off state is
            // applied from the option in configureWebContents(). webPreferences.spellcheck
            // is immutable after creation, so leaving it false would force a restart to enable.
            spellcheck: true,
            webviewTag: true
        },
        ...getWindowExtraOpts(),
        icon: getIcon()
    };
}

/** Per-window wiring for an extra window, whichever way it was created. */
function adoptExtraWindow(win: BrowserWindow) {
    win.setMenuBarVisibility(false);
    configureWebContents(win.webContents, optionService.getOptionBool("spellCheckEnabled"));
    trackWindowFocus(win);
}

async function createMainWindow(startHidden = false) {
    if ("setUserTasks" in electron.app) {
        electron.app.setUserTasks([
            {
                program: process.execPath,
                arguments: "--new-window",
                iconPath: process.execPath,
                iconIndex: 0,
                title: "Open New Window",
                description: "Open new window"
            }
        ]);
    }

    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
    });

    const spellcheckEnabled = optionService.getOptionBool("spellCheckEnabled");

    const { BrowserWindow } = await import("electron"); // should not be statically imported

    mainWindow = new BrowserWindow({
        x: mainWindowState.x,
        y: mainWindowState.y,
        width: mainWindowState.width,
        height: mainWindowState.height,
        minWidth: 500,
        minHeight: 400,
        title: "Trilium Notes",
        // Start hidden (launched at login with hide-on-autostart) means the window
        // is never shown until the user summons it from the tray. Constructing it
        // hidden avoids a visible flash that show()-then-hide() would cause.
        show: !startHidden,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: getPreloadScript(),
            // Always attach Chromium's spell-check subsystem so it can be toggled at
            // runtime via session.setSpellCheckerEnabled(); the actual on/off state is
            // applied from the option in configureWebContents(). webPreferences.spellcheck
            // is immutable after creation, so leaving it false would force a restart to enable.
            spellcheck: true,
            webviewTag: true
        },
        icon: getIcon(),
        ...getWindowExtraOpts()
    });

    markStartupMetric("main-window-created");
    // First time the renderer has produced a frame of the page — the closest
    // main-process signal to "the window displays something".
    mainWindow.once("ready-to-show", () => markStartupMetric("main-window-first-paint"));
    mainWindow.webContents.once("did-finish-load", () => markStartupMetric("main-window-load-finished"));

    if (startHidden) {
        const hiddenWindow = mainWindow;
        const manageWindowState = () => {
            if (deferredWindowStateManagers.delete(hiddenWindow)) {
                mainWindowState.manage(hiddenWindow);
            }
        };
        deferredWindowStateManagers.set(hiddenWindow, manageWindowState);
        // This event is a fallback for a reveal that does not use showWindow().
        hiddenWindow.once("show", manageWindowState);
    } else {
        mainWindowState.manage(mainWindow);
    }

    mainWindow.setMenuBarVisibility(false);
    mainWindow.loadURL(TRILIUM_APP_BASE_URL);
    // Close-to-tray: when enabled, closing the main window hides it to the tray
    // instead of quitting. Only intercepts a genuine window close (not an app
    // quit, which sets `isQuitting` first). Extra windows are unaffected.
    mainWindow.on("close", (event) => {
        if (!isQuitting && !optionService.getOptionBool("disableTray") && optionService.getOptionBool("closeToTray")) {
            event.preventDefault();
            mainWindow?.hide();
        }
    });
    mainWindow.on("closed", () => (mainWindow = null));

    configureWebContents(mainWindow.webContents, spellcheckEnabled);
    trackWindowFocus(mainWindow);
}

function getWindowExtraOpts() {
    const extraOpts: Partial<BrowserWindowConstructorOptions> = {};

    if (!optionService.getOptionBool("nativeTitleBarVisible")) {
        if (coreUtils.isMac()) {
            extraOpts.titleBarStyle = "hiddenInset";
            extraOpts.titleBarOverlay = true;
        } else if (coreUtils.isWindows() || coreUtils.isLinux()) {
            // Window Controls Overlay: Chromium draws the caption buttons itself, following the
            // platform's own conventions (button glyphs, order and which side they sit on).
            // Supported on Windows and, since Electron 27, on Linux too.
            extraOpts.titleBarStyle = "hidden";
            extraOpts.titleBarOverlay = true;
        } else {
            extraOpts.frame = false;
        }

        // Window effects (Mica on Windows and Vibrancy on macOS)
        // These only work if native title bar is not enabled.
        if (optionService.getOptionBool("backgroundEffects")) {
            if (coreUtils.isMac()) {
                extraOpts.transparent = true;
                extraOpts.visualEffectState = "active";
            } else if (coreUtils.isWindows() && supportsBackgroundMaterial) {
                extraOpts.backgroundMaterial = "auto";
            }
        }
    }

    return extraOpts;
}

async function configureWebContents(webContents: WebContents, spellcheckEnabled: boolean) {
    // Window-open and navigation policy is NOT applied here: it is installed
    // globally for every WebContents (including setup and print windows,
    // which never pass through this function) by web_contents_security.ts.

    setupSpellcheckForSession(webContents.session, spellcheckEnabled);
    setupExportRevealForSession(webContents.session);

    // `window.open` from this renderer creates an extra window in the same
    // process (see installWindowOpenPolicy); it needs the same wiring as one
    // the main process created.
    webContents.on("did-create-window", (child) => adoptExtraWindow(child));

    // Forward full-screen events to the renderer via IPC.
    const win = electron.BrowserWindow.fromWebContents(webContents);
    if (win) {
        win.on("enter-full-screen", () => webContents.send("enter-full-screen"));
        win.on("leave-full-screen", () => webContents.send("leave-full-screen"));
    }

    // Forward navigation events to the renderer for back/forward button state.
    webContents.on("did-navigate", () => webContents.send("did-navigate"));
    webContents.on("did-navigate-in-page", () => webContents.send("did-navigate-in-page"));

    // Keep the renderer informed about whether DevTools is docked into this window, where
    // Chromium disables the native window material (Mica / vibrancy) and the renderer should
    // suspend its transparent background effects. Re-checked on focus because re-docking an
    // already open DevTools emits no dedicated event.
    const sendDevToolsDockState = () => webContents.send("dev-tools-dock-changed", isDevToolsDocked(webContents));
    webContents.on("devtools-opened", sendDevToolsDockState);
    webContents.on("devtools-focused", sendDevToolsDockState);
    webContents.on("devtools-closed", sendDevToolsDockState);

    // Forward context-menu event to the renderer with only the fields we need.
    webContents.on("context-menu", (_event, params) => {
        webContents.send("context-menu", {
            x: params.x,
            y: params.y,
            linkURL: params.linkURL,
            linkText: params.linkText,
            mediaType: params.mediaType,
            isEditable: params.isEditable,
            selectionText: params.selectionText,
            misspelledWord: params.misspelledWord,
            dictionarySuggestions: params.dictionarySuggestions,
            editFlags: {
                canCut: params.editFlags.canCut,
                canCopy: params.editFlags.canCopy,
                canPaste: params.editFlags.canPaste
            }
        });
    });
}

/** Whether DevTools for the given contents is open and docked into the page's own window (as opposed to a separate window). */
function isDevToolsDocked(webContents: WebContents) {
    const devToolsWebContents = webContents.devToolsWebContents;
    if (!webContents.isDevToolsOpened() || !devToolsWebContents) {
        return false;
    }

    // A docked DevTools view is hosted by the same BrowserWindow as the page itself; when
    // detached it lives in its own native window, which is not a BrowserWindow and for which
    // fromWebContents() returns null.
    const devToolsWindow = electron.BrowserWindow.fromWebContents(devToolsWebContents);
    return devToolsWindow !== null && devToolsWindow === electron.BrowserWindow.fromWebContents(webContents);
}

/**
 * Reveals note exports in the OS file manager once their download finishes, matching the native subtree
 * export (which reveals via shell.showItemInFolder). Single-note and OPML exports go through Electron's
 * download manager rather than the native handler, so they're caught here. Scoped to `/export/` URLs so
 * attachment/revision/file downloads are left alone, and registered once per session.
 */
function setupExportRevealForSession(session: Session) {
    if (exportRevealSessions.has(session)) {
        return;
    }
    exportRevealSessions.add(session);

    session.on("will-download", (_event, item) => {
        if (!/\/export\//.test(item.getURL())) {
            return;
        }
        item.once("done", (_e, state) => {
            if (state === "completed") {
                electron.shell.showItemInFolder(item.getSavePath());
            }
        });
    });
}

function setupSpellcheckForSession(session: Session, enabled: boolean) {
    // Preload the configured languages once per session (idempotent thereafter via the
    // WeakSet guard) so a later live enable already has them. Harmless while disabled.
    // This MUST run before setSpellCheckerEnabled(): Electron's setSpellCheckerLanguages()
    // implicitly forces kSpellCheckEnable = !languages.empty(), so calling it after a
    // disable would silently re-enable spell check on every launch (issue #10569).
    if (!loadedSpellcheckSessions.has(session)) {
        loadedSpellcheckSessions.add(session);
        session.setSpellCheckerLanguages(getConfiguredSpellcheckLanguages());
    }
    session.setSpellCheckerEnabled(enabled);
}

function getConfiguredSpellcheckLanguages(): string[] {
    return optionService
        .getOption("spellCheckLanguageCode")
        .split(",")
        .map((code) => code.trim())
        .filter(Boolean);
}

/**
 * Re-applies the spell-check language list to every open window's session so a
 * language change in the settings takes effect without restarting the app.
 * Sessions are deduplicated because all windows share the default session.
 */
function applySpellcheckLanguages(languageCodes: string[]) {
    // setSpellCheckerLanguages() forces the enabled state to !languageCodes.empty(), so a
    // language change while spell check is disabled would re-enable it. Re-assert the option
    // afterwards to keep the toggle authoritative (see setupSpellcheckForSession, issue #10569).
    const enabled = optionService.getOptionBool("spellCheckEnabled");
    const sessions = new Set<Session>();
    for (const win of electron.BrowserWindow.getAllWindows()) {
        sessions.add(win.webContents.session);
    }
    for (const session of sessions) {
        session.setSpellCheckerLanguages(languageCodes);
        session.setSpellCheckerEnabled(enabled);
    }
}

/**
 * Enables or disables the spell checker on every open window's session so the
 * toggle in settings takes effect without restarting the app. Relies on the
 * windows having been created with `webPreferences.spellcheck: true`.
 */
function applySpellcheckEnabled(enabled: boolean) {
    const sessions = new Set<Session>();
    for (const win of electron.BrowserWindow.getAllWindows()) {
        sessions.add(win.webContents.session);
    }
    for (const session of sessions) {
        session.setSpellCheckerEnabled(enabled);
    }
}

function getIcon() {
    if (process.env.NODE_ENV === "development") {
        return path.join(__dirname, "../../electron-forge/app-icon/png/256x256-dev.png");
    }
    if (app_info.appVersion.includes("test")) {
        return path.join(RESOURCE_DIR, "../public/assets/icon-dev.png");
    }
    return path.join(RESOURCE_DIR, "../public/assets/icon.png");
}

async function createSetupWindow() {
    const { BrowserWindow } = await import("electron"); // should not be statically imported
    const width = 750;
    const height = 650;
    setupWindow = new BrowserWindow({
        width,
        height,
        useContentSize: true,
        resizable: false,
        autoHideMenuBar: true,
        // What the window is for, which differs by how it was reached: a first run is getting the
        // user started, while an instance sent here by a marker is starting over on a knowledge base
        // it already has. Translated in the language the marker carried, which `initializeCore` has
        // already loaded by this point.
        title: isSetupRequested() ? t("setup-window.start-over") : t("setup-window.getting-started"),
        icon: getIcon(),
        // Background effects (Mica on Windows 11 22H2+, vibrancy on macOS)
        ...(coreUtils.isWindows() && supportsBackgroundMaterial && { backgroundMaterial: "mica" as const }),
        ...(coreUtils.isMac() && { transparent: true, visualEffectState: "active" as const, vibrancy: "under-window" as const }),
        // The window controls draw over the page, as in the main window with its default
        // `nativeTitleBarVisible`; the page reserves `env(titlebar-area-height)` for them.
        titleBarStyle: coreUtils.isMac() ? "hiddenInset" : "hidden",
        titleBarOverlay: true,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: getPreloadScript()
        }
    });
    setupWindow.removeMenu();
    // The wizard is served by the application's own page, whose `<title>` Electron would otherwise
    // apply to the window the moment it loads, replacing the one set above with the plain app name.
    setupWindow.on("page-title-updated", (e) => e.preventDefault());
    setupWindow.loadURL(TRILIUM_APP_BASE_URL);
    setupWindow.on("closed", () => (setupWindow = null));
}

function closeSetupWindow() {
    if (setupWindow) {
        setupWindow.close();
    }
}

async function registerGlobalShortcuts() {
    const { globalShortcut } = await import("electron");

    await sql_init.dbReady;

    const allActions = keyboardActionsService.getKeyboardActions();

    for (const action of allActions) {
        if (!("effectiveShortcuts" in action) || !action.effectiveShortcuts) {
            continue;
        }

        for (const shortcut of action.effectiveShortcuts) {
            if (shortcut.startsWith("global:")) {
                const translatedShortcut = shortcut.substr(7);

                const result = globalShortcut.register(
                    translatedShortcut,
                    cls.wrap(() => {
                        const targetWindow = getLastFocusedWindow() || mainWindow;
                        if (!targetWindow || targetWindow.isDestroyed()) {
                            return;
                        }

                        if (action.actionName === "toggleTray") {
                            targetWindow.focus();
                        } else {
                            showAndFocusWindow(targetWindow);
                        }

                        targetWindow.webContents.send("globalShortcut", action.actionName);
                    })
                );

                if (result) {
                    getLog().info(`Registered global shortcut ${translatedShortcut} for action ${action.actionName}`);
                } else {
                    getLog().info(`Could not register global shortcut ${translatedShortcut}`);
                }
            }
        }
    }
}

function showWindow(window: BrowserWindow) {
    // 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();
}

function showAndFocusWindow(window: BrowserWindow) {
    /* v8 ignore next -- defensive guard; every caller passes a non-null window narrowed beforehand */
    if (!window) return;

    if (window.isMinimized()) {
        window.restore();
    }

    showWindow(window);
    window.focus();
}

function getMainWindow() {
    return mainWindow;
}

function getLastFocusedWindow() {
    return allWindows.length > 0 ? allWindows[allWindows.length - 1] : null;
}

function getAllWindows() {
    return allWindows;
}

/**
 * Registers the renderer↔main IPC handlers backing `window.electronApi.window.*`
 * and the setup→main window swap that fires when the DB transitions to
 * initialized mid-session.
 *
 * Call once during desktop startup, before `app.ready` fires.
 */
export function setupWindowing() {
    // Window-open, navigation, <webview>-attach and permission policy is applied
    // to every WebContents the app creates. Installed here rather than left to
    // each entry point so a new Electron launcher cannot silently ship without
    // the renderer/main security boundary.
    setupWebContentsSecurity({ extraWindowOptions: getExtraWindowOptions });

    // Mark a genuine quit so the close-to-tray interceptor lets windows close for
    // real. Fires for every quit path (Cmd+Q, tray "Quit", app menu, OS shutdown).
    electron.app.on("before-quit", () => {
        isQuitting = true;
    });

    // This runs at `ready`, before the first window exists. A menu set after a framed window is
    // created shows the menu bar of that window again. The log service can be unready here.
    electron.app.whenReady().then(setupApplicationMenu).catch((e) => {
        console.error(`Could not set the application menu: ${e}`);
    });

    // Only app windows: reloading the hidden transcription capture page would end its capture.
    electron.ipcMain.on("reload-all-windows", () => {
        for (const win of electron.BrowserWindow.getAllWindows()) {
            if (isTriliumAppShellUrl(win.webContents.getURL())) {
                win.reload();
            }
        }
    });

    electron.ipcMain.on("restart-app", () => {
        electron.app.relaunch();
        electron.app.exit();
    });

    electron.ipcMain.on("copy-image-to-clipboard", async (_event, buffer: Uint8Array) => {
        try {
            const image = electron.nativeImage.createFromBuffer(Buffer.from(buffer));
            if (image.isEmpty()) {
                getLog().error("copy-image-to-clipboard: nativeImage is empty, unsupported format?");
                return;
            }
            // `clipboard.write()` takes MIME-typed payloads, and PNG is the format every
            // platform clipboard accepts, so the decoded image is re-encoded to PNG.
            const png = new Uint8Array(image.toPNG());
            await electron.clipboard.write([new electron.ClipboardItem({ "image/png": new Blob([png], { type: "image/png" }) })]);
        } catch (e) {
            getLog().error(`copy-image-to-clipboard failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
        }
    });

    electron.ipcMain.handle("read-clipboard-text", () => electron.clipboard.readText());
    electron.ipcMain.handle("read-clipboard-html", async () => {
        for (const item of await electron.clipboard.read()) {
            if (item.types.includes("text/html")) {
                const html = await item.getType("text/html");
                return html instanceof Blob ? html.text() : "";
            }
        }
        return "";
    });

    electron.ipcMain.on("show-window", (event) => {
        const window = electron.BrowserWindow.fromWebContents(event.sender);
        if (window) {
            showWindow(window);
        }
    });

    electron.ipcMain.handle("clear-cache", async (event) => {
        await event.sender.session.clearCache();
    });

    electron.ipcMain.on("toggle-all-windows", () => {
        const windows = electron.BrowserWindow.getAllWindows();
        const isVisible = windows.every((w) => w.isVisible());
        for (const win of windows) {
            if (isVisible) {
                win.hide();
            } else {
                showWindow(win);
            }
        }
    });

    electron.ipcMain.on("get-available-spellchecker-languages", (event) => {
        event.returnValue = event.sender.session.availableSpellCheckerLanguages;
    });

    electron.ipcMain.on("set-spellchecker-languages", (_event, languageCodes: string[]) => {
        applySpellcheckLanguages(languageCodes);
    });

    electron.ipcMain.on("set-spellchecker-enabled", (_event, enabled: boolean) => {
        applySpellcheckEnabled(enabled);
    });

    // Window management IPC handlers (replacing @electron/remote for renderer access)
    electron.ipcMain.on("set-title-bar-overlay", (event, options: { color: string; symbolColor: string; height?: number }) => {
        electron.BrowserWindow.fromWebContents(event.sender)?.setTitleBarOverlay(options);
    });

    electron.ipcMain.on("set-window-button-position", (event, position: { x: number; y: number }) => {
        electron.BrowserWindow.fromWebContents(event.sender)?.setWindowButtonPosition(position);
    });

    electron.ipcMain.on("set-background-material", (event, material: string) => {
        const win = electron.BrowserWindow.fromWebContents(event.sender);
        win?.setBackgroundMaterial(material as Parameters<typeof win.setBackgroundMaterial>[0]);
    });

    electron.ipcMain.on("set-vibrancy", (event, vibrancy: string) => {
        const win = electron.BrowserWindow.fromWebContents(event.sender);
        win?.setVibrancy(vibrancy as Parameters<typeof win.setVibrancy>[0]);
    });

    electron.ipcMain.on("clear-navigation-history", (event) => {
        electron.BrowserWindow.fromWebContents(event.sender)?.webContents.navigationHistory.clear();
    });

    electron.ipcMain.on("set-native-theme-source", (_event, source: "system" | "light" | "dark") => {
        electron.nativeTheme.themeSource = source;
    });

    electron.ipcMain.on("toggle-dev-tools", (event) => {
        event.sender.toggleDevTools();
    });

    electron.ipcMain.on("is-dev-tools-docked", (event) => {
        event.returnValue = isDevToolsDocked(event.sender);
    });

    electron.ipcMain.on("is-full-screen", (event) => {
        event.returnValue = electron.BrowserWindow.fromWebContents(event.sender)?.isFullScreen() ?? false;
    });

    electron.ipcMain.on("set-full-screen", (event, enabled: boolean) => {
        electron.BrowserWindow.fromWebContents(event.sender)?.setFullScreen(enabled);
    });

    electron.ipcMain.on("minimize-window", (event) => {
        electron.BrowserWindow.fromWebContents(event.sender)?.minimize();
    });

    electron.ipcMain.on("maximize-window", (event) => {
        electron.BrowserWindow.fromWebContents(event.sender)?.maximize();
    });

    electron.ipcMain.on("unmaximize-window", (event) => {
        electron.BrowserWindow.fromWebContents(event.sender)?.unmaximize();
    });

    electron.ipcMain.on("is-maximized", (event) => {
        event.returnValue = electron.BrowserWindow.fromWebContents(event.sender)?.isMaximized() ?? false;
    });

    electron.ipcMain.on("close-window", (event) => {
        electron.BrowserWindow.fromWebContents(event.sender)?.close();
    });

    electron.ipcMain.on("is-always-on-top", (event) => {
        event.returnValue = electron.BrowserWindow.fromWebContents(event.sender)?.isAlwaysOnTop() ?? false;
    });

    electron.ipcMain.on("set-always-on-top", (event, enabled: boolean) => {
        electron.BrowserWindow.fromWebContents(event.sender)?.setAlwaysOnTop(enabled);
    });

    electron.ipcMain.on("web-contents-action", (event, action: string, text?: string) => {
        const wc = event.sender;
        switch (action) {
            case "cut": wc.cut(); break;
            case "copy": wc.copy(); break;
            case "paste": wc.paste(); break;
            case "pasteAndMatchStyle": wc.pasteAndMatchStyle(); break;
            case "insertText": if (text) wc.insertText(text); break;
        }
    });

    electron.ipcMain.on("navigation-history", (event, method: string) => {
        const wc = event.sender;
        switch (method) {
            case "canGoBack": event.returnValue = wc.navigationHistory.canGoBack(); break;
            case "canGoForward": event.returnValue = wc.navigationHistory.canGoForward(); break;
            case "getAllEntries": event.returnValue = wc.navigationHistory.getAllEntries(); break;
            case "getActiveIndex": event.returnValue = wc.navigationHistory.getActiveIndex(); break;
            case "length": event.returnValue = wc.navigationHistory.length(); break;
            default: event.returnValue = null;
        }
    });

    electron.ipcMain.on("navigation-history-go-to-index", (event, index: number) => {
        event.sender.navigationHistory.goToIndex(index);
    });

    // Swap the setup wizard window for the main app window once the DB
    // transitions to initialized mid-session (fresh install / sync-from-server
    // flow). Idempotent: if no setup window exists (e.g., DB was already
    // initialized at startup and main was created in onReady), this is a no-op.
    events.subscribe(events.DB_INITIALIZED, async () => {
        if (!setupWindow) return;
        try {
            await createMainWindow();
            closeSetupWindow();
        } catch (err) {
            getLog().error(`Failed to swap setup window for main window: ${err}`);
        }
    });
}

/**
 * Installs an application menu without the `minimize` role. `setMenuBarVisibility(false)` keeps
 * the menu accelerators active, and `minimize` binds Ctrl+M, the text editor's math shortcut.
 */
function setupApplicationMenu() {
    // Cmd+M is standard on macOS. The app can be ready before `initializeCore()` makes
    // `coreUtils.isMac()` usable, so this reads `process.platform`.
    if (process.platform === "darwin") {
        return;
    }

    electron.Menu.setApplicationMenu(electron.Menu.buildFromTemplate([
        { role: "fileMenu" },
        { role: "editMenu" },
        { role: "viewMenu" },
        { role: "windowMenu", submenu: [{ role: "close" }] }
    ]));
}

export default {
    createMainWindow,
    createExtraWindow,
    createSetupWindow,
    closeSetupWindow,
    registerGlobalShortcuts,
    showAndFocusWindow,
    getMainWindow,
    getLastFocusedWindow,
    getAllWindows
};