[116] Exporte atomar (Tauri save_export), Electron speichert Projekte atomar im Hauptprozess, Wiederherstellung aus .obp~ (Öffnen-Angebot + Datei-Menü)
This commit is contained in:
22 files changed
+755
-29
No files matched your search
@@ -34,6 +34,8 @@ export interface NativeAppMenuHandlers {
|
||||
onOpenProject: () => void;
|
||||
onSaveProject: () => void;
|
||||
onSaveProjectAs: () => void;
|
||||
/** Datei: vorige Fassung (.obp~) der aktuellen Datei wiederherstellen ([116]). */
|
||||
onRestoreBackup: () => void;
|
||||
onImport: () => void;
|
||||
onExportPdf: () => void;
|
||||
onExportDxf: () => void;
|
||||
@@ -204,6 +206,10 @@ export function useNativeAppMenu(
|
||||
accelerator: "CmdOrCtrl+Shift+S",
|
||||
action: () => handlersRef.current.onSaveProjectAs(),
|
||||
}),
|
||||
await MenuItem.new({
|
||||
text: t("menu.native.restoreBackup"),
|
||||
action: () => handlersRef.current.onRestoreBackup(),
|
||||
}),
|
||||
await MenuItem.new({
|
||||
text: t("menu.native.import"),
|
||||
action: () => handlersRef.current.onImport(),
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// Atomares Schreiben im Electron-Hauptprozess ([116], scripts/electron-files.cjs) — gleiche Garantien wie atomic_save.rs.
|
||||
|
||||
import { mkdtempSync, mkdirSync, readFileSync, existsSync, writeFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
const { writeAtomic, backupExists } = createRequire(import.meta.url)("../../scripts/electron-files.cjs") as {
|
||||
writeAtomic: (file: string, text: string, keepBackup: boolean) => void;
|
||||
backupExists: (file: string) => boolean;
|
||||
};
|
||||
|
||||
const dirs: string[] = [];
|
||||
const tmp = () => {
|
||||
const d = mkdtempSync(join(tmpdir(), "dossier-efiles-"));
|
||||
dirs.push(d);
|
||||
return d;
|
||||
};
|
||||
afterEach(() => {
|
||||
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("electron-files: atomares Speichern", () => {
|
||||
it("neue Datei ohne Sicherung, keine Temp-Datei", () => {
|
||||
const p = join(tmp(), "a.obp");
|
||||
writeAtomic(p, "eins", true);
|
||||
expect(readFileSync(p, "utf8")).toBe("eins");
|
||||
expect(backupExists(p)).toBe(false);
|
||||
expect(existsSync(`${p}.tmp`)).toBe(false);
|
||||
});
|
||||
|
||||
it("Überschreiben sichert die Vorversion als ~", () => {
|
||||
const p = join(tmp(), "a.obp");
|
||||
writeAtomic(p, "eins", true);
|
||||
writeAtomic(p, "zwei äöü", true);
|
||||
expect(readFileSync(p, "utf8")).toBe("zwei äöü");
|
||||
expect(readFileSync(`${p}~`, "utf8")).toBe("eins");
|
||||
expect(backupExists(p)).toBe(true);
|
||||
});
|
||||
|
||||
it("Fehler lässt das Original heil und räumt die Temp-Datei auf", () => {
|
||||
const d = tmp();
|
||||
const p = join(d, "a.obp");
|
||||
writeAtomic(p, "original", true);
|
||||
mkdirSync(`${p}.tmp`); // Ordner an der Stelle der Temp-Datei
|
||||
expect(() => writeAtomic(p, "neu", true)).toThrow();
|
||||
expect(readFileSync(p, "utf8")).toBe("original");
|
||||
expect(() => writeAtomic(join(d, "nope", "b.obp"), "x", true)).toThrow();
|
||||
});
|
||||
|
||||
it("liegengebliebene Temp-Datei eines Absturzes stört nicht", () => {
|
||||
const p = join(tmp(), "a.obp");
|
||||
writeAtomic(p, "alt", true);
|
||||
writeFileSync(`${p}.tmp`, '{"walls": [');
|
||||
writeAtomic(p, "neu", true);
|
||||
expect(readFileSync(p, "utf8")).toBe("neu");
|
||||
expect(existsSync(`${p}.tmp`)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
// Sicherung der Vorversion (`<pfad>~`, [116]): erkennen/lesen unter Tauri und Electron; Electron speichert atomar über den Hauptprozess.
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
type Invoke = (cmd: string, args?: Record<string, unknown>) => Promise<unknown>;
|
||||
|
||||
async function withTauri(invoke: Invoke) {
|
||||
vi.resetModules();
|
||||
vi.stubGlobal("window", { __TAURI_INTERNALS__: {} });
|
||||
vi.doMock("@tauri-apps/api/core", () => ({ invoke }));
|
||||
vi.doMock("@tauri-apps/plugin-dialog", () => ({ save: async () => "/tmp/a.obp" }));
|
||||
return import("./projectFile");
|
||||
}
|
||||
|
||||
describe("Sicherung unter Tauri", () => {
|
||||
it("backupAvailable / readBackupText fragen die Rust-Befehle", async () => {
|
||||
const calls: [string, unknown][] = [];
|
||||
const m = await withTauri(async (cmd, args) => {
|
||||
calls.push([cmd, args]);
|
||||
return cmd === "backup_exists" ? true : "{\"alt\":1}";
|
||||
});
|
||||
expect(await m.backupAvailable("/tmp/a.obp")).toBe(true);
|
||||
expect(await m.readBackupText("/tmp/a.obp")).toBe("{\"alt\":1}");
|
||||
expect(calls.map((c) => c[0])).toEqual(["backup_exists", "read_backup"]);
|
||||
});
|
||||
|
||||
it("Fehler der Befehle: keine Sicherung statt Absturz", async () => {
|
||||
const m = await withTauri(async () => {
|
||||
throw "kaputt";
|
||||
});
|
||||
expect(await m.backupAvailable("/tmp/a.obp")).toBe(false);
|
||||
expect(await m.readBackupText("/tmp/a.obp")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ohne Dateisystem (Browser)", () => {
|
||||
it("keine Sicherung", async () => {
|
||||
vi.stubGlobal("window", {});
|
||||
const m = await import("./projectFile");
|
||||
expect(await m.backupAvailable("/x.obp")).toBe(false);
|
||||
expect(await m.readBackupText("/x.obp")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Electron: Projekt-Speichern über den Hauptprozess", () => {
|
||||
function withElectron(files: Record<string, unknown>) {
|
||||
vi.resetModules();
|
||||
vi.stubGlobal("window", { dossierFiles: files });
|
||||
return import("./projectFile");
|
||||
}
|
||||
|
||||
it("bekannter Pfad: saveAtomic ohne Dialog, Pfad-Callback danach", async () => {
|
||||
const calls: unknown[][] = [];
|
||||
const m = await withElectron({ saveAtomic: async (...a: unknown[]) => void calls.push(a) });
|
||||
const saved: string[] = [];
|
||||
expect(await m.saveProjectFile("{}", "x", (p) => saved.push(p), "/home/u/a.obp")).toBe(true);
|
||||
expect(calls).toEqual([["/home/u/a.obp", "{}"]]);
|
||||
expect(saved).toEqual(["/home/u/a.obp"]);
|
||||
});
|
||||
|
||||
it("ohne Pfad: Speichern-Dialog im Hauptprozess; Abbruch = false", async () => {
|
||||
const m = await withElectron({ saveAs: async () => null });
|
||||
expect(await m.saveProjectFile("{}", "x")).toBe(false);
|
||||
const m2 = await withElectron({ saveAs: async (name: string) => `/home/u/${name}` });
|
||||
const saved: string[] = [];
|
||||
expect(await m2.saveProjectFile("{}", "haus", (p) => saved.push(p))).toBe(true);
|
||||
expect(saved).toEqual(["/home/u/haus.obp"]);
|
||||
});
|
||||
|
||||
it("Fehler: SaveError, kein Download", async () => {
|
||||
const m = await withElectron({
|
||||
saveAtomic: async () => {
|
||||
throw new Error("EACCES");
|
||||
},
|
||||
});
|
||||
const { SaveError } = await import("./saveFile");
|
||||
await expect(m.saveProjectFile("{}", "x", undefined, "/ro/a.obp")).rejects.toBeInstanceOf(SaveError);
|
||||
});
|
||||
|
||||
it("backupAvailable / readBackupText über die Brücke", async () => {
|
||||
const m = await withElectron({ backupExists: async () => true, readBackup: async () => "text" });
|
||||
expect(await m.backupAvailable("/a.obp")).toBe(true);
|
||||
expect(await m.readBackupText("/a.obp")).toBe("text");
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,7 @@
|
||||
// normalen Schliessen. Nur unter Tauri relevant: im reinen Browser gibt es
|
||||
// keinen echten Dateipfad (Blob-Download), daher entfällt der Lock dort.
|
||||
|
||||
import { saveTextFile } from "./saveFile";
|
||||
import { saveTextFile, SaveError } from "./saveFile";
|
||||
|
||||
/** Datei-Endung für Projektdateien (ohne Punkt). Einzige Änderungsstelle. */
|
||||
export const PROJECT_EXT = "obp";
|
||||
@@ -39,6 +39,57 @@ export function isTauriRuntime(): boolean {
|
||||
return typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
|
||||
}
|
||||
|
||||
/** Brücke des Electron-Hauptprozesses für Projektdateien ([116], `scripts/electron-files.cjs`, `electron-preload.cjs`). */
|
||||
export interface DossierFiles {
|
||||
saveAtomic: (path: string, text: string) => Promise<boolean>;
|
||||
/** Speichern-Dialog + atomar schreiben; `null` = abgebrochen. */
|
||||
saveAs: (defaultName: string, text: string, filters?: { name: string; extensions: string[] }[]) => Promise<string | null>;
|
||||
backupExists: (path: string) => Promise<boolean>;
|
||||
readBackup: (path: string) => Promise<string | null>;
|
||||
/** Pfad einer vom Nutzer gewählten Datei (Electron), sonst `null`. */
|
||||
pathForFile: (file: File) => string | null;
|
||||
}
|
||||
declare global {
|
||||
interface Window {
|
||||
dossierFiles?: DossierFiles;
|
||||
}
|
||||
}
|
||||
|
||||
/** Electron-Dateibrücke, falls vorhanden. */
|
||||
export function electronFiles(): DossierFiles | null {
|
||||
return typeof window !== "undefined" && window.dossierFiles ? window.dossierFiles : null;
|
||||
}
|
||||
|
||||
const errMsg = (err: unknown): string => (err instanceof Error ? err.message : String(err));
|
||||
|
||||
/** Gibt es zur Projektdatei `path` eine Sicherung der Vorversion (`<path>~`)? Ohne Dateisystem (Browser) immer `false`. */
|
||||
export async function backupAvailable(path: string): Promise<boolean> {
|
||||
try {
|
||||
if (isTauriRuntime()) {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
return (await invoke("backup_exists", { path })) === true;
|
||||
}
|
||||
return (await electronFiles()?.backupExists(path)) === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Inhalt der Sicherung `<path>~`; `null`, wenn es keine gibt (oder ohne Dateisystem). */
|
||||
export async function readBackupText(path: string): Promise<string | null> {
|
||||
try {
|
||||
if (isTauriRuntime()) {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
const text = await invoke("read_backup", { path });
|
||||
return typeof text === "string" ? text : null;
|
||||
}
|
||||
const text = await electronFiles()?.readBackup(path);
|
||||
return typeof text === "string" ? text : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Ergebnis eines erfolgreichen nativen Öffnen-Vorgangs. */
|
||||
export interface OpenedProjectFile {
|
||||
path: string;
|
||||
@@ -134,6 +185,18 @@ export async function saveProjectFile(
|
||||
return true;
|
||||
}
|
||||
const filename = `${projectName || "projekt"}.${PROJECT_EXT}`;
|
||||
// Electron ([116]): atomar über den Hauptprozess (Temp + Umbenennen, Vorversion als `~`); ohne bekannten Pfad Dialog dort.
|
||||
const ef = electronFiles();
|
||||
if (ef && !isTauriRuntime()) {
|
||||
try {
|
||||
const path = knownPath ? ((await ef.saveAtomic(knownPath, json)), knownPath) : await ef.saveAs(filename, json, PROJECT_DIALOG_FILTERS);
|
||||
if (!path) return false; // Dialog abgebrochen
|
||||
onSavedPath?.(path);
|
||||
return true;
|
||||
} catch (err) {
|
||||
throw new SaveError(errMsg(err));
|
||||
}
|
||||
}
|
||||
return saveTextFile(json, filename, "application/json", PROJECT_DIALOG_FILTERS, onSavedPath, true);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// Exporte unter Tauri atomar schreiben ([116]): Rust-Befehl `save_export`, Fehler werden gemeldet, nie stiller Download.
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
type Invoke = (cmd: string, args?: unknown, opts?: unknown) => Promise<unknown>;
|
||||
|
||||
async function withTauri(invoke: Invoke) {
|
||||
vi.resetModules();
|
||||
vi.stubGlobal("window", { __TAURI_INTERNALS__: {} });
|
||||
vi.doMock("@tauri-apps/plugin-dialog", () => ({ save: async () => "/tmp/Pläne/a b.pdf" }));
|
||||
vi.doMock("@tauri-apps/api/core", () => ({ invoke }));
|
||||
return import("./saveFile");
|
||||
}
|
||||
|
||||
describe("Exporte schreiben atomar ([116])", () => {
|
||||
it("saveBinaryFile: Bytes als Rohkörper, Pfad prozent-kodiert im Header", async () => {
|
||||
const calls: unknown[][] = [];
|
||||
const m = await withTauri(async (cmd, args, opts) => void calls.push([cmd, args, opts]));
|
||||
const bytes = new Uint8Array([1, 2, 3]);
|
||||
expect(await m.saveBinaryFile(bytes, "a.pdf")).toBe(true);
|
||||
expect(calls).toEqual([["save_export", bytes, { headers: { "x-path": "%2Ftmp%2FPl%C3%A4ne%2Fa%20b.pdf" } }]]);
|
||||
});
|
||||
|
||||
it("saveTextFile (kein Projekt): Text als UTF-8-Bytes über save_export", async () => {
|
||||
const calls: [string, Uint8Array][] = [];
|
||||
const m = await withTauri(async (cmd, args) => void calls.push([cmd, args as Uint8Array]));
|
||||
expect(await m.saveTextFile("äö", "a.dxf")).toBe(true);
|
||||
expect(calls[0][0]).toBe("save_export");
|
||||
expect(new TextDecoder().decode(calls[0][1])).toBe("äö");
|
||||
});
|
||||
|
||||
it("Schreibfehler: gemeldet, false, kein Download-Fallback", async () => {
|
||||
const m = await withTauri(async () => {
|
||||
throw "Umbenennen: Permission denied";
|
||||
});
|
||||
const reported: string[] = [];
|
||||
m.setExportErrorReporter((msg) => reported.push(msg));
|
||||
const createObjectURL = vi.fn();
|
||||
vi.stubGlobal("URL", { createObjectURL });
|
||||
expect(await m.saveBinaryFile(new Uint8Array([1]), "a.pdf")).toBe(false);
|
||||
expect(reported).toEqual(["Umbenennen: Permission denied"]);
|
||||
expect(createObjectURL).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("OBJ + MTL: beide Dateien atomar", async () => {
|
||||
const calls: string[] = [];
|
||||
const m = await withTauri(async (cmd) => void calls.push(cmd));
|
||||
const ok = await m.saveTextWithCompanion((n) => ({ main: `mtllib ${n}`, companion: "m" }), "a.obj", "mtl");
|
||||
expect(ok).toBe(true);
|
||||
expect(calls).toEqual(["save_export", "save_export"]);
|
||||
});
|
||||
});
|
||||
+48
-10
@@ -32,6 +32,30 @@ export async function writeFileAtomic(path: string, content: string): Promise<vo
|
||||
}
|
||||
}
|
||||
|
||||
/** Export atomar schreiben ([116]): Rust-Befehl `save_export` (Temp-Datei + fsync + Umbenennen, keine `~`-Sicherung);
|
||||
* Bytes als Rohkörper, der Pfad prozent-kodiert im Header. Wirft {@link SaveError}. */
|
||||
async function writeExportAtomic(path: string, bytes: Uint8Array): Promise<void> {
|
||||
try {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
await invoke("save_export", bytes, { headers: { "x-path": encodeURIComponent(path) } });
|
||||
} catch (err) {
|
||||
throw new SaveError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
|
||||
let exportErrorReporter: ((message: string) => void) | null = null;
|
||||
|
||||
/** Meldet gescheiterte Export-Schreibvorgänge (die App hängt `notify` ein); ohne Melder: Konsole. */
|
||||
export function setExportErrorReporter(fn: ((message: string) => void) | null): void {
|
||||
exportErrorReporter = fn;
|
||||
}
|
||||
|
||||
function reportExportError(err: unknown): void {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
console.error("Export schreiben fehlgeschlagen:", err);
|
||||
exportErrorReporter?.(msg);
|
||||
}
|
||||
|
||||
/** Datei-Endungsfilter fuer den nativen Speichern-/Oeffnen-Dialog (Tauri). */
|
||||
export interface FileDialogFilter {
|
||||
name: string;
|
||||
@@ -40,7 +64,7 @@ export interface FileDialogFilter {
|
||||
|
||||
/**
|
||||
* Speichert Text-Inhalt in eine Datei.
|
||||
* - Unter Tauri: nativer Save-Dialog (Ordner + Name) → `writeTextFile`.
|
||||
* - Unter Tauri: nativer Save-Dialog (Ordner + Name) → atomar schreiben (`save_export`, [116]); Fehler → Melder, kein Download.
|
||||
* - Im Browser: Blob + Anchor-Download in den Download-Ordner.
|
||||
*
|
||||
* @param filters Optionale Datei-Endungsfilter fuer den nativen Dialog (z. B.
|
||||
@@ -70,8 +94,13 @@ export async function saveTextFile(
|
||||
if (!path) return false; // Nutzer hat abgebrochen
|
||||
if (atomic) await writeFileAtomic(path, content);
|
||||
else {
|
||||
const { writeTextFile } = await import("@tauri-apps/plugin-fs");
|
||||
await writeTextFile(path, content);
|
||||
// Export ([116]): atomar; bei Fehler melden, nie als Download ausgeben, das Ziel bleibt heil.
|
||||
try {
|
||||
await writeExportAtomic(path, new TextEncoder().encode(content));
|
||||
} catch (err) {
|
||||
reportExportError(err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
onSavedPath?.(path);
|
||||
return true;
|
||||
@@ -96,7 +125,7 @@ export async function saveTextFile(
|
||||
* Speichert Binaer-Inhalt (z. B. ein PDF) in eine Datei — gleiches Tauri-/
|
||||
* Browser-Muster wie {@link saveTextFile}, nur mit `writeFile` (Bytes) statt
|
||||
* `writeTextFile`.
|
||||
* - Unter Tauri: nativer Save-Dialog → `writeFile(path, bytes)`.
|
||||
* - Unter Tauri: nativer Save-Dialog → atomar schreiben (`save_export`, [116]).
|
||||
* - Im Browser: Blob + Anchor-Download.
|
||||
*
|
||||
* @returns `true` wenn geschrieben/geladen wurde, `false` bei Abbruch.
|
||||
@@ -111,8 +140,12 @@ export async function saveBinaryFile(
|
||||
const { save } = await import("@tauri-apps/plugin-dialog");
|
||||
const path = await save({ defaultPath: defaultName });
|
||||
if (!path) return false; // Nutzer hat abgebrochen
|
||||
const { writeFile } = await import("@tauri-apps/plugin-fs");
|
||||
await writeFile(path, bytes);
|
||||
try {
|
||||
await writeExportAtomic(path, bytes);
|
||||
} catch (err) {
|
||||
reportExportError(err);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (!warnedFallback) {
|
||||
@@ -176,14 +209,19 @@ export async function saveTextWithCompanion(
|
||||
if (isTauri()) {
|
||||
try {
|
||||
const { save } = await import("@tauri-apps/plugin-dialog");
|
||||
const { writeTextFile } = await import("@tauri-apps/plugin-fs");
|
||||
const enc = new TextEncoder();
|
||||
const path = await save({ defaultPath: defaultName, filters });
|
||||
if (!path) return false;
|
||||
const companionName = `${stemOf(path)}.${companionExt}`;
|
||||
const files = build(companionName);
|
||||
await writeTextFile(path, files.main);
|
||||
const companionPath = await save({ defaultPath: path.replace(/[^\\/]*$/, companionName), filters: companionFilters });
|
||||
if (companionPath) await writeTextFile(companionPath, files.companion);
|
||||
try {
|
||||
await writeExportAtomic(path, enc.encode(files.main));
|
||||
const companionPath = await save({ defaultPath: path.replace(/[^\\/]*$/, companionName), filters: companionFilters });
|
||||
if (companionPath) await writeExportAtomic(companionPath, enc.encode(files.companion));
|
||||
} catch (err) {
|
||||
reportExportError(err);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (!warnedFallback) {
|
||||
|
||||
Reference in new issue
Block a user