Files
DOSSIER/src/core/document.ts
T
Claude 2ab2b340cb [195b] Objekteinstellungen-Fenster: Ops-Strom statt Neuladen des Projekts
Das Hauptfenster sammelt die vom Kern-Dokument angenommenen Ops (ProjectDocument.onChange:
Commit, Griff, Befehl, Import, Undo/Redo, Sprung) und schickt sie mit laufender Nummer; das
Fenster führt sie ohne Verlauf nach (applyRemote = doc_apply + applyOps). Rückfall Feld-Differenz
mit Vollabgleich bei Laden/Neu oder fehlenden Ops; Lücke oder abgelehnte Ops fordern den ganzen
Stand an. Grossgebäude: 0.4 ms statt 56 ms je Wandänderung (Linux, vitest).
2026-11-12 04:06:04 +00:00

886 lines
39 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Projekt-Dokument im Rust-Kern ([K4], Stufe S1; S3: Prüfung und Undo/Redo im Kern, s. `commit`;
// S4: Laden/Speichern der Projektdatei, s. `loadFile`/`serialize`). Änderungen kommen als Ops
// (`commit`), ein anderes Projekt als Ganzes (`load`, `loadFile` — leert den Verlauf). TS hält die
// Leseansicht (`current`). Abfragen finden ihr Dokument über die Leseansicht (`documentFor`); ein
// abgewandeltes Projekt wird ausdrücklich geöffnet (`withDocument`) statt abgeglichen ([122]).
import type { Project, UiState } from "../model/types";
import { core, registerCoreRestore } from "../engine/coreWasm";
import { applyOps, opsToJson } from "./ops";
import { fromMarkedJson, toMarkedJson } from "./ops";
import type { CoreOp } from "./ops";
import { opsMutation } from "./opsBuild";
import { StepStates } from "./stepStates";
import { HistoryBackup } from "./historyBackup";
import type { ProjectMutation } from "./opsBuild";
import type { IfcImportResult } from "../io/ifcImport";
import type { MeshImportReport } from "../io/meshImport";
/**
* Gelesene Zeichnungs-Datei für den Kern ([K4] S4): Puffer des Format-Moduls, je Stück (paralleles Lesen
* grosser DXF) hintereinander als `[n, len_0 … len_{n−1}, daten …]`, die String-Tabellen je Stück, und wie
* der Puffer zu lesen ist (DXF/DWG bzw. PDF-Seite mit Massstab).
*/
export interface ImportSource {
geom: Float64Array;
strings: string[][];
source: { kind: "drawing" } | { kind: "pdf"; scale: number; texts?: boolean };
}
/** Entscheidung des Import-Dialogs (bzw. CLI) für {@link ProjectDocument.importDrawing}; Texte schon übersetzt. */
export interface DrawingImportDecision {
target: { kind: "existing"; levelId: string } | { kind: "new"; name: string };
categoryMode: "byLayer" | "active";
activeCategoryCode: string;
importMeshes: boolean;
/** Mitte des Ausschnitts (Platzierung „viewCenter"); fehlt = an den Datei-Koordinaten. */
viewCenter?: [number, number];
/** Name einer neuen Zeichnung ohne Eingabe, `{n}` = Nummer. */
levelNameTemplate?: string;
/** Elternkategorie der neuen Layer-Kategorien. */
parentName?: string;
/** Name neuer Linienstile aus PDF-Strichmustern, `{pattern}` = Muster. */
dashStyleTemplate?: string;
/** [143] Erkannte Höhenlinien als Gelände-Höhenlinien (`contourSet`) statt als 2D-Zeichnung übernehmen. */
terrainContours?: boolean;
/** [143] Name des Höhenlinien-Satzes (übersetzt). */
terrainName?: string;
}
/** Rohergebnis des IFC-Lesers (`fileio`): Bericht (JSON), Positionen, Indizes, Zahlen der Bauteil-Erkennung. */
export interface IfcFlatInput {
meta: string;
positions: Float64Array;
indices: Uint32Array;
elementData?: Float64Array;
}
/** Änderungs-Antwort des 3D-Modells (Kern `model3d_cache::write_delta`). */
interface Model3dDelta {
mark: number;
wallKeys: number[];
/** [180] Einträge ausgeblendeter Klassen: behalten, nicht zeigen (fehlt = keine). */
wallKeep?: number[];
wallNew: [number, unknown[]][];
openingKeys: number[];
/** [180] Wie `wallKeep`. */
openingKeep?: number[];
openingNew: [number, unknown[], unknown[], unknown[], unknown[], unknown[]][];
openingTail: unknown[];
[rest: string]: unknown;
}
/** Gelesene Einträge der letzten Antwort (Laufnummer → Wandkörper bzw. 5 Listen Einbauteile). */
interface Model3dDeltaCache {
mark: number;
walls: Map<number, unknown[]>;
openings: Map<number, unknown[][]>;
}
/** Setzt die Teile aus Antwort und gehaltenen Einträgen zusammen; `null`, wenn ein Eintrag fehlt. */
/** Einträge des 3D-Modells mit Laufnummer (Wandkörper bzw. 5 Listen Einbauteile) und Öffnungs-Rest. */
export interface Model3dKeyed {
wallEntries: (readonly [number, unknown[]])[];
openingEntries: (readonly [number, unknown[][]])[];
openingTail: unknown[];
}
function assembleModel3dDelta(
r: Model3dDelta,
cache: Model3dDeltaCache | undefined,
): { parts: Record<string, unknown>; keyed: Model3dKeyed; cache: Model3dDeltaCache } | null {
const wallNew = new Map(r.wallNew);
const walls: unknown[] = [];
const wallMap = new Map<number, unknown[]>();
for (const k of r.wallKeys) {
const e = wallNew.get(k) ?? cache?.walls.get(k);
if (!e) return null;
for (const x of e) walls.push(x);
wallMap.set(k, e);
}
for (const k of r.wallKeep ?? []) {
const e = wallNew.get(k) ?? cache?.walls.get(k);
if (!e) return null;
wallMap.set(k, e);
}
const openNew = new Map(r.openingNew.map(([k, ...lists]) => [k, lists] as const));
const openMap = new Map<number, unknown[][]>();
const entries: unknown[][][] = [];
for (const k of r.openingKeys) {
const e = openNew.get(k) ?? cache?.openings.get(k);
if (!e) return null;
entries.push(e);
openMap.set(k, e);
}
for (const k of r.openingKeep ?? []) {
const e = openNew.get(k) ?? cache?.openings.get(k);
if (!e) return null;
openMap.set(k, e);
}
const openingMeshes: unknown[] = [];
for (let l = 0; l < 5; l++) for (const e of entries) for (const x of e[l]) openingMeshes.push(x);
for (const x of r.openingTail) openingMeshes.push(x);
const { mark, wallKeys: _wk, wallKeep: _wp, wallNew: _wn, openingKeys: _ok, openingKeep: _op, openingNew: _on, openingTail, ...rest } = r;
// Einträge mit Laufnummer zusätzlich, für den 3D-Viewer (Teil-Updates, `toWalls3d.projectToModel3dParts`).
const keyed: Model3dKeyed = {
wallEntries: r.wallKeys.map((k) => [k, wallMap.get(k)!] as const),
openingEntries: r.openingKeys.map((k) => [k, openMap.get(k)!] as const),
openingTail,
};
return { parts: { ...rest, walls, openingMeshes }, keyed, cache: { mark, walls: wallMap, openings: openMap } };
}
/** Ergebnis des Ladens einer Projektdatei ({@link ProjectDocument.loadFile}). */
export type LoadFileResult =
| { ok: true; project: Project; warnings: string[]; migratedFrom: number | null }
| { ok: false; error: string };
/** Wurzel-Abfragen des Kerns (`queries.rs::run_root`). */
export type RootQueryName = "penRebakeOps" | "penDeleteOps" | "penSeedOps" | "standardsMergeOps" | "standardsUpdatePlan" | "standardsUpdateOps" | "folderPdfPages" | "layoutTitleBlock" | "translatePatch" | "translateOps" | "selectionFilterPatch";
/** Abfragen des Kerns (`queries.rs`). */
export type QueryName =
| "hiddenElements"
| "surfaceOpening"
| "presentationSheet"
| "kennzahlen"
| "areaTable"
| "programCompare"
| "programLayout"
| "ivhb"
| "siteCheck"
| "excavationQuantities"
| "dormerStatus"
| "buildingFootprint"
| "modelTop"
| "shadows"
| "materialMaps"
| "slabs"
| "columnMeshes"
| "walls"
| "openingMeshes"
| "stairSlabs"
| "stairMeshes"
| "stairRailings"
| "roofMeshes"
| "roofCutLayers"
| "openingSchedule"
| "elementSchedule"
| "roomBook"
| "uValue"
| "componentLayerFunctions"
| "sheetTables"
| "sheetTableCatalog"
| "openingPreview"
| "scheduleRows"
| "scheduleCsv"
| "pickGeometry"
| "solidProps"
| "explodeOffsets"
| "model3dParts"
| "model3dPartsDelta"
| "projectSolidSpecs"
| "planDomains"
| "ifcExportData"
| "meshExportData"
| "groupMembership"
| "containingGroup"
| "selectionCategoryCodes"
| "expandToGroups"
| "drawingUnderlay"
| "drawingLines"
| "drawingPrims"
| "levelMarkers"
| "planUnderlay"
| "sectionPlan"
| "elevationPlan"
| "selectionHighlight"
| "modelJson";
/** [195b] Beobachter einer neuen Leseansicht: alter und neuer Stand, Ops dazwischen (`null` = unbekannt). */
export type DocumentChangeListener = (before: Project, after: Project, ops: readonly CoreOp[] | null) => void;
export class ProjectDocument {
private handle = 0;
private mirror: Project;
/** Verlaufsgrenzen (Schritte, Bytes), beim Neuöffnen wieder gesetzt. */
private limits: [number, number] | null = null;
/** Stände grosser Verlaufsschritte (Undo/Redo ohne Ops-Rückgabe, s. `stepStates.ts`). */
private steps = new StepStates();
/** Kopie des Kern-Verlaufs für einen Neustart nach Panic ([118]). */
private hist = new HistoryBackup();
/** Gelieferte Einträge des 3D-Modells je Argument-Satz ([58], {@link model3dParts}). */
private m3d = new Map<string, Model3dDeltaCache>();
constructor(project: Project) {
this.mirror = project;
this.reopen(project);
if (liveDocs.size >= 64) for (const r of liveDocs) if (!r.deref()) liveDocs.delete(r);
liveDocs.add(new WeakRef(this));
}
/** Handle im Kern (0 = nicht offen). */
get id(): number {
return this.handle;
}
/**
* Nach einem Kern-Neustart ([118], `coreWasm.ts`): die alte Instanz samt Handle und Verlauf ist weg;
* das Dokument öffnet sich aus der Leseansicht neu (die ist der letzte angenommene Stand — eine
* Änderung, deren Aufruf den Panic auslöste, war noch nicht übernommen). Der Verlauf kommt aus der
* TS-Kopie zurück (`historyBackup.ts`), wenn sie zu dieser Leseansicht gehört; sonst beginnt er leer.
*/
restoreAfterRestart(): void {
this.m3d.clear();
const wasOpen = this.handle !== 0;
this.handle = 0;
this.steps.clear();
this.historyKept = true;
if (!wasOpen) return this.hist.clear();
this.reopen(this.mirror);
this.historyKept = this.hist.restore(this.handle, this.mirror);
}
/** Ob beim letzten Kern-Neustart der Verlauf erhalten blieb ([118]; Meldung an den Benutzer). */
historyKept = true;
/**
* Neue Leseansicht nach einer angenommenen Änderung bzw. Undo/Redo; Verlaufskopie nachführen ([118]).
* `ops` = die Ops, die den alten Stand in den neuen überführen (`null` = unbekannt, z. B. Laden).
*/
private setMirror(project: Project, ops: readonly CoreOp[] | null): void {
const before = this.mirror;
this.mirror = project;
this.hist.sync(this.handle, project);
this.notifyChange(before, project, ops);
}
/** [195b] Beobachter der übernommenen Stände (s. {@link onChange}). */
private changeListeners = new Set<DocumentChangeListener>();
/**
* [195b] Meldet jede neue Leseansicht samt der Ops, die dahin führten (Commit, Griff, Befehl, Import,
* Undo/Redo, Sprung im Verlauf; `null` bei Laden oder grossem Verlaufsschritt ohne Ops-Rückgabe). So
* kann ein Spiegel (natives Nebenfenster) dieselben Ops nachführen statt das Projekt neu zu laden.
* Liefert die Abmeldung.
*/
onChange(fn: DocumentChangeListener): () => void {
this.changeListeners.add(fn);
return () => this.changeListeners.delete(fn);
}
private notifyChange(before: Project, after: Project, ops: readonly CoreOp[] | null): void {
for (const fn of [...this.changeListeners]) fn(before, after, ops);
}
/**
* [195b] Ops nachführen, die ein ANDERES Dokument schon geprüft, angewendet und aufgezeichnet hat
* (Spiegel eines Nebenfensters, Ops-Strom des Hauptfensters): ohne Verlaufseintrag (`doc_apply`), die
* Leseansicht wie beim Commit über `applyOps`. `null` = das Dokument spiegelt `base` nicht oder der Kern
* lehnt ab (Dokument unverändert; der Aufrufer gleicht dann ganz ab).
*/
applyRemote(base: Project, ops: readonly CoreOp[]): Project | null {
if (base !== this.mirror || !this.handle) return null;
if (ops.length === 0) return base;
if (core().doc_apply(this.handle, opsToJson(ops))) return null;
const project = applyOps(base, ops, core().doc_last_hits(this.handle));
this.setMirror(project, ops);
return project;
}
private reopen(project: Project): void {
this.m3d.clear();
if (this.handle) core().doc_close(this.handle);
this.handle = core().doc_open(JSON.stringify(project));
if (!this.handle) console.warn("Projekt-Dokument im Kern konnte nicht geöffnet werden.");
else if (this.limits) core().doc_history_limits(this.handle, this.limits[0], this.limits[1]);
}
/**
* Abfrage auf dem typisierten Projekt im Kern (`queries.rs`); `args` Zahlen, `text` ein Text
* (z. B. eine id). Das Ergebnis ist JSON; Fehler im Kern (Projekt passt nicht zum Modell,
* Rechenfehler) werfen mit der Meldung des Kerns.
*/
query<T>(name: QueryName, args: number[] = [], text = ""): T {
return JSON.parse(this.queryJson(name, args, text)) as T;
}
/**
* Teile des 3D-Modells (`model3dParts` ohne Explosion, `args` = deren 5 Zahlen) über Änderungs-Antworten
* ([58], Kern `model3d_cache.rs`): der Kern schreibt nur die Wände/Öffnungs-Einbauteile aus, die seit der
* letzten Antwort für dieselben Argumente neu sind; die übrigen kommen aus den hier gehaltenen, schon
* gelesenen Einträgen. Ergebnis wie `query("model3dParts", args)`. Die Einträge werden zwischen den
* Ergebnissen geteilt — nicht verändern.
*/
model3dParts<T>(args: number[], text = ""): T {
return this.model3dPartsKeyed<T>(args, text).parts;
}
/**
* Wie {@link model3dParts}, dazu die Einträge mit Laufnummer (3D-Viewer, Teil-Updates [58]). `text`: Klassen-Filter
* `{"hide": [codes]}` ([180]); Einträge ausgeblendeter Klassen bleiben gehalten (Umschalten schickt nichts neu).
*/
model3dPartsKeyed<T>(args: number[], text = ""): { parts: T; keyed: Model3dKeyed } {
const a = [0, 0, 0, 0, 0].map((d, i) => args[i] ?? d);
const key = a.join(",");
let cache = this.m3d.get(key);
for (let attempt = 0; attempt < 2; attempt++) {
const r = JSON.parse(this.queryJson("model3dPartsDelta", [...a, cache?.mark ?? 0], text)) as Model3dDelta;
const out = assembleModel3dDelta(r, cache);
if (out) {
this.m3d.delete(key);
this.m3d.set(key, out.cache);
if (this.m3d.size > 4) this.m3d.delete(this.m3d.keys().next().value!);
return { parts: out.parts as T, keyed: out.keyed };
}
// Ein Eintrag fehlt (sollte nicht vorkommen): einmal alles neu anfordern.
cache = undefined;
}
throw new Error("Kern-Abfrage „model3dPartsDelta“: Einträge fehlen");
}
/** Wie {@link query}, aber das JSON als Text (spart das Parsen, wenn es nur weitergereicht wird). */
queryJson(name: QueryName, args: number[] = [], text = ""): string {
if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`);
const out = core().doc_query_args(this.handle, name, Float64Array.from(args), text);
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
return out;
}
/**
* Abfrage auf dem rohen Projekt-JSON des Kerns (`queries.rs::run_root`): rechnet verlustfrei auf dem
* Baum (unbekannte Felder, Schlüsselreihenfolge) und liefert meist Ops. `text`: Argument (Text/JSON).
*/
queryRoot<T>(name: RootQueryName, text = ""): T {
if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`);
const out = core().doc_query_root(this.handle, name, text);
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
return JSON.parse(out) as T;
}
/**
* Abfrage mit binärer Antwort (`queries.rs::run_bin`, z. B. `planDomains` als Plan-Puffer v2,
* s. `plan/planBuf.ts`). Fehler kommen als Fehlerpuffer (`decodePlanBuf` wirft die Meldung).
*/
queryBin(name: QueryName, args: number[] | Float64Array = [], text = ""): Uint8Array {
if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`);
return core().doc_query_bin(this.handle, name, args instanceof Float64Array ? args : Float64Array.from(args), text);
}
/**
* Projekt laden (Neu, Musterhaus, Abgleich nach einer Änderung vorbei an den Ops): ersetzt den
* ganzen Inhalt im Kern und leert den Verlauf. `project` wird die Leseansicht (Identität bleibt).
*/
load(project: Project): void {
const before = this.mirror;
this.mirror = project;
this.steps.clear();
this.m3d.clear();
if (!this.handle || !core().doc_load_json(this.handle, JSON.stringify(project))) this.reopen(project);
this.hist.sync(this.handle, project);
this.notifyChange(before, project, null);
}
/**
* Projektdatei laden (Öffnen, Vorlage, Wiederherstellen; [K4] S4): der Kern liest den Text, migriert
* ältere Formate, prüft und ergänzt (`project_format.rs`) und lädt das Ergebnis direkt ins Dokument
* (Verlauf leer). Die Leseansicht kommt als JSON des Dokuments zurück. Bei Fehler bleibt alles, wie es war.
*/
loadFile(text: string, now = Date.now()): LoadFileResult {
if (!this.handle) this.reopen({} as Project);
if (!this.handle) return { ok: false, error: "Projekt-Dokument im Kern nicht offen." };
const r = JSON.parse(core().doc_load_file(this.handle, text, now)) as
| { ok: true; warnings: string[]; migratedFrom: number | null }
| { ok: false; error: string };
if (!r.ok) return r;
const project = JSON.parse(core().doc_json(this.handle)) as Project;
this.setMirror(project, null);
return { ok: true, project, warnings: r.warnings, migratedFrom: r.migratedFrom };
}
/** Datei-Text des Projekts (Formatversion vorn, Einrückung 2, Zeichen für Zeichen wie `JSON.stringify`). */
serialize(ui?: UiState): string {
if (!this.handle) return "";
// `ui` ([136], offene Reiter) ersetzt `uiState` nur in der Datei; das Dokument bleibt unverändert.
return ui ? core().doc_serialize_with_ui(this.handle, JSON.stringify(ui)) : core().doc_serialize(this.handle);
}
/** Boden-Spuren der 2D-Zeichnungen als LineList-Vertices `[px, py, pz, r, g, b]`; `hide` = Klassen-Filter ([180]). */
drawingLineVerts(explode = 0, hide = ""): Float32Array {
return this.handle ? core().doc_drawing_line_verts(this.handle, explode, hide) : new Float32Array(0);
}
/** Zulässige Hülle im 3D ([63]) für render3d `set_ghost`; leer ohne Baurecht oder `siteRules.show3d`. */
siteEnvelope(): Float32Array {
return this.handle ? core().doc_site_envelope(this.handle) : new Float32Array(0);
}
/** Ansichtsschraffur auf den Flächen (Wände, Decken, Dächer) für render3d `set_pattern_lines`. */
surfacePatternLines(explode = 0, hide = ""): Float32Array {
return this.handle ? core().doc_surface_pattern_lines(this.handle, explode, hide) : new Float32Array(0);
}
/** Das Dokument als JSON-Text (Test, Export). */
json(): string {
return this.handle ? core().doc_json(this.handle) : "";
}
close(): void {
if (this.handle) core().doc_close(this.handle);
this.handle = 0;
for (const r of liveDocs) if (r.deref() === this) liveDocs.delete(r);
}
// ── Änderungen mit Verlauf ([K4] S3, [7], [8]) ──────────────────────────────
// Der Kern prüft, wendet an und zeichnet Undo-Schritte als inverse Ops auf; das TS-Projekt ist
// die Leseansicht und wird mit genau den Ops nachgeführt, die der Kern angenommen bzw. für
// Undo/Redo geliefert hat (`applyOps`, unveränderte Elemente behalten ihre Identität).
/** Stand des Spiegels (die zuletzt übernommene Leseansicht). */
get current(): Project {
return this.mirror;
}
/**
* Stellt sicher, dass das Dokument `base` spiegelt. Wurde das Projekt vorbei an den Ops
* geändert (fremder Stand), passt der Verlauf nicht mehr: `base` wird als Ganzes geladen.
*/
private ensure(base: Project): void {
if (base === this.mirror && this.handle) return;
this.load(base);
}
/**
* Benutzer-Änderung: `ops` (auf `base`) im Kern prüfen, anwenden und als Undo-Schritt
* aufzeichnen (`coalesceKey` + `now` in ms: Serien im Zeitfenster = ein Schritt).
* Ergebnis: neues Projekt oder die Meldungen des Kerns (dann bleibt alles unverändert).
*/
commit(base: Project, ops: readonly CoreOp[], coalesceKey: string | undefined, now: number): { project: Project } | { problems: string[] } {
this.ensure(base);
if (!this.handle) return { problems: ["Projekt-Dokument im Kern nicht offen."] };
const res = core().doc_commit(this.handle, opsToJson(ops), coalesceKey ?? "", now);
if (res) {
let problems: string[];
try {
problems = JSON.parse(res) as string[];
} catch {
problems = [res];
}
return { problems };
}
const extra = this.lastExtra();
const project = this.withExtra(applyOps(base, ops, core().doc_last_hits(this.handle)), extra);
const all = extra.length ? [...ops, ...extra] : ops;
this.setMirror(project, all);
this.rememberCommit(base, project, all);
return { project };
}
/**
* Griff-Änderung ([K4] S3, `grips.rs`): der Kern rechnet `req` (s. `GripRequest`) auf seinem Stand
* von `base` und wendet das Ergebnis wie {@link commit} an — ein Aufruf je Mausschritt. Ergebnis:
* neues Projekt und die angewendeten Ops (leer = nichts zu tun, dann `project === base`), ein
* Hinweis-Schlüssel (i18n) oder die Meldungen der Prüfung (dann bleibt alles unverändert).
*/
commitGrip(base: Project, req: object, coalesceKey: string | undefined, now: number): { project: Project; ops: CoreOp[]; notice?: string } | { problems: string[] } {
this.ensure(base);
if (!this.handle) return { problems: ["Projekt-Dokument im Kern nicht offen."] };
const out = core().doc_grip_commit(this.handle, gripJson(req), coalesceKey ?? "", now);
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
const r = fromMarkedJson<{ ops: CoreOp[]; notice?: string } | { problems: string[] }>(out);
if ("problems" in r) return r;
if (r.ops.length === 0) return { project: base, ops: r.ops, notice: r.notice };
const extra = this.lastExtra();
const project = this.withExtra(applyOps(base, r.ops, core().doc_last_hits(this.handle)), extra);
const ops = extra.length ? [...r.ops, ...extra] : r.ops;
this.setMirror(project, ops);
return { project, ops, notice: r.notice };
}
/**
* Wie {@link queryRoot} für Abfragen, deren Antwort nicht endliche Zahlen als Marken trägt
* (`selectionInfo`, `drawingBBoxes`); die Marken werden wieder Zahlen.
*/
queryRootMarked<T>(name: "selectionInfo" | "drawingBBoxes" | "verticalExtents", text = ""): T {
if (!this.handle) throw new Error(`Kern-Abfrage „${name}": Dokument nicht offen`);
const out = core().doc_query_root(this.handle, name, text);
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
return fromMarkedJson<T>(out);
}
/** Wie {@link commitGrip}, aber nur rechnen (ohne Anwenden): die Ops und ggf. der Hinweis. */
gripOps(req: object): { ops: CoreOp[]; notice?: string } {
if (!this.handle) throw new Error("Kern-Abfrage „gripOps“: Dokument nicht offen");
const out = core().doc_query_root(this.handle, "gripOps", gripJson(req));
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
return fromMarkedJson(out);
}
/**
* Ops eines Befehls ([K4] S3, `commands.rs`): `req` = `{cmd, …}` (Zahlen dürfen NaN/±∞ sein), gerechnet
* auf dem Stand des Dokuments (ohne Anwenden). Nicht endliche Ergebnisse kommen als Zahlen zurück.
*/
cmdOps(req: object): CoreOp[] {
if (!this.handle) throw new Error("Kern-Abfrage „cmdOps“: Dokument nicht offen");
const out = core().doc_query_root(this.handle, "cmdOps", toMarkedJson(req));
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
return fromMarkedJson<{ ops: CoreOp[] }>(out).ops;
}
/**
* Befehl rechnen und anwenden ([K4] S3, `doc_cmd_commit`): wie {@link commitGrip} — ein Kern-Aufruf
* statt Ops hin (Rechnung) und zurück (Commit). Ergebnis: neues Projekt und die angewendeten Ops (leer
* = nichts zu tun, dann `project === base`), ein Hinweis-Schlüssel (i18n, z. B. [144] Öffnung an der
* Nachbaröffnung angehalten) oder die Meldungen der Prüfung.
*/
commitCmd(base: Project, req: object, coalesceKey: string | undefined, now: number): { project: Project; ops: CoreOp[]; notice?: string } | { problems: string[] } {
this.ensure(base);
if (!this.handle) return { problems: ["Projekt-Dokument im Kern nicht offen."] };
const out = core().doc_cmd_commit(this.handle, toMarkedJson(req), coalesceKey ?? "", now);
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
const r = fromMarkedJson<{ ops: CoreOp[]; notice?: string } | { problems: string[] }>(out);
if ("problems" in r) return r;
if (r.ops.length === 0) return { project: base, ops: r.ops, notice: r.notice };
const extra = this.lastExtra();
const project = this.withExtra(applyOps(base, r.ops), extra);
const ops = extra.length ? [...r.ops, ...extra] : r.ops;
this.setMirror(project, ops);
return { project, ops, notice: r.notice };
}
/**
* Kern-Aufruf, der Ops rechnet und gleich als Benutzer-Änderung anwendet (Importe, [K4] S4): `call`
* bekommt das Handle und liefert `{ops, …}`, `{problems}` oder einen Fehlertext mit `\u0001` vorn (wirft).
* Die Leseansicht wird mit den angewendeten Ops nachgeführt; die übrigen Felder kommen unverändert zurück.
*/
private commitCore<R extends object>(base: Project, call: (h: number) => string): ({ project: Project; ops: CoreOp[] } & R) | { problems: string[] } {
this.ensure(base);
if (!this.handle) return { problems: ["Projekt-Dokument im Kern nicht offen."] };
const out = call(this.handle);
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
const r = fromMarkedJson<({ ops: CoreOp[] } & R) | { problems: string[] }>(out);
if ("problems" in r) return r;
const extra = r.ops.length ? this.lastExtra() : [];
const project = r.ops.length ? this.withExtra(applyOps(base, r.ops), extra) : base;
const ops = extra.length ? [...r.ops, ...extra] : r.ops;
this.setMirror(project, ops);
this.rememberCommit(base, project, ops);
return { ...r, ops, project };
}
/**
* Zeichnungs-Import (DXF/DWG/PDF, [K4] S4): der Kern wandelt die gelesene Datei (`src`, Puffer des
* Format-Moduls) nach der Entscheidung des Dialogs in Ops (Zeichnungsebene, Kategorien je Layer,
* Linienstile, 2D-Zeichnungen, Kontext-Meshes) und wendet sie als EINEN Undo-Schritt an.
*/
importDrawing(base: Project, src: ImportSource, decision: DrawingImportDecision, now: number) {
return this.commitCore<{ levelId: string; drawings: number; meshes: number; terrainContours: number }>(base, (h) =>
core().doc_import_drawing(h, src.geom, JSON.stringify(src.strings), JSON.stringify(src.source), JSON.stringify(decision), "", now),
);
}
/** IFC-Import ([B3]/[B4], [K4] S4): Kontext-Meshes bzw. (`opts.elements`) Bauteile, ein Undo-Schritt. */
importIfc(base: Project, flat: IfcFlatInput, opts: { fileName: string; group?: string; elements?: boolean }, now: number) {
return this.commitCore<IfcImportResult>(base, (h) =>
core().doc_import_ifc(h, flat.meta, flat.positions, flat.indices, flat.elementData ?? new Float64Array(0), JSON.stringify(opts), "", now),
);
}
/** Mesh-Import (OBJ/STL/glTF/PLY, [C11], [K4] S4): Kontext-Meshes, ein Undo-Schritt. */
importMesh(base: Project, flat: { flat: Float64Array; strings: string[] }, opts: { fileName: string; placement?: string; group?: string }, now: number) {
return this.commitCore<{ report: MeshImportReport; contextObjects: number }>(base, (h) =>
core().doc_import_mesh(h, flat.flat, JSON.stringify(flat.strings), JSON.stringify(opts), "", now),
);
}
/** STEP-Import (truck → Kern, [K4] S4): ein Kontext-Mesh je Körper, ein Undo-Schritt. */
importStep(base: Project, flat: Float64Array, opts: { fileName: string }, now: number) {
return this.commitCore<{ contextObjects: number }>(base, (h) => core().doc_import_step(h, flat, JSON.stringify(opts), "", now));
}
/** Abfrage eines Befehls zwischen den Schritten (`doc_cmd_query`: Treffer, Vorschau-Formen), JSON-Antwort. */
cmdQuery<T>(req: object): T {
if (!this.handle) throw new Error("Kern-Abfrage „cmdQuery“: Dokument nicht offen");
const out = core().doc_cmd_query(this.handle, toMarkedJson(req));
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
return fromMarkedJson<T>(out);
}
/**
* Vorschau eines Zeichenbefehls (`doc_create_preview`, `cmd_create.rs`): `reqJson` = Optionen (mit
* Nicht-endlich-Marken; `null` = dieselben wie beim letzten Aufruf), `pts` flach; Antwort
* `[ok, nInfo, info…, Formen…]`.
*/
createPreview(reqJson: string | null, pts: Float64Array): Float64Array {
if (!this.handle) return new Float64Array(0);
return reqJson === null ? core().doc_create_preview_again(this.handle, pts) : core().doc_create_preview(this.handle, reqJson, pts);
}
/** Treffer-Abfrage eines Zeichenbefehls (`doc_create_query`), JSON-Antwort. */
createQuery<T>(req: object): T {
if (!this.handle) throw new Error("Kern-Abfrage „createQuery“: Dokument nicht offen");
const out = core().doc_create_query(this.handle, toMarkedJson(req));
if (out.startsWith("\u0001")) throw new Error(out.slice(1));
return fromMarkedJson<T>(out);
}
/** Vorschau-Formen eines Befehls (`doc_cmd_preview`): flach je Form `[art, n, x0, y0, …]`. */
cmdPreview(req: object): Float64Array {
return this.handle ? core().doc_cmd_preview(this.handle, toMarkedJson(req)) : new Float64Array(0);
}
/** Einen Schritt zurück auf `base` (= aktuelles Projekt); `null` = nichts rückgängig zu machen. */
undo(base: Project): Project | null {
return this.jump(base, "doc_undo");
}
/** Einen Schritt vor; `null` = nichts wiederherzustellen. */
redo(base: Project): Project | null {
return this.jump(base, "doc_redo");
}
private jump(base: Project, fn: "doc_undo" | "doc_redo"): Project | null {
if (base !== this.mirror || !this.handle) {
this.ensure(base);
return null;
}
const undo = fn === "doc_undo";
const top = this.historySeqs()[undo ? 0 : 1];
// Grosser Schritt, dessen Stände TS noch hält: der Kern wendet ihn an, ohne Ops zurückzugeben.
if (this.steps.has(top)) {
if (!core().doc_jump_quiet(this.handle, !undo)) return null;
const project = this.steps.jump(top, base, undo, this.historySeqs()[undo ? 1 : 0]);
this.setMirror(project, null);
return project;
}
const json = core()[fn](this.handle);
if (!json) return null;
const ops = JSON.parse(json) as CoreOp[];
const project = applyOps(base, ops, core().doc_last_hits(this.handle));
this.setMirror(project, ops);
// Gegenschritt (neu oben auf dem anderen Stapel) führt zwischen denselben Ständen.
const next = this.historySeqs()[undo ? 1 : 0];
if (undo) this.steps.remember(next, project, base, ops);
else this.steps.remember(next, base, project, ops);
return project;
}
/** Springt im Verlauf auf Undo-Tiefe `target` (mehrere Schritte, ein Kern-Aufruf); `null` = schon dort/ausserhalb. */
jumpTo(base: Project, target: number): Project | null {
if (base !== this.mirror || !this.handle) {
this.ensure(base);
return null;
}
const json = core().doc_history_jump(this.handle, target);
if (!json) return null;
const ops = JSON.parse(json) as CoreOp[];
const project = applyOps(base, ops, core().doc_last_hits(this.handle));
this.setMirror(project, ops);
return project;
}
/** Beschriftung (i18n-Schlüssel oder Text) für den nächsten neu angelegten Undo-Schritt; leer = keine. */
setHistoryLabel(label: string): void {
if (this.handle) core().doc_history_label(this.handle, label);
}
/** Beschriftungen der Verlaufsschritte: Undo (ältester zuerst) und Redo (nächster zuerst). */
historyLabels(): { undo: string[]; redo: string[] } {
const json = this.handle ? core().doc_history_labels(this.handle) : "";
return json ? (JSON.parse(json) as { undo: string[]; redo: string[] }) : { undo: [], redo: [] };
}
/** Laufnummern der obersten Verlaufsschritte `[Undo, Redo, letzte Aufzeichnung verschmolzen]`. */
private historySeqs(): number[] {
return this.handle ? Array.from(core().doc_history_seq(this.handle)) : [0, 0, 0];
}
/** Nach einer angenommenen Änderung: grossen, eigenen (nicht verschmolzenen) Schritt merken. */
/**
* Nachführ-Ops des letzten Commits ([38], assoziative Bemassung): der Kern hat sie im selben
* Undo-Schritt angewendet, die Leseansicht übernimmt sie hinter den eigenen Ops.
*/
private lastExtra(): CoreOp[] {
const json = this.handle ? core().doc_last_extra(this.handle) : "";
return json ? (JSON.parse(json) as CoreOp[]) : [];
}
private withExtra(project: Project, extra: readonly CoreOp[]): Project {
return extra.length ? applyOps(project, extra) : project;
}
private rememberCommit(base: Project, project: Project, ops: readonly CoreOp[]): void {
const [seq, , merged] = this.historySeqs();
if (!merged) this.steps.remember(seq, base, project, ops);
}
/** Verlaufsstand: Undo-/Redo-Tiefe und geschätzter Speicher (Bytes). */
historyState(): { undo: number; redo: number; bytes: number } {
const s = this.handle ? core().doc_history_state(this.handle) : new Float64Array(0);
return { undo: s[0] ?? 0, redo: s[1] ?? 0, bytes: s[2] ?? 0 };
}
clearHistory(): void {
this.steps.clear();
if (this.handle) core().doc_history_clear(this.handle);
this.hist.sync(this.handle, this.mirror);
}
/** Grenzen des Verlaufs (Schritte, ungefähre Bytes). */
setHistoryLimits(steps: number, bytes: number): void {
this.limits = [steps, bytes];
if (this.handle) core().doc_history_limits(this.handle, steps, bytes);
}
/** Gruppe: alle Änderungen bis {@link endGroup} werden ein Undo-Schritt (verschachtelbar). */
beginGroup(): void {
if (this.handle) core().doc_group_begin(this.handle);
}
/**
* Wie {@link beginGroup}, mit `coalesceKey` (+ `now` in ms): aufeinanderfolgende Gruppen mit
* gleichem Schlüssel im Zeitfenster schliessen an denselben Undo-Schritt an (Griff-Zug, der je
* Mausschritt mehrere Elemente bewegt), [K4] S3.
*/
beginKeyedGroup(coalesceKey: string, now: number): void {
if (this.handle) core().doc_group_begin_keyed(this.handle, coalesceKey, now);
}
endGroup(): void {
if (this.handle) core().doc_group_end(this.handle);
this.hist.sync(this.handle, this.mirror);
}
}
/** Alle Dokumente (schwach gehalten), die nach einem Kern-Neustart neu geöffnet werden. */
const liveDocs = new Set<WeakRef<ProjectDocument>>();
registerCoreRestore(() => {
for (const r of liveDocs) {
const doc = r.deref();
if (!doc) liveDocs.delete(r);
else
try {
doc.restoreAfterRestart();
} catch (e) {
// Bleibt zu (Handle 0) und öffnet sich beim nächsten Gebrauch neu (`ensure`/`load`).
console.error("Kern-Dokument nach Neustart nicht wieder geöffnet.", e);
}
}
});
/** Griff-Anfrage als JSON; Marken nur bei nicht endlichen Zahlen (der Ersetzer kostet je Wert einen Aufruf). */
function gripJson(req: object): string {
for (const v of Object.values(req)) {
const bad = typeof v === "number" ? !Number.isFinite(v) : Array.isArray(v) && v.some((x) => typeof x === "number" && !Number.isFinite(x));
if (bad) return toMarkedJson(req);
}
return JSON.stringify(req);
}
let shared: ProjectDocument | null = null;
/**
* Das Dokument des CLI (ohne Verlauf): eine dort geladene Datei ({@link ProjectDocument.loadFile})
* ist sofort das Dokument der Abfragen auf ihrem Projekt (s. {@link documentFor}).
*/
export function sharedDocument(): ProjectDocument {
if (!shared) shared = new ProjectDocument({} as Project);
return shared;
}
/** Dokument des Stores (mit Verlauf); Abfragen auf dessen aktuellem Projekt laufen direkt darüber. */
let primary: ProjectDocument | null = null;
/** Meldet das Dokument des Stores an (s. {@link documentFor}). */
export function setPrimaryDocument(doc: ProjectDocument | null): void {
primary = doc;
}
/** Ausdrücklich geöffnete, kurzlebige Dokumente ({@link withDocument}), innerste zuletzt. */
const scoped: ProjectDocument[] = [];
/** Offenes Dokument, dessen Leseansicht `project` ist (Store, CLI, {@link withDocument}). */
function lookup(project: Project): ProjectDocument | null {
if (primary && primary.current === project && primary.id) return primary;
for (let i = scoped.length - 1; i >= 0; i--) if (scoped[i].current === project && scoped[i].id) return scoped[i];
if (shared && shared.current === project && shared.id) return shared;
return null;
}
/**
* Rechnet `run` auf einem eigenen, kurzlebigen Dokument von `project` (z. B. Export einer gefilterten
* Kopie): voll geöffnet, ohne Abgleich; Abfragen auf `project` (`documentFor`) treffen es, solange
* `run` läuft (auch über `await`), danach wird es geschlossen. Ist `project` schon offen (Store),
* läuft `run` direkt auf jenem Dokument.
*/
export function withDocument<T>(project: Project, run: (doc: ProjectDocument) => T): T {
const known = lookup(project);
if (known) return run(known);
const doc = new ProjectDocument(project);
if (!doc.id) throw new Error("Projekt-Dokument im Kern konnte nicht geöffnet werden.");
scoped.push(doc);
const done = () => {
scoped.splice(scoped.indexOf(doc), 1);
doc.close();
};
let out: T;
try {
out = run(doc);
} catch (e) {
done();
throw e;
}
if (out instanceof Promise) return out.finally(done) as T;
done();
return out;
}
/** Ohne Store (Tests, Skripte): Dokument des zuletzt gefragten fremden Projekts, als Ganzes geladen. */
let detached: ProjectDocument | null = null;
/** Zähler der Ganz-Ladungen ausserhalb der offenen Dokumente (Messung, Tests: heisser Pfad = 0). */
let detachedLoads = 0;
export function detachedLoadCount(): number {
return detachedLoads;
}
const ENV = (import.meta as unknown as { env?: Record<string, unknown> }).env;
/** Entwicklung und Tests: ein Projekt ohne offenes Dokument neben dem Store ist ein Fehler. */
const STRICT = !!ENV?.DEV || ENV?.MODE === "test";
/**
* Das Kern-Dokument, dessen Leseansicht `project` ist: das des Stores (aktueller Stand), des CLI
* oder eines {@link withDocument}. Es gibt keinen versteckten Abgleich mehr ([122]): wer ein
* abgewandeltes Projekt abfragen will, öffnet es ausdrücklich ({@link withDocument}) oder gibt der
* Kern-Abfrage einen Filter mit (z. B. Fang ohne gezogene Elemente, `holdModelSnap`).
*
* Ohne Store-Dokument (Unit-Tests, Skripte, Musterhaus-Bau) wird ein fremdes Projekt als Ganzes in
* ein eigenes Dokument geladen (kein Abgleich, jede neue Identität = volles Laden). Mit Store-Dokument
* ist ein fremdes Projekt ein Fehler: in Entwicklung/Tests wirft es, im Produkt meldet es und lädt.
*/
export function documentFor(project: Project): ProjectDocument {
const known = lookup(project);
if (known) return known;
if (primary && primary.id) {
const msg = "documentFor: Projekt ist weder der Stand des Store-Dokuments noch ausdrücklich geöffnet (withDocument).";
if (STRICT) throw new Error(msg);
console.error(msg);
}
if (!detached) {
detached = new ProjectDocument(project);
detachedLoads++;
} else if (detached.current !== project || !detached.id) {
detached.load(project);
detachedLoads++;
}
if (!detached.id) throw new Error("Projekt-Dokument im Kern konnte nicht geöffnet werden.");
return detached;
}
/**
* Änderung als Befehls-Anfrage an den Kern ([K4] S3, `commands.rs`): `toOps` rechnet die Ops auf dem
* Dokument des Projekts; der Store wendet `coreReq` direkt im Kern an (`ProjectDocument.commitCmd`).
*/
export function cmdMutation(req: object): ProjectMutation {
return Object.assign(opsMutation((p) => documentFor(p).cmdOps(req)), { coreReq: req });
}