Skip to content

Build your personal knowledge base with Trilium Notes

19.8 KB
Raw Blame
import { getLog, utils as coreUtils } from "@triliumnext/core";
import { default as electron, ipcMain, type IpcMainEvent } from "electron";
import fs from "fs/promises";
import { t } from "i18next";
import path from "path";

import { TRILIUM_APP_BASE_URL } from "./trilium_app_origin.js";

// Preload bundle path — built next to main.mjs in production by
// apps/desktop/scripts/build.ts, or compiled in-place by the dev runner
// (scripts/electron-start.mts) into apps/desktop/src/preload.compiled.cjs.
// Print windows share the same preload as the main window so the renderer
// has access to `window.electronApi.printing.sendPrintProgress`.
//
// Lazy: `coreUtils.isDev()` calls `getPlatform()` which throws until
// `initializeCore()` has run. Module load happens before that, so we defer
// resolution to the first print invocation.
let preloadScriptCache: string | undefined;
function getPreloadScript(): string {
    if (preloadScriptCache === undefined) {
        // Dev: this file lives one directory below the preload bundle.
        // Prod: this file is bundled into dist/main.mjs alongside preload.cjs
        //   (no `..` — keep this synced with apps/desktop/src/services/window.ts).
        /* 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;
}

/** How long the print page can go without reporting progress before the render is abandoned. */
export const RENDER_STALL_TIMEOUT_MS = 30_000;

interface PrintOpts {
    notePath: string;
    printToPdf: boolean;
}

interface ExportAsPdfOpts {
    notePath: string;
    /**
     * Prints the sender's own window, which the renderer prepared for printing as this live print,
     * instead of `notePath`. `print-done` echoes it so the renderer restores only that live print.
     */
    liveJobId?: number;
    title: string;
    landscape: boolean;
    pageSize: "A0" | "A1" | "A2" | "A3" | "A4" | "A5" | "A6" | "Legal" | "Letter" | "Tabloid" | "Ledger";
    scale: number;
    margins: string;
    pageRanges: string;
}

interface PreviewOpts extends ExportAsPdfOpts {
    /** Echoed back with the result so the dialog can drop results of superseded requests. */
    requestId: number;
}

interface PrintFromPreviewOpts extends ExportAsPdfOpts {
    silent: boolean;
    deviceName?: string;
}

/** Parses the printMargins attribute into Electron margins.
 *  Values are stored in mm and converted to inches for Electron.
 *  Presets expand to explicit numeric margins since Electron's `marginType` aliases
 *  (especially `none` and `printableArea`) behave inconsistently for PDF output. */
export function parseMargins(margins: string): Electron.Margins {
    const mmToInches = (mm: number) => mm / 25.4;
    const uniform = (mm: number): Electron.Margins => ({
        marginType: "custom",
        top: mmToInches(mm),
        right: mmToInches(mm),
        bottom: mmToInches(mm),
        left: mmToInches(mm)
    });

    if (!margins || margins === "default") return uniform(20);  // 2cm
    if (margins === "none") return uniform(0);
    if (margins === "minimum") return uniform(5);

    const parts = margins.split(",").map(Number);
    if (parts.length === 4 && parts.every((n) => !isNaN(n))) {
        return {
            marginType: "custom",
            top: mmToInches(parts[0]),
            right: mmToInches(parts[1]),
            bottom: mmToInches(parts[2]),
            left: mmToInches(parts[3])
        };
    }

    return uniform(10);
}

/** Convert "1-5, 8, 11-13" into PageRanges array form expected by webContents.print. */
export function parsePageRangesForPrint(pageRanges: string): { from: number; to: number }[] | undefined {
    if (!pageRanges?.trim()) return undefined;
    const ranges: { from: number; to: number }[] = [];
    for (const part of pageRanges.split(",")) {
        const trimmed = part.trim();
        if (!trimmed) continue;
        const [fromStr, toStr] = trimmed.split("-").map(s => s.trim());
        const from = parseInt(fromStr, 10);
        const to = toStr ? parseInt(toStr, 10) : from;
        if (!isNaN(from) && !isNaN(to)) ranges.push({ from, to });
    }
    return ranges.length ? ranges : undefined;
}

async function getBrowserWindowForPrinting(e: IpcMainEvent, notePath: string, action: "printing" | "exporting_pdf") {
    // Offscreen rendering crashes on Wayland due to a Chromium bug where the OSR surface
    // lacks a valid xdg_toplevel role, causing a fatal zxdg_exporter_v2 protocol error.
    // On Linux we work around this by creating a regular window positioned off-screen,
    // since `show: false` without OSR causes Chromium to skip rendering entirely.
    const useOffscreen = process.platform !== "linux";
    const browserWindow = new electron.BrowserWindow({
        show: !useOffscreen,
        ...(useOffscreen ? {} : {
            width: 1,
            height: 1,
            frame: false,
            skipTaskbar: true,
            focusable: false,
        }),
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: getPreloadScript(),
            offscreen: useOffscreen,
            devTools: false,
            session: e.sender.session
        },
    });

    // Capture ALL console output (including errors) for debugging
    browserWindow.webContents.on("console-message", ({ level, message, lineNumber, sourceId }) => {
        if (level === "debug") return;
        if (level === "error") {
            getLog().error(`[Print Window ${sourceId}:${lineNumber}] ${message}`);
            return;
        }
        getLog().info(`[Print Window ${sourceId}:${lineNumber}] ${message}`);
    });

    // Collections report progress while they render, so only a render that stops advancing times out.
    let stallTimer: ReturnType<typeof setTimeout> | undefined;
    let rejectStalled: (err: Error) => void = () => {};
    const stalled = new Promise<never>((_resolve, reject) => {
        rejectStalled = reject;
    });
    const restartStallTimer = () => {
        clearTimeout(stallTimer);
        stallTimer = setTimeout(() => {
            rejectStalled(new Error(t("pdf.render-timeout", { seconds: RENDER_STALL_TIMEOUT_MS / 1000 })));
        }, RENDER_STALL_TIMEOUT_MS);
    };

    // Every print window reports on the same channel, so a job only listens to its own.
    const progressCallback = (progressEvent: IpcMainEvent, progress: number) => {
        if (progressEvent.sender !== browserWindow.webContents) return;
        restartStallTimer();
        e.sender.send("print-progress", { progress, action });
    };
    ipcMain.on("print-progress", progressCallback);
    restartStallTimer();

    try {
        const printReport = await Promise.race([ loadPrintPage(browserWindow, notePath), stalled ]);
        return { browserWindow, printReport };
    } catch (err) {
        getLog().error(`Unable to render ${notePath} for printing: ${err}`);
        browserWindow.destroy();
        throw err;
    } finally {
        clearTimeout(stallTimer);
        ipcMain.off("print-progress", progressCallback);
    }
}

/**
 * Returns the page a print job prints: the sender's own window for a live print, otherwise a new
 * window rendering `notePath`. `dispose` releases it once the job is done.
 */
async function getPrintTarget(e: IpcMainEvent, notePath: string, action: "printing" | "exporting_pdf", live?: boolean) {
    if (live) {
        return { webContents: e.sender, printReport: undefined, dispose: () => {} };
    }

    const { browserWindow, printReport } = await getBrowserWindowForPrinting(e, notePath, action);
    return { webContents: browserWindow.webContents, printReport, dispose: () => browserWindow.destroy() };
}

/** Loads the print page into `browserWindow` and resolves with its report once the note is ready. */
async function loadPrintPage(browserWindow: Electron.BrowserWindow, notePath: string): Promise<unknown> {
    // Load through the custom protocol so the print window is same-origin
    // with the main renderer (`trilium-app://app/`). Loading over HTTP
    // would split origins — the main window's session cookie wouldn't
    // reach the print window, auth would redirect to /login, and the
    // print page would never render.
    await browserWindow.loadURL(`${TRILIUM_APP_BASE_URL}?print#${notePath}`);

    // Set up error tracking and logging in the renderer process
    await browserWindow.webContents.executeJavaScript(`
        (function() {
            window._printWindowErrors = [];
            window.addEventListener("error", (e) => {
                const errorMsg = "Uncaught error: " + e.message + " at " + e.filename + ":" + e.lineno + ":" + e.colno;
                console.error(errorMsg);
                if (e.error?.stack) console.error(e.error.stack);
                window._printWindowErrors.push({
                    type: 'error',
                    message: errorMsg,
                    stack: e.error?.stack
                });
            });
            window.addEventListener("unhandledrejection", (e) => {
                const errorMsg = "Unhandled rejection: " + String(e.reason);
                console.error(errorMsg);
                if (e.reason?.stack) console.error(e.reason.stack);
                window._printWindowErrors.push({
                    type: 'rejection',
                    message: errorMsg,
                    stack: e.reason?.stack
                });
            });
        })();
    `).catch(err => getLog().error(`Failed to set up error handlers in print window: ${err}`));

    return await browserWindow.webContents.executeJavaScript(`
        new Promise((resolve, reject) => {
            if (window._noteReady) return resolve(window._noteReady);

            // Check for errors periodically
            const errorChecker = setInterval(() => {
                if (window._printWindowErrors && window._printWindowErrors.length > 0) {
                    clearInterval(errorChecker);
                    const errors = window._printWindowErrors.map(e => e.message).join('; ');
                    reject(new Error("Print window errors: " + errors));
                }
            }, 100);

            window.addEventListener("note-ready", (data) => {
                clearInterval(errorChecker);
                resolve(data.detail);
            });
        });
    `);
}

/** Registers all printing-related IPC handlers. Call once on Electron startup. */
export function setupPrintingHandlers() {
    electron.ipcMain.on("print-note", async (e, { notePath }: PrintOpts) => {
        try {
            const { browserWindow, printReport } = await getBrowserWindowForPrinting(e, notePath, "printing");
            browserWindow.webContents.print({}, (success, failureReason) => {
                if (!success && failureReason !== "Print job canceled") {
                    electron.dialog.showErrorBox(t("pdf.unable-to-print"), failureReason);
                }
                e.sender.send("print-done", printReport);
                browserWindow.destroy();
            });
        } catch (err) {
            e.sender.send("print-done", {
                type: "error",
                message: err instanceof Error ? err.message : String(err),
                stack: err instanceof Error ? err.stack : undefined
            });
        }
    });

    electron.ipcMain.on("export-as-pdf", async (e, { title, notePath, landscape, pageSize, scale, margins, pageRanges }: ExportAsPdfOpts) => {
        try {
            const { browserWindow, printReport } = await getBrowserWindowForPrinting(e, notePath, "exporting_pdf");

            async function print() {
                const filePath = electron.dialog.showSaveDialogSync(browserWindow, {
                    defaultPath: coreUtils.formatDownloadTitle(title, "file", "application/pdf"),
                    filters: [
                        {
                            name: t("pdf.export_filter"),
                            extensions: ["pdf"]
                        }
                    ]
                });
                if (!filePath) return;

                let buffer: Buffer;
                try {
                    buffer = await browserWindow.webContents.printToPDF({
                        landscape,
                        pageSize,
                        scale,
                        margins: parseMargins(margins),
                        pageRanges: pageRanges || undefined,
                        preferCSSPageSize: false,
                        generateDocumentOutline: true,
                        generateTaggedPDF: true,
                        printBackground: true,
                        displayHeaderFooter: true,
                        headerTemplate: `<div></div>`,
                        footerTemplate: `
                            <div class="pageNumber" style="width: 100%; text-align: center; font-size: 10pt;">
                            </div>
                        `
                    });
                } catch (_e) {
                    electron.dialog.showErrorBox(t("pdf.unable-to-export-title"), t("pdf.unable-to-export-message"));
                    return;
                }

                try {
                    await fs.writeFile(filePath, buffer);
                } catch (_e) {
                    electron.dialog.showErrorBox(t("pdf.unable-to-export-title"), t("pdf.unable-to-save-message"));
                    return;
                }

                electron.shell.openPath(filePath);
            }

            try {
                await print();
            } finally {
                e.sender.send("print-done", printReport);
                browserWindow.destroy();
            }
        } catch (err) {
            e.sender.send("print-done", {
                type: "error",
                message: err instanceof Error ? err.message : String(err),
                stack: err instanceof Error ? err.stack : undefined
            });
        }
    });

    electron.ipcMain.on("export-as-pdf-preview", async (e, { notePath, liveJobId, requestId, landscape, pageSize, scale, margins, pageRanges }: PreviewOpts) => {
        const live = typeof liveJobId === "number";
        try {
            const { webContents, printReport, dispose } = await getPrintTarget(e, notePath, "exporting_pdf", live);

            try {
                const buffer = await webContents.printToPDF({
                    landscape,
                    pageSize,
                    scale,
                    margins: parseMargins(margins),
                    pageRanges: pageRanges || undefined,
                    preferCSSPageSize: false,
                    generateDocumentOutline: true,
                    generateTaggedPDF: true,
                    printBackground: true,
                    displayHeaderFooter: true,
                    headerTemplate: `<div></div>`,
                    footerTemplate: `
                        <div class="pageNumber" style="width: 100%; text-align: center; font-size: 10pt;">
                        </div>
                    `
                });

                e.sender.send("export-as-pdf-preview-result", { buffer, notePath, requestId });
            } catch (err) {
                const message = err instanceof Error ? err.message : String(err);
                e.sender.send("export-as-pdf-preview-result", { notePath, requestId, error: message });
            } finally {
                // A live print stays prepared until the print itself is done.
                if (!live) e.sender.send("print-done", printReport);
                dispose();
            }
        } catch (err) {
            // The preview dialog reports the error itself, so no `print-done` goes out.
            e.sender.send("export-as-pdf-preview-result", { notePath, requestId, error: err instanceof Error ? err.message : String(err) });
        }
    });

    electron.ipcMain.on("save-pdf", async (_e, { title, buffer }: { title: string; buffer: Buffer }) => {
        const focusedWindow = electron.BrowserWindow.getFocusedWindow();
        if (!focusedWindow) return;

        const filePath = electron.dialog.showSaveDialogSync(focusedWindow, {
            defaultPath: coreUtils.formatDownloadTitle(title, "file", "application/pdf"),
            filters: [
                {
                    name: t("pdf.export_filter"),
                    extensions: ["pdf"]
                }
            ]
        });
        if (!filePath) return;

        try {
            await fs.writeFile(filePath, Buffer.from(buffer));
        } catch (_e) {
            electron.dialog.showErrorBox(t("pdf.unable-to-export-title"), t("pdf.unable-to-save-message"));
            return;
        }

        electron.shell.openPath(filePath);
    });

    electron.ipcMain.handle("get-printers", async (e) => {
        try {
            const printers = await e.sender.getPrintersAsync();
            return printers.map((p) => {
                // Platform-specific: CUPS uses "printer-location", Windows/mac often expose "location".
                const opts = (p.options ?? {}) as Record<string, string>;
                return {
                    name: p.name,
                    displayName: p.displayName,
                    description: p.description,
                    location: opts["printer-location"] || opts.location || "",
                    isDefault: (p as unknown as { isDefault?: boolean }).isDefault ?? false
                };
            });
        } catch {
            return [];
        }
    });

    electron.ipcMain.on("print-from-preview", async (e, { notePath, liveJobId, landscape, pageSize, scale, margins, pageRanges, silent, deviceName }: PrintFromPreviewOpts) => {
        const live = typeof liveJobId === "number";
        try {
            const { webContents, printReport, dispose } = await getPrintTarget(e, notePath, "printing", live);

            // print() accepts most of the same options as printToPDF, but typing differs
            // slightly (e.g. no "Ledger" pageSize). Cast to keep this concise.
            // "Ledger" and "Tabloid" are the same physical size (11×17 in); Electron's
            // print() API only recognises "Tabloid", so we map "Ledger" to "Tabloid".
            const printOpts: Electron.WebContentsPrintOptions = {
                silent,
                deviceName,
                landscape,
                pageSize: pageSize === "Ledger" ? "Tabloid" : pageSize,
                scaleFactor: Math.round(scale * 100),
                margins: parseMargins(margins),
                pageRanges: parsePageRangesForPrint(pageRanges),
                printBackground: true
            };

            webContents.print(printOpts, (success, failureReason) => {
                if (!success && failureReason !== "Print job canceled") {
                    electron.dialog.showErrorBox(t("pdf.unable-to-print"), failureReason);
                }
                e.sender.send("print-from-preview-done");
                // Also sent for a live print: it is what restores the sender's window.
                sendPrintDone(e, printReport ?? { type: "single-note" }, live ? liveJobId : undefined);
                dispose();
            });
        } catch (err) {
            e.sender.send("print-from-preview-done");
            sendPrintDone(e, {
                type: "error",
                message: err instanceof Error ? err.message : String(err),
                stack: err instanceof Error ? err.stack : undefined
            }, live ? liveJobId : undefined);
        }
    });
}

/** Sends `print-done`, naming the live print it ends, if any, so the renderer restores only that one. */
function sendPrintDone(e: IpcMainEvent, printReport: unknown, liveJobId: number | undefined) {
    if (liveJobId === undefined) {
        e.sender.send("print-done", printReport);
    } else {
        e.sender.send("print-done", printReport, liveJobId);
    }
}