From ce0d9950d0faecc8238be4f8df275fa8297661d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 09:36:23 +0000 Subject: [PATCH] [K3d][K4] Text-Layout im Kern: Raumstempel, Rich-Text, Umbruch, Text-Rahmen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Neu `core/src/text_layout.rs` (Rich-Text → Zeilen/Tspans, Wortumbruch, Raumstempel-Block, einfacher Umbruch, Text-Rahmen, fontNameOf) und `core/src/plan_text.rs` (Texte aus dem Text-JSON des Plan-Puffers). Render-Szene, DXF und Druck-SVG setzen die Texte selbst beim Massstab der Ausgabe; TS übergibt kein Layout mehr. renderHtml.ts/textFrame.ts sind dünne Fassaden. Gelöscht: planSceneTexts, stampLines/textInput, drawingTextNode, runToTspan und Umbruch in TS, dxfCadParts.ts, texts_from (Szene, DXF). Gleichheit alt/neu (temporäre Tests, entfernt): 288 Pläne Szene/DXF/Druck-SVG, 600 Layouts, 3000 Stempel-Blöcke/Umbrüche, 230 CLI-Dateien byte-gleich. --- TODO.md | 29 ++ src-tauri/core/src/lib.rs | 2 + src-tauri/core/src/plan_dxf.rs | 99 +--- src-tauri/core/src/plan_print_svg.rs | 112 ++++- src-tauri/core/src/plan_scene.rs | 18 +- src-tauri/core/src/plan_text.rs | 300 ++++++++++++ src-tauri/core/src/text_layout.rs | 635 +++++++++++++++++++++++++ src-tauri/core/src/web/mod.rs | 1 + src-tauri/core/src/web/plan_dxf.rs | 28 +- src-tauri/core/src/web/plan_scene.rs | 37 +- src-tauri/core/src/web/text_layout.rs | 124 +++++ src/export/dxfCadParts.test.ts | 13 - src/export/dxfCadParts.ts | 16 - src/export/exportDxf.ts | 98 +--- src/export/planToPrintSvg.ts | 131 ++--- src/plan/planParts.ts | 8 +- src/plan/toRenderScene.ts | 208 ++------ src/text/renderHtml.ts | 207 ++++---- src/text/textFrame.ts | 53 +-- src/views/plan/planView/primitives.tsx | 57 +-- 20 files changed, 1456 insertions(+), 720 deletions(-) create mode 100644 src-tauri/core/src/plan_text.rs create mode 100644 src-tauri/core/src/text_layout.rs create mode 100644 src-tauri/core/src/web/text_layout.rs delete mode 100644 src/export/dxfCadParts.test.ts delete mode 100644 src/export/dxfCadParts.ts diff --git a/TODO.md b/TODO.md index f82bfe5f..3204fb8f 100644 --- a/TODO.md +++ b/TODO.md @@ -264,6 +264,35 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern Bleibt: der native macOS-Pfad (`useNativePlanRenderer`/`GpuChunkCache`) liest die Liste weiter (nicht in der Tauri-App geprüft); SVG-Rückfall ohne GPU, Geschoss-Überlagerung mit gedimmten Ebenen (`materializeGreyed`), Gruppen-Isolation, Schnitt/Ansicht-Overlays in `viewportContent` und Abzugskörper/Mono/Massstab lesen die Liste (dann wie bisher). + ✅ (29.10.) **Text-Layout im Kern** ([K3d]/[K4]): `core/src/text_layout.rs` (Rich-Text → Zeilen/Tspans, Run-Stile inkl. + Hoch-/Tiefstellung, Wortumbruch auf Spaltenbreite, Raumstempel-Block, einfacher Umbruch, Text-Rahmen, `fontNameOf`) und + `core/src/plan_text.rs` (Raumstempel/Einzeltexte aus dem Text-JSON des Plan-Puffers). Die Kern-Verbraucher setzen die Texte + selbst beim Massstab der Ausgabe: Render-Szene (`plan_scene_bin(segs, greyed, N)`, neu `plan_scene_texts` für + `planToRenderScene`), DXF/DWG (`plan_dxf_flat` ohne Text-Eingabe, Standard-Schrift aus den Projekt-Textstilen), Druck-SVG + (Einzeltexte als Anweisungen `X`/`L`/`R` statt `T` + TS-Layout). TS übergibt kein Layout mehr; gelöscht: `planSceneTexts`, + `stampLines`/`textInput` (DXF), `drawingTextNode` (Druck-SVG), `runToTspan`/Umbruch in `renderHtml.ts`, die Schätzung in + `textFrame.ts`, `dxfCadParts.ts` (+ Test, `fontNameOf` → Rust), `texts_from` (Szene, DXF). `renderHtml.ts` + (`docToLines`/`wrapDocToLines`/`stampBlockLines`/`wrapPlainText`) und `textFrame.ts` sind dünne Fassaden (Ergebnis flach, + Tspan-Texte als Ausschnitte der Eingabe, je Dokument-Objekt gemerkt) für SVG-Rückfall der PlanView, Layout-Blatt, + Layout-PDF und Griffe. Der eigene Plan-Puffer trägt Text-JSON jetzt immer (auch für die Szene). + Glyphen-Metrik: es gibt keine — wie bisher geschätzt (UTF-16-Länge × Grösse × 0.55); keine Schriftdateien, kein + Canvas-Messen im Layout (nur `fontMetrics.ts` misst für die Inline-Editoren Grundlinie → Oberkante, bleibt TS). + Gleichheit (temporäre Tests alt gegen neu, danach entfernt; alter Stand = Kern + TS des Hauptstands im selben Lauf): + 288 Pläne × Szene (Texte + Binär-md5), DXF-Zahlen und -Zeichenketten, Druck-SVG (DOM serialisiert) — 6 Projekte mit + Raumstempeln aller Varianten (Feldmodell mit Nummer/Zeile 2/Flächen-Präfix/Nutzung/Ausrichtungen/Personen/Rundung, + `stampDoc`, Name) und 60 Einzeltexten (Rich-Text mit gemischten Stilen, Hoch-/Tiefstellung, Absatz-Zeilenhöhen, + Spalten, Drehungen, Umlaute/Emoji/CJK/NBSP/U+0085/BOM, `\r\n`) × EG/OG × 1:50/1:100/mono × Ausgabe 1:50/100/200, + dazu 60 Zufallspläne mit Text-Primitiven (gedimmt, Deckkraft, gedimmte Bereiche): 57 527 Szenen-Zeilen, 9 741 Druck-Texte + gleich; 600 Dokumente `docToLines`/`wrapDocToLines` + 600 Text-Rahmen gleich; 3000 Raumstempel-Blöcke und einfache + Umbrüche der PlanView gleich; CLI `plan` (svg/json), `dxf` (1:50/100/200, `--binary --layout --dim-unit cm`), `dwg` für + Beispiel, Kataster- und Klein-DXF-Import sowie zwei Rich-Text-Projekte: 230 Dateien byte-gleich. Einzige Abweichung: + `−0` in TS-erzeugten Text-Primitiven (nicht aus dem Kern-Puffer) wird über JSON zu `0` (nur DXF-Zahlen, nur Zufallspläne). + Messung (Node, `--no-opt`, Linux-Container unter Last; 3000 Einzeltexte + 400 Raumstempel): `planSceneBin` 44–70 → + 47–66 ms (gleich), DXF-Sammler 67–91 → 42–58 ms, `planToRenderScene` (nur Export) 20–36 → 56–78 ms (JSON der Texte im + Kern lesen); Fassade `wrapDocToLines` ungemerkt ~7 → ~28 µs je Aufruf (JSON hin, flache Zeilen zurück), gemerkt < 1 µs. + Gefunden, bewusst unverändert: im Druck-SVG (Layout-Viewports) tragen die Runs der Einzeltexte `font-size` = Höhe in + Metern statt Papier-mm (alte TS-Formel `basePt · unitPerPt`); offen als eigener Fehler. + Nicht in der Tauri-App angesehen (nativer Text-Pfad `nativeText.ts` unverändert). Nachteile (bewusst): Übergang mit doppelter Datenhaltung, Format muss TS/Rust gleich bleiben (Versionsnummer + Hin-und-zurück-Tests), Text-Layout bleibt bis [K4] in TS. - ◐ **[K4] Modell und Ops in Rust** [2]; TS bekommt die Typen generiert (z. B. `ts-rs`). · XL diff --git a/src-tauri/core/src/lib.rs b/src-tauri/core/src/lib.rs index 9ec7952f..44f1539a 100644 --- a/src-tauri/core/src/lib.rs +++ b/src-tauri/core/src/lib.rs @@ -83,6 +83,8 @@ pub mod selection_filter; pub mod reorder; pub mod ugrid; pub mod wasm_alloc; +pub mod text_layout; +pub mod plan_text; #[cfg(feature = "web")] mod web; diff --git a/src-tauri/core/src/plan_dxf.rs b/src-tauri/core/src/plan_dxf.rs index eb6b2ad8..23c8bb1e 100644 --- a/src-tauri/core/src/plan_dxf.rs +++ b/src-tauri/core/src/plan_dxf.rs @@ -7,9 +7,9 @@ //! //! Gleiche Eingabe ⇒ dieselben Zahlen und Zeichenketten in derselben Reihenfolge wie die TS-Fassung //! (Zeichenketten-Indizes nach erstem Gebrauch, Definitionen an der Stelle ihres ersten Gebrauchs). -//! Text-Layout bleibt TS: die Zeilen der Raumstempel und die Absätze/Wörter der Einzeltexte kommen -//! fertig mit ([`TextIn`]); der Zeilenumbruch nach Spaltenbreite läuft hier (er hängt in Blöcken -//! an der blocklokalen Grösse). +//! Texte: die Zeilen der Raumstempel und die Absätze/Wörter der Einzeltexte setzt der Kern aus dem +//! Text-JSON des Puffers ([`crate::plan_text::dxf_text`] → [`TextIn`]); der Zeilenumbruch nach +//! Spaltenbreite läuft hier (er hängt in Blöcken an der blocklokalen Grösse). use crate::hatch::{self, Hatch, HatchKind, Motif, Pattern, V2}; use crate::js_fmt::{js_number, to_fixed}; @@ -78,11 +78,11 @@ pub struct DxfOptions { pub paper_layout: bool, /// Ausmass des Plans (`Plan.bounds`) für den Papierbereich. pub bounds: [f64; 4], - /// Standard-Schrift (erste Schrift der Projekt-Textstile, sonst Arial; in TS aufgelöst). + /// Standard-Schrift (erste Schrift der Projekt-Textstile, sonst Arial; [`crate::plan_text::default_font`]). pub default_font: String, } -/// Schrift eines Texts (in TS aufgelöst: Familie nach `fontNameOf`, sonst Standard-Schrift). +/// Schrift eines Texts (Familie nach `font_name_of`, sonst Standard-Schrift). #[derive(Clone, Debug, PartialEq)] pub struct TextStyleIn { pub family: String, @@ -102,7 +102,7 @@ pub struct StampLine { pub down: f64, } -/// Text-Eingabe aus TS je Plan-Index (Layout bleibt TS). +/// Text-Eingabe je Text-Eintrag (aus dem Text-JSON gesetzt, s. [`crate::plan_text::dxf_text`]). #[derive(Clone, Debug, PartialEq)] pub enum TextIn { /// `text` (Raumstempel): Anker und Zeilen. @@ -758,25 +758,13 @@ fn to_local(p: &Prim, f: Frame) -> Option { } /// Zeilen eines Einzeltexts (`drawingTextLines`): Absätze, bei Spaltenbreite wortweise umbrochen -/// (Zeichenzahl in UTF-16-Einheiten wie `String.length`); Zeilenabstand 1.25 × Höhe. +/// (`text_layout::wrap_words`, Zeichenzahl in UTF-16-Einheiten); Zeilenabstand 1.25 × Höhe. fn single_lines(height: f64, wrap: f64, paras: &[(String, Vec)]) -> Vec<(String, f64)> { let mut lines: Vec = Vec::new(); if wrap > 0.0 { - let max_chars = jsnum::max(1.0, (wrap / (height * 0.55)).floor()); - let ulen = |s: &str| s.encode_utf16().count() as f64; + let m = crate::text_layout::max_chars(wrap, height); for (_, words) in paras { - let mut line = String::new(); - for word in words { - if line.is_empty() { - line = word.clone(); - } else if ulen(&line) + 1.0 + ulen(word) <= max_chars { - line.push(' '); - line.push_str(word); - } else { - lines.push(std::mem::replace(&mut line, word.clone())); - } - } - lines.push(line); + crate::text_layout::wrap_words(words, m, &mut lines); } } else { lines.extend(paras.iter().map(|p| p.0.clone())); @@ -1115,17 +1103,16 @@ fn flatten<'a>(cats: &'a [LayerCategory], out: &mut Vec<&'a LayerCategory>) { } } -/// Sammelt die flache Zeichnung aus den Abschnitten des Plans (`texts`: Text-Eingabe je -/// Plan-Index). `None` bei kaputtem Puffer. -pub fn collect(parts: &mut [Part], texts: &HashMap, project: &Project, o: &DxfOptions) -> Option { +/// Sammelt die flache Zeichnung aus den Abschnitten des Plans (Texte aus ihrem JSON). `None` bei +/// kaputtem Puffer. +pub fn collect(parts: &mut [Part], project: &Project, o: &DxfOptions) -> Option { // Primitive in Plan-Reihenfolge lesen. let mut entries: Vec = Vec::new(); - let mut gi = 0usize; for part in parts.iter_mut() { let hatches = part.view.hatch_table()?; for i in part.from..part.to { - entries.push(read_entry(part, i, &hatches, texts.get(&gi))?); - gi += 1; + let text = crate::plan_text::read_text(part, i).map(|t| crate::plan_text::dxf_text(&t, o.scale, &o.default_font)); + entries.push(read_entry(part, i, &hatches, text.as_ref())?); } } @@ -1299,64 +1286,6 @@ pub fn collect(parts: &mut [Part], texts: &HashMap, project: &Pro Some(FlatDxf { nums: root, strings, model: main.counts, blocks: block_counts }) } -/// Text-Eingabe aus TS lesen: Zahlen `[Index, Art, …]` (s. `src/export/exportDxf.ts`), Texte. -/// Art 6 (Raumstempel): `[x, y, nZeilen, (Text, Höhe, Ausrichtung, Schrift, fett, kursiv, ab)*]`; -/// Art 7 (Einzeltext): `[x, y, Winkel, Höhe, Spalte, Schrift, fett, kursiv, nAbsätze, -/// (Absatz, nWörter, Wort*)*]`. Schrift/Text = Index in `strs`. -pub fn texts_from(nums: &[f64], strs: &[&str]) -> Option> { - let mut out = HashMap::new(); - let mut k = 0usize; - let mut next = || -> Option { - let v = *nums.get(k)?; - k += 1; - Some(v) - }; - let s_of = |v: f64| -> Option { strs.get(whole(v)?).map(|s| s.to_string()) }; - loop { - let Some(idx) = next() else { break }; - let idx = whole(idx)?; - let kind = next()?; - let at = V2 { x: next()?, y: next()? }; - if kind == 6.0 { - let n = whole(next()?)?; - let mut lines = Vec::with_capacity(n.min(1024)); - for _ in 0..n { - let text = s_of(next()?)?; - let height = next()?; - let align = next()?; - let family = s_of(next()?)?; - let bold = next()? != 0.0; - let italic = next()? != 0.0; - let down = next()?; - lines.push(StampLine { text, height, align, style: TextStyleIn { family, bold, italic }, down }); - } - out.insert(idx, TextIn::Stamp { at, lines }); - } else if kind == 7.0 { - let angle = next()?; - let height = next()?; - let wrap = next()?; - let family = s_of(next()?)?; - let bold = next()? != 0.0; - let italic = next()? != 0.0; - let n = whole(next()?)?; - let mut paras = Vec::with_capacity(n.min(1024)); - for _ in 0..n { - let para = s_of(next()?)?; - let nw = whole(next()?)?; - let mut words = Vec::with_capacity(nw.min(1024)); - for _ in 0..nw { - words.push(s_of(next()?)?); - } - paras.push((para, words)); - } - out.insert(idx, TextIn::Single { at, angle, height, wrap, style: TextStyleIn { family, bold, italic }, paras }); - } else { - return None; - } - } - Some(out) -} - /// Ergebnis als Bytes: f64-Teil `[MAGIC "DXF1", nZahlen, nTexte, 8 Modell-, 8 Block-Zähler, /// Zahlen…, Länge je Text…]`, danach die Texte als UTF-16. pub fn encode(f: &FlatDxf) -> Vec { diff --git a/src-tauri/core/src/plan_print_svg.rs b/src-tauri/core/src/plan_print_svg.rs index d7384bcf..26bafa99 100644 --- a/src-tauri/core/src/plan_print_svg.rs +++ b/src-tauri/core/src/plan_print_svg.rs @@ -5,21 +5,29 @@ //! `String(Math.round(v * 1000) / 1000)`). Schraffuren als geklippte Vektorlinien, Zickzack/Motiv als //! Polylinie, Bögen als ``. //! -//! In TS bleiben: der ``-Rahmen und das weisse Blatt, die Bild-Schraffur-`` (laufende -//! Ids im Dokument) und die Einzeltexte (Text-Layout `wrapDocToLines`). Dafür stehen Anweisungen in -//! der Liste. +//! In TS bleiben: der ``-Rahmen und das weisse Blatt und die Bild-Schraffur-`` +//! (laufende Ids im Dokument). Die Einzeltexte setzt der Kern (`crate::text_layout`, Zeilen als +//! `` je Zeile mit je einem `` je Run/Wort). //! //! Format: Datensätze getrennt durch `\x1e`, Felder durch `\x1f`: //! - `E`, Ebene (0 = ins ``, 1 = in die offene Gruppe), Tag, dann Name/Wert-Paare; //! - `G`, Deckkraft (leer = keine) — öffnet eine ``; `g` schliesst sie (hängt sie ans ``); //! - `I`, Punkte-Attribut, Bild-JSON — Bild-Schraffur: `` anlegen und ein Polygon damit füllen; -//! - `T`, Plan-Index, Deckkraft — Einzeltext an dieser Stelle. +//! - `X`, Name/Wert-Paare — `` ins `` (wird der offene Text); +//! - `L`, Inhalt (leer = keiner), Name/Wert-Paare — Zeilen-`` in den offenen Text (wird die +//! offene Zeile); +//! - `R`, Inhalt, Name/Wert-Paare — Run-`` in die offene Zeile. +//! +//! Texte, die selbst `\x1e`/`\x1f` enthalten, zerfallen dabei (Steuerzeichen kommen in Plantexten +//! nicht vor). use crate::hatch::{self, Hatch, Motif, Pattern, V2}; use crate::js_fmt::js_number; use crate::jsnum; use crate::plan_buf::{whole, Rec, View, F_COLOR, F_DASH_NULL, F_OPACITY, T_ARC, T_CIRCLE, T_DRAWING_ARC, T_DRAWING_TEXT, T_IMAGE, T_LINE, T_POLYGON}; use crate::plan_parts::{greyed_of, Part}; +use crate::plan_text::SingleText; +use crate::text_layout::{wrap_doc_to_lines, LayoutOpts, LineAlign, TEXT_LINE_HEIGHT_MULT}; use std::f64::consts::PI; /// Optionen: Massstab-Nenner, Blatt (mm) und Ausmass des Plans (`Plan.bounds`). @@ -70,6 +78,16 @@ impl Out { self.s.push_str(&fields.join("\u{1f}")); } + /// Datensatz aus festen Feldern und Name/Wert-Paaren. + fn tagged(&mut self, head: &[&str], attrs: &[(&str, String)]) { + let mut f: Vec<&str> = head.to_vec(); + for (k, v) in attrs { + f.push(k); + f.push(v); + } + self.rec(&f); + } + fn el(&mut self, depth: u8, tag: &str, attrs: &[(&str, String)]) { let d = depth.to_string(); let mut f: Vec<&str> = vec!["E", &d, tag]; @@ -243,7 +261,7 @@ fn opacity_of(greyed: bool, obj: f64) -> String { } /// Ein Eintrag als Knoten. -fn entry(out: &mut Out, view: &View, i: usize, gi: usize, hatches: &[(i32, Hatch, i32)], m: Map) -> Option<()> { +fn entry(out: &mut Out, view: &View, i: usize, hatches: &[(i32, Hatch, i32)], m: Map) -> Option<()> { let rec: Rec = view.rec(i)?; let f = &rec.f; let k = m.k; @@ -397,11 +415,14 @@ fn entry(out: &mut Out, view: &View, i: usize, gi: usize, hatches: &[(i32, Hatch out.el(0, "path", &attrs); } T_DRAWING_TEXT | T_IMAGE => { - let j: serde_json::Value = serde_json::from_str(&view.string(whole(f[0])?)?).ok()?; + let js = view.string(whole(f[0])?)?; + let j: serde_json::Value = serde_json::from_str(&js).ok()?; let jg = j.get("greyed").and_then(|g| g.as_bool()).unwrap_or(false); if rec.tag == T_DRAWING_TEXT { let obj = j.get("opacity").and_then(|o| o.as_f64()).unwrap_or(1.0); - out.rec(&["T", &gi.to_string(), &opacity_of(jg, obj)]); + if let Ok(t) = serde_json::from_str::(&js) { + text_node(out, &t, m, opacity_of(jg, obj)); + } } else { let (min, max) = (j.get("min")?, j.get("max")?); let (x0, y0, x1, y1) = (num(min, "x"), num(min, "y"), num(max, "x"), num(max, "y")); @@ -437,6 +458,62 @@ fn entry(out: &mut Out, view: &View, i: usize, gi: usize, hatches: &[(i32, Hatch Some(()) } +/// Einzeltext (Text-Werkzeug/DXF-Import) als `` mit ``-Zeilen (früher +/// `drawingTextNode` in `planToPrintSvg.ts`): Grösse in Papier-mm, bei Spaltenbreite wortweise +/// umbrochen (Run-Grenzen bleiben), gedreht um den Anker. +fn text_node(out: &mut Out, t: &SingleText, m: Map, opacity: String) { + let k = m.k; + let c = m.at(t.at.x, t.at.y); + let unit_per_pt = (0.0254 / 72.0) * k; + let base_pt = if unit_per_pt > 0.0 { t.height_m / unit_per_pt } else { 0.0 }; + let wrap = t.wrap().map(|w| w * k); + let o = LayoutOpts { line_height: t.height_m * k * TEXT_LINE_HEIGHT_MULT, unit_per_pt, base_pt, color: t.color.as_deref().unwrap_or("#000000") }; + let lines = wrap_doc_to_lines(&t.doc(), &o, wrap); + if lines.is_empty() { + return; + } + let mut attrs: Vec<(&str, String)> = Vec::new(); + let deg = -(t.angle * 180.0) / PI; + if deg != 0.0 && !deg.is_nan() { + attrs.push(("transform", format!("rotate({} {} {})", r3(deg), r3(c.x), r3(c.y)))); + } + if !opacity.is_empty() { + attrs.push(("opacity", opacity)); + } + out.tagged(&["X"], &attrs); + // `!wrapWidthUnits`: 0/NaN zählen wie keine Spalte. + let col = wrap.filter(|w| *w != 0.0 && !w.is_nan()); + let mut y = c.y; + for (n, line) in lines.iter().enumerate() { + if n > 0 { + y += line.line_height; + } + let (anchor, x) = match (line.align, col) { + (LineAlign::Center, Some(w)) => ("middle", c.x + w / 2.0), + (LineAlign::Right, Some(w)) => ("end", c.x + w), + (LineAlign::Center, None) => ("middle", c.x), + (LineAlign::Right, None) => ("end", c.x), + (LineAlign::Left, _) => ("start", c.x), + }; + let content = if line.tspans.is_empty() { "\u{200b}" } else { "" }; + out.tagged(&["L", content], &[("x", r3(x)), ("y", r3(y)), ("text-anchor", anchor.to_string())]); + for ts in &line.tspans { + let mut a: Vec<(&str, String)> = vec![("font-size", r3(ts.font_size)), ("fill", ts.fill.clone())]; + if let Some(w) = ts.font_weight() { + a.push(("font-weight", w.to_string())); + } + if let Some(st) = ts.font_style() { + a.push(("font-style", st.to_string())); + } + a.push(("font-family", ts.font_family.clone().unwrap_or_else(|| "Helvetica, Arial, sans-serif".to_string()))); + if let Some(d) = ts.text_decoration { + a.push(("text-decoration", d.to_string())); + } + out.tagged(&["R", &ts.text], &a); + } + } +} + fn empty_hatch() -> Hatch { Hatch { pattern: Pattern::None, @@ -463,12 +540,10 @@ pub fn print_svg_ops(parts: &mut [Part], o: &PrintOptions) -> Option { let content_h = (max_y - min_y) * k; let m = Map { off_x: (o.page_w - content_w) / 2.0, off_y: (o.page_h - content_h) / 2.0, min_x, max_y, k }; let mut out = Out { s: String::new(), first: true }; - let mut gi = 0usize; for part in parts.iter_mut() { let hatches = part.view.hatch_table()?; for i in part.from..part.to { - entry(&mut out, &part.view, i, gi, &hatches, m)?; - gi += 1; + entry(&mut out, &part.view, i, &hatches, m)?; } } Some(out.s) @@ -488,6 +563,23 @@ mod tests { assert_eq!(dash_attr(&[2.0, 0.5]), "2 0.5"); } + #[test] + fn einzeltext_als_zeilen_und_runs() { + let js = "{\"kind\":\"drawingText\",\"at\":{\"x\":1,\"y\":2},\"text\":\"aa bb\",\"heightM\":0.5,\"angle\":0.5,\"color\":\"#123\",\"wrapWidth\":0.6,\"marks\":{\"bold\":true}}"; + let t: SingleText = serde_json::from_str(js).unwrap(); + let m = Map { off_x: 0.0, off_y: 0.0, min_x: 0.0, max_y: 10.0, k: 10.0 }; + let mut out = Out { s: String::new(), first: true }; + text_node(&mut out, &t, m, "0.5".into()); + let recs: Vec> = out.s.split('\u{1e}').map(|r| r.split('\u{1f}').collect()).collect(); + // Drehung um den Anker (10, 80 mm), eine Zeile (Spalte 6 mm), je Wort/Leerraum ein Run. + assert_eq!(recs[0], ["X", "transform", "rotate(-28.648 10 80)", "opacity", "0.5"]); + assert_eq!(recs[1], ["L", "", "x", "10", "y", "80", "text-anchor", "start"]); + // Run-Grösse = heightM (wie die frühere TS-Fassung: `basePt · unitPerPt` mit `unitPerPt` in + // pt→mm, also Meter statt Papier-mm — bekannte Abweichung, bewusst unverändert übernommen). + assert_eq!(recs[2], ["R", "aa", "font-size", "0.5", "fill", "#123", "font-weight", "700", "font-family", "Helvetica, Arial, sans-serif"]); + assert_eq!((recs[3][1], recs[4][1], recs.len()), (" ", "bb", 5)); + } + #[test] fn schraffur_parallel_geklippt() { let sq = [V2 { x: 0.0, y: 0.0 }, V2 { x: 10.0, y: 0.0 }, V2 { x: 10.0, y: 10.0 }, V2 { x: 0.0, y: 10.0 }]; diff --git a/src-tauri/core/src/plan_scene.rs b/src-tauri/core/src/plan_scene.rs index fdd57e7e..357360a2 100644 --- a/src-tauri/core/src/plan_scene.rs +++ b/src-tauri/core/src/plan_scene.rs @@ -621,7 +621,7 @@ pub fn build_scene(parts: &mut [Part], greyed_ranges: &[(usize, usize)]) -> Opti // ── Ausgaben ───────────────────────────────────────────────────────────────────────────────────── -/// Eine Textzeile (von TS gesetzt) für die render2d-Szene. +/// Eine Textzeile (gesetzt in `plan_text::scene_texts`) für die render2d-Szene. pub struct SText { pub pos: V2, pub size_mm: f64, @@ -631,22 +631,6 @@ pub struct SText { pub content: Vec, } -/// Texte aus `[x, y, sizeMm, r, g, b, a, align, nBytes]*` und den UTF-8-Bytes; `None` bei Unsinn. -pub fn texts_from(nums: &[f64], bytes: &[u8]) -> Option> { - if nums.len() % 9 != 0 { - return None; - } - let mut out = Vec::with_capacity(nums.len() / 9); - let mut o = 0usize; - for t in nums.chunks_exact(9) { - let n = whole(t[8])?; - let content = bytes.get(o..o.checked_add(n)?)?.to_vec(); - o += n; - out.push(SText { pos: v2(t[0], t[1]), size_mm: t[2], color: [t[3], t[4], t[5], t[6]], align: whole(t[7])? as u32, content }); - } - (o == bytes.len()).then_some(out) -} - /// `z >>> 0` (ToUint32). fn u32_of(z: f64) -> u32 { jsnum::to_int32(z) as u32 diff --git a/src-tauri/core/src/plan_text.rs b/src-tauri/core/src/plan_text.rs new file mode 100644 index 00000000..0ed4aea1 --- /dev/null +++ b/src-tauri/core/src/plan_text.rs @@ -0,0 +1,300 @@ +//! Texte eines Plans für die Ausgaben ([K3d]/[K4], früher TS: `planSceneTexts` in +//! `src/plan/toRenderScene.ts`, `stampLines`/`textInput` in `src/export/exportDxf.ts`): Raumstempel +//! (`text`) und Einzeltexte (`drawingText`) reisen im Plan-Puffer als JSON (Rich-Text-Dokument, +//! Live-Zeilen, Höhe, Spalte); gesetzt wird hier beim Verbrauch — die Zeilenlage hängt am Massstab +//! der Ausgabe (Raumstempel in Papier-pt, Run-Grössen der Einzeltexte in pt), nicht am Plan. +//! Layout selbst: [`crate::text_layout`]. +//! +//! Zahlen im JSON, die TS als `null` geschrieben hat (NaN), werden NaN. + +use crate::model::{Marks, RichTextDoc}; +use crate::plan::prim::StampLine; +use crate::plan_buf::{whole, T_DRAWING_TEXT, T_TEXT}; +use crate::plan_dxf::{StampLine as DxfLine, TextIn, TextStyleIn}; +use crate::plan_parts::{in_ranges, Part}; +use crate::plan_scene::{to_rgba, Rgba, SText}; +use crate::text_layout::{doc_from_text, doc_to_lines, font_name_of, is_blank, plain_text, split_ws, stamp_block, wrap_doc_to_lines, LayoutOpts, LineAlign, Placed, PT_TO_MM, TEXT_LINE_HEIGHT_MULT}; +use serde::{Deserialize, Deserializer}; + +fn num<'de, D: Deserializer<'de>>(d: D) -> Result { + Ok(Option::::deserialize(d)?.unwrap_or(f64::NAN)) +} + +#[derive(Deserialize, Clone, Copy, Debug)] +pub struct P { + #[serde(deserialize_with = "num")] + pub x: f64, + #[serde(deserialize_with = "num")] + pub y: f64, +} + +/// Raumstempel (`Primitive` `text`). +#[derive(Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct StampText { + pub at: P, + pub doc: RichTextDoc, + #[serde(default)] + pub extra_lines: Vec, + #[serde(deserialize_with = "num")] + pub base_pt: f64, + #[serde(default)] + pub color: Option, + #[serde(default)] + pub greyed: Option, +} + +/// Einzeltext (`Primitive` `drawingText`). +#[derive(Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct SingleText { + pub at: P, + #[serde(default)] + pub text: String, + #[serde(deserialize_with = "num")] + pub height_m: f64, + #[serde(deserialize_with = "num")] + pub angle: f64, + #[serde(default)] + pub color: Option, + #[serde(default)] + pub marks: Option, + #[serde(default)] + pub wrap_width: Option, + #[serde(default)] + pub doc: Option, + #[serde(default)] + pub greyed: Option, + #[serde(default)] + pub opacity: Option, +} + +impl SingleText { + /// `p.doc ?? docFromText(p.text, p.marks ?? {})`. + pub fn doc(&self) -> RichTextDoc { + match &self.doc { + Some(d) => d.clone(), + None => doc_from_text(&self.text, self.marks.as_ref().unwrap_or(&Marks::default())), + } + } + /// `p.wrapWidth && p.wrapWidth > 0 ? p.wrapWidth : undefined`. + pub fn wrap(&self) -> Option { + self.wrap_width.filter(|w| *w > 0.0) + } +} + +pub enum TextPrim { + Stamp(StampText), + Single(SingleText), +} + +/// Text-Eintrag `i` eines Abschnitts lesen (`None`: kein Text, kein JSON oder unlesbar). +pub fn read_text(part: &mut Part, i: usize) -> Option { + let rec = part.view.rec(i)?; + if rec.tag != T_TEXT && rec.tag != T_DRAWING_TEXT { + return None; + } + let idx = *rec.f.first()?; + whole(idx)?; + let js = part.str(idx)?; + if rec.tag == T_TEXT { + serde_json::from_str(js).ok().map(TextPrim::Stamp) + } else { + serde_json::from_str(js).ok().map(TextPrim::Single) + } +} + +// ── Render-Szene ───────────────────────────────────────────────────────────────────────────────── + +const INK: Rgba = [0.1, 0.1, 0.1, 1.0]; +/// Grauton gedimmter Texte (wie `GREY_RGB`). +const GREY_RGB: f64 = 0.549; + +fn greyed_color(c: Rgba, greyed: bool) -> Rgba { + if greyed { + [GREY_RGB, GREY_RGB, GREY_RGB, c[3]] + } else { + c + } +} + +fn push(out: &mut Vec, x: f64, y: f64, content: String, size_mm: f64, color: Rgba, align: LineAlign) { + out.push(SText { pos: crate::hatch::V2 { x, y }, size_mm, color, align: align.code(), content: content.into_bytes() }); +} + +/// Textzeilen der Render-Szene in Zeichenreihenfolge (`planSceneTexts`): Raumstempel = Rich-Text- +/// Zeilen + Live-Zeilen, Block vertikal um den Anker zentriert, Vorschub 1.3 × Basisgrösse; +/// Einzeltexte top-down ab `at` mit `heightM` als Basisgrösse, umbrochen auf die Spalte. +/// `paper_scale_n` (1:N) rechnet Papier-mm in Modell-Meter um. `None` bei kaputtem Puffer. +pub fn scene_texts(parts: &mut [Part], ranges: &[(usize, usize)], paper_scale_n: f64) -> Option> { + let mm_to_m = paper_scale_n / 1000.0; + let mut out = Vec::new(); + let mut gi = 0usize; + for part in parts.iter_mut() { + for i in part.from..part.to { + let forced = !ranges.is_empty() && in_ranges(ranges, gi); + gi += 1; + let tag = part.view.rec(i)?.tag; + if tag != T_TEXT && tag != T_DRAWING_TEXT { + continue; + } + match read_text(part, i) { + Some(TextPrim::Stamp(t)) => stamp_scene(&t, forced, mm_to_m, &mut out), + Some(TextPrim::Single(t)) => single_scene(&t, forced, mm_to_m, &mut out), + None => {} + } + } + } + Some(out) +} + +fn stamp_scene(t: &StampText, forced: bool, mm_to_m: f64, out: &mut Vec) { + let greyed = t.greyed == Some(true) || forced; + let color = t.color.as_deref(); + let def = greyed_color(to_rgba(color).unwrap_or(INK), greyed); + let o = LayoutOpts { line_height: 0.0, unit_per_pt: PT_TO_MM, base_pt: t.base_pt, color: color.unwrap_or("#000000") }; + let base_mm = t.base_pt * PT_TO_MM; + let mut flat: Vec<(String, f64, Rgba, LineAlign)> = Vec::new(); + for line in doc_to_lines(&t.doc, &o) { + let fill = line.tspans.first().map(|s| s.fill.as_str()).or(color); + let c = greyed_color(to_rgba(fill).unwrap_or(def), greyed); + flat.push((line.content(), line.max_size().unwrap_or(base_mm), c, line.align)); + } + for l in &t.extra_lines { + flat.push((l.text.clone(), base_mm * 0.8, def, LineAlign::of(Some(l.align)))); + } + if flat.is_empty() { + return; + } + let base_h = base_mm * mm_to_m; + let line_gap = base_h * 1.3; + let total_h = base_h + (flat.len() - 1) as f64 * line_gap; + for (k, (content, size, c, align)) in flat.into_iter().enumerate() { + if is_blank(&content) { + continue; + } + push(out, t.at.x, t.at.y + total_h / 2.0 - base_h * 0.8 - k as f64 * line_gap, content, size, c, align); + } +} + +fn single_scene(t: &SingleText, forced: bool, mm_to_m: f64, out: &mut Vec) { + let greyed = t.greyed == Some(true) || forced; + let color = t.color.as_deref(); + let def = greyed_color(to_rgba(color).unwrap_or(INK), greyed); + let unit_per_pt = PT_TO_MM * mm_to_m; + let base_pt = if unit_per_pt > 0.0 { t.height_m / unit_per_pt } else { 0.0 }; + let o = LayoutOpts { line_height: t.height_m * TEXT_LINE_HEIGHT_MULT, unit_per_pt, base_pt, color: color.unwrap_or("#000000") }; + let mut dy = 0.0; + for (k, line) in wrap_doc_to_lines(&t.doc(), &o, t.wrap()).into_iter().enumerate() { + if k > 0 { + dy += line.line_height; + } + let content = line.content(); + if is_blank(&content) { + continue; + } + let size_m = line.max_size().unwrap_or(t.height_m); + let fill = line.tspans.first().map(|s| s.fill.as_str()).or(color); + let c = greyed_color(to_rgba(fill).unwrap_or(def), greyed); + push(out, t.at.x, t.at.y - dy, content, if unit_per_pt > 0.0 { size_m / mm_to_m } else { size_m }, c, line.align); + } +} + +// ── DXF ────────────────────────────────────────────────────────────────────────────────────────── + +/// Standard-Schrift des DXF-Exports: erste Schrift der Projekt-Textstile, sonst Arial. +pub fn default_font(project: &crate::model::Project) -> String { + project.text_styles.iter().flatten().find_map(|s| font_name_of(s.marks.font.as_deref())).unwrap_or_else(|| "Arial".to_string()) +} + +/// Text-Eingabe des DXF-Sammlers für einen Text-Eintrag (`scale` = Massstabsnenner). +pub fn dxf_text(t: &TextPrim, scale: f64, default_font: &str) -> TextIn { + let family = |font: Option<&str>| font_name_of(font).unwrap_or_else(|| default_font.to_string()); + match t { + TextPrim::Stamp(p) => TextIn::Stamp { at: crate::hatch::V2 { x: p.at.x, y: p.at.y }, lines: stamp_lines(p, scale, &family) }, + TextPrim::Single(p) => { + let paras: Vec = match &p.doc { + Some(d) => plain_text(d).split('\n').map(str::to_string).collect(), + None => split_lines(&p.text), + }; + let marks = p.marks.as_ref().or_else(|| p.doc.as_ref().and_then(|d| d.paragraphs.first()).and_then(|q| q.runs.first()).map(|r| &r.marks)); + let style = TextStyleIn { + family: family(marks.and_then(|m| m.font.as_deref())), + bold: marks.is_some_and(|m| m.bold == Some(true)), + italic: marks.is_some_and(|m| m.italic == Some(true)), + }; + TextIn::Single { + at: crate::hatch::V2 { x: p.at.x, y: p.at.y }, + angle: p.angle, + height: p.height_m, + wrap: p.wrap_width.unwrap_or(f64::NAN), + style, + paras: paras.into_iter().map(|q| { let w = split_ws(&q).into_iter().map(str::to_string).collect(); (q, w) }).collect(), + } + } + } +} + +/// `text.split(/\r?\n/)`. +fn split_lines(s: &str) -> Vec { + let parts: Vec<&str> = s.split('\n').collect(); + let n = parts.len(); + parts.into_iter().enumerate().map(|(k, p)| if k + 1 < n { p.strip_suffix('\r').unwrap_or(p) } else { p }.to_string()).collect() +} + +/// Zeilen eines Raumstempels für den DXF-Export (`stampLines`): wie in der Plan-Ansicht vertikal um +/// den Anker zentriert ([`stamp_block`]), Höhen in Modell-Metern beim Massstab. +fn stamp_lines(p: &StampText, scale: f64, family: &dyn Fn(Option<&str>) -> String) -> Vec { + let unit_per_pt = (0.0254 / 72.0) * scale; + let extra: Vec<(&str, LineAlign)> = p.extra_lines.iter().map(|l| (l.text.as_str(), LineAlign::of(Some(l.align)))).collect(); + let mut out = Vec::new(); + for Placed { line, y } in stamp_block(&p.doc, &extra, p.base_pt, unit_per_pt, p.color.as_deref().unwrap_or("#000000"), 0.0) { + let text = line.content(); + let Some(first) = line.tspans.first() else { continue }; + if is_blank(&text) { + continue; + } + out.push(DxfLine { + height: line.max_size().unwrap_or(f64::NAN), + align: line.align.code() as f64, + style: TextStyleIn { family: family(first.font_family.as_deref()), bold: first.bold, italic: first.italic }, + down: y, + text, + }); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn json_lesen_und_null_als_nan() { + let s: SingleText = serde_json::from_str(r##"{"kind":"drawingText","at":{"x":1,"y":null},"text":"a","heightM":0.2,"angle":0,"color":"#000","wrapWidth":null}"##).unwrap(); + assert!(s.at.y.is_nan() && s.wrap().is_none()); + assert_eq!(s.doc().paragraphs.len(), 1); + let t: StampText = serde_json::from_str(r##"{"kind":"text","at":{"x":0,"y":0},"doc":{"version":1,"paragraphs":[]},"extraLines":[{"text":"x","align":"center"}],"basePt":9,"color":"#fff","roomId":"r"}"##).unwrap(); + assert_eq!(t.extra_lines.len(), 1); + } + + #[test] + fn zeilen_mit_wagenruecklauf() { + assert_eq!(split_lines("a\r\nb\r"), ["a", "b\r"]); + assert_eq!(split_lines(""), [""]); + } + + #[test] + fn raumstempel_zentriert_und_leerzeilen_ohne_text() { + let t: StampText = serde_json::from_str(r##"{"at":{"x":2,"y":3},"doc":{"version":1,"paragraphs":[{"runs":[{"text":"Wohnen","marks":{"bold":true}}],"align":"center"},{"runs":[]}]},"extraLines":[{"text":"17.01 m²","align":"right"}],"basePt":10,"color":"#333"}"##).unwrap(); + let mut out = Vec::new(); + stamp_scene(&t, false, 0.1, &mut out); + assert_eq!(out.len(), 2); + let base_h = 10.0 * PT_TO_MM * 0.1; + assert_eq!(out[0].pos.y, 3.0 + (base_h + 2.0 * base_h * 1.3) / 2.0 - base_h * 0.8); + assert_eq!((out[0].align, out[1].align), (1, 2)); + let l = stamp_lines(&t, 100.0, &|f| f.unwrap_or("Arial").to_string()); + assert_eq!(l.len(), 2); + assert!(l[0].style.bold && l[0].style.family == "Arial"); + } +} diff --git a/src-tauri/core/src/text_layout.rs b/src-tauri/core/src/text_layout.rs new file mode 100644 index 00000000..f336d98e --- /dev/null +++ b/src-tauri/core/src/text_layout.rs @@ -0,0 +1,635 @@ +//! Text-Layout ([K3d]/[K4], früher `src/text/renderHtml.ts` `docToLines`/`wrapDocToLines`/`runToTspan` +//! und `src/text/textFrame.ts`): Rich-Text-Dokument → Zeilen mit Tspans (Grössen schon in +//! Benutzereinheiten), Wortumbruch auf eine Spaltenbreite, geschätzter Text-Rahmen. Grundlage der +//! Text-Verbraucher im Kern (Render-Szene, Druck-SVG, DXF; `plan_text.rs`) und — über die Bindung +//! `text_lines` — der TS-Fassade für Editor-Vorschau, Layout-Blatt und SVG-Rückfall. +//! +//! Glyphen-Metrik: es gibt keine. Wie die TS-Fassung schätzt der Umbruch die Breite eines Wortes +//! als `UTF-16-Länge × Schriftgrösse × 0.55` (keine Schriftdatei, kein Canvas-Messen) — damit ist +//! das Ergebnis bitgleich zur TS-Fassung und unabhängig von installierten Schriften. +//! +//! JS-Semantik, wo sie das Ergebnis bestimmt: Leerraum wie `\s` (WhiteSpace + LineTerminator, s. +//! [`js_space`]), Längen in UTF-16-Einheiten (`String.length`), Rundung `Math.round(n·1000)/1000`, +//! `Math.max` mit NaN. + +use crate::jsnum; +use crate::model::{Align, Marks, Paragraph, RichTextDoc, TextRun}; +pub use crate::plan::overrides::{js_space, js_trim}; +use serde::Serialize; + +/// Faktor, um den Hoch-/Tiefstellung verkleinert wird. +pub const SCRIPT_SCALE: f64 = 0.7; +/// Geschätzte Zeichenbreite als Vielfaches der Schriftgrösse (Umbruch, Text-Rahmen). +pub const CHAR_WIDTH_FACTOR: f64 = 0.55; +/// Zeilenabstand gezeichneter Einzeltexte (Vielfaches der Höhe), `TEXT_LINE_HEIGHT_MULT`. +pub const TEXT_LINE_HEIGHT_MULT: f64 = 1.25; +/// 1 pt in Papier-mm. +pub const PT_TO_MM: f64 = 25.4 / 72.0; + +/// Ausrichtung einer Zeile. Unbekannte Werte (`Align::Unknown`) gelten wie fehlende als links — +/// alle Verbraucher behandelten sie schon in TS wie links. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum LineAlign { + Left, + Center, + Right, +} + +impl LineAlign { + pub fn of(a: Option) -> LineAlign { + match a { + Some(Align::Center) => LineAlign::Center, + Some(Align::Right) => LineAlign::Right, + _ => LineAlign::Left, + } + } + /// 0 links · 1 Mitte · 2 rechts (render2d, DXF). + pub fn code(self) -> u32 { + match self { + LineAlign::Left => 0, + LineAlign::Center => 1, + LineAlign::Right => 2, + } + } +} + +/// Ein Tspan (ein Run bzw. ein Wort innerhalb einer Zeile), Feldreihenfolge wie `SvgTspan` in TS. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Tspan { + pub text: String, + /// Schriftgrösse in Benutzereinheiten (auf 1/1000 gerundet). + pub font_size: f64, + pub fill: String, + #[serde(rename = "fontWeight", skip_serializing_if = "std::ops::Not::not", serialize_with = "ser_weight")] + pub bold: bool, + #[serde(rename = "fontStyle", skip_serializing_if = "std::ops::Not::not", serialize_with = "ser_style")] + pub italic: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub font_family: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub text_decoration: Option<&'static str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub baseline_shift: Option, +} + +fn ser_weight(_: &bool, s: S) -> Result { + s.serialize_str("700") +} +fn ser_style(_: &bool, s: S) -> Result { + s.serialize_str("italic") +} + +impl Tspan { + /// `fontWeight` (`"700"` oder keins), wie das SVG-Attribut. + pub fn font_weight(&self) -> Option<&'static str> { + self.bold.then_some("700") + } + pub fn font_style(&self) -> Option<&'static str> { + self.italic.then_some("italic") + } +} + +/// Eine Zeile (Absatz bzw. umbrochene Teilzeile). +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Line { + pub tspans: Vec, + pub align: LineAlign, + /// Vorschub zu dieser Zeile (Benutzereinheiten). + pub line_height: f64, +} + +impl Line { + /// Inhalt der Zeile (Runs verkettet). + pub fn content(&self) -> String { + self.tspans.iter().map(|t| t.text.as_str()).collect() + } + /// Grösste Schrift der Zeile (`Math.max(...fontSize)`), `None` ohne Tspans. + pub fn max_size(&self) -> Option { + if self.tspans.is_empty() { + None + } else { + Some(self.tspans.iter().fold(f64::NEG_INFINITY, |m, t| jsnum::max(m, t.font_size))) + } + } +} + +/// Optionen wie `SvgTextOptions` (ohne Anker, den setzt der Aufrufer). +#[derive(Clone, Copy, Debug)] +pub struct LayoutOpts<'a> { + /// Vorschub für Absätze ohne eigene `lineHeight`. + pub line_height: f64, + /// `sizePt × unitPerPt` = Grösse in Benutzereinheiten. + pub unit_per_pt: f64, + /// Basisgrösse (pt) für Runs ohne eigene Grösse (TS: `basePt ?? 12`). + pub base_pt: f64, + /// Standardfarbe (TS: `color ?? "#000000"`). + pub color: &'a str, +} + +/// `Math.round(n * 1000) / 1000`. +pub fn round3(n: f64) -> f64 { + jsnum::round(n * 1000.0) / 1000.0 +} + +/// Länge in UTF-16-Einheiten (`String.length`). +pub fn utf16_len(s: &str) -> usize { + s.chars().map(char::len_utf16).sum() +} + +/// `!s.trim()`: leer oder nur Leerraum. +pub fn is_blank(s: &str) -> bool { + js_trim(s).is_empty() +} + +/// `runToTspan`. +pub fn run_to_tspan(run: &TextRun, base_pt: f64, unit_per_pt: f64, color: &str) -> Tspan { + tspan_of(run.text.clone(), &run.marks, base_pt, unit_per_pt, color) +} + +pub fn tspan_of(text: String, m: &Marks, base_pt: f64, unit_per_pt: f64, color: &str) -> Tspan { + let sup = m.super_ == Some(true); + let sub = m.sub == Some(true); + let size_pt = m.size_pt.unwrap_or(base_pt) * if sup || sub { SCRIPT_SCALE } else { 1.0 }; + let font_size = size_pt * unit_per_pt; + let deco = match (m.underline == Some(true), m.strike == Some(true)) { + (true, true) => Some("underline line-through"), + (true, false) => Some("underline"), + (false, true) => Some("line-through"), + (false, false) => None, + }; + let baseline_shift = if sub { + Some(round3(-font_size * 0.2)) + } else if sup { + Some(round3(font_size * 0.35)) + } else { + None + }; + Tspan { + text, + font_size: round3(font_size), + fill: m.color.clone().unwrap_or_else(|| color.to_string()), + bold: m.bold == Some(true), + italic: m.italic == Some(true), + font_family: m.font.clone().filter(|f| !f.is_empty()), + text_decoration: deco, + baseline_shift, + } +} + +fn para_line_height(p: &Paragraph, o: &LayoutOpts) -> f64 { + match p.line_height { + Some(lh) => o.base_pt * o.unit_per_pt * lh, + None => o.line_height, + } +} + +/// Verweis auf ein Textstück: Absatz `para`, Run `run` (Live-Zeilen des Raumstempels: `para` ≥ +/// Absatzzahl, `run` 0), Bereich in Bytes (`b0..b1`) und in UTF-16-Einheiten (`u0..u1`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Tok { + pub para: usize, + pub run: usize, + pub b0: usize, + pub b1: usize, + pub u0: usize, + pub u1: usize, +} + +/// Eine Zeile als Verweise auf die Quelle (das eigentliche Layout; [`Line`] ist die ausgeschriebene +/// Form). +#[derive(Clone, Debug, PartialEq)] +pub struct LineRef { + pub toks: Vec, + pub align: LineAlign, + pub line_height: f64, +} + +/// Gerundete Schriftgrösse eines Runs (wie `runToTspan`). +fn run_font_size(m: &Marks, base_pt: f64, unit_per_pt: f64) -> f64 { + let script = m.super_ == Some(true) || m.sub == Some(true); + let size_pt = m.size_pt.unwrap_or(base_pt) * if script { SCRIPT_SCALE } else { 1.0 }; + round3(size_pt * unit_per_pt) +} + +/// Zeilen als Verweise (`docToLines`/`wrapDocToLines`): ohne Spalte (`wrap` ≤ 0/NaN/`None`) eine +/// Zeile je Absatz (leere Runs entfallen), sonst wortweise umbrochen — Wortbreite = UTF-16-Länge × +/// Schriftgrösse × 0.55, Leerraum am Zeilenrand fällt weg, Run-Grenzen bleiben. +pub fn layout_refs(doc: &RichTextDoc, o: &LayoutOpts, wrap: Option) -> Vec { + let max_width = wrap.filter(|w| *w > 0.0); + struct Token { + tok: Tok, + width: f64, + is_space: bool, + } + let mut lines = Vec::new(); + for (pi, p) in doc.paragraphs.iter().enumerate() { + let line_height = para_line_height(p, o); + let align = LineAlign::of(p.align); + let Some(max_width) = max_width else { + let toks = p.runs.iter().enumerate().filter(|(_, r)| !r.text.is_empty()).map(|(ri, r)| Tok { para: pi, run: ri, b0: 0, b1: r.text.len(), u0: 0, u1: utf16_len(&r.text) }).collect(); + lines.push(LineRef { toks, align, line_height }); + continue; + }; + let mut tokens: Vec = Vec::new(); + for (ri, run) in p.runs.iter().enumerate() { + if run.text.is_empty() { + continue; + } + let fs = run_font_size(&run.marks, o.base_pt, o.unit_per_pt); + let (mut b, mut u) = (0, 0); + for part in split_keep_ws(&run.text) { + let ul = utf16_len(part); + let is_space = part.chars().next().is_some_and(js_space); + tokens.push(Token { tok: Tok { para: pi, run: ri, b0: b, b1: b + part.len(), u0: u, u1: u + ul }, width: ul as f64 * fs * CHAR_WIDTH_FACTOR, is_space }); + b += part.len(); + u += ul; + } + } + if tokens.is_empty() { + lines.push(LineRef { toks: Vec::new(), align, line_height }); + continue; + } + let mut current: Vec = Vec::new(); + let mut current_width = 0.0; + let flush = |current: &mut Vec, lines: &mut Vec| { + while current.last().is_some_and(|t| t.is_space) { + current.pop(); + } + lines.push(LineRef { toks: current.drain(..).map(|t| t.tok).collect(), align, line_height }); + }; + for tok in tokens { + if current.is_empty() && tok.is_space { + continue; + } + if !current.is_empty() && current_width + tok.width > max_width { + flush(&mut current, &mut lines); + current_width = 0.0; + if tok.is_space { + continue; + } + } + current_width += tok.width; + current.push(tok); + } + flush(&mut current, &mut lines); + } + lines +} + +/// Verweis-Zeilen ausschreiben (Tspans mit Text und Stil des Runs). +pub fn lines_of(doc: &RichTextDoc, refs: Vec, o: &LayoutOpts) -> Vec { + refs.into_iter() + .map(|l| Line { + tspans: l + .toks + .iter() + .map(|t| { + let r = &doc.paragraphs[t.para].runs[t.run]; + tspan_of(r.text[t.b0..t.b1].to_string(), &r.marks, o.base_pt, o.unit_per_pt, o.color) + }) + .collect(), + align: l.align, + line_height: l.line_height, + }) + .collect() +} + +/// `docToLines`: eine Zeile je Absatz, leere Runs entfallen. +pub fn doc_to_lines(doc: &RichTextDoc, o: &LayoutOpts) -> Vec { + lines_of(doc, layout_refs(doc, o, None), o) +} + +/// `text.split(/(\s+)/)` ohne leere Teile: abwechselnd Wort- und Leerraum-Stücke. +pub fn split_keep_ws(s: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut start = 0; + let mut prev: Option = None; + for (i, c) in s.char_indices() { + let sp = js_space(c); + if prev.is_some_and(|p| p != sp) { + out.push(&s[start..i]); + start = i; + } + prev = Some(sp); + } + if start < s.len() { + out.push(&s[start..]); + } + out +} + +/// `s.split(/\s+/)` (JS): Teile zwischen Leerraum-Folgen, auch leere am Rand; `""` → `[""]`. +pub fn split_ws(s: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut start = 0; + let mut in_ws = false; + for (i, c) in s.char_indices() { + let sp = js_space(c); + if sp && !in_ws { + out.push(&s[start..i]); + in_ws = true; + } else if !sp && in_ws { + start = i; + in_ws = false; + } + } + out.push(if in_ws { "" } else { &s[start..] }); + out +} + +/// `wrapDocToLines`: wie [`doc_to_lines`], bricht aber wortweise auf `wrap` um (gleiche Einheiten +/// wie die Schriftgrösse); `wrap` ≤ 0/NaN/`None` → eine Zeile je Absatz. Run-Grenzen bleiben. +pub fn wrap_doc_to_lines(doc: &RichTextDoc, o: &LayoutOpts, wrap: Option) -> Vec { + lines_of(doc, layout_refs(doc, o, wrap), o) +} + +/// Eine gesetzte Zeile mit ihrer Grundlinie (`y`). +#[derive(Clone, Debug, PartialEq)] +pub struct Placed { + pub line: Line, + pub y: f64, +} + +/// Raumstempel-Block als Verweise (Plan-Ansicht, DXF): Rich-Text-Zeilen (Vorschub 1.3 × +/// Basisgrösse bzw. die Absatz-Zeilenhöhe), darunter die Live-Zeilen (`extra`: Text und +/// Ausrichtung; Verweis-Absatz = Absatzzahl + Nummer), vertikal um `y0` zentriert; `y` wächst nach +/// unten (Bildschirm) — im Modell ist es der Abstand nach unten. +pub fn stamp_block_refs(doc: &RichTextDoc, extra: &[(&str, LineAlign)], base_pt: f64, unit_per_pt: f64, color: &str, y0: f64) -> Vec<(LineRef, f64)> { + let base_fs = base_pt * unit_per_pt; + let line_gap = base_fs * 1.3; + let mut lines = layout_refs(doc, &LayoutOpts { line_height: line_gap, unit_per_pt, base_pt, color }, None); + let n = doc.paragraphs.len(); + for (i, (text, align)) in extra.iter().enumerate() { + lines.push(LineRef { toks: vec![Tok { para: n + i, run: 0, b0: 0, b1: text.len(), u0: 0, u1: utf16_len(text) }], align: *align, line_height: line_gap }); + } + if lines.is_empty() { + return Vec::new(); + } + let total_h = base_fs + lines[1..].iter().fold(0.0, |s, l| s + l.line_height); + let mut y = y0 - total_h / 2.0 + base_fs * 0.8; + lines + .into_iter() + .enumerate() + .map(|(k, line)| { + if k > 0 { + y += line.line_height; + } + (line, y) + }) + .collect() +} + +/// Stil der Live-Zeilen eines Raumstempels (0.8 × Basisgrösse, ungerundet, Farbe `color`). +pub fn stamp_extra_tspan(text: String, base_pt: f64, unit_per_pt: f64, color: &str) -> Tspan { + Tspan { text, font_size: base_pt * unit_per_pt * 0.8, fill: color.to_string(), bold: false, italic: false, font_family: None, text_decoration: None, baseline_shift: None } +} + +/// Raumstempel-Block ausgeschrieben ([`stamp_block_refs`]). +pub fn stamp_block(doc: &RichTextDoc, extra: &[(&str, LineAlign)], base_pt: f64, unit_per_pt: f64, color: &str, y0: f64) -> Vec { + let o = LayoutOpts { line_height: 0.0, unit_per_pt, base_pt, color }; + let n = doc.paragraphs.len(); + stamp_block_refs(doc, extra, base_pt, unit_per_pt, color, y0) + .into_iter() + .map(|(l, y)| { + let tspans = l + .toks + .iter() + .map(|t| { + if t.para >= n { + stamp_extra_tspan(extra[t.para - n].0.to_string(), base_pt, unit_per_pt, color) + } else { + let r = &doc.paragraphs[t.para].runs[t.run]; + tspan_of(r.text[t.b0..t.b1].to_string(), &r.marks, o.base_pt, o.unit_per_pt, o.color) + } + }) + .collect(); + Placed { line: Line { tspans, align: l.align, line_height: l.line_height }, y } + }) + .collect() +} + +/// Wortumbruch eines Absatzes nach Zeichenzahl (Wörter nach `split(/\s+/)`, mit einem Leerzeichen +/// verbunden; Länge in UTF-16-Einheiten) — einfacher Text ohne Rich-Dokument (Plan-Ansicht, DXF). +pub fn wrap_words>(words: &[S], max_chars: f64, lines: &mut Vec) { + let mut line = String::new(); + for word in words { + let word = word.as_ref(); + if line.is_empty() { + line = word.to_string(); + } else if (utf16_len(&line) + 1 + utf16_len(word)) as f64 <= max_chars { + line.push(' '); + line.push_str(word); + } else { + lines.push(std::mem::replace(&mut line, word.to_string())); + } + } + lines.push(line); +} + +/// Höchstzahl Zeichen je Zeile: `max(1, floor(Spalte / (Grösse × 0.55)))`. +pub fn max_chars(wrap: f64, font_size: f64) -> f64 { + jsnum::max(1.0, (wrap / (font_size * CHAR_WIDTH_FACTOR)).floor()) +} + +/// Einfacher Text auf eine Spalte umbrochen (Absätze an `\n`). +pub fn wrap_plain(text: &str, wrap: f64, font_size: f64) -> Vec { + let m = max_chars(wrap, font_size); + let mut lines = Vec::new(); + for para in text.split('\n') { + wrap_words(&split_ws(para), m, &mut lines); + } + lines +} + +/// `docFromText(text, marks)`: je Zeile (`\n`) ein Absatz, leere Zeile ohne Run. +pub fn doc_from_text(text: &str, marks: &Marks) -> RichTextDoc { + RichTextDoc { + version: 1.0, + paragraphs: text + .split('\n') + .map(|l| Paragraph { + runs: if l.is_empty() { vec![] } else { vec![TextRun { text: l.to_string(), marks: marks.clone(), ..Default::default() }] }, + ..Default::default() + }) + .collect(), + ..Default::default() + } +} + +/// `plainText(doc)`: Absätze (Runs verkettet) mit `\n` verbunden. +pub fn plain_text(doc: &RichTextDoc) -> String { + doc.paragraphs.iter().map(|p| p.runs.iter().map(|r| r.text.as_str()).collect::()).collect::>().join("\n") +} + +/// `fontNameOf`: erste Schriftfamilie eines CSS-`font-family`-Werts ohne Anführungszeichen; +/// generische Familien und CSS-Variablen (`var(…)`) → `None`. +pub fn font_name_of(css: Option<&str>) -> Option { + let css = css.filter(|c| !c.is_empty())?; + // `css.replace(/var\([^)]*\)/g, "")` + let mut s = String::with_capacity(css.len()); + let mut pos = 0; + while let Some(i) = css[pos..].find("var(").map(|i| pos + i) { + let Some(j) = css[i + 4..].find(')').map(|j| i + 4 + j) else { break }; + s.push_str(&css[pos..i]); + pos = j + 1; + } + s.push_str(&css[pos..]); + const GENERIC: [&str; 9] = ["sans-serif", "serif", "monospace", "cursive", "fantasy", "system-ui", "ui-sans-serif", "inherit", "initial"]; + for raw in s.split(',') { + let mut t = js_trim(raw); + // `.replace(/^["']|["']$/g, "")` + if t.starts_with(['"', '\'']) { + t = &t[1..]; + } + if t.ends_with(['"', '\'']) { + t = &t[..t.len() - 1]; + } + let name = js_trim(t); + if name.is_empty() || GENERIC.iter().any(|g| name.eq_ignore_ascii_case(g)) { + continue; + } + return Some(name.to_string()); + } + None +} + +/// `textFrameCorners`: vier Ecken (oben-links · oben-rechts · unten-rechts · unten-links vor der +/// Drehung) des geschätzten Rahmens eines Einzeltexts in Modell-Metern. `at` = Grundlinie links der +/// ersten Zeile; Höhe aus der echten Zeilenzahl, Breite aus der längsten Zeile geschätzt (oder +/// `wrap`); `baseline_from_top` = Grundlinie → Oberkante als Vielfaches der Höhe (in TS gemessen). +pub fn text_frame_corners(doc: &RichTextDoc, at: (f64, f64), height_m: f64, angle: f64, wrap: Option, baseline_from_top: f64) -> [(f64, f64); 4] { + let line_height = height_m * TEXT_LINE_HEIGHT_MULT; + let wrap = wrap.filter(|w| *w > 0.0); + let o = LayoutOpts { line_height, unit_per_pt: 1.0, base_pt: height_m, color: "#000000" }; + let lines = wrap_doc_to_lines(doc, &o, wrap); + let max_chars = if lines.is_empty() { + 1.0 + } else { + lines.iter().fold(1.0, |m, l| jsnum::max(m, l.tspans.iter().map(|t| utf16_len(&t.text)).sum::() as f64)) + }; + let width = wrap.unwrap_or_else(|| jsnum::max(height_m, max_chars * height_m * CHAR_WIDTH_FACTOR)); + let height = jsnum::max(1.0, lines.len() as f64) * line_height; + let top = height_m * baseline_from_top; + let local = [(0.0, top), (width, top), (width, top - height), (0.0, top - height)]; + let (c, s) = (jsnum::cos(angle), jsnum::sin(angle)); + local.map(|(x, y)| (at.0 + x * c - y * s, at.1 + x * s + y * c)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const O: LayoutOpts = LayoutOpts { line_height: 10.0, unit_per_pt: 1.0, base_pt: 10.0, color: "#000000" }; + + fn doc(paras: Vec>) -> RichTextDoc { + RichTextDoc { + version: 1.0, + paragraphs: paras + .into_iter() + .map(|runs| Paragraph { runs: runs.into_iter().map(|(t, m)| TextRun { text: t.into(), marks: m, ..Default::default() }).collect(), ..Default::default() }) + .collect(), + ..Default::default() + } + } + + fn texts(lines: &[Line]) -> Vec { + lines.iter().map(Line::content).collect() + } + + #[test] + fn ohne_spalte_eine_zeile_je_absatz() { + let d = doc_from_text("hallo welt\n\nzwei", &Marks::default()); + assert_eq!(wrap_doc_to_lines(&d, &O, None), doc_to_lines(&d, &O)); + assert_eq!(wrap_doc_to_lines(&d, &O, Some(f64::NAN)), doc_to_lines(&d, &O)); + assert_eq!(texts(&doc_to_lines(&d, &O)), ["hallo welt", "", "zwei"]); + } + + #[test] + fn bricht_wortweise_um_und_verliert_nichts() { + let d = doc_from_text("eins zwei drei vier fünf", &Marks::default()); + let l = wrap_doc_to_lines(&d, &O, Some(30.0)); + // 5.5 Einheiten je Zeichen: "eins" (22) + " " (5.5) passt, "zwei" (22) nicht mehr. + assert_eq!(texts(&l), ["eins", "zwei", "drei", "vier", "fünf"]); + let l = wrap_doc_to_lines(&doc_from_text("aa bb cc", &Marks::default()), &O, Some(1.0)); + assert_eq!(texts(&l), ["aa", "bb", "cc"]); + } + + #[test] + fn run_grenzen_und_formatierung_bleiben() { + let bold = Marks { bold: Some(true), ..Default::default() }; + let d = doc(vec![vec![("normal ", Marks::default()), ("fett", bold), (" weiter", Marks::default())]]); + let l = wrap_doc_to_lines(&d, &O, Some(1000.0)); + assert_eq!(l.len(), 1); + let t: Vec<_> = l[0].tspans.iter().map(|t| (t.text.as_str(), t.bold)).collect(); + assert_eq!(t, [("normal", false), (" ", false), ("fett", true), (" ", false), ("weiter", false)]); + } + + #[test] + fn leerer_absatz_ergibt_leere_zeile() { + let d = doc(vec![vec![], vec![("x", Marks::default())]]); + let l = wrap_doc_to_lines(&d, &O, Some(100.0)); + assert_eq!(l.len(), 2); + assert!(l[0].tspans.is_empty()); + } + + #[test] + fn breite_in_utf16_einheiten_und_js_leerraum() { + // 🏠 zählt 2 Einheiten (11 bei Grösse 10), NBSP trennt Wörter, U+0085 nicht (kein JS-\s). + assert_eq!(split_keep_ws("a\u{a0}b\u{85}c d"), ["a", "\u{a0}", "b\u{85}c", " ", "d"]); + assert_eq!(split_ws(" a b "), ["", "a", "b", ""]); + assert_eq!(split_ws(""), [""]); + let d = doc_from_text("🏠 🏠", &Marks::default()); + assert_eq!(texts(&wrap_doc_to_lines(&d, &O, Some(27.5))), ["🏠 🏠"]); + assert_eq!(texts(&wrap_doc_to_lines(&d, &O, Some(27.4))), ["🏠", "🏠"]); + } + + #[test] + fn tspan_grosse_hochstellung_farbe() { + let m = Marks { super_: Some(true), size_pt: Some(9.0), color: Some(String::new()), font: Some(String::new()), underline: Some(true), strike: Some(true), ..Default::default() }; + let t = run_to_tspan(&TextRun { text: "x".into(), marks: m, ..Default::default() }, 12.0, 25.4 / 72.0, "#123"); + assert_eq!(t.font_size, round3(9.0 * 0.7 * (25.4 / 72.0))); + assert_eq!(t.baseline_shift, Some(round3(9.0 * 0.7 * (25.4 / 72.0) * 0.35))); + assert_eq!(t.fill, ""); // `color ?? …`: leere Farbe bleibt + assert_eq!(t.font_family, None); + assert_eq!(t.text_decoration, Some("underline line-through")); + let j = serde_json::to_string(&t).unwrap(); + assert!(j.starts_with("{\"text\":\"x\",\"fontSize\":") && !j.contains("fontWeight") && j.contains("\"baselineShift\":")); + } + + #[test] + fn absatz_zeilenhoehe_aus_basisgroesse() { + let mut d = doc_from_text("a\nb", &Marks::default()); + d.paragraphs[1].line_height = Some(1.5); + d.paragraphs[1].align = Some(Align::Unknown); + let l = doc_to_lines(&d, &LayoutOpts { line_height: 7.0, unit_per_pt: 2.0, base_pt: 10.0, color: "#000" }); + assert_eq!((l[0].line_height, l[1].line_height, l[1].align), (7.0, 30.0, LineAlign::Left)); + } + + #[test] + fn schriftname_aus_css() { + assert_eq!(font_name_of(Some("\"Helvetica Neue\", Arial, sans-serif")).as_deref(), Some("Helvetica Neue")); + assert_eq!(font_name_of(Some("var(--font-ui, sans-serif)")), None); + assert_eq!(font_name_of(Some("sans-serif, Arial")).as_deref(), Some("Arial")); + assert_eq!(font_name_of(Some("'Source Sans 3'")).as_deref(), Some("Source Sans 3")); + assert_eq!(font_name_of(Some("SERIF, 'x")).as_deref(), Some("x")); + assert_eq!(font_name_of(Some("var(--a), Times")).as_deref(), Some("Times")); + assert_eq!(font_name_of(None), None); + assert_eq!(font_name_of(Some("")), None); + assert_eq!(font_name_of(Some("\"")), None); + } + + #[test] + fn text_rahmen() { + let d = doc_from_text("Hallo", &Marks::default()); + let c = text_frame_corners(&d, (0.0, 0.0), 0.2, 0.0, None, 0.9); + assert!((c[0].1 - 0.18).abs() < 1e-12 && (c[2].1 - (0.18 - 0.25)).abs() < 1e-12); + assert!((c[1].0 - 5.0 * 0.2 * 0.55).abs() < 1e-12); + let w = text_frame_corners(&d, (0.0, 0.0), 0.2, 0.0, Some(1.5), 0.9); + assert_eq!(w[1].0, 1.5); + let r = text_frame_corners(&d, (0.0, 0.0), 0.2, std::f64::consts::FRAC_PI_2, None, 0.9); + assert!((r[0].0 + 0.18).abs() < 1e-12 && r[0].1.abs() < 1e-12); + } +} diff --git a/src-tauri/core/src/web/mod.rs b/src-tauri/core/src/web/mod.rs index c1e49abf..45e7e646 100644 --- a/src-tauri/core/src/web/mod.rs +++ b/src-tauri/core/src/web/mod.rs @@ -38,6 +38,7 @@ mod pens; mod layout_model; mod parametric_walls; mod reorder; +mod text_layout; use wasm_bindgen::prelude::wasm_bindgen; diff --git a/src-tauri/core/src/web/plan_dxf.rs b/src-tauri/core/src/web/plan_dxf.rs index 96933435..8bcd6caa 100644 --- a/src-tauri/core/src/web/plan_dxf.rs +++ b/src-tauri/core/src/web/plan_dxf.rs @@ -2,34 +2,32 @@ //! `plan_parts`) und dem Projekt-Dokument. Leeres Ergebnis = Puffer fehlt (TS legt neu ab und //! fragt nochmals), Dokument nicht offen/unpassend oder kaputte Eingabe — nie Panic. -use crate::plan_dxf::{collect, encode, texts_from, DxfOptions}; +use crate::plan_dxf::{collect, encode, DxfOptions}; use crate::plan_parts::parts_from; use wasm_bindgen::prelude::wasm_bindgen; /// Flache Zeichnung (Format `plan_dxf::encode`). `opts` = `[Massstab, Schraffuren 0/1, cm 0/1, -/// Papierbereich 0/1, minX, minY, maxX, maxY]`; `text_nums`/`text_strs` = Text-Eingabe -/// (`plan_dxf::texts_from`, Texte je mit `\0` davor); `default_font` = Standard-Schrift. +/// Papierbereich 0/1, minX, minY, maxX, maxY]`. Texte setzt der Kern aus dem Text-JSON der Puffer +/// (`plan_text`), die Standard-Schrift kommt aus den Textstilen des Projekts. #[wasm_bindgen] -pub fn plan_dxf_flat(doc: u32, segs: &[f64], text_nums: &[f64], text_strs: &str, opts: &[f64], default_font: &str) -> Vec { +pub fn plan_dxf_flat(doc: u32, segs: &[f64], opts: &[f64]) -> Vec { let Ok([scale, hatches, cm, layout, min_x, min_y, max_x, max_y]) = <[f64; 8]>::try_from(opts) else { return Vec::new() }; if !(scale.is_finite() && scale > 0.0) { return Vec::new(); } - let strs: Vec<&str> = text_strs.split('\0').skip(1).collect(); - let Some(texts) = texts_from(text_nums, &strs) else { return Vec::new() }; let Some(held) = super::plan_buf::held_for_segs(segs) else { return Vec::new() }; let Some(mut parts) = parts_from(segs, |nr| held.iter().find(|e| e.0 == nr).map(|e| &*e.1)) else { return Vec::new() }; - let o = DxfOptions { - scale, - include_hatches: hatches != 0.0, - dim_cm: cm != 0.0, - paper_layout: layout != 0.0, - bounds: [min_x, min_y, max_x, max_y], - default_font: default_font.to_string(), - }; super::document::with_doc(doc, |d| { let p = d.project().ok()?; - collect(&mut parts, &texts, p, &o).map(|f| encode(&f)) + let o = DxfOptions { + scale, + include_hatches: hatches != 0.0, + dim_cm: cm != 0.0, + paper_layout: layout != 0.0, + bounds: [min_x, min_y, max_x, max_y], + default_font: crate::plan_text::default_font(p), + }; + collect(&mut parts, p, &o).map(|f| encode(&f)) }) .flatten() .unwrap_or_default() diff --git a/src-tauri/core/src/web/plan_scene.rs b/src-tauri/core/src/web/plan_scene.rs index f57ce18e..0c6883e2 100644 --- a/src-tauri/core/src/web/plan_scene.rs +++ b/src-tauri/core/src/web/plan_scene.rs @@ -4,7 +4,9 @@ //! Puffer dann neu ab und fragt nochmals. use crate::plan_parts::{parts_from, ranges_from}; -use crate::plan_scene::{build_scene, encode_scene_bin, encode_scene_f64, texts_from, Scene}; +use crate::plan_scene::SText; +use crate::plan_text::scene_texts; +use crate::plan_scene::{build_scene, encode_scene_bin, encode_scene_f64, Scene}; use wasm_bindgen::prelude::wasm_bindgen; fn scene_of(segs: &[f64], greyed: &[f64]) -> Option { @@ -13,17 +15,42 @@ fn scene_of(segs: &[f64], greyed: &[f64]) -> Option { build_scene(&mut parts, &ranges_from(greyed)?) } -/// render2d-Szene v1 (Bytes für `set_scene_bin`/`push_native_scene`); Texte fertig gesetzt aus -/// TS: `[x, y, sizeMm, r, g, b, a, align, nBytes]*` + UTF-8-Bytes. Leer = Fehler. +/// Gesetzte Textzeilen des Plans (`plan_text::scene_texts`) beim Massstab 1:`paper_scale_n`. +fn texts_of(segs: &[f64], greyed: &[f64], paper_scale_n: f64) -> Option> { + let held = super::plan_buf::held_for_segs(segs)?; + let mut parts = parts_from(segs, |nr| held.iter().find(|e| e.0 == nr).map(|e| &*e.1))?; + scene_texts(&mut parts, &ranges_from(greyed)?, paper_scale_n) +} + +/// render2d-Szene v1 (Bytes für `set_scene_bin`/`push_native_scene`) samt Texten, gesetzt beim +/// Massstab 1:`paper_scale_n` (die Abschnitte tragen das Text-JSON). Leer = Fehler. #[wasm_bindgen] -pub fn plan_scene_bin(segs: &[f64], greyed: &[f64], text_nums: &[f64], text_bytes: &[u8]) -> Vec { - let Some(texts) = texts_from(text_nums, text_bytes) else { return Vec::new() }; +pub fn plan_scene_bin(segs: &[f64], greyed: &[f64], paper_scale_n: f64) -> Vec { + let Some(texts) = texts_of(segs, greyed, paper_scale_n) else { return Vec::new() }; match scene_of(segs, greyed) { Some(s) => encode_scene_bin(&s, &texts), None => Vec::new(), } } +/// Textzeilen der Szene für Export/`--format json`: `[n, (x, y, sizeMm, r, g, b, a, align, +/// nUtf16)*, UTF-16-Einheiten…]`. Leer = Fehler. +#[wasm_bindgen] +pub fn plan_scene_texts(segs: &[f64], greyed: &[f64], paper_scale_n: f64) -> Vec { + let Some(texts) = texts_of(segs, greyed, paper_scale_n) else { return Vec::new() }; + let mut out = Vec::with_capacity(1 + texts.len() * 12); + out.push(texts.len() as f64); + let mut units: Vec = Vec::new(); + for t in &texts { + let s = String::from_utf8_lossy(&t.content); + let n0 = units.len(); + units.extend(s.encode_utf16().map(f64::from)); + out.extend_from_slice(&[t.pos.x, t.pos.y, t.size_mm, t.color[0], t.color[1], t.color[2], t.color[3], t.align as f64, (units.len() - n0) as f64]); + } + out.extend(units); + out +} + /// Verlustfreie Szene (Format s. `plan_scene`) für Export und `--format json`. Leer = Fehler. #[wasm_bindgen] pub fn plan_scene_f64(segs: &[f64], greyed: &[f64]) -> Vec { diff --git a/src-tauri/core/src/web/text_layout.rs b/src-tauri/core/src/web/text_layout.rs new file mode 100644 index 00000000..8661938b --- /dev/null +++ b/src-tauri/core/src/web/text_layout.rs @@ -0,0 +1,124 @@ +//! Bindungen des Text-Layouts (`crate::text_layout`) für die TS-Fassade `src/text/renderHtml.ts` +//! (`docToLines`/`wrapDocToLines`, Raumstempel-Block, einfacher Umbruch) und `src/text/textFrame.ts`. +//! Das Dokument reist als JSON (Text, keine Geometrie); kaputte Eingaben ergeben ein leeres +//! Ergebnis — nie Panic. +//! +//! Zeilen kommen flach zurück (`encode_lines`): `[nZeilen, nStile, Stil*, Zeile*]`; +//! Stil = `[Grösse, Bits, Versatz, nFarbe, nSchrift (−1 = keine), Farbe…, Schrift…]` (Bits: 1 fett, +//! 2 kursiv, 4 unterstrichen, 8 durchgestrichen, 16 mit Versatz; Texte als UTF-16-Einheiten); +//! Zeile = `[Ausrichtung 0/1/2, Vorschub, y (NaN = keins), nTspans, (Stil, Absatz, Run, von, bis)*]` +//! — der Text eines Tspans ist `runs[Run].text.slice(von, bis)` des Absatzes in der Eingabe (TS hat +//! sie schon; keine Texte über die Grenze zurück). + +use crate::model::RichTextDoc; +use crate::text_layout::{layout_refs, tspan_of, stamp_block_refs, stamp_extra_tspan, text_frame_corners, wrap_plain, LayoutOpts, LineAlign, LineRef, Tok, Tspan}; +use wasm_bindgen::prelude::wasm_bindgen; + +fn style_bits(t: &Tspan) -> f64 { + let deco = match t.text_decoration { + Some("underline") => 4, + Some("line-through") => 8, + Some(_) => 12, + None => 0, + }; + (t.bold as u32 | (t.italic as u32) << 1 | deco | (t.baseline_shift.is_some() as u32) << 4) as f64 +} + +/// Verweis-Zeilen flach (Format s. Modulkopf); `style(tok)` = Stil (Tspan ohne Text) des Stücks, +/// `ys` = Grundlinien je Zeile. +fn encode_lines(lines: &[LineRef], ys: Option<&[f64]>, style: impl Fn(&Tok) -> Tspan) -> Vec { + let mut styles: Vec = Vec::new(); + let mut keys: Vec<(usize, usize)> = Vec::new(); + let mut key_style: Vec = Vec::new(); + let mut body: Vec = Vec::new(); + for (k, l) in lines.iter().enumerate() { + body.extend_from_slice(&[l.align.code() as f64, l.line_height, ys.and_then(|y| y.get(k).copied()).unwrap_or(f64::NAN), l.toks.len() as f64]); + for t in &l.toks { + let si = match keys.iter().position(|q| *q == (t.para, t.run)) { + Some(i) => key_style[i], + None => { + let st = style(t); + let same = |u: &Tspan| { + u.font_size.to_bits() == st.font_size.to_bits() + && style_bits(u) == style_bits(&st) + && u.baseline_shift.map(f64::to_bits) == st.baseline_shift.map(f64::to_bits) + && u.fill == st.fill + && u.font_family == st.font_family + }; + let si = match styles.iter().position(same) { + Some(i) => i, + None => { + styles.push(st); + styles.len() - 1 + } + }; + keys.push((t.para, t.run)); + key_style.push(si); + si + } + }; + body.extend_from_slice(&[si as f64, t.para as f64, t.run as f64, t.u0 as f64, t.u1 as f64]); + } + } + let mut out = vec![lines.len() as f64, styles.len() as f64]; + for t in &styles { + out.extend_from_slice(&[t.font_size, style_bits(t), t.baseline_shift.unwrap_or(0.0), t.fill.encode_utf16().count() as f64]); + out.push(t.font_family.as_ref().map_or(-1.0, |f| f.encode_utf16().count() as f64)); + out.extend(t.fill.encode_utf16().map(f64::from)); + if let Some(f) = &t.font_family { + out.extend(f.encode_utf16().map(f64::from)); + } + } + out.extend(body); + out +} + +/// Zeilen eines Dokuments (`SvgLine[]`, flach). `opts` = `[lineHeight, unitPerPt, basePt gesetzt +/// 0/1, basePt, Spaltenbreite]` (Spalte ≤ 0/NaN = kein Umbruch); `color` fehlt → `#000000`. +/// Leer = kaputte Eingabe. +#[wasm_bindgen] +pub fn text_lines(doc_json: &str, opts: &[f64], color: Option) -> Vec { + let Ok([line_height, unit_per_pt, has_base, base_pt, wrap]) = <[f64; 5]>::try_from(opts) else { return Vec::new() }; + let Ok(doc) = serde_json::from_str::(doc_json) else { return Vec::new() }; + let o = LayoutOpts { line_height, unit_per_pt, base_pt: if has_base != 0.0 { base_pt } else { 12.0 }, color: color.as_deref().unwrap_or("#000000") }; + let refs = layout_refs(&doc, &o, Some(wrap)); + encode_lines(&refs, None, |t| tspan_of(String::new(), &doc.paragraphs[t.para].runs[t.run].marks, o.base_pt, o.unit_per_pt, o.color)) +} + +/// Rahmen eines Einzeltexts: `opts` = `[atX, atY, heightM, angle, Spaltenbreite (NaN = keine), +/// Grundlinie→Oberkante]` → `[x0, y0, …, x3, y3]` (Reihenfolge s. `text_frame_corners`). Leer = +/// kaputte Eingabe. +#[wasm_bindgen] +pub fn text_frame(doc_json: &str, opts: &[f64]) -> Vec { + let Ok([x, y, height_m, angle, wrap, baseline]) = <[f64; 6]>::try_from(opts) else { return Vec::new() }; + let Ok(doc) = serde_json::from_str::(doc_json) else { return Vec::new() }; + text_frame_corners(&doc, (x, y), height_m, angle, Some(wrap), baseline).iter().flat_map(|c| [c.0, c.1]).collect() +} + +/// Raumstempel-Block der Plan-Ansicht (`stamp_block_refs`): `prim_json` = das Primitiv `text`; +/// Zeilen flach mit Grundlinie `y` (um `y0` zentriert, `y` nach unten; Live-Zeile `i` als Absatz +/// Absatzzahl + `i`). Leer = kaputte Eingabe. +#[wasm_bindgen] +pub fn text_stamp_block(prim_json: &str, unit_per_pt: f64, y0: f64) -> Vec { + let Ok(p) = serde_json::from_str::(prim_json) else { return Vec::new() }; + let extra: Vec<(&str, LineAlign)> = p.extra_lines.iter().map(|l| (l.text.as_str(), LineAlign::of(Some(l.align)))).collect(); + let color = p.color.as_deref().unwrap_or("#000000"); + let placed = stamp_block_refs(&p.doc, &extra, p.base_pt, unit_per_pt, color, y0); + let ys: Vec = placed.iter().map(|q| q.1).collect(); + let lines: Vec = placed.into_iter().map(|q| q.0).collect(); + let n = p.doc.paragraphs.len(); + encode_lines(&lines, Some(&ys), |t| { + if t.para >= n { + stamp_extra_tspan(String::new(), p.base_pt, unit_per_pt, color) + } else { + tspan_of(String::new(), &p.doc.paragraphs[t.para].runs[t.run].marks, p.base_pt, unit_per_pt, color) + } + }) +} + +/// Einfacher Text auf die Spalte `wrap` umbrochen (Schriftgrösse `font_size`, gleiche Einheiten), +/// Zeilen als JSON-Liste. +#[wasm_bindgen] +pub fn text_wrap_plain(text: &str, wrap: f64, font_size: f64) -> String { + serde_json::to_string(&wrap_plain(text, wrap, font_size)).unwrap_or_default() +} diff --git a/src/export/dxfCadParts.test.ts b/src/export/dxfCadParts.test.ts deleted file mode 100644 index 2e7ce4ce..00000000 --- a/src/export/dxfCadParts.test.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { fontNameOf } from "./dxfCadParts"; - -describe("fontNameOf", () => { - it("erste echte Familie, ohne Anführungszeichen; generische/Variablen übersprungen", () => { - expect(fontNameOf('"Helvetica Neue", Arial, sans-serif')).toBe("Helvetica Neue"); - expect(fontNameOf("var(--font-ui, sans-serif)")).toBeNull(); - expect(fontNameOf("sans-serif, Arial")).toBe("Arial"); - expect(fontNameOf("'Source Sans 3'")).toBe("Source Sans 3"); - expect(fontNameOf(undefined)).toBeNull(); - expect(fontNameOf("")).toBeNull(); - }); -}); diff --git a/src/export/dxfCadParts.ts b/src/export/dxfCadParts.ts deleted file mode 100644 index ff2beb33..00000000 --- a/src/export/dxfCadParts.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Baustein des Fachplaner-Exports ([C2], 28.10.): Schriftname aus CSS-Familie (Text-Layout bleibt TS). -// Linientypen, blocklokale Primitive, Papierformate und der Sammler selbst liegen seit [K3d] im Kern -// (`src-tauri/core/src/plan_dxf.rs`). - -/** Erste Schriftfamilie aus einem CSS-`font-family`-Wert ohne Anführungszeichen; generische Familien/CSS-Variablen → null. */ -export function fontNameOf(css: string | undefined | null): string | null { - if (!css) return null; - // `var(--font-ui, sans-serif)` enthält selbst ein Komma: vor dem Teilen entfernen. - for (const raw of css.replace(/var\([^)]*\)/g, "").split(",")) { - const name = raw.trim().replace(/^["']|["']$/g, "").trim(); - if (!name) continue; - if (/^(sans-serif|serif|monospace|cursive|fantasy|system-ui|ui-sans-serif|inherit|initial)$/i.test(name)) continue; - return name; - } - return null; -} diff --git a/src/export/exportDxf.ts b/src/export/exportDxf.ts index a9a0b6c0..146230e1 100644 --- a/src/export/exportDxf.ts +++ b/src/export/exportDxf.ts @@ -11,9 +11,9 @@ // Seit [K3d] (29.10.) sammelt der Kern (`src-tauri/core/src/plan_dxf.rs`) Ebenen und Entitäten // direkt aus den Plan-Puffern und dem Projekt-Dokument in die flache Zeichnung (Kodierung s. // `src-tauri/fileio/src/export.rs`); Rust (acadrust, fileio) schreibt die Datei ([C1]/[C2]). -// DXF = R2018 ASCII (UTF-8), DWG = R2018. Hier bleibt das Text-Layout (Zeilen der Raumstempel, -// Absätze/Wörter der Einzeltexte, Schriftfamilien) — es geht als flache Eingabe an den Kern — -// und die Übergabe an fileio. Das Format-Modul wird nachgeladen: vor `buildPlanDxf`/ +// DXF = R2018 ASCII (UTF-8), DWG = R2018. Auch die Texte (Zeilen der Raumstempel, Absätze/Wörter +// der Einzeltexte, Schriftfamilien) setzt der Kern aus dem Text-JSON der Puffer; hier bleibt die +// Übergabe an fileio. Das Format-Modul wird nachgeladen: vor `buildPlanDxf`/ // `buildPlanDwg` einmal `await loadFileio()` (savePlanDxf und die CLI tun das). // // Fachplaner-Export (28.10., [C2]): damit in AutoCAD/BricsCAD weitergearbeitet werden kann, entstehen @@ -27,18 +27,13 @@ // Ausrichtung (Raumstempel mit Fläche als TEXT, links/Mitte/rechts), optional Papierbereich. // Alles andere (Wände, Umrisse, Schraffuren) bleibt wie bisher Linie/Polylinie/HATCH. -import type { Plan, Primitive } from "../plan/generatePlan"; +import type { Plan } from "../plan/generatePlan"; import type { Project } from "../model/types"; -import type { Marks } from "../text/richText"; import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension"; -import { plainText } from "../text/richText"; -import { docToLines } from "../text/renderHtml"; import { fileio, loadFileio } from "../engine/fileioWasm"; import { core } from "../engine/coreWasm"; import { documentFor } from "../core/document"; import { planParts, withPlanParts } from "../plan/planParts"; -import { planTextEntries } from "../plan/planLazy"; -import { fontNameOf } from "./dxfCadParts"; export interface ExportDxfOptions { /** Titel/Geschossname (nur als Kommentar-freundlicher Dateiname genutzt). */ @@ -82,61 +77,11 @@ export interface FlatDrawing { stats(): { model: Record; blocks: Record }; } -/** Eine Zeile einer (Rich-)Text-Ausgabe. */ -interface OutLine { - text: string; - /** Schrifthöhe (Meter). */ - height: number; - align: 0 | 1 | 2; - marks?: Marks; - /** Versatz der Grundlinie vom Anker nach unten (Meter, ≥ 0 für spätere Zeilen). */ - down: number; -} - /** Massstab des Exports (endlich und > 0, sonst 1:100). */ function scaleOf(opts: ExportDxfOptions): number { return opts.scaleDenominator && Number.isFinite(opts.scaleDenominator) && opts.scaleDenominator > 0 ? opts.scaleDenominator : DEFAULT_SCALE_DENOMINATOR; } -/** - * Text-Eingabe für den Kern (`plan_dxf::texts_from`): je Raumstempel die gesetzten Zeilen, je - * Einzeltext Anker/Winkel/Höhe/Spalte, Schrift und Absätze mit ihren Wörtern (`split(/\s+/)`). - * Nur die Text-Einträge des Plans werden gelesen. - */ -function textInput(plan: Plan, scale: number, defaultFont: string): { nums: Float64Array; strs: string } { - const nums: number[] = []; - const strs: string[] = []; - const idx = new Map(); - const S = (s: string): number => { - let i = idx.get(s); - if (i === undefined) { - i = strs.length; - strs.push(s); - idx.set(s, i); - } - return i; - }; - const family = (marks: Marks | undefined): number => S(fontNameOf(marks?.font) ?? defaultFont); - for (const { i, p } of planTextEntries(plan)) { - if (p.kind === "text") { - const lines = stampLines(p, scale); - nums.push(i, 6, p.at.x, p.at.y, lines.length); - for (const l of lines) nums.push(S(l.text), l.height, l.align, family(l.marks), l.marks?.bold ? 1 : 0, l.marks?.italic ? 1 : 0, l.down); - } else if (p.kind === "drawingText") { - const paragraphs = p.doc ? plainText(p.doc).split("\n") : p.text.split(/\r?\n/); - const marks = p.marks ?? p.doc?.paragraphs[0]?.runs[0]?.marks; - const wrap = typeof p.wrapWidth === "number" ? p.wrapWidth : NaN; - nums.push(i, 7, p.at.x, p.at.y, p.angle, p.heightM, wrap, family(marks), marks?.bold ? 1 : 0, marks?.italic ? 1 : 0, paragraphs.length); - for (const para of paragraphs) { - const words = para.split(/\s+/); - nums.push(S(para), words.length); - for (const w of words) nums.push(S(w)); - } - } - } - return { nums: Float64Array.from(nums), strs: strs.map((s) => "\0" + s).join("") }; -} - /** Kern-Antwort (`plan_dxf::encode`) → flache Zeichnung; leer = Fehler. */ function decodeFlat(bytes: Uint8Array): FlatDrawing { const b = bytes.byteOffset % 8 === 0 ? bytes : bytes.slice(); @@ -184,14 +129,11 @@ export function collectPlanDrawing( opts: ExportDxfOptions = {}, ): FlatDrawing { const scale = scaleOf(opts); - // Standard-Schrift: erste im Projekt hinterlegte Schrift der Textstile, sonst Arial. - const defaultFont = (project.textStyles ?? []).map((s) => fontNameOf(s.marks.font)).find((f) => f) ?? "Arial"; - const { nums, strs } = textInput(plan, scale, defaultFont); const b = plan.bounds; const o = Float64Array.of(scale, (opts.includeHatches ?? true) ? 1 : 0, opts.dimUnit === "cm" ? 1 : 0, opts.paperLayout ? 1 : 0, b.minX, b.minY, b.maxX, b.maxY); const doc = documentFor(project).id; // Eigener Puffer mit Schraffur-JSON (Verlauf-Schraffuren brauchen ihre Farben). - const bytes = withPlanParts(planParts(plan, true), (segs) => core().plan_dxf_flat(doc, segs, nums, strs, o, defaultFont)); + const bytes = withPlanParts(planParts(plan, true), (segs) => core().plan_dxf_flat(doc, segs, o)); return decodeFlat(bytes); } @@ -242,36 +184,6 @@ function writeCad(format: CadExportFormat, drawing: FlatDrawing): Uint8Array { return bytes; } -/** Stempel-/Textzeilen eines Primitivs `text` (Raumstempel): Rich-Text-Doc + Live-Zeilen, vertikal um den Anker zentriert wie in der Plan-Ansicht. */ -function stampLines(p: Extract, scale: number): OutLine[] { - const unitPerPt = (0.0254 / 72) * scale; // 1 pt Papier in Modell-Metern - const baseFs = p.basePt * unitPerPt; - const lineGap = baseFs * 1.3; - const docLines = docToLines(p.doc, { x: 0, y: 0, lineHeight: lineGap, unitPerPt, basePt: p.basePt, color: p.color }); - const lines = [ - ...docLines.map((l) => ({ align: l.align, lineHeight: l.lineHeight, ts: l.tspans })), - ...p.extraLines.map((l) => ({ align: l.align, lineHeight: lineGap, ts: [{ text: l.text, fontSize: baseFs * 0.8, fontFamily: undefined as string | undefined, fontWeight: undefined as string | undefined, fontStyle: undefined as string | undefined }] })), - ]; - if (lines.length === 0) return []; - const totalH = baseFs + lines.slice(1).reduce((s, l) => s + l.lineHeight, 0); - let down = -totalH / 2 + baseFs * 0.8; - const out: OutLine[] = []; - lines.forEach((l, k) => { - if (k > 0) down += l.lineHeight; - const text = l.ts.map((t) => t.text).join(""); - const first = l.ts[0]; - if (!text.trim() || !first) return; - out.push({ - text, - height: Math.max(...l.ts.map((t) => t.fontSize)), - align: l.align === "center" ? 1 : l.align === "right" ? 2 : 0, - marks: { font: first.fontFamily, bold: first.fontWeight === "700", italic: first.fontStyle === "italic" }, - down, - }); - }); - return out; -} - /** Baut die Datei und löst den Download aus (Browser). Lädt das Format-Modul bei Bedarf. */ export async function savePlanDxf( plan: Plan, diff --git a/src/export/planToPrintSvg.ts b/src/export/planToPrintSvg.ts index 140f36db..19e0f048 100644 --- a/src/export/planToPrintSvg.ts +++ b/src/export/planToPrintSvg.ts @@ -20,19 +20,15 @@ // Vektorlinien direkt ins SVG. So bleibt das PDF rein vektoriell und scharf. // // Seit [K3d] (29.10.) rechnet der Kern die Knoten aus den Plan-Puffern -// (`src-tauri/core/src/plan_print_svg.rs`, Anweisungsliste); hier bleiben der -// -Rahmen, die Bild- (laufende Ids) und die Einzeltexte -// (Text-Layout `wrapDocToLines`). Ausgabe unverändert (gleiche Knoten/Attribute). +// (`src-tauri/core/src/plan_print_svg.rs`, Anweisungsliste) samt gesetzter Einzeltexte; +// hier bleiben der -Rahmen und die Bild- (laufende Ids). Ausgabe unverändert +// (gleiche Knoten/Attribute). // // Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md). -import type { HatchRender, Plan, Primitive } from "../plan/generatePlan"; -import type { Vec2 } from "../model/types"; -import { wrapDocToLines, type SvgLine } from "../text/renderHtml"; -import { docFromText } from "../text/richText"; +import type { HatchRender, Plan } from "../plan/generatePlan"; import { core } from "../engine/coreWasm"; import { planParts, withPlanParts } from "../plan/planParts"; -import { planPrimAt } from "../plan/planLazy"; /** SVG-Namespace für die programmatisch erzeugten Knoten. */ const SVG_NS = "http://www.w3.org/2000/svg"; @@ -111,15 +107,6 @@ function mmPerMeter(n: number): number { return 1000 / n; } -/** - * Bildet einen Welt-Punkt (Meter) auf Papier-Millimeter ab. Der Inhalt wird so - * verschoben, dass die Plan-Bounds (in mm) zentriert auf dem Blatt liegen. - * Plan-Y zeigt nach oben → SVG-Y nach unten (Spiegelung), daher das Minus. - */ -interface Mapper { - (p: Vec2): Vec2; -} - /** * Erzeugt das Druck-SVG aus einem Plan. Reihenfolge der Primitive bleibt * erhalten (Zeichenreihenfolge = Stapelung); Schraffuren werden als geklippte @@ -147,11 +134,6 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg { // Blatt. Wir mappen maxY → offsetYmm. const offsetYmm = (opts.pageHeightMm - contentHmm) / 2; - const map: Mapper = (p) => ({ - x: offsetXmm + (p.x - b.minX) * k, - y: offsetYmm + (b.maxY - p.y) * k, - }); - const svg = document.createElementNS(SVG_NS, "svg") as SVGSVGElement; svg.setAttribute("xmlns", SVG_NS); // Breite/Höhe als REINE Zahlen (= viewBox-Einheiten), KEINE „mm"-Einheit: so @@ -175,7 +157,7 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg { const o = Float64Array.of(n, opts.pageWidthMm, opts.pageHeightMm, b.minX, b.minY, b.maxX, b.maxY); const ops = withPlanParts(planParts(plan, true), (segs) => core().plan_print_svg_ops(segs, o)); if (!ops) throw new Error("Druck-SVG: Plan im Kern unlesbar"); - applyOps(svg, ops.slice(1), plan, map, k); + applyOps(svg, ops.slice(1)); return { svg, @@ -187,17 +169,22 @@ export function planToPrintSvg(plan: Plan, opts: PrintSvgOptions): PrintSvg { /** * Legt die Knoten der Kern-Anweisungsliste an (Format s. `plan_print_svg.rs`): Elemente mit ihren - * Attributen in Reihenfolge, Gruppen, Bild-Schraffuren (`` hier) und Einzeltexte (Layout hier). + * Attributen in Reihenfolge, Gruppen, Bild-Schraffuren (`` hier) und gesetzte Einzeltexte. */ -function applyOps(svg: SVGSVGElement, ops: string, plan: Plan, map: Mapper, mmPerM: number): void { +function applyOps(svg: SVGSVGElement, ops: string): void { if (!ops) return; let g: SVGElement | null = null; + let text: SVGElement | null = null; + let line: SVGElement | null = null; + const attrs = (el: SVGElement, f: string[], from: number) => { + for (let i = from; i + 1 < f.length; i += 2) el.setAttribute(f[i], f[i + 1]); + }; for (const rec of ops.split("\u001e")) { const f = rec.split("\u001f"); switch (f[0]) { case "E": { const el = document.createElementNS(SVG_NS, f[2]) as SVGElement; - for (let i = 3; i + 1 < f.length; i += 2) el.setAttribute(f[i], f[i + 1]); + attrs(el, f, 3); (f[1] === "1" && g ? g : svg).appendChild(el); break; } @@ -219,87 +206,29 @@ function applyOps(svg: SVGSVGElement, ops: string, plan: Plan, map: Mapper, mmPe g?.appendChild(el); break; } - case "T": { - const p = planPrimAt(plan, Number(f[1])); - if (p?.kind !== "drawingText") break; - const node = drawingTextNode(p, map, mmPerM); - if (node) { - if (f[2]) node.setAttribute("opacity", f[2]); - svg.appendChild(node); - } + case "X": + // Einzeltext: mit Zeilen-s, darin je Run/Wort ein . + text = document.createElementNS(SVG_NS, "text") as SVGElement; + attrs(text, f, 1); + svg.appendChild(text); + break; + case "L": + line = document.createElementNS(SVG_NS, "tspan") as SVGElement; + attrs(line, f, 2); + if (f[1]) line.textContent = f[1]; + text?.appendChild(line); + break; + case "R": { + const run = document.createElementNS(SVG_NS, "tspan") as SVGElement; + attrs(run, f, 2); + run.textContent = f[1]; + line?.appendChild(run); break; } } } } -/** - * Modellverankerter Einzeltext (Text-Werkzeug/DXF-Import) als `` mit - * ``-Zeilen — analog zur Bildschirm-Darstellung (PlanView.tsx - * `case "drawingText"`), aber DOM-Knoten statt JSX. Bricht bei gesetzter - * Spaltenbreite wortweise um (Run-Grenzen bleiben erhalten). - */ -function drawingTextNode( - p: Extract, - map: Mapper, - mmPerM: number, -): SVGTextElement | null { - const doc = p.doc ?? docFromText(p.text, p.marks ?? {}); - const c = map(p.at); - const fontSizeMm = p.heightM * mmPerM; - const unitPerPt = (0.0254 / 72) * mmPerM; - const basePt = unitPerPt > 0 ? p.heightM / unitPerPt : 0; - const lineHeight = fontSizeMm * 1.25; - const wrapWidthUnits = p.wrapWidth && p.wrapWidth > 0 ? p.wrapWidth * mmPerM : undefined; - const lines: SvgLine[] = wrapDocToLines(doc, { - x: 0, - y: 0, - lineHeight, - unitPerPt, - basePt, - color: p.color, - ...(wrapWidthUnits ? { wrapWidthUnits } : {}), - }); - if (lines.length === 0) return null; - - const el = document.createElementNS(SVG_NS, "text"); - const deg = -(p.angle * 180) / Math.PI; - if (deg) el.setAttribute("transform", `rotate(${round(deg)} ${round(c.x)} ${round(c.y)})`); - let y = c.y; - lines.forEach((line, k) => { - if (k > 0) y += line.lineHeight; - const anchor = line.align === "center" ? "middle" : line.align === "right" ? "end" : "start"; - const x = !wrapWidthUnits - ? c.x - : line.align === "center" - ? c.x + wrapWidthUnits / 2 - : line.align === "right" - ? c.x + wrapWidthUnits - : c.x; - const lineTspan = document.createElementNS(SVG_NS, "tspan"); - lineTspan.setAttribute("x", String(round(x))); - lineTspan.setAttribute("y", String(round(y))); - lineTspan.setAttribute("text-anchor", anchor); - if (line.tspans.length === 0) { - lineTspan.textContent = "​"; - } else { - for (const ts of line.tspans) { - const run = document.createElementNS(SVG_NS, "tspan"); - run.setAttribute("font-size", String(round(ts.fontSize))); - run.setAttribute("fill", ts.fill); - if (ts.fontWeight) run.setAttribute("font-weight", ts.fontWeight); - if (ts.fontStyle) run.setAttribute("font-style", ts.fontStyle); - run.setAttribute("font-family", ts.fontFamily ?? "Helvetica, Arial, sans-serif"); - if (ts.textDecoration) run.setAttribute("text-decoration", ts.textDecoration); - run.textContent = ts.text; - lineTspan.appendChild(run); - } - } - el.appendChild(lineTspan); - }); - return el; -} - /** Auf 3 Nachkommastellen runden (kompaktes, exaktes SVG). */ function round(v: number): number { return Math.round(v * 1000) / 1000; diff --git a/src/plan/planParts.ts b/src/plan/planParts.ts index b4e5eb37..d03312ed 100644 --- a/src/plan/planParts.ts +++ b/src/plan/planParts.ts @@ -59,8 +59,8 @@ const cache = new WeakMap = { - black: "#000000", - white: "#ffffff", - red: "#ff0000", - none: "none", - transparent: "none", -}; - -/** Hex/Named-Farbe → [r,g,b,a] in 0..1, oder null bei "none"/leer (Kern: `plan_scene::to_rgba`). */ -function toRgba(input: string | undefined, alpha = 1): RRgba | null { - if (!input) return null; - let h = input.trim().toLowerCase(); - if (h === "none" || h === "transparent") return null; - if (h[0] !== "#") { - const mapped = NAMED[h]; - if (!mapped) return [0, 0, 0, alpha]; - if (mapped === "none") return null; - h = mapped; - } - h = h.slice(1); - // Kurzformen auf Langform expandieren (#rgb → #rrggbb, #rgba → #rrggbbaa). - if (h.length === 3 || h.length === 4) h = h.split("").map((c) => c + c).join(""); - if (h.length !== 6 && h.length !== 8) return [0, 0, 0, alpha]; - const r = parseInt(h.slice(0, 2), 16) / 255; - const g = parseInt(h.slice(2, 4), 16) / 255; - const b = parseInt(h.slice(4, 6), 16) / 255; - // 8-stelliges Hex trägt den Alpha-Kanal selbst; sonst der Parameter. - const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : alpha; - if (![r, g, b, a].every((v) => Number.isFinite(v))) return [0, 0, 0, alpha]; - return [r, g, b, a]; -} +const ALIGNS: readonly RTextAlign[] = ["left", "center", "right"]; /** - * Textzeilen und eingebettete Bilder eines Plans in Zeichenreihenfolge. Layout wie im SVG-Pfad - * (PlanView, case "text"): Rich-Text-Zeilen + Live-Zusatzzeilen, Block vertikal um den Anker - * zentriert, Zeilenvorschub 1.3·Basisgröße; Einzeltexte (`drawingText`) top-down ab `at` mit - * `heightM` als Basisgrösse. `paperScaleN` (1:N) rechnet Papier-mm in Modell-Meter um. + * Textzeilen eines Plans in Zeichenreihenfolge, gesetzt im Kern (`plan_text::scene_texts`): Raumstempel + * = Rich-Text-Zeilen + Live-Zusatzzeilen, Block vertikal um den Anker zentriert, Vorschub 1.3·Basisgrösse; + * Einzeltexte (`drawingText`) top-down ab `at` mit `heightM` als Basisgrösse, umbrochen auf die Spalte. + * `paperScaleN` (1:N) rechnet Papier-mm in Modell-Meter um. */ -export function planSceneTexts(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): { texts: RText[]; images: RImage[] } { - const mmToM = paperScaleN / 1000; // Papier-mm → Modell-Meter beim gewählten Massstab. - const texts: RText[] = []; - const images: RImage[] = []; - const ranges = plan.greyedRanges; - // Nur die Text-/Bild-Einträge ([K3d], aus den Typ-Kennungen des Plan-Puffers). - for (const { i, p } of planTextEntries(plan)) { - if (p.kind === "text") { - const greyed = p.greyed || inGreyedRange(ranges, i); - const defCol = greyedColor(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], greyed); - // unitPerPt = PT_TO_MM → tspan.fontSize ist direkt die Papier-mm-Größe. - const docLines = docToLines(p.doc, { - x: 0, - y: 0, - lineHeight: 0, - unitPerPt: PT_TO_MM, - basePt: p.basePt, - color: p.color, - }); - const baseMm = p.basePt * PT_TO_MM; - const flat: { content: string; sizeMm: number; color: RRgba; align: RTextAlign }[] = []; - for (const line of docLines) { - flat.push({ - // Runs einer Zeile werden zusammengelegt (ein Buffer je Zeile); - // Größe/Farbe des größten bzw. ersten Runs gelten für die Zeile. - content: line.tspans.map((t) => t.text).join(""), - sizeMm: line.tspans.length ? Math.max(...line.tspans.map((t) => t.fontSize)) : baseMm, - color: greyedColor(toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, greyed), - align: line.align, - }); - } - for (const line of p.extraLines) { - flat.push({ content: line.text, sizeMm: baseMm * 0.8, color: defCol, align: line.align }); - } - if (flat.length > 0) { - const baseH = baseMm * mmToM; // Basisgröße in Modell-Metern, beim gewählten Massstab - const lineGap = baseH * 1.3; - const totalH = baseH + (flat.length - 1) * lineGap; - flat.forEach((line, k) => { - if (!line.content.trim()) return; // Leerzeile: nur Vorschub - texts.push({ - // Baseline der Zeile k (Modell-Y nach oben, deshalb minus): - // Browser: startY = c.y − H/2 + 0.8·fs (Bildschirm-Y nach unten). - pos: [p.at.x, p.at.y + totalH / 2 - baseH * 0.8 - k * lineGap], - content: line.content, - sizeMm: line.sizeMm, - color: line.color, - align: line.align, - }); - }); - } - } else if (p.kind === "drawingText") { - // Modellverankerter Einzeltext (Text-Werkzeug/DXF-Import): top-down ab `at`, `heightM` - // (Modell-Meter) als Basisgrösse — massstabsfrei an der Modellgeometrie verankert. - const greyed = p.greyed || inGreyedRange(ranges, i); - const doc = p.doc ?? docFromText(p.text, p.marks ?? {}); - const defCol = greyedColor(toRgba(p.color, 1) ?? [0.1, 0.1, 0.1, 1], greyed); - const unitPerPt = PT_TO_MM * mmToM; // pt (Run-Override) -> Papier-mm -> Modell-Meter. - const basePt = unitPerPt > 0 ? p.heightM / unitPerPt : 0; - const lineHeight = p.heightM * 1.25; - const wrapWidthUnits = p.wrapWidth && p.wrapWidth > 0 ? p.wrapWidth : undefined; - const docLines = wrapDocToLines(doc, { - x: 0, - y: 0, - lineHeight, - unitPerPt, - basePt, - color: p.color, - ...(wrapWidthUnits ? { wrapWidthUnits } : {}), - }); - let dy = 0; - docLines.forEach((line, k) => { - if (k > 0) dy += line.lineHeight; - const content = line.tspans.map((t) => t.text).join(""); - if (!content.trim()) return; - const sizeM = line.tspans.length ? Math.max(...line.tspans.map((t) => t.fontSize)) : p.heightM; - texts.push({ - pos: [p.at.x, p.at.y - dy], - content, - sizeMm: unitPerPt > 0 ? sizeM / mmToM : sizeM, - color: greyedColor(toRgba(line.tspans[0]?.fill ?? p.color, 1) ?? defCol, greyed), - align: line.align, - }); - }); - } else if (p.kind === "drawingImage") { - // Eingebettetes Rasterbild — keine Rust-Textur (s. `RImage`); `sceneToPrintSvg.ts` liest es. - images.push({ min: [p.min.x, p.min.y], max: [p.max.x, p.max.y], src: p.src, opacity: p.opacity }); - } +function sceneTexts(plan: Plan, paperScaleN: number): RText[] { + const greyed = greyedFlat(plan); + const f = withPlanParts(planParts(plan), (segs) => core().plan_scene_texts(segs, greyed, paperScaleN)); + const n = f[0] ?? 0; + const out: RText[] = new Array(n); + let u = 1 + n * 9; + for (let k = 0; k < n; k++) { + const o = 1 + k * 9; + const len = f[o + 8]; + let content = ""; + for (let j = 0; j < len; j += 8192) content += String.fromCharCode.apply(null, Array.from(f.subarray(u + j, u + Math.min(len, j + 8192)))); + u += len; + out[k] = { pos: [f[o], f[o + 1]], content, sizeMm: f[o + 2], color: [f[o + 3], f[o + 4], f[o + 5], f[o + 6]], align: ALIGNS[f[o + 7]] ?? "left" }; } - return { texts, images }; + return out; } -const ALIGN: Record = { left: 0, center: 1, right: 2 }; -const textEncoder = new TextEncoder(); +/** Eingebettete Bilder des Plans (nur Text-/Bild-Einträge, kein Layout). */ +function sceneImages(plan: Plan): RImage[] { + const images: RImage[] = []; + for (const { p } of planTextEntries(plan)) { + if (p.kind === "drawingImage") images.push({ min: [p.min.x, p.min.y], max: [p.max.x, p.max.y], src: p.src, opacity: p.opacity }); + } + return images; +} /** Leere render2d-Szene (nur Kopf), falls der Kern nichts liefern kann. */ function emptySceneBin(): Uint8Array { @@ -295,24 +177,12 @@ function emptySceneBin(): Uint8Array { /** * render2d-Szene (Binärformat v1, `render2d/src/scene_bin.rs`) für `set_scene_bin` bzw. - * `push_native_scene`. Geometrie aus dem Kern, Texte aus {@link planSceneTexts}; + * `push_native_scene`. Geometrie und Texte (beim Massstab 1:`paperScaleN`) aus dem Kern; * `plan.greyedRanges` gelten wie materialisiertes `greyed`. */ export function planSceneBin(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): Uint8Array { - const { texts } = planSceneTexts(plan, paperScaleN); - const nums = new Float64Array(texts.length * 9); - const strs = texts.map((t) => textEncoder.encode(t.content)); - let nBytes = 0; - for (const s of strs) nBytes += s.length; - const bytes = new Uint8Array(nBytes); - let o = 0; - texts.forEach((t, i) => { - nums.set([t.pos[0], t.pos[1], t.sizeMm, t.color[0], t.color[1], t.color[2], t.color[3], ALIGN[t.align] ?? 0, strs[i].length], i * 9); - bytes.set(strs[i], o); - o += strs[i].length; - }); const greyed = greyedFlat(plan); - const out = withPlanParts(planParts(plan), (segs) => core().plan_scene_bin(segs, greyed, nums, bytes)); + const out = withPlanParts(planParts(plan), (segs) => core().plan_scene_bin(segs, greyed, paperScaleN)); return out.length ? out : emptySceneBin(); } @@ -385,12 +255,10 @@ function decodeSceneF64(f: Float64Array): SceneGeometry { /** * Plan → Render-Szene als Objekte (Druck-/SVG-Export, `dossier-cli plan --format json`). - * `paperScaleN` ist der Massstab-Nenner N (1:N) für die Zeilenlage der Texte (s. - * {@link planSceneTexts}). + * `paperScaleN` ist der Massstab-Nenner N (1:N) für die Zeilenlage der Texte. */ export function planToRenderScene(plan: Plan, paperScaleN: number = STAMP_DEFAULT_N): RScene { const greyed = greyedFlat(plan); const geo = decodeSceneF64(withPlanParts(planParts(plan), (segs) => core().plan_scene_f64(segs, greyed))); - const { texts, images } = planSceneTexts(plan, paperScaleN); - return { ...geo, texts, images, bounds: { ...plan.bounds } }; + return { ...geo, texts: sceneTexts(plan, paperScaleN), images: sceneImages(plan), bounds: { ...plan.bounds } }; } diff --git a/src/text/renderHtml.ts b/src/text/renderHtml.ts index 96f70cbc..e7046533 100644 --- a/src/text/renderHtml.ts +++ b/src/text/renderHtml.ts @@ -3,8 +3,12 @@ // nach SVG- (für den vektoriellen Grundriss-/Print-Renderer). Beide Wege // bilden dieselbe Mark→Stil-Zuordnung ab, damit Editor-Vorschau und gezeichneter // Text identisch aussehen. Reines Modul: keine React-/App-Abhängigkeit. +// +// Das Zeilen-Layout (`docToLines`/`wrapDocToLines`: Run→Tspan, Wortumbruch) rechnet der Rust-Kern +// (`src-tauri/core/src/text_layout.rs`, Bindung `text_lines`); hier nur die Fassade. import type { Marks, Paragraph, RichTextDoc, TextRun } from "./richText"; +import { core } from "../engine/coreWasm"; // ── Text-Escaping ─────────────────────────────────────────────────────────── @@ -172,116 +176,123 @@ export interface SvgTextOptions { color?: string; } -/** - * Zerlegt das Dokument in Zeilen/Tspans mit bereits in Benutzereinheiten - * umgerechneten Grössen. Der Aufrufer positioniert die Zeilen selbst (Baseline - * der Zeile i = `y + Σ lineHeight[0..i-1]`). - */ -export function docToLines(doc: RichTextDoc, opts: SvgTextOptions): SvgLine[] { - const basePt = opts.basePt ?? 12; - const color = opts.color ?? "#000000"; - const baseUnit = basePt * opts.unitPerPt; - return doc.paragraphs.map((p) => ({ - align: p.align ?? "left", - lineHeight: p.lineHeight != null ? baseUnit * p.lineHeight : opts.lineHeight, - tspans: p.runs - .filter((r) => r.text.length > 0) - .map((r) => runToTspan(r, basePt, opts.unitPerPt, color)), - })); +const ALIGNS = ["left", "center", "right"] as const; + +/** UTF-16-Einheiten `f[at…at+n)` als Text. */ +function unitsText(f: Float64Array, at: number, n: number): string { + let s = ""; + for (let j = 0; j < n; j += 4096) s += String.fromCharCode.apply(null, Array.from(f.subarray(at + j, at + Math.min(n, j + 4096)))); + return s; } -/** Geschätzte Zeichenbreite als Vielfaches der Schriftgrösse (gleiche Heuristik - * wie der bisherige Wortumbruch für einheitlich formatierten Text, s. - * PlanView.tsx `case "drawingText"`) — kein echtes Font-Metrics-Messen, aber - * für die Platzierung von Zeilenumbrüchen ausreichend. */ -const CHAR_WIDTH_FACTOR = 0.55; +/** + * Flache Zeilen des Kerns (Format s. `src-tauri/core/src/web/text_layout.rs`) → `SvgLine[]`, mit + * `withY` samt Grundlinie `y`. Die Tspan-Texte sind Ausschnitte der Eingabe (`text(Absatz, Run)`). + * Feldreihenfolge der Tspans wie früher in TS. + */ +function decodeLines(f: Float64Array, text: (para: number, run: number) => string, withY: true): PlacedLine[]; +function decodeLines(f: Float64Array, text: (para: number, run: number) => string, withY: false): SvgLine[]; +function decodeLines(f: Float64Array, text: (para: number, run: number) => string, withY: boolean): Array { + if (f.length < 2) return []; + let k = 2; + const styles: Array> = []; + for (let i = 0; i < f[1]; i++) { + const [fontSize, bits, shift, nFill, nFam] = [f[k], f[k + 1], f[k + 2], f[k + 3], f[k + 4]]; + k += 5; + const fill = unitsText(f, k, nFill); + k += nFill; + const st: Omit = { fontSize, fill }; + if (bits & 1) st.fontWeight = "700"; + if (bits & 2) st.fontStyle = "italic"; + if (nFam >= 0) { + st.fontFamily = unitsText(f, k, nFam); + k += nFam; + } + const deco = bits & 12; + if (deco) st.textDecoration = deco === 4 ? "underline" : deco === 8 ? "line-through" : "underline line-through"; + if (bits & 16) st.baselineShift = shift; + styles.push(st); + } + const out: Array = new Array(f[0]); + for (let i = 0; i < f[0]; i++) { + const align = ALIGNS[f[k]] ?? "left"; + const lineHeight = f[k + 1]; + const y = f[k + 2]; + const n = f[k + 3]; + k += 4; + const tspans: SvgTspan[] = new Array(n); + for (let j = 0; j < n; j++, k += 5) { + const src = text(f[k + 1], f[k + 2]); + tspans[j] = { text: f[k + 3] === 0 && f[k + 4] === src.length ? src : src.slice(f[k + 3], f[k + 4]), ...styles[f[k]] }; + } + out[i] = withY ? { tspans, align, lineHeight, y } : { tspans, align, lineHeight }; + } + return out; +} + +/** Zuletzt gesetzte Zeilen je Dokument-Objekt und Optionen (Neuzeichnen beim Zoomen/Verschieben). */ +const memo = new WeakMap>(); + +/** Zeilen aus dem Kern (`text_lines`); kaputte Eingabe → keine Zeilen. Ergebnis nicht verändern (geteilt). */ +function kernelLines(doc: RichTextDoc, opts: SvgTextOptions, wrap: number | undefined): SvgLine[] { + const key = `${opts.lineHeight}|${opts.unitPerPt}|${opts.basePt}|${wrap}|${opts.color}`; + let byOpts = memo.get(doc); + const hit = byOpts?.get(key); + if (hit) return hit; + const o = Float64Array.of(opts.lineHeight, opts.unitPerPt, opts.basePt == null ? 0 : 1, opts.basePt ?? 0, wrap ?? NaN); + const lines = decodeLines(core().text_lines(JSON.stringify(doc), o, opts.color ?? undefined), (p, r) => doc.paragraphs[p].runs[r].text, false); + if (!byOpts) memo.set(doc, (byOpts = new Map())); + if (byOpts.size > 8) byOpts.clear(); + byOpts.set(key, lines); + return lines; +} + +/** + * Zerlegt das Dokument in Zeilen/Tspans mit bereits in Benutzereinheiten + * umgerechneten Grössen (eine Zeile je Absatz). Der Aufrufer positioniert die Zeilen selbst + * (Baseline der Zeile i = `y + Σ lineHeight[0..i-1]`). + */ +export function docToLines(doc: RichTextDoc, opts: SvgTextOptions): SvgLine[] { + return kernelLines(doc, opts, undefined); +} /** * Wie {@link docToLines}, bricht aber zusätzlich wortweise auf `wrapWidthUnits` * um (in denselben Benutzereinheiten wie `SvgTextOptions.x`) — für Textfelder/ - * -rahmen mit fester Breite (InDesign-artig). Ohne `wrapWidthUnits` identisch - * zu `docToLines` (eine Zeile je Absatz). Respektiert Run-Grenzen: ein Wort - * behält die Formatierung seines Runs, auch wenn die Zeile mehrere Runs mischt. + * -rahmen mit fester Breite (InDesign-artig). Wortbreite geschätzt (UTF-16-Länge × + * Schriftgrösse × 0.55, kein Font-Messen). Ohne `wrapWidthUnits` identisch zu `docToLines`. + * Respektiert Run-Grenzen: ein Wort behält die Formatierung seines Runs. */ export function wrapDocToLines( doc: RichTextDoc, opts: SvgTextOptions & { wrapWidthUnits?: number }, ): SvgLine[] { - if (!opts.wrapWidthUnits || opts.wrapWidthUnits <= 0) return docToLines(doc, opts); - const basePt = opts.basePt ?? 12; - const color = opts.color ?? "#000000"; - const baseUnit = basePt * opts.unitPerPt; - const maxWidth = opts.wrapWidthUnits; - - interface Token { - tspan: SvgTspan; - widthUnits: number; - isSpace: boolean; - } - - const lines: SvgLine[] = []; - for (const p of doc.paragraphs) { - const lineHeight = p.lineHeight != null ? baseUnit * p.lineHeight : opts.lineHeight; - const align = p.align ?? "left"; - - const tokens: Token[] = []; - for (const run of p.runs) { - if (run.text.length === 0) continue; - const base = runToTspan(run, basePt, opts.unitPerPt, color); - for (const part of run.text.split(/(\s+)/).filter((s) => s.length > 0)) { - const isSpace = /^\s/.test(part); - tokens.push({ - tspan: { ...base, text: part }, - widthUnits: part.length * base.fontSize * CHAR_WIDTH_FACTOR, - isSpace, - }); - } - } - - if (tokens.length === 0) { - lines.push({ tspans: [], align, lineHeight }); - continue; - } - - let current: Token[] = []; - let currentWidth = 0; - const flush = () => { - while (current.length && current[current.length - 1].isSpace) current.pop(); - lines.push({ tspans: current.map((t) => t.tspan), align, lineHeight }); - current = []; - currentWidth = 0; - }; - for (const tok of tokens) { - if (current.length === 0 && tok.isSpace) continue; - if (current.length > 0 && currentWidth + tok.widthUnits > maxWidth) { - flush(); - if (tok.isSpace) continue; - } - current.push(tok); - currentWidth += tok.widthUnits; - } - flush(); - } - return lines; + return kernelLines(doc, opts, opts.wrapWidthUnits); } -function runToTspan(run: TextRun, basePt: number, unitPerPt: number, color: string): SvgTspan { - const m = run.marks; - const script = m.super || m.sub; - const sizePt = (m.sizePt ?? basePt) * (script ? SCRIPT_SCALE : 1); - const fontSize = sizePt * unitPerPt; - const tspan: SvgTspan = { - text: run.text, - fontSize: round(fontSize), - fill: m.color ?? color, - }; - if (m.bold) tspan.fontWeight = "700"; - if (m.italic) tspan.fontStyle = "italic"; - if (m.font) tspan.fontFamily = m.font; - const deco = textDecoration(m); - if (deco) tspan.textDecoration = deco; - if (m.super) tspan.baselineShift = round(fontSize * 0.35); - if (m.sub) tspan.baselineShift = round(-fontSize * 0.2); - return tspan; +/** Eine gesetzte Zeile mit ihrer Grundlinie `y` (Bildschirm: nach unten wachsend). */ +export type PlacedLine = SvgLine & { y: number }; + +/** + * Raumstempel-Block (Kern `stamp_block`): Rich-Text-Zeilen (Vorschub 1.3 × Basisgrösse bzw. die + * Absatz-Zeilenhöhe) und darunter die Live-Zeilen (0.8 × Basisgrösse), vertikal um `y0` zentriert. + * `stamp` ist das Plan-Primitiv `text`. + */ +export function stampBlockLines( + stamp: { at: { x: number; y: number }; doc: RichTextDoc; extraLines: ReadonlyArray<{ text: string; align: string }>; basePt: number; color?: string }, + unitPerPt: number, + y0: number, +): PlacedLine[] { + const n = stamp.doc.paragraphs.length; + const text = (p: number, r: number): string => (p < n ? stamp.doc.paragraphs[p].runs[r].text : stamp.extraLines[p - n].text); + return decodeLines(core().text_stamp_block(JSON.stringify(stamp), unitPerPt, y0), text, true); } +/** + * Einfacher Text (ohne Rich-Dokument) auf die Spalte `wrap` umbrochen: Absätze an `\n`, Wörter mit + * einem Leerzeichen verbunden, geschätzte Zeichenbreite 0.55 × `fontSize` (gleiche Einheiten). + */ +export function wrapPlainText(text: string, wrap: number, fontSize: number): string[] { + const json = core().text_wrap_plain(text, wrap, fontSize); + return json ? (JSON.parse(json) as string[]) : [text]; +} diff --git a/src/text/textFrame.ts b/src/text/textFrame.ts index 5cdc58e3..dca5a217 100644 --- a/src/text/textFrame.ts +++ b/src/text/textFrame.ts @@ -11,8 +11,8 @@ import type { Vec2 } from "../model/types"; import type { Marks, RichTextDoc } from "./richText"; import { docFromText } from "./richText"; -import { wrapDocToLines } from "./renderHtml"; import { contentFontBaselineFromTop, TEXT_LINE_HEIGHT_MULT } from "./fontMetrics"; +import { core } from "../engine/coreWasm"; /** Minimale Felder, die `textFrameCorners` braucht — sowohl `Primitive` * ("drawingText", PlanView.tsx) als auch `Drawing2DGeom["text"]` @@ -30,52 +30,19 @@ export interface TextFrameInput { wrapWidth?: number; } -/** Geschätzter Zeichenbreite-Faktor je Schriftgrösse — deckt sich mit - * `CHAR_WIDTH_FACTOR` in `renderHtml.ts` (dort nicht exportiert; kein echtes - * Font-Measuring im SVG, reicht aber für Rahmen/Griffe). */ -const TEXT_CHAR_WIDTH_FACTOR = 0.55; - /** * Vier Eckpunkte (Modell-Meter, Reihenfolge oben-links · oben-rechts · * unten-rechts · unten-links VOR Rotation) eines groben Rahmens um einen - * gezeichneten Text. Höhe aus der ECHTEN Zeilenzahl (`wrapDocToLines`, - * dieselbe Umbruch-Logik wie beim Rendern in `primitives.tsx` - * "drawingText"), Breite aus der längsten Zeile geschätzt (oder `wrapWidth`, - * falls gesetzt — dann ist die Spaltenbreite exakt bekannt). `at` ist die - * Baseline-links der ERSTEN Zeile; Rotation um `angle` (CCW, Modell-Radiant) - * um genau diesen Punkt, analog zum SVG-`rotate` beim eigentlichen Rendern. + * gezeichneten Text. Rechnet der Kern (`text_layout::text_frame_corners`): Höhe aus der + * ECHTEN Zeilenzahl (derselbe Umbruch wie beim Rendern), Breite aus der längsten Zeile + * geschätzt (UTF-16-Länge × Höhe × 0.55, oder `wrapWidth`, falls gesetzt). `at` ist die + * Baseline-links der ERSTEN Zeile; Rotation um `angle` (CCW, Modell-Radiant) um genau + * diesen Punkt. Hier bleibt nur die Canvas-Messung Baseline → Oberkante. */ export function textFrameCorners(p: TextFrameInput): Vec2[] { const doc = p.doc ?? docFromText(p.text, p.marks ?? {}); - const lineHeight = p.heightM * TEXT_LINE_HEIGHT_MULT; - const wrapWidthUnits = p.wrapWidth && p.wrapWidth > 0 ? p.wrapWidth : undefined; - const lines = wrapDocToLines(doc, { - x: 0, - y: 0, - lineHeight, - unitPerPt: 1, - basePt: p.heightM, - ...(wrapWidthUnits ? { wrapWidthUnits } : {}), - }); - const maxLineChars = lines.length - ? Math.max(1, ...lines.map((l) => l.tspans.reduce((n, t) => n + t.text.length, 0))) - : 1; - const width = - wrapWidthUnits ?? Math.max(p.heightM, maxLineChars * p.heightM * TEXT_CHAR_WIDTH_FACTOR); - const height = Math.max(1, lines.length) * lineHeight; - // Baseline → Oberkante erste Zeile: echtes Font-Measuring statt der groben - // "ganzes heightM"-Näherung. - const top = p.heightM * contentFontBaselineFromTop(TEXT_LINE_HEIGHT_MULT); - const local: Vec2[] = [ - { x: 0, y: top }, - { x: width, y: top }, - { x: width, y: top - height }, - { x: 0, y: top - height }, - ]; - const cos = Math.cos(p.angle); - const sin = Math.sin(p.angle); - return local.map((l) => ({ - x: p.at.x + l.x * cos - l.y * sin, - y: p.at.y + l.x * sin + l.y * cos, - })); + const top = contentFontBaselineFromTop(TEXT_LINE_HEIGHT_MULT); + const f = core().text_frame(JSON.stringify(doc), Float64Array.of(p.at.x, p.at.y, p.heightM, p.angle, p.wrapWidth ?? NaN, top)); + if (f.length !== 8) return [p.at, p.at, p.at, p.at].map((q) => ({ x: q.x, y: q.y })); + return [0, 2, 4, 6].map((i) => ({ x: f[i], y: f[i + 1] })); } diff --git a/src/views/plan/planView/primitives.tsx b/src/views/plan/planView/primitives.tsx index 5ce4fa9c..e4dad6d5 100644 --- a/src/views/plan/planView/primitives.tsx +++ b/src/views/plan/planView/primitives.tsx @@ -5,7 +5,7 @@ import type { HatchRender, Primitive } from "../../../core"; import { NO_HATCH } from "../../../core"; -import { docToLines, wrapDocToLines, type SvgLine } from "../../../text/renderHtml"; +import { stampBlockLines, wrapDocToLines, wrapPlainText, type SvgLine } from "../../../text/renderHtml"; import type { Vec2 } from "../../../model/types"; import { quantizePen } from "../../../export/sceneToPrintSvg"; import { buildRandomHatchRuns, zigzagPoints, motifPoints, DASH_MM_TO_M } from "../../../core"; @@ -707,37 +707,10 @@ export function renderPrimitive( // verankert). unitPerPt bildet 1 pt auf viewBox-Einheiten ab. const nRef = print ? paperScale! : 100; const unitPerPt = (1 / 72) * 0.0254 * nRef * PX_PER_M; - const baseFs = p.basePt * unitPerPt; - const lineGap = baseFs * 1.3; - // Rich-Text-Zeilen (Stempel-Doc) + LIVE-Zusatzzeilen (Fläche/SIA) darunter. - const docLines: SvgLine[] = docToLines(p.doc, { - x: 0, - y: 0, - lineHeight: lineGap, - unitPerPt, - basePt: p.basePt, - color: p.color, - }); - const extra: SvgLine[] = p.extraLines.map((line) => ({ - align: line.align, - lineHeight: lineGap, - tspans: [{ text: line.text, fontSize: baseFs * 0.8, fill: p.color }], - })); - const lines = [...docLines, ...extra]; + // Rich-Text-Zeilen (Stempel-Doc) + LIVE-Zusatzzeilen (Fläche/SIA) darunter, Block vertikal + // um den Anker zentriert (Kern `stamp_block`, absatzeigene Zeilenhöhen inbegriffen). + const lines = stampBlockLines(p, unitPerPt, c.y); if (lines.length === 0) return null; - // Block vertikal um den Anker zentrieren. Absätze können eine eigene - // Zeilenhöhe tragen (Text-Gruppe, Zeilenhöhe-Regler) — darum kumulierte - // Vorschübe statt eines einzigen festen lineGap. - const totalH = baseFs + lines.slice(1).reduce((sum, l) => sum + l.lineHeight, 0); - const startY = c.y - totalH / 2 + baseFs * 0.8; - const lineYs: number[] = []; - { - let y = startY; - lines.forEach((line, k) => { - if (k > 0) y += line.lineHeight; - lineYs.push(y); - }); - } return ( {lines.map((line, k) => { @@ -751,7 +724,7 @@ export function renderPrimitive( {line.tspans.map((ts, j) => ( @@ -870,25 +843,9 @@ export function renderPrimitive( // Alt-Pfad: einfacher String + einheitliche `marks` (Text-Werkzeug/DXF-Import // ohne Rich-Doc) — unverändert. // Spaltentext: bei gesetzter `wrapWidth` den Text wortweise auf die Breite - // umbrechen (Zeichenbreite ≈ 0.55·fontSize geschätzt), sonst eine Zeile. + // umbrechen (Kern `wrap_plain`, Zeichenbreite ≈ 0.55·fontSize geschätzt), sonst eine Zeile. const lineH = fontSize * 1.25; - const lines: string[] = []; - if (p.wrapWidth && p.wrapWidth > 0) { - const maxPx = p.wrapWidth * PX_PER_M; - const charPx = fontSize * 0.55; - const maxChars = Math.max(1, Math.floor(maxPx / charPx)); - for (const paragraph of p.text.split("\n")) { - let line = ""; - for (const word of paragraph.split(/\s+/)) { - if (line === "") line = word; - else if ((line.length + 1 + word.length) <= maxChars) line += " " + word; - else { lines.push(line); line = word; } - } - lines.push(line); - } - } else { - lines.push(p.text); - } + const lines: string[] = p.wrapWidth && p.wrapWidth > 0 ? wrapPlainText(p.text, p.wrapWidth * PX_PER_M, fontSize) : [p.text]; // Einheitliche Formatierung (Text-Werkzeug + Oberleisten-Formatier-Gruppe): // Schriftfamilie/fett/kursiv/Unterstreichung aus `marks`; Grösse bleibt über // heightM (Modell-Meter). Farbe steckt bereits in p.color (marks.color-Vorrang