[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
@@ -107,8 +107,16 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC.
|
||||
Geprüft ohne Befund: `save_atomic` (Temp + fsync + Umbenennen + `~`; 3 neue Rust-Tests), Fehler → `SaveError` → `notify`, Projekt bleibt ungespeichert;
|
||||
Rundreise aller Beispiele und der Robustheits-Fixtures samt Libobj/`fill`/`identifiers`/Baurecht (`src/io/projectRoundtrip.test.ts`); Autosave `sampleProjectBig`
|
||||
(1.7 MB) Serialisieren ≈ 35 ms, Prüfen ≈ 33 ms (headless gemessen). Tests: `autosave.test.ts`, `closeGuard.test.ts`, `saveFile.test.ts`, `e2e/datensicherheit116.spec.ts`
|
||||
(Browser). **Offen:** nichts davon in der Tauri-App geprüft — `doc/RELEASE-1.0.md` Abschnitt 14 (Mac); Exporte (`saveBinaryFile`, PDF/DXF) schreiben weiter nicht atomar;
|
||||
Electron schreibt Projektdateien als Download (kein atomares Überschreiben möglich), `.obp~` ohne Wiederherstellungs-UI; Autosave ist ein Fenster-Zustand der Webview
|
||||
(Browser). **Fortsetzung 14.11. (8):** (8) **Exporte atomar** (Tauri): `saveBinaryFile`/`saveTextFile`/OBJ+MTL schreiben über den Rust-Befehl `save_export`
|
||||
(Rohkörper, Pfad prozent-kodiert im Header; Temp + fsync + Umbenennen, keine `~`), vorher `writeFile`/`writeTextFile` des Plugins; Fehler → `setExportErrorReporter`
|
||||
(in `useProjectFileActions` an `notify` gehängt, `export.save.failed`), kein Download-Ersatz, Ziel bleibt heil. (9) **Electron:** Projekt-Speichern atomar im
|
||||
Hauptprozess (`scripts/electron-files.cjs`, `window.dossierFiles`: `saveAtomic`, `saveAs` mit Dialog, `backupExists`, `readBackup`, `pathForFile`); Pfad aus
|
||||
Kommandozeilen-Start oder gewählter Datei, sonst Dialog. (10) **`.obp~`-Wiederherstellung:** lässt sich die Datei nicht laden, die Sicherung aber, bietet
|
||||
`BackupOfferDialog` „Vorige Fassung (.obp~) öffnen" (Lock bleibt bis zur Antwort; geöffnete Sicherung gilt als ungespeichert); Datei-Menü „Vorige Fassung
|
||||
wiederherstellen …" (AppMenuBar + natives Menü, immer aktiv, ohne Sicherung Hinweis `backup.none`); Rust `backup_exists`/`read_backup`. Tests: `atomic_save.rs`
|
||||
(Export, Prozent-Dekodierung, Sicherung lesen), `saveFile.export.test.ts`, `electronFiles.test.ts`, `projectBackup.test.ts`. **Offen:** nichts davon in der
|
||||
Tauri-App/Electron geprüft — `doc/RELEASE-1.0.md` Abschnitt 14 (14.14–14.19; Mac); Fenster für Dialoge/Menü nur per tsc; Menüpunkt nicht ausgegraut; Electron-Kommandozeilen-
|
||||
Start setzt keine Zuletzt-geöffnet-Einträge; Autosave ist ein Fenster-Zustand der Webview
|
||||
(Löschen der Webview-Daten löscht die Kopien); Autosave serialisiert im Hauptfaden (≈ 35 ms bei Grossgebäude, bei viel grösseren Projekten Worker erwägen). · S
|
||||
- Release-Notes-Entwurf `doc/RELEASE-NOTES-1.0.md` (14.11.), offene Fragen an den Maintainer dort markiert (`**[Frage M: …]**`); nach dem Mac-Durchlauf [206] Einschränkungen nachführen.
|
||||
- [30] Release-Workflow lauffähig: macOS universal signiert/notarisiert, Updater, Versionsnummer 1.0.0-beta; [57]/[120] CI auf GitHub grün.
|
||||
|
||||
@@ -178,6 +178,12 @@ Speichern, Autosave und Schliessen sind im Browser und in Unit-Tests geprüft (`
|
||||
| 14.11 | Datei in Dossier öffnen, dieselbe Datei in einer zweiten Instanz öffnen; danach die erste Instanz per Fenster schliessen (mit „Nicht speichern") | zweite Instanz meldet Sperre; nach dem Schliessen ist die Sperre frei (`t.obp.lock` lässt sich neu sperren) |
|
||||
| 14.12 | `dossier-cli :gross migrate --out gross.obp`, in der App öffnen, ändern, 35 s im Plan arbeiten (Zoomen, Wände wählen) | kein spürbares Stocken beim Autosave (gemessen headless: 1.7 MB, Serialisieren ≈ 35 ms) |
|
||||
| 14.13 | Alle Vorlagen und `gross.obp`: öffnen → ⌘S → schliessen → wieder öffnen | gleicher Inhalt, keine Meldung „mit Hinweis geladen" in der Konsole; Objekte (WC/Tisch), Klassen-Füllung, Kennwort/Kennungen, Baurecht-Vorgaben noch da |
|
||||
| 14.14 | Exporte atomar: PDF, DXF, IFC, PNG (Bild), GLB, OBJ+MTL je einmal in einen neuen Ordner exportieren; dieselbe Datei nochmals überschreiben; im Terminal `ls` | Dateien öffnen sich in Vorschau/Fremdprogramm; keine `.tmp` und keine `~` neben Exporten; Überschreiben ersetzt die Datei ganz |
|
||||
| 14.15 | Export-Schreibfehler: Zielordner sperren (`chmod a-w ordner`), PDF dorthin exportieren; ebenso eine vorhandene Datei schreibgeschützt (`chmod a-w x.pdf`) und überschreiben | rote Meldung „Export konnte nicht geschrieben werden …"; kein stiller Download-Ersatz; die vorhandene Zieldatei ist unverändert und nicht abgeschnitten |
|
||||
| 14.16 | Pfad mit Umlauten/Leerzeichen/`%` (`~/Pläne 100%/a b.pdf`) als Exportziel | Datei liegt genau dort (der Pfad wird prozent-kodiert an den Rust-Befehl `save_export` gereicht) |
|
||||
| 14.17 | Beschädigte Datei mit Sicherung: `t.obp` zweimal speichern (damit `t.obp~` existiert), dann `t.obp` abschneiden (`head -c 5000 t.obp > x && mv x t.obp`), über „Öffnen“ wählen | Overlay „Vorige Fassung öffnen?" mit Fehlertext; „Vorige Fassung (.obp~) öffnen“ lädt den Stand (Titel ungespeichert), erster ⌘S überschreibt `t.obp`, `t.obp~` ist dann die beschädigte Fassung; „Abbrechen“: bisheriges Projekt bleibt, Sperre frei. Ohne `t.obp~`: nur die rote Meldung wie 14.7 |
|
||||
| 14.18 | Datei → „Vorige Fassung wiederherstellen …“ bei offener Datei mit `~` / ohne `~` / ohne Dateipfad (neues Projekt) | mit `~`: Stand der Sicherung ist offen, Hinweis „Vorige Fassung geöffnet …", Datei bleibt bis ⌘S unverändert (bei ungespeicherten Änderungen vorher die Rückfrage); sonst Hinweis „Es gibt keine vorige Fassung …". Hinweis: der Menüeintrag ist immer aktiv (kein Ausgrauen) |
|
||||
| 14.19 | Linux/Electron (`scripts/electron-shell.sh`): `dossier t.obp` (Pfad per Argument) → ändern → ⌘/Strg+S; danach „Speichern unter“ im Hauptprozess-Dialog; `t.obp~` und `t.obp.tmp` ansehen | kein Download mehr: die Datei wird am Pfad überschrieben, `t.obp~` = Vorversion, keine `.tmp`; ohne Pfad (leeres Projekt) erscheint der Speichern-Dialog; nur im Linux-Container nicht geprüft (nur die Dateiebene `scripts/electron-files.cjs` per Test) |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// electron-files.cjs — Projektdateien im Electron-Hauptprozess ([116]): atomar schreiben (Temp-Datei + fsync + Umbenennen,
|
||||
// Vorversion als `<pfad>~`), „Speichern unter" mit Dialog, Sicherung erkennen/lesen. Gegenstück zu src-tauri/src/atomic_save.rs
|
||||
// (Tauri). Renderer-Seite: src/native/projectFile.ts (`window.dossierFiles`, electron-preload.cjs).
|
||||
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
/** Schreibt `text` atomar nach `file`; mit `keepBackup` landet die Vorversion in `<file>~`. Wirft bei Fehler, das Ziel bleibt heil. */
|
||||
function writeAtomic(file, text, keepBackup) {
|
||||
const tmp = `${file}.tmp`;
|
||||
const backup = `${file}~`;
|
||||
try {
|
||||
const fd = fs.openSync(tmp, "w");
|
||||
try {
|
||||
fs.writeFileSync(fd, text, "utf8");
|
||||
fs.fsyncSync(fd);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
// Kopie statt Umbenennen: der Zielpfad existiert so zu jedem Zeitpunkt.
|
||||
if (keepBackup && fs.existsSync(file)) fs.copyFileSync(file, backup);
|
||||
fs.renameSync(tmp, file);
|
||||
} catch (err) {
|
||||
try {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
} catch {
|
||||
/* ignorieren */
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
try {
|
||||
const dir = fs.openSync(path.dirname(file), "r");
|
||||
try {
|
||||
fs.fsyncSync(dir);
|
||||
} finally {
|
||||
fs.closeSync(dir);
|
||||
}
|
||||
} catch {
|
||||
/* Ordner-Sync ist best effort (Windows) */
|
||||
}
|
||||
}
|
||||
|
||||
const backupExists = (file) => {
|
||||
try {
|
||||
return fs.statSync(`${file}~`).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/** Meldet die IPC-Kanäle an. `getWindow()` liefert das Hauptfenster (Elternfenster der Dialoge). */
|
||||
function register(ipcMain, dialog, getWindow) {
|
||||
ipcMain.handle("file:save-atomic", (_e, file, text) => {
|
||||
if (typeof file !== "string" || !file || typeof text !== "string") throw new Error("Ungültiger Aufruf");
|
||||
writeAtomic(file, text, true);
|
||||
return true;
|
||||
});
|
||||
// „Speichern unter": Dialog, dann atomar schreiben; null = abgebrochen.
|
||||
ipcMain.handle("file:save-as", async (_e, defaultName, text, filters) => {
|
||||
if (typeof text !== "string") throw new Error("Ungültiger Aufruf");
|
||||
const win = getWindow();
|
||||
const opts = { defaultPath: String(defaultName || "projekt.obp"), filters: Array.isArray(filters) ? filters : undefined };
|
||||
const r = win ? await dialog.showSaveDialog(win, opts) : await dialog.showSaveDialog(opts);
|
||||
if (r.canceled || !r.filePath) return null;
|
||||
writeAtomic(r.filePath, text, true);
|
||||
return r.filePath;
|
||||
});
|
||||
ipcMain.handle("file:backup-exists", (_e, file) => typeof file === "string" && backupExists(file));
|
||||
ipcMain.handle("file:read-backup", (_e, file) => {
|
||||
if (typeof file !== "string" || !backupExists(file)) return null;
|
||||
return fs.readFileSync(`${file}~`, "utf8");
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { register, writeAtomic, backupExists };
|
||||
@@ -4,11 +4,12 @@
|
||||
// (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 } = require("electron");
|
||||
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/
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// electron-main.cjs) — sonst gaebe es keine Moeglichkeit, das Fenster ueberhaupt
|
||||
// zu steuern.
|
||||
|
||||
const { contextBridge, ipcRenderer } = require("electron");
|
||||
const { contextBridge, ipcRenderer, webUtils } = require("electron");
|
||||
|
||||
contextBridge.exposeInMainWorld("dossierWindow", {
|
||||
minimize: () => ipcRenderer.send("window:minimize"),
|
||||
@@ -56,3 +56,19 @@ contextBridge.exposeInMainWorld("dossierLaunch", {
|
||||
return () => ipcRenderer.removeListener("launch:open-file", listener);
|
||||
},
|
||||
});
|
||||
|
||||
// [116] Projektdateien: atomar speichern (Temp + Umbenennen, Vorversion als `~`), „Speichern unter", Sicherung lesen.
|
||||
// Renderer-Seite: src/native/projectFile.ts. `pathForFile` liefert den Pfad einer im Dialog gewählten Datei.
|
||||
contextBridge.exposeInMainWorld("dossierFiles", {
|
||||
saveAtomic: (path, text) => ipcRenderer.invoke("file:save-atomic", path, text),
|
||||
saveAs: (defaultName, text, filters) => ipcRenderer.invoke("file:save-as", defaultName, text, filters),
|
||||
backupExists: (path) => ipcRenderer.invoke("file:backup-exists", path),
|
||||
readBackup: (path) => ipcRenderer.invoke("file:read-backup", path),
|
||||
pathForFile: (file) => {
|
||||
try {
|
||||
return webUtils.getPathForFile(file) || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -15,6 +15,44 @@ fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
|
||||
|
||||
/// Schreibt `content` atomar nach `path`; die Vorversion landet in `<path>~`.
|
||||
pub fn save_atomic_impl(path: &Path, content: &[u8]) -> Result<(), String> {
|
||||
write_atomic(path, content, true)
|
||||
}
|
||||
|
||||
/// Export ([116]): atomar wie `save_atomic_impl`, aber ohne `<path>~` (ein Export ersetzt eine Datei bewusst).
|
||||
pub fn export_atomic_impl(path: &Path, content: &[u8]) -> Result<(), String> {
|
||||
write_atomic(path, content, false)
|
||||
}
|
||||
|
||||
/// Gibt es eine Sicherung der Vorversion (`<path>~`)?
|
||||
pub fn backup_exists_impl(path: &Path) -> bool {
|
||||
with_suffix(path, "~").is_file()
|
||||
}
|
||||
|
||||
/// Liest die Sicherung der Vorversion (`<path>~`); `None`, wenn es keine gibt oder sie nicht als UTF-8 lesbar ist.
|
||||
pub fn read_backup_impl(path: &Path) -> Option<String> {
|
||||
fs::read_to_string(with_suffix(path, "~")).ok()
|
||||
}
|
||||
|
||||
/// Dekodiert `%XX` (UTF-8) aus einem Header-Wert; ungültige Folgen bleiben wie sie sind.
|
||||
pub fn percent_decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
if b[i] == b'%' && i + 2 < b.len() + 0 && i + 2 <= b.len() - 1 {
|
||||
if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
|
||||
out.push(v);
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(b[i]);
|
||||
i += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
fn write_atomic(path: &Path, content: &[u8], keep_backup: bool) -> Result<(), String> {
|
||||
let tmp = with_suffix(path, ".tmp");
|
||||
let backup = with_suffix(path, "~");
|
||||
let write_tmp = || -> std::io::Result<()> {
|
||||
@@ -27,7 +65,7 @@ pub fn save_atomic_impl(path: &Path, content: &[u8]) -> Result<(), String> {
|
||||
return Err(format!("Temp-Datei schreiben: {e}"));
|
||||
}
|
||||
// Vorversion sichern (Kopie statt Umbenennen: der Zielpfad existiert so zu jedem Zeitpunkt).
|
||||
if path.exists() {
|
||||
if keep_backup && path.exists() {
|
||||
if let Err(e) = fs::copy(path, &backup) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(format!("Sicherung anlegen: {e}"));
|
||||
@@ -57,6 +95,60 @@ mod tests {
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_ueberschreibt_atomar_ohne_sicherung() {
|
||||
let d = tmpdir("export");
|
||||
let p = d.join("plan.pdf");
|
||||
export_atomic_impl(&p, b"%PDF-1").unwrap();
|
||||
export_atomic_impl(&p, &[0u8, 255, 1, 2]).unwrap();
|
||||
assert_eq!(fs::read(&p).unwrap(), vec![0u8, 255, 1, 2]);
|
||||
assert!(!with_suffix(&p, "~").exists());
|
||||
assert!(!with_suffix(&p, ".tmp").exists());
|
||||
fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_fehler_laesst_ziel_heil() {
|
||||
let d = tmpdir("export-fehler");
|
||||
let p = d.join("plan.dxf");
|
||||
export_atomic_impl(&p, b"alt").unwrap();
|
||||
fs::create_dir(with_suffix(&p, ".tmp")).unwrap();
|
||||
assert!(export_atomic_impl(&p, b"neu").is_err());
|
||||
assert_eq!(fs::read(&p).unwrap(), b"alt");
|
||||
assert!(export_atomic_impl(&d.join("nope").join("x.dxf"), b"x").is_err());
|
||||
fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sicherung_wird_erkannt() {
|
||||
let d = tmpdir("exists");
|
||||
let p = d.join("a.obp");
|
||||
save_atomic_impl(&p, b"eins").unwrap();
|
||||
assert!(!backup_exists_impl(&p));
|
||||
save_atomic_impl(&p, b"zwei").unwrap();
|
||||
assert!(backup_exists_impl(&p));
|
||||
fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sicherung_wird_gelesen() {
|
||||
let d = tmpdir("read-backup");
|
||||
let p = d.join("a.obp");
|
||||
assert_eq!(read_backup_impl(&p), None);
|
||||
save_atomic_impl(&p, "eins äö".as_bytes()).unwrap();
|
||||
save_atomic_impl(&p, b"zwei").unwrap();
|
||||
assert_eq!(read_backup_impl(&p).as_deref(), Some("eins äö"));
|
||||
fs::remove_dir_all(&d).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prozent_dekodierung_von_pfaden() {
|
||||
assert_eq!(percent_decode("/tmp/Pl%C3%A4ne/a%20b.pdf"), "/tmp/Pläne/a b.pdf");
|
||||
assert_eq!(percent_decode("/x/100%"), "/x/100%");
|
||||
assert_eq!(percent_decode("/x/%zz"), "/x/%zz");
|
||||
assert_eq!(percent_decode("C:%5Cx"), "C:\\x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neue_datei_ohne_sicherung() {
|
||||
let d = tmpdir("neu");
|
||||
|
||||
@@ -43,6 +43,35 @@ fn save_atomic(path: String, content: String) -> Result<(), String> {
|
||||
atomic_save::save_atomic_impl(&PathBuf::from(path), content.as_bytes())
|
||||
}
|
||||
|
||||
/// Export schreiben ([116], PDF/DXF/IFC/PNG …): Bytes als Rohkörper, Zielpfad prozent-kodiert im Header `x-path`;
|
||||
/// atomar (Temp + fsync + Umbenennen), das Ziel bleibt bei Fehler heil. Keine `~`-Sicherung.
|
||||
#[tauri::command]
|
||||
fn save_export(request: tauri::ipc::Request<'_>) -> Result<(), String> {
|
||||
let path = request
|
||||
.headers()
|
||||
.get("x-path")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(atomic_save::percent_decode)
|
||||
.filter(|p| !p.is_empty())
|
||||
.ok_or_else(|| "Zielpfad fehlt".to_string())?;
|
||||
let tauri::ipc::InvokeBody::Raw(bytes) = request.body() else {
|
||||
return Err("Inhalt fehlt".to_string());
|
||||
};
|
||||
atomic_save::export_atomic_impl(&PathBuf::from(path), bytes)
|
||||
}
|
||||
|
||||
/// Gibt es zur Projektdatei eine Sicherung der Vorversion (`<pfad>~`)? ([116])
|
||||
#[tauri::command]
|
||||
fn backup_exists(path: String) -> bool {
|
||||
atomic_save::backup_exists_impl(&PathBuf::from(path))
|
||||
}
|
||||
|
||||
/// Inhalt der Sicherung der Vorversion (`<pfad>~`), falls vorhanden ([116]).
|
||||
#[tauri::command]
|
||||
fn read_backup(path: String) -> Option<String> {
|
||||
atomic_save::read_backup_impl(&PathBuf::from(path))
|
||||
}
|
||||
|
||||
/// Blender-Programmdatei ([211]): eigene Angabe aus den Einstellungen, sonst PATH und die üblichen Orte. `None` = nicht gefunden.
|
||||
#[tauri::command]
|
||||
fn blender_find(custom: Option<String>) -> Option<String> {
|
||||
@@ -414,6 +443,9 @@ pub fn run() {
|
||||
acquire_project_lock,
|
||||
release_project_lock,
|
||||
save_atomic,
|
||||
save_export,
|
||||
backup_exists,
|
||||
read_backup,
|
||||
blender_find,
|
||||
blender_job_dir,
|
||||
blender_start,
|
||||
@@ -438,6 +470,9 @@ pub fn run() {
|
||||
acquire_project_lock,
|
||||
release_project_lock,
|
||||
save_atomic,
|
||||
save_export,
|
||||
backup_exists,
|
||||
read_backup,
|
||||
blender_find,
|
||||
blender_job_dir,
|
||||
blender_start,
|
||||
|
||||
+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