[93] Merge: Zeichnen auf dem Layout-Blatt = Zeichnen im Grundriss (Blatt-Ebene mit normalen 2D-Zeichnungen, Format 3 migriert Anmerkungen)

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-29 20:41:54 +00:00
commit 44e17eeb97
43 files changed
+1245 -2756

No files matched your search

+15 -3
View File
@@ -92,12 +92,22 @@ pub struct Ctx<'a> {
pub floor_height: Option<f64>,
pub cat: &'a str,
pub wall_type: &'a str,
/// Schrifthöhe neuer Texte (Modell-Meter, `textHeight` im Kontext): im Grundriss die Vorgabe
/// [`DEFAULT_TEXT_HEIGHT`], auf einem Layout-Blatt (Papier 1:1) die Papierhöhe.
pub text_height: f64,
}
/// Schrifthöhe neuer Texte im Grundriss (Modell-Meter, 2.5 mm bei 1:100).
pub const DEFAULT_TEXT_HEIGHT: f64 = 0.25;
fn text_height_of(c: &Value) -> f64 {
opt_n(c, "textHeight").filter(|h| *h > 0.0 && h.is_finite()).unwrap_or(DEFAULT_TEXT_HEIGHT)
}
pub(crate) fn ctx_of(v: &Value) -> Ctx<'_> {
let c = v.get("ctx").unwrap_or(&Value::Null);
let fh = opt_n(c, "floorHeight").filter(|h| *h > 0.0);
Ctx { level: s_of(c, "level"), floor_height: fh, cat: s_of(c, "cat"), wall_type: s_of(c, "wallType") }
Ctx { level: s_of(c, "level"), floor_height: fh, cat: s_of(c, "cat"), wall_type: s_of(c, "wallType"), text_height: text_height_of(c) }
}
// ── Werte bauen ──────────────────────────────────────────────────────────────
@@ -912,20 +922,22 @@ pub struct Req {
floor_height: Option<f64>,
cat: String,
wall_type: String,
text_height: f64,
}
impl Req {
pub fn new(v: Value) -> Req {
let c = ctx_of(&v);
let (level, floor_height, cat, wall_type) = (c.level.to_string(), c.floor_height, c.cat.to_string(), c.wall_type.to_string());
Req { cmd: s_of(&v, "cmd").to_string(), v, level, floor_height, cat, wall_type }
let text_height = c.text_height;
Req { cmd: s_of(&v, "cmd").to_string(), v, level, floor_height, cat, wall_type, text_height }
}
}
/// Wie [`preview`] mit gelesener Anfrage (Mausschritt: dieselbe Anfrage, neue Punkte).
pub fn preview_req(root: &Map<String, Value>, req: &Req, pts: &[f64]) -> Preview {
let v = &req.v;
let ctx = Ctx { level: &req.level, floor_height: req.floor_height, cat: &req.cat, wall_type: &req.wall_type };
let ctx = Ctx { level: &req.level, floor_height: req.floor_height, cat: &req.cat, wall_type: &req.wall_type, text_height: req.text_height };
let pts = flat_pts(pts);
let mut p = Preview { ok: true, ..Default::default() };
let out = &mut p.shapes;
+32 -15
View File
@@ -823,21 +823,22 @@ fn multiline_preview(v: &Value, pts: &[V], p: &mut Preview) {
}
}
const TEXT_HEIGHT: f64 = 0.25;
const TEXTBOX_MIN: f64 = 0.2;
/// Mindestgrösse eines Textrahmens als Vielfaches der Schrifthöhe (0.2 m bei 0.25 m Schrift).
const TEXTBOX_MIN_PER_HEIGHT: f64 = 0.8;
fn text_geom(at: Value, extra: Vec<(&str, Value)>) -> Value {
let mut f = vec![("shape", s("text")), ("at", at), ("text", s("")), ("height", js_num(TEXT_HEIGHT)), ("angle", js_num(0.0))];
fn text_geom(ctx: &Ctx, at: Value, extra: Vec<(&str, Value)>) -> Value {
let mut f = vec![("shape", s("text")), ("at", at), ("text", s("")), ("height", js_num(ctx.text_height)), ("angle", js_num(0.0))];
f.extend(extra);
obj(f)
}
/// Textrahmen aus zwei Ecken: Anker oben links (eine Zeile tief), Breite, Mindesthöhe.
fn textbox_frame(a: V, b: V) -> (V, f64, f64) {
fn textbox_frame(a: V, b: V, text_height: f64) -> (V, f64, f64) {
let (mn, mx) = rect_geom(a, b);
let width = jsnum::max(TEXTBOX_MIN, mx.0 - mn.0);
let height = jsnum::max(TEXTBOX_MIN, mx.1 - mn.1);
((mn.0, mx.1 - TEXT_HEIGHT), width, height)
let min = TEXTBOX_MIN_PER_HEIGHT * text_height;
let width = jsnum::max(min, mx.0 - mn.0);
let height = jsnum::max(min, mx.1 - mn.1);
((mn.0, mx.1 - text_height), width, height)
}
fn kote_tri(at: V, kind: &str) -> [V; 3] {
@@ -1091,15 +1092,15 @@ pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) ->
add_op("drawings2d", vec![d])
}
"multiline" => multiline_ops(v, ctx, ids),
"text" => add_drawing(v, ctx, ids, text_geom(pt_val(v, "at"), vec![])),
"text" => add_drawing(v, ctx, ids, text_geom(ctx, pt_val(v, "at"), vec![])),
"textbox" => {
let (at, width, _) = textbox_frame(p_of(v, "a"), p_of(v, "b"));
add_drawing(v, ctx, ids, text_geom(pv(at), vec![("width", js_num(width))]))
let (at, width, _) = textbox_frame(p_of(v, "a"), p_of(v, "b"), ctx.text_height);
add_drawing(v, ctx, ids, text_geom(ctx, pv(at), vec![("width", js_num(width))]))
}
"textpath" => {
let pts = pts_val(v, "pts");
let at = pts.get(0).cloned().unwrap_or(Value::Null);
add_drawing(v, ctx, ids, text_geom(at, vec![("pathPts", pts)]))
add_drawing(v, ctx, ids, text_geom(ctx, at, vec![("pathPts", pts)]))
}
"leader" => {
let mut extra = vec![("leaderTarget", pt_val(v, "target"))];
@@ -1107,7 +1108,7 @@ pub fn ops(root: &Map<String, Value>, v: &Value, ctx: &Ctx, ids: &mut IdGen) ->
if bends.as_array().is_some_and(|b| !b.is_empty()) {
extra.push(("leaderBendPoints", bends));
}
add_drawing(v, ctx, ids, text_geom(pt_val(v, "at"), extra))
add_drawing(v, ctx, ids, text_geom(ctx, pt_val(v, "at"), extra))
}
"kote" => add_drawing(
v,
@@ -1160,7 +1161,7 @@ pub fn preview(root: &Map<String, Value>, v: &Value, ctx: &Ctx, pts: &[V], p: &m
"textbox" => {
if let [a, b] = pts {
let (mn, mx) = rect_geom(*a, *b);
let (_, w, h) = textbox_frame(*a, *b);
let (_, w, h) = textbox_frame(*a, *b, ctx.text_height);
p.info.extend([w, h]);
p.shapes.poly(&corners_of(mn, mx));
}
@@ -1232,7 +1233,23 @@ mod tests {
use super::*;
fn ctx() -> Ctx<'static> {
Ctx { level: "L", floor_height: None, cat: "20", wall_type: "" }
Ctx { level: "L", floor_height: None, cat: "20", wall_type: "", text_height: crate::cmd_create::DEFAULT_TEXT_HEIGHT }
}
#[test]
fn schrifthoehe_aus_dem_kontext() {
// Grundriss: Vorgabe 0.25 m; Layout-Blatt (Papier 1:1): die Papierhöhe aus `textHeight`.
let v = json!({"cmd": "text", "at": {"x": 0.1, "y": -0.1}, "ctx": {"level": "blatt", "cat": "20", "textHeight": 0.0035}});
let c = crate::cmd_create::ctx_of(&v);
assert_eq!(c.text_height, 0.0035);
let o = ops(&Map::new(), &v, &c, &mut IdGen::new("s")).unwrap();
assert_eq!(o[0].to_json()["items"][0]["geom"]["height"], 0.0035);
let plain = json!({"ctx": {"level": "eg", "textHeight": -1}});
assert_eq!(crate::cmd_create::ctx_of(&plain).text_height, crate::cmd_create::DEFAULT_TEXT_HEIGHT);
// Textrahmen: Mindestgrösse folgt der Schrifthöhe, Anker eine Zeile unter der Oberkante.
let (at, w, h) = textbox_frame((0.0, 0.0), (0.0001, -0.0001), 0.0035);
assert!((w - 0.0028).abs() < 1e-12 && (h - 0.0028).abs() < 1e-12);
assert!((at.1 - (0.0 - 0.0035)).abs() < 1e-12);
}
#[test]
+1 -1
View File
@@ -819,7 +819,7 @@ mod tests {
assert_eq!(d.project().unwrap().walls.len(), 0);
assert_eq!(d.field("openings").unwrap()[0]["kind"], "door");
assert!(d.undo().is_none());
assert!(d.serialize().starts_with("{\n \"formatVersion\": 2,\n \"id\": \"q\""));
assert!(d.serialize().starts_with("{\n \"formatVersion\": 3,\n \"id\": \"q\""));
}
#[test]
+10 -6
View File
@@ -1309,6 +1309,14 @@ pub struct DrawingLevel {
#[serde(rename = "levelMarks", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub level_marks: Option<bool>,
/// Blatt-Ebene (nur kind "drawing"): gehört zum Layout mit dieser ID und trägt dessen
/// 2D-Zeichnung (Linien, Texte, Bilder …) als gewöhnliche `drawings2d`. Koordinaten = Papier
/// im Massstab 1:1 in Metern, Ursprung oben links am Blatt, Papier-y nach unten = −y
/// (Papier-mm (x, y) ↔ Modell (x/1000, −y/1000)). Nicht im Navigator; nur sichtbar, wenn das
/// Blatt offen ist. Fehlt ⇒ gewöhnliche Ebene.
#[serde(rename = "layoutId", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub layout_id: Option<String>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -3367,13 +3375,9 @@ pub struct Layout {
#[serde(rename = "customHeightMm", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub custom_height_mm: Option<f64>,
/// Die 2D-Zeichnung auf dem Blatt liegt auf der Blatt-Ebene ({@link DrawingLevel.layoutId}),
/// nicht im Layout (bis Format 2: `annotations`, s. `project_format::migrate_layout_annotations`).
pub viewports: Vec<LayoutViewport>,
/// 2D-Markups direkt auf dem Blatt (Linie/Rechteck/Text), siehe
/// {@link LayoutAnnotation}. Additiv — Alt-Layouts ohne dieses Feld laden
/// unverändert (Editor/CRUD behandeln ein fehlendes Array wie ein leeres).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub annotations: Option<Vec<LayoutAnnotation>>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
-82
View File
@@ -439,88 +439,6 @@ pub enum Drawing2DGeom {
},
}
/// Layout-Beschriftung (Tag `kind`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(tag = "kind")]
pub enum LayoutAnnotation {
#[serde(rename = "line")]
Line {
id: String,
#[serde(rename = "x1Mm")]
x1_mm: f64,
#[serde(rename = "y1Mm")]
y1_mm: f64,
#[serde(rename = "x2Mm")]
x2_mm: f64,
#[serde(rename = "y2Mm")]
y2_mm: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
color: Option<String>,
#[serde(rename = "weightMm", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
weight_mm: Option<f64>,
},
#[serde(rename = "rect")]
Rect {
id: String,
#[serde(rename = "xMm")]
x_mm: f64,
#[serde(rename = "yMm")]
y_mm: f64,
#[serde(rename = "widthMm")]
width_mm: f64,
#[serde(rename = "heightMm")]
height_mm: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
color: Option<String>,
#[serde(rename = "weightMm", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
weight_mm: Option<f64>,
},
#[serde(rename = "text")]
Text {
id: String,
#[serde(rename = "xMm")]
x_mm: f64,
#[serde(rename = "yMm")]
y_mm: f64,
text: String,
#[serde(rename = "heightMm")]
height_mm: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
color: Option<String>,
/// Reiches Textfeld (mehrere Absätze, gemischte Formatierung) — Vorrang vor
/// `text`, s. gleichnamiges Feld bei `Drawing2DGeom["text"]`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
doc: Option<RichTextDoc>,
/// Optionale Rahmenbreite (mm) — bricht `doc` wortweise um; fehlt sie: einzeilig.
#[serde(rename = "widthMm", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
width_mm: Option<f64>,
},
#[serde(rename = "image")]
Image {
id: String,
#[serde(rename = "xMm")]
x_mm: f64,
#[serde(rename = "yMm")]
y_mm: f64,
#[serde(rename = "widthMm")]
width_mm: f64,
#[serde(rename = "heightMm")]
height_mm: f64,
/// Bildquelle als Data-URL (PNG/JPEG) — eingebettet, keine externe Datei.
src: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
opacity: Option<f64>,
},
}
/// Parametrische Wandregel (Tag `type`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
#[serde(tag = "type")]
+17 -1
View File
@@ -394,8 +394,10 @@ impl Post {
}
/// Nachbearbeitung eines Plans: Schwarz-Weiss und Strichstärken-Faktor; `None`, wenn sie nichts tut.
/// Auf einer Blatt-Ebene (`layoutId`) gelten die Strichstärken unverändert (Papier 1:1).
pub fn post_for(p: &Project, a: &super::domains::PlanArgs) -> Option<Post> {
Some(Post { mono: a.mono, lw: line_weight_factor(p, a.scale) }).filter(Post::active)
let sheet = p.floor(&a.floor).is_some_and(|l| l.layout_id.is_some());
Some(Post { mono: a.mono, lw: if sheet { 1.0 } else { line_weight_factor(p, a.scale) } }).filter(Post::active)
}
// ── Ausmass ─────────────────────────────────────────────────────────────────────────────────────
@@ -479,6 +481,20 @@ mod tests {
assert_eq!(line_weight_factor(&on, f64::NAN), 1.0);
}
#[test]
fn blatt_ebene_ohne_strichstaerken_faktor() {
let mut p = sample();
p.scale_line_weights = Some(true);
let mut sheet = p.drawing_levels[0].clone();
sheet.id = "blatt".into();
sheet.kind = crate::model::DrawingLevelKind::Drawing;
sheet.layout_id = Some("L1".into());
p.drawing_levels.push(sheet);
let args = |floor: &str| super::super::domains::PlanArgs::parse(1.0, &serde_json::json!({"floor": floor, "scale": 1}).to_string()).unwrap();
assert_eq!(post_for(&p, &args("blatt")), None, "Papier 1:1: Stärken unverändert");
assert!(post_for(&p, &args("eg")).is_some_and(|q| q.lw > 1.0));
}
#[test]
fn abzugskoerper_spart_wand_aus() {
let mut v: serde_json::Value = serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap();
+187 -3
View File
@@ -9,7 +9,7 @@
use serde_json::{Map, Value};
/// Aktuelle Version des Dateiformats. Bei jeder Formatänderung erhöhen + Migration anhängen.
pub const PROJECT_FORMAT_VERSION: u64 = 2;
pub const PROJECT_FORMAT_VERSION: u64 = 3;
const REQUIRED_ARRAYS: [&str; 3] = ["walls", "layers", "drawingLevels"];
const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"];
@@ -86,6 +86,144 @@ fn migrate_doors(mut raw: Map<String, Value>) -> Map<String, Value> {
raw
}
/// Kategorie für Blatt-Zeichnungen aus der Migration: „50" (Text), sonst die erste Kategorie.
fn sheet_category(raw: &Map<String, Value>) -> String {
fn walk(v: &Value, out: &mut Vec<String>) {
for c in v.as_array().into_iter().flatten() {
if let Some(code) = c.get("code").and_then(Value::as_str) {
out.push(code.to_string());
}
if let Some(ch) = c.get("children") {
walk(ch, out);
}
}
}
let mut codes = Vec::new();
if let Some(l) = raw.get("layers") {
walk(l, &mut codes);
}
if codes.iter().any(|c| c == "50") {
return "50".into();
}
codes.into_iter().next().unwrap_or_else(|| "50".into())
}
/// Papier-mm (x, y nach unten) → Blatt-Ebene (Meter, y nach oben), s. `DrawingLevel.layoutId`.
fn sheet_pt(x_mm: f64, y_mm: f64) -> Value {
serde_json::json!({"x": x_mm / 1000.0, "y": -y_mm / 1000.0})
}
/// Eine Alt-Annotation (Papier-mm) als `geom` + Zusatzfelder einer 2D-Zeichnung; `None` = unlesbar.
fn annotation_geom(a: &Value) -> Option<(Value, Vec<(&'static str, Value)>)> {
let n = |k: &str| a.get(k).and_then(Value::as_f64).filter(|v| v.is_finite());
let mut extra: Vec<(&'static str, Value)> = Vec::new();
let color = a.get("color").and_then(Value::as_str).unwrap_or("#111111").to_string();
let kind = a.get("kind").and_then(Value::as_str)?;
let geom = match kind {
"line" => {
extra.push(("color", Value::String(color)));
extra.push(("weightMm", n("weightMm").unwrap_or(0.25).into()));
serde_json::json!({"shape": "line", "a": sheet_pt(n("x1Mm")?, n("y1Mm")?), "b": sheet_pt(n("x2Mm")?, n("y2Mm")?)})
}
"rect" | "image" => {
let (x, y, w, h) = (n("xMm")?, n("yMm")?, n("widthMm")?, n("heightMm")?);
let (x0, x1) = (x.min(x + w), x.max(x + w));
let (y0, y1) = (y.min(y + h), y.max(y + h));
let (min, max) = (sheet_pt(x0, y1), sheet_pt(x1, y0));
if kind == "rect" {
extra.push(("color", Value::String(color)));
extra.push(("weightMm", n("weightMm").unwrap_or(0.25).into()));
serde_json::json!({"shape": "rect", "min": min, "max": max})
} else {
let mut g = serde_json::json!({"shape": "image", "min": min, "max": max, "src": a.get("src").and_then(Value::as_str)?});
if let Some(o) = n("opacity") {
g["opacity"] = o.into();
}
g
}
}
"text" => {
extra.push(("color", Value::String(color)));
let mut g = serde_json::json!({
"shape": "text",
"at": sheet_pt(n("xMm")?, n("yMm")?),
"text": a.get("text").and_then(Value::as_str).unwrap_or_default(),
"height": n("heightMm")? / 1000.0,
"angle": 0,
});
if let Some(w) = n("widthMm").filter(|w| *w > 0.0) {
g["width"] = (w / 1000.0).into();
}
if let Some(d) = a.get("doc").filter(|d| d.is_object()) {
g["doc"] = d.clone();
}
g
}
_ => return None,
};
Some((geom, extra))
}
/// 2 → 3: Blatt-Zeichnungen sind gewöhnliche 2D-Zeichnungen auf einer Blatt-Ebene
/// (`DrawingLevel.layoutId`) statt eigener `Layout.annotations` in Papier-mm. Jedes Layout bekommt
/// seine Blatt-Ebene; Linie/Rechteck/Text/Bild werden zu `line`/`rect`/`text`/`image`.
fn migrate_layout_annotations(mut raw: Map<String, Value>) -> Map<String, Value> {
let Some(Value::Array(mut layouts)) = raw.get("layouts").cloned() else { return raw };
let mut levels: Vec<Value> = raw.get("drawingLevels").and_then(Value::as_array).cloned().unwrap_or_default();
let mut drawings: Vec<Value> = raw.get("drawings2d").and_then(Value::as_array).cloned().unwrap_or_default();
let mut level_ids: std::collections::HashSet<String> =
levels.iter().filter_map(|l| l.get("id").and_then(Value::as_str).map(str::to_owned)).collect();
let mut drawing_ids: std::collections::HashSet<String> =
drawings.iter().filter_map(|d| d.get("id").and_then(Value::as_str).map(str::to_owned)).collect();
let cat = sheet_category(&raw);
for lay in layouts.iter_mut() {
let Some(lay) = lay.as_object_mut() else { continue };
let annotations = lay.shift_remove("annotations");
let Some(layout_id) = lay.get("id").and_then(Value::as_str).map(str::to_owned) else { continue };
let existing = levels
.iter()
.find(|l| l.get("layoutId").and_then(Value::as_str) == Some(layout_id.as_str()))
.and_then(|l| l.get("id"))
.and_then(Value::as_str)
.map(str::to_owned);
let level_id = match existing {
Some(id) => id,
None => {
let mut id = format!("sheet-{layout_id}");
while level_ids.contains(&id) {
id.push_str("-s");
}
level_ids.insert(id.clone());
let name = lay.get("name").and_then(Value::as_str).unwrap_or_default();
levels.push(serde_json::json!({"id": id, "name": name, "kind": "drawing", "visible": true, "locked": false, "layoutId": layout_id}));
id
}
};
for a in annotations.as_ref().and_then(Value::as_array).into_iter().flatten() {
let Some((geom, extra)) = annotation_geom(a) else { continue };
let mut id = a.get("id").and_then(Value::as_str).filter(|s| !s.is_empty()).unwrap_or("ann").to_string();
while drawing_ids.contains(&id) {
id.push_str("-a");
}
drawing_ids.insert(id.clone());
let mut d = Map::new();
d.insert("id".into(), Value::String(id));
d.insert("type".into(), "drawing2d".into());
d.insert("levelId".into(), Value::String(level_id.clone()));
d.insert("categoryCode".into(), Value::String(cat.clone()));
d.insert("geom".into(), geom);
for (k, v) in extra {
d.insert(k.into(), v);
}
drawings.push(Value::Object(d));
}
}
raw.insert("layouts".into(), Value::Array(layouts));
raw.insert("drawingLevels".into(), Value::Array(levels));
raw.insert("drawings2d".into(), Value::Array(drawings));
raw
}
/// Liest eine Projektdatei (Text) tolerant ein, migriert und prüft sie. `now_ms`: Zeitpunkt für
/// eine Ersatz-ID, falls die Datei keine trägt.
pub fn parse_project_file(text: &str, now_ms: f64) -> Parsed {
@@ -128,6 +266,7 @@ pub fn parse_project_object(raw: Value, now_ms: f64) -> Parsed {
for i in version..PROJECT_FORMAT_VERSION {
obj = match i {
1 => migrate_doors(obj),
2 => migrate_layout_annotations(obj),
_ => obj, // 0 → 1: Einführung von `formatVersion`; Inhalt unverändert.
};
}
@@ -321,7 +460,7 @@ mod tests {
fn alte_datei_wird_migriert_und_ergaenzt() {
let Parsed::Ok { project, warnings, migrated_from } = parse_project_object(minimal(), 0.0) else { panic!() };
assert_eq!(migrated_from, Some(0));
assert_eq!(project["formatVersion"], 2);
assert_eq!(project["formatVersion"], 3);
assert_eq!(project["lineStyles"], json!([]));
assert!(warnings.is_empty());
}
@@ -362,6 +501,51 @@ mod tests {
assert_eq!(o[2]["id"], "O1-t");
}
#[test]
fn layout_annotationen_werden_blatt_zeichnungen() {
let mut v = minimal();
v["formatVersion"] = json!(2);
v["layers"] = json!([{"code": "20", "children": [{"code": "50"}]}]);
v["drawings2d"] = json!([{"id": "a1", "levelId": "eg"}]);
v["layouts"] = json!([
{"id": "L1", "name": "Blatt 1", "paper": "a3", "orientation": "landscape", "viewports": [], "annotations": [
{"kind": "line", "id": "a1", "x1Mm": 10, "y1Mm": 20, "x2Mm": 110, "y2Mm": 20, "weightMm": 0.5},
{"kind": "rect", "id": "a2", "xMm": 10, "yMm": 20, "widthMm": 50, "heightMm": 30, "color": "#ff0000"},
{"kind": "text", "id": "a3", "xMm": 5, "yMm": 7, "text": "Hallo", "heightMm": 3.5, "widthMm": 40},
{"kind": "image", "id": "a4", "xMm": 0, "yMm": 0, "widthMm": 20, "heightMm": 10, "src": "data:image/png;base64,AA", "opacity": 0.5},
{"kind": "line", "id": "kaputt", "x1Mm": "x"}
]},
{"id": "L2", "name": "Blatt 2", "paper": "a4", "orientation": "portrait", "viewports": []}
]);
let Parsed::Ok { project, migrated_from, .. } = parse_project_object(v, 0.0) else { panic!() };
assert_eq!(migrated_from, Some(2));
assert!(project["layouts"][0].get("annotations").is_none());
let levels = project["drawingLevels"].as_array().unwrap();
assert_eq!(levels.len(), 2, "jedes Layout bekommt seine Blatt-Ebene");
assert_eq!(levels[0], json!({"id": "sheet-L1", "name": "Blatt 1", "kind": "drawing", "visible": true, "locked": false, "layoutId": "L1"}));
assert_eq!(levels[1]["layoutId"], "L2");
let d = project["drawings2d"].as_array().unwrap();
assert_eq!(d.len(), 5, "kaputte Annotation fällt weg");
assert_eq!(d[1]["id"], "a1-a", "ID-Kollision mit bestehender Zeichnung");
assert_eq!(d[1]["levelId"], "sheet-L1");
assert_eq!(d[1]["categoryCode"], "50");
assert_eq!(d[1]["geom"], json!({"shape": "line", "a": {"x": 0.01, "y": -0.02}, "b": {"x": 0.11, "y": -0.02}}));
assert_eq!(d[1]["weightMm"], 0.5);
assert_eq!(d[2]["geom"], json!({"shape": "rect", "min": {"x": 0.01, "y": -0.05}, "max": {"x": 0.06, "y": -0.02}}));
assert_eq!(d[2]["color"], "#ff0000");
assert_eq!(d[3]["geom"]["at"], json!({"x": 0.005, "y": -0.007}));
assert_eq!(d[3]["geom"]["height"], 0.0035);
assert_eq!(d[3]["geom"]["width"], 0.04);
assert_eq!(d[4]["geom"]["src"], "data:image/png;base64,AA");
assert_eq!(d[4]["geom"]["max"]["x"], 0.02);
assert_eq!(d[4]["geom"]["min"]["y"], -0.01);
// Schon migriert: ein zweiter Lauf ändert nichts mehr.
let mut again = project.clone();
again.insert("formatVersion".into(), json!(2));
let Parsed::Ok { project: p2, .. } = parse_project_object(Value::Object(again), 0.0) else { panic!() };
assert_eq!(p2, project);
}
#[test]
fn unbekannte_felder_bleiben_und_werden_gemeldet() {
let mut v = minimal();
@@ -420,6 +604,6 @@ mod tests {
fn serialisierung_setzt_version_nach_vorn() {
let Value::Object(m) = minimal() else { panic!() };
let s = serialize_project(&m);
assert!(s.starts_with("{\n \"formatVersion\": 2,\n \"id\": \"p\""));
assert!(s.starts_with("{\n \"formatVersion\": 3,\n \"id\": \"p\""));
}
}