[K3d][K4] Text-Layout im Kern: Raumstempel, Rich-Text, Umbruch, Text-Rahmen

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.
This commit is contained in:
Claude committed 2026-10-29 09:36:23 +00:00
1 parent 24735a4b53
commit ce0d9950d0
20 files changed
+1456 -720

No files matched your search

+2
View File
@@ -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;
+14 -85
View File
@@ -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<Prim> {
}
/// 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<String>)]) -> Vec<(String, f64)> {
let mut lines: Vec<String> = 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<usize, TextIn>, project: &Project, o: &DxfOptions) -> Option<FlatDxf> {
/// 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<FlatDxf> {
// Primitive in Plan-Reihenfolge lesen.
let mut entries: Vec<Entry> = 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<usize, TextIn>, 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<HashMap<usize, TextIn>> {
let mut out = HashMap::new();
let mut k = 0usize;
let mut next = || -> Option<f64> {
let v = *nums.get(k)?;
k += 1;
Some(v)
};
let s_of = |v: f64| -> Option<String> { 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<u8> {
+102 -10
View File
@@ -5,21 +5,29 @@
//! `String(Math.round(v * 1000) / 1000)`). Schraffuren als geklippte Vektorlinien, Zickzack/Motiv als
//! Polylinie, Bögen als `<path>`.
//!
//! In TS bleiben: der `<svg>`-Rahmen und das weisse Blatt, die Bild-Schraffur-`<pattern>` (laufende
//! Ids im Dokument) und die Einzeltexte (Text-Layout `wrapDocToLines`). Dafür stehen Anweisungen in
//! der Liste.
//! In TS bleiben: der `<svg>`-Rahmen und das weisse Blatt und die Bild-Schraffur-`<pattern>`
//! (laufende Ids im Dokument). Die Einzeltexte setzt der Kern (`crate::text_layout`, Zeilen als
//! `<tspan>` je Zeile mit je einem `<tspan>` je Run/Wort).
//!
//! Format: Datensätze getrennt durch `\x1e`, Felder durch `\x1f`:
//! - `E`, Ebene (0 = ins `<svg>`, 1 = in die offene Gruppe), Tag, dann Name/Wert-Paare;
//! - `G`, Deckkraft (leer = keine) — öffnet eine `<g>`; `g` schliesst sie (hängt sie ans `<svg>`);
//! - `I`, Punkte-Attribut, Bild-JSON — Bild-Schraffur: `<pattern>` anlegen und ein Polygon damit füllen;
//! - `T`, Plan-Index, Deckkraft — Einzeltext an dieser Stelle.
//! - `X`, Name/Wert-Paare — `<text>` ins `<svg>` (wird der offene Text);
//! - `L`, Inhalt (leer = keiner), Name/Wert-Paare — Zeilen-`<tspan>` in den offenen Text (wird die
//! offene Zeile);
//! - `R`, Inhalt, Name/Wert-Paare — Run-`<tspan>` 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::<SingleText>(&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 `<text>` mit `<tspan>`-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<String> {
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<Vec<&str>> = 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 }];
+1 -17
View File
@@ -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<u8>,
}
/// 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<Vec<SText>> {
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
+300
View File
@@ -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<f64, D::Error> {
Ok(Option::<f64>::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<StampLine>,
#[serde(deserialize_with = "num")]
pub base_pt: f64,
#[serde(default)]
pub color: Option<String>,
#[serde(default)]
pub greyed: Option<bool>,
}
/// 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<String>,
#[serde(default)]
pub marks: Option<Marks>,
#[serde(default)]
pub wrap_width: Option<f64>,
#[serde(default)]
pub doc: Option<RichTextDoc>,
#[serde(default)]
pub greyed: Option<bool>,
#[serde(default)]
pub opacity: Option<f64>,
}
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<f64> {
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<TextPrim> {
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<SText>, 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<Vec<SText>> {
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<SText>) {
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<SText>) {
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<String> = 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<String> {
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<DxfLine> {
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");
}
}
+635
View File
@@ -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<Align>) -> 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<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text_decoration: Option<&'static str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub baseline_shift: Option<f64>,
}
fn ser_weight<S: serde::Serializer>(_: &bool, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str("700")
}
fn ser_style<S: serde::Serializer>(_: &bool, s: S) -> Result<S::Ok, S::Error> {
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<Tspan>,
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<f64> {
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<Tok>,
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<f64>) -> Vec<LineRef> {
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<Token> = 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<Token> = Vec::new();
let mut current_width = 0.0;
let flush = |current: &mut Vec<Token>, lines: &mut Vec<LineRef>| {
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<LineRef>, o: &LayoutOpts) -> Vec<Line> {
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<Line> {
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<bool> = 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<f64>) -> Vec<Line> {
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<Placed> {
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<S: AsRef<str>>(words: &[S], max_chars: f64, lines: &mut Vec<String>) {
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<String> {
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::<String>()).collect::<Vec<_>>().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<String> {
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<f64>, 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::<usize>() 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<Vec<(&str, Marks)>>) -> 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<String> {
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);
}
}
+1
View File
@@ -38,6 +38,7 @@ mod pens;
mod layout_model;
mod parametric_walls;
mod reorder;
mod text_layout;
use wasm_bindgen::prelude::wasm_bindgen;
+13 -15
View File
@@ -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<u8> {
pub fn plan_dxf_flat(doc: u32, segs: &[f64], opts: &[f64]) -> Vec<u8> {
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()
+32 -5
View File
@@ -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<Scene> {
@@ -13,17 +15,42 @@ fn scene_of(segs: &[f64], greyed: &[f64]) -> Option<Scene> {
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<Vec<SText>> {
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<u8> {
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<u8> {
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<f64> {
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<f64> = 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<f64> {
+124
View File
@@ -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<f64> {
let mut styles: Vec<Tspan> = Vec::new();
let mut keys: Vec<(usize, usize)> = Vec::new();
let mut key_style: Vec<usize> = Vec::new();
let mut body: Vec<f64> = 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<String>) -> Vec<f64> {
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::<RichTextDoc>(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<f64> {
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::<RichTextDoc>(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<f64> {
let Ok(p) = serde_json::from_str::<crate::plan_text::StampText>(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<f64> = placed.iter().map(|q| q.1).collect();
let lines: Vec<LineRef> = 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()
}