[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
+2
-1
@@ -394,7 +394,7 @@ export default function App() {
|
||||
planViewRef,
|
||||
);
|
||||
const {
|
||||
projectFileInputRef, projectTemplateFileInputRef, openImportForFile, onSaveProject, onSaveProjectAs,
|
||||
projectFileInputRef, projectTemplateFileInputRef, openImportForFile, onSaveProject, onSaveProjectAs, onRestoreBackup,
|
||||
onNewProject, onNewProjectFromSample, onNewProjectFromComplexSample, onNewProjectFromWettbewerbSample, onNewProjectFromTemplate,
|
||||
onProjectTemplateFileChosen, onExportIfc, onExportObj, onExportStl, onOpenProject, onProjectFileChosen,
|
||||
} = files;
|
||||
@@ -705,6 +705,7 @@ export default function App() {
|
||||
onOpenProject,
|
||||
onSaveProject,
|
||||
onSaveProjectAs,
|
||||
onRestoreBackup,
|
||||
onImport: () => dxfInputRef.current?.click(),
|
||||
onImportPointCloud: () => openPointCloudFileDialog(),
|
||||
onImportMesh: () => openMeshFileDialog(),
|
||||
|
||||
@@ -3042,6 +3042,15 @@ export const de = {
|
||||
"core.restarted": "Interner Fehler im Kern – der Vorgang wurde abgebrochen, Projekt und Rückgängig-Verlauf sind wiederhergestellt.",
|
||||
"core.restartedHistoryLost": "Interner Fehler im Kern – der Vorgang wurde abgebrochen, das Projekt ist wiederhergestellt. Der Rückgängig-Verlauf liess sich nicht wiederherstellen und wurde geleert.",
|
||||
"project.save.failed": "Projekt konnte nicht gespeichert werden; die Datei und die Wiederherstellungskopie bleiben unverändert.",
|
||||
"menu.native.restoreBackup": "Vorige Fassung wiederherstellen …",
|
||||
"backup.none": "Es gibt keine vorige Fassung (.obp~) zu dieser Datei.",
|
||||
"backup.damaged": "Die vorige Fassung (.obp~) ist beschädigt und lässt sich nicht öffnen.",
|
||||
"backup.restored": "Vorige Fassung geöffnet. Sie ersetzt die Datei erst beim Speichern; die jetzige Fassung wird dann zur Sicherung (.obp~).",
|
||||
"backup.offer.title": "Vorige Fassung öffnen?",
|
||||
"backup.offer.message": "„{name}“ lässt sich nicht laden ({error}). Beim letzten Speichern wurde aber die vorige Fassung gesichert (.obp~). Diese öffnen?",
|
||||
"backup.offer.accept": "Vorige Fassung (.obp~) öffnen",
|
||||
"backup.offer.cancel": "Abbrechen",
|
||||
"export.save.failed": "Export konnte nicht geschrieben werden; eine vorhandene Zieldatei bleibt unverändert.",
|
||||
"menu.native.clashCheck": "Kollisionsprüfung …",
|
||||
"menu.native.kennzahlen": "Kennzahlen und Raumprogramm …",
|
||||
"kennzahlen.summary": "GF {gf} m² · aGF {agf} m² · GV {gv} m³",
|
||||
|
||||
@@ -2990,6 +2990,15 @@ export const en: Record<TranslationKey, string> = {
|
||||
"core.restarted": "Internal error in the core – the operation was aborted; the project and the undo history have been restored.",
|
||||
"core.restartedHistoryLost": "Internal error in the core – the operation was aborted and the project has been restored. The undo history could not be restored and was cleared.",
|
||||
"project.save.failed": "Project could not be saved; the file and the recovery copy are unchanged.",
|
||||
"menu.native.restoreBackup": "Restore Previous Version…",
|
||||
"backup.none": "There is no previous version (.obp~) of this file.",
|
||||
"backup.damaged": "The previous version (.obp~) is damaged and cannot be opened.",
|
||||
"backup.restored": "Previous version opened. It replaces the file only when you save; the current version then becomes the backup (.obp~).",
|
||||
"backup.offer.title": "Open previous version?",
|
||||
"backup.offer.message": "\"{name}\" cannot be loaded ({error}). The previous version was saved as a backup (.obp~) at the last save. Open it instead?",
|
||||
"backup.offer.accept": "Open previous version (.obp~)",
|
||||
"backup.offer.cancel": "Cancel",
|
||||
"export.save.failed": "The export could not be written; an existing target file is unchanged.",
|
||||
"menu.native.clashCheck": "Clash detection …",
|
||||
"menu.native.kennzahlen": "Key figures and room programme …",
|
||||
"kennzahlen.summary": "GFA {gf} m² · usable {agf} m² · volume {gv} m³",
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -93,6 +93,7 @@ export function useNativeMenu(opts: {
|
||||
onOpenProject,
|
||||
onSaveProject,
|
||||
onSaveProjectAs,
|
||||
onRestoreBackup,
|
||||
onExportSchedule,
|
||||
onExportIfc,
|
||||
onExportObj,
|
||||
@@ -122,6 +123,7 @@ export function useNativeMenu(opts: {
|
||||
onOpenProject,
|
||||
onSaveProject,
|
||||
onSaveProjectAs,
|
||||
onRestoreBackup,
|
||||
onImport: () => dxfInputRef.current?.click(),
|
||||
onExportPdf: () => setExportOpen(true),
|
||||
onExportDxf: () => setExportDxfOpen(true),
|
||||
|
||||
@@ -30,7 +30,7 @@ import { loadFileio } from "../engine/fileioWasm";
|
||||
import { exportProjectStep } from "../export/exportStep";
|
||||
import { exportGlb, exportMtl, exportObj, exportStl } from "../export/exportMesh";
|
||||
import type { ExportSaveFormat } from "../ui/ExportSaveDialog";
|
||||
import { saveBinaryFile, saveTextFile, saveTextWithCompanion } from "../native/saveFile";
|
||||
import { saveBinaryFile, saveTextFile, saveTextWithCompanion, setExportErrorReporter } from "../native/saveFile";
|
||||
import {
|
||||
saveProjectFile,
|
||||
openProjectFileNative,
|
||||
@@ -41,6 +41,8 @@ import {
|
||||
registerCloseGuard,
|
||||
quitApp,
|
||||
isTauriRuntime,
|
||||
electronFiles,
|
||||
readBackupText,
|
||||
} from "../native/projectFile";
|
||||
import type { LockInfo } from "../native/projectFile";
|
||||
import { addRecentProject, removeRecentProject } from "./recentProjects";
|
||||
@@ -70,6 +72,8 @@ export type ImportDialogState = {
|
||||
/** Von electron-preload.cjs injiziert (nur Electron/Linux, [170]): Projektdatei aus `dossier datei.obp`. */
|
||||
interface LaunchProject {
|
||||
name: string;
|
||||
/** Voller Pfad der Datei ([116]): Speichern schreibt dann atomar dorthin. */
|
||||
path?: string;
|
||||
text: string;
|
||||
}
|
||||
declare global {
|
||||
@@ -99,6 +103,15 @@ function openProjectOrReport(content: string, notify: (msg: string, kind?: Notif
|
||||
return r.project;
|
||||
}
|
||||
|
||||
/** Angebot „Vorige Fassung (.obp~) öffnen" ([116]): die Datei liess sich nicht laden, die Sicherung schon. */
|
||||
export interface BackupOffer {
|
||||
path: string;
|
||||
text: string;
|
||||
/** Fehlermeldung beim Laden der eigentlichen Datei. */
|
||||
error: string;
|
||||
lockOwned: boolean;
|
||||
}
|
||||
|
||||
export function useProjectFileActions(
|
||||
setImportState: (next: ImportDialogState) => void,
|
||||
setExportSaveFormat: (format: ExportSaveFormat | null) => void,
|
||||
@@ -143,6 +156,12 @@ export function useProjectFileActions(
|
||||
// Eine verworfene Aktion (Neu/Öffnen), die erst nach Bestätigung des
|
||||
// "Ungespeicherte Änderungen"-Dialogs ausgeführt wird — s. `guardDiscard`.
|
||||
const [pendingDiscard, setPendingDiscard] = useState<(() => void) | null>(null);
|
||||
const [backupOffer, setBackupOffer] = useState<BackupOffer | null>(null);
|
||||
// Gescheiterte Export-Schreibvorgänge ([116], native/saveFile.ts) als Meldung statt stiller Konsole.
|
||||
useEffect(() => {
|
||||
setExportErrorReporter((msg) => notify(`${t("export.save.failed")} ${msg}`, "error"));
|
||||
return () => setExportErrorReporter(null);
|
||||
}, []);
|
||||
/**
|
||||
* Führt `action` (Projekt ERSETZEN — Neu/Öffnen) nur direkt aus, wenn seit
|
||||
* dem letzten Speichern/Laden nichts geändert wurde; sonst wird sie als
|
||||
@@ -539,6 +558,59 @@ export function useProjectFileActions(
|
||||
r.readAsText(file);
|
||||
};
|
||||
|
||||
// Öffnet `content`; lässt sich die Datei nicht laden, aber ihre Sicherung `<pfad>~` ([116]), bietet ein Overlay-Dialog die
|
||||
// vorige Fassung an (der Lock bleibt bis zur Antwort), sonst wird der Fehler gemeldet. `null` = nicht geladen.
|
||||
const openOrOfferBackup = (content: string, path: string | null, lockOwned: boolean): Project | null => {
|
||||
const r = getState().openProjectFile(content);
|
||||
if (r.ok) {
|
||||
for (const w of r.warnings) console.info(`Projekt geladen mit Hinweis: ${w}`);
|
||||
return r.project;
|
||||
}
|
||||
const fail = () => {
|
||||
notify(`${t("project.open.failed")} ${r.error}`, "error");
|
||||
if (path && lockOwned) void releaseProjectLock(path);
|
||||
};
|
||||
if (!path) fail();
|
||||
else
|
||||
void readBackupText(path).then((text) => {
|
||||
if (text && parseProjectFile(text).ok) setBackupOffer({ path, text, error: r.error, lockOwned });
|
||||
else fail();
|
||||
});
|
||||
return null;
|
||||
};
|
||||
const onBackupOfferAccept = () => {
|
||||
if (!backupOffer) return;
|
||||
const { path, text, lockOwned } = backupOffer;
|
||||
setBackupOffer(null);
|
||||
applyOpenedProjectFile(path, text, lockOwned, true);
|
||||
};
|
||||
const onBackupOfferCancel = () => {
|
||||
if (backupOffer?.lockOwned) void releaseProjectLock(backupOffer.path);
|
||||
setBackupOffer(null);
|
||||
};
|
||||
// Datei-Menü „Vorige Fassung wiederherstellen …": die Sicherung der aktuellen Datei (`<pfad>~`) wird zum offenen
|
||||
// Projekt, die Datei selbst bleibt bis zum nächsten Speichern unverändert (dann wird die jetzige Fassung zur Sicherung).
|
||||
const onRestoreBackup = () => {
|
||||
const path = savePathRef.current;
|
||||
if (!path) {
|
||||
notify(t("backup.none"), "info");
|
||||
return;
|
||||
}
|
||||
void readBackupText(path).then((text) => {
|
||||
if (!text) {
|
||||
notify(t("backup.none"), "info");
|
||||
return;
|
||||
}
|
||||
if (!parseProjectFile(text).ok) {
|
||||
notify(t("backup.damaged"), "error");
|
||||
return;
|
||||
}
|
||||
guardDiscard(() => {
|
||||
if (openProjectOrReport(text, notify)) notify(t("backup.restored"), "info");
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Gibt den Lock der zuletzt geöffneten Projektdatei frei (falls wir ihn
|
||||
// halten) und vergisst den Pfad — vor dem Wechsel auf ein anderes Projekt.
|
||||
const releaseCurrentProjectLock = () => {
|
||||
@@ -553,15 +625,13 @@ export function useProjectFileActions(
|
||||
// Übernimmt ein per Pfad geöffnetes Projekt (Tauri-Fluss): parst, prüft grob
|
||||
// die Form, gibt einen evtl. vorher gehaltenen Lock frei und merkt sich Pfad
|
||||
// + ob WIR den Schreib-Lock für die neue Datei halten.
|
||||
const applyOpenedProjectFile = (path: string, content: string, lockOwned: boolean) => {
|
||||
const applyOpenedProjectFile = (path: string, content: string, lockOwned: boolean, fromBackup = false) => {
|
||||
guardDiscard(() => {
|
||||
const loaded = openProjectOrReport(content, notify);
|
||||
if (!loaded) {
|
||||
if (lockOwned) void releaseProjectLock(path);
|
||||
return;
|
||||
}
|
||||
const loaded = openOrOfferBackup(content, path, lockOwned);
|
||||
if (!loaded) return;
|
||||
releaseCurrentProjectLock();
|
||||
lastSavedProjectRef.current = loaded;
|
||||
// Aus der Sicherung: bleibt „ungespeichert", bis der Nutzer die Datei bewusst überschreibt.
|
||||
if (!fromBackup) lastSavedProjectRef.current = loaded;
|
||||
openedProjectPathRef.current = path;
|
||||
savePathRef.current = path;
|
||||
setAnonymityProjectFileName(path);
|
||||
@@ -689,18 +759,21 @@ export function useProjectFileActions(
|
||||
}
|
||||
};
|
||||
|
||||
const onProjectFileChosen = (file: File) => {
|
||||
const onProjectFileChosen = (file: File, knownPath?: string | null) => {
|
||||
const r = new FileReader();
|
||||
r.onload = () => {
|
||||
const content = String(r.result ?? "");
|
||||
// Electron ([116]): der Pfad der gewählten Datei erlaubt atomares Speichern und die Sicherung `.obp~`; im Browser gibt es keinen.
|
||||
const path = knownPath ?? electronFiles()?.pathForFile(file) ?? null;
|
||||
// Browser-Pfad hat keinen echten Dateipfad → kein Lock für die neue
|
||||
// Datei, aber ein evtl. vorher (unter Tauri) gehaltener Lock wird frei.
|
||||
guardDiscard(() => {
|
||||
const loaded = openProjectOrReport(content, notify);
|
||||
const loaded = openOrOfferBackup(content, path, false);
|
||||
if (!loaded) return;
|
||||
releaseCurrentProjectLock();
|
||||
lastSavedProjectRef.current = loaded;
|
||||
setAnonymityProjectFileName(file.name); // [208] Browser/Electron-Start: kein Pfad, aber der Dateiname
|
||||
if (path) savePathRef.current = path;
|
||||
setAnonymityProjectFileName(path ?? file.name); // [208] Browser/Electron-Start: kein Pfad, aber der Dateiname
|
||||
});
|
||||
};
|
||||
r.onerror = () => notify(`${t("project.open.failed")} ${r.error?.message ?? ""}`, "error");
|
||||
@@ -714,7 +787,7 @@ export function useProjectFileActions(
|
||||
useEffect(() => {
|
||||
const api = window.dossierLaunch;
|
||||
if (!api) return;
|
||||
const open = (f: LaunchProject) => chosenRef.current(new File([f.text], f.name));
|
||||
const open = (f: LaunchProject) => chosenRef.current(new File([f.text], f.name), f.path);
|
||||
void api.takeOpenFile().then((f) => f && open(f));
|
||||
return api.onOpenFile(open);
|
||||
}, []);
|
||||
@@ -774,6 +847,10 @@ export function useProjectFileActions(
|
||||
projectLockOwnedRef,
|
||||
lockConflict,
|
||||
setLockConflict,
|
||||
backupOffer,
|
||||
onBackupOfferAccept,
|
||||
onBackupOfferCancel,
|
||||
onRestoreBackup,
|
||||
recovery,
|
||||
onRecoverRestore,
|
||||
onRecoverDiscard,
|
||||
|
||||
@@ -35,6 +35,7 @@ import { ImageExportDialogHost } from "./ImageExportDialog";
|
||||
import { ShortcutOverviewDialogHost } from "./ShortcutOverviewDialog";
|
||||
import { PromptDialog } from "./PromptDialog";
|
||||
import { RecoverAutosaveDialog } from "./RecoverAutosaveDialog";
|
||||
import { BackupOfferDialog } from "./BackupOfferDialog";
|
||||
import { ResourceManager, type ResourceManagerHandlers } from "./ResourceManager";
|
||||
import { SettingsDialog } from "./SettingsDialog";
|
||||
import { UnsavedChangesDialog } from "./UnsavedChangesDialog";
|
||||
@@ -113,6 +114,9 @@ export function AppDialogs(props: {
|
||||
onRecoverLater,
|
||||
lockConflict,
|
||||
setLockConflict,
|
||||
backupOffer,
|
||||
onBackupOfferAccept,
|
||||
onBackupOfferCancel,
|
||||
pendingDiscard,
|
||||
setPendingDiscard,
|
||||
loadImportLayout,
|
||||
@@ -263,6 +267,14 @@ export function AppDialogs(props: {
|
||||
onLater={onRecoverLater}
|
||||
/>
|
||||
)}
|
||||
{backupOffer && (
|
||||
<BackupOfferDialog
|
||||
path={backupOffer.path}
|
||||
error={backupOffer.error}
|
||||
onAccept={onBackupOfferAccept}
|
||||
onCancel={onBackupOfferCancel}
|
||||
/>
|
||||
)}
|
||||
{lockConflict && (
|
||||
<LockConflictDialog
|
||||
info={lockConflict.info}
|
||||
|
||||
@@ -25,6 +25,8 @@ export interface AppMenuBarProps {
|
||||
onOpenProject: () => void;
|
||||
onSaveProject: () => void;
|
||||
onSaveProjectAs: () => void;
|
||||
/** Datei: vorige Fassung (.obp~) der aktuellen Datei wiederherstellen ([116]). */
|
||||
onRestoreBackup: () => void;
|
||||
onImport: () => void;
|
||||
/** Datei: Punktwolke importieren ([27]). */
|
||||
onImportPointCloud?: () => void;
|
||||
@@ -72,6 +74,7 @@ export const AppMenuBar = memo(function AppMenuBar({
|
||||
onOpenProject,
|
||||
onSaveProject,
|
||||
onSaveProjectAs,
|
||||
onRestoreBackup,
|
||||
onImport,
|
||||
onImportPointCloud,
|
||||
onImportMesh,
|
||||
@@ -107,6 +110,7 @@ export const AppMenuBar = memo(function AppMenuBar({
|
||||
{ label: t("file.open"), onSelect: onOpenProject },
|
||||
{ label: t("file.save"), onSelect: onSaveProject },
|
||||
{ label: t("menu.native.saveAs"), onSelect: onSaveProjectAs },
|
||||
{ label: t("menu.native.restoreBackup"), onSelect: onRestoreBackup },
|
||||
{ divider: true },
|
||||
{ label: t("file.import"), onSelect: onImport },
|
||||
...(onImportPointCloud ? [{ label: t("menu.native.importPointCloud"), onSelect: onImportPointCloud }] : []),
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Angebot „Vorige Fassung (.obp~) öffnen" ([116]): die gewählte Projektdatei liess sich nicht laden, ihre Sicherung
|
||||
// aus dem vorletzten Speichern schon. Overlay-Dialog wie `RecoverAutosaveDialog` (kein `window.confirm`).
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { t } from "../i18n";
|
||||
import { useModalFocus } from "./modalFocus";
|
||||
|
||||
export interface BackupOfferDialogProps {
|
||||
/** Pfad der Projektdatei, die sich nicht laden liess. */
|
||||
path: string;
|
||||
/** Fehlermeldung beim Laden. */
|
||||
error: string;
|
||||
onAccept: () => void;
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
export function BackupOfferDialog({ path, error, onAccept, onCancel }: BackupOfferDialogProps) {
|
||||
const dialogRef = useModalFocus({});
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onCancel();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onCancel]);
|
||||
|
||||
const name = path.split(/[\\/]/).pop() ?? path;
|
||||
|
||||
return (
|
||||
<div className="imp-overlay recover-overlay" onClick={onCancel}>
|
||||
<div
|
||||
className="imp-dialog"
|
||||
ref={dialogRef}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t("backup.offer.title")}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<header className="imp-head">
|
||||
<span className="imp-head-title">{t("backup.offer.title")}</span>
|
||||
<button className="imp-close" onClick={onCancel} aria-label={t("export.close")}>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
<div className="imp-body">
|
||||
<section className="imp-section">
|
||||
<div className="imp-section-title">{t("backup.offer.message", { name, error })}</div>
|
||||
</section>
|
||||
</div>
|
||||
<footer className="imp-foot">
|
||||
<button className="imp-btn" onClick={onCancel}>
|
||||
{t("backup.offer.cancel")}
|
||||
</button>
|
||||
<button className="imp-btn primary" onClick={onAccept}>
|
||||
{t("backup.offer.accept")}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -33,6 +33,7 @@ export type TopBarEvents = Required<
|
||||
| "onOpenProject"
|
||||
| "onSaveProject"
|
||||
| "onSaveProjectAs"
|
||||
| "onRestoreBackup"
|
||||
| "onImport"
|
||||
| "onImportPointCloud"
|
||||
| "onImportMesh"
|
||||
@@ -134,6 +135,7 @@ export function useTopBarElements(opts: {
|
||||
onOpenProject={ev.onOpenProject}
|
||||
onSaveProject={ev.onSaveProject}
|
||||
onSaveProjectAs={ev.onSaveProjectAs}
|
||||
onRestoreBackup={ev.onRestoreBackup}
|
||||
onImport={ev.onImport}
|
||||
onImportPointCloud={ev.onImportPointCloud}
|
||||
onImportMesh={ev.onImportMesh}
|
||||
|
||||
Reference in new issue
Block a user