[208] Wettbewerbs-Abgabe: Bilder auf Layout-Blättern, Plakat-Vorlagen A0/A1, anonyme Abgabe, Satz „WBW-Abgabe“

- Bild-Element im Layout (Layout.images, Data-URL wie ContextImage): Kern layout_image.rs (Dateikopf, Seitenverhältnis,
  Zuschnitt, dpi), Blatt mit Knopf, Verschieben, Skalieren, HUD; PDF bettet das Original ein (JPEG ohne Neukompression).
- Rendering-Dialog: „Ins Layout einsetzen“.
- Plakat-Vorlagen A0/A1 hoch/quer (Master mit Raster-Hilfslinien, Kopfzeile mit Kennwort-Feld und Plan x/n, Massstab je
  Viewport; Kern layout_poster.rs), wählbar in „Neues Layout“.
- Project.competition: anonym + Kennwort; Plankopf, PDF-Info (Producer/Datum neutralisiert) und Dateinamen nur mit Kennwort.
- Publikationssatz „WBW-Abgabe“ mit allen Plakaten.
This commit is contained in:
Claude committed 2026-11-12 19:40:40 +00:00
1 parent 61c11fc03f
commit cebb7c313d
39 files changed
+2184 -27

No files matched your search

+1
View File
@@ -81,6 +81,7 @@ Neues Modul: `<modul>.rs` und `mod` in `lib.rs`, Bindungen in `web/<modul>.rs` u
| `dim_assoc.rs`, `magic_wand.rs`, `polyline_vertex.rs`, `drawing_recognize.rs` | assoziative Bemassung, Zauberstab, Punkttypen, Bauteile aus Zeichnung erkennen |
| `layers.rs`, `levels.rs`, `groups.rs`, `pens.rs`, `reorder.rs`, `folder_tree.rs` | Ebenen, Geschosse, Gruppen, Stiftsätze, Z-Reihenfolge, Ordner |
| `layout_model.rs`, `sheet_viewports.rs`, `sheet_table.rs`, `presentation_sheet.rs` | Layout-Blätter, Viewports, Tabellen, Präsentationsplan |
| `layout_image.rs`, `layout_poster.rs` | Bilder auf Blättern (Dateikopf, Zuschnitt, dpi) und Plakat-Vorlagen mit Raster und Kopfzeile ([208]) |
| `parametric_walls.rs`, `geo_translate.rs`, `geo_rebase.rs` | parametrische Wände; Projekt verschieben; Ursprung für Exporte |
## Analyse
+238
View File
@@ -0,0 +1,238 @@
//! Bilder auf Layout-Blättern ([208]): Kopfdaten (Format, Pixelgrösse) aus einer Data-URL lesen, Seitenverhältnis,
//! Zeichen- und Klipp-Rechteck mit Zuschnitt, Startgrösse auf dem Blatt und Auflösung (dpi). Die Bytes selbst
//! bleiben unverändert (PDF bettet JPEG ohne Neukompression ein); hier wird nichts dekodiert ausser dem Kopf.
use serde::Serialize;
/// Format und Pixelgrösse eines Bilds.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ImageInfo {
/// "image/png" oder "image/jpeg".
pub mime: String,
pub width: u32,
pub height: u32,
}
fn b64_val(c: u8) -> Option<u8> {
match c {
b'A'..=b'Z' => Some(c - b'A'),
b'a'..=b'z' => Some(c - b'a' + 26),
b'0'..=b'9' => Some(c - b'0' + 52),
b'+' | b'-' => Some(62),
b'/' | b'_' => Some(63),
_ => None,
}
}
/// Base64 (Standard und URL-sicher, Leerraum und Füllzeichen ignoriert); `None` bei Unsinn.
pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(s.len() / 4 * 3);
let (mut acc, mut bits) = (0u32, 0u32);
for &c in s.as_bytes() {
if c == b'=' || c.is_ascii_whitespace() {
continue;
}
acc = (acc << 6) | u32::from(b64_val(c)?);
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((acc >> bits) as u8);
acc &= (1 << bits) - 1;
}
}
Some(out)
}
/// Bytes einer `data:image/…;base64,…`-URL.
pub fn data_url_bytes(src: &str) -> Option<Vec<u8>> {
let rest = src.strip_prefix("data:")?;
let (head, body) = rest.split_once(',')?;
if !head.ends_with(";base64") {
return None;
}
base64_decode(body)
}
/// Format und Grösse aus den Bytes (PNG: IHDR, JPEG: erster Start-of-Frame-Marker).
pub fn image_info_bytes(b: &[u8]) -> Option<ImageInfo> {
if b.len() >= 24 && b[..8] == [0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a] && &b[12..16] == b"IHDR" {
let w = u32::from_be_bytes([b[16], b[17], b[18], b[19]]);
let h = u32::from_be_bytes([b[20], b[21], b[22], b[23]]);
return (w > 0 && h > 0).then(|| ImageInfo { mime: "image/png".into(), width: w, height: h });
}
if b.len() >= 4 && b[0] == 0xff && b[1] == 0xd8 {
let mut i = 2;
while i + 4 <= b.len() {
if b[i] != 0xff {
i += 1;
continue;
}
let m = b[i + 1];
if m == 0xff {
i += 1;
continue;
}
// Marker ohne Länge
if m == 0xd8 || m == 0x01 || (0xd0..=0xd7).contains(&m) {
i += 2;
continue;
}
let len = usize::from(u16::from_be_bytes([b[i + 2], b[i + 3]]));
if (0xc0..=0xcf).contains(&m) && m != 0xc4 && m != 0xc8 && m != 0xcc {
if i + 9 > b.len() {
return None;
}
let h = u32::from(u16::from_be_bytes([b[i + 5], b[i + 6]]));
let w = u32::from(u16::from_be_bytes([b[i + 7], b[i + 8]]));
return (w > 0 && h > 0).then(|| ImageInfo { mime: "image/jpeg".into(), width: w, height: h });
}
i += 2 + len.max(2);
}
}
None
}
/// Format und Grösse einer Data-URL.
pub fn image_info(src: &str) -> Option<ImageInfo> {
image_info_bytes(&data_url_bytes(src)?)
}
/// Rechteck in Papier-mm.
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct Rect {
pub x: f64,
pub y: f64,
pub w: f64,
pub h: f64,
}
/// Zuschnitt als Anteile des Originals `(x, y, w, h)`, auf sinnvolle Werte begrenzt (mindestens 1 % Kantenlänge).
pub fn clamp_crop(c: Option<(f64, f64, f64, f64)>) -> (f64, f64, f64, f64) {
let Some((x, y, w, h)) = c else { return (0.0, 0.0, 1.0, 1.0) };
if ![x, y, w, h].iter().all(|v| v.is_finite()) {
return (0.0, 0.0, 1.0, 1.0);
}
let x = x.clamp(0.0, 0.99);
let y = y.clamp(0.0, 0.99);
let w = w.clamp(0.01, 1.0 - x);
let h = h.clamp(0.01, 1.0 - y);
(x, y, w, h)
}
/// Seitenverhältnis (Breite/Höhe) des gezeigten Ausschnitts.
pub fn aspect(px_w: f64, px_h: f64, crop: Option<(f64, f64, f64, f64)>) -> f64 {
let (_, _, cw, ch) = clamp_crop(crop);
if px_w > 0.0 && px_h > 0.0 {
(px_w * cw) / (px_h * ch)
} else {
1.0
}
}
/// Zeichen- und Klipp-Rechteck: `clip` = der Rahmen auf dem Blatt, `draw` = das GANZE Original so gelegt, dass
/// der Zuschnitt genau den Rahmen füllt (das PDF setzt das Bild dorthin und klippt auf `clip`).
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Geometry {
pub clip: Rect,
pub draw: Rect,
/// Auflösung des gezeigten Ausschnitts auf dem Blatt in dpi (Pixel je Zoll).
pub dpi: f64,
}
pub fn geometry(frame: Rect, px_w: f64, crop: Option<(f64, f64, f64, f64)>) -> Geometry {
let (cx, cy, cw, ch) = clamp_crop(crop);
let full_w = frame.w / cw;
let full_h = frame.h / ch;
let draw = Rect { x: frame.x - cx * full_w, y: frame.y - cy * full_h, w: full_w, h: full_h };
let dpi = if frame.w > 0.0 { px_w * cw / (frame.w / 25.4) } else { 0.0 };
Geometry { clip: frame, draw, dpi }
}
/// Startrahmen eines neuen Bilds: so gross wie möglich in `max_frac` des Blatts, Seitenverhältnis gehalten, mittig.
pub fn initial_frame(px_w: f64, px_h: f64, sheet_w: f64, sheet_h: f64, max_frac: f64) -> Rect {
let a = aspect(px_w, px_h, None);
let (bw, bh) = (sheet_w * max_frac, sheet_h * max_frac);
let (w, h) = if bw / bh > a { (bh * a, bh) } else { (bw, bw / a) };
Rect { x: (sheet_w - w) / 2.0, y: (sheet_h - h) / 2.0, w, h }
}
#[cfg(test)]
mod tests {
use super::*;
/// 1×1-PNG (rot).
const PNG_1X1: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";
fn png_header(w: u32, h: u32) -> Vec<u8> {
let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, b'I', b'H', b'D', b'R'];
v.extend_from_slice(&w.to_be_bytes());
v.extend_from_slice(&h.to_be_bytes());
v
}
#[test]
fn png_kopf() {
let i = image_info(PNG_1X1).unwrap();
assert_eq!((i.mime.as_str(), i.width, i.height), ("image/png", 1, 1));
let i = image_info_bytes(&png_header(4000, 2250)).unwrap();
assert_eq!((i.width, i.height), (4000, 2250));
}
#[test]
fn jpeg_kopf_ueberspringt_andere_segmente() {
// SOI, APP0 (Länge 16), DHT (C4, darf nicht als Frame zählen), SOF0 480×640
let mut b = vec![0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10];
b.extend_from_slice(&[0u8; 14]);
b.extend_from_slice(&[0xff, 0xc4, 0x00, 0x04, 0, 0]);
b.extend_from_slice(&[0xff, 0xc0, 0x00, 0x11, 8, 0x02, 0x80, 0x01, 0xe0, 3]);
let i = image_info_bytes(&b).unwrap();
assert_eq!((i.mime.as_str(), i.width, i.height), ("image/jpeg", 480, 640));
}
#[test]
fn unsinn_liefert_nichts() {
assert!(image_info("data:image/png;base64,@@@").is_none());
assert!(image_info("hallo").is_none());
assert!(image_info("data:image/png;base64,AAAA").is_none());
assert!(image_info_bytes(&[0xff, 0xd8, 0xff]).is_none());
assert!(image_info_bytes(&png_header(0, 5)).is_none());
}
#[test]
fn base64_wie_standard() {
assert_eq!(base64_decode("TWFu").unwrap(), b"Man");
assert_eq!(base64_decode("TWE=").unwrap(), b"Ma");
assert_eq!(base64_decode("TQ").unwrap(), b"M");
}
#[test]
fn seitenverhaeltnis_mit_zuschnitt() {
assert_eq!(aspect(4000.0, 2000.0, None), 2.0);
// Mitte-Hälfte der Breite: 2000×2000 → quadratisch
assert_eq!(aspect(4000.0, 2000.0, Some((0.25, 0.0, 0.5, 1.0))), 1.0);
assert_eq!(aspect(0.0, 0.0, None), 1.0);
assert_eq!(aspect(10.0, 10.0, Some((f64::NAN, 0.0, 1.0, 1.0))), 1.0);
}
#[test]
fn zeichenrechteck_fuellt_den_rahmen_mit_dem_zuschnitt() {
let frame = Rect { x: 100.0, y: 50.0, w: 200.0, h: 100.0 };
let g = geometry(frame, 4000.0, None);
assert_eq!(g.draw, frame);
assert!((g.dpi - 4000.0 / (200.0 / 25.4)).abs() < 1e-9);
// rechte Hälfte: das ganze Bild ist doppelt so breit, beginnt links vom Rahmen
let g = geometry(frame, 4000.0, Some((0.5, 0.0, 0.5, 1.0)));
assert_eq!(g.draw, Rect { x: 100.0 - 200.0, y: 50.0, w: 400.0, h: 100.0 });
assert_eq!(g.clip, frame);
}
#[test]
fn startrahmen_haelt_verhaeltnis_und_passt_ins_blatt() {
let r = initial_frame(3000.0, 2000.0, 841.0, 594.0, 0.6);
assert!((r.w / r.h - 1.5).abs() < 1e-9);
assert!(r.w <= 841.0 * 0.6 + 1e-9 && r.h <= 594.0 * 0.6 + 1e-9);
assert!((r.x + r.w / 2.0 - 420.5).abs() < 1e-9 && (r.y + r.h / 2.0 - 297.0).abs() < 1e-9);
let hoch = initial_frame(1000.0, 4000.0, 841.0, 594.0, 0.6);
assert!((hoch.h - 594.0 * 0.6).abs() < 1e-9);
}
}
+59 -2
View File
@@ -106,6 +106,14 @@ pub struct TitleBlock {
pub date: String,
pub author: String,
pub plan_number: String,
/// Kennwort der Abgabe ([208], `Project.competition.keyword`), sonst leer.
pub keyword: String,
/// Anonyme Abgabe ([208]): `project_name` ist das Kennwort, `author` leer.
pub anonymous: bool,
/// „Plan x/n" ([208]): Stelle des Blatts unter den Blättern mit Plakat-Kopfzeile seines Masters
/// (ohne solchen Master: unter allen Blättern des Projekts).
pub plan_index: usize,
pub plan_count: usize,
}
/// Titelblock mit Master-Vererbung (`resolveTitleBlock`): `layout` mit `id`/`name`/`planNumber` und
@@ -134,13 +142,37 @@ pub fn resolve_title_block(root: &Map<String, Value>, layout: &Value, master: &V
let idx = list(root, "layouts").iter().position(|l| l.get("id").and_then(Value::as_str) == layout_id && layout_id.is_some());
let auto = format!("{:02}", idx.unwrap_or(0) + 1);
let text = |v: Option<&Value>| v.and_then(Value::as_str).unwrap_or("").to_string();
// Wettbewerb ([208])
let comp = root.get("competition").filter(|v| v.is_object());
let keyword = non_empty(comp.and_then(|c| c.get("keyword"))).unwrap_or_default();
let anonymous = comp.and_then(|c| c.get("anonymous")).and_then(Value::as_bool).unwrap_or(false);
// „Plan x/n": unter den Blättern, deren Master die Plakat-Kopfzeile trägt (hat das Blatt keinen solchen Master: alle)
let masters = list(root, "masterLayouts");
let poster_master = |l: &Value| {
let mid = l.get("masterId").and_then(Value::as_str);
mid.is_some()
&& masters
.iter()
.any(|m| m.get("id").and_then(Value::as_str) == mid && m.get("posterHeader").and_then(Value::as_bool).unwrap_or(false))
};
let all = list(root, "layouts");
let (plan_index, plan_count) = if poster_master(layout) {
let group: Vec<&Value> = all.iter().filter(|l| poster_master(l)).collect();
(group.iter().position(|l| l.get("id").and_then(Value::as_str) == layout_id && layout_id.is_some()).map_or(0, |i| i + 1), group.len())
} else {
(idx.map_or(0, |i| i + 1), all.len())
};
TitleBlock {
project_name: non_empty(tb_get("projectName")).unwrap_or_else(|| text(root.get("name"))),
project_name: if anonymous { keyword.clone() } else { non_empty(tb_get("projectName")).unwrap_or_else(|| text(root.get("name"))) },
sheet_name: non_empty(tb_get("sheetName")).unwrap_or_else(|| text(layout.get("name"))),
scale: non_empty(tb_get("scale")).unwrap_or(scale_text),
date: non_empty(tb_get("date")).unwrap_or_else(|| today.to_string()),
author: non_empty(tb_get("author")).unwrap_or_default(),
author: if anonymous { String::new() } else { non_empty(tb_get("author")).unwrap_or_default() },
plan_number: non_empty(layout.get("planNumber")).unwrap_or(auto),
keyword,
anonymous,
plan_index,
plan_count,
}
}
@@ -189,6 +221,10 @@ mod tests {
date: "2026-10-29".into(),
author: String::new(),
plan_number: "02".into(),
keyword: String::new(),
anonymous: false,
plan_index: 2,
plan_count: 2,
}
);
let none = resolve_title_block(&root, &json!({"id": "x", "name": "Y", "viewports": [], "planNumber": " A1 "}), &Value::Null, "d");
@@ -210,4 +246,25 @@ mod tests {
let got: Vec<(usize, f64, f64)> = pages.iter().map(|p| (p.layout, p.width_mm, p.height_mm)).collect();
assert_eq!(got, vec![(0, 297.0, 420.0), (1, 297.0, 210.0)]);
}
#[test]
fn anonym_zeigt_nur_das_kennwort() {
let root = obj(json!({
"name": "Haus Muster AG",
"competition": {"anonymous": true, "keyword": " FALKE 7 "},
"layouts": [{"id": "a", "masterId": "m"}, {"id": "b"}, {"id": "c", "masterId": "m"}],
"masterLayouts": [{"id": "m", "posterHeader": true, "titleBlock": {"projectName": "Büro AG", "author": "M. Muster"}}],
}));
let master = root["masterLayouts"][0].clone();
let layout = json!({"id": "c", "name": "Grundriss", "masterId": "m", "viewports": []});
let tb = resolve_title_block(&root, &layout, &master, "d");
assert_eq!((tb.project_name.as_str(), tb.author.as_str(), tb.keyword.as_str(), tb.anonymous), ("FALKE 7", "", "FALKE 7", true));
// Plan x/n zählt nur Blätter mit Plakat-Master: „c" ist das zweite von zwei
assert_eq!((tb.plan_index, tb.plan_count), (2, 2));
// nicht anonym: Name und Autor des Masters bleiben, Kennwort steht trotzdem bereit
let mut open = root.clone();
open.insert("competition".into(), json!({"anonymous": false, "keyword": "K"}));
let tb = resolve_title_block(&open, &layout, &master, "d");
assert_eq!((tb.project_name.as_str(), tb.author.as_str(), tb.keyword.as_str(), tb.anonymous), ("Büro AG", "M. Muster", "K", false));
}
}
+145
View File
@@ -0,0 +1,145 @@
//! Plakat-Vorlagen für Wettbewerbs-Abgaben ([208]): Ränder, Spaltenraster (Hilfslinien), Kopfzeile mit
//! Kennwort-Feld und „Plan x/n". Die Masse folgen der Blattgrösse (A0 gross, A1/kleiner); gezeichnet wird die
//! Kopfzeile am Bildschirm (SVG) und im PDF (jsPDF) aus denselben Elementen (`header_items`).
use serde::Serialize;
/// Masse eines Plakats in Papier-mm.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PosterMetrics {
pub width_mm: f64,
pub height_mm: f64,
pub margin_mm: f64,
pub header_height_mm: f64,
pub columns: u32,
pub gutter_mm: f64,
/// Obere Kante der Inhaltsfläche (unter der Kopfzeile plus Spaltenabstand).
pub content_top_mm: f64,
pub guides: Vec<Guide>,
}
/// Hilfslinie: `axis` "x" (senkrecht, von links) oder "y" (waagrecht, von oben).
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Guide {
pub axis: &'static str,
pub pos_mm: f64,
}
fn r2(v: f64) -> f64 {
(v * 100.0).round() / 100.0
}
/// Plakat-Masse für ein Blatt `w`×`h` mm. A0-Klasse = lange Kante ab 1000 mm.
pub fn metrics(w: f64, h: f64) -> PosterMetrics {
let landscape = w > h;
let big = w.max(h) >= 1000.0;
let (margin, header, gutter) = if big { (25.0, 40.0, 12.0) } else { (20.0, 28.0, 10.0) };
let columns: u32 = match (big, landscape) {
(true, true) => 8,
(true, false) => 6,
(false, true) => 6,
(false, false) => 4,
};
let col_w = (w - 2.0 * margin - f64::from(columns - 1) * gutter) / f64::from(columns);
let mut guides = Vec::new();
for i in 0..columns {
let left = margin + f64::from(i) * (col_w + gutter);
guides.push(Guide { axis: "x", pos_mm: r2(left) });
guides.push(Guide { axis: "x", pos_mm: r2(left + col_w) });
}
let content_top = margin + header + gutter;
guides.push(Guide { axis: "y", pos_mm: r2(margin) });
guides.push(Guide { axis: "y", pos_mm: r2(margin + header) });
guides.push(Guide { axis: "y", pos_mm: r2(content_top) });
guides.push(Guide { axis: "y", pos_mm: r2(h - margin) });
PosterMetrics { width_mm: w, height_mm: h, margin_mm: margin, header_height_mm: header, columns, gutter_mm: gutter, content_top_mm: content_top, guides }
}
/// Zeichenelement der Kopfzeile (Papier-mm). Texthöhe `size_mm` ist die Schrifthöhe (Em), `y` die Grundlinie.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum HeaderItem {
Rect { x: f64, y: f64, w: f64, h: f64, stroke: f64 },
#[serde(rename_all = "camelCase")]
Text { x: f64, y: f64, text: String, size_mm: f64, align: &'static str, bold: bool },
}
/// Kopfzeile: Band über die Satzbreite, links das Kennwort-Feld (Beschriftung klein, Kennwort gross), in der Mitte
/// der Titel (leer bei anonymer Abgabe), rechts „Plan x/n".
pub fn header_items(w: f64, h: f64, keyword_label: &str, keyword: &str, title: &str, plan_text: &str) -> Vec<HeaderItem> {
let m = metrics(w, h);
let (x0, y0) = (m.margin_mm, m.margin_mm);
let band_w = w - 2.0 * m.margin_mm;
let hh = m.header_height_mm;
let pad = hh * 0.18;
let kw_w = (band_w * 0.28).min(hh * 7.0);
let mut out = vec![
HeaderItem::Rect { x: x0, y: y0, w: band_w, h: hh, stroke: 0.35 },
HeaderItem::Rect { x: x0, y: y0, w: kw_w, h: hh, stroke: 0.35 },
HeaderItem::Text { x: x0 + pad, y: y0 + hh * 0.3, text: keyword_label.to_string(), size_mm: hh * 0.2, align: "left", bold: false },
];
if !keyword.is_empty() {
out.push(HeaderItem::Text { x: x0 + pad, y: y0 + hh * 0.8, text: keyword.to_string(), size_mm: hh * 0.42, align: "left", bold: true });
}
if !title.is_empty() {
out.push(HeaderItem::Text { x: x0 + kw_w + (band_w - kw_w) / 2.0 - hh * 0.9, y: y0 + hh * 0.64, text: title.to_string(), size_mm: hh * 0.4, align: "center", bold: true });
}
if !plan_text.is_empty() {
out.push(HeaderItem::Text { x: x0 + band_w - pad, y: y0 + hh * 0.64, text: plan_text.to_string(), size_mm: hh * 0.4, align: "right", bold: false });
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a1_quer_hat_sechs_spalten_im_rand() {
let m = metrics(841.0, 594.0);
assert_eq!((m.columns, m.margin_mm, m.header_height_mm), (6, 20.0, 28.0));
let xs: Vec<f64> = m.guides.iter().filter(|g| g.axis == "x").map(|g| g.pos_mm).collect();
assert_eq!(xs.len(), 12);
assert_eq!(xs[0], 20.0);
assert!((xs[11] - (841.0 - 20.0)).abs() < 0.01);
// gleich breite Spalten, Abstand = Spaltenabstand
assert!(((xs[2] - xs[1]) - 10.0).abs() < 0.02);
assert!(((xs[1] - xs[0]) - (xs[3] - xs[2])).abs() < 0.02);
let ys: Vec<f64> = m.guides.iter().filter(|g| g.axis == "y").map(|g| g.pos_mm).collect();
assert_eq!(ys, vec![20.0, 48.0, 58.0, 574.0]);
}
#[test]
fn spaltenzahl_nach_format_und_ausrichtung() {
assert_eq!(metrics(1189.0, 841.0).columns, 8);
assert_eq!(metrics(841.0, 1189.0).columns, 6);
assert_eq!(metrics(594.0, 841.0).columns, 4);
assert_eq!(metrics(841.0, 594.0).columns, 6);
assert_eq!(metrics(1189.0, 841.0).margin_mm, 25.0);
}
#[test]
fn kopfzeile_zeigt_kennwort_und_plannummer() {
let items = header_items(841.0, 594.0, "Kennwort", "FALKE 7", "", "Plan 2/5");
let texts: Vec<&str> = items
.iter()
.filter_map(|i| if let HeaderItem::Text { text, .. } = i { Some(text.as_str()) } else { None })
.collect();
assert_eq!(texts, vec!["Kennwort", "FALKE 7", "Plan 2/5"]);
// alles innerhalb des Blatts
for i in &items {
if let HeaderItem::Rect { x, y, w, h, .. } = i {
assert!(*x >= 0.0 && *y >= 0.0 && x + w <= 841.0 && y + h <= 594.0);
}
}
}
#[test]
fn leeres_kennwort_laesst_das_feld_leer() {
let items = header_items(841.0, 594.0, "Kennwort", "", "Haus", "Plan 1/1");
assert!(!items.iter().any(|i| matches!(i, HeaderItem::Text { bold: true, text, .. } if text.is_empty())));
assert!(items.iter().any(|i| matches!(i, HeaderItem::Text { text, .. } if text == "Haus")));
}
}
+2
View File
@@ -94,7 +94,9 @@ pub mod layers;
pub mod levels;
pub mod pens;
pub mod folder_tree;
pub mod layout_image;
pub mod layout_model;
pub mod layout_poster;
pub mod clash_broad;
pub mod sheet_viewports;
pub mod parametric_walls;
+110
View File
@@ -5574,6 +5574,90 @@ pub struct Layout {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub tables: Option<Vec<LayoutTable>>,
/// Bilder auf dem Blatt ([208]): Renderings, Fotos, Luftbilder; fehlt = keine.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub images: Option<Vec<LayoutImage>>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
}
/// Bild auf einem Layout-Blatt ([208]): PNG oder JPEG als Data-URL (gleicher Weg wie `ContextImage.src`),
/// im Rahmen `xMm`/`yMm`/`widthMm`/`heightMm` (Papier-mm). Das Seitenverhältnis des Ausschnitts bleibt erhalten;
/// `crop` schneidet zu (Anteile 0..1 des Originals). Im PDF wird das Original unverändert eingebettet (JPEG ohne
/// Neukompression).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
pub struct LayoutImage {
pub id: String,
/// Anzeigename (Dateiname).
pub name: String,
/// Bildquelle als Data-URL (`data:image/png;base64,…` oder `data:image/jpeg;base64,…`).
pub src: String,
/// Linke Kante auf dem Blatt (mm, von links).
#[serde(rename = "xMm")]
pub x_mm: f64,
/// Obere Kante auf dem Blatt (mm, von oben).
#[serde(rename = "yMm")]
pub y_mm: f64,
/// Breite des gezeigten Ausschnitts (mm).
#[serde(rename = "widthMm")]
pub width_mm: f64,
/// Höhe des gezeigten Ausschnitts (mm).
#[serde(rename = "heightMm")]
pub height_mm: f64,
/// Pixelbreite des Originals (aus dem Dateikopf gelesen).
#[serde(rename = "pixelWidth")]
pub pixel_width: f64,
/// Pixelhöhe des Originals.
#[serde(rename = "pixelHeight")]
pub pixel_height: f64,
/// Zuschnitt als Anteile des Originals (0..1); fehlt = ganzes Bild.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional, inline)]
pub crop: Option<LayoutImageCrop>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
}
/// Zuschnitt eines Blatt-Bilds ([208]): linke/obere Kante und Breite/Höhe als Anteile des Originals.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
pub struct LayoutImageCrop {
pub x: f64,
pub y: f64,
pub w: f64,
pub h: f64,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
}
/// Hilfslinie eines Masters ([208], Gestaltungsraster): senkrecht (`x`) oder waagrecht (`y`) in Papier-mm.
/// Nur am Bildschirm, nie im Druck.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
pub struct LayoutGuide {
/// "x" = senkrechte Linie bei `posMm` von links, "y" = waagrechte Linie bei `posMm` von oben.
pub axis: String,
#[serde(rename = "posMm")]
pub pos_mm: f64,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
}
/// Wettbewerbs-Einstellung des Projekts ([208]): anonym = Kennwort statt Büro- und Projektname in Plankopf,
/// Dateinamen und PDF-Metadaten.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
#[serde(default)]
pub struct CompetitionSettings {
/// Anonyme Abgabe: keine Büro-/Autor-Angaben in Export und Plankopf.
pub anonymous: bool,
/// Kennwort der Abgabe (steht in Plankopf und PDF-Titel).
pub keyword: String,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -5747,6 +5831,22 @@ pub struct MasterLayout {
#[serde(rename = "customHeightMm", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub custom_height_mm: Option<f64>,
/// Vorlagen-Schlüssel ([208], z. B. "poster-a1-landscape"): wiederverwendet den Master beim Anlegen weiterer Plakate.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub template: Option<String>,
/// Plakat-Kopfzeile ([208]): Band über die Satzbreite mit Kennwort-Feld, Projekttitel und „Plan x/n".
#[serde(rename = "posterHeader", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub poster_header: Option<bool>,
/// Massstab unter jedem Viewport ausgeben ([208]).
#[serde(rename = "viewportScaleLabels", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub viewport_scale_labels: Option<bool>,
/// Hilfslinien des Gestaltungsrasters ([208]), nur am Bildschirm.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub guides: Option<Vec<LayoutGuide>>,
#[serde(flatten)]
#[ts(skip)]
pub extra: Extra,
@@ -6093,6 +6193,10 @@ pub struct Project {
#[serde(rename = "projectNumber", default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub project_number: Option<String>,
/// Wettbewerb ([208]): anonyme Abgabe mit Kennwort.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[ts(optional)]
pub competition: Option<CompetitionSettings>,
/// Höhe von ±0.00 (OK fertig Boden des Bezugsgeschosses, `DrawingLevel.zeroLevel`)
/// in Metern über Meer (m ü. M.), editierbar im Einstellungs-Fenster. Optional.
/// Die automatischen Koten im Schnitt/in der Ansicht schreiben „±0.00 = 512.40"
@@ -6956,6 +7060,12 @@ impl Project {
None => Default::default(),
};
}
"competition" => {
self.competition = match v {
Some(v) => <Option<CompetitionSettings>>::deserialize(v).map_err(|e| e.to_string())?,
None => Default::default(),
};
}
"referenceElevationMasl" => {
self.reference_elevation_masl = match v {
Some(v) => <Option<f64>>::deserialize(v).map_err(|e| e.to_string())?,
+2 -2
View File
@@ -15,13 +15,13 @@ const REQUIRED_ARRAYS: [&str; 3] = ["walls", "layers", "drawingLevels"];
const DEFAULT_ARRAYS: [&str; 5] = ["lineStyles", "hatches", "components", "wallTypes", "drawings2d"];
/// Bekannte Felder von `Project` (für die Meldung unbekannter Felder).
const KNOWN_KEYS: [&str; 57] = [
const KNOWN_KEYS: [&str; 58] = [
"formatVersion", "id", "name", "lineStyles", "textStyles", "hatches", "components", "wallTypes",
"ceilingTypes", "roofTypes", "blockDefs", "doorTypes", "windowTypes", "stairTypes", "pens",
"penSets", "activePenSetId", "customPalettes", "builtinPaletteBanks", "drawingLevels", "layers",
"walls", "ceilings", "roofs", "openings", "stairs", "rooms", "drawings2d", "context",
"extrudedSolids", "columns", "groups", "parametricWalls", "overrideRules", "viewSnapshots",
"viewSnapshotFolders", "viewTemplates", "layouts", "masterLayouts", "layoutFolders", "publishSets", "publishLog", "projectNumber", "referenceElevationMasl",
"viewSnapshotFolders", "viewTemplates", "layouts", "masterLayouts", "layoutFolders", "publishSets", "publishLog", "projectNumber", "competition", "referenceElevationMasl",
"geoAnchor", "roomProgram", "roomProgramTolerance", "parcelArea", "sunStudy", "siteRules", "scaleLineWeights",
"lineCap", "lineJoin", "trees", "uiState",
"modelViewOptions", "cameras",
+41
View File
@@ -36,6 +36,47 @@ pub fn layout_call(name: &str, arg_json: &str) -> String {
None => return String::new(),
}
}
// Bilder auf Blättern ([208], `layout_image.rs`): `imageInfo` (`{src}`) liest Format und Pixelgrösse aus der
// Data-URL; `imageGeometry` (`{xMm,yMm,widthMm,heightMm,pixelWidth,crop?}`) liefert Klipp-/Zeichen-Rechteck
// und dpi; `imageAspect` (`{pixelWidth,pixelHeight,crop?}`); `imageInitial` (`{pixelWidth,pixelHeight,sheetW,sheetH}`).
"imageInfo" => {
let Ok(a) = serde_json::from_str::<Value>(arg_json) else { return String::new() };
match crate::layout_image::image_info(a["src"].as_str().unwrap_or("")) {
Some(i) => json!(i),
None => return String::new(),
}
}
"imageGeometry" | "imageAspect" | "imageInitial" => {
let Ok(a) = serde_json::from_str::<Value>(arg_json) else { return String::new() };
let num = |k: &str| a[k].as_f64().filter(|v| v.is_finite());
let crop = a["crop"].as_object().and_then(|c| Some((c.get("x")?.as_f64()?, c.get("y")?.as_f64()?, c.get("w")?.as_f64()?, c.get("h")?.as_f64()?)));
match name {
"imageGeometry" => {
let (Some(x), Some(y), Some(w), Some(h), Some(px)) = (num("xMm"), num("yMm"), num("widthMm"), num("heightMm"), num("pixelWidth")) else { return String::new() };
json!(crate::layout_image::geometry(crate::layout_image::Rect { x, y, w, h }, px, crop))
}
"imageAspect" => {
let (Some(pw), Some(ph)) = (num("pixelWidth"), num("pixelHeight")) else { return String::new() };
json!(crate::layout_image::aspect(pw, ph, crop))
}
_ => {
let (Some(pw), Some(ph), Some(sw), Some(sh)) = (num("pixelWidth"), num("pixelHeight"), num("sheetW"), num("sheetH")) else { return String::new() };
json!(crate::layout_image::initial_frame(pw, ph, sw, sh, 0.6))
}
}
}
// Plakat-Vorlagen ([208], `layout_poster.rs`): `posterMetrics` (`{widthMm,heightMm}`) und `posterHeader`
// (`{widthMm,heightMm,keywordLabel,keyword,title,planText}`).
"posterMetrics" | "posterHeader" => {
let Ok(a) = serde_json::from_str::<Value>(arg_json) else { return String::new() };
let (Some(w), Some(h)) = (a["widthMm"].as_f64().filter(|v| *v > 0.0 && v.is_finite()), a["heightMm"].as_f64().filter(|v| *v > 0.0 && v.is_finite())) else { return String::new() };
if name == "posterMetrics" {
json!(crate::layout_poster::metrics(w, h))
} else {
let s = |k: &str| a[k].as_str().unwrap_or("").to_string();
json!(crate::layout_poster::header_items(w, h, &s("keywordLabel"), &s("keyword"), &s("title"), &s("planText")))
}
}
_ => {
let Ok(a) = serde_json::from_str::<Args>(arg_json) else { return String::new() };
match name {