[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:
39 files changed
+2184
-27
No files matched your search
@@ -65,8 +65,23 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC.
|
||||
### Phase 2 (20.–26.11.): Wettbewerb lückenlos
|
||||
- ○ **[207]** Schwarzplan / Situationsplan 1:500: Gebäude schwarz gefüllt, Nachbarbauten (Kataster/swisstopo) grau/schwarz,
|
||||
Parzelle, Strassen, Nordpfeil, Massstabsbalken; als Ansichtsvorlage „Situation WBW“. · M
|
||||
- ○ **[208]** Wettbewerbs-Layouts: Plakat-Vorlagen A0/A1 hoch/quer mit Raster, Kennwort-Feld (Anonymität: kein Büroname,
|
||||
Metadaten im PDF leer), Planköpfe; Publikationssatz „WBW-Abgabe“ → PDF. · M
|
||||
- ◐ **[208]** Wettbewerbs-Abgabe (12.11.). Umgesetzt: **Bild-Element im Layout** (`Layout.images`, `LayoutImage`: PNG/JPEG als Data-URL wie
|
||||
`ContextImage.src`, Rahmen in Papier-mm, Zuschnitt als Anteile; Kern `layout_image.rs`: Dateikopf, Seitenverhältnis, Zeichen-/Klipp-Rechteck,
|
||||
dpi; Blatt: Knopf „Bild“, verschieben, Ecke skalieren mit festem Seitenverhältnis, HUD mit Breite, Zuschnitt, dpi-Warnung unter 100;
|
||||
PDF: Original unverändert eingebettet, JPEG ohne Neukompression, auf den Rahmen geklippt). Rendering-Dialog: „Ins Layout einsetzen“
|
||||
(Ziel-Blatt wählbar, vorgewählt das offene). **Plakat-Vorlagen** A0/A1 hoch/quer (`MasterLayout.template`, `posterHeader`,
|
||||
`viewportScaleLabels`, `guides`; Kern `layout_poster.rs`: Ränder, Spalten 4–8, Hilfslinien nur am Bildschirm, Kopfzeile mit Kennwort-Feld
|
||||
und „Plan x/n“ unter den Plakat-Blättern, Massstab unter jedem Viewport), wählbar im Dialog „Neues Layout“. **Anonymität**
|
||||
(`Project.competition`: anonym + Kennwort; Mappe, Abschnitt Publikation): Plankopf zeigt das Kennwort statt Projekt/Bearbeiter, PDF-Info
|
||||
nur Titel = Kennwort, Producer/Datum längengleich neutralisiert (`export/pdfInfo.ts`; jsPDF schreibt sie sonst immer), Dateinamen und
|
||||
Schriftfeld des Einzelplan-PDF mit Kennwort. **Publikationssatz „WBW-Abgabe“** (Knopf in der Publikation): alle Plakate als ein PDF,
|
||||
Format über den Satz-Editor auf Einzeldateien umstellbar. Tests: Rust (`layout_image`, `layout_poster`, Titelblock anonym), vitest
|
||||
(`layoutImages`, `posterTemplates`, `layoutPdf.images`), e2e `competition` (A1 quer aus Vorlage, Bild, anonym, PDF). Offen: Hilfslinien nicht
|
||||
als Fang und nicht frei setzbar; Bild-Zuschnitt nur per Prozentfeldern (kein Ziehen), Bild in DXF/IFC-Exporten nicht; Anonymität nur im PDF und
|
||||
in Dateinamen (IFC/DXF/SVG-Metadaten, Layer-/Blattnamen mit Büroangaben prüft niemand); Berichts-PDF (`areaReport`)
|
||||
noch nicht anonymisiert (Blatt-, Ordner- und Satz-PDF sind es); Download-Namen im Browser ohne Tauri-Dialog; grosse Bilder: jede
|
||||
Blatt-Änderung (Viewport verschieben …) ersetzt das ganze Layout samt Data-URL im Op und im Verlauf (wie `ContextImage`) — bei vielen MB Bilder
|
||||
in eine eigene Sammlung auslagern; nicht in der Tauri-App/auf dem Mac geprüft. · M
|
||||
- [61] Raumprogramm gegen Modell und Flächennachweis SIA 416 als Tabelle/Layout-Element ([70]); Kennzahlen (GF, GV, HNF/GF, Fassadenanteil).
|
||||
- 3D-Bilder für die Abgabe: hochaufgelöster PNG-Export (Perspektive, Axonometrie, Schatten), Sonnenstand; [205] Pausfolie.
|
||||
- [199]/[204] Plan- und App-Review-Reste im Darstellungsbereich 1:500/1:200 schliessen.
|
||||
|
||||
@@ -292,6 +292,7 @@ Beispiel: Die Plan-Ansicht zeigt das Erdgeschoss im Massstab 1:100.
|
||||
| SVG (CLI, Goldens) | `planToSvgString()` in `src/export/planToSvgString.ts` | `plan_svg_string()` → `plan_svg()` in `plan/svg.rs` | Text |
|
||||
| PDF eines Plans | `src/export/exportPdf.ts`: `planToRenderScene()` → `sceneToPrintSvg()` (`src/export/sceneToPrintSvg.ts`) | `plan_scene_f64()` in `plan/scene.rs` | jsPDF und svg2pdf.js |
|
||||
| Layout-Blatt, Blatt-PDF | `planToPrintSvg()` in `src/export/planToPrintSvg.ts`, aufgerufen von `src/ui/LayoutSheet.tsx` und `src/export/layoutPdf.ts` | `plan_print_svg_ops()` → `print_svg_ops()` in `plan/print_svg.rs` | SVG-Knoten in Papier-mm |
|
||||
| Bild auf dem Layout-Blatt, Plakat-Vorlage ([208]) | `src/model/layoutImages.ts` (Data-URL, Zuschnitt), `src/model/posterTemplates.ts`, Bildzeichnen in `layoutPdf.ts` (`drawImagesPdf`, JPEG ohne Neukompression), `LayoutSheet.tsx` | `layout_image.rs`, `layout_poster.rs` über `layout_call` | `Layout.images`, Master mit Raster/Kopfzeile |
|
||||
| DXF, DWG | `src/export/exportDxf.ts` | `plan_dxf_flat()` → `collect()`, `encode()` in `plan/dxf.rs` | `fileio`: `export_dxf()`, `export_dwg()` in `src-tauri/fileio/src/export.rs` |
|
||||
|
||||
Runde Formen (Stütze, Bogenwand, Bogen-Umrisse) reisen im Puffer als Vielecke; die Ausgaben erkennen die Bögen
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
// [208] Wettbewerbs-Abgabe: Blatt A1 quer aus der Plakat-Vorlage (Raster, Kopfzeile mit Kennwort, Massstab je
|
||||
// Viewport), Bild aufs Blatt setzen (Zuschnitt, Auflösung), anonyme Abgabe mit Kennwort und der Satz
|
||||
// „WBW-Abgabe" → ein PDF ohne Büro-/Autor-Metadaten. Mit DOSSIER_SHOTS=<ordner> entstehen PDF und Screenshot.
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { deflateSync, inflateSync } from "node:zlib";
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, openSample, openTab, startNewProject, test } from "./app";
|
||||
|
||||
/** PNG (Verlauf, Standard 160 × 90 px), im Test erzeugt: kein Fixture, nur die Pflicht-Chunks. */
|
||||
function testPng(w = 160, h = 90): Buffer {
|
||||
const crc = (buf: Buffer): number => {
|
||||
let c = ~0;
|
||||
for (const b of buf) {
|
||||
c ^= b;
|
||||
for (let k = 0; k < 8; k++) c = (c >>> 1) ^ (0xedb88320 & -(c & 1));
|
||||
}
|
||||
return ~c >>> 0;
|
||||
};
|
||||
const chunk = (type: string, data: Buffer): Buffer => {
|
||||
const len = Buffer.alloc(4);
|
||||
len.writeUInt32BE(data.length);
|
||||
const td = Buffer.concat([Buffer.from(type, "latin1"), data]);
|
||||
const c = Buffer.alloc(4);
|
||||
c.writeUInt32BE(crc(td));
|
||||
return Buffer.concat([len, td, c]);
|
||||
};
|
||||
const ihdr = Buffer.alloc(13);
|
||||
ihdr.writeUInt32BE(w, 0);
|
||||
ihdr.writeUInt32BE(h, 4);
|
||||
ihdr[8] = 8; // Bits
|
||||
ihdr[9] = 2; // RGB
|
||||
const raw = Buffer.alloc((w * 3 + 1) * h);
|
||||
for (let y = 0; y < h; y++) {
|
||||
const row = y * (w * 3 + 1);
|
||||
for (let x = 0; x < w; x++) {
|
||||
raw[row + 1 + x * 3] = Math.round((x / w) * 200);
|
||||
raw[row + 2 + x * 3] = Math.round(120 + (y / h) * 100);
|
||||
raw[row + 3 + x * 3] = 200 - Math.round((y / h) * 120);
|
||||
}
|
||||
}
|
||||
const idat = deflateSync(raw);
|
||||
return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", ihdr), chunk("IDAT", idat), chunk("IEND", Buffer.alloc(0))]);
|
||||
}
|
||||
|
||||
/** Text aller Inhaltsströme eines PDFs (Flate entpackt). */
|
||||
function pdfStreams(buf: Buffer): string {
|
||||
const src = buf.toString("latin1");
|
||||
let out = src;
|
||||
for (const m of src.matchAll(/stream\r?\n/g)) {
|
||||
const start = m.index! + m[0].length;
|
||||
const end = src.indexOf("endstream", start);
|
||||
if (end < 0) continue;
|
||||
try {
|
||||
out += inflateSync(buf.subarray(start, end)).toString("latin1");
|
||||
} catch {
|
||||
/* kein Flate-Strom */
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function paperBox(page: Page) {
|
||||
return (await page.locator("[data-sheet-backdrop] > rect").nth(1).boundingBox())!;
|
||||
}
|
||||
|
||||
test("Plakat A1 quer aus Vorlage, Bild einsetzen, anonym als WBW-Abgabe exportieren", async ({ page }) => {
|
||||
await startNewProject(page);
|
||||
await openSample(page);
|
||||
|
||||
// Ausschnitt „EG" für den Viewport.
|
||||
await openTab(page, "Ausschnitte");
|
||||
await page.getByTitle("Ausschnitt speichern").first().click();
|
||||
await page.getByPlaceholder("Ausschnitt speichern als:").fill("EG");
|
||||
await page.keyboard.press("Enter");
|
||||
|
||||
// Neues Layout aus der Plakat-Vorlage A1 quer.
|
||||
await openTab(page, "Mappe");
|
||||
await page.getByRole("button", { name: "Layout erstellen" }).first().click();
|
||||
await page.locator("[data-testid=newlayout-poster]").check();
|
||||
await expect(page.locator("[data-testid=newlayout-poster-select]")).toHaveValue("poster-a1-landscape");
|
||||
await page.getByRole("button", { name: "Erstellen", exact: true }).click();
|
||||
await page.keyboard.press("Enter");
|
||||
await page.locator(".nav-row", { hasText: "Layout" }).first().dblclick();
|
||||
await expect(page.locator(".layout-sheet-pane")).toBeVisible();
|
||||
|
||||
// Blatt: A1 quer (841 : 594), Kopfzeile mit Kennwort-Feld, Hilfslinien des Gestaltungsrasters.
|
||||
const paper = await paperBox(page);
|
||||
expect(paper.width / paper.height).toBeCloseTo(841 / 594, 2);
|
||||
await expect(page.locator("[data-poster-header]")).toBeAttached();
|
||||
await expect(page.locator("[data-poster-header] text").first()).toHaveText("Kennwort");
|
||||
await expect(page.locator("[data-poster-header] text").last()).toHaveText("Plan 1/1");
|
||||
expect(await page.locator("[data-guides] line").count()).toBe(16); // 6 Spalten × 2 + 4 waagrechte
|
||||
|
||||
// Viewport aufziehen: Massstabsangabe darunter.
|
||||
await page.getByRole("button", { name: /Viewport aufziehen/ }).click();
|
||||
const a = { x: paper.x + paper.width * 0.03, y: paper.y + paper.height * 0.16 };
|
||||
const b = { x: paper.x + paper.width * 0.5, y: paper.y + paper.height * 0.8 };
|
||||
await page.mouse.move(a.x, a.y);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(b.x, b.y, { steps: 6 });
|
||||
await page.mouse.up();
|
||||
const bind = page.locator(".layout-sheet-bind select");
|
||||
if (await bind.isVisible().catch(() => false)) await bind.selectOption({ label: "EG" });
|
||||
await expect(page.locator("[data-viewport-id] svg").first()).toBeAttached();
|
||||
await expect(page.locator("[data-scale-label]").first()).toHaveText(/^1:\d+$/);
|
||||
|
||||
// Bild einsetzen (PNG), mittig im Seitenverhältnis; Auflösung und Zuschnitt im HUD.
|
||||
await page.locator("[data-testid=sheet-image-input]").setInputFiles({ name: "rendering.png", mimeType: "image/png", buffer: testPng() });
|
||||
const img = page.locator("[data-image-id]");
|
||||
await expect(img).toHaveCount(1);
|
||||
await expect(page.locator("[data-testid=image-hud]")).toBeVisible();
|
||||
await expect(page.locator("[data-testid=image-dpi]")).toContainText("dpi");
|
||||
const w0 = Number(await page.locator("[data-testid=image-width]").inputValue());
|
||||
expect(w0).toBeGreaterThan(100);
|
||||
// Breite ändern: die Höhe folgt dem Seitenverhältnis (160 : 90); in die rechten zwei Spalten des Rasters schieben.
|
||||
await page.locator("[data-testid=image-width]").fill("250");
|
||||
await expect(page.locator("[data-image-id] svg image")).toHaveAttribute("height", "140.6");
|
||||
await page.locator("[data-testid=image-x]").fill("570");
|
||||
await page.locator("[data-testid=image-y]").fill("70");
|
||||
await expect(page.locator("[data-image-id] svg image")).toHaveAttribute("x", "570");
|
||||
// Zuschnitt links 25 %: Rahmen behält die Breite, die Höhe wächst (Ausschnitt schmaler); das ganze Bild liegt breiter dahinter.
|
||||
await page.locator("[data-testid=image-crop-left]").fill("25");
|
||||
await expect(page.locator("[data-image-id] svg image")).toHaveAttribute("width", /^333\./);
|
||||
// Verschieben per Maus: Körper ziehen, die Lage ändert sich.
|
||||
const body = page.locator("[data-image-body]");
|
||||
await expect(body).toBeAttached();
|
||||
const bb = (await body.boundingBox())!;
|
||||
await page.mouse.move(bb.x + bb.width / 2, bb.y + bb.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(bb.x + bb.width / 2 - 30, bb.y + bb.height / 2 + 20, { steps: 4 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => Number(await page.locator("[data-testid=image-x]").inputValue())).toBeLessThan(570);
|
||||
await page.locator("[data-testid=image-x]").fill("570");
|
||||
await page.locator("[data-testid=image-y]").fill("70");
|
||||
|
||||
// Anonyme Abgabe mit Kennwort; Plankopf zeigt nur das Kennwort.
|
||||
await page.locator("[data-testid=competition-anonymous]").check();
|
||||
await page.locator("[data-testid=competition-keyword]").fill("FALKE 7");
|
||||
await expect(page.locator("[data-poster-header] text", { hasText: "FALKE 7" })).toBeAttached();
|
||||
await expect(page.locator("[data-poster-header] text", { hasText: "Demo-Haus" })).toHaveCount(0);
|
||||
|
||||
// Satz „WBW-Abgabe": ein PDF.
|
||||
await page.locator("[data-testid=publish-add-wbw]").click();
|
||||
await expect(page.locator("[data-publish-set]")).toHaveCount(1);
|
||||
const pending = page.waitForEvent("download");
|
||||
await page.locator("[data-publish-set] [data-publish-run]").click();
|
||||
const dl = await pending;
|
||||
expect(dl.suggestedFilename()).toBe("FALKE 7_WBW-Abgabe.pdf");
|
||||
const path = await dl.path();
|
||||
const bytes = await readFile(path);
|
||||
const text = bytes.toString("latin1");
|
||||
expect(text.slice(0, 5)).toBe("%PDF-");
|
||||
expect(text).toMatch(/\/MediaBox \[0 0 2383\.93\d* 1683\.7\d*/); // A1 quer
|
||||
expect(text).toContain("/Title (FALKE 7)");
|
||||
expect(text).not.toContain("jsPDF");
|
||||
expect(text).not.toContain("Demo-Haus");
|
||||
expect(text).toContain("/Subtype /Image");
|
||||
const content = pdfStreams(bytes);
|
||||
expect(content).toContain("(FALKE 7)");
|
||||
expect(content).toContain("(Kennwort)");
|
||||
expect(content).not.toContain("Demo-Haus");
|
||||
|
||||
if (process.env.DOSSIER_SHOTS) {
|
||||
await mkdir(process.env.DOSSIER_SHOTS, { recursive: true });
|
||||
await writeFile(`${process.env.DOSSIER_SHOTS}/plakat-a1-quer.pdf`, bytes);
|
||||
await page.screenshot({ path: `${process.env.DOSSIER_SHOTS}/plakat-a1-quer-blatt.png` });
|
||||
}
|
||||
});
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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")));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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())?,
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -16,6 +16,7 @@ Abschnitt 3.4).
|
||||
| `exportPdf.ts` | Vektor-PDF eines Plans (Massstab, Papier, Ausrichtung) mit jsPDF und svg2pdf |
|
||||
| `layoutPdf.ts` | alle Layouts eines Ordners als Mehrseiten-PDF |
|
||||
| `pdfLayers.ts` | PDF-Ebenen (Optional Content Groups, `[80]`) |
|
||||
| `pdfInfo.ts` | PDF-Info-Wörterbuch; bei anonymer Wettbewerbs-Abgabe nur das Kennwort, Producer/Datum längengleich neutralisiert (`[208]`) |
|
||||
| `exportDxf.ts` | DXF/DWG des Grundrisses in Modellmetern; Schreiben in `src-tauri/fileio/src/export.rs` |
|
||||
| `legendSvg.ts` | Legende als Plan-/Druck-SVG (`[82]`) |
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@ import "svg2pdf.js";
|
||||
import type { Plan } from "../plan/generatePlan";
|
||||
import { planToRenderScene } from "../plan/toRenderScene";
|
||||
import { sceneToPrintSvg } from "./sceneToPrintSvg";
|
||||
import type { Project } from "../model/types";
|
||||
import { finishPdfBytes, pdfInfoFields } from "./pdfInfo";
|
||||
|
||||
/** Unterstützte Papierformate (Blattmasse in mm, Hochformat-Basis). */
|
||||
export type PaperFormat = "a4" | "a3";
|
||||
@@ -42,6 +44,8 @@ export interface ExportPdfOptions {
|
||||
titleBlock?: boolean;
|
||||
/** Dateiname des Downloads (ohne/inkl. .pdf). */
|
||||
fileName?: string;
|
||||
/** Wettbewerb ([208]): bei anonymer Abgabe nur das Kennwort als Titel, keine Erzeuger-/Datumsangaben im PDF. */
|
||||
competition?: Project["competition"];
|
||||
}
|
||||
|
||||
/** Blattmasse (mm) nach Format + Ausrichtung. */
|
||||
@@ -90,6 +94,8 @@ export async function buildPlanPdf(
|
||||
// und deckungsgleich mit der Blattgröße; svg2pdf bildet sie 1:1 auf das mm-Ziel
|
||||
// (Blattbreite/-höhe) ab.
|
||||
await doc.svg(print.svg, { x: 0, y: 0, width: pageW, height: pageH });
|
||||
// Info-Wörterbuch ([208]): anonym nur das Kennwort.
|
||||
doc.setProperties(pdfInfoFields({ name: opts.subtitle ?? opts.title, competition: opts.competition }));
|
||||
|
||||
if (opts.titleBlock ?? true) {
|
||||
drawTitleBlock(doc, pageW, pageH, opts);
|
||||
@@ -149,5 +155,16 @@ export async function savePlanPdf(
|
||||
): Promise<void> {
|
||||
const doc = await buildPlanPdf(plan, opts);
|
||||
const name = (opts.fileName ?? "grundriss").replace(/\.pdf$/i, "");
|
||||
if (opts.competition?.anonymous) {
|
||||
// doc.save() schreibt Producer/Datum selbst; anonym darum über die nachbearbeiteten Bytes.
|
||||
const bytes = finishPdfBytes({ competition: opts.competition }, new Uint8Array(doc.output("arraybuffer")));
|
||||
const url = URL.createObjectURL(new Blob([bytes as BlobPart], { type: "application/pdf" }));
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${name}.pdf`;
|
||||
a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
return;
|
||||
}
|
||||
doc.save(`${name}.pdf`);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// [208] Blatt-PDF: Bild eingebettet (JPEG ohne Neukompression), Plakat-Kopfzeile, anonyme Abgabe ohne Metadaten.
|
||||
import { inflateSync } from "node:zlib";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Layout, Project } from "../model/types";
|
||||
import { createPosterMaster, posterTemplate } from "../model/posterTemplates";
|
||||
import { addImage, createLayoutImage } from "../model/layoutImages";
|
||||
import { JPEG_64X48, PNG_40X30, PNG_40X30_ALPHA } from "../model/layoutImages.testing";
|
||||
import { buildPagesPdf, layoutPages, pdfBytes } from "./layoutPdf";
|
||||
import { pdfInfoText } from "./pdfInfo";
|
||||
|
||||
const latin1 = (b: Uint8Array): string => {
|
||||
let s = "";
|
||||
for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]);
|
||||
return s;
|
||||
};
|
||||
|
||||
/** Alle Flate-Streams des PDF entpackt, hintereinander (Seiteninhalt ist komprimiert). */
|
||||
function streamsText(bytes: Uint8Array): string {
|
||||
const all = Buffer.from(bytes);
|
||||
const text = all.toString("latin1");
|
||||
let out = "";
|
||||
for (const m of text.matchAll(/stream\r?\n/g)) {
|
||||
const from = m.index! + m[0].length;
|
||||
const to = text.indexOf("endstream", from);
|
||||
try {
|
||||
out += inflateSync(all.subarray(from, to)).toString("latin1") + "\n";
|
||||
} catch {
|
||||
// kein Flate-Stream (z. B. JPEG)
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function indexOfBytes(hay: Uint8Array, needle: Uint8Array): number {
|
||||
outer: for (let i = 0; i + needle.length <= hay.length; i++) {
|
||||
for (let j = 0; j < needle.length; j++) if (hay[i + j] !== needle[j]) continue outer;
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function poster(extra?: Partial<Project>): Project {
|
||||
const master = createPosterMaster("m1", posterTemplate("poster-a1-landscape")!);
|
||||
master.titleBlock = { projectName: "Büro Muster AG", author: "Maria Muster" };
|
||||
const base: Layout = { id: "l1", name: "Grundriss", paper: "a1", orientation: "landscape", masterId: "m1", viewports: [] };
|
||||
const img = createLayoutImage("i1", "foto.jpg", JPEG_64X48, { w: 841, h: 594 })!;
|
||||
return { ...sampleProject, name: "Haus Muster", masterLayouts: [master], layouts: [addImage(base, img)], ...extra };
|
||||
}
|
||||
|
||||
describe("Blatt-PDF mit Bild", () => {
|
||||
it("bettet das JPEG unverändert ein (DCTDecode, keine Neukompression)", async () => {
|
||||
const p = poster();
|
||||
const doc = await buildPagesPdf(p, layoutPages(p, ["l1"]));
|
||||
const bytes = pdfBytes(p, doc!);
|
||||
expect(latin1(bytes)).toContain("/DCTDecode");
|
||||
expect(indexOfBytes(bytes, JPEG_64X48)).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("PNG mit und ohne Alpha lässt sich einbetten", async () => {
|
||||
for (const png of [PNG_40X30, PNG_40X30_ALPHA]) {
|
||||
const p = poster();
|
||||
const img = createLayoutImage("i2", "r.png", png, { w: 841, h: 594 })!;
|
||||
p.layouts = [addImage({ ...p.layouts![0], images: [] }, img)];
|
||||
const doc = await buildPagesPdf(p, layoutPages(p, ["l1"]));
|
||||
expect(latin1(pdfBytes(p, doc!))).toContain("/Subtype /Image");
|
||||
}
|
||||
});
|
||||
|
||||
it("Blattgrösse A1 quer, Plakat-Kopfzeile mit Kennwort und Plan x/n", async () => {
|
||||
const p = poster({ competition: { anonymous: false, keyword: "FALKE 7" } });
|
||||
const doc = await buildPagesPdf(p, layoutPages(p, ["l1"]));
|
||||
const bytes = pdfBytes(p, doc!);
|
||||
expect(latin1(bytes)).toMatch(/\/MediaBox \[0 0 2383\.93\d* 1683\.7\d*/); // 841 × 594 mm in pt
|
||||
const content = streamsText(bytes);
|
||||
expect(content).toContain("(Kennwort)");
|
||||
expect(content).toContain("(FALKE 7)");
|
||||
expect(content).toContain("(Plan 1/1)");
|
||||
});
|
||||
|
||||
it("anonyme Abgabe: keine Büro-/Autor-Angaben, Info nur mit Kennwort, kein jsPDF-Producer", async () => {
|
||||
const p = poster({ competition: { anonymous: true, keyword: "FALKE 7" } });
|
||||
const doc = await buildPagesPdf(p, layoutPages(p, ["l1"]));
|
||||
const bytes = pdfBytes(p, doc!);
|
||||
const info = pdfInfoText(bytes);
|
||||
expect(info).toContain("/Title (FALKE 7)");
|
||||
expect(info).not.toMatch(/jsPDF/);
|
||||
expect(info).not.toContain("/Author");
|
||||
expect(info).not.toContain("/Creator");
|
||||
expect(info).toContain("D:20000101000000");
|
||||
const all = latin1(bytes) + streamsText(bytes);
|
||||
expect(all).not.toContain("Büro Muster");
|
||||
expect(all).not.toContain("Maria Muster");
|
||||
expect(all).not.toContain("Haus Muster");
|
||||
expect(all).toContain("(FALKE 7)");
|
||||
});
|
||||
|
||||
it("nicht anonym: Projektname im Titel, Bearbeiter im Info-Wörterbuch", async () => {
|
||||
const p = poster();
|
||||
const doc = await buildPagesPdf(p, layoutPages(p, ["l1"]));
|
||||
const info = pdfInfoText(pdfBytes(p, doc!));
|
||||
expect(info).toContain("/Title (Haus Muster)");
|
||||
expect(info).toContain("Maria Muster");
|
||||
});
|
||||
});
|
||||
+77
-1
@@ -20,6 +20,9 @@ import { generatePlan, type Plan } from "../plan/generatePlan";
|
||||
import { snapshotMono, snapshotOverrideRuleIds, snapshotTemplate, viewportLevelPlan } from "../plan/viewportPlan";
|
||||
import { planToPrintSvg } from "./planToPrintSvg";
|
||||
import { drawTablesPdf, sheetTables } from "./sheetTable";
|
||||
import { applyPdfInfo, finishPdfBytes } from "./pdfInfo";
|
||||
import { imageGeometry } from "../model/layoutImages";
|
||||
import { posterHeaderItems, viewportScaleLabel } from "../model/posterTemplates";
|
||||
import { collectVisibleCodes } from "../model/types";
|
||||
import {
|
||||
effectiveSheetSizeMm,
|
||||
@@ -90,6 +93,9 @@ function drawTitleBlock(
|
||||
doc.text(`${tb.date} · ${fmt}`, x + boxW - 3, y + boxH - 2.4, { align: "right" });
|
||||
}
|
||||
|
||||
/** Schrifthöhe in mm → pt (jsPDF misst Schriftgrössen in pt). */
|
||||
const MM_TO_PT = 72 / 25.4;
|
||||
|
||||
function clip(s: string, max: number): string {
|
||||
return s.length > max ? s.slice(0, max - 1) + "…" : s;
|
||||
}
|
||||
@@ -149,6 +155,55 @@ function inLayer(ctx: PageCtx, name: string, fn: () => void | Promise<void>): Pr
|
||||
return ctx.layers ? ctx.layers.run(name, fn) : fn();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bilder des Blatts ([208]): das Original unverändert eingebettet (JPEG ohne Neukompression), auf den Rahmen
|
||||
* geklippt; mit Zuschnitt liegt das ganze Bild verschoben/vergrössert dahinter, sichtbar ist nur der Rahmen.
|
||||
*/
|
||||
function drawImagesPdf(doc: jsPDF, layout: Layout): void {
|
||||
for (const img of layout.images ?? []) {
|
||||
const m = /^data:image\/(png|jpeg);base64,/.exec(img.src);
|
||||
if (!m || img.widthMm <= 0 || img.heightMm <= 0) continue;
|
||||
const g = imageGeometry(img);
|
||||
doc.saveGraphicsState();
|
||||
doc.rect(g.clip.x, g.clip.y, g.clip.w, g.clip.h, null);
|
||||
doc.clip();
|
||||
doc.discardPath();
|
||||
try {
|
||||
doc.addImage(img.src, m[1] === "png" ? "PNG" : "JPEG", g.draw.x, g.draw.y, g.draw.w, g.draw.h, img.id, "NONE");
|
||||
} finally {
|
||||
doc.restoreGraphicsState();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Massstabsangabe unter jedem Viewport ([208], Master `viewportScaleLabels`). */
|
||||
function drawScaleLabelsPdf(doc: jsPDF, project: Project, layout: Layout, sheet: { w: number; h: number }, scaleOverride?: number): void {
|
||||
doc.setTextColor(17, 17, 17);
|
||||
doc.setFont("helvetica", "normal");
|
||||
for (const vp of layout.viewports) {
|
||||
const l = viewportScaleLabel(project, vp, sheet, scaleOverride);
|
||||
if (!l) continue;
|
||||
doc.setFontSize(l.sizeMm * MM_TO_PT);
|
||||
doc.text(l.text, l.x, l.y);
|
||||
}
|
||||
}
|
||||
|
||||
/** Plakat-Kopfzeile ([208]): Band, Kennwort-Feld, Titel, „Plan x/n". */
|
||||
function drawPosterHeaderPdf(doc: jsPDF, project: Project, layout: Layout, master: MasterLayout, sheet: { w: number; h: number }): void {
|
||||
doc.setDrawColor(17, 17, 17);
|
||||
doc.setTextColor(17, 17, 17);
|
||||
for (const it of posterHeaderItems(project, layout, master, sheet)) {
|
||||
if (it.kind === "rect") {
|
||||
doc.setLineWidth(it.stroke);
|
||||
doc.rect(it.x, it.y, it.w, it.h);
|
||||
} else {
|
||||
doc.setFont("helvetica", it.bold ? "bold" : "normal");
|
||||
doc.setFontSize(it.sizeMm * MM_TO_PT);
|
||||
doc.text(it.text, it.x, it.y, { align: it.align });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Zeichnet die Viewports + Master-Elemente EINER Seite in das jsPDF-Dokument. */
|
||||
async function renderPage(
|
||||
doc: jsPDF,
|
||||
@@ -196,6 +251,18 @@ async function renderPage(
|
||||
}
|
||||
}
|
||||
|
||||
// Bilder ([208]): Renderings, Fotos — über den Viewports, unter Legenden und Schriftfeld.
|
||||
try {
|
||||
await inLayer(ctx, t("pdfLayers.images"), () => drawImagesPdf(doc, layout));
|
||||
} catch {
|
||||
// Ein Bild, das nicht einbettet, darf die Seite nicht killen.
|
||||
}
|
||||
|
||||
// Massstab je Viewport ([208]).
|
||||
if (master?.viewportScaleLabels) {
|
||||
await inLayer(ctx, t("pdfLayers.frame"), () => drawScaleLabelsPdf(doc, project, layout, { w: widthMm, h: heightMm }, ctx.scaleOverride));
|
||||
}
|
||||
|
||||
// Legenden ([82]): live aus den Viewports (oder Handauswahl), Muster vom Kern-Schraffurgenerator.
|
||||
for (const lg of layout.legends ?? []) {
|
||||
try {
|
||||
@@ -219,6 +286,7 @@ async function renderPage(
|
||||
}
|
||||
const tb = resolveTitleBlock(project, layout, master);
|
||||
drawTitleBlock(doc, widthMm, heightMm, tb, layout.paper, layout.orientation, ctx.includeRevision);
|
||||
if (master.posterHeader) drawPosterHeaderPdf(doc, project, layout, master, { w: widthMm, h: heightMm });
|
||||
});
|
||||
}
|
||||
|
||||
@@ -259,6 +327,9 @@ export async function buildPagesPdf(project: Project, pages: FolderPdfPage[], op
|
||||
|
||||
const first = sizeOf(pages[0]);
|
||||
const doc = new jsPDF({ unit: "mm", format: [first.w, first.h], orientation: orientOf(first), compress: true });
|
||||
// Info-Wörterbuch: anonym nur das Kennwort ([208]); sonst Projektname und Bearbeiter des ersten Blatts.
|
||||
const firstMaster = findMaster(project, pages[0].layout);
|
||||
applyPdfInfo(doc, project, firstMaster ? resolveTitleBlock(project, pages[0].layout, firstMaster).author : undefined);
|
||||
const ctx: PageCtx = {
|
||||
layers: opts.layers ? enablePdfLayers(doc) : undefined,
|
||||
scaleOverride: opts.scaleOverride && opts.scaleOverride > 0 ? opts.scaleOverride : undefined,
|
||||
@@ -301,5 +372,10 @@ export async function buildFolderPdf(project: Project, folderId: string): Promis
|
||||
export async function folderPdfBytes(project: Project, folderId: string): Promise<Uint8Array | null> {
|
||||
const doc = await buildFolderPdf(project, folderId);
|
||||
if (!doc) return null;
|
||||
return new Uint8Array(doc.output("arraybuffer"));
|
||||
return pdfBytes(project, doc);
|
||||
}
|
||||
|
||||
/** Fertige PDF-Bytes eines Dokuments; bei anonymer Abgabe ohne Erzeuger-/Datumsangaben ([208]). */
|
||||
export function pdfBytes(project: Project, doc: jsPDF): Uint8Array {
|
||||
return finishPdfBytes(project, new Uint8Array(doc.output("arraybuffer")));
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// PDF-Metadaten ([208]): Titel/Autor/Ersteller des Info-Wörterbuchs. Bei anonymer Wettbewerbs-Abgabe
|
||||
// (`Project.competition`) enthält das PDF nur das Kennwort als Titel — keine Büro-, Autor- oder Programmangaben:
|
||||
// jsPDF schreibt `/Producer (jsPDF x.y.z)` und `/CreationDate` immer selbst, darum wird die fertige Datei
|
||||
// längengleich nachbearbeitet (Xref-Offsets bleiben gültig).
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch.
|
||||
|
||||
import type { jsPDF } from "jspdf";
|
||||
import type { Project } from "../model/types";
|
||||
|
||||
/** Ist die Abgabe anonym? */
|
||||
export function isAnonymous(project: Pick<Project, "competition">): boolean {
|
||||
return project.competition?.anonymous === true;
|
||||
}
|
||||
|
||||
/** Kennwort der Abgabe (getrimmt, leer ohne Wettbewerb). */
|
||||
export function competitionKeyword(project: Pick<Project, "competition">): string {
|
||||
return (project.competition?.keyword ?? "").trim();
|
||||
}
|
||||
|
||||
/** Projektname für Schriftfelder und Dateinamen der Exporte: bei anonymer Abgabe das Kennwort. */
|
||||
export function exportProjectName(project: Pick<Project, "name" | "competition">): string {
|
||||
return isAnonymous(project) ? competitionKeyword(project) : (project.name ?? "");
|
||||
}
|
||||
|
||||
/** Info-Felder, die ins PDF gehören: anonym nur das Kennwort als Titel, sonst Projektname und Autor des Titelblocks. */
|
||||
export function pdfInfoFields(project: Pick<Project, "name" | "competition">, author?: string): { title: string; author: string; subject: string; keywords: string; creator: string } {
|
||||
if (isAnonymous(project)) return { title: competitionKeyword(project), author: "", subject: "", keywords: "", creator: "" };
|
||||
return { title: project.name ?? "", author: author ?? "", subject: "", keywords: "", creator: "Dossier" };
|
||||
}
|
||||
|
||||
/** Setzt die Info-Felder auf dem jsPDF-Dokument. */
|
||||
export function applyPdfInfo(doc: jsPDF, project: Pick<Project, "name" | "competition">, author?: string): void {
|
||||
doc.setProperties(pdfInfoFields(project, author));
|
||||
}
|
||||
|
||||
/**
|
||||
* Anonymisiert die fertigen PDF-Bytes: `/Producer (…)` wird durch Leerzeichen gleicher Länge ersetzt und das
|
||||
* Datum in `/CreationDate` auf einen festen Wert gesetzt. Gilt nur für anonyme Abgaben; sonst unverändert.
|
||||
*/
|
||||
export function finishPdfBytes(project: Pick<Project, "competition">, bytes: Uint8Array): Uint8Array {
|
||||
return isAnonymous(project) ? neutralizePdfInfo(bytes) : bytes;
|
||||
}
|
||||
|
||||
/** Letzte Fundstelle des ASCII-Musters in den Bytes (-1: keine). */
|
||||
function lastIndexOfAscii(bytes: Uint8Array, pattern: string): number {
|
||||
const n = pattern.length;
|
||||
outer: for (let i = bytes.length - n; i >= 0; i--) {
|
||||
for (let j = 0; j < n; j++) if (bytes[i + j] !== pattern.charCodeAt(j)) continue outer;
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Längengleiche Ersetzung der Erzeuger- und Datumsangabe im Info-Wörterbuch (das letzte im Text, nahe dem Ende). */
|
||||
export function neutralizePdfInfo(bytes: Uint8Array): Uint8Array {
|
||||
// Byteweise, nicht über TextDecoder: "latin1" ist dort windows-1252 und verfälschte Binärdaten.
|
||||
const out = new Uint8Array(bytes);
|
||||
const blank = (key: string, fn: (v: string) => string) => {
|
||||
const at = lastIndexOfAscii(out, `${key} (`);
|
||||
if (at < 0) return;
|
||||
const from = at + key.length + 2;
|
||||
let to = from;
|
||||
while (to < out.length && out[to] !== 0x29 /* ) */) to++;
|
||||
if (to >= out.length) return;
|
||||
let v = "";
|
||||
for (let i = from; i < to; i++) v += String.fromCharCode(out[i]);
|
||||
const next = fn(v);
|
||||
if (next.length !== v.length) return;
|
||||
for (let i = 0; i < next.length; i++) out[from + i] = next.charCodeAt(i);
|
||||
};
|
||||
blank("/Producer", (v) => " ".repeat(v.length));
|
||||
blank("/CreationDate", (v) => v.replace(/^D:\d{14}/, "D:20000101000000"));
|
||||
blank("/ModDate", (v) => v.replace(/^D:\d{14}/, "D:20000101000000"));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Hilfsfunktion für Tests: das Info-Wörterbuch als Text. */
|
||||
export function pdfInfoText(bytes: Uint8Array): string {
|
||||
const at = lastIndexOfAscii(bytes, "/Producer");
|
||||
if (at < 0) return "";
|
||||
const start = Math.max(0, at - 4);
|
||||
let s = "";
|
||||
for (let i = start; i < Math.min(bytes.length, at + 400); i++) s += String.fromCharCode(bytes[i]);
|
||||
const end = s.indexOf(">>");
|
||||
return end < 0 ? s : s.slice(0, end + 2);
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import { collectVisibleCodes } from "../model/types";
|
||||
import { generatePlan } from "../plan/generatePlan";
|
||||
import { sheetLevelOf } from "../model/layoutModel";
|
||||
import { legendDrawings, legendEntries } from "../analysis/legend";
|
||||
import { buildPagesPdf, layoutPages } from "./layoutPdf";
|
||||
import { buildPagesPdf, layoutPages, pdfBytes } from "./layoutPdf";
|
||||
import { buildPlanDwg, buildPlanDxfBinary } from "./exportDxf";
|
||||
import { loadFileio } from "../engine/fileioWasm";
|
||||
import { withDocument } from "../core/document";
|
||||
@@ -97,7 +97,7 @@ async function publishFiles(shown: Project, set: PublishSet, plan: PublishPlan):
|
||||
paperOverride: plan.paperOverride,
|
||||
includeRevision: plan.includeRevision,
|
||||
});
|
||||
if (doc) out.push({ fileName: f.fileName, bytes: new Uint8Array(doc.output("arraybuffer")), mime: "application/pdf" });
|
||||
if (doc) out.push({ fileName: f.fileName, bytes: pdfBytes(shown, doc), mime: "application/pdf" });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -85,9 +85,11 @@ export function planPublish(project: Project, set: PublishSet, today: string): P
|
||||
const revision = includeRevision ? (bump ? nextRevision(l.revision) : (l.revision ?? "")) : "";
|
||||
return { layoutId: l.id, number: tb.planNumber, name: l.name, revision };
|
||||
});
|
||||
// Anonyme Abgabe ([208]): Dateinamen tragen das Kennwort statt Projektnummer und Projektname.
|
||||
const anon = project.competition?.anonymous === true;
|
||||
const base = {
|
||||
Projektnummer: project.projectNumber ?? "",
|
||||
Projekt: project.name ?? "",
|
||||
Projektnummer: anon ? "" : (project.projectNumber ?? ""),
|
||||
Projekt: anon ? (project.competition?.keyword ?? "").trim() : (project.name ?? ""),
|
||||
Datum: today,
|
||||
Satz: set.name,
|
||||
};
|
||||
|
||||
@@ -3955,6 +3955,35 @@ export const de = {
|
||||
"settings.section.rendering": "Rendering",
|
||||
"settings.blenderPath": "Blender-Programmdatei",
|
||||
"settings.blenderPath.hint": "Leer: Blender wird im PATH und an den üblichen Orten gesucht (macOS: /Applications/Blender.app).",
|
||||
// [208] Wettbewerbs-Abgabe: Bilder auf Blättern, Plakat-Vorlagen, Anonymität
|
||||
"sheetImage.title": "Bild",
|
||||
"sheetImage.add": "Bild",
|
||||
"sheetImage.width": "Breite mm",
|
||||
"sheetImage.dpi": "{dpi} dpi auf dem Blatt",
|
||||
"sheetImage.lowDpi": "niedrige Auflösung",
|
||||
"sheetImage.crop": "Zuschnitt",
|
||||
"sheetImage.crop.left": "Links",
|
||||
"sheetImage.crop.right": "Rechts",
|
||||
"sheetImage.crop.top": "Oben",
|
||||
"sheetImage.crop.bottom": "Unten",
|
||||
"sheetImage.cropReset": "Zuschnitt aufheben",
|
||||
"sheetImage.remove": "Bild entfernen",
|
||||
"sheetImage.invalid": "Nur PNG- und JPEG-Bilder bis 40 MB lassen sich einsetzen.",
|
||||
"pdfLayers.images": "Bilder",
|
||||
"poster.template.name": "Plakat {format} {orientation}",
|
||||
"poster.header.keyword": "Kennwort",
|
||||
"poster.header.plan": "Plan {x}/{n}",
|
||||
"layouts.newLayout.poster": "Plakat-Vorlage (Wettbewerb)",
|
||||
"layouts.newLayout.posterHint": "Gestaltungsraster als Hilfslinien, Kopfzeile mit Kennwort und „Plan x/n“, Massstab unter jedem Viewport.",
|
||||
"publish.competition.anonymous": "Wettbewerb (anonym)",
|
||||
"publish.competition.keyword": "Kennwort",
|
||||
"publish.competition.hint": "Plankopf, PDF-Titel und Dateinamen zeigen nur das Kennwort; kein Büro- oder Autorname, keine Programm- und Datumsangaben im PDF.",
|
||||
"publish.wbw.add": "WBW-Abgabe anlegen",
|
||||
"publish.wbw.name": "WBW-Abgabe",
|
||||
"render.toLayout": "Ins Layout einsetzen",
|
||||
"render.toLayout.target": "Blatt",
|
||||
"render.toLayout.none": "Noch kein Layout-Blatt vorhanden: zuerst ein Blatt anlegen.",
|
||||
"render.toLayout.done": "Rendering ins Blatt „{name}“ eingesetzt.",
|
||||
} as const;
|
||||
|
||||
export type TranslationKey = keyof typeof de;
|
||||
@@ -3941,4 +3941,33 @@ export const en: Record<TranslationKey, string> = {
|
||||
"settings.section.rendering": "Rendering",
|
||||
"settings.blenderPath": "Blender executable",
|
||||
"settings.blenderPath.hint": "Empty: Blender is searched in PATH and the usual places (macOS: /Applications/Blender.app).",
|
||||
// [208] Competition submission: images on sheets, poster templates, anonymity
|
||||
"sheetImage.title": "Image",
|
||||
"sheetImage.add": "Image",
|
||||
"sheetImage.width": "Width mm",
|
||||
"sheetImage.dpi": "{dpi} dpi on the sheet",
|
||||
"sheetImage.lowDpi": "low resolution",
|
||||
"sheetImage.crop": "Crop",
|
||||
"sheetImage.crop.left": "Left",
|
||||
"sheetImage.crop.right": "Right",
|
||||
"sheetImage.crop.top": "Top",
|
||||
"sheetImage.crop.bottom": "Bottom",
|
||||
"sheetImage.cropReset": "Reset crop",
|
||||
"sheetImage.remove": "Remove image",
|
||||
"sheetImage.invalid": "Only PNG and JPEG images up to 40 MB can be placed.",
|
||||
"pdfLayers.images": "Images",
|
||||
"poster.template.name": "Poster {format} {orientation}",
|
||||
"poster.header.keyword": "Keyword",
|
||||
"poster.header.plan": "Plan {x}/{n}",
|
||||
"layouts.newLayout.poster": "Poster template (competition)",
|
||||
"layouts.newLayout.posterHint": "Layout grid as guides, header with keyword and \"Plan x/n\", scale under every viewport.",
|
||||
"publish.competition.anonymous": "Competition (anonymous)",
|
||||
"publish.competition.keyword": "Keyword",
|
||||
"publish.competition.hint": "Title block, PDF title and file names show only the keyword; no office or author name, no program or date details in the PDF.",
|
||||
"publish.wbw.add": "Create competition set",
|
||||
"publish.wbw.name": "Competition submission",
|
||||
"render.toLayout": "Place in layout",
|
||||
"render.toLayout.target": "Sheet",
|
||||
"render.toLayout.none": "No layout sheet yet: create a sheet first.",
|
||||
"render.toLayout.done": "Rendering placed on sheet \"{name}\".",
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
// Bilder auf Layout-Blättern ([208]): Einlesen (Format am Dateikopf), Seitenverhältnis, Zuschnitt, Listen-Änderungen.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Layout } from "./types";
|
||||
import {
|
||||
addImage,
|
||||
bytesToDataUrl,
|
||||
createLayoutImage,
|
||||
cropImage,
|
||||
dataUrlToBytes,
|
||||
imageAspect,
|
||||
imageGeometry,
|
||||
imageInfo,
|
||||
patchImage,
|
||||
removeImage,
|
||||
resizeImageWidth,
|
||||
} from "./layoutImages";
|
||||
import { JPEG_64X48, PNG_40X30, PNG_40X30_ALPHA } from "./layoutImages.testing";
|
||||
|
||||
const A1 = { w: 841, h: 594 };
|
||||
const layout = (): Layout => ({ id: "l1", name: "Blatt", paper: "a1", orientation: "landscape", viewports: [] });
|
||||
|
||||
describe("Blatt-Bilder", () => {
|
||||
it("liest Format und Pixelgrösse aus dem Dateikopf", () => {
|
||||
expect(imageInfo(bytesToDataUrl(JPEG_64X48, "image/jpeg"))).toEqual({ mime: "image/jpeg", width: 64, height: 48 });
|
||||
expect(imageInfo(bytesToDataUrl(PNG_40X30, "image/png"))).toEqual({ mime: "image/png", width: 40, height: 30 });
|
||||
expect(imageInfo(bytesToDataUrl(PNG_40X30_ALPHA, "image/png"))?.width).toBe(40);
|
||||
expect(imageInfo("data:image/gif;base64,R0lGODlhAQABAAAAACw=")).toBeNull();
|
||||
});
|
||||
|
||||
it("Data-URL und Bytes sind verlustfrei austauschbar", () => {
|
||||
expect(dataUrlToBytes(bytesToDataUrl(JPEG_64X48, "image/jpeg"))).toEqual(JPEG_64X48);
|
||||
});
|
||||
|
||||
it("neues Bild liegt mittig, im Seitenverhältnis, und die Dateiendung zählt nicht", () => {
|
||||
// JPEG-Bytes mit PNG-Hinweis: der Kopf entscheidet
|
||||
const img = createLayoutImage("i1", "foto.png", JPEG_64X48, A1, "image/png")!;
|
||||
expect(img.src.startsWith("data:image/jpeg;base64,")).toBe(true);
|
||||
expect([img.pixelWidth, img.pixelHeight]).toEqual([64, 48]);
|
||||
expect(img.widthMm / img.heightMm).toBeCloseTo(64 / 48, 1);
|
||||
expect(img.widthMm).toBeLessThanOrEqual(841 * 0.6 + 0.1);
|
||||
expect(img.xMm + img.widthMm / 2).toBeCloseTo(420.5, 0);
|
||||
expect(img.yMm + img.heightMm / 2).toBeCloseTo(297, 0);
|
||||
});
|
||||
|
||||
it("weist Unbrauchbares ab", () => {
|
||||
expect(createLayoutImage("i", "x", new Uint8Array([1, 2, 3]), A1)).toBeNull();
|
||||
expect(createLayoutImage("i", "x", new Uint8Array(), A1)).toBeNull();
|
||||
});
|
||||
|
||||
it("Breite ändern hält das Seitenverhältnis, Zuschnitt ändert es", () => {
|
||||
const img = createLayoutImage("i1", "a", PNG_40X30, A1)!;
|
||||
const r = resizeImageWidth(img, 200);
|
||||
expect(r).toEqual({ widthMm: 200, heightMm: 150 });
|
||||
// linke Hälfte: 20×30 px → Verhältnis 2/3
|
||||
const c = cropImage({ ...img, ...r }, { x: 0, y: 0, w: 0.5, h: 1 });
|
||||
expect(c.widthMm).toBe(200);
|
||||
expect(c.heightMm).toBe(300);
|
||||
expect(imageAspect({ ...img, crop: c.crop })).toBeCloseTo(2 / 3, 6);
|
||||
});
|
||||
|
||||
it("Zeichen-Rechteck füllt mit Zuschnitt den Rahmen; dpi folgt der Grösse", () => {
|
||||
const img = { ...createLayoutImage("i1", "a", PNG_40X30, A1)!, xMm: 100, yMm: 50, widthMm: 100, heightMm: 75 };
|
||||
const g = imageGeometry(img);
|
||||
expect(g.draw).toEqual(g.clip);
|
||||
expect(g.dpi).toBeCloseTo(40 / (100 / 25.4), 6);
|
||||
const c = imageGeometry({ ...img, crop: { x: 0.5, y: 0, w: 0.5, h: 1 }, heightMm: 150 });
|
||||
expect(c.draw.w).toBe(200);
|
||||
expect(c.draw.x).toBe(0);
|
||||
});
|
||||
|
||||
it("hängt an, ändert und entfernt Bilder am Blatt", () => {
|
||||
const img = createLayoutImage("i1", "a", PNG_40X30, A1)!;
|
||||
let l = addImage(layout(), img);
|
||||
expect(l.images).toHaveLength(1);
|
||||
l = patchImage(l, "i1", { xMm: 5, crop: { x: 0.1, y: 0.1, w: 0.5, h: 0.5 } });
|
||||
expect(l.images![0].xMm).toBe(5);
|
||||
l = patchImage(l, "i1", { crop: undefined });
|
||||
expect("crop" in l.images![0]).toBe(false);
|
||||
expect(removeImage(l, "i1").images).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
// Testbilder für Blatt-Bilder ([208]): kleine echte Dateien (JPEG 64×48, PNG 40×30 RGB, PNG 40×30 RGBA), als Base64.
|
||||
|
||||
const b64 = (s: string): Uint8Array => Uint8Array.from(Buffer.from(s, "base64"));
|
||||
|
||||
export const JPEG_64X48 = b64("/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAwAEADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD57itParsVp7VqRWntV2K09q+1qYk4cLjDLhtOnFXIrT2rVitParsVp7VxTxJ9JhcYZUNp7VditPatSK09quxWntXHPEn0uFxhlxWntVyK09q1YrT2q7Fae1cdTEn0uFxhw8Vp7VcitPatWK09quw2ntWk8SfzRhcYZUVp7VditPatSK09quxWntXHUxJ9LhcYZcNp7VcitPatWK09quxWntXHUxJ9JhcYZUVp7VditPatSK09quxWntXFPEn0uFxhw8Vp7VditPatWK09quRWntWtTEn804XGGXFae1XYrT2rUitParsNp7VxzxJ9JhcYZUVp7VditPatWK09quRWntXHPEn0uFxhlw2ntVyK09q1YrT2q7Fae1cVTEn0mFxh/9k=");
|
||||
export const PNG_40X30 = b64("iVBORw0KGgoAAAANSUhEUgAAACgAAAAeCAIAAADRv8uKAAAASklEQVR4nO3PMQ6AMAzAQCNVBX7dp7MiZuQuzpRkse6ANWHCCe/lc/7+H1xsmcG9K5xYCyfWwom1cGItnFgLJ9bCibVwYi2cWJoHuaEC5Ls5JT8AAAAASUVORK5CYII=");
|
||||
export const PNG_40X30_ALPHA = b64("iVBORw0KGgoAAAANSUhEUgAAACgAAAAeCAYAAABe3VzdAAAAWUlEQVR4nO3QMQ6AIBAF0U9CUG/NzbWxoDA2kwDFvGbJbkOmJP1uSVqS453j+2s3815zZms11+ov/LMgZUHKgpQFKQtSFqQsSFmQsiBlQcqClAUpC1LbF3wAq2UD44jvAb0AAAAASUVORK5CYII=");
|
||||
@@ -0,0 +1,137 @@
|
||||
// Bilder auf Layout-Blättern ([208]): Renderings, Fotos, Luftbilder als PNG/JPEG. Im Projekt liegt das Bild als
|
||||
// Data-URL (`LayoutImage.src`) — derselbe Weg wie bei `ContextImage` (Luftbild als Unterlage). Rechnung
|
||||
// (Dateikopf lesen, Seitenverhältnis, Zeichen-/Klipp-Rechteck mit Zuschnitt, Startgrösse) im Kern
|
||||
// (`src-tauri/core/src/layout_image.rs`); hier nur die dünne Fassade, Listen-Änderungen am Layout und das Einlesen.
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch.
|
||||
|
||||
import type { Layout, LayoutImage } from "./types";
|
||||
import { core } from "../engine/coreWasm";
|
||||
|
||||
export interface ImageInfo {
|
||||
mime: string;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** Rechteck in Papier-mm. */
|
||||
export interface RectXYWH {
|
||||
x: number;
|
||||
y: number;
|
||||
w: number;
|
||||
h: number;
|
||||
}
|
||||
|
||||
/** Mehr als 40 MB Bild in einem Projekt sprengt Speichern und Autosave. */
|
||||
export const MAX_IMAGE_BYTES = 40 * 1024 * 1024;
|
||||
|
||||
function call<T>(name: string, arg: unknown): T | null {
|
||||
const out = core().layout_call(name, JSON.stringify(arg));
|
||||
return out === "" ? null : (JSON.parse(out) as T);
|
||||
}
|
||||
|
||||
/** Format und Pixelgrösse einer PNG-/JPEG-Data-URL; `null` bei anderen Formaten oder kaputten Daten. */
|
||||
export function imageInfo(src: string): ImageInfo | null {
|
||||
return call<ImageInfo>("imageInfo", { src });
|
||||
}
|
||||
|
||||
/** Seitenverhältnis (Breite/Höhe) des gezeigten Ausschnitts, Zuschnitt eingerechnet. */
|
||||
export function imageAspect(img: Pick<LayoutImage, "pixelWidth" | "pixelHeight" | "crop">): number {
|
||||
return call<number>("imageAspect", img) ?? 1;
|
||||
}
|
||||
|
||||
/** Klipp-Rahmen, Zeichen-Rechteck des GANZEN Originals und Auflösung (dpi) des Bilds auf dem Blatt. */
|
||||
export function imageGeometry(img: LayoutImage): { clip: RectXYWH; draw: RectXYWH; dpi: number } {
|
||||
const g = call<{ clip: RectXYWH; draw: RectXYWH; dpi: number }>("imageGeometry", img);
|
||||
const r = { x: img.xMm, y: img.yMm, w: img.widthMm, h: img.heightMm };
|
||||
return g ?? { clip: r, draw: r, dpi: 0 };
|
||||
}
|
||||
|
||||
/** Startrahmen eines neuen Bilds auf einem Blatt `sheetW`×`sheetH` mm: Seitenverhältnis gehalten, mittig. */
|
||||
export function initialImageFrame(pixelWidth: number, pixelHeight: number, sheetW: number, sheetH: number): RectXYWH {
|
||||
return call<RectXYWH>("imageInitial", { pixelWidth, pixelHeight, sheetW, sheetH }) ?? { x: 0, y: 0, w: sheetW / 2, h: sheetH / 2 };
|
||||
}
|
||||
|
||||
/** Bytes → Data-URL (in Stücken, damit grosse Bilder keinen Stapel sprengen). */
|
||||
export function bytesToDataUrl(bytes: Uint8Array, mime: string): string {
|
||||
let bin = "";
|
||||
const chunk = 0x8000;
|
||||
for (let i = 0; i < bytes.length; i += chunk) bin += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
||||
return `data:${mime};base64,${btoa(bin)}`;
|
||||
}
|
||||
|
||||
/** Data-URL → Bytes (für den PDF-Export und „Speichern unter"). */
|
||||
export function dataUrlToBytes(src: string): Uint8Array {
|
||||
const bin = atob(src.slice(src.indexOf(",") + 1));
|
||||
const out = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Neues Blatt-Bild aus Dateibytes: erkennt PNG/JPEG am Kopf (nicht am Dateinamen), legt es mittig und im
|
||||
* Seitenverhältnis auf das Blatt. `null`, wenn es weder PNG noch JPEG ist oder zu gross.
|
||||
*/
|
||||
export function createLayoutImage(
|
||||
id: string,
|
||||
name: string,
|
||||
bytes: Uint8Array,
|
||||
sheet: { w: number; h: number },
|
||||
mimeHint = "image/png",
|
||||
): LayoutImage | null {
|
||||
if (bytes.length === 0 || bytes.length > MAX_IMAGE_BYTES) return null;
|
||||
const src = bytesToDataUrl(bytes, mimeHint);
|
||||
const info = imageInfo(src);
|
||||
if (!info) return null;
|
||||
// Der Kopf entscheidet über das Format, nicht der Hinweis (umbenannte Dateien).
|
||||
const real = info.mime === mimeHint ? src : bytesToDataUrl(bytes, info.mime);
|
||||
const f = initialImageFrame(info.width, info.height, sheet.w, sheet.h);
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
src: real,
|
||||
xMm: round1(f.x),
|
||||
yMm: round1(f.y),
|
||||
widthMm: round1(f.w),
|
||||
heightMm: round1(f.h),
|
||||
pixelWidth: info.width,
|
||||
pixelHeight: info.height,
|
||||
};
|
||||
}
|
||||
|
||||
function round1(v: number): number {
|
||||
return Math.round(v * 10) / 10;
|
||||
}
|
||||
|
||||
/** Breite ändern, Höhe folgt dem Seitenverhältnis des Ausschnitts. */
|
||||
export function resizeImageWidth(img: LayoutImage, widthMm: number): Pick<LayoutImage, "widthMm" | "heightMm"> {
|
||||
const w = Math.max(5, widthMm);
|
||||
return { widthMm: round1(w), heightMm: round1(w / imageAspect(img)) };
|
||||
}
|
||||
|
||||
/** Neuer Zuschnitt (Anteile 0..1): der Rahmen behält seine Breite, die Höhe folgt dem neuen Seitenverhältnis. */
|
||||
export function cropImage(img: LayoutImage, crop: LayoutImage["crop"]): Pick<LayoutImage, "crop" | "widthMm" | "heightMm"> {
|
||||
const next = { ...img, crop };
|
||||
return { crop, widthMm: img.widthMm, heightMm: round1(img.widthMm / imageAspect(next)) };
|
||||
}
|
||||
|
||||
/** Bild an das Blatt anhängen. */
|
||||
export function addImage(layout: Layout, image: LayoutImage): Layout {
|
||||
return { ...layout, images: [...(layout.images ?? []), image] };
|
||||
}
|
||||
|
||||
export function removeImage(layout: Layout, imageId: string): Layout {
|
||||
return { ...layout, images: (layout.images ?? []).filter((i) => i.id !== imageId) };
|
||||
}
|
||||
|
||||
export function patchImage(layout: Layout, imageId: string, patch: Partial<Omit<LayoutImage, "id">>): Layout {
|
||||
return {
|
||||
...layout,
|
||||
images: (layout.images ?? []).map((i) => {
|
||||
if (i.id !== imageId) return i;
|
||||
const next = { ...i, ...patch };
|
||||
for (const k of Object.keys(patch) as (keyof typeof patch)[]) if (patch[k] === undefined) delete (next as Record<string, unknown>)[k];
|
||||
return next;
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -519,6 +519,13 @@ export interface ResolvedTitleBlock {
|
||||
planNumber: string;
|
||||
/** Revisionsindex des Blatts (`Layout.revision`, [79]); fehlt = keiner. */
|
||||
revision?: string;
|
||||
/** Kennwort der Abgabe (`Project.competition.keyword`, [208]); leer ohne Wettbewerb. */
|
||||
keyword: string;
|
||||
/** Anonyme Abgabe ([208]): `projectName` ist das Kennwort, `author` leer. */
|
||||
anonymous: boolean;
|
||||
/** „Plan x/n" ([208]): Stelle des Blatts und Anzahl der Blätter, die mitzählen (Kern `resolve_title_block`). */
|
||||
planIndex: number;
|
||||
planCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -536,7 +543,7 @@ export function resolveTitleBlock(
|
||||
today: string = new Date().toISOString().slice(0, 10),
|
||||
): ResolvedTitleBlock {
|
||||
const arg = {
|
||||
layout: { id: layout.id, name: layout.name, planNumber: layout.planNumber, viewports: (layout.viewports ?? []).slice(0, 1) },
|
||||
layout: { id: layout.id, name: layout.name, planNumber: layout.planNumber, masterId: layout.masterId, viewports: (layout.viewports ?? []).slice(0, 1) },
|
||||
master: master ? { titleBlock: master.titleBlock } : null,
|
||||
today,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// [208] Plakat-Vorlagen: Master mit Raster, Kopfzeile, Massstabsangabe; Blatt „aus Vorlage"; anonymer Plankopf.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sampleProject } from "./sampleProject";
|
||||
import { buildComplexSampleProject } from "./sampleProjectComplex";
|
||||
import type { Layout, Project } from "./types";
|
||||
import { effectiveSheetSizeMm, findMaster, resolveTitleBlock } from "./layoutModel";
|
||||
import { createPosterMaster, findPosterMaster, POSTER_TEMPLATES, posterHeaderItems, posterMetrics, posterTemplate, viewportScaleLabel } from "./posterTemplates";
|
||||
import { addWbwSetOps, setCompetitionOps } from "../state/publishActions";
|
||||
import { applyOps } from "../core/ops";
|
||||
import { planPublish } from "../export/publishSet";
|
||||
import { placeImageOps } from "../state/layoutImageActions";
|
||||
import { PNG_40X30 } from "./layoutImages.testing";
|
||||
|
||||
function withPosters(competition?: Project["competition"]): Project {
|
||||
const m = createPosterMaster("m1", posterTemplate("poster-a1-landscape")!);
|
||||
const lay = (id: string, name: string): Layout => ({ id, name, paper: "a1", orientation: "landscape", masterId: "m1", viewports: [] });
|
||||
return { ...sampleProject, name: "Haus Muster", projectNumber: "2611", masterLayouts: [m], layouts: [lay("p1", "Situation"), lay("p2", "Grundrisse"), { ...lay("x", "Anderes"), masterId: undefined }], competition };
|
||||
}
|
||||
|
||||
describe("Plakat-Vorlagen", () => {
|
||||
it("A0 und A1, hoch und quer", () => {
|
||||
expect(POSTER_TEMPLATES.map((p) => p.key)).toEqual(["poster-a0-portrait", "poster-a0-landscape", "poster-a1-portrait", "poster-a1-landscape"]);
|
||||
for (const tpl of POSTER_TEMPLATES) {
|
||||
const m = createPosterMaster(`m-${tpl.key}`, tpl);
|
||||
const size = effectiveSheetSizeMm(m);
|
||||
expect(tpl.orientation === "landscape" ? size.w > size.h : size.h > size.w).toBe(true);
|
||||
expect(m.template).toBe(tpl.key);
|
||||
expect(m.posterHeader).toBe(true);
|
||||
expect(m.viewportScaleLabels).toBe(true);
|
||||
// Raster: 2 senkrechte Linien je Spalte, 4 waagrechte
|
||||
const mm = posterMetrics(size.w, size.h);
|
||||
expect(m.guides!.filter((g) => g.axis === "x")).toHaveLength(mm.columns * 2);
|
||||
expect(m.guides!.filter((g) => g.axis === "y")).toHaveLength(4);
|
||||
// alle Linien liegen im Blatt
|
||||
for (const g of m.guides!) {
|
||||
expect(g.posMm).toBeGreaterThan(0);
|
||||
expect(g.posMm).toBeLessThan(g.axis === "x" ? size.w : size.h);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("A1 quer misst 841 × 594 mm mit 6 Spalten", () => {
|
||||
const m = createPosterMaster("m", posterTemplate("poster-a1-landscape")!);
|
||||
expect(effectiveSheetSizeMm(m)).toEqual({ w: 841, h: 594 });
|
||||
expect(posterMetrics(841, 594).columns).toBe(6);
|
||||
});
|
||||
|
||||
it("findet den Master einer Vorlage im Projekt wieder", () => {
|
||||
const p = withPosters();
|
||||
expect(findPosterMaster(p, "poster-a1-landscape")?.id).toBe("m1");
|
||||
expect(findPosterMaster(p, "poster-a0-portrait")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Kopfzeile: Kennwort-Feld und „Plan x/n“ zählen nur Plakate", () => {
|
||||
const p = withPosters({ anonymous: true, keyword: "FALKE 7" });
|
||||
const lay = p.layouts![1];
|
||||
const items = posterHeaderItems(p, lay, findMaster(p, lay)!, { w: 841, h: 594 });
|
||||
const texts = items.flatMap((i) => (i.kind === "text" ? [i.text] : []));
|
||||
expect(texts).toContain("Kennwort");
|
||||
expect(texts).toContain("FALKE 7");
|
||||
expect(texts).toContain("Plan 2/2");
|
||||
// anonym: kein Projektname in der Kopfzeile
|
||||
expect(texts.some((x) => x.includes("Haus Muster"))).toBe(false);
|
||||
});
|
||||
|
||||
it("offene Abgabe zeigt den Projektnamen in der Kopfzeile", () => {
|
||||
const p = withPosters({ anonymous: false, keyword: "FALKE 7" });
|
||||
const items = posterHeaderItems(p, p.layouts![0], findMaster(p, p.layouts![0])!, { w: 841, h: 594 });
|
||||
expect(items.flatMap((i) => (i.kind === "text" ? [i.text] : []))).toContain("Haus Muster");
|
||||
});
|
||||
|
||||
it("Plankopf anonym: Kennwort statt Projektname, kein Bearbeiter", () => {
|
||||
const p = withPosters({ anonymous: true, keyword: " FALKE 7 " });
|
||||
p.masterLayouts![0].titleBlock = { projectName: "Büro AG", author: "M. Muster" };
|
||||
const tb = resolveTitleBlock(p, p.layouts![0], p.masterLayouts![0]);
|
||||
expect([tb.projectName, tb.author, tb.anonymous, tb.keyword]).toEqual(["FALKE 7", "", true, "FALKE 7"]);
|
||||
});
|
||||
|
||||
it("Massstabsangabe unter dem Viewport", () => {
|
||||
const snap = buildComplexSampleProject().viewSnapshots![0];
|
||||
const p = { ...withPosters(), viewSnapshots: [{ ...snap, scaleDenominator: 200 }] };
|
||||
const vp = { id: "v", snapshotId: snap.id, xMm: 50, yMm: 100, widthMm: 300, heightMm: 200 };
|
||||
const l = viewportScaleLabel(p, vp, { w: 841, h: 594 })!;
|
||||
expect(l.text).toBe("1:200");
|
||||
expect(l.x).toBe(50);
|
||||
expect(l.y).toBeGreaterThan(300);
|
||||
expect(viewportScaleLabel(p, { ...vp, scaleDenominator: 100 }, { w: 841, h: 594 })!.text).toBe("1:100");
|
||||
expect(viewportScaleLabel(p, { ...vp, snapshotId: "gibt-es-nicht" }, { w: 841, h: 594 })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Wettbewerb und WBW-Abgabe", () => {
|
||||
it("Einstellung anonym + Kennwort als Ops; leer entfernt das Feld", () => {
|
||||
let p = withPosters();
|
||||
p = applyOps(p, setCompetitionOps(p, { anonymous: true }));
|
||||
expect(p.competition).toEqual({ anonymous: true, keyword: "" });
|
||||
p = applyOps(p, setCompetitionOps(p, { keyword: "FALKE 7" }));
|
||||
expect(p.competition).toEqual({ anonymous: true, keyword: "FALKE 7" });
|
||||
p = applyOps(p, setCompetitionOps(p, { anonymous: false, keyword: "" }));
|
||||
expect(p.competition).toBeUndefined();
|
||||
});
|
||||
|
||||
it("Satz „WBW-Abgabe“ enthält die Plakate in Blattfolge, ein PDF, Dateiname = Kennwort", () => {
|
||||
let p = withPosters({ anonymous: true, keyword: "FALKE 7" });
|
||||
p = applyOps(p, addWbwSetOps(p, "s1"));
|
||||
const set = p.publishSets!.find((s) => s.id === "s1")!;
|
||||
expect(set.layoutIds).toEqual(["p1", "p2"]);
|
||||
expect(set.format).toBe("pdf-multi");
|
||||
const plan = planPublish(p, set, "2026-11-12");
|
||||
expect(plan.files).toHaveLength(1);
|
||||
expect(plan.files[0].layoutIds).toEqual(["p1", "p2"]);
|
||||
expect(plan.files[0].fileName).toBe("FALKE 7_WBW-Abgabe.pdf");
|
||||
expect(plan.files[0].fileName).not.toMatch(/Muster|2611/);
|
||||
});
|
||||
|
||||
it("Einzeldateien (pdf-single) tragen ebenfalls kein Projekt", () => {
|
||||
let p = withPosters({ anonymous: true, keyword: "FALKE 7" });
|
||||
p = applyOps(p, addWbwSetOps(p, "s1"));
|
||||
const set = { ...p.publishSets![0], format: "pdf-single", namePattern: "{Projektnummer}_{Projekt}_{Blattnummer}" };
|
||||
const plan = planPublish(p, set, "2026-11-12");
|
||||
expect(plan.files.map((f) => f.fileName)).toEqual(["FALKE 7_01.pdf", "FALKE 7_02.pdf"]);
|
||||
});
|
||||
|
||||
it("nicht anonym bleibt der Dateiname mit Projekt", () => {
|
||||
let p = withPosters();
|
||||
p = applyOps(p, addWbwSetOps(p, "s1"));
|
||||
expect(planPublish(p, p.publishSets![0], "2026-11-12").files[0].fileName).toBe("Haus Muster_WBW-Abgabe.pdf");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Rendering ins Layout einsetzen", () => {
|
||||
it("Ops setzen das Bild mittig aufs Blatt (A1 quer)", () => {
|
||||
let p = withPosters();
|
||||
const ops = placeImageOps(p, "p1", "r.png", PNG_40X30, "img-1")!;
|
||||
p = applyOps(p, ops);
|
||||
const img = p.layouts![0].images![0];
|
||||
expect(img.id).toBe("img-1");
|
||||
expect(img.pixelWidth).toBe(40);
|
||||
expect(img.xMm + img.widthMm / 2).toBeCloseTo(420.5, 0);
|
||||
expect(img.widthMm / img.heightMm).toBeCloseTo(4 / 3, 1);
|
||||
});
|
||||
|
||||
it("unbekanntes Blatt oder kein Bild: keine Ops", () => {
|
||||
const p = withPosters();
|
||||
expect(placeImageOps(p, "gibts-nicht", "r.png", PNG_40X30, "i")).toBeNull();
|
||||
expect(placeImageOps(p, "p1", "r.png", new Uint8Array([1, 2]), "i")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
// Plakat-Vorlagen für Wettbewerbs-Abgaben ([208]): A0/A1 hoch und quer. Eine Vorlage ist ein Masterlayout
|
||||
// (`MasterLayout.template`) mit Gestaltungsraster (Hilfslinien), Plakat-Kopfzeile (Kennwort-Feld, Projekttitel,
|
||||
// „Plan x/n") und Massstabsangabe unter jedem Viewport; ein Blatt „aus Vorlage" ist ein Layout, das an diesen
|
||||
// Master gebunden ist. Masse und Kopfzeile rechnet der Kern (`src-tauri/core/src/layout_poster.rs`).
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch.
|
||||
|
||||
import type { Layout, LayoutOrientation, LayoutPaperFormat, MasterLayout, Project } from "./types";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import { t } from "../i18n/translate";
|
||||
import { findSnapshot, resolveTitleBlock, resolveViewportScale, sheetSizeMm } from "./layoutModel";
|
||||
|
||||
export interface PosterTemplate {
|
||||
/** Schlüssel in `MasterLayout.template`. */
|
||||
key: string;
|
||||
paper: LayoutPaperFormat;
|
||||
orientation: LayoutOrientation;
|
||||
}
|
||||
|
||||
export const POSTER_TEMPLATES: readonly PosterTemplate[] = [
|
||||
{ key: "poster-a0-portrait", paper: "a0", orientation: "portrait" },
|
||||
{ key: "poster-a0-landscape", paper: "a0", orientation: "landscape" },
|
||||
{ key: "poster-a1-portrait", paper: "a1", orientation: "portrait" },
|
||||
{ key: "poster-a1-landscape", paper: "a1", orientation: "landscape" },
|
||||
];
|
||||
|
||||
export function posterTemplate(key: string): PosterTemplate | undefined {
|
||||
return POSTER_TEMPLATES.find((p) => p.key === key);
|
||||
}
|
||||
|
||||
/** Anzeigename einer Vorlage („Plakat A1 quer"). */
|
||||
export function posterTemplateLabel(tpl: PosterTemplate): string {
|
||||
return t("poster.template.name", {
|
||||
format: tpl.paper.toUpperCase(),
|
||||
orientation: tpl.orientation === "landscape" ? t("layouts.landscape") : t("layouts.portrait"),
|
||||
});
|
||||
}
|
||||
|
||||
export interface PosterMetrics {
|
||||
widthMm: number;
|
||||
heightMm: number;
|
||||
marginMm: number;
|
||||
headerHeightMm: number;
|
||||
columns: number;
|
||||
gutterMm: number;
|
||||
contentTopMm: number;
|
||||
guides: { axis: "x" | "y"; posMm: number }[];
|
||||
}
|
||||
|
||||
/** Ränder, Spalten und Hilfslinien für ein Blatt `widthMm`×`heightMm`. */
|
||||
export function posterMetrics(widthMm: number, heightMm: number): PosterMetrics {
|
||||
const out = core().layout_call("posterMetrics", JSON.stringify({ widthMm, heightMm }));
|
||||
if (out === "") throw new Error("Kern: Plakat-Masse nicht berechenbar");
|
||||
return JSON.parse(out) as PosterMetrics;
|
||||
}
|
||||
|
||||
/** Master der Vorlage (Titelblock leer, Hilfslinien des Rasters, Kopfzeile, Massstabsangaben). */
|
||||
export function createPosterMaster(id: string, tpl: PosterTemplate): MasterLayout {
|
||||
const size = sheetSizeMm(tpl.paper, tpl.orientation);
|
||||
const m = posterMetrics(size.w, size.h);
|
||||
return {
|
||||
id,
|
||||
name: posterTemplateLabel(tpl),
|
||||
paper: tpl.paper,
|
||||
orientation: tpl.orientation,
|
||||
titleBlock: {},
|
||||
border: false,
|
||||
template: tpl.key,
|
||||
posterHeader: true,
|
||||
viewportScaleLabels: true,
|
||||
guides: m.guides,
|
||||
};
|
||||
}
|
||||
|
||||
/** Der vorhandene Master einer Vorlage im Projekt (Plakate teilen einen Master je Vorlage). */
|
||||
export function findPosterMaster(project: Pick<Project, "masterLayouts">, key: string): MasterLayout | undefined {
|
||||
return (project.masterLayouts ?? []).find((m) => m.template === key);
|
||||
}
|
||||
|
||||
export type HeaderItem =
|
||||
| { kind: "rect"; x: number; y: number; w: number; h: number; stroke: number }
|
||||
| { kind: "text"; x: number; y: number; text: string; sizeMm: number; align: "left" | "center" | "right"; bold: boolean };
|
||||
|
||||
/**
|
||||
* Zeichenelemente der Plakat-Kopfzeile eines Blatts: Kennwort-Feld, Projekttitel (bei anonymer Abgabe leer) und
|
||||
* „Plan x/n". Bildschirm (SVG) und PDF zeichnen dieselben Elemente.
|
||||
*/
|
||||
export function posterHeaderItems(project: Project, layout: Layout, master: MasterLayout, sheet: { w: number; h: number }): HeaderItem[] {
|
||||
const tb = resolveTitleBlock(project, layout, master);
|
||||
const title = tb.anonymous ? "" : tb.projectName;
|
||||
const planText = tb.planCount > 0 ? t("poster.header.plan", { x: tb.planIndex, n: tb.planCount }) : "";
|
||||
const out = core().layout_call(
|
||||
"posterHeader",
|
||||
JSON.stringify({ widthMm: sheet.w, heightMm: sheet.h, keywordLabel: t("poster.header.keyword"), keyword: tb.keyword, title, planText }),
|
||||
);
|
||||
return out === "" ? [] : (JSON.parse(out) as HeaderItem[]);
|
||||
}
|
||||
|
||||
/** Massstabsangabe unter einem Viewport: Text, Lage (Papier-mm, Grundlinie) und Schrifthöhe. */
|
||||
export function viewportScaleLabel(
|
||||
project: Project,
|
||||
vp: Layout["viewports"][number],
|
||||
sheet: { w: number; h: number },
|
||||
scaleOverride?: number,
|
||||
): { text: string; x: number; y: number; sizeMm: number } | null {
|
||||
const snap = findSnapshot(project, vp.snapshotId);
|
||||
if (!snap) return null;
|
||||
const n = scaleOverride ?? resolveViewportScale(vp, snap);
|
||||
const sizeMm = Math.max(3, Math.min(sheet.w, sheet.h) / 140);
|
||||
return { text: `1:${n}`, x: vp.xMm, y: vp.yMm + vp.heightMm + sizeMm * 1.3, sizeMm };
|
||||
}
|
||||
@@ -336,6 +336,17 @@ export type Column = {
|
||||
*/
|
||||
export type ColumnProfile = { kind: "rect"; width: number; depth: number } | { kind: "round"; radius: number };
|
||||
|
||||
/**
|
||||
* Wettbewerbs-Einstellung des Projekts ([208]): anonym = Kennwort statt Büro- und Projektname in Plankopf,
|
||||
* Dateinamen und PDF-Metadaten.
|
||||
*/
|
||||
export type CompetitionSettings = {
|
||||
/** Anonyme Abgabe: keine Büro-/Autor-Angaben in Export und Plankopf. */
|
||||
anonymous: boolean;
|
||||
/** Kennwort der Abgabe (steht in Plankopf und PDF-Titel). */
|
||||
keyword: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Ein Bauteil-Material (Component Manager) — vereint Plan-Schnittdarstellung
|
||||
* (Schraffur) und 3D-Erscheinung. Ersetzt das frühere `Material`.
|
||||
@@ -1833,6 +1844,8 @@ export type Layout = {
|
||||
legends?: Array<LayoutLegend>;
|
||||
/** Lebendige Tabellen auf dem Blatt ([111]); fehlt = keine. */
|
||||
tables?: Array<LayoutTable>;
|
||||
/** Bilder auf dem Blatt ([208]): Renderings, Fotos, Luftbilder; fehlt = keine. */
|
||||
images?: Array<LayoutImage>;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1855,6 +1868,44 @@ export type LayoutFolder = {
|
||||
kind?: "layout" | "master";
|
||||
};
|
||||
|
||||
/**
|
||||
* Hilfslinie eines Masters ([208], Gestaltungsraster): senkrecht (`x`) oder waagrecht (`y`) in Papier-mm.
|
||||
* Nur am Bildschirm, nie im Druck.
|
||||
*/
|
||||
export type LayoutGuide = {
|
||||
/** "x" = senkrechte Linie bei `posMm` von links, "y" = waagrechte Linie bei `posMm` von oben. */
|
||||
axis: string;
|
||||
posMm: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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).
|
||||
*/
|
||||
export type LayoutImage = {
|
||||
id: string;
|
||||
/** Anzeigename (Dateiname). */
|
||||
name: string;
|
||||
/** Bildquelle als Data-URL (`data:image/png;base64,…` oder `data:image/jpeg;base64,…`). */
|
||||
src: string;
|
||||
/** Linke Kante auf dem Blatt (mm, von links). */
|
||||
xMm: number;
|
||||
/** Obere Kante auf dem Blatt (mm, von oben). */
|
||||
yMm: number;
|
||||
/** Breite des gezeigten Ausschnitts (mm). */
|
||||
widthMm: number;
|
||||
/** Höhe des gezeigten Ausschnitts (mm). */
|
||||
heightMm: number;
|
||||
/** Pixelbreite des Originals (aus dem Dateikopf gelesen). */
|
||||
pixelWidth: number;
|
||||
/** Pixelhöhe des Originals. */
|
||||
pixelHeight: number;
|
||||
/** Zuschnitt als Anteile des Originals (0..1); fehlt = ganzes Bild. */
|
||||
crop?: { x: number; y: number; w: number; h: number };
|
||||
};
|
||||
|
||||
/**
|
||||
* Grafische Legende auf einem Layout-Blatt ([82]): listet Schraffuren/Materialien, Linientypen und/oder
|
||||
* Kategorien der gezeigten Viewports (`manualKeys` leer) oder einer Handauswahl, mit Muster und Name.
|
||||
@@ -2085,6 +2136,18 @@ export type MasterLayout = {
|
||||
customWidthMm?: number;
|
||||
/** Freie Blatthöhe in mm (siehe {@link MasterLayout.customWidthMm}). */
|
||||
customHeightMm?: number;
|
||||
/**
|
||||
* Vorlagen-Schlüssel ([208], z. B. "poster-a1-landscape"): wiederverwendet den Master beim Anlegen weiterer Plakate.
|
||||
*/
|
||||
template?: string;
|
||||
/**
|
||||
* Plakat-Kopfzeile ([208]): Band über die Satzbreite mit Kennwort-Feld, Projekttitel und „Plan x/n".
|
||||
*/
|
||||
posterHeader?: boolean;
|
||||
/** Massstab unter jedem Viewport ausgeben ([208]). */
|
||||
viewportScaleLabels?: boolean;
|
||||
/** Hilfslinien des Gestaltungsrasters ([208]), nur am Bildschirm. */
|
||||
guides?: Array<LayoutGuide>;
|
||||
};
|
||||
|
||||
/** [173] Darstellung der Stufen über der Schnitthöhe. */
|
||||
@@ -2965,6 +3028,8 @@ export type Project = {
|
||||
publishLog?: Array<PublishLogEntry>;
|
||||
/** Projektnummer für Titelblock und Dateinamen ([79]). */
|
||||
projectNumber?: string;
|
||||
/** Wettbewerb ([208]): anonyme Abgabe mit Kennwort. */
|
||||
competition?: CompetitionSettings;
|
||||
/**
|
||||
* Höhe von ±0.00 (OK fertig Boden des Bezugsgeschosses, `DrawingLevel.zeroLevel`)
|
||||
* in Metern über Meer (m ü. M.), editierbar im Einstellungs-Fenster. Optional.
|
||||
|
||||
@@ -460,6 +460,7 @@ export function LayoutsPanel() {
|
||||
orientation: start.orientation,
|
||||
customWidthMm: start.customWidthMm,
|
||||
customHeightMm: start.customHeightMm,
|
||||
posterTemplate: start.posterTemplate,
|
||||
});
|
||||
if (activeFolderId) expandFolder(activeFolderId);
|
||||
setDialog(null);
|
||||
|
||||
@@ -173,6 +173,32 @@ export function PublishSection() {
|
||||
onChange={(e) => host.onSetProjectNumber(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{/* Wettbewerb ([208]): anonyme Abgabe mit Kennwort; WBW-Satz mit allen Plakaten. */}
|
||||
<div style={{ padding: "2px 10px", display: "grid", gap: 4, fontSize: 12 }} data-competition>
|
||||
<label style={{ display: "flex", gap: 6, alignItems: "center" }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
data-testid="competition-anonymous"
|
||||
checked={project.competition?.anonymous === true}
|
||||
onChange={(e) => host.onSetCompetition({ anonymous: e.target.checked })}
|
||||
/>
|
||||
<span>{t("publish.competition.anonymous")}</span>
|
||||
</label>
|
||||
<label style={{ display: "flex", gap: 6, alignItems: "center" }}>
|
||||
<span>{t("publish.competition.keyword")}</span>
|
||||
<input
|
||||
className="res-input mono"
|
||||
style={{ flex: 1 }}
|
||||
data-testid="competition-keyword"
|
||||
value={project.competition?.keyword ?? ""}
|
||||
onChange={(e) => host.onSetCompetition({ keyword: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
{project.competition?.anonymous === true && <div style={{ color: "var(--muted)" }}>{t("publish.competition.hint")}</div>}
|
||||
<button className="nav-add" style={{ justifySelf: "start", whiteSpace: "nowrap", padding: "1px 6px", fontSize: 12 }} data-testid="publish-add-wbw" onClick={() => setOpen(host.onAddWbwSet())}>
|
||||
+ {t("publish.wbw.add")}
|
||||
</button>
|
||||
</div>
|
||||
{sets.length === 0 && <div style={{ padding: "4px 10px 8px", fontSize: 12, color: "var(--muted)" }}>{t("publish.none")}</div>}
|
||||
{sets.map((s) => (
|
||||
<div key={s.id} data-publish-set={s.id}>
|
||||
|
||||
@@ -803,6 +803,10 @@ export interface PanelHostValue {
|
||||
onPublishSet: (id: string) => void;
|
||||
/** Setzt die Projektnummer (Dateinamen-Muster `{Projektnummer}`). */
|
||||
onSetProjectNumber: (value: string) => void;
|
||||
/** Wettbewerb ([208]): anonyme Abgabe und Kennwort setzen (Teil-Patch). */
|
||||
onSetCompetition: (patch: { anonymous?: boolean; keyword?: string }) => void;
|
||||
/** Legt den Publikationssatz „WBW-Abgabe" mit allen Plakaten an; liefert dessen Id. */
|
||||
onAddWbwSet: () => string;
|
||||
}
|
||||
|
||||
/** Startwerte eines neuen Layouts (aus dem „Neues Layout"-Dialog). */
|
||||
@@ -815,6 +819,8 @@ export interface CreateLayoutOptions {
|
||||
orientation: LayoutOrientation;
|
||||
customWidthMm?: number;
|
||||
customHeightMm?: number;
|
||||
/** Plakat-Vorlage ([208], Schlüssel aus `model/posterTemplates`): legt den Vorlagen-Master an bzw. verwendet ihn. */
|
||||
posterTemplate?: string;
|
||||
}
|
||||
|
||||
/** Startwerte eines neuen Masterlayouts (aus dem „Neues Masterlayout"-Dialog). */
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Bilder aufs Layout-Blatt setzen ([208]): aus dem Rendering-Dialog („Ins Layout einsetzen"), später auch für
|
||||
// Fotos. Reine Ops-Bildung (`placeImageOps`) getrennt vom Store-Aufruf, damit sie ohne DOM testbar ist.
|
||||
|
||||
import { patchItem, type CoreOp } from "../core";
|
||||
import type { Layout, Project } from "../model/types";
|
||||
import { addImage, createLayoutImage } from "../model/layoutImages";
|
||||
import { effectiveSheetSizeMm, findMaster, sheetLevelOf } from "../model/layoutModel";
|
||||
import { getState } from "./appStore";
|
||||
|
||||
/** Blatt, das beim Einsetzen vorgewählt ist: das Blatt der aktiven Ebene (offenes Layout), sonst das letzte. */
|
||||
export function defaultTargetLayout(project: Pick<Project, "layouts" | "drawingLevels">, activeLevelId: string): Layout | undefined {
|
||||
const layouts = project.layouts ?? [];
|
||||
const level = project.drawingLevels.find((l) => l.id === activeLevelId);
|
||||
return layouts.find((l) => l.id === level?.layoutId) ?? layouts[layouts.length - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Ops, die `bytes` (PNG/JPEG) mittig und im Seitenverhältnis auf das Blatt `layoutId` setzen; `null`, wenn das Blatt
|
||||
* fehlt oder die Bytes kein PNG/JPEG sind. `id` ist die Bild-Id (Aufrufer: Zeitstempel).
|
||||
*/
|
||||
export function placeImageOps(project: Project, layoutId: string, name: string, bytes: Uint8Array, id: string, mime = "image/png"): CoreOp[] | null {
|
||||
const layout = (project.layouts ?? []).find((l) => l.id === layoutId);
|
||||
if (!layout) return null;
|
||||
const image = createLayoutImage(id, name, bytes, effectiveSheetSizeMm(findMaster(project, layout) ?? layout), mime);
|
||||
if (!image) return null;
|
||||
return patchItem(project, "layouts", layoutId, (l) => addImage(l, image));
|
||||
}
|
||||
|
||||
/** Setzt das Bild auf das Blatt (ein Undo-Schritt); `false`, wenn nichts eingesetzt werden konnte. */
|
||||
export function placeImageOnLayout(layoutId: string, name: string, bytes: Uint8Array, mime = "image/png"): boolean {
|
||||
const st = getState();
|
||||
const ops = placeImageOps(st.project, layoutId, name, bytes, `img-${Date.now()}`, mime);
|
||||
if (!ops) return false;
|
||||
st.applyChange(ops);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Blatt-Ebene eines Layouts (für „Blatt öffnen" nach dem Einsetzen). */
|
||||
export function layoutSheetLevelId(project: Project, layoutId: string): string | undefined {
|
||||
return sheetLevelOf(project, layoutId)?.id;
|
||||
}
|
||||
@@ -5,9 +5,10 @@ import { addItems, fieldOps, patchItem, patchItems, removeItems } from "../../co
|
||||
import { t } from "../../i18n";
|
||||
import { createLayout, createLayoutFolder, createMasterLayout, deleteFolder as deleteLayoutFolder, deleteMasterFolder, moveLayoutToFolder, moveFolderToFolder, createSheetLevel } from "../../model/layoutModel";
|
||||
import { folderPdfBytes } from "../../export/layoutPdf";
|
||||
import { addPublishSetOps, deletePublishSetOps, patchPublishSetOps, publishSet } from "../publishActions";
|
||||
import { addPublishSetOps, addWbwSetOps, deletePublishSetOps, patchPublishSetOps, publishSet, setCompetitionOps } from "../publishActions";
|
||||
import { openLayoutTab } from "../tabNavigation";
|
||||
import { saveBinaryFile } from "../../native/saveFile";
|
||||
import { createPosterMaster, findPosterMaster, posterTemplate } from "../../model/posterTemplates";
|
||||
import type { FlatHostOpts, HostPart } from "./types";
|
||||
|
||||
export function buildLayoutsHost(c: FlatHostOpts) {
|
||||
@@ -105,10 +106,15 @@ export function buildLayoutsHost(c: FlatHostOpts) {
|
||||
},
|
||||
onCreateLayout: (opts) => {
|
||||
const id = `lay-${Date.now()}`;
|
||||
// Plakat-Vorlage ([208]): der Master der Vorlage wird angelegt, falls das Projekt noch keinen hat.
|
||||
const tpl = opts.posterTemplate ? posterTemplate(opts.posterTemplate) : undefined;
|
||||
const posterMaster = tpl ? (findPosterMaster(project, tpl.key) ?? createPosterMaster(`mas-${tpl.key}`, tpl)) : undefined;
|
||||
const newMaster = posterMaster && !findPosterMaster(project, posterMaster.template ?? "") ? posterMaster : undefined;
|
||||
const masterId = posterMaster?.id ?? opts.masterId;
|
||||
// Bei gebundenem Master erbt das Blatt dessen Papier/Ausrichtung/Grösse.
|
||||
const master = opts.masterId
|
||||
const master = posterMaster ?? (opts.masterId
|
||||
? (project.masterLayouts ?? []).find((m) => m.id === opts.masterId)
|
||||
: undefined;
|
||||
: undefined);
|
||||
const paper = master?.paper ?? opts.paper;
|
||||
const orientation = master?.orientation ?? opts.orientation;
|
||||
const customWidthMm = master ? master.customWidthMm : opts.customWidthMm;
|
||||
@@ -116,13 +122,17 @@ export function buildLayoutsHost(c: FlatHostOpts) {
|
||||
const lay = createLayout(id, t("layouts.defaultName"), paper, orientation);
|
||||
const full = {
|
||||
...lay,
|
||||
...(opts.masterId ? { masterId: opts.masterId } : {}),
|
||||
...(masterId ? { masterId } : {}),
|
||||
...(opts.folderId ? { folderId: opts.folderId } : {}),
|
||||
...(customWidthMm !== undefined && customHeightMm !== undefined
|
||||
? { customWidthMm, customHeightMm }
|
||||
: {}),
|
||||
};
|
||||
applyChange([...addItems("layouts", [full]), ...addItems("drawingLevels", [createSheetLevel(`sheet-${id}`, full)])]);
|
||||
applyChange([
|
||||
...(newMaster ? addItems("masterLayouts", [newMaster]) : []),
|
||||
...addItems("layouts", [full]),
|
||||
...addItems("drawingLevels", [createSheetLevel(`sheet-${id}`, full)]),
|
||||
]);
|
||||
return id;
|
||||
},
|
||||
onCreateMasterLayout: (opts) => {
|
||||
@@ -163,6 +173,12 @@ export function buildLayoutsHost(c: FlatHostOpts) {
|
||||
return id;
|
||||
},
|
||||
onPatchPublishSet: (id, patch) => applyChange((p) => patchPublishSetOps(p, id, patch), `pubset-${id}`),
|
||||
onSetCompetition: (patch) => applyChange((p) => setCompetitionOps(p, patch), "competition"),
|
||||
onAddWbwSet: () => {
|
||||
const id = `pubset-${Date.now()}`;
|
||||
applyChange((p) => addWbwSetOps(p, id));
|
||||
return id;
|
||||
},
|
||||
onSetProjectNumber: (value) => applyChange((p) => fieldOps(p, "projectNumber", value.trim() ? value : undefined), "projectNumber"),
|
||||
onDeletePublishSet: (id) => applyChange((p) => deletePublishSetOps(p, id)),
|
||||
onPublishSet: (id) => {
|
||||
|
||||
@@ -14,6 +14,30 @@ export function addPublishSetOps(p: Project, id: string): CoreOp[] {
|
||||
return fieldOps(p, "publishSets", [...(p.publishSets ?? []), set]);
|
||||
}
|
||||
|
||||
/** Publikationssatz „WBW-Abgabe" ([208]): alle Plakate (Blätter mit Plakat-Master, sonst alle Blätter) als ein PDF. */
|
||||
export function addWbwSetOps(p: Project, id: string): CoreOp[] {
|
||||
const posterMasters = new Set((p.masterLayouts ?? []).filter((m) => m.posterHeader).map((m) => m.id));
|
||||
const posters = (p.layouts ?? []).filter((l) => l.masterId && posterMasters.has(l.masterId));
|
||||
const layoutIds = (posters.length > 0 ? posters : (p.layouts ?? [])).map((l) => l.id);
|
||||
const set: PublishSet = {
|
||||
id,
|
||||
name: t("publish.wbw.name"),
|
||||
layoutIds,
|
||||
format: "pdf-multi",
|
||||
namePattern: "{Projekt}_{Satz}",
|
||||
includeRevision: false,
|
||||
bumpRevision: false,
|
||||
pdfLayers: false,
|
||||
};
|
||||
return fieldOps(p, "publishSets", [...(p.publishSets ?? []), set]);
|
||||
}
|
||||
|
||||
/** Wettbewerbs-Einstellung ([208]) ändern; ohne Kennwort und nicht anonym entfällt das Feld. */
|
||||
export function setCompetitionOps(p: Project, patch: { anonymous?: boolean; keyword?: string }): CoreOp[] {
|
||||
const next = { anonymous: false, keyword: "", ...p.competition, ...patch };
|
||||
return fieldOps(p, "competition", next.anonymous || next.keyword.trim() ? next : undefined);
|
||||
}
|
||||
|
||||
export function patchPublishSetOps(p: Project, id: string, patch: Partial<Omit<PublishSet, "id">>): CoreOp[] {
|
||||
return fieldOps(p, "publishSets", (p.publishSets ?? []).map((s) => (s.id === id ? { ...s, ...patch } : s)));
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { CategoryDisplayResolver } from "../core";
|
||||
import type { DetailLevel } from "../model/viewTypes";
|
||||
import type { DisplayResolver } from "../viewport/Viewport3D";
|
||||
import { savePlanPdf } from "../export/exportPdf";
|
||||
import { exportProjectName } from "../export/pdfInfo";
|
||||
import { savePlanSvg } from "../export/exportSvg";
|
||||
import { savePlanDxf } from "../export/exportDxf";
|
||||
import type { ExportPdfDecision } from "../ui/ExportPdfDialog";
|
||||
@@ -110,8 +111,10 @@ export function useExportHandlers(opts: {
|
||||
paper: decision.paper,
|
||||
orientation: decision.orientation,
|
||||
title: activeLevelName,
|
||||
subtitle: getState().project.name,
|
||||
fileName: `${getState().project.name}-${activeLevelName}`,
|
||||
// Wettbewerb anonym ([208]): Kennwort statt Projektname in Schriftfeld und Dateiname.
|
||||
subtitle: exportProjectName(getState().project),
|
||||
fileName: `${exportProjectName(getState().project)}-${activeLevelName}`,
|
||||
competition: getState().project.competition,
|
||||
});
|
||||
setExportOpen(false);
|
||||
};
|
||||
@@ -137,7 +140,7 @@ export function useExportHandlers(opts: {
|
||||
scaleDenominator: decision.scaleDenominator,
|
||||
paper: decision.paper,
|
||||
orientation: decision.orientation,
|
||||
fileName: `${getState().project.name}-${activeLevelName}`,
|
||||
fileName: `${exportProjectName(getState().project)}-${activeLevelName}`,
|
||||
});
|
||||
setExportOpen(false);
|
||||
};
|
||||
@@ -194,7 +197,7 @@ export function useExportHandlers(opts: {
|
||||
dimUnit: decision.dimUnit,
|
||||
paperLayout: decision.paperLayout,
|
||||
levelId: activeLevelId,
|
||||
fileName: `${getState().project.name}-${activeLevelName}`,
|
||||
fileName: `${exportProjectName(getState().project)}-${activeLevelName}`,
|
||||
});
|
||||
} catch (err) {
|
||||
getState().notify(`${t("exportDxf.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error");
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import type { Layout, LayoutLegend, LayoutTable, LayoutTitleBlock, LayoutViewport } from "../model/types";
|
||||
import type { Layout, LayoutImage, LayoutLegend, LayoutTable, LayoutTitleBlock, LayoutViewport } from "../model/types";
|
||||
import { useStore } from "./appStore";
|
||||
import { addItems, patchItem } from "../core";
|
||||
import type { ProjectSlice } from "./projectSlice";
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
patchTable as patchTableInLayout,
|
||||
removeTable as removeTableFromLayout,
|
||||
} from "../model/layoutModel";
|
||||
import { addImage, patchImage, removeImage } from "../model/layoutImages";
|
||||
import { addLegend, patchLegend, removeLegend } from "../analysis/legend";
|
||||
import { useEventBundle } from "./useEvent";
|
||||
|
||||
@@ -95,6 +96,10 @@ export function useSheetPane(opts: {
|
||||
onPatchTable: (tableId: string, patch: Partial<Omit<LayoutTable, "id">>, coalesceKey?: string) =>
|
||||
patchOpenLayout(openId(), (l) => patchTableInLayout(l, tableId, patch), coalesceKey),
|
||||
onRemoveTable: (tableId: string) => patchOpenLayout(openId(), (l) => removeTableFromLayout(l, tableId)),
|
||||
onAddImage: (image: LayoutImage) => patchOpenLayout(openId(), (l) => addImage(l, image)),
|
||||
onPatchImage: (imageId: string, patch: Partial<Omit<LayoutImage, "id">>, coalesceKey?: string) =>
|
||||
patchOpenLayout(openId(), (l) => patchImage(l, imageId, patch), coalesceKey),
|
||||
onRemoveImage: (imageId: string) => patchOpenLayout(openId(), (l) => removeImage(l, imageId)),
|
||||
onAddViewport: (snapshotId: string, init: Partial<Omit<LayoutViewport, "id" | "snapshotId">>) =>
|
||||
patchOpenLayout(openId(), (l) =>
|
||||
addViewportToLayout(l, createViewport(`vp-${Date.now()}`, snapshotId, init)),
|
||||
|
||||
@@ -15,6 +15,7 @@ import type {
|
||||
MasterLayout,
|
||||
} from "../model/types";
|
||||
import { PAPER_FORMAT_GROUPS } from "../model/layoutModel";
|
||||
import { POSTER_TEMPLATES, posterTemplateLabel } from "../model/posterTemplates";
|
||||
|
||||
/** Startwerte eines neuen Blatts/Masters (Grösse). */
|
||||
export interface LayoutSizeStart {
|
||||
@@ -28,6 +29,8 @@ export interface LayoutSizeStart {
|
||||
export interface NewLayoutStart extends LayoutSizeStart {
|
||||
/** Gebundenes Masterlayout (erbt dessen Papier/Ausrichtung); sonst undefined. */
|
||||
masterId?: string;
|
||||
/** Plakat-Vorlage ([208], Schlüssel aus `POSTER_TEMPLATES`): Master, Raster und Kopfzeile kommen aus der Vorlage. */
|
||||
posterTemplate?: string;
|
||||
}
|
||||
|
||||
type SizeMode = LayoutPaperFormat | "custom";
|
||||
@@ -236,9 +239,10 @@ export function NewLayoutDialog({
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const hasMasters = masters.length > 0;
|
||||
const [source, setSource] = useState<"master" | "free">(
|
||||
const [source, setSource] = useState<"master" | "free" | "poster">(
|
||||
hasMasters ? "master" : "free",
|
||||
);
|
||||
const [posterKey, setPosterKey] = useState<string>("poster-a1-landscape");
|
||||
const [masterId, setMasterId] = useState<string>(masters[0]?.id ?? "");
|
||||
const [mode, setMode] = useState<SizeMode>("a4");
|
||||
const [orientation, setOrientation] = useState<LayoutOrientation>("portrait");
|
||||
@@ -246,6 +250,11 @@ export function NewLayoutDialog({
|
||||
const [hMm, setHMm] = useState(297);
|
||||
|
||||
const confirm = () => {
|
||||
if (source === "poster") {
|
||||
const tpl = POSTER_TEMPLATES.find((p) => p.key === posterKey) ?? POSTER_TEMPLATES[0];
|
||||
onCreate({ posterTemplate: tpl.key, paper: tpl.paper, orientation: tpl.orientation });
|
||||
return;
|
||||
}
|
||||
if (source === "master" && masterId) {
|
||||
// Grösse erbt der Aufrufer vom Master; wir liefern nur die Bindung + eine
|
||||
// sinnvolle Rückfall-Grösse (A4 hoch), falls der Master unauflösbar ist.
|
||||
@@ -276,9 +285,29 @@ export function NewLayoutDialog({
|
||||
/>
|
||||
<span>{t("layouts.newLayout.freeSize")}</span>
|
||||
</label>
|
||||
<label className="imp-radio">
|
||||
<input
|
||||
type="radio"
|
||||
data-testid="newlayout-poster"
|
||||
checked={source === "poster"}
|
||||
onChange={() => setSource("poster")}
|
||||
/>
|
||||
<span>{t("layouts.newLayout.poster")}</span>
|
||||
</label>
|
||||
</section>
|
||||
|
||||
{source === "master" ? (
|
||||
{source === "poster" ? (
|
||||
<section className="imp-section">
|
||||
<select className="imp-select" data-testid="newlayout-poster-select" value={posterKey} onChange={(e) => setPosterKey(e.target.value)}>
|
||||
{POSTER_TEMPLATES.map((p) => (
|
||||
<option key={p.key} value={p.key}>
|
||||
{posterTemplateLabel(p)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="imp-note">{t("layouts.newLayout.posterHint")}</div>
|
||||
</section>
|
||||
) : source === "master" ? (
|
||||
<section className="imp-section">
|
||||
{hasMasters ? (
|
||||
<select
|
||||
|
||||
+195
-3
@@ -15,6 +15,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { PointerEvent as ReactPointerEvent, ReactNode, RefObject } from "react";
|
||||
import type {
|
||||
Layout,
|
||||
LayoutImage,
|
||||
LayoutLegend,
|
||||
LayoutTitleBlock,
|
||||
LayoutOrientation,
|
||||
@@ -28,6 +29,9 @@ import type {
|
||||
import { createTable, PX_PER_M, sheetTables, TABLE_SOURCES, snapshotMono, snapshotOverrideRuleIds, snapshotTemplate, tableSourceLabel, viewportLevelPlan } from "../core";
|
||||
import type { TableOut } from "../core";
|
||||
import { SheetTableHud } from "./SheetTableHud";
|
||||
import { SheetImageHud } from "./SheetImageHud";
|
||||
import { createLayoutImage, imageAspect, imageGeometry } from "../model/layoutImages";
|
||||
import { posterHeaderItems, viewportScaleLabel } from "../model/posterTemplates";
|
||||
import { planToPrintSvg } from "../export/planToPrintSvg";
|
||||
import { legendPlan, legendPrintSvg } from "../export/legendSvg";
|
||||
import { legendBox, legendEntries, legendKeysOfViewports, type LegendKind } from "../analysis/legend";
|
||||
@@ -54,6 +58,7 @@ import {
|
||||
} from "./layoutSheetMath";
|
||||
import type { PlanSelection, PlanViewHandle } from "../views/plan/PlanView";
|
||||
import { t } from "../i18n";
|
||||
import { getState } from "../state/appStore";
|
||||
|
||||
// ── Geteilter Render-Kern ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -231,6 +236,11 @@ export interface LayoutSheetHandlers {
|
||||
/** Ändert eine Tabelle (Teil-Patch; gleiche `coalesceKey` fassen sich zu einem Undo-Schritt zusammen). */
|
||||
onPatchTable: (tableId: string, patch: Partial<Omit<LayoutTable, "id">>, coalesceKey?: string) => void;
|
||||
onRemoveTable: (tableId: string) => void;
|
||||
/** Setzt ein Bild (PNG/JPEG) auf das Blatt ([208]). */
|
||||
onAddImage: (image: LayoutImage) => void;
|
||||
/** Ändert ein Bild (Lage, Breite, Zuschnitt); gleiche `coalesceKey` = ein Undo-Schritt. */
|
||||
onPatchImage: (imageId: string, patch: Partial<Omit<LayoutImage, "id">>, coalesceKey?: string) => void;
|
||||
onRemoveImage: (imageId: string) => void;
|
||||
/**
|
||||
* [137] Schriftfeld bearbeiten: Blattname/Plan-Nr./Index am Blatt, Projekt/Bearbeiter/Datum am Master
|
||||
* (gleiche `coalesceKey` = ein Undo-Schritt beim Tippen).
|
||||
@@ -313,6 +323,10 @@ export function LayoutSheetPane({
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [selectedLegendId, setSelectedLegendId] = useState<string | null>(null);
|
||||
const [selectedTableId, setSelectedTableId] = useState<string | null>(null);
|
||||
// Bilder ([208]): Auswahl und laufendes Verschieben/Skalieren (Ghost-Rahmen in mm).
|
||||
const [selectedImageId, setSelectedImageId] = useState<string | null>(null);
|
||||
const [imagePreview, setImagePreview] = useState<{ id: string; rect: RectMm } | null>(null);
|
||||
const fileRef = useRef<HTMLInputElement | null>(null);
|
||||
// [137] Schriftfeld angeklickt → Felder bearbeiten.
|
||||
const [titleBlockSelected, setTitleBlockSelected] = useState(false);
|
||||
// Tabellen-Verschiebung läuft (Versatz in mm), sonst null.
|
||||
@@ -337,12 +351,15 @@ export function LayoutSheetPane({
|
||||
const tables = useMemo(() => sheetTables(project, layout.id), [project, layout.id]);
|
||||
const layoutTables = layout.tables ?? [];
|
||||
const selectedTable = layoutTables.find((tb) => tb.id === selectedTableId) ?? null;
|
||||
const layoutImages = layout.images ?? [];
|
||||
const selectedImage = layoutImages.find((i) => i.id === selectedImageId) ?? null;
|
||||
|
||||
// Gelöschter Viewport / anderes Blatt → Auswahl und laufendes Platzieren verwerfen.
|
||||
useEffect(() => {
|
||||
setSelectedId(null);
|
||||
setSelectedLegendId(null);
|
||||
setSelectedTableId(null);
|
||||
setSelectedImageId(null);
|
||||
setTitleBlockSelected(false);
|
||||
setPlacing(false);
|
||||
setPendingRect(null);
|
||||
@@ -357,14 +374,20 @@ export function LayoutSheetPane({
|
||||
|
||||
// Entf löscht den gewählten Viewport, Escape hebt Auswahl/Platzieren auf (nicht in Eingabefeldern).
|
||||
useEffect(() => {
|
||||
if (!selectedVp && !placing && !selectedTable) return;
|
||||
if (!selectedVp && !placing && !selectedTable && !selectedImage) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
const el = e.target as HTMLElement | null;
|
||||
if (el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName))) return;
|
||||
if (e.key === "Escape") {
|
||||
setSelectedId(null);
|
||||
setSelectedTableId(null);
|
||||
setSelectedImageId(null);
|
||||
setPlacing(false);
|
||||
} else if ((e.key === "Delete" || e.key === "Backspace") && selectedImage && !selectedVp && !selectedTable) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handlers.onRemoveImage(selectedImage.id);
|
||||
setSelectedImageId(null);
|
||||
} else if ((e.key === "Delete" || e.key === "Backspace") && selectedTable && !selectedVp) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
@@ -379,7 +402,7 @@ export function LayoutSheetPane({
|
||||
};
|
||||
window.addEventListener("keydown", onKey, true);
|
||||
return () => window.removeEventListener("keydown", onKey, true);
|
||||
}, [selectedVp, selectedTable, placing, handlers]);
|
||||
}, [selectedVp, selectedTable, selectedImage, placing, handlers]);
|
||||
|
||||
// Client-Pixel → Blatt-mm über die Bildschirm-Matrix der Blatt-Gruppe (enthält Pan/Zoom).
|
||||
const toMm = (clientX: number, clientY: number): { xMm: number; yMm: number } | null => {
|
||||
@@ -466,6 +489,60 @@ export function LayoutSheetPane({
|
||||
window.addEventListener("pointercancel", up);
|
||||
};
|
||||
|
||||
// Bild verschieben (Körper) oder an der unteren rechten Ecke skalieren (Seitenverhältnis bleibt): Ghost live,
|
||||
// beim Loslassen ein Patch (auf 0.1 mm).
|
||||
const startImageDrag = (e: ReactPointerEvent<SVGElement>, img: LayoutImage, handle: "body" | "se") => {
|
||||
if (e.button !== 0) return;
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
const grab = toMm(e.clientX, e.clientY);
|
||||
if (!grab) return;
|
||||
const aspect = imageAspect(img);
|
||||
let last: RectMm = { xMm: img.xMm, yMm: img.yMm, widthMm: img.widthMm, heightMm: img.heightMm };
|
||||
const move = (ev: PointerEvent) => {
|
||||
const mm = toMm(ev.clientX, ev.clientY);
|
||||
if (!mm) return;
|
||||
const dx = mm.xMm - grab.xMm;
|
||||
const dy = mm.yMm - grab.yMm;
|
||||
if (handle === "body") {
|
||||
last = { xMm: img.xMm + dx, yMm: img.yMm + dy, widthMm: img.widthMm, heightMm: img.heightMm };
|
||||
} else {
|
||||
const w = Math.max(MIN_VP_MM, img.widthMm + dx);
|
||||
last = { xMm: img.xMm, yMm: img.yMm, widthMm: w, heightMm: w / aspect };
|
||||
}
|
||||
setImagePreview({ id: img.id, rect: last });
|
||||
};
|
||||
const up = () => {
|
||||
window.removeEventListener("pointermove", move);
|
||||
window.removeEventListener("pointerup", up);
|
||||
window.removeEventListener("pointercancel", up);
|
||||
setImagePreview(null);
|
||||
if (last.xMm === img.xMm && last.yMm === img.yMm && last.widthMm === img.widthMm) return;
|
||||
handlers.onPatchImage(img.id, { xMm: round1(last.xMm), yMm: round1(last.yMm), widthMm: round1(last.widthMm), heightMm: round1(last.heightMm) });
|
||||
};
|
||||
window.addEventListener("pointermove", move);
|
||||
window.addEventListener("pointerup", up);
|
||||
window.addEventListener("pointercancel", up);
|
||||
};
|
||||
|
||||
const imageRect = (img: LayoutImage): RectMm =>
|
||||
imagePreview && imagePreview.id === img.id ? imagePreview.rect : { xMm: img.xMm, yMm: img.yMm, widthMm: img.widthMm, heightMm: img.heightMm };
|
||||
|
||||
// Bilddatei gewählt → mittig aufs Blatt, im Seitenverhältnis ([208]). Format erkennt der Kern am Dateikopf.
|
||||
const addImageFile = async (file: File) => {
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
const img = createLayoutImage(`img-${Date.now()}`, file.name, bytes, sheet, file.type === "image/jpeg" ? "image/jpeg" : "image/png");
|
||||
if (!img) {
|
||||
getState().notify(t("sheetImage.invalid"), "warning");
|
||||
return;
|
||||
}
|
||||
handlers.onAddImage(img);
|
||||
setSelectedImageId(img.id);
|
||||
setSelectedId(null);
|
||||
setSelectedTableId(null);
|
||||
setSelectedLegendId(null);
|
||||
};
|
||||
|
||||
const displayRect = (vp: LayoutViewport): RectMm =>
|
||||
preview && preview.drag.mode === "edit" && preview.drag.id === vp.id ? preview.rect : vpRect(vp);
|
||||
|
||||
@@ -483,6 +560,28 @@ export function LayoutSheetPane({
|
||||
{drawBorder && (
|
||||
<rect x={5} y={5} width={sheet.w - 10} height={sheet.h - 10} fill="none" stroke="#111111" strokeWidth={0.35} pointerEvents="none" />
|
||||
)}
|
||||
{master?.posterHeader && (
|
||||
<g pointerEvents="none" data-poster-header>
|
||||
{posterHeaderItems(project, layout, master, sheet).map((it, i) =>
|
||||
it.kind === "rect" ? (
|
||||
<rect key={i} x={it.x} y={it.y} width={it.w} height={it.h} fill="none" stroke="#111111" strokeWidth={it.stroke} />
|
||||
) : (
|
||||
<text
|
||||
key={i}
|
||||
x={it.x}
|
||||
y={it.y}
|
||||
fontSize={it.sizeMm}
|
||||
fontFamily="Helvetica, Arial, sans-serif"
|
||||
fontWeight={it.bold ? "bold" : "normal"}
|
||||
textAnchor={it.align === "center" ? "middle" : it.align === "right" ? "end" : "start"}
|
||||
fill="#111111"
|
||||
>
|
||||
{it.text}
|
||||
</text>
|
||||
),
|
||||
)}
|
||||
</g>
|
||||
)}
|
||||
{master && (
|
||||
<g pointerEvents="none">
|
||||
<TitleBlockSvg sheet={sheet} tb={titleBlock} paper={layout.paper} orientation={layout.orientation} />
|
||||
@@ -519,6 +618,31 @@ export function LayoutSheetPane({
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{/* Bilder ([208]): über den Viewports, unter Legenden und Tabellen. */}
|
||||
{layoutImages.map((img) => {
|
||||
const r = imageRect(img);
|
||||
const g = imageGeometry({ ...img, xMm: r.xMm, yMm: r.yMm, widthMm: r.widthMm, heightMm: r.heightMm });
|
||||
return (
|
||||
<g key={img.id} data-image-id={img.id}>
|
||||
<svg x={g.clip.x} y={g.clip.y} width={g.clip.w} height={g.clip.h} viewBox={`${g.clip.x} ${g.clip.y} ${g.clip.w} ${g.clip.h}`} overflow="hidden" pointerEvents="none">
|
||||
<image href={img.src} x={g.draw.x} y={g.draw.y} width={g.draw.w} height={g.draw.h} preserveAspectRatio="none" />
|
||||
</svg>
|
||||
{img.id === selectedImageId && (
|
||||
<rect {...rectAttrs(r)} fill="none" stroke={ACCENT} strokeWidth={hair * 1.5} pointerEvents="none" data-image-selected />
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{/* Massstab unter jedem Viewport (Master „Massstabsangaben"). */}
|
||||
{master?.viewportScaleLabels &&
|
||||
layout.viewports.map((vp) => {
|
||||
const l = viewportScaleLabel(project, vp, sheet);
|
||||
return l ? (
|
||||
<text key={`sl-${vp.id}`} x={l.x} y={l.y} fontSize={l.sizeMm} fontFamily="Helvetica, Arial, sans-serif" fill="#111111" pointerEvents="none" data-scale-label>
|
||||
{l.text}
|
||||
</text>
|
||||
) : null;
|
||||
})}
|
||||
{(layout.legends ?? []).map((lg) => {
|
||||
const box = legendBox(project, layout, lg);
|
||||
return (
|
||||
@@ -608,6 +732,42 @@ export function LayoutSheetPane({
|
||||
))}
|
||||
</g>
|
||||
)}
|
||||
{/* Gewähltes Bild: Körper verschieben, Ecke unten rechts skalieren. */}
|
||||
{selectedImage && editable && (
|
||||
<g>
|
||||
<rect
|
||||
{...rectAttrs(imageRect(selectedImage))}
|
||||
fill="transparent"
|
||||
style={{ cursor: "move" }}
|
||||
data-image-body
|
||||
onPointerDown={(e) => startImageDrag(e, selectedImage, "body")}
|
||||
/>
|
||||
<rect
|
||||
x={imageRect(selectedImage).xMm + imageRect(selectedImage).widthMm - grip / 2}
|
||||
y={imageRect(selectedImage).yMm + imageRect(selectedImage).heightMm - grip / 2}
|
||||
width={grip}
|
||||
height={grip}
|
||||
fill="#ffffff"
|
||||
stroke={ACCENT}
|
||||
strokeWidth={hair * 1.5}
|
||||
style={{ cursor: "nwse-resize" }}
|
||||
data-image-grip="se"
|
||||
onPointerDown={(e) => startImageDrag(e, selectedImage, "se")}
|
||||
/>
|
||||
</g>
|
||||
)}
|
||||
{/* Hilfslinien des Gestaltungsrasters ([208]): nur am Bildschirm, nie im Druck. */}
|
||||
{(master?.guides ?? []).length > 0 && (
|
||||
<g pointerEvents="none" data-guides>
|
||||
{(master?.guides ?? []).map((gd, i) =>
|
||||
gd.axis === "x" ? (
|
||||
<line key={i} x1={gd.posMm} y1={0} x2={gd.posMm} y2={sheet.h} stroke="#06b6d4" strokeWidth={hair} strokeDasharray={`${hair * 6} ${hair * 4}`} opacity={0.7} />
|
||||
) : (
|
||||
<line key={i} x1={0} y1={gd.posMm} x2={sheet.w} y2={gd.posMm} stroke="#06b6d4" strokeWidth={hair} strokeDasharray={`${hair * 6} ${hair * 4}`} opacity={0.7} />
|
||||
),
|
||||
)}
|
||||
</g>
|
||||
)}
|
||||
{/* Viewport aufziehen: das ganze Blatt fängt den Zug. */}
|
||||
{placing && editable && (
|
||||
<rect
|
||||
@@ -667,10 +827,15 @@ export function LayoutSheetPane({
|
||||
const onTitle = !tableHit && !lg && !!master && !!handlers.onPatchTitleBlock &&
|
||||
mm.xMm >= tbb.xMm && mm.xMm <= tbb.xMm + tbb.widthMm && mm.yMm >= tbb.yMm && mm.yMm <= tbb.yMm + tbb.heightMm;
|
||||
setTitleBlockSelected(onTitle);
|
||||
const hit = tableHit || lg || onTitle ? null : pickViewport(layout.viewports, mm.xMm, mm.yMm, 0);
|
||||
const imgHit = tableHit || lg || onTitle
|
||||
? undefined
|
||||
: [...layoutImages].reverse().find((i) => mm.xMm >= i.xMm && mm.xMm <= i.xMm + i.widthMm && mm.yMm >= i.yMm && mm.yMm <= i.yMm + i.heightMm);
|
||||
setSelectedImageId(imgHit ? imgHit.id : null);
|
||||
const hit = tableHit || lg || onTitle || imgHit ? null : pickViewport(layout.viewports, mm.xMm, mm.yMm, 0);
|
||||
setSelectedId(hit ? hit.id : null);
|
||||
} else {
|
||||
setSelectedId(null);
|
||||
setSelectedImageId(null);
|
||||
setSelectedTableId(null);
|
||||
setSelectedLegendId(null);
|
||||
setTitleBlockSelected(false);
|
||||
@@ -737,6 +902,21 @@ export function LayoutSheetPane({
|
||||
<option key={src} value={src}>{tableSourceLabel(src)}</option>
|
||||
))}
|
||||
</select>
|
||||
<button className="nav-add" data-add-image disabled={toolInputActive} title={t("sheetImage.add")} onClick={() => fileRef.current?.click()}>
|
||||
+ {t("sheetImage.add")}
|
||||
</button>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/png,image/jpeg"
|
||||
style={{ display: "none" }}
|
||||
data-testid="sheet-image-input"
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (f) void addImageFile(f);
|
||||
}}
|
||||
/>
|
||||
<span style={{ flex: 1 }} />
|
||||
<button className="nav-add" onClick={() => planViewRef.current?.fit()} title={t("layouts.fit")}>
|
||||
{t("layouts.fit")}
|
||||
@@ -837,6 +1017,18 @@ export function LayoutSheetPane({
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Eigenschaften des gewählten Bilds ([208]). */}
|
||||
{selectedImage && !selectedVp && !selectedTable && (
|
||||
<SheetImageHud
|
||||
image={selectedImage}
|
||||
onPatch={(patch) => handlers.onPatchImage(selectedImage.id, patch, `sheetImage:${selectedImage.id}`)}
|
||||
onRemove={() => {
|
||||
handlers.onRemoveImage(selectedImage.id);
|
||||
setSelectedImageId(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Eigenschaften der gewählten Tabelle ([111]). */}
|
||||
{selectedTable && !selectedVp && (
|
||||
<SheetTableHud
|
||||
|
||||
@@ -23,6 +23,7 @@ import { getBlenderPath, setBlenderPath } from "../state/blenderSettings";
|
||||
import { buildPackage, currentRenderCamera, packageAsZip, renderHost, renderWithBlender } from "../state/renderAction";
|
||||
import { openExternalUrl } from "../native/blender";
|
||||
import { saveBinaryFile } from "../native/saveFile";
|
||||
import { defaultTargetLayout, placeImageOnLayout } from "../state/layoutImageActions";
|
||||
|
||||
type SizeId = "hd" | "uhd" | "a4" | "a3" | "a2" | "custom";
|
||||
const SIZES: Record<Exclude<SizeId, "custom">, () => { width: number; height: number }> = {
|
||||
@@ -59,6 +60,8 @@ export const RenderDialogHost = memo(function RenderDialogHost() {
|
||||
const [png, setPng] = useState<Uint8Array | null>(null);
|
||||
const [imageUrl, setImageUrl] = useState<string | null>(null);
|
||||
const abort = useRef<AbortController | null>(null);
|
||||
// [208] Ziel-Blatt für „Ins Layout einsetzen" (vorgewählt: das offene Blatt).
|
||||
const [layoutTarget, setLayoutTarget] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
setRenderDialogOpener(() => {
|
||||
@@ -70,6 +73,7 @@ export const RenderDialogHost = memo(function RenderDialogHost() {
|
||||
setMessage("");
|
||||
setPng(null);
|
||||
setHost(undefined);
|
||||
setLayoutTarget(defaultTargetLayout(st.project, st.activeLevelId)?.id ?? "");
|
||||
setOpen(true);
|
||||
void renderHost().then(setHost, () => setHost(null));
|
||||
});
|
||||
@@ -184,6 +188,16 @@ export const RenderDialogHost = memo(function RenderDialogHost() {
|
||||
}
|
||||
};
|
||||
|
||||
// [208] Rendering als Bild aufs gewählte Blatt (mittig, Seitenverhältnis gehalten, volle Auflösung).
|
||||
const placeInLayout = () => {
|
||||
if (!png) return;
|
||||
const st = getState();
|
||||
const layout = (st.project.layouts ?? []).find((l) => l.id === layoutTarget);
|
||||
const name = `${(st.project.name || "projekt").replace(/[^\w.-]+/g, "_")}-rendering.png`;
|
||||
if (layout && placeImageOnLayout(layout.id, name, png)) st.notify(t("render.toLayout.done", { name: layout.name }), "info");
|
||||
else st.notify(t("render.toLayout.none"), "warning");
|
||||
};
|
||||
|
||||
const savePng = async () => {
|
||||
if (!png) return;
|
||||
const st = getState();
|
||||
@@ -295,6 +309,18 @@ export const RenderDialogHost = memo(function RenderDialogHost() {
|
||||
<section className="imp-section" data-testid="render-result">
|
||||
<div className="imp-note">{t("render.done", { width: dims.width, height: dims.height })}</div>
|
||||
<img src={imageUrl} alt={t("render.title")} style={{ maxWidth: "100%", maxHeight: 360, display: "block", marginTop: 6 }} />
|
||||
{(getState().project.layouts ?? []).length > 0 && (
|
||||
<label style={{ display: "flex", gap: 6, alignItems: "center", marginTop: 8 }}>
|
||||
<span>{t("render.toLayout.target")}</span>
|
||||
<select className="imp-select" data-testid="render-layout-target" value={layoutTarget} onChange={(e) => setLayoutTarget(e.target.value)}>
|
||||
{(getState().project.layouts ?? []).map((l) => (
|
||||
<option key={l.id} value={l.id}>
|
||||
{l.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
@@ -319,6 +345,15 @@ export const RenderDialogHost = memo(function RenderDialogHost() {
|
||||
<button className="imp-btn" onClick={() => setPhase("setup")}>
|
||||
{t("render.again")}
|
||||
</button>
|
||||
<button
|
||||
className="imp-btn"
|
||||
data-testid="render-to-layout"
|
||||
disabled={(getState().project.layouts ?? []).length === 0}
|
||||
title={(getState().project.layouts ?? []).length === 0 ? t("render.toLayout.none") : undefined}
|
||||
onClick={placeInLayout}
|
||||
>
|
||||
{t("render.toLayout")}
|
||||
</button>
|
||||
<button className="imp-btn primary" data-testid="render-save" onClick={() => void savePng()}>
|
||||
{t("render.save")}
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
// Eigenschaften des gewählten Bilds auf dem Layout-Blatt ([208]): Lage, Breite (Höhe folgt dem Seitenverhältnis),
|
||||
// Zuschnitt in Prozent je Kante, Auflösung (dpi) und Löschen. Gestaltung wie die übrigen Blatt-HUDs.
|
||||
|
||||
import type { LayoutImage } from "../model/types";
|
||||
import { cropImage, imageGeometry, resizeImageWidth } from "../model/layoutImages";
|
||||
import { t } from "../i18n";
|
||||
|
||||
/** dpi, ab denen ein Bild für den Druck knapp wird (Plakate werden aus Distanz betrachtet). */
|
||||
export const LOW_DPI = 100;
|
||||
|
||||
type Edge = "left" | "right" | "top" | "bottom";
|
||||
|
||||
/** Zuschnitt-Anteile (0..1) → Randabstände je Kante in Prozent. */
|
||||
function edges(img: LayoutImage): Record<Edge, number> {
|
||||
const c = img.crop ?? { x: 0, y: 0, w: 1, h: 1 };
|
||||
return {
|
||||
left: Math.round(c.x * 1000) / 10,
|
||||
top: Math.round(c.y * 1000) / 10,
|
||||
right: Math.round((1 - c.x - c.w) * 1000) / 10,
|
||||
bottom: Math.round((1 - c.y - c.h) * 1000) / 10,
|
||||
};
|
||||
}
|
||||
|
||||
function cropFromEdges(e: Record<Edge, number>): LayoutImage["crop"] {
|
||||
const l = Math.min(98, Math.max(0, e.left)) / 100;
|
||||
const t0 = Math.min(98, Math.max(0, e.top)) / 100;
|
||||
const r = Math.min(98 - l * 100, Math.max(0, e.right)) / 100;
|
||||
const b = Math.min(98 - t0 * 100, Math.max(0, e.bottom)) / 100;
|
||||
if (l === 0 && t0 === 0 && r === 0 && b === 0) return undefined;
|
||||
return { x: l, y: t0, w: 1 - l - r, h: 1 - t0 - b };
|
||||
}
|
||||
|
||||
export function SheetImageHud({
|
||||
image,
|
||||
onPatch,
|
||||
onRemove,
|
||||
}: {
|
||||
image: LayoutImage;
|
||||
onPatch: (patch: Partial<Omit<LayoutImage, "id">>) => void;
|
||||
onRemove: () => void;
|
||||
}) {
|
||||
const e = edges(image);
|
||||
const dpi = Math.round(imageGeometry(image).dpi);
|
||||
const num = (v: number, set: (n: number) => void, testId?: string) => (
|
||||
<input
|
||||
type="number"
|
||||
className="res-input mono num"
|
||||
step={1}
|
||||
data-testid={testId}
|
||||
value={Math.round(v * 10) / 10}
|
||||
onChange={(ev) => {
|
||||
const n = parseFloat(ev.target.value);
|
||||
if (Number.isFinite(n)) set(n);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<div className="layout-sheet-hud" data-sheet-ui data-image-hud data-testid="image-hud">
|
||||
<div className="layout-sheet-hud-title">{image.name || t("sheetImage.title")}</div>
|
||||
<div className="layout-sheet-hud-row">
|
||||
<span>X / Y mm</span>
|
||||
<span className="layout-sheet-hud-scale">
|
||||
{num(image.xMm, (xMm) => onPatch({ xMm }), "image-x")}
|
||||
{num(image.yMm, (yMm) => onPatch({ yMm }), "image-y")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="layout-sheet-hud-row">
|
||||
<span>{t("sheetImage.width")}</span>
|
||||
<span className="layout-sheet-hud-scale">{num(image.widthMm, (w) => onPatch(resizeImageWidth(image, w)), "image-width")}</span>
|
||||
</div>
|
||||
<div className="layout-sheet-hud-size">
|
||||
{Math.round(image.widthMm)} × {Math.round(image.heightMm)} mm · {image.pixelWidth} × {image.pixelHeight} px
|
||||
</div>
|
||||
<div className="layout-sheet-hud-size" data-testid="image-dpi" style={dpi > 0 && dpi < LOW_DPI ? { color: "#b45309" } : undefined}>
|
||||
{dpi > 0 ? t("sheetImage.dpi", { dpi }) : ""}
|
||||
{dpi > 0 && dpi < LOW_DPI ? ` · ${t("sheetImage.lowDpi")}` : ""}
|
||||
</div>
|
||||
<div className="layout-sheet-hud-title" style={{ marginTop: 6 }}>{t("sheetImage.crop")}</div>
|
||||
{(["left", "right", "top", "bottom"] as Edge[]).map((k) => (
|
||||
<div key={k} className="layout-sheet-hud-row">
|
||||
<span>{t(`sheetImage.crop.${k}`)}</span>
|
||||
<span className="layout-sheet-hud-scale">
|
||||
{num(e[k], (v) => onPatch(cropImage(image, cropFromEdges({ ...e, [k]: v }))), `image-crop-${k}`)}%
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
<div className="layout-sheet-hud-actions">
|
||||
{image.crop && (
|
||||
<button className="nav-add" data-testid="image-crop-reset" onClick={() => onPatch(cropImage(image, undefined))} title={t("sheetImage.cropReset")}>
|
||||
{t("sheetImage.cropReset")}
|
||||
</button>
|
||||
)}
|
||||
<button className="nav-add" data-testid="image-remove" onClick={onRemove} title={t("sheetImage.remove")}>
|
||||
<span className="material-symbols-outlined" aria-hidden="true">delete</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user