Files
DOSSIER/scripts/electron-main.cjs
T
Claude 64563dba44 [170][30][261] Linux-App: AppImage im Container gebaut und mit Playwright-Electron geprüft, vier Fehler behoben
Linux ist ab 1.0 offiziell (Entscheid 16.11.). Das AppImage wird wie im Release gebaut
(npm run build && npm run electron:pack) und mit `npm run test:linux-app` bedient
(e2e/linuxApp170.spec.ts, Playwright _electron, Xvfb; im normalen e2e-Lauf übersprungen):
Start, Kern, Wand per Befehlszeile, Speichern atomar mit .obp~, Strg+S, Öffnen per Dialog
und per Argument, PDF/DXF auf die Platte, Autosave-Wiederherstellen nach kill -9.
Grün über FUSE, mit APPIMAGE_EXTRACT_AND_RUN=1 und entpackt (linux-unpacked).

Behoben:
- scripts/electron-files.cjs fehlte in `files` von electron-builder.yml: das gepackte
  Programm startete nicht („Cannot find module“). Test src/native/electronPackage.test.ts
  prüft alle require() von Hauptprozess und Preload gegen die Paketliste.
- `dossier datei.obp`: Datei wurde hinter dem Startbildschirm geladen bzw. wartete auf eine
  Rückfrage, die dort nicht erscheint; jetzt direkt in den Editor (onLaunchFile).
- Strg+S / Strg+Umschalt+S / Strg+O gab es nur im nativen Tauri-Menü; jetzt auch im
  Browser/Electron (useFileShortcuts, fileShortcutFor + Test).
- Datei → „Exportieren: PDF“ fehlte im Browser/Electron (nur natives Menü); ergänzt, e2e io.spec.ts.

Buildnummer [261]: Vite schreibt dist/build-info.json; scripts/electron-pack.cjs gibt sie über
die electron-builder-API als buildVersion und extraMetadata.dossierBuild weiter (über `-c.` auf der
Kommandozeile würde „261116.10“ zur Zahl). release.yml: `--version=` statt `-c.extraMetadata.version`,
neuer Schritt „AppImage prüfen“ (xvfb, libfuse2t64; nicht auf GitHub gelaufen).

Doku: doc/RELEASE-1.0.md Abschnitt 15 (Linux-App, Status je Schritt), Release-Notes Linux,
README „Linux installieren“, TODO [170]/[261].

Geprüft: npm run check --fast (tsc, vitest) grün; e2e io/datensicherheit116/start im Browser grün;
test:linux-app dreimal grün. Nicht geprüft: Rust-Tests (nichts geändert), echte GPU, Wayland,
GTK-Dialoge von Hand, Sandbox als normaler Benutzer, Mac/Tauri.
2026-11-16 10:47:51 +00:00

235 lines
9.3 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 } = require("electron");
const path = require("node:path");
const fs = require("node:fs");
const { buildCsp } = require("./csp.cjs");
require("./electron-blender.cjs").register(ipcMain); // [211] Blender 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 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;
// [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;
// [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) => {
cb({ responseHeaders: { ...details.responseHeaders, "Content-Security-Policy": [buildCsp()] } });
});
}
createWindow();
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit();
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});