Desktop app for designing parametric 3D models in CadQuery together with the coding agent of your choice
TypeScript 3d-modeling3d-printing3d-printing-toolsagentagentic-aiai-cadcadcadqueryclaude-codecodexelectronfemllmmacdmakeropencodeparametric-designpythonsteptext-to-cad
App: Markierung mit bearbeitbaren Formen (E16)
Kai-Jungsthoefeld45c1bcceca3
diff --git a/app/resources/template/AGENTS.md b/app/resources/template/AGENTS.mdindex 6561753..d75ebcc 100644--- a/app/resources/template/AGENTS.md+++ b/app/resources/template/AGENTS.md@@ -53,4 +53,8 @@ This folder is a git repository, and the `git` on your PATH is the one the app u## Feedback from the user-The user can send screenshots and sketches. They arrive as image files in `.cadide/feedback/`, the path is pasted into your input. Look at the image, compare it with the model, and change `model.py`.+The app pastes short notes into your input. The user adds their own words and sends them:++- `[Markierung: .cadide/feedback/markierung-20260930-1405.png]`: a picture of the 3D view (or a blank sketch) with the user's drawings: arrows, circles, handwritten text, often with dimensions. **Open the image file and look at it**, compare it with the model, then change the code. If the note says `zeigt den älteren Stand <hash>`, the picture shows that older commit, not the current code (`git show <hash>:model.py`). Leave the images where they are.+- `[Auswahl: Bauteil "…", model.py Zeile …]`: the part the user clicked, with the lines of its `add_part` call and the clicked face.+- `[Build-Fehler: …]`: the message of the last failed build.diff --git a/app/src/main/files.ts b/app/src/main/files.tsindex 23ce74e..76002df 100644--- a/app/src/main/files.ts+++ b/app/src/main/files.ts@@ -1,11 +1,13 @@import fs from 'node:fs';import path from 'node:path';-import type { FileNode, ImportResult } from '../shared/types';+import type { FeedbackResult, FileNode, ImportResult } from '../shared/types';const HIDDEN = new Set(['.git', '.cadide', '__pycache__', 'node_modules', '.venv', 'venv', 'env']);const MAX_ENTRIES = 2000;const MAX_DEPTH = 5;const MAX_IMPORT_BYTES = 500 * 1024 * 1024;+const MAX_FEEDBACK_BYTES = 64 * 1024 * 1024;+const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);/*** Kopiert gezogene Dateien nach inputs/ (E33). Der Agent bindet sie danach im Skript ein.@@ -32,16 +34,46 @@ export function importInputs(root: string, sources: string[]): ImportResult {return res;}+/**+ * Legt ein Bild der Markierung in .cadide/feedback/ ab (E16). Dort ist es nicht in Git (E11), wandert aber mit der ZIP.+ * Der Name trägt Datum und Uhrzeit, bei Gleichstand kommt „-2“ dazu. Vorhandenes wird nie überschrieben.+ */+export function saveFeedbackImage(root: string, png: unknown, when = new Date()): FeedbackResult {+ const bytes = png instanceof Uint8Array ? png : png instanceof ArrayBuffer ? new Uint8Array(png) : null;+ if (!bytes || bytes.length < PNG_SIGNATURE.length || !PNG_SIGNATURE.equals(bytes.subarray(0, PNG_SIGNATURE.length))) return { ok: false, error: 'Das ist kein PNG-Bild.' };+ if (bytes.length > MAX_FEEDBACK_BYTES) return { ok: false, error: 'Das Bild ist größer als 64 MB.' };+ const two = (n: number) => String(n).padStart(2, '0');+ const stem = `markierung-${when.getFullYear()}${two(when.getMonth() + 1)}${two(when.getDate())}-${two(when.getHours())}${two(when.getMinutes())}`;+ try {+ fs.mkdirSync(resolveInside(root, '.cadide/feedback'), { recursive: true });+ for (let i = 1; ; i++) {+ const rel = `.cadide/feedback/${stem}${i > 1 ? `-${i}` : ''}.png`;+ try {+ // „wx“: entsteht die Datei zwischen Prüfung und Schreiben, schlägt das Schreiben fehl statt zu überschreiben+ fs.writeFileSync(resolveInside(root, rel), bytes, { flag: 'wx' });+ return { ok: true, path: rel };+ } catch (e) { if ((e as NodeJS.ErrnoException).code !== 'EEXIST' || i > 999) throw e; }+ }+ } catch (e) { return { ok: false, error: e instanceof Error ? e.message : String(e) }; }+}++const exists = (p: string) => { try { fs.lstatSync(p); return true; } catch { return false; } };+/*** Loest einen Pfad relativ zum Projektordner auf und lehnt alles ab, was ausserhalb landet* (auch ueber Symlinks). Der Renderer bekommt so nie Zugriff auf andere Dateien des Rechners.*/export function resolveInside(root: string, rel: string): string {const abs = path.resolve(root, rel);- const realRoot = fs.realpathSync(root);- const real = fs.existsSync(abs) ? fs.realpathSync(abs) : abs;const inside = (p: string, r: string) => p === r || p.startsWith(r + path.sep);- if (!inside(abs, path.resolve(root)) || !inside(real, realRoot)) throw new Error(`Pfad liegt ausserhalb des Projekts: ${rel}`);+ const outside = () => new Error(`Pfad liegt ausserhalb des Projekts: ${rel}`);+ if (!inside(abs, path.resolve(root))) throw outside();+ // Gibt es das Ziel noch nicht, zählt der nächste vorhandene Ordner darüber. Sonst könnte ein Verweis weiter oben+ // (etwa .cadide als Verknüpfung nach außen) neue Dateien außerhalb des Projekts landen lassen.+ let probe = abs, rest = '';+ while (!exists(probe) && path.dirname(probe) !== probe) { rest = rest ? path.join(path.basename(probe), rest) : path.basename(probe); probe = path.dirname(probe); }+ const real = rest ? path.join(fs.realpathSync(probe), rest) : fs.realpathSync(probe);+ if (!inside(real, fs.realpathSync(root))) throw outside();return abs;}diff --git a/app/src/main/main.ts b/app/src/main/main.tsindex ecb7cbb..3a045ce 100644--- a/app/src/main/main.ts+++ b/app/src/main/main.ts@@ -3,7 +3,7 @@ import fs from 'node:fs';import path from 'node:path';import { detectAgents } from './agents';import { setTestAnswers } from './dialogs';-import { importInputs, listFiles, resolveInside } from './files';+import { importInputs, listFiles, resolveInside, saveFeedbackImage } from './files';import { ProjectController } from './projects';import { terminalEnv } from './terminals';import { thumbnailsDir } from './paths';@@ -50,6 +50,7 @@ function registerIpc(ctl: ProjectController): void {ipcMain.handle('fs:list', () => listFiles(dir()));ipcMain.handle('fs:import', (_e, paths: string[]) => importInputs(dir(), Array.isArray(paths) ? paths.map(String) : []));+ ipcMain.handle('fs:saveFeedback', (_e, png: unknown) => saveFeedbackImage(dir(), png));ipcMain.handle('fs:readText', (_e, rel: string) => fs.readFileSync(resolveInside(dir(), rel), 'utf8'));ipcMain.handle('fs:readBinary', (_e, rel: string) => {const b = fs.readFileSync(resolveInside(dir(), rel));diff --git a/app/src/preload/preload.ts b/app/src/preload/preload.tsindex 1088392..91e1146 100644--- a/app/src/preload/preload.ts+++ b/app/src/preload/preload.ts@@ -39,6 +39,7 @@ const api: CadideApi = {onChanged: (cb) => { ipcRenderer.on('fs:changed', () => cb()); },// Der Renderer kennt keine Dateipfade. Nur die Pfade gezogener Dateien gehen an den Hauptprozess, der prüft und kopiert.importFiles: (files) => ipcRenderer.invoke('fs:import', files.map((f) => webUtils.getPathForFile(f)).filter(Boolean)),+ saveFeedback: (png) => ipcRenderer.invoke('fs:saveFeedback', png),},term: {create: (opts) => ipcRenderer.invoke('term:create', opts),diff --git a/app/src/renderer/icons.ts b/app/src/renderer/icons.tsindex 1d90549..59c16c1 100644--- a/app/src/renderer/icons.ts+++ b/app/src/renderer/icons.ts@@ -33,6 +33,12 @@ const PATHS: Record<string, string> = {link: '<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/>',info: '<circle cx="12" cy="12" r="9"/><path d="M12 11v5M12 8v.01"/>', spin: '<path d="M12 3a9 9 0 1 1-9 9"/>',play: '<path d="M7 5v14l11-7z"/>',+ // Werkzeuge der Markierung+ pointer: '<path d="M6 3v16l4.2-4.1 2.9 6.2 2.6-1.2-2.9-6.1H18.5z"/>',+ trash: '<path d="M4 7h16M10 11v6M14 11v6"/><path d="M6 7l1 13h10l1-13M9 7V4h6v3"/>',+ pen: '<path d="M4 20h4L19 9l-4-4L4 16z"/>', arrow: '<path d="M5 19 19 5M9 5h10v10"/>',+ square: '<rect x="4" y="4" width="16" height="16" rx="1.5"/>', circle: '<circle cx="12" cy="12" r="8"/>',+ text: '<path d="M5 6V4h14v2M12 4v16M9 20h6"/>', undo: '<path d="M9 14 4 9l5-5"/><path d="M4 9h11a5 5 0 0 1 0 10h-3"/>',};export function icon(name: string, size = 16, stroke = 1.8): SVGSVGElement {diff --git a/app/src/renderer/index.html b/app/src/renderer/index.htmlindex f16de50..8aab8ea 100644--- a/app/src/renderer/index.html+++ b/app/src/renderer/index.html@@ -80,7 +80,7 @@<button disabled title="Messen kommt in einem späteren Schritt"><i data-icon="ruler"></i><span class="lbl">Messen</span></button><button disabled title="Die Schnittansicht kommt in einem späteren Schritt"><i data-icon="section"></i><span class="lbl">Schnitt</span></button><span class="vsep"></span>- <button class="hot" disabled title="Screenshot mit Markierung kommt im nächsten Schritt"><i data-icon="camera"></i><span class="lbl">Markieren</span></button>+ <button id="btn-mark" class="hot" title="Viewer-Bild markieren und an den Agenten geben"><i data-icon="camera"></i><span class="lbl">Markieren</span></button></div><div id="cube" class="cube">@@ -133,6 +133,34 @@<button id="btn-live" class="btn">Zurück zu Jetzt</button><button id="btn-restore" class="btn vio" title="Diesen Stand als neuen Stand übernehmen">Wiederherstellen</button></div>++ <!-- Markierung (E16): eingefrorenes Bild des Viewers oder leere Fläche zum Zeichnen -->+ <div id="markup" class="markup" hidden>+ <canvas id="mark-canvas" aria-label="Zeichenfläche"></canvas>+ <div class="mk-frame"></div>+ <input id="mark-text" class="mk-text" type="text" spellcheck="false" autocomplete="off" aria-label="Text der Markierung" hidden>+ <div id="mark-tools" class="float dock mk-tools" role="toolbar" aria-label="Markieren">+ <span class="mk-title"><i data-icon="camera" data-size="15"></i><b>Markieren</b></span><span class="vsep"></span>+ <button data-tool="select" aria-pressed="false" aria-label="Auswählen" title="Auswählen: Form anklicken und ziehen. Ecken skalieren (Umschalt: Seitenverhältnis), der Punkt oben dreht (Umschalt: 15°-Schritte), Entf löscht, Doppelklick bearbeitet Text"><i data-icon="pointer"></i></button>+ <button data-tool="pen" aria-pressed="true" aria-label="Stift" title="Stift: frei zeichnen"><i data-icon="pen"></i></button>+ <button data-tool="arrow" aria-pressed="false" aria-label="Pfeil" title="Pfeil: vom Anfang zur Spitze ziehen"><i data-icon="arrow"></i></button>+ <button data-tool="rect" aria-pressed="false" aria-label="Rechteck" title="Rechteck (mit Umschalt: Quadrat)"><i data-icon="square"></i></button>+ <button data-tool="ellipse" aria-pressed="false" aria-label="Kreis" title="Kreis oder Ellipse (mit Umschalt: Kreis)"><i data-icon="circle"></i></button>+ <button data-tool="text" aria-pressed="false" aria-label="Text" title="Text: an die Stelle klicken, schreiben, Enter. Klick auf einen Text bearbeitet ihn"><i data-icon="text"></i></button>+ <span class="vsep"></span>+ <button id="btn-mark-color" class="mk-colorbtn" aria-haspopup="menu" aria-expanded="false" aria-label="Farbe" title="Farbe (gilt auch für die ausgewählte Form)"><span id="mark-color-sw" class="swatch"></span><i data-icon="down" data-size="12" data-stroke="2"></i></button>+ <span class="vsep"></span>+ <button id="btn-mark-undo" aria-label="Rückgängig" title="Rückgängig (Strg Z), wiederholen mit Strg Y" disabled><i data-icon="undo"></i></button>+ <button id="btn-mark-delete" aria-label="Löschen" title="Ausgewählte Form löschen (Entf)" disabled><i data-icon="trash"></i></button>+ <span class="vsep"></span>+ <button id="btn-mark-blank" aria-pressed="false" title="Auf leerer Fläche zeichnen statt auf dem Viewer-Bild"><i data-icon="image"></i><span class="lbl">Leere Fläche</span></button>+ </div>+ <div id="mark-hint" class="float mk-hint"></div>+ <div class="mk-actions">+ <button id="btn-mark-cancel" class="btn" title="Zeichnung verwerfen (Escape)">Abbrechen</button>+ <button id="btn-mark-send" class="btn primary" title="Als PNG in .cadide/feedback/ speichern und den Pfad in die Eingabe des Agenten einfügen"><i data-icon="send" data-size="15" data-stroke="2"></i>An Agent geben</button>+ </div>+ </div></section><div id="versions" class="tl">@@ -153,7 +181,7 @@<div id="term-panes"></div><div id="handoff" class="handoff"><span class="c3">Einfügen:</span><button id="btn-ins-sel" class="btn sm" disabled title="Bauteil, Datei und Zeilen der Auswahl in die Eingabe einfügen"><i data-icon="target" data-size="13" data-stroke="2"></i>Auswahl</button>- <button id="btn-ins-mark" class="btn sm" disabled title="Screenshot mit Markierung kommt im nächsten Schritt"><i data-icon="image" data-size="13" data-stroke="2"></i>Markierung</button>+ <button id="btn-ins-mark" class="btn sm" title="Viewer-Bild markieren und den Pfad einfügen"><i data-icon="image" data-size="13" data-stroke="2"></i>Markierung</button><button id="btn-ins-err" class="btn sm" disabled title="Meldung des letzten Builds in die Eingabe einfügen"><i data-icon="alert" data-size="13" data-stroke="2"></i>Build-Fehler</button></div><div id="agent-strip" class="strip" hidden>@@ -220,6 +248,25 @@<div id="menu-ctx" class="menu" role="menu" hidden></div>+ <div id="menu-mark-color" class="menu" role="menu" aria-label="Farbe der Markierung" hidden>+ <div class="mh">FARBE</div>+ <div class="mk-palette">+ <button data-color="orange" aria-pressed="true" aria-label="Orange" title="Orange" style="--c:var(--mk-orange)"></button>+ <button data-color="red" aria-pressed="false" aria-label="Rot" title="Rot" style="--c:var(--mk-red)"></button>+ <button data-color="pink" aria-pressed="false" aria-label="Pink" title="Pink" style="--c:var(--mk-pink)"></button>+ <button data-color="violet" aria-pressed="false" aria-label="Violett" title="Violett" style="--c:var(--mk-violet)"></button>+ <button data-color="blue" aria-pressed="false" aria-label="Blau" title="Blau" style="--c:var(--mk-blue)"></button>+ <button data-color="cyan" aria-pressed="false" aria-label="Türkis" title="Türkis" style="--c:var(--mk-cyan)"></button>+ <button data-color="green" aria-pressed="false" aria-label="Grün" title="Grün" style="--c:var(--mk-green)"></button>+ <button data-color="yellow" aria-pressed="false" aria-label="Gelb" title="Gelb" style="--c:var(--mk-yellow)"></button>+ <button data-color="white" aria-pressed="false" aria-label="Weiß" title="Weiß" style="--c:var(--mk-white)"></button>+ <button data-color="black" aria-pressed="false" aria-label="Schwarz" title="Schwarz" style="--c:var(--mk-black)"></button>+ </div>+ <div class="msep"></div>+ <label class="mi keep mk-custom" title="Beliebige Farbe im Farbdialog wählen"><input id="mark-color-custom" type="color" value="#f29a38"><span>Eigene Farbe …</span></label>+ <div class="mnote">Ist eine Form ausgewählt, bekommt sie die Farbe gleich mit.</div>+ </div>+<div id="start" class="start" hidden><header class="top"><span class="logo"><i data-icon="cube" data-size="22"></i></span><b class="brand">CAD-IDE</b><span class="grow"></span><button id="btn-start-close" class="btn">Zurück zum Modell</button></header>diff --git a/app/src/renderer/main.ts b/app/src/renderer/main.tsindex 399adbc..8838ccb 100644--- a/app/src/renderer/main.ts+++ b/app/src/renderer/main.ts@@ -2,6 +2,7 @@ import type { AgentInfo, BuildStatus, ModelMap, PartMap, PreviewResult, ProjectIimport { CodePanel, codeRows } from './code';import { FileTree, TEXT_EXT } from './filetree';import { hydrateIcons, icon } from './icons';+import { Markup } from './markup';import { PartsCard } from './parts';import { TerminalTabs } from './terminals';import { $, el, fmtWhen, menuItem, menus, toast } from './ui';@@ -184,16 +185,56 @@ function errorText(): string | null {return `[Build-Fehler: ${where}${e.message.replace(/\s+/g, ' ').trim().slice(0, 400)}] `;}-/** Fügt Text in die Eingabezeile des aktiven Terminals ein. Abschicken macht der Nutzer selbst (E11). */-function insertToAgent(text: string | null): void {+/** Fügt Text in die Eingabezeile des aktiven Terminals ein. Abschicken macht der Nutzer selbst (E11). `done` steht vor der Meldung. */+function insertToAgent(text: string | null, done?: string): void {if (!text) return;- if (!terminals.count) { toast('Kein Terminal offen. Starte über + einen Agenten oder ein Terminal.', 'error'); return; }+ const pre = done ? `${done}\n` : '';+ if (!terminals.count) { toast(`${pre}Kein Terminal offen. Starte über + einen Agenten oder ein Terminal.`, 'error'); return; }setAgentCollapsed(false);const title = terminals.insert(text);- if (title) toast(`In die Eingabe von ${title} eingefügt. Enter schickt ab.`);- else toast('Das Terminal ist beendet. Öffne über + ein neues.', 'error');+ if (title) toast(`${pre}In die Eingabe von ${title} eingefügt. Enter schickt ab.`);+ else toast(`${pre}Das Terminal ist beendet. Öffne über + ein neues.`, 'error');}+// ---- Markierung (E16) -------------------------------------------------------------------------------------------++const markup = new Markup({+ viewer: $('viewer'), layer: $('markup'), canvas: $<HTMLCanvasElement>('mark-canvas'), text: $<HTMLInputElement>('mark-text'),+ hint: $('mark-hint'), tools: $('mark-tools'), undo: $<HTMLButtonElement>('btn-mark-undo'), del: $<HTMLButtonElement>('btn-mark-delete'),+ blank: $<HTMLButtonElement>('btn-mark-blank'), colorBtn: $<HTMLButtonElement>('btn-mark-color'), colorSwatch: $('mark-color-sw'),+ palette: $('menu-mark-color'), custom: $<HTMLInputElement>('mark-color-custom'),+});++/** Friert die Ansicht ein, wie sie gerade ist (auch als Vorschau eines alten Stands, nur ohne Auswahl). Ohne Modell: leere Fläche. */+function startMarkup(): void {+ if (!project || markup.active) return;+ menus.close();+ markup.open(viewer.partList().length ? viewer.snapshot() : null);+}++async function sendMarkup(): Promise<void> {+ const btn = $<HTMLButtonElement>('btn-mark-send');+ if (btn.disabled || !markup.active) return;+ btn.disabled = true;+ try {+ const r = await api.fs.saveFeedback(await markup.image());+ // Ging das Speichern schief, bleibt die Zeichnung offen: Nichts geht verloren, der Nutzer kann es noch einmal versuchen+ if (!r.ok || !r.path) { toast(`Die Markierung ließ sich nicht speichern: ${r.error ?? 'unbekannter Fehler'}`, 'error'); return; }+ const old = versions.previewed;+ markup.close();+ // Zeigt das Bild einen alten Stand, soll der Agent das wissen (sonst vergleicht er es mit dem aktuellen Code)+ const note = old ? `, zeigt den älteren Stand ${old.short} "${old.subject.slice(0, 80)}"` : '';+ insertToAgent(`[Markierung: ${r.path}${note}] `, `Markierung gespeichert: ${r.path}`);+ } catch (e) {+ toast(`Die Markierung ließ sich nicht speichern: ${e instanceof Error ? e.message : String(e)}`, 'error');+ } finally { btn.disabled = false; }+}++$('btn-mark').addEventListener('click', startMarkup);+$('btn-ins-mark').addEventListener('click', startMarkup);+$('btn-mark-cancel').addEventListener('click', () => markup.close());+$('btn-mark-send').addEventListener('click', () => void sendMarkup());+function openPartMenu(id: string, x: number, y: number): void {const e = partEntry(id);const visible = viewer.isVisible(id);@@ -339,6 +380,7 @@ async function onProject(p: ProjectInfo): Promise<void> {map = null;lastOkAt = null;textCache.clear();+ markup.close();viewer.clear();versions.reset();terminals.closeAll();@@ -677,6 +719,9 @@ if (api.testMode) {partSize: (name: string) => { const p = viewer.partList().find((x) => x.name === name); return p ? viewer.partSize(p.id) : null; },versionsUi: () => ({ restoreHidden: $('btn-restore').hidden, problem: $('vproblem').hidden ? '' : $('vproblem').textContent }),selectionText, errorText,+ markup: () => markup.state(),+ markPixel: (x: number, y: number) => markup.pixel(x, y),+ markHandles: () => markup.handles(),insert: (text: string) => insertToAgent(text),showPanel: (p: PanelName | null) => showPanel(p),showStart: (on: boolean) => showStart(on),diff --git a/app/src/renderer/markup.ts b/app/src/renderer/markup.tsnew file mode 100644index 0000000..74f67cb--- /dev/null+++ b/app/src/renderer/markup.ts@@ -0,0 +1,630 @@+import { el, fmtWhen, menus, toast } from './ui';++/** Werkzeuge der Markierung (E16). Nichts ist maßhaltig, Maße schreibt man als Text daneben. */+export type MarkTool = 'select' | 'pen' | 'arrow' | 'rect' | 'ellipse' | 'text';+type DrawTool = Exclude<MarkTool, 'select'>;+type Pt = [number, number];++/**+ * Eine gezeichnete Form. Die Geometrie liegt unskaliert um den Mittelpunkt (x, y), dazu kommen Drehung und Skalierung.+ * So lassen sich Formen nachträglich verschieben, drehen und skalieren, ohne dass die Strichstärke mitwächst.+ * Text hat keine Punkte, sondern die Größe seines Kastens (`box`).+ */+interface Shape { id: number; tool: DrawTool; color: string; pts: Pt[]; text?: string; box?: Pt; x: number; y: number; rot: number; sx: number; sy: number }++type Handle = { kind: 'move' } | { kind: 'rotate' } | { kind: 'scale'; corner: number };+type Drag =+ | { kind: 'draw'; tool: DrawTool; color: string; raw: Pt[] }+ | { kind: 'move' | 'rotate' | 'scale'; corner: number; id: number; start: Pt; orig: Shape; before: Shape[]; moved: boolean };++interface Ui {+ /** Bekommt die Klasse `marking`: Bauteilkarte, Würfel und Karten treten zurück, damit das Bild sauber bleibt. */+ viewer: HTMLElement;+ layer: HTMLElement;+ canvas: HTMLCanvasElement;+ text: HTMLInputElement;+ hint: HTMLElement;+ /** Werkzeugleiste mit Knöpfen `[data-tool]`. */+ tools: HTMLElement;+ undo: HTMLButtonElement;+ del: HTMLButtonElement;+ blank: HTMLButtonElement;+ /** Knopf mit der aktuellen Farbe, darunter das Menü mit Knöpfen `[data-color]` und der eigenen Farbe. */+ colorBtn: HTMLButtonElement;+ colorSwatch: HTMLElement;+ palette: HTMLElement;+ custom: HTMLInputElement;+}++const LINE = 3; // Strichstärke in CSS-Pixeln+const FONT = 19;+/** Rand plus Innenabstand des Textfelds: So steht der Text im Bild dort, wo er beim Tippen stand. */+const TEXT_PAD: Pt = [5, 3];+/** Abstand des Auswahlrahmens zur Form, Abstand des Drehgriffs über dem Rahmen, Fangradius der Griffe und der Linien (CSS-Pixel). */+const SEL_PAD = 6, ROT_GAP = 24, GRAB = 9, TOL = 6;+const css = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();+const clone = <T>(v: T): T => structuredClone(v);+const turn = (a: number, u: number, v: number): Pt => [u * Math.cos(a) - v * Math.sin(a), u * Math.sin(a) + v * Math.cos(a)];+const dist = (a: Pt, b: Pt) => Math.hypot(a[0] - b[0], a[1] - b[1]);++/**+ * Zeichnen auf einem eingefrorenen Bild des Viewers oder auf leerer Fläche (E16). Das Ergebnis ist ein PNG in voller+ * Auflösung. Gespeichert und an den Agenten gegeben wird es in main.ts, hier entsteht nur das Bild.+ * Jede Form bleibt ein eigenes Objekt: Mit „Auswählen“ lässt sie sich verschieben, drehen, skalieren, umfärben und löschen.+ * Formen liegen in CSS-Pixeln vor und werden bei jeder Änderung komplett neu gezeichnet (wenige Formen, das reicht).+ */+export class Markup {+ private shapes: Shape[] = [];+ /** Stände vor jeder Änderung, für Rückgängig und Wiederholen. */+ private history: Shape[][] = [];+ private future: Shape[][] = [];+ private nextId = 1;+ private selected: number | null = null;+ private drag: Drag | null = null;+ private tool: MarkTool = 'pen';+ private color: string;+ /** Name der Farbe aus der Palette, null bei eigener Farbe. */+ private colorName: string | null = 'orange';+ private bg: HTMLCanvasElement | null = null;+ private blankBg = false;+ private scale = 1;+ private size: Pt = [0, 0];+ private takenAt = Date.now();+ /** Offenes Textfeld: neuer Text an `p` (oben links) oder ein vorhandener Text (`id`). */+ private editing: { id: number | null; p: Pt; color: string } | null = null;+ private escUntil = 0;+ private lastPress: { id: number; t: number } | null = null;++ constructor(private ui: Ui) {+ this.color = css('--mk-orange') || '#f29a38';+ ui.tools.querySelectorAll<HTMLButtonElement>('[data-tool]').forEach((b) => b.addEventListener('click', () => this.setTool(b.dataset.tool as MarkTool)));+ ui.colorBtn.addEventListener('click', () => menus.toggle(ui.palette, ui.colorBtn));+ ui.palette.querySelectorAll<HTMLButtonElement>('[data-color]').forEach((b) => b.addEventListener('click', () => {+ this.setColor(css(`--mk-${b.dataset.color}`) || this.color, b.dataset.color!);+ menus.close();+ }));+ // „change“ statt „input“: Der Farbdialog meldet sich so nur einmal, sonst entstünde pro Zwischenwert ein Rückgängig-Schritt+ ui.custom.addEventListener('change', () => this.setColor(ui.custom.value, null));+ ui.undo.addEventListener('click', () => this.undo());+ ui.del.addEventListener('click', () => this.removeSelected());+ ui.blank.addEventListener('click', () => { this.blankBg = !this.blankBg || !this.bg; this.renderUi(); this.draw(); });+ this.installPointer();+ ui.text.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') { e.preventDefault(); this.commitText(); }+ else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); this.cancelText(); }+ });+ // Übernommen wird mit Enter, beim nächsten Klick auf die Zeichenfläche und beim Abschicken, bewusst nicht beim+ // Verlassen des Felds: Ein Blur-Ereignis käme je nach Klickreihenfolge einem gerade neu geöffneten Feld in die Quere.+ window.addEventListener('keydown', (e) => {+ // Im Terminal gehört Escape dem Agenten (Claude Code unterbricht damit), im Textfeld dem Textfeld+ if (!this.active || e.target === ui.text || (e.target as HTMLElement | null)?.closest?.('#terminals')) return;+ const k = e.key.length === 1 ? e.key.toLowerCase() : e.key;+ if (k === 'Escape') { e.preventDefault(); this.escape(); }+ else if (e.ctrlKey && !e.altKey && (k === 'y' || (k === 'z' && e.shiftKey))) { e.preventDefault(); this.redo(); }+ else if (e.ctrlKey && !e.altKey && k === 'z') { e.preventDefault(); this.undo(); }+ else if ((k === 'Delete' || k === 'Backspace') && this.selected != null) { e.preventDefault(); this.removeSelected(); }+ else if (k.startsWith('Arrow') && this.selected != null && !e.ctrlKey && !e.altKey) { e.preventDefault(); this.nudge(k, e.shiftKey ? 10 : 1); }+ });+ }++ get active(): boolean { return !this.ui.layer.hidden; }++ /** Öffnet die Zeichenfläche über dem Viewer. `snapshot` ist das Bild des Viewers in Gerätepixeln, ohne Bild bleibt nur die leere Fläche. */+ open(snapshot: HTMLCanvasElement | null): void {+ const w = this.ui.viewer.clientWidth, h = this.ui.viewer.clientHeight;+ this.bg = snapshot && snapshot.width && snapshot.height ? snapshot : null;+ this.scale = this.bg ? this.bg.width / w : window.devicePixelRatio || 1;+ this.size = [w, h];+ this.reset();+ this.blankBg = !this.bg;+ this.takenAt = Date.now();+ const c = this.ui.canvas;+ // Feste Größe für die ganze Sitzung: Ändert sich das Fenster, bleibt das Bild, wie es aufgenommen wurde+ c.width = this.bg ? this.bg.width : Math.round(w * this.scale);+ c.height = this.bg ? this.bg.height : Math.round(h * this.scale);+ c.style.width = `${w}px`;+ c.style.height = `${h}px`;+ this.ui.layer.hidden = false;+ this.ui.viewer.classList.add('marking');+ this.ui.blank.disabled = !this.bg;+ this.renderUi();+ this.draw();+ }++ /** Schließt die Zeichenfläche und verwirft die Zeichnung. */+ close(): void {+ if (menus.isOpen(this.ui.palette)) menus.close();+ this.reset();+ this.bg = null;+ this.ui.layer.hidden = true;+ this.ui.viewer.classList.remove('marking');+ this.ui.canvas.width = 0; // Speicher des Bildes freigeben+ this.ui.canvas.height = 0;+ }++ private reset(): void {+ this.shapes = [];+ this.history = [];+ this.future = [];+ this.selected = null;+ this.drag = null;+ this.editing = null;+ this.lastPress = null;+ this.escUntil = 0;+ this.ui.text.hidden = true;+ }++ undo(): void {+ if (this.editing) { this.cancelText(); return; }+ const prev = this.history.pop();+ if (!prev) return;+ this.future.push(clone(this.shapes));+ this.shapes = prev;+ this.changed();+ }++ redo(): void {+ const next = this.future.pop();+ if (!next) return;+ this.history.push(clone(this.shapes));+ this.shapes = next;+ this.changed();+ }++ /** PNG mit Hintergrund in voller Auflösung, ohne Auswahlrahmen. Ein offenes Textfeld wird vorher übernommen. */+ async image(): Promise<Uint8Array> {+ this.commitText();+ this.drag = null;+ this.draw(false);+ const blob = await new Promise<Blob | null>((r) => this.ui.canvas.toBlob(r, 'image/png'));+ this.draw();+ if (!blob) throw new Error('Das Bild ließ sich nicht erzeugen.');+ return new Uint8Array(await blob.arrayBuffer());+ }++ // ---- Bearbeiten -----------------------------------------------------------------------------------------------++ private sel(): Shape | undefined { return this.selected == null ? undefined : this.shapes.find((s) => s.id === this.selected); }++ /** Vor jeder Änderung aufrufen: legt den bisherigen Stand für Rückgängig ab. */+ private remember(before: Shape[] = clone(this.shapes)): void {+ this.history.push(before);+ this.future = [];+ }++ private changed(): void {+ if (!this.sel()) this.selected = null;+ this.renderUi();+ this.draw();+ }++ private setTool(t: MarkTool): void {+ this.tool = t;+ if (t !== 'select') this.selected = null;+ this.renderUi();+ this.draw();+ }++ /** Neue Farbe für alles Folgende. Eine ausgewählte Form und ein offenes Textfeld bekommen sie gleich mit. */+ private setColor(hex: string, name: string | null): void {+ this.color = hex;+ this.colorName = name;+ const s = this.sel();+ if (s && s.color !== hex) { this.remember(); s.color = hex; }+ if (this.editing) { this.editing.color = hex; this.ui.text.style.color = hex; }+ this.renderUi();+ this.draw();+ }++ private removeSelected(): void {+ const s = this.sel();+ if (!s) return;+ this.remember();+ this.shapes = this.shapes.filter((x) => x !== s);+ this.changed();+ }++ private nudge(key: string, d: number): void {+ const s = this.sel();+ if (!s) return;+ this.remember();+ if (key === 'ArrowLeft') s.x -= d; else if (key === 'ArrowRight') s.x += d;+ else if (key === 'ArrowUp') s.y -= d; else if (key === 'ArrowDown') s.y += d;+ this.changed();+ }++ /** Escape hebt zuerst die Auswahl auf. Ohne Zeichnung schließt es sofort, mit Zeichnung erst beim zweiten Mal. */+ private escape(): void {+ if (this.selected != null) { this.selected = null; this.changed(); return; }+ if (!this.shapes.length || Date.now() < this.escUntil) { this.close(); return; }+ this.escUntil = Date.now() + 3000;+ toast('Noch einmal Escape verwirft die Zeichnung.', 'info');+ }++ // ---- Geometrie ------------------------------------------------------------------------------------------------++ private makeShape(tool: DrawTool, color: string, raw: Pt[], id = 0): Shape {+ const xs = raw.map((p) => p[0]), ys = raw.map((p) => p[1]);+ const x = (Math.min(...xs) + Math.max(...xs)) / 2, y = (Math.min(...ys) + Math.max(...ys)) / 2;+ return { id, tool, color, pts: raw.map((p): Pt => [p[0] - x, p[1] - y]), x, y, rot: 0, sx: 1, sy: 1 };+ }++ /** Kasten der Form im eigenen, unskalierten System: [x0, y0, x1, y1]. */+ private bounds(s: Shape): [number, number, number, number] {+ if (s.box) return [-s.box[0] / 2, -s.box[1] / 2, s.box[0] / 2, s.box[1] / 2];+ const xs = s.pts.map((p) => p[0]), ys = s.pts.map((p) => p[1]);+ return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];+ }++ private world(s: Shape, p: Pt): Pt {+ const [u, v] = turn(s.rot, p[0] * s.sx, p[1] * s.sy);+ return [s.x + u, s.y + v];+ }++ /** Punkte auf der Zeichenfläche: die Linie (Stift, Pfeil) bzw. der geschlossene Umriss (Rechteck, Ellipse). */+ private outline(s: Shape): Pt[] {+ if (s.tool === 'pen' || s.tool === 'arrow') return s.pts.map((p) => this.world(s, p));+ const [x0, y0, x1, y1] = this.bounds(s);+ if (s.tool === 'rect') return ([[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]] as Pt[]).map((p) => this.world(s, p));+ // Die Ellipse als Vieleck: So bleibt die Strichstärke beim Skalieren gleich+ const cx = (x0 + x1) / 2, cy = (y0 + y1) / 2, rx = (x1 - x0) / 2, ry = (y1 - y0) / 2;+ return Array.from({ length: 73 }, (_, i) => this.world(s, [cx + rx * Math.cos((i / 72) * 2 * Math.PI), cy + ry * Math.sin((i / 72) * 2 * Math.PI)]));+ }++ /** Auswahlrahmen: Ecken (oben links im Uhrzeigersinn), Drehgriff und der Rahmen im gedrehten System der Form. */+ private frame(s: Shape) {+ const [x0, y0, x1, y1] = this.bounds(s);+ const a = x0 * s.sx - SEL_PAD, b = x1 * s.sx + SEL_PAD, c = y0 * s.sy - SEL_PAD, d = y1 * s.sy + SEL_PAD;+ const at = (u: number, v: number): Pt => { const [x, y] = turn(s.rot, u, v); return [s.x + x, s.y + y]; };+ return { corners: [at(a, c), at(b, c), at(b, d), at(a, d)], top: at((a + b) / 2, c), rotate: at((a + b) / 2, c - ROT_GAP), rect: [a, c, b, d] as const };+ }++ private hits(s: Shape, p: Pt): boolean {+ if (s.tool === 'text') {+ const [x0, y0, x1, y1] = this.bounds(s);+ const [u, v] = turn(-s.rot, p[0] - s.x, p[1] - s.y);+ return u / s.sx >= x0 && u / s.sx <= x1 && v / s.sy >= y0 && v / s.sy <= y1;+ }+ // Rechteck und Ellipse sind hohl: Getroffen wird die Linie, damit Formen darunter erreichbar bleiben+ const o = this.outline(s);+ if (o.length === 1) return dist(p, o[0]) <= TOL;+ for (let i = 1; i < o.length; i++) if (segDist(p, o[i - 1], o[i]) <= TOL) return true;+ return false;+ }++ /** Oberste Form an dieser Stelle. */+ private hit(p: Pt): Shape | undefined {+ for (let i = this.shapes.length - 1; i >= 0; i--) if (this.hits(this.shapes[i], p)) return this.shapes[i];+ return undefined;+ }++ private handleAt(s: Shape, p: Pt): Handle | null {+ const f = this.frame(s);+ if (dist(p, f.rotate) <= GRAB) return { kind: 'rotate' };+ const i = f.corners.findIndex((q) => dist(p, q) <= GRAB);+ if (i >= 0) return { kind: 'scale', corner: i };+ const [u, v] = turn(-s.rot, p[0] - s.x, p[1] - s.y);+ const [a, c, b, d] = f.rect;+ return u >= a && u <= b && v >= c && v <= d ? { kind: 'move' } : null;+ }++ /** Skalieren an einer Ecke: Die gegenüberliegende Ecke bleibt stehen. Text und Umschalt behalten das Seitenverhältnis. */+ private scaleTo(s: Shape, o: Shape, corner: number, p: Pt, keep: boolean): void {+ const [x0, y0, x1, y1] = this.bounds(o);+ const w = x1 - x0, h = y1 - y0;+ const anchor = this.frame(o).corners[(corner + 2) % 4];+ const dx = corner === 1 || corner === 2 ? 1 : -1, dy = corner >= 2 ? 1 : -1;+ const [u, v] = turn(-o.rot, p[0] - anchor[0], p[1] - anchor[1]);+ // Ohne Ausdehnung in einer Richtung (etwa eine waagerechte Linie) wird in dieser Richtung nicht skaliert+ let sx = w > 1 ? Math.max(0.05, (dx * u - 2 * SEL_PAD) / w) : o.sx;+ let sy = h > 1 ? Math.max(0.05, (dy * v - 2 * SEL_PAD) / h) : o.sy;+ if (keep || o.tool === 'text') {+ const f = Math.max(w > 1 ? sx / o.sx : 0, h > 1 ? sy / o.sy : 0) || 1;+ sx = o.sx * f;+ sy = o.sy * f;+ }+ const [ax, ay] = turn(o.rot, dx > 0 ? x0 * sx - SEL_PAD : x1 * sx + SEL_PAD, dy > 0 ? y0 * sy - SEL_PAD : y1 * sy + SEL_PAD);+ s.sx = sx; s.sy = sy;+ s.x = anchor[0] - ax; s.y = anchor[1] - ay;+ }++ // ---- Eingabe --------------------------------------------------------------------------------------------------++ private at(e: PointerEvent): Pt {+ const r = this.ui.canvas.getBoundingClientRect();+ return [Math.max(0, Math.min(this.size[0], e.clientX - r.left)), Math.max(0, Math.min(this.size[1], e.clientY - r.top))];+ }++ private installPointer(): void {+ const c = this.ui.canvas;+ c.addEventListener('pointerdown', (e) => {+ if (e.button !== 0) return;+ e.preventDefault(); // kein Fokuswechsel, sonst schlösse sich ein gerade geöffnetes Textfeld sofort wieder+ this.commitText();+ const p = this.at(e);+ if (this.tool === 'select') this.pressSelect(p);+ else if (this.tool === 'text') {+ const t = this.hit(p);+ if (t?.tool === 'text') this.editText(t); else this.openText(p);+ return;+ } else this.drag = { kind: 'draw', tool: this.tool, color: this.color, raw: [p] };+ if (this.drag) try { c.setPointerCapture(e.pointerId); } catch { /* synthetische Ereignisse (Tests) haben keinen aktiven Zeiger */ }+ this.draw();+ });+ c.addEventListener('pointermove', (e) => {+ const p = this.at(e);+ if (!this.drag) { if (this.tool === 'select') c.style.cursor = this.cursorAt(p); return; }+ this.dragTo(p, e.shiftKey);+ this.draw();+ });+ c.addEventListener('pointerup', (e) => {+ const d = this.drag;+ if (!d) return;+ this.dragTo(this.at(e), e.shiftKey);+ this.drag = null;+ if (d.kind === 'draw') {+ const [a, b = a] = d.raw;+ // Ein bloßer Klick ergibt mit dem Stift einen Punkt, bei den Formen nichts+ if (d.tool === 'pen' || dist(a, b) >= 4) { this.remember(); this.shapes.push(this.makeShape(d.tool, d.color, d.raw, this.nextId++)); }+ } else if (d.moved) this.remember(d.before);+ this.renderUi();+ this.draw();+ });+ c.addEventListener('pointercancel', () => {+ const d = this.drag;+ this.drag = null;+ if (d && d.kind !== 'draw' && d.moved) this.shapes = d.before; // abgebrochen: zurück zum Stand davor+ this.changed();+ });+ }++ /** Klick mit „Auswählen“: Griff der gewählten Form, sonst die oberste Form an der Stelle, sonst Auswahl aufheben. */+ private pressSelect(p: Pt): void {+ const cur = this.sel();+ let target = cur;+ let h = cur ? this.handleAt(cur, p) : null;+ if (!h) { target = this.hit(p); h = target ? { kind: 'move' } : null; }+ if (!target || !h) { this.selected = null; this.lastPress = null; this.renderUi(); return; }+ const now = Date.now();+ if (h.kind === 'move' && target.tool === 'text' && this.lastPress?.id === target.id && now - this.lastPress.t < 450) {+ this.lastPress = null; // Doppelklick auf einen Text: bearbeiten+ this.editText(target);+ return;+ }+ this.lastPress = { id: target.id, t: now };+ this.selected = target.id;+ this.drag = { kind: h.kind, corner: h.kind === 'scale' ? h.corner : 0, id: target.id, start: p, orig: clone(target), before: clone(this.shapes), moved: false };+ this.renderUi();+ }++ private dragTo(p: Pt, shift: boolean): void {+ const d = this.drag!;+ if (d.kind === 'draw') {+ if (d.tool === 'pen') { if (dist(p, d.raw[d.raw.length - 1]) >= 1.5) d.raw.push(p); }+ else d.raw[1] = shift && (d.tool === 'rect' || d.tool === 'ellipse') ? square(d.raw[0], p) : p;+ return;+ }+ const s = this.shapes.find((x) => x.id === d.id);+ if (!s || (!d.moved && dist(p, d.start) < 1)) return;+ d.moved = true;+ const o = d.orig;+ if (d.kind === 'move') { s.x = o.x + p[0] - d.start[0]; s.y = o.y + p[1] - d.start[1]; }+ else if (d.kind === 'rotate') {+ let r = o.rot + Math.atan2(p[1] - o.y, p[0] - o.x) - Math.atan2(d.start[1] - o.y, d.start[0] - o.x);+ if (shift) r = Math.round(r / (Math.PI / 12)) * (Math.PI / 12); // Umschalt: in 15-Grad-Schritten+ s.rot = r;+ } else this.scaleTo(s, o, d.corner, p, shift);+ }++ private cursorAt(p: Pt): string {+ const s = this.sel();+ const h = s ? this.handleAt(s, p) : null;+ if (h?.kind === 'rotate') return 'grab';+ if (h?.kind === 'scale') {+ const q = this.frame(s!).corners[h.corner];+ const deg = ((Math.atan2(q[1] - s!.y, q[0] - s!.x) * 180) / Math.PI + 180) % 180;+ return ['ew-resize', 'nwse-resize', 'ns-resize', 'nesw-resize'][Math.round(deg / 45) % 4];+ }+ return h || this.hit(p) ? 'move' : 'default';+ }++ // ---- Text -----------------------------------------------------------------------------------------------------++ private font(): string { return `600 ${FONT}px ${css('--sans') || 'sans-serif'}`; }++ private textBox(text: string): Pt {+ const g = this.ui.canvas.getContext('2d');+ if (!g) return [text.length * FONT * 0.6 + 2 * TEXT_PAD[0], FONT + 2 * TEXT_PAD[1]];+ g.save();+ g.font = this.font();+ const w = g.measureText(text).width;+ g.restore();+ return [w + 2 * TEXT_PAD[0], FONT + 2 * TEXT_PAD[1]];+ }++ private openText(p: Pt): void {+ this.editing = { id: null, p, color: this.color };+ this.showInput('', p, '', FONT);+ }++ /** Vorhandenen Text bearbeiten. Das Feld steht ungedreht über dem Mittelpunkt, die Form tritt solange zurück. */+ private editText(s: Shape): void {+ this.editing = { id: s.id, p: [s.x, s.y], color: s.color };+ this.showInput(s.text ?? '', [s.x, s.y], 'translate(-50%, -50%)', FONT * s.sx);+ this.draw();+ }++ private showInput(value: string, p: Pt, transform: string, size: number): void {+ const t = this.ui.text;+ t.value = value;+ Object.assign(t.style, { left: `${p[0]}px`, top: `${p[1]}px`, transform, fontSize: `${size}px`, color: this.editing!.color });+ t.hidden = false;+ // Erst nach dem Mausklick fokussieren, der sonst den Fokus wieder mitnimmt. Schreibmarke ans Ende.+ setTimeout(() => { t.focus(); t.setSelectionRange(t.value.length, t.value.length); }, 0);+ }++ private commitText(): void {+ const ed = this.editing;+ if (!ed) return;+ this.editing = null;+ const text = this.ui.text.value.trim();+ this.ui.text.hidden = true;+ if (ed.id != null) {+ const s = this.shapes.find((x) => x.id === ed.id);+ if (s && (text !== s.text || ed.color !== s.color)) {+ this.remember();+ // Leer übernommen heißt gelöscht+ if (!text) this.shapes = this.shapes.filter((x) => x !== s);+ else { s.text = text; s.color = ed.color; s.box = this.textBox(text); }+ }+ } else if (text) {+ this.remember();+ const box = this.textBox(text);+ this.shapes.push({ id: this.nextId++, tool: 'text', color: ed.color, pts: [], text, box, x: ed.p[0] + box[0] / 2, y: ed.p[1] + box[1] / 2, rot: 0, sx: 1, sy: 1 });+ }+ this.changed();+ }++ private cancelText(): void {+ this.editing = null;+ this.ui.text.hidden = true;+ this.draw();+ }++ // ---- Zeichnen -------------------------------------------------------------------------------------------------++ private draw(withSelection = true): void {+ const c = this.ui.canvas;+ const g = c.getContext('2d');+ if (!g || !c.width) return;+ g.setTransform(1, 0, 0, 1, 0, 0);+ if (this.bg && !this.blankBg) g.drawImage(this.bg, 0, 0);+ else { g.fillStyle = css('--s2') || '#1b1e23'; g.fillRect(0, 0, c.width, c.height); }+ g.setTransform(this.scale, 0, 0, this.scale, 0, 0);+ for (const s of this.shapes) if (s.id !== this.editing?.id) this.paint(g, s);+ const d = this.drag;+ if (d?.kind === 'draw') this.paint(g, this.makeShape(d.tool, d.color, d.raw));+ const s = withSelection && this.tool === 'select' ? this.sel() : undefined;+ if (s && s.id !== this.editing?.id) this.paintSelection(g, s);+ }++ private paint(g: CanvasRenderingContext2D, s: Shape): void {+ g.save();+ g.strokeStyle = g.fillStyle = s.color;+ g.lineWidth = LINE;+ g.lineCap = 'round';+ g.lineJoin = 'round';+ // Dunkler Schatten, damit Striche und Text auch auf hellen Bauteilen lesbar bleiben. Er skaliert nicht mit, daher mal scale.+ g.shadowColor = 'rgba(0,0,0,.55)';+ g.shadowBlur = 3 * this.scale;+ if (s.tool === 'text' && s.text && s.box) {+ g.translate(s.x, s.y);+ g.rotate(s.rot);+ g.scale(s.sx, s.sy);+ g.font = this.font();+ // Grundlinie wie im Textfeld (line-height 1): Die Schriftbox steht mittig in der Zeile, darin liegt die Grundlinie+ const m = g.measureText(s.text);+ const asc = m.fontBoundingBoxAscent, desc = m.fontBoundingBoxDescent;+ g.fillText(s.text, -s.box[0] / 2 + TEXT_PAD[0], -s.box[1] / 2 + TEXT_PAD[1] + (FONT - asc - desc) / 2 + asc);+ g.restore();+ return;+ }+ const p = this.outline(s);+ const [a, b = a] = p;+ g.beginPath();+ g.moveTo(a[0], a[1]);+ if (s.tool === 'pen') {+ if (p.length === 1) g.lineTo(a[0] + 0.01, a[1]);+ // Durch die Mittelpunkte geglättet, sonst wirkt Freihand eckig+ for (let i = 1; i < p.length - 1; i++) g.quadraticCurveTo(p[i][0], p[i][1], (p[i][0] + p[i + 1][0]) / 2, (p[i][1] + p[i + 1][1]) / 2);+ if (p.length > 1) g.lineTo(p[p.length - 1][0], p[p.length - 1][1]);+ } else if (s.tool === 'arrow') {+ const ang = Math.atan2(b[1] - a[1], b[0] - a[0]);+ const head = Math.min(16, dist(a, b) * 0.4);+ g.lineTo(b[0], b[1]);+ for (const k of [-0.5, 0.5]) { g.moveTo(b[0], b[1]); g.lineTo(b[0] - head * Math.cos(ang + k), b[1] - head * Math.sin(ang + k)); }+ } else {+ for (const q of p.slice(1)) g.lineTo(q[0], q[1]);+ g.closePath();+ }+ g.stroke();+ g.restore();+ }++ /** Rahmen, Eckgriffe (skalieren) und Drehgriff. Kommt nie ins Bild für den Agenten. */+ private paintSelection(g: CanvasRenderingContext2D, s: Shape): void {+ const f = this.frame(s);+ g.save();+ g.strokeStyle = css('--acc') || '#f29a38';+ g.fillStyle = css('--tx') || '#e6e8eb';+ g.lineWidth = 1;+ g.setLineDash([4, 3]);+ g.beginPath();+ f.corners.forEach((q, i) => (i ? g.lineTo(q[0], q[1]) : g.moveTo(q[0], q[1])));+ g.closePath();+ g.moveTo(f.top[0], f.top[1]);+ g.lineTo(f.rotate[0], f.rotate[1]);+ g.stroke();+ g.setLineDash([]);+ g.lineWidth = 1.5;+ for (const q of f.corners) { g.fillRect(q[0] - 4, q[1] - 4, 8, 8); g.strokeRect(q[0] - 4, q[1] - 4, 8, 8); }+ g.beginPath();+ g.arc(f.rotate[0], f.rotate[1], 5, 0, Math.PI * 2);+ g.fill();+ g.stroke();+ g.restore();+ }++ private renderUi(): void {+ const u = this.ui;+ u.tools.querySelectorAll<HTMLButtonElement>('[data-tool]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.tool === this.tool)));+ u.palette.querySelectorAll<HTMLButtonElement>('[data-color]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.color === this.colorName)));+ u.colorSwatch.style.setProperty('--c', this.color);+ if (/^#[0-9a-f]{6}$/i.test(this.color)) u.custom.value = this.color;+ u.undo.disabled = !this.history.length && !this.editing;+ u.del.disabled = this.selected == null;+ u.blank.setAttribute('aria-pressed', String(this.blankBg));+ u.canvas.style.cursor = this.tool === 'select' ? 'default' : this.tool === 'text' ? 'text' : 'crosshair';+ u.hint.replaceChildren(this.blankBg ? 'Leere Fläche. Das Bild landet in ' : `Bild des Viewers von ${fmtWhen(this.takenAt)}. Es landet in `,+ el('code', { textContent: '.cadide/feedback/' }), ', der Pfad in der Eingabe des Agenten.');+ }++ // ---- Prüfhilfen (nur für Tests) -------------------------------------------------------------------------------++ state() {+ const r = (v: number, n = 2) => +v.toFixed(n);+ return {+ active: this.active, tool: this.tool, color: this.color, blank: this.blankBg, size: this.size, pixels: [this.ui.canvas.width, this.ui.canvas.height],+ shapes: this.shapes.map((s) => s.tool),+ items: this.shapes.map((s) => ({ tool: s.tool, color: s.color, text: s.text ?? null, x: r(s.x), y: r(s.y), rot: r(s.rot, 4), sx: r(s.sx, 3), sy: r(s.sy, 3) })),+ selected: this.shapes.findIndex((s) => s.id === this.selected), editing: !!this.editing, undo: this.history.length, redo: this.future.length,+ };+ }++ /** Griffe der ausgewählten Form in CSS-Pixeln der Zeichenfläche. */+ handles() {+ const s = this.sel();+ if (!s) return null;+ const f = this.frame(s);+ return { corners: f.corners, rotate: f.rotate, center: [s.x, s.y] };+ }++ /** RGBA eines Bildpunkts, Koordinaten in CSS-Pixeln der Zeichenfläche. */+ pixel(x: number, y: number): number[] {+ const g = this.ui.canvas.getContext('2d');+ return g ? [...g.getImageData(Math.round(x * this.scale), Math.round(y * this.scale), 1, 1).data] : [];+ }+}++/** Mit Umschalt: Quadrat bzw. Kreis. */+function square(a: Pt, p: Pt): Pt {+ const d = Math.max(Math.abs(p[0] - a[0]), Math.abs(p[1] - a[1]));+ return [a[0] + Math.sign(p[0] - a[0] || 1) * d, a[1] + Math.sign(p[1] - a[1] || 1) * d];+}++/** Abstand eines Punkts von einer Strecke. */+function segDist(p: Pt, a: Pt, b: Pt): number {+ const dx = b[0] - a[0], dy = b[1] - a[1], len = dx * dx + dy * dy;+ const t = len ? Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / len)) : 0;+ return Math.hypot(p[0] - a[0] - t * dx, p[1] - a[1] - t * dy);+}diff --git a/app/src/renderer/style.css b/app/src/renderer/style.cssindex 1752267..cec498e 100644--- a/app/src/renderer/style.css+++ b/app/src/renderer/style.css@@ -18,6 +18,9 @@--acc:#f29a38; --acc-tx:#f6b46a; --acc-tint:rgba(242,154,56,.14); --acc-line:rgba(242,154,56,.45);--vio:#9aa6ff; --vio-tint:rgba(154,166,255,.14);--ok:#5cc98b; --warn:#e8c547; --err:#f07470; --err-tint:rgba(240,116,112,.12);+ /* Stiftfarben der Markierung (landen im Bild für den Agenten, keine Bedeutung in der Oberfläche) */+ --mk-orange:var(--acc); --mk-red:#f0524d; --mk-pink:#f47ab4; --mk-violet:#a78bfa; --mk-blue:#5ea8ff;+ --mk-cyan:#2fd0c0; --mk-green:#4fcf7f; --mk-yellow:#f7d046; --mk-white:#f4f5f6; --mk-black:#121417;--sans:'IBM Plex Sans','Segoe UI',system-ui,sans-serif; --mono:'IBM Plex Mono',Consolas,'Cascadia Mono',monospace;--shadow:0 10px 30px rgba(0,0,0,.35);}@@ -132,8 +135,8 @@ code { font-family:var(--mono); font-size:.95em; }#center { flex:1; min-width:0; display:flex; flex-direction:column; }#viewer { flex:1; position:relative; overflow:hidden; min-height:120px; container-type:inline-size; container-name:viewer;background:radial-gradient(ellipse at 52% 44%, #272c34 0%, #1b1e23 60%, #16181c 100%); }-#viewer canvas { position:absolute; inset:0; width:100%; height:100%; display:block; transition:opacity .2s; }-#viewer.dim canvas { opacity:.35; filter:grayscale(.5); }+#viewer > canvas { position:absolute; inset:0; width:100%; height:100%; display:block; transition:opacity .2s; }+#viewer.dim > canvas { opacity:.35; filter:grayscale(.5); }#viewer.preview::after { content:''; position:absolute; inset:0; border:2px solid var(--vio); pointer-events:none; z-index:6; }#viewer-msg { position:absolute; left:50%; top:50%; transform:translate(-50%,-50%); color:var(--tx2); pointer-events:none; white-space:pre-wrap; text-align:center; z-index:1; max-width:70%; }#viewer-msg.error { color:var(--err); }@@ -168,7 +171,6 @@ code { font-family:var(--mono); font-size:.95em; }.dock button:hover:not(:disabled), .dock button[aria-expanded=true] { background:var(--s3); }.dock button.hot { background:var(--acc-tint); color:var(--acc-tx); font-weight:500; }.dock button:disabled { color:#5d6671; }-.dock button.hot:disabled { background:transparent; color:#8a6a45; }.vsep { width:1px; height:20px; background:var(--line2); margin:0 3px; flex-shrink:0; }@container viewer (max-width: 900px) { .dock .lbl { display:none; } .dock button { padding:0 8px; gap:3px; } }@@ -215,6 +217,28 @@ code { font-family:var(--mono); font-size:.95em; }.bn-text .tag { font-size:11px; padding:1px 7px; border-radius:9px; background:var(--vio-tint); color:#cdd2ff; }#bn-sub { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }+/* ---- Markierung (E16) ----------------------------------------------------------------------------------------- */+#viewer.marking > .float, #viewer.marking > .cube, #viewer.marking > #viewer-msg { display:none; }+.markup { position:absolute; inset:0; z-index:8; background:var(--s2); }+.markup canvas { position:absolute; left:0; top:0; display:block; touch-action:none; }+.mk-frame { position:absolute; inset:6px; border:2px dashed var(--acc-line); border-radius:8px; pointer-events:none; }+.mk-tools { left:12px; top:12px; }+.mk-title { display:flex; align-items:center; gap:7px; padding:0 10px 0 8px; color:var(--acc-tx); }+.mk-tools [data-tool][aria-pressed=true], #btn-mark-blank[aria-pressed=true] { background:var(--acc-tint); color:var(--acc-tx); font-weight:500; }+.mk-tools .mk-colorbtn { gap:5px; padding:0 7px 0 9px; }+.mk-tools .swatch { width:16px; height:16px; border-radius:50%; background:var(--c); box-shadow:inset 0 0 0 1px rgba(255,255,255,.25); }+.mk-palette { display:grid; grid-template-columns:repeat(5, 28px); gap:10px; padding:6px 10px 10px; }+.mk-palette button { width:28px; height:28px; border-radius:50%; background:var(--c); box-shadow:inset 0 0 0 1px rgba(255,255,255,.25); }+.mk-palette button:hover { box-shadow:0 0 0 2px var(--s2), 0 0 0 4px var(--line2); }+.mk-palette button[aria-pressed=true] { box-shadow:0 0 0 2px var(--s2), 0 0 0 4px var(--acc-tx); }+.mk-custom { cursor:pointer; }+.mk-custom input { width:22px; height:22px; padding:0; border:0; background:none; cursor:pointer; flex-shrink:0; }+.mk-hint { left:12px; bottom:12px; padding:8px 12px; font-size:12px; color:var(--tx2); max-width:calc(100% - 330px); }+.mk-actions { position:absolute; right:12px; bottom:12px; z-index:2; display:flex; gap:8px; }+.mk-actions .btn:not(.primary) { background:var(--s2); }+.mk-text { position:absolute; z-index:1; font:600 19px/1 var(--sans); padding:2px 4px; border:1px dashed currentColor; border-radius:3px;+ background:rgba(15,17,20,.55); outline:none; field-sizing:content; min-width:140px; }+/* ---- Verlauf --------------------------------------------------------------------------------------------------- */.tl { height:44px; flex-shrink:0; display:flex; align-items:center; gap:14px; padding:0 16px; background:var(--s1); border-top:1px solid var(--line); min-width:0; }.tl .lbl { flex-shrink:0; display:flex; align-items:center; gap:7px; color:var(--tx2); font-size:12px; font-weight:500; }diff --git a/app/src/renderer/versions.ts b/app/src/renderer/versions.tsindex fcd49d5..d6d7971 100644--- a/app/src/renderer/versions.ts+++ b/app/src/renderer/versions.ts@@ -40,6 +40,8 @@ export class VersionsBar {}get previewing(): boolean { return this.previewHash !== null; }+ /** Der alte Stand, der gerade als Vorschau zu sehen ist. */+ get previewed(): CommitInfo | null { return this.previewHash ? this.log.commits.find((c) => c.hash === this.previewHash) ?? null : null; }/** Stand der letzten Speicherung, für den grünen Punkt. */setSaved(head: string | null): void {diff --git a/app/src/renderer/viewer.ts b/app/src/renderer/viewer.tsindex 03d5eed..b571563 100644--- a/app/src/renderer/viewer.ts+++ b/app/src/renderer/viewer.ts@@ -282,6 +282,47 @@ export class Viewer {requestAnimationFrame(() => { this.renderQueued = false; this.renderer.render(this.scene, this.camera); });}+ /**+ * Bild der aktuellen Ansicht in voller Auflösung, Grundlage der Markierung (E16). Die Zeichenfläche ist durchsichtig,+ * den Verlauf dahinter malt sonst CSS. Er wird hier nachgebildet (`radial-gradient(ellipse at 52% 44%, …)` in style.css),+ * damit das Bild aussieht wie der Viewer. Die Auswahl fehlt im Bild: Sie ist Orange wie der Stift und würde die Markierung verschlucken.+ */+ snapshot(): HTMLCanvasElement {+ const sel = this.selectedId;+ this.selectedId = null;+ this.applySelection();+ this.highlight.visible = false;+ this.renderer.render(this.scene, this.camera);+ const c = document.createElement('canvas');+ try { this.paintSnapshot(c); } finally {+ this.selectedId = sel;+ this.applySelection();+ this.highlight.visible = true;+ this.requestRender();+ }+ return c;+ }++ private paintSnapshot(c: HTMLCanvasElement): void {+ const src = this.renderer.domElement;+ c.width = src.width; c.height = src.height;+ const g = c.getContext('2d');+ if (!g || !c.width || !c.height) return;+ const w = c.width, h = c.height, cx = w * 0.52, cy = h * 0.44;+ // CSS: Ellipse mit dem Seitenverhältnis von closest-side, die durch die fernste Ecke geht (farthest-corner)+ const k = Math.min(cx, w - cx) / Math.min(cy, h - cy);+ const ry = Math.hypot(Math.max(cx, w - cx) / k, Math.max(cy, h - cy)), rx = ry * k;+ g.save();+ g.translate(cx, cy);+ g.scale(1, ry / rx);+ const grad = g.createRadialGradient(0, 0, 0, 0, 0, rx);+ grad.addColorStop(0, '#272c34'); grad.addColorStop(0.6, '#1b1e23'); grad.addColorStop(1, '#16181c');+ g.fillStyle = grad;+ g.fillRect(-cx, -cy * rx / ry, w, h * rx / ry);+ g.restore();+ g.drawImage(src, 0, 0);+ }+/*** Vorschaubild für die Startseite: aktuelle Ansicht, mittig auf das Seitenverhältnis zugeschnitten, als JPEG.* Der Hintergrund ist sonst durchsichtig, deshalb bekommt das Bild den Grundton der Oberfläche.diff --git a/app/src/shared/types.ts b/app/src/shared/types.tsindex 3f8d41e..045ac18 100644--- a/app/src/shared/types.ts+++ b/app/src/shared/types.ts@@ -32,6 +32,8 @@ export interface BuildStatus {export interface ExportResult { ok: boolean; files: string[]; error?: string }/** Dateien, die per Ziehen nach inputs/ kopiert wurden (E33). */export interface ImportResult { files: string[]; errors: string[] }+/** Gespeicherte Markierung (E16). `path` relativ zum Projekt, z. B. `.cadide/feedback/markierung-20260930-1405.png`. */+export interface FeedbackResult { ok: boolean; path?: string; error?: string }export interface FileNode { name: string; path: string; dir: boolean; children?: FileNode[] }@@ -106,6 +108,8 @@ export interface CadideApi {onChanged(cb: () => void): void;/** Kopiert gezogene Dateien nach inputs/. Vorhandenes wird nie überschrieben. */importFiles(files: File[]): Promise<ImportResult>;+ /** Legt ein PNG der Markierung in .cadide/feedback/ ab. Vorhandenes wird nie überschrieben. */+ saveFeedback(png: Uint8Array): Promise<FeedbackResult>;};term: {create(opts?: { command?: string; title?: string }): Promise<number>;diff --git a/app/test/smoke.mjs b/app/test/smoke.mjsindex a6de095..9234651 100644--- a/app/test/smoke.mjs+++ b/app/test/smoke.mjs@@ -79,6 +79,119 @@ try {check('Bestätigung „In die Eingabe von Terminal eingefügt"', (await ev(() => window.__t.toast())).text.includes('In die Eingabe von Terminal eingefügt'));await ev((id) => window.cadide.term.write(id, '\x03'), tid); // Zeile verwerfen+ // Markierung (E16): Viewer-Bild einfrieren, zeichnen, als PNG nach .cadide/feedback/, Pfad in die Eingabe+ const dirtyBefore = (await ev(() => window.cadide.project.saveState())).dirtyFiles;+ const lidPos = await ev((l) => { const v = window.__t.viewer, r = document.getElementById('viewer').getBoundingClientRect(), p = v.screenOf(l.id, l.face); return [p.x - r.left, p.y - r.top]; }, lidFace);+ await domClick('btn-mark');+ await waitFor('Zeichenfläche offen', () => window.__t.markup().active, 5000).catch(() => {});+ const hiddenUi = await ev(() => ['parts', 'cube', 'selcard'].every((id) => getComputedStyle(document.getElementById(id)).display === 'none'));+ const mk0 = await ev(() => window.__t.markup());+ check('„Markieren": Zeichenfläche offen, Bauteilkarte, Würfel und Auswahlkarte treten zurück', mk0.active && !mk0.blank && hiddenUi && mk0.pixels[0] > 0, `${mk0.pixels.join('x')} px`);+ const [bgPx, lidPx] = await ev((p) => [window.__t.markPixel(3, 3), window.__t.markPixel(p[0], p[1])], lidPos);+ // Die angeklickte Fläche leuchtet im Viewer orange. Im Bild fehlt die Auswahl, sonst verschluckt sie die orange Markierung.+ check('Das eingefrorene Bild zeigt das Modell ohne Auswahlfarbe', bgPx[3] === 255 && lidPx.slice(0, 3).reduce((s, v, i) => s + Math.abs(v - bgPx[i]), 0) > 40+ && !(lidPx[0] > 200 && lidPx[2] < 120), `${bgPx.slice(0, 3)} / ${lidPx.slice(0, 3)}`);+ check('Die Auswahl im Viewer selbst bleibt bestehen', await ev(() => window.__t.viewer.selection) === lidFace.id);+ const drag = (pts) => ev((pts) => {+ const c = document.getElementById('mark-canvas'), r = c.getBoundingClientRect();+ const fire = (type, [x, y]) => c.dispatchEvent(new PointerEvent(type, { clientX: r.left + x, clientY: r.top + y, bubbles: true, cancelable: true, button: 0, pointerId: 1, isPrimary: true }));+ fire('pointerdown', pts[0]); for (const p of pts.slice(1)) fire('pointermove', p); fire('pointerup', pts[pts.length - 1]);+ }, pts);+ const tool = (name) => ev((n) => document.querySelector(`#mark-tools [data-tool="${n}"]`).click(), name);+ await drag([[60, 300], [100, 302], [140, 300], [180, 301]]);+ await tool('arrow'); await drag([[420, 140], [lidPos[0], lidPos[1]]]);+ await tool('rect'); await drag([[40, 380], [200, 460]]);+ await tool('ellipse'); await drag([[250, 380], [252, 381]]); // bloßer Klick: keine Form+ await tool('text'); await drag([[430, 110]]);+ await sleep(100);+ await ev(() => { document.getElementById('mark-text').value = 'vorne spitz, etwa 1 mm'; });+ await shot('7a-markieren-text');+ await ev(() => document.getElementById('mark-text').dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));+ const mk1 = await ev(() => window.__t.markup());+ const penPx = await ev(() => window.__t.markPixel(120, 301));+ check('Zeichnen: Stift, Pfeil, Rechteck, Text (Klick ohne Ziehen ergibt keine Form)', JSON.stringify(mk1.shapes) === '["pen","arrow","rect","text"]', mk1.shapes.join(','));+ check('Stiftstrich im Bild in Orange', penPx[0] > 200 && penPx[1] > 110 && penPx[1] < 190 && penPx[2] < 110, penPx.slice(0, 3).join(','));+ await shot('7-markieren');+ await tool('ellipse'); await drag([[250, 380], [330, 440]]);+ await domClick('btn-mark-undo');+ check('Rückgängig nimmt die letzte Form zurück', JSON.stringify((await ev(() => window.__t.markup())).shapes) === '["pen","arrow","rect","text"]');+ await domClick('btn-mark-blank');+ const blankPx = await ev((p) => window.__t.markPixel(p[0] + 30, p[1] + 30), lidPos);+ await shot('7c-markieren-leer');+ check('„Leere Fläche": Hintergrund ohne Modell, Zeichnung bleibt', (await ev(() => window.__t.markup())).blank && blankPx.slice(0, 3).join() === '27,30,35'+ && (await ev(() => window.__t.markup())).shapes.length === 4, blankPx.slice(0, 3).join(','));+ await domClick('btn-mark-blank');++ // Gezeichnetes bleibt bearbeitbar: auswählen, verschieben, drehen, skalieren, umfärben, löschen+ const mk = () => ev(() => window.__t.markup());+ const key = (k, o = {}) => ev(([k, o]) => document.body.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true, ...o })), [k, o]);+ await tool('select');+ const rect0 = (await mk()).items[2];+ await drag([[40, 420], [60, 410], [80, 400]]); // Klick auf den linken Rand, dann ziehen+ let st = await mk();+ check('Auswählen: Klick auf den Rand wählt das Rechteck, Ziehen verschiebt es', st.selected === 2 && st.items[2].x === rect0.x + 40 && st.items[2].y === rect0.y - 20, `${st.selected}: ${st.items[2].x},${st.items[2].y}`);+ let hd = await ev(() => window.__t.markHandles());+ await drag([hd.rotate, [hd.center[0] + 50, hd.rotate[1] + 20], [hd.center[0] + 100, hd.center[1]]]);+ st = await mk();+ check('Drehgriff dreht um die Mitte (hier um 90°)', Math.abs(st.items[2].rot - Math.PI / 2) < 0.01 && st.items[2].x === rect0.x + 40, `${st.items[2].rot} rad`);+ hd = await ev(() => window.__t.markHandles());+ const [cx2, cy2] = hd.corners[2];+ await drag([[cx2, cy2], [cx2 + (cx2 - hd.center[0]) * 0.5, cy2 + (cy2 - hd.center[1]) * 0.5]]);+ st = await mk();+ const hd2 = await ev(() => window.__t.markHandles());+ check('Eckgriff skaliert, die gegenüberliegende Ecke bleibt stehen', st.items[2].sx > 1.2 && st.items[2].sy > 1.2 && Math.hypot(hd2.corners[0][0] - hd.corners[0][0], hd2.corners[0][1] - hd.corners[0][1]) < 0.5,+ `${st.items[2].sx} × ${st.items[2].sy}`);+ await domClick('btn-mark-color');+ const swatches = await ev(() => document.querySelectorAll('#menu-mark-color [data-color]').length);+ await shot('7e-markieren-farben');+ await ev(() => document.querySelector('#menu-mark-color [data-color="blue"]').click());+ st = await mk();+ check('Farbmenü: 10 Farben und eigene Farbe, die ausgewählte Form wird umgefärbt', swatches === 10 && await ev(() => !!document.getElementById('mark-color-custom'))+ && st.items[2].color === '#5ea8ff' && st.color === '#5ea8ff' && await ev(() => document.getElementById('menu-mark-color').hidden), `${swatches} Farben, ${st.items[2].color}`);+ await shot('7d-markieren-auswahl');+ await key('Delete');+ st = await mk();+ check('Entf löscht die ausgewählte Form', JSON.stringify(st.shapes) === '["pen","arrow","text"]' && st.selected === -1, st.shapes.join(','));+ await domClick('btn-mark-undo');+ st = await mk();+ check('Rückgängig holt sie zurück, mit Drehung, Größe und Farbe', st.shapes.length === 4 && st.items[2].color === '#5ea8ff' && Math.abs(st.items[2].rot - Math.PI / 2) < 0.01 && st.items[2].sx > 1.2);+ await key('y', { ctrlKey: true });+ check('Strg+Y wiederholt das Löschen', (await mk()).shapes.length === 3);+ await domClick('btn-mark-undo');+ const tx = (await mk()).items[3];+ await drag([[tx.x, tx.y]]); await drag([[tx.x, tx.y]]);+ await sleep(50);+ const ed = await ev(() => ({ open: !document.getElementById('mark-text').hidden, value: document.getElementById('mark-text').value }));+ await ev(() => { const t = document.getElementById('mark-text'); t.value = 'Spitze etwa 1 mm'; t.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); });+ st = await mk();+ check('Doppelklick auf einen Text öffnet ihn zum Bearbeiten, Enter übernimmt', ed.open && ed.value === 'vorne spitz, etwa 1 mm' && st.items[3].text === 'Spitze etwa 1 mm' && st.shapes.length === 4, ed.value);+ await key('Escape');+ check('Escape hebt zuerst nur die Auswahl auf', (await mk()).selected === -1 && (await mk()).active);++ await ev(() => document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));+ check('Escape mit Zeichnung verwirft nicht sofort (erst beim zweiten Mal)', (await ev(() => window.__t.markup())).active && (await ev(() => window.__t.toast())).text.includes('Noch einmal Escape'));+ const px = (await ev(() => window.__t.markup())).pixels;+ await domClick('btn-mark-send');+ await waitFor('Markierung gespeichert', () => !window.__t.markup().active, 10000).catch(() => {});+ const fbDir = path.join(proj.dir, '.cadide', 'feedback');+ const fbFiles = fs.existsSync(fbDir) ? fs.readdirSync(fbDir) : [];+ const png = fbFiles.length === 1 ? fs.readFileSync(path.join(fbDir, fbFiles[0])) : Buffer.alloc(0);+ if (process.env.SMOKE_SHOTS && png.length) fs.writeFileSync(path.join(APP, 'test', 'shots', '7b-markierung-bild.png'), png); // so sieht der Agent es+ check('„An Agent geben": PNG in .cadide/feedback/, so groß wie der Viewer in Gerätepixeln', /^markierung-\d{8}-\d{4}\.png$/.test(fbFiles[0] ?? '') && png.length > 2000+ && png.readUInt32BE(16) === px[0] && png.readUInt32BE(20) === px[1], `${fbFiles.join(',')} ${png.length > 24 ? `${png.readUInt32BE(16)}x${png.readUInt32BE(20)}` : ''}`);+ await waitFor('Pfad im Terminal', (id) => window.__t.termText(id).includes('[Markierung: .cadide/feedback/markierung-'), 10000, tid).catch(() => {});+ check('Pfad steht in der Eingabe des Terminals, nicht abgeschickt', (await ev((id) => window.__t.termText(id), tid)).includes(`[Markierung: .cadide/feedback/${fbFiles[0]}]`));+ const tst = await ev(() => window.__t.toast());+ check('Meldung nennt Datei und Ziel, Bauteilkarte ist zurück', tst.text.includes(`Markierung gespeichert: .cadide/feedback/${fbFiles[0]}`) && tst.text.includes('In die Eingabe von Terminal eingefügt')+ && await ev(() => getComputedStyle(document.getElementById('parts')).display !== 'none'), tst.text.replace(/\s+/g, ' ').slice(0, 70));+ await ev((id) => window.cadide.term.write(id, '\x03'), tid);+ check('Markierung zählt nicht als ungespeicherte Änderung (nicht in Git, E11)', (await ev(() => window.cadide.project.saveState())).dirtyFiles === dirtyBefore);+ await domClick('btn-ins-mark');+ await waitFor('Zeichenfläche über die Übergabeleiste', () => window.__t.markup().active, 5000).catch(() => {});+ const viaHandoff = await ev(() => window.__t.markup().active);+ await ev(() => document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));+ check('„Markierung" in der Übergabeleiste öffnet die Zeichenfläche, Escape ohne Zeichnung schließt', viaHandoff && !(await ev(() => window.__t.markup().active)) && fs.readdirSync(fbDir).length === 1);+// 4) Auto-Build: Änderung an model.py -> neuer Build -> drittes Bauteilconst modelPy = path.join(proj.dir, 'model.py');const original = fs.readFileSync(modelPy, 'utf8');diff --git a/app/test/unit.mjs b/app/test/unit.mjsindex 180f678..5b8f362 100644--- a/app/test/unit.mjs+++ b/app/test/unit.mjs@@ -14,7 +14,7 @@ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'cadide-unit-'));try {const out = path.join(tmp, 'files.mjs');await build({ entryPoints: [path.join(APP, 'src', 'main', 'files.ts')], outfile: out, bundle: true, platform: 'node', format: 'esm', logLevel: 'silent' });- const { importInputs } = await import(pathToFileURL(out).href);+ const { importInputs, saveFeedbackImage } = await import(pathToFileURL(out).href);const proj = path.join(tmp, 'projekt');const src = path.join(tmp, 'quelle');@@ -44,6 +44,26 @@ try {r = importInputs(proj2, [path.join(src, 'platine.step')]);check('inputs/ zeigt nach außen: Import wird abgelehnt, draußen landet nichts', r.files.length === 0 && fs.readdirSync(outside).length === 0, r.errors[0]?.slice(0, 70) ?? '');} else check('inputs/ als Verweis nach außen (übersprungen, Verweis nicht anlegbar)', true);++ // Markierung (E16): PNG nach .cadide/feedback/, Name mit Datum und Uhrzeit, nichts wird überschrieben+ const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);+ const when = new Date(2026, 8, 30, 14, 5);+ const f1 = saveFeedbackImage(proj, png, when), f2 = saveFeedbackImage(proj, png, when);+ check('Markierung landet als markierung-JJJJMMTT-HHMM.png in .cadide/feedback/', f1.ok && f1.path === '.cadide/feedback/markierung-20260930-1405.png'+ && fs.readFileSync(path.join(proj, f1.path)).equals(Buffer.from(png)), f1.path ?? f1.error);+ check('Zweite Markierung in derselben Minute: neuer Name mit -2, erste bleibt', f2.ok && f2.path === '.cadide/feedback/markierung-20260930-1405-2.png'+ && fs.existsSync(path.join(proj, f1.path)), f2.path ?? f2.error);+ const bad = saveFeedbackImage(proj, new TextEncoder().encode('kein Bild'), when);+ check('Kein PNG: abgelehnt, nichts geschrieben', !bad.ok && fs.readdirSync(path.join(proj, '.cadide', 'feedback')).length === 2, bad.error);+ // .cadide als Verweis nach außen, feedback/ gibt es noch nicht: Auch der Ordner darüber zählt+ const proj3 = path.join(tmp, 'projekt3');+ fs.mkdirSync(proj3);+ let linked3 = true;+ try { fs.symlinkSync(outside, path.join(proj3, '.cadide'), 'junction'); } catch { linked3 = false; }+ if (linked3) {+ const r3 = saveFeedbackImage(proj3, png, when);+ check('.cadide zeigt nach außen: Markierung abgelehnt, draußen landet nichts', !r3.ok && fs.readdirSync(outside).length === 0, r3.error?.slice(0, 70) ?? '');+ } else check('.cadide als Verweis nach außen (übersprungen, Verweis nicht anlegbar)', true);} catch (e) {console.log('ABBRUCH:', e.message);t.fail();diff --git a/app/test/versions.mjs b/app/test/versions.mjsindex 0c6928e..5eceafb 100644--- a/app/test/versions.mjs+++ b/app/test/versions.mjs@@ -105,6 +105,15 @@ try {await sleep(4000);check('Ein Build während der Vorschau ändert die Anzeige nicht', (await ev(() => window.__t.partSize('Body')))[0] === 60);fs.writeFileSync(modelPy, fs.readFileSync(modelPy, 'utf8').replace('\n# Kommentar während der Vorschau\n', ''));+ // Markierung einer Vorschau: Der Agent erfährt, dass das Bild einen alten Stand zeigt (sonst vergleicht er es mit dem aktuellen Code)+ await domClick('btn-mark');+ await waitFor('Zeichenfläche', () => window.__t.markup().active, 5000).catch(() => {});+ await domClick('btn-mark-send');+ const firstShort = await g('rev-parse', '--short', first);+ await waitFor('Markierung im Terminal', (i) => window.__t.termText(i).includes('[Markierung: .cadide/feedback/'), 10000, await term()).catch(() => {});+ check('Markierung in der Vorschau nennt den alten Stand', (await termText()).includes(`zeigt den älteren Stand ${firstShort} "Neues Modell angelegt"]`), (await termText()).match(/\[Markierung:[^\]]*\]/)?.[0]?.slice(0, 90) ?? '');+ check('Nach der Markierung läuft die Vorschau weiter', !!(await versions()).previewing && await ev(() => document.getElementById('viewer').classList.contains('preview')));+ await ev((i) => window.cadide.term.write(i, '\x03'), await term()); // Zeile verwerfen// ---- 5) Wiederherstellen als neuer Commit ----await app.answers([0]);@@ -120,6 +129,8 @@ try {// ---- 6) Störfall: .git verschwindet (Agent hat es gelöscht/verschoben) ----await app.domClick('btn-save');await waitFor('gespeichert nach Restore', () => !window.__t.saveState().unsaved, 60000);+ check('ZIP enthält die Markierung aus .cadide/feedback/ (in Git ist sie nicht)', (await listZip(zipPath)).some((n) => /^\.cadide\/feedback\/markierung-\d{8}-\d{4}\.png$/.test(n))+ && (await g('ls-files', '.cadide/feedback')) === '');fs.renameSync(path.join(dir, '.git'), path.join(dir, '.git_weg'));await waitFor('Problem gemeldet', () => window.__t.versions().problems.some((p) => p.includes('Kein Git-Verlauf')), 20000);check('Ohne .git: Verlauf meldet das Problem verständlich', (await versions()).problems[0].includes('Kein Git-Verlauf'), (await versions()).problems[0].slice(0, 50));