Files
DOSSIER/scripts/electron-main.cjs

275 lines
11 KiB
JavaScript

// electron-main.js — Electron-Prototyp-Shell für die CAD-App.
//
// Ersetzt WebKitGTK (Tauri-Linux-Webview) durch Chromium, damit WebGPU
// (render2d-WASM-Engine, ?engine=wasm) zuverlässig läuft. Kein Rust-Backend
// nötig: compute_joins hat einen TS-Fallback (src/compute/index.ts).
const { app, BrowserWindow, Menu, ipcMain, protocol, session, dialog, shell } = require("electron");
const path = require("node:path");
const fs = require("node:fs");
const { buildCsp } = require("./csp.cjs");
const links = require("./electron-links.cjs"); // [268] externe Links, fremde Navigation
require("./electron-blender.cjs").register(ipcMain); // [211] Blender als eigener Prozess
require("./electron-cycles.cjs").register(ipcMain, app); // [215] mitgeliefertes Cycles als eigener Prozess
require("./electron-files.cjs").register(ipcMain, dialog, () => mainWindow); // [116] Projekt atomar speichern, Sicherung lesen
// Randloses App-Fenster wie chromium-shell.sh (--app=…): keine native
// Menüleiste (File/Edit/View/Window), kein Fensterrahmen. Minimieren/
// Maximieren/Schliessen laufen darum über eine eigene Fenstersteuerung im
// Renderer (WindowControls.tsx) + IPC hier unten — ohne frame gibt es sonst
// gar keine Möglichkeit, das Fenster zu steuern.
Menu.setApplicationMenu(null);
// Gleiche Flags wie scripts/chromium-shell.sh — WebGPU liegt unter Linux
// hinter --enable-unsafe-webgpu, und WebGPU braucht das Vulkan-Backend.
app.commandLine.appendSwitch("enable-unsafe-webgpu");
// Unter Wayland läuft Dossier nativ (`--ozone-platform=wayland`) mit GPU-Modus „minimal“: Chromiums Vulkan-Compositor
// verträgt sich nicht mit Wayland („not compatible with Vulkan“), und über XWayland zeigt der Compositor einen
// schwarzen Rand in abgerundeten Fensterecken (Test Maintainer, Void/Wayland, 13.11.). Übersteuerbar: DOSSIER_OZONE=wayland|x11.
const wayland = !!(process.env.WAYLAND_DISPLAY || process.env.XDG_SESSION_TYPE === "wayland");
const ozone = process.env.DOSSIER_OZONE || (wayland ? "wayland" : "");
// DOSSIER_GPU: „vulkan“ (Vorgabe ausser unter Wayland: Skia + ANGLE über Vulkan), „angle“ (nur ANGLE über Vulkan, Skia/
// Compositor auf GL), „minimal“ (nur WebGPU freigeben, sonst Chromium-Vorgaben; Vorgabe unter nativem Wayland).
const gpu = process.env.DOSSIER_GPU || (ozone === "wayland" ? "minimal" : "vulkan");
if (gpu === "vulkan") app.commandLine.appendSwitch("enable-features", "Vulkan,VulkanFromANGLE,DefaultANGLEVulkan");
else if (gpu === "angle") app.commandLine.appendSwitch("enable-features", "VulkanFromANGLE,DefaultANGLEVulkan");
console.log(`[dossier] GPU-Modus: ${gpu}${ozone ? `, Plattform: ${ozone}` : ""}`);
// [261] Version und Buildnummer ins Log (Fehlerberichte); `dossierBuild` setzt scripts/electron-pack.cjs ins gepackte package.json.
try {
const build = require("../package.json").dossierBuild;
console.log(`[dossier] Version ${app.getVersion()}${build ? ` (Build ${build})` : ""}`);
} catch {
/* ohne package.json: kein Log */
}
if (ozone) app.commandLine.appendSwitch("ozone-platform", ozone);
const DEV_URL = "http://localhost:5187";
const isDev = !app.isPackaged && !process.env.DOSSIER_USE_DIST; // DOSSIER_USE_DIST=1: gebautes dist ohne Paket prüfen
// [170] Gepackt (AppImage/Flatpak) lädt die App aus `dist` über ein eigenes, „standard“-Schema statt
// file://: absolute Asset-Pfade (/assets/…), fetch() der WASM-Module (application/wasm), Worker und
// localStorage brauchen einen richtigen Ursprung. Muss vor `ready` registriert werden.
const APP_SCHEME = "dossier";
const APP_ORIGIN = `${APP_SCHEME}://app`;
const APP_ORIGINS = [APP_ORIGIN, new URL(DEV_URL).origin]; // [268] erlaubte Ursprünge für Navigation/CSP
const DIST_DIR = path.join(__dirname, "..", "dist");
const MIME = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".wasm": "application/wasm",
".svg": "image/svg+xml",
".png": "image/png",
".jpg": "image/jpeg",
".webp": "image/webp",
".woff": "font/woff",
".woff2": "font/woff2",
".ttf": "font/ttf",
".txt": "text/plain; charset=utf-8",
".map": "application/json; charset=utf-8",
};
protocol.registerSchemesAsPrivileged([
{ scheme: APP_SCHEME, privileges: { standard: true, secure: true, supportFetchAPI: true, stream: true, corsEnabled: true } },
]);
function serveDist(request) {
const { pathname } = new URL(request.url);
let rel = decodeURIComponent(pathname);
if (rel === "/" || rel === "") rel = "/index.html";
const file = path.normalize(path.join(DIST_DIR, rel));
// Kein Ausbruch aus dist (../).
if (file !== DIST_DIR && !file.startsWith(DIST_DIR + path.sep)) return new Response("Forbidden", { status: 403 });
try {
const body = fs.readFileSync(file);
const type = MIME[path.extname(file).toLowerCase()] || "application/octet-stream";
return new Response(body, { headers: { "content-type": type } });
} catch {
return new Response("Not found", { status: 404 });
}
}
// [170] Projektdatei per Argument (`dossier datei.obp`, Doppelklick im Dateimanager über %F im
// Desktop-Eintrag). Erste vorhandene .obp-Datei der Argumente; relative Pfade gegen `cwd`.
function findProjectArg(argv, cwd) {
for (const a of argv.slice(1)) {
if (!a || a.startsWith("-") || !/\.obp$/i.test(a)) continue;
const full = path.resolve(cwd || process.cwd(), a);
try {
if (fs.statSync(full).isFile()) return full;
} catch {
/* nicht vorhanden: ignorieren */
}
}
return null;
}
let mainWindow = null;
let pendingOpenFile = findProjectArg(process.argv, process.cwd());
function readProject(file) {
try {
return { name: path.basename(file), path: file, text: fs.readFileSync(file, "utf8") };
} catch {
return null;
}
}
// Nur eine Instanz: ein zweiter Start (`dossier b.obp`) reicht die Datei an das offene Fenster weiter.
const gotLock = app.requestSingleInstanceLock();
if (!gotLock) {
app.quit();
} else {
app.on("second-instance", (_event, argv, cwd) => {
const file = findProjectArg(argv, cwd);
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
const proj = file && readProject(file);
if (proj) mainWindow.webContents.send("launch:open-file", proj);
} else if (file) {
pendingOpenFile = file;
}
});
}
ipcMain.handle("launch:take-open-file", () => {
const file = pendingOpenFile;
pendingOpenFile = null;
return file ? readProject(file) : null;
});
const closeGuard = new Set(); // Fenster-IDs mit Schliess-Wächter ([116])
const forceClose = new Set(); // Fenster-IDs, die jetzt ohne Rückfrage schliessen dürfen
function createWindow() {
const win = new BrowserWindow({
title: "Dossier",
width: 1600,
height: 1000,
frame: false,
autoHideMenuBar: true,
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: path.join(__dirname, "electron-preload.cjs"),
},
});
mainWindow = win;
// [268] Nie ein Kindfenster (es erbte Preload/CSP): https/mailto im System-Browser, alles andere verwerfen.
// Navigation und Weiterleitung des App-Fensters bleiben im App-Ursprung (gepackt `dossier://app`, Dev der Vite-Server).
win.webContents.setWindowOpenHandler(({ url }) => {
const d = links.windowOpenDecision(url);
if (d.external) void shell.openExternal(d.external);
return { action: "deny" };
});
const guardNav = (event, url) => {
const d = links.navigationDecision(url, APP_ORIGINS);
if (d.allow) return;
event.preventDefault();
if (d.external) void shell.openExternal(d.external);
};
// [290] Start-Meldungen der Seite (`[dossier] WebGPU-Adapter: …`) ins Terminal/Log — sonst sieht man unter Linux nicht,
// ob das 3D auf der Grafikkarte oder in SwiftShader (CPU) läuft.
win.webContents.on("console-message", (e, _level, legacy) => {
const msg = String(e.message ?? legacy ?? "");
if (msg.startsWith("[dossier]")) console.log(msg);
});
win.webContents.on("will-navigate", guardNav);
win.webContents.on("will-redirect", guardNav);
// [116] Schliess-Wächter: ist er gesetzt (Renderer läuft), geht das Fenster erst nach „window:force-close" zu;
// der Renderer fragt bei ungespeicherten Änderungen im Overlay nach. Stürzt der Renderer ab, gilt der Wächter nicht mehr.
win.webContents.on("render-process-gone", () => closeGuard.delete(win.id));
win.on("close", (e) => {
if (closeGuard.has(win.id) && !forceClose.has(win.id)) {
e.preventDefault();
win.webContents.send("window:close-requested");
}
});
win.on("closed", () => {
closeGuard.delete(win.id);
forceClose.delete(win.id);
if (mainWindow === win) mainWindow = null;
});
const notifyMaximized = () => {
win.webContents.send("window:maximized-changed", win.isMaximized());
};
win.on("maximize", notifyMaximized);
win.on("unmaximize", notifyMaximized);
if (isDev) {
win.loadURL(DEV_URL);
} else {
win.loadURL(`${APP_ORIGIN}/index.html`);
}
}
// Fenstersteuerung vom Renderer (WindowControls.tsx über electron-preload.cjs).
// Wirkt auf das Fenster, aus dem das Event kam (mehrfachfenster-sicher).
ipcMain.on("window:minimize", (event) => {
BrowserWindow.fromWebContents(event.sender)?.minimize();
});
ipcMain.on("window:toggle-maximize", (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (!win) return;
if (win.isMaximized()) win.unmaximize();
else win.maximize();
});
ipcMain.on("window:close", (event) => {
BrowserWindow.fromWebContents(event.sender)?.close();
});
ipcMain.on("window:set-close-guard", (event, enabled) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (!win) return;
if (enabled) closeGuard.add(win.id);
else closeGuard.delete(win.id);
});
ipcMain.on("window:force-close", (event) => {
const win = BrowserWindow.fromWebContents(event.sender);
if (!win) return;
forceClose.add(win.id);
win.close();
});
ipcMain.handle("window:is-maximized", (event) => {
return BrowserWindow.fromWebContents(event.sender)?.isMaximized() ?? false;
});
app.whenReady().then(() => {
if (!gotLock) return;
// [273] Liegengebliebene Arbeitsordner von Rendering/Cycles (älter als 24 h) aufräumen.
try {
const bl = require("./electron-blender.cjs");
bl.sweepOldJobDirs(bl.renderRoot(), 24 * 3600 * 1000);
} catch {
// Aufräumen ist nie wichtiger als der Start
}
// [117] CSP als Antwort-Header — nur gepackt: der Dev-Server (Vite HMR) braucht Inline-Skripte.
if (!isDev) {
protocol.handle(APP_SCHEME, serveDist);
session.defaultSession.webRequest.onHeadersReceived((details, cb) => {
// [268] Nur Antworten des App-Ursprungs bekommen die CSP.
if (!links.shouldSetCsp(details.url, APP_ORIGINS)) return cb({});
cb({ responseHeaders: { ...details.responseHeaders, "Content-Security-Policy": [buildCsp()] } });
});
}
createWindow();
// [290] Chromiums GPU-Status ins Log: „webgpu: enabled“ = Hardware; „unavailable_software“/„disabled_*“ = CPU/aus.
try {
const st = app.getGPUFeatureStatus();
console.log(`[dossier] GPU-Status: webgpu=${st.webgpu ?? "?"}, gpu_compositing=${st.gpu_compositing}, rasterization=${st.rasterization}`);
} catch {
/* nur Log */
}
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit();
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});