Skip to main content

brep_app/panels/
cam.rs

1//! The CAM pane — the browser tree of the CAM workbench
2//! ([`crate::workbench::cam`]): **Setups**, each with its operations, **NC
3//! Programs** and the **Tool Library**, over the document's `cam` block.
4//!
5//! The pane holds only the widget's transient state (its hit rects, the
6//! selected row, an action a toolbar button handed it). Every record it draws
7//! is read from the engine's document each frame through
8//! [`crate::document::cam`], which is the one place the block's shape is
9//! spelled, and every edit is one checkpointed write of the whole block
10//! ([`History::set_cam_block`](brep_render::history::History::set_cam_block)) — undo and save / reload come from the
11//! document, not from here.
12//!
13//! A block the document module cannot read is left exactly as it is: the
14//! pane shows why under its header and refuses every mutation until the
15//! document is repaired, so nothing a user wrote is ever saved over.
16
17use crate::ui_kit;
18use crate::automation::hit_keys::HitKeyDoc;
19use crate::document::cam::{self as cam_doc, resolve_frame, strategy_kinds, CamDocument, SetupFrame, SetupOrientation};
20use crate::form_view::{form_view, FormBanner, FormViewSpec};
21use crate::panels::file::{SaveBody, SaveRequest};
22use crate::panels::{cam_generate, cam_library, cam_machine, cam_operation, cam_setup, cam_tool};
23use crate::store::ModelStore;
24use brep_cam::model::{Point3, RigidTransform};
25use brep_render::engine_state::{EngineState, RefSelectTarget};
26use eframe::egui;
27use serde_json::{json, Value};
28use std::collections::{BTreeMap, HashMap};
29
30/// An action a toolbar button hands the pane (the shell's dispatch arms in
31/// `app.rs`), performed on the next frame the pane draws — which the shell
32/// guarantees by surfacing the pane in the same arm.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum CamRequest {
35    NewSetup,
36    NewTool,
37    NewOperation,
38    Generate,
39}
40
41/// The document's `cam` block, or why it cannot be read.
42/// The handle an operation row shows for its tool: the tool's NUMBER as the
43/// Tool Library row shows it ("T1"), not its record id ("T2") — the two read
44/// as different tools when the ids and the numbers drifted apart
45/// (ui-polish-2026-10-28 row 6). A tool the document no longer holds keeps
46/// its id, which is the honest reading of a dangling reference.
47fn tool_handle(doc: &CamDocument, tool: &brep_cam::model::ToolId) -> String {
48    doc.tools.iter().find(|t| &t.id == tool).map_or_else(|| tool.to_string(), |t| format!("T{}", t.number))
49}
50
51pub fn cam_document(state: &EngineState) -> Result<CamDocument, String> {
52    cam_doc::load(state.history.cam_block())
53}
54
55/// Write the block back as a USER edit (one undo step). `coalesce` groups a
56/// run of rapid same-target edits (typing in one field) into one step.
57pub fn write_cam_document(state: &mut EngineState, doc: &CamDocument, coalesce: Option<&str>) {
58    state.history.set_cam_block(cam_doc::store(doc), coalesce);
59    state.dirty = true;
60}
61
62/// Write the block back WITHOUT an undo step — for a derived value that
63/// belongs to the edit just made (the frame a pick resolves to).
64fn write_cam_document_no_undo(state: &mut EngineState, doc: &CamDocument) {
65    state.history.set_cam_block_no_undo(cam_doc::store(doc));
66    state.dirty = true;
67}
68
69/// The frame setup `id`'s picks resolve to against the model on screen, or
70/// why they do not.
71pub fn setup_frame(state: &EngineState, doc: &CamDocument, id: &str) -> Result<SetupFrame, String> {
72    let orientation = doc.orientation(id);
73    let face = |name: &str| cam_doc::classify_face(&face_triangles(state, name));
74    // A feature's published axis (a helix's `…:Axis`) reads as a straight
75    // edge along it.
76    let edge = |name: &str| {
77        state.scene.edge_polyline_world(name).or_else(|| {
78            state.cam_named_axis(name).map(|(p, d)| vec![p, [p[0] + d[0], p[1] + d[1], p[2] + d[2]]])
79        })
80    };
81    resolve_frame(&orientation, &face, &edge)
82}
83
84/// The world triangles of the face named `name` (empty when no solid on
85/// screen carries it), for the orientation's face classifier.
86fn face_triangles(state: &EngineState, name: &str) -> Vec<[[f64; 3]; 3]> {
87    for solid in state.scene.solids() {
88        let Some(face) = solid.faces.iter().find(|f| f.name == name) else { continue };
89        let (positions, indices) = (&solid.mesh.positions, &solid.mesh.indices);
90        let start = face.tri_start as usize;
91        let end = (start + face.tri_count as usize).min(indices.len() / 3);
92        let p = |i: u32| {
93            let v = positions[i as usize];
94            [v[0] as f64, v[1] as f64, v[2] as f64]
95        };
96        return (start..end).map(|t| [p(indices[t * 3]), p(indices[t * 3 + 1]), p(indices[t * 3 + 2])]).collect();
97    }
98    Vec::new()
99}
100
101/// Apply a form PATCH (`cam_setup::apply_setup_form`) to setup `id`:
102/// one undo step, coalesced per setup and field run when `coalesce` is set.
103pub fn update_setup(state: &mut EngineState, id: &str, patch: &Value, coalesce: Option<&str>) -> Result<(), String> {
104    edit_cam_document(state, coalesce, |doc| {
105        let mut orientation = doc.orientation(id);
106        let setup = doc.setup_mut(id).ok_or_else(|| format!("no setup `{id}`"))?;
107        cam_setup::apply_setup_form(patch, setup, &mut orientation)?;
108        // A rest stock starts from an EARLIER setup's simulated stock.
109        if let brep_cam::model::Stock::FromRest { setup: source } = &setup.stock {
110            let source = source.as_str().to_string();
111            let at = |name: &str| doc.setups.iter().position(|s| s.id.as_str() == name);
112            match (at(&source), at(id)) {
113                (Some(s), Some(me)) if s < me => {}
114                (Some(_), _) => return Err(format!("stockSetup: setup `{source}` comes after `{id}`; a rest stock starts from an earlier setup")),
115                (None, _) => return Err(format!("stockSetup: no setup `{source}`")),
116            }
117        }
118        doc.set_orientation(id, orientation);
119        cam_setup::apply_machine_form(patch, doc, id)?;
120        Ok(())
121    })?;
122    sync_setup_frame(state, id);
123    Ok(())
124}
125
126/// Write the frame setup `id`'s picks resolve to into its `modelToMachine`
127/// when it differs from what is stored — the derived half of a pick or an
128/// orientation edit, written without its own undo step. Picks that do not
129/// resolve leave the stored transform alone; the dialog shows why.
130pub fn sync_setup_frame(state: &mut EngineState, id: &str) -> Option<String> {
131    let doc = cam_document(state).ok()?;
132    let frame = match setup_frame(state, &doc, id) {
133        Ok(frame) => frame,
134        Err(why) => return Some(why),
135    };
136    let transform = match frame.transform() {
137        Ok(t) => t,
138        Err(why) => return Some(why),
139    };
140    let setup = doc.setup(id)?;
141    if setup.model_to_machine == transform {
142        return None;
143    }
144    let mut next = doc.clone();
145    next.setup_mut(id)?.model_to_machine = transform;
146    write_cam_document_no_undo(state, &next);
147    None
148}
149
150/// Apply a form PATCH (`cam_tool::apply_tool_form`) to tool `id`: one undo
151/// step, coalesced per tool and field run when `coalesce` is set.
152pub fn update_tool(state: &mut EngineState, id: &str, patch: &Value, coalesce: Option<&str>) -> Result<(), String> {
153    edit_cam_document(state, coalesce, |doc| {
154        let tool = doc.tool_mut(id).ok_or_else(|| format!("no tool `{id}`"))?;
155        cam_tool::apply_tool_form(patch, tool)
156    })
157}
158
159/// Add a custom machine copied from `base` (a built-in id, or another custom
160/// machine's), named `name`. Returns the id.
161pub fn add_machine(state: &mut EngineState, base: &str, name: Option<&str>) -> Result<String, String> {
162    edit_cam_document(state, None, |doc| {
163        let source = doc.machine(base).ok_or_else(|| format!("base: no machine `{base}` (a built-in id or a document machine)"))?;
164        Ok(doc.add_machine(source, name))
165    })
166}
167
168/// Apply a machine editor PATCH (`cam_machine::apply_machine_form`) to the
169/// document's machine `id`; a built-in is copied first (`add_machine`).
170pub fn update_machine(state: &mut EngineState, id: &str, patch: &Value, coalesce: Option<&str>) -> Result<(), String> {
171    edit_cam_document(state, coalesce, |doc| {
172        let machine = doc.machine_mut(id).ok_or_else(|| format!("no document machine `{id}` (a built-in is copied into the document first)"))?;
173        cam_machine::apply_machine_form(patch, machine)
174    })
175}
176
177/// Duplicate tool `id` under a fresh id and the next free number. Returns
178/// the new id.
179pub fn duplicate_tool(state: &mut EngineState, id: &str) -> Result<String, String> {
180    edit_cam_document(state, None, |doc| {
181        let source = doc.tool(id).ok_or_else(|| format!("no tool `{id}`"))?.clone();
182        let number = doc.tools.iter().map(|t| t.number).max().unwrap_or(0) + 1;
183        let new_id = doc.next_id("T");
184        doc.tools.push(cam_tool::duplicate(&source, &new_id, number));
185        Ok(new_id)
186    })
187}
188
189/// Feeds and speeds for tool `id` from `material`, through C12's
190/// calculator, written into the tool. Returns the calculator's adjustments.
191pub fn calculate_tool_feeds(state: &mut EngineState, id: &str, material: &str) -> Result<Vec<String>, String> {
192    edit_cam_document(state, None, |doc| {
193        let tool = doc.tool_mut(id).ok_or_else(|| format!("no tool `{id}`"))?;
194        cam_tool::calculate_feeds(tool, material)
195    })
196}
197
198/// Add user-library tool `library_id` to the document under a fresh id and
199/// the next free number (its name and geometry as the library has them).
200pub fn add_tool_from_library(state: &mut EngineState, store: &dyn ModelStore, library_id: &str) -> Result<String, String> {
201    let source = cam_library::tool(store, library_id)?;
202    edit_cam_document(state, None, |doc| {
203        let number = doc.tools.iter().map(|t| t.number).max().unwrap_or(0) + 1;
204        let id = doc.next_id("T");
205        let mut tool = source.clone();
206        tool.id = id.as_str().into();
207        tool.number = number;
208        if let Some(holder) = &mut tool.holder {
209            holder.id = format!("{id}-holder").into();
210        }
211        doc.tools.push(tool);
212        Ok(id)
213    })
214}
215
216/// Import a library file's text (`cam_library::import_text`) into the
217/// document's tools, each under a fresh id and number. Returns the ids added
218/// and the importer's skipped rows.
219pub fn import_tools(state: &mut EngineState, name: &str, text: &str) -> Result<(Vec<String>, Vec<String>), String> {
220    let report = cam_library::import_text(name, text)?;
221    let issues: Vec<String> = report.issues.iter().map(|i| format!("row {}: {}", i.row, i.message)).collect();
222    let ids = edit_cam_document(state, None, |doc| {
223        let mut ids = Vec::new();
224        let mut number = doc.tools.iter().map(|t| t.number).max().unwrap_or(0);
225        for mut tool in report.document.library.tools.clone() {
226            number += 1;
227            let id = doc.next_id("T");
228            tool.id = id.as_str().into();
229            tool.number = number;
230            if let Some(holder) = &mut tool.holder {
231                holder.id = format!("{id}-holder").into();
232            }
233            doc.tools.push(tool);
234            ids.push(id);
235        }
236        Ok(ids)
237    })?;
238    Ok((ids, issues))
239}
240
241/// The document's tools as a library document, for export.
242pub fn export_document_tools(state: &EngineState) -> Result<String, String> {
243    let doc = cam_document(state)?;
244    let mut library = brep_cam::library::ToolLibrary::new("Document tools");
245    library.tools = doc.tools.clone();
246    brep_cam::library::interchange::LibraryDocument::new(library).to_json()
247}
248
249/// Apply a form PATCH (`cam_operation::apply_operation_form`) to operation
250/// `id`: one undo step, coalesced per operation and field run when
251/// `coalesce` is set. Face references the patch names get their owning
252/// solid from the scene.
253pub fn update_operation(state: &mut EngineState, id: &str, patch: &Value, coalesce: Option<&str>) -> Result<(), String> {
254    let owners = face_owners(state);
255    let edge_owners = edge_owners(state);
256    edit_cam_document(state, coalesce, |doc| {
257        let tools = doc.tools.clone();
258        // The multi-axis finish's source designation (lane C17), refused by
259        // field before anything is applied.
260        crate::panels::cam_multiaxis::apply_source(patch, doc, id)?;
261        let operation = doc.operation_mut(id).ok_or_else(|| format!("no operation `{id}`"))?;
262        cam_operation::apply_operation_form(patch, operation, &tools)?;
263        cam_operation::resolve_face_owners(operation, &|face| owners.get(face).cloned());
264        cam_operation::resolve_edge_owners(operation, &|edge| edge_owners.get(edge).cloned());
265        Ok(())
266    })
267}
268
269/// Every edge name on screen → its solid's name.
270fn edge_owners(state: &EngineState) -> HashMap<String, String> {
271    let mut owners = HashMap::new();
272    for solid in state.scene.solids() {
273        for edge in solid.edges.iter().filter(|e| !e.name.is_empty()) {
274            owners.insert(edge.name.clone(), solid.name.clone());
275        }
276    }
277    owners
278}
279
280/// Every face name on screen → its solid's name.
281fn face_owners(state: &EngineState) -> HashMap<String, String> {
282    let mut owners = HashMap::new();
283    for solid in state.scene.solids() {
284        for face in &solid.faces {
285            owners.insert(face.name.clone(), solid.name.clone());
286        }
287    }
288    owners
289}
290
291/// Fill the owning solid of operation `id`'s picked faces from the scene —
292/// the derived half of a face pick, written without its own undo step — and
293/// sample a committed machining-boundary pick into its containment boundary.
294/// A boundary pick that cannot be used (not a sketch profile, a plane not
295/// across the setup's Z) is consumed and refused by name; the boundary stays.
296pub fn sync_operation_faces(state: &mut EngineState, id: &str) -> Result<(), String> {
297    let owners = face_owners(state);
298    let edge_owners = edge_owners(state);
299    // A committed chain pick is folded into the model by the load; the block
300    // is rewritten once so it no longer carries the staging key.
301    let block = state.history.cam_block();
302    let pending = block.as_ref().is_some_and(|b| cam_doc::has_pending_chain_pick(b));
303    let boundary_pick = block.as_ref().and_then(|b| cam_doc::pending_boundary_pick(b, id));
304    let Ok(mut doc) = cam_document(state) else { return Ok(()) };
305    let setup = doc.operation(id).and_then(|op| doc.setup(op.setup.as_str())).cloned();
306    let tools = doc.tools.clone();
307    let Some(operation) = doc.operation_mut(id) else { return Ok(()) };
308    let faces = cam_operation::resolve_face_owners(operation, &|face| owners.get(face).cloned());
309    let edges = cam_operation::resolve_edge_owners(operation, &|edge| edge_owners.get(edge).cloned());
310    let mut refused = None;
311    if let Some(names) = &boundary_pick {
312        let chord = operation.tolerance / 4.0;
313        let sampled = setup
314            .as_ref()
315            .ok_or_else(|| format!("{id}: its setup is not defined"))
316            .and_then(|setup| boundary_from_profile(state, names, setup, chord))
317            .and_then(|loops| {
318                let loops: Vec<Value> = loops.iter().map(|l| json!(l.iter().map(|p| [p.x, p.y]).collect::<Vec<_>>())).collect();
319                cam_operation::apply_operation_form(&json!({ "strategy": { "containment": { "boundary": loops } } }), operation, &tools).map_err(|e| format!("{id}: {e}"))
320            });
321        refused = sampled.err();
322    }
323    if faces || edges || pending || boundary_pick.is_some() {
324        write_cam_document_no_undo(state, &doc);
325    }
326    refused.map_or(Ok(()), Err)
327}
328
329/// The loops of the sketch profile `names` picks (every region, outer and
330/// holes — the containment reads loops even-odd), sampled within `chord` and
331/// taken into the machine XY of `setup`. Refused by name for anything but one
332/// sketch profile, and for a profile whose plane is not across machine Z.
333fn boundary_from_profile(state: &EngineState, names: &[String], setup: &brep_cam::model::Setup, chord: f64) -> Result<Vec<Vec<brep_cam::model::Point2>>, String> {
334    use brep_cam::model::{ChainSource, Point2};
335    let chain = cam_doc::chain_from_names(names).ok_or_else(|| "nothing was picked for the machining boundary".to_string())?;
336    if !matches!(chain.source, ChainSource::SketchProfile { .. }) {
337        return Err(format!("the machining boundary is picked as a sketch profile (a sketch's face), not `{}`", names.join(", ")));
338    }
339    let (_, profiles) = state.cam_chain_geometry(std::slice::from_ref(&chain))?;
340    let (sketch, profile) = profiles.first().ok_or_else(|| "the picked sketch has no profile".to_string())?;
341    let mut loops = Vec::new();
342    for region in &profile.regions {
343        for profile_loop in region {
344            let mut points: Vec<Point3> = Vec::new();
345            for curve in &profile_loop.curves {
346                for p in sample_curve(curve, chord)? {
347                    let p = setup.model_to_machine.apply_point(Point3::new(p.x, p.y, p.z));
348                    if points.last().is_none_or(|q: &Point3| q.distance(p) > 1e-9) {
349                        points.push(p);
350                    }
351                }
352            }
353            if points.len() > 1 && points[0].distance(*points.last().expect("non-empty")) <= 1e-9 {
354                points.pop();
355            }
356            let (lo, hi) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p.z), hi.max(p.z)));
357            if hi - lo > chord.max(1e-6) {
358                return Err(format!("sketch `{sketch}` is not across the setup's Z (its profile spans {:.4} in machine Z); pick a profile parallel to the machine's XY", hi - lo));
359            }
360            loops.push(points.iter().map(|p| Point2::new(p.x, p.y)).collect());
361        }
362    }
363    if loops.is_empty() {
364        return Err(format!("sketch `{sketch}` has no closed profile"));
365    }
366    Ok(loops)
367}
368
369/// Points along `curve` whose chords stay within `chord` of it: a line its
370/// two ends; a curved span split until each chord's midpoint deviation is
371/// within `chord` (16 halvings at most).
372fn sample_curve(curve: &brep_render::brep_kernel::NurbsCurve, chord: f64) -> Result<Vec<brep_render::brep_kernel::Vec3>, String> {
373    use brep_render::brep_kernel::Vec3;
374    let [a, b] = curve.domain()?;
375    let at = |t: f64| curve.evaluate(t);
376    let dist = |p: Vec3, q: Vec3, m: Vec3| {
377        let (dx, dy, dz) = (q.x - p.x, q.y - p.y, q.z - p.z);
378        let (mx, my, mz) = (m.x - p.x, m.y - p.y, m.z - p.z);
379        let len2 = dx * dx + dy * dy + dz * dz;
380        let t = if len2 > 0.0 { ((mx * dx + my * dy + mz * dz) / len2).clamp(0.0, 1.0) } else { 0.0 };
381        ((mx - t * dx).powi(2) + (my - t * dy).powi(2) + (mz - t * dz).powi(2)).sqrt()
382    };
383    let mut out = vec![at(a)?];
384    // A curved span starts at eight pieces, so an S-bend's chord midpoint
385    // cannot sit on the curve by chance.
386    let pieces = if curve.degree <= 1 { (curve.control_points.len() - 1).max(1) } else { 8 * (curve.control_points.len() - curve.degree).max(1) };
387    let mut stack: Vec<(f64, f64, u32)> = (0..pieces).rev().map(|i| (a + (b - a) * i as f64 / pieces as f64, a + (b - a) * (i + 1) as f64 / pieces as f64, 0)).collect();
388    while let Some((t0, t1, depth)) = stack.pop() {
389        let (p0, p1, pm) = (at(t0)?, at(t1)?, at(0.5 * (t0 + t1))?);
390        if curve.degree > 1 && depth < 16 && dist(p0, p1, pm) > chord {
391            stack.push((0.5 * (t0 + t1), t1, depth + 1));
392            stack.push((t0, 0.5 * (t0 + t1), depth + 1));
393        } else {
394            out.push(p1);
395        }
396    }
397    Ok(out)
398}
399
400/// Arm the reference picker for operation `id`'s field `key`; refused for a
401/// key that is not one of its reference fields.
402pub fn begin_operation_pick(state: &mut EngineState, id: &str, key: &str) -> Result<(), String> {
403    let doc = cam_document(state)?;
404    let operation = doc.operation(id).ok_or_else(|| format!("no operation `{id}`"))?;
405    let (path, filter, multiple, label) = cam_operation::pick_path(id, key).ok_or_else(|| format!("`{key}` is not a reference field of an operation"))?;
406    let params = cam_operation::operation_form_params(operation);
407    let seed: Vec<String> = params["targets"].get(key).and_then(Value::as_array).map(|l| l.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();
408    if state.ref_select_active() {
409        state.finish_ref_select();
410    }
411    state.begin_ref_select_for_cam(id, path, format!("{}: {label}", operation.name), filter, multiple, seed);
412    Ok(())
413}
414
415/// Queue the generation of `ops` (every enabled operation with targets when
416/// `None`): the jobs the engine's runner takes, one operation each. Returns
417/// the ids queued and, per operation that could not be queued, why.
418pub fn generate(state: &mut EngineState, ops: Option<&[String]>) -> Result<(Vec<String>, Vec<(String, String)>), String> {
419    let doc = cam_document(state)?;
420    let ids: Vec<String> = match ops {
421        Some(ids) => ids.to_vec(),
422        None => doc.operations.iter().filter(|op| op.enabled).map(|op| op.id.as_str().to_string()).collect(),
423    };
424    let mut jobs = Vec::new();
425    let mut refused = Vec::new();
426    for id in ids {
427        match cam_generate::job_for(state, &doc, &id) {
428            Ok(job) => jobs.push(job),
429            Err(why) => refused.push((id, why)),
430        }
431    }
432    state.cam.job_builder.get_or_insert(cam_generate::job_at_dispatch);
433    let queued = state.cam_enqueue(jobs);
434    Ok((queued, refused))
435}
436
437/// Arm the reference picker for setup `id`'s field `key`, seeded with the
438/// field's current names; refused for a key that is not a reference field.
439pub fn begin_setup_pick(state: &mut EngineState, id: &str, key: &str) -> Result<(), String> {
440    let doc = cam_document(state)?;
441    let setup = doc.setup(id).ok_or_else(|| format!("no setup `{id}`"))?;
442    let (path, filter, multiple, label) = cam_setup::pick_path(id, key).ok_or_else(|| format!("`{key}` is not a reference field of a setup"))?;
443    let params = cam_setup::setup_form_params(setup, &doc.orientation(id));
444    let seed: Vec<String> = match params.get(key) {
445        Some(Value::Array(list)) => list.iter().filter_map(Value::as_str).map(str::to_string).collect(),
446        Some(Value::String(s)) if !s.is_empty() => vec![s.clone()],
447        _ => Vec::new(),
448    };
449    if state.ref_select_active() {
450        state.finish_ref_select();
451    }
452    state.begin_ref_select_for_cam(id, path, format!("{}: {label}", setup.name), filter, multiple, seed);
453    Ok(())
454}
455
456/// Read, change and write the block in one step; a block that cannot be read
457/// refuses the change with the read error, and a refused change writes
458/// nothing.
459pub fn edit_cam_document<T>(
460    state: &mut EngineState,
461    coalesce: Option<&str>,
462    change: impl FnOnce(&mut CamDocument) -> Result<T, String>,
463) -> Result<T, String> {
464    let mut doc = cam_document(state)?;
465    let out = change(&mut doc)?;
466    write_cam_document(state, &doc, coalesce);
467    Ok(out)
468}
469
470/// Add a setup: returns the id.
471pub fn add_setup(state: &mut EngineState, name: Option<&str>) -> Result<String, String> {
472    edit_cam_document(state, None, |doc| Ok(doc.add_setup(name)))
473}
474
475/// Add a tool: returns the id.
476pub fn add_tool(state: &mut EngineState, name: Option<&str>) -> Result<String, String> {
477    edit_cam_document(state, None, |doc| Ok(doc.add_tool(name)))
478}
479
480/// Add an operation of strategy kind `kind` to `setup` with `tool`; refused,
481/// naming what is missing, when any of them does not exist. Returns the id.
482pub fn add_operation(state: &mut EngineState, setup: &str, tool: &str, kind: &str, name: Option<&str>) -> Result<String, String> {
483    edit_cam_document(state, None, |doc| doc.add_operation(setup, tool, kind, name))
484}
485
486/// Add an NC program over `operations` (each must exist). Returns the id.
487pub fn add_program(state: &mut EngineState, name: Option<&str>, post: &str, operations: &[String]) -> Result<String, String> {
488    add_program_with(state, name, post, operations, &BTreeMap::new())
489}
490
491/// [`add_program`] with post properties, in one step: a refused property
492/// leaves no program behind.
493pub fn add_program_with(state: &mut EngineState, name: Option<&str>, post: &str, operations: &[String], properties: &BTreeMap<String, Value>) -> Result<String, String> {
494    edit_cam_document(state, None, |doc| {
495        let id = doc.add_program(name, post, operations)?;
496        if !properties.is_empty() {
497            doc.set_program_properties(&id, properties)?;
498        }
499        Ok(id)
500    })
501}
502
503/// Set or clear (`null`) post properties of NC program `id`.
504pub fn set_program_properties(state: &mut EngineState, id: &str, patch: &BTreeMap<String, Value>) -> Result<(), String> {
505    edit_cam_document(state, None, |doc| doc.set_program_properties(id, patch))
506}
507
508/// Remove the record with `id` (see [`CamDocument::remove`]).
509pub fn remove_record(state: &mut EngineState, id: &str) -> Result<(), String> {
510    edit_cam_document(state, None, |doc| doc.remove(id))
511}
512
513/// One setup's resolved geometry, as the viewport draws it and `cam_state`
514/// reports it.
515#[derive(Clone, Debug, PartialEq)]
516pub struct SetupGeometry {
517    pub frame: Result<SetupFrame, String>,
518    pub stock: Option<(Point3, Point3)>,
519}
520
521/// A stamp of everything the setups' geometry is read from: the document
522/// revision (the block) and the scene's solids (count, content revisions,
523/// visibility). Equal stamps mean equal frames and stock boxes.
524fn geometry_stamp(state: &EngineState) -> (u64, u64) {
525    let mut scene: u64 = 0xcbf2_9ce4_8422_2325;
526    for solid in state.scene.solids() {
527        for byte in solid.name.bytes().chain([solid.visible as u8]).chain(solid.revision.to_le_bytes()) {
528            scene ^= byte as u64;
529            scene = scene.wrapping_mul(0x0000_0100_0000_01b3);
530        }
531    }
532    (state.history.revision(), scene)
533}
534
535/// The block as the `cam_state` command and the `__brepCam` blob report it:
536/// every record in its model serde form, each setup with the ids of its
537/// operations, the strategy kinds an operation can be, the pane's selection
538/// and its last notice — or, for a block that cannot be read, `error` and
539/// empty lists. The setups' frames and stock boxes come from the pane's
540/// cache ([`CamPanel::refresh_geometry`]), which the caller refreshes first.
541pub fn cam_state_json(state: &EngineState, panel: &CamPanel) -> String {
542    let (doc, error) = match cam_document(state) {
543        Ok(doc) => (doc, None),
544        Err(why) => (CamDocument::default(), Some(why)),
545    };
546    json!({
547        "setups": doc.setups.iter().map(|s| {
548            let mut record = serde_json::to_value(s).unwrap_or(Value::Null);
549            if let Some(object) = record.as_object_mut() {
550                object.insert("operations".into(), json!(doc.operations_of(s.id.as_str()).map(|op| op.id.as_str()).collect::<Vec<_>>()));
551            }
552            record
553        }).collect::<Vec<_>>(),
554        "tools": doc.tools,
555        "operations": doc.operations,
556        // What each operation's strategy still needs before it generates.
557        "problems": doc.operations.iter().filter_map(|op| cam_operation::strategy_problem(op).map(|p| (op.id.as_str().to_string(), json!(p)))).collect::<serde_json::Map<String, Value>>(),
558        "ncPrograms": doc.nc_programs,
559        "multiAxisSources": doc.multi_axis_sources,
560        "idCounter": doc.id_counter,
561        "strategies": strategy_kinds(),
562        "orientations": doc.orientations,
563        // Every setup's resolved frame and stock box, as the viewport draws
564        // them: `null` where the picks do not resolve (`frameError` says why).
565        "frames": doc.setups.iter().map(|s| {
566            let id = s.id.as_str();
567            let geometry = panel.geometry.get(id).cloned().unwrap_or_else(|| SetupGeometry { frame: setup_frame(state, &doc, id), stock: cam_setup::stock_bounds(s, &state.scene) });
568            let (frame, frame_error) = match geometry.frame {
569                Ok(frame) => (Some(frame), None),
570                Err(why) => (None, Some(why)),
571            };
572            let p = |p: Point3| json!([p.x, p.y, p.z]);
573            (id.to_string(), json!({
574                "origin": frame.map(|f| p(f.origin)),
575                "xAxis": frame.map(|f| p(f.x_axis)),
576                "zAxis": frame.map(|f| p(f.z_axis)),
577                "frameError": frame_error,
578                "stock": geometry.stock.map(|(min, max)| json!({ "min": p(min), "max": p(max) })),
579                // A bounds-offset stock in the setup's own frame: top / bottom along machine Z.
580                "stockMachine": cam_setup::stock_bounds_machine(s, &state.scene).map(|b| json!({ "min": p(b.min), "max": p(b.max) })),
581            }))
582        }).collect::<serde_json::Map<String, Value>>(),
583        "selected": panel.selected,
584        "open": panel.open,
585        "notice": panel.notice,
586        "error": error,
587        // Generation: the engine's queue and results, and each operation's
588        // status against the document as it stands (stale when its inputs moved).
589        "generation": state.cam_generation_json(),
590        "autoprogram": panel.autoprogram.state(state),
591        "statuses": doc.operations.iter().map(|op| {
592            let id = op.id.as_str();
593            let status = cam_generate::status_of(state, &doc, id);
594            let detail = match &status {
595                cam_generate::OpStatus::Ok { motions, cutting_length } => json!({ "motions": motions, "cuttingLength": cutting_length }),
596                cam_generate::OpStatus::Stale { motions } => json!({ "motions": motions }),
597                cam_generate::OpStatus::Error(e) => json!({ "error": e }),
598                _ => json!({}),
599            };
600            (id.to_string(), json!({ "status": status.word(), "detail": detail }))
601        }).collect::<serde_json::Map<String, Value>>(),
602        "scrub": panel.scrub,
603        // The document's custom machines and the built-in library's ids (C17c).
604        "machines": doc.machines,
605        "builtinMachines": brep_cam::kinematics::library::builtin_ids(),
606        "hiddenToolpaths": panel.hidden_toolpaths.iter().collect::<Vec<_>>(),
607    })
608    .to_string()
609}
610
611/// What the pane asks the shell for, drained once per frame by `app.rs`:
612/// the file chooser (an import) and the save door (an export) are the
613/// shell's, like the PLM pane's.
614#[derive(Debug, Default)]
615pub struct CamShellRequests {
616    /// Open the file chooser for `(tag, title)`.
617    pub pick_file: Option<(String, String)>,
618    /// Files to save or download.
619    pub save_files: Vec<SaveRequest>,
620}
621
622/// The chooser tag a tool import is asked under.
623pub const IMPORT_TOOLS_TAG: &str = "cam-tools";
624
625/// The pane's transient UI state.
626pub struct CamPanel {
627    pub autoprogram: crate::panels::cam_autoprogram::AutoProgramPanel,
628    hits: HashMap<String, egui::Rect>,
629    /// The selected row's id (a setup, operation, tool or program).
630    selected: Option<String>,
631    /// An action handed over by a toolbar button, performed on the next draw.
632    request: Option<CamRequest>,
633    /// What the last action said that was not a record (a refusal, a count),
634    /// drawn under the header until the next action.
635    notice: Option<String>,
636    /// The setup whose dialog is open, drawn in place of the tree.
637    open: Option<String>,
638    /// The form field (its key) a pick is running in, so the form draws that
639    /// field focused: the engine's pick state carries the BLOCK path, which
640    /// is not the field's.
641    picking_field: Option<String>,
642    /// The last overlay group pushed, so an unchanged frame costs nothing.
643    overlay: String,
644    /// Every setup's resolved frame and stock box, by setup id, as of
645    /// `geometry_stamp` — walking every visible solid's mesh is O(mesh), and
646    /// the state blob is published every frame, so it is done once per
647    /// change, not once per frame.
648    geometry: HashMap<String, SetupGeometry>,
649    geometry_stamp: Option<(u64, u64)>,
650    /// Requests for the shell, taken each frame ([`Self::take_shell_requests`]).
651    shell: CamShellRequests,
652    /// The user library's tools (id, name, number), re-read when the pane
653    /// draws the library menu; `None` until then.
654    user_library: Option<Result<Vec<(String, String, u32)>, String>>,
655    /// The last import's outcome: ids added and rows skipped.
656    import_report: Option<(Vec<String>, Vec<String>)>,
657    /// The work material chosen in the tool dialog for Calculate feeds —
658    /// the calculator's input, not a tool field, so it lives here.
659    feeds_material: Option<String>,
660    /// The toolpath preview's scrub position on the selected operation, as a
661    /// fraction of its segments; `None` draws no tool marker.
662    scrub: Option<f64>,
663    /// The simulation player section (lane C17), drawn under the tree.
664    pub sim: crate::panels::cam_sim::CamSimPanel,
665    /// The NC program post preview (contract C19-27), drawn under the tree.
666    pub post: crate::panels::cam_post::CamPostPanel,
667    /// The toolpath overlay groups last pushed, by operation, so a result
668    /// that is gone is removed from the viewport.
669    overlay_ops: std::collections::BTreeSet<String>,
670    /// What the pushed overlay was built from (the setup group's text, the
671    /// results stamp, the selection, the scrub, the hidden set's stamp), so a
672    /// frame with nothing changed serialises no toolpath.
673    overlay_key: Option<(String, u64, Option<String>, Option<u64>, u64)>,
674    /// Operations whose toolpath is hidden in the viewport (the row menu's
675    /// Hide toolpath / `cam_toolpath_visible`); pane state, not the document's.
676    hidden_toolpaths: std::collections::BTreeSet<String>,
677    hidden_stamp: u64,
678}
679
680impl Default for CamPanel {
681    fn default() -> Self {
682        Self::new()
683    }
684}
685
686/// Section hit keys.
687const SECTION_SETUPS: &str = "cam:section:setups";
688const SECTION_PROGRAMS: &str = "cam:section:programs";
689const SECTION_TOOLS: &str = "cam:section:tools";
690const SECTION_MACHINES: &str = "cam:section:machines";
691
692impl CamPanel {
693    pub fn new() -> Self {
694        Self {
695            autoprogram: Default::default(),
696            hits: HashMap::new(),
697            selected: None,
698            request: None,
699            notice: None,
700            open: None,
701            picking_field: None,
702            overlay: String::new(),
703            geometry: HashMap::new(),
704            geometry_stamp: None,
705            shell: CamShellRequests::default(),
706            user_library: None,
707            import_report: None,
708            feeds_material: None,
709            scrub: None,
710            sim: crate::panels::cam_sim::CamSimPanel::new(),
711            post: crate::panels::cam_post::CamPostPanel::new(),
712            overlay_ops: std::collections::BTreeSet::new(),
713            overlay_key: None,
714            hidden_toolpaths: std::collections::BTreeSet::new(),
715            hidden_stamp: 0,
716        }
717    }
718
719    /// Show or hide operation `id`'s toolpath in the viewport.
720    pub fn set_toolpath_visible(&mut self, id: &str, visible: bool) {
721        let changed = if visible { self.hidden_toolpaths.remove(id) } else { self.hidden_toolpaths.insert(id.to_string()) };
722        if changed {
723            self.hidden_stamp += 1;
724        }
725    }
726
727    /// The operations whose toolpath is hidden.
728    pub fn hidden_toolpaths(&self) -> &std::collections::BTreeSet<String> {
729        &self.hidden_toolpaths
730    }
731
732    /// Set the preview's scrub fraction (`None` clears the marker).
733    pub fn set_scrub(&mut self, fraction: Option<f64>) {
734        self.scrub = fraction.map(|f| f.clamp(0.0, 1.0));
735    }
736
737    /// The requests the pane made this frame, for the shell.
738    pub fn take_shell_requests(&mut self) -> CamShellRequests {
739        if let Some(save) = self.sim.pending_save.take() {
740            self.shell.save_files.push(save);
741        }
742        if let Some(save) = self.post.pending_save.take() {
743            self.shell.save_files.push(save);
744        }
745        std::mem::take(&mut self.shell)
746    }
747
748    /// The file the chooser delivered for an import: read as text, imported
749    /// into the document's tools, the outcome shown under the header.
750    pub fn deliver_picked(&mut self, state: &mut EngineState, name: &str, bytes: &[u8]) {
751        let text = String::from_utf8_lossy(bytes);
752        match import_tools(state, name, &text) {
753            Ok((ids, issues)) => {
754                self.notice = Some(format!(
755                    "imported {} tool{} from {name}{}",
756                    ids.len(),
757                    if ids.len() == 1 { "" } else { "s" },
758                    if issues.is_empty() { String::new() } else { format!(" ({} row{} skipped)", issues.len(), if issues.len() == 1 { "" } else { "s" }) }
759                ));
760                self.import_report = Some((ids, issues));
761            }
762            Err(why) => self.refuse(state, format!("import {name}: {why}")),
763        }
764    }
765
766    /// The user library as the pane last read it (`None` = not read yet).
767    pub fn user_library(&self) -> Option<&Result<Vec<(String, String, u32)>, String>> {
768        self.user_library.as_ref()
769    }
770
771    /// Re-read the user library's listing from the store.
772    pub fn refresh_user_library(&mut self, store: &dyn ModelStore) {
773        self.user_library = Some(cam_library::load(store).map(|lib| lib.library.tools.iter().map(|t| (t.id.as_str().to_string(), t.name.clone(), t.number)).collect()));
774    }
775
776    /// Bring the setups' geometry cache up to date with the document and the
777    /// scene. Cheap when nothing changed (two counters and a walk of the
778    /// solid list's headers); the callers that publish or draw from the
779    /// cache call it first.
780    pub fn refresh_geometry(&mut self, state: &EngineState) {
781        let stamp = geometry_stamp(state);
782        if self.geometry_stamp == Some(stamp) {
783            return;
784        }
785        self.geometry.clear();
786        if let Ok(doc) = cam_document(state) {
787            for setup in &doc.setups {
788                let id = setup.id.as_str();
789                self.geometry.insert(
790                    id.to_string(),
791                    SetupGeometry { frame: setup_frame(state, &doc, id), stock: cam_setup::stock_bounds(setup, &state.scene) },
792                );
793            }
794        }
795        self.geometry_stamp = Some(stamp);
796    }
797
798    /// The setup whose dialog is open.
799    pub fn open_setup(&self) -> Option<&str> {
800        self.open.as_deref()
801    }
802
803    /// Open setup `id`'s dialog (`None` closes it).
804    pub fn set_open(&mut self, id: Option<String>) {
805        if id != self.open {
806            self.picking_field = None;
807        }
808        self.open = id;
809    }
810
811    /// Hand the pane an action; it runs on the next frame the pane draws.
812    pub fn request(&mut self, request: CamRequest) {
813        self.request = Some(request);
814    }
815
816    /// The selected row's id.
817    pub fn selected(&self) -> Option<&str> {
818        self.selected.as_deref()
819    }
820
821    /// Select a row by id (`None` clears). The id is not checked against the
822    /// block here: a row that no longer exists simply draws nothing selected.
823    pub fn select(&mut self, id: Option<String>) {
824        self.selected = id;
825    }
826
827    /// The setup an operation would go into: the selected setup, the selected
828    /// operation's setup, or the only setup there is.
829    fn target_setup(&self, doc: &CamDocument) -> Option<String> {
830        if let Some(selected) = &self.selected {
831            if doc.setup(selected).is_some() {
832                return Some(selected.clone());
833            }
834            if let Some(op) = doc.operation(selected) {
835                return Some(op.setup.as_str().to_string());
836            }
837        }
838        match doc.setups.as_slice() {
839            [only] => Some(only.id.as_str().to_string()),
840            _ => None,
841        }
842    }
843
844    /// The tool an operation would use: the selected tool, or the only one.
845    fn target_tool(&self, doc: &CamDocument) -> Option<String> {
846        if let Some(selected) = &self.selected {
847            if doc.tool(selected).is_some() {
848                return Some(selected.clone());
849            }
850        }
851        match doc.tools.as_slice() {
852            [only] => Some(only.id.as_str().to_string()),
853            _ => None,
854        }
855    }
856
857    /// Say why an action did not produce a record: a toast, and the line
858    /// under the header.
859    fn refuse(&mut self, state: &mut EngineState, why: String) {
860        state.push_notice(format!("CAM: {why}"));
861        self.notice = Some(why);
862    }
863
864    /// Perform a handed-over action against the engine.
865    fn perform(&mut self, request: CamRequest, state: &mut EngineState) {
866        self.notice = None;
867        let doc = match cam_document(state) {
868            Ok(doc) => doc,
869            Err(why) => return self.refuse(state, why),
870        };
871        let outcome = match request {
872            CamRequest::NewSetup => add_setup(state, None),
873            CamRequest::NewTool => add_tool(state, None),
874            CamRequest::NewOperation => match (self.target_setup(&doc), self.target_tool(&doc)) {
875                (Some(setup), Some(tool)) => add_operation(state, &setup, &tool, "parallel", None),
876                (None, _) if doc.setups.is_empty() => Err("no setup yet: press New setup first".to_string()),
877                (None, _) => Err("select the setup the operation goes into".to_string()),
878                (_, None) if doc.tools.is_empty() => Err("no tool yet: press New tool first".to_string()),
879                (_, None) => Err("select the tool the operation uses".to_string()),
880            },
881            CamRequest::Generate => {
882                if doc.operations.is_empty() {
883                    Err("nothing to generate: add an operation first".to_string())
884                } else {
885                    match generate(state, None) {
886                        Ok((queued, refused)) => {
887                            if !refused.is_empty() {
888                                self.notice = Some(refused.iter().map(|(_, why)| why.as_str()).collect::<Vec<_>>().join("; "));
889                            }
890                            if queued.is_empty() && refused.is_empty() {
891                                self.notice = Some("every operation is already queued or generating".to_string());
892                            }
893                            return;
894                        }
895                        Err(why) => Err(why),
896                    }
897                }
898            }
899        };
900        match outcome {
901            Ok(id) => self.selected = Some(id),
902            Err(why) => self.refuse(state, why),
903        }
904    }
905
906    /// Draw the pane: perform any handed-over action, then the header and the
907    /// three sections, applying at most one deferred engine mutation.
908    pub fn show(&mut self, ui: &mut egui::Ui, state: &mut EngineState, store: &dyn ModelStore) {
909        self.hits.clear();
910        // Unprefixed, as `scroll_into_view` looks it up (`<panel>/panel:clip`).
911        self.hits.insert("panel:clip".into(), ui.clip_rect());
912        if let Some(request) = self.request.take() {
913            self.perform(request, state);
914        }
915        self.refresh_geometry(state);
916        let (doc, error) = match cam_document(state) {
917            Ok(doc) => (doc, None),
918            Err(why) => (CamDocument::default(), Some(why)),
919        };
920
921        self.autoprogram.poll(state);
922        // --- header -----------------------------------------------------------
923        let mut request = None;
924        ui.horizontal_wrapped(|ui| {
925            for (key, label, hover, what) in [
926                ("cam:new:setup", "New setup", "Add a setup (work coordinate system, stock, heights)", CamRequest::NewSetup),
927                ("cam:new:tool", "New tool", "Add a tool to the document's library", CamRequest::NewTool),
928                ("cam:new:operation", "New operation", "Add an operation to the selected setup with the selected tool", CamRequest::NewOperation),
929                ("cam:generate", "Generate", "Compute the toolpaths of every operation that needs it", CamRequest::Generate),
930            ] {
931                let button = ui.add(ui_kit::Button::new(&label)).on_hover_text(hover);
932                self.hits.insert(key.into(), button.rect);
933                if button.clicked() {
934                    request = Some(what);
935                }
936            }
937            let auto = ui.add(ui_kit::Button::new("Program part automatically"));
938            self.hits.insert("cam:auto:open".into(), auto.rect);
939            if auto.clicked() {
940                self.open = None;
941                let setup = self.target_setup(&doc);
942                match setup.ok_or_else(|| "select a setup before programming".to_string()).and_then(|id| self.autoprogram.preview(state, &id)) { Ok(()) => {}, Err(why) => self.notice = Some(why) }
943            }
944            ui.add(
945                egui::Label::new(
946                    egui::RichText::new(format!(
947                        "{} setup{} | {} tool{} | {} operation{}",
948                        doc.setups.len(),
949                        if doc.setups.len() == 1 { "" } else { "s" },
950                        doc.tools.len(),
951                        if doc.tools.len() == 1 { "" } else { "s" },
952                        doc.operations.len(),
953                        if doc.operations.len() == 1 { "" } else { "s" },
954                    ))
955                    .weak(),
956                )
957                .wrap_mode(egui::TextWrapMode::Extend),
958            );
959        });
960        if let Some(error) = &error {
961            let label = ui_kit::status::error(ui, error);
962            self.hits.insert("cam:error".into(), label.rect);
963        }
964        if let Some(notice) = &self.notice {
965            let label = ui_kit::status::warn(ui, notice);
966            self.hits.insert("cam:notice".into(), label.rect);
967        }
968        if state.cam.busy() {
969            ui.horizontal_wrapped(|ui| {
970                let text = match (&state.cam.progress, state.cam.in_flight()) {
971                    (Some(p), _) if p.total > 0 => format!("generating {}: {} {}/{}", p.operation, p.phase, p.current, p.total),
972                    (Some(p), _) => format!("generating {}: {}", p.operation, p.phase),
973                    (None, Some(op)) => format!("generating {op}\u{2026}"),
974                    (None, None) => "generation queued\u{2026}".to_string(),
975                };
976                let queued = state.cam.queued().len();
977                let line = ui.label(egui::RichText::new(if queued > 0 { format!("{text} (+{queued} queued)") } else { text }).weak());
978                self.hits.insert("cam:progress".into(), line.rect);
979                let cancel = ui.add(ui_kit::Button::new("Cancel")).on_hover_text("Drop the queue; the operation generating stops at its next chunk where the runner can");
980                self.hits.insert("cam:cancel".into(), cancel.rect);
981                if cancel.clicked() {
982                    state.cam_cancel();
983                }
984            });
985        } else if let Some(notice) = &state.cam.notice {
986            let line = ui.label(egui::RichText::new(notice).weak());
987            self.hits.insert("cam:progress".into(), line.rect);
988        }
989        ui.add_space(2.0);
990
991        if self.autoprogram.open {
992            self.autoprogram.show(ui, state, &mut self.hits);
993            if let Some(request) = request {
994                self.perform(request, state);
995            }
996            return;
997        }
998
999        // --- the open setup's dialog, in place of the tree ----------------------
1000        if let Some(id) = self.open.clone() {
1001            if doc.setup(&id).is_some() {
1002                self.show_setup_form(ui, state, &doc, &id);
1003                if let Some(request) = request {
1004                    self.perform(request, state);
1005                }
1006                return;
1007            }
1008            if doc.tool(&id).is_some() {
1009                self.show_tool_form(ui, state, store, &doc, &id);
1010                if let Some(request) = request {
1011                    self.perform(request, state);
1012                }
1013                return;
1014            }
1015            if doc.operation(&id).is_some() {
1016                self.show_operation_form(ui, state, &doc, &id);
1017                if let Some(request) = request {
1018                    self.perform(request, state);
1019                }
1020                return;
1021            }
1022            if doc.machines.iter().any(|m| m.id.as_str() == id) {
1023                self.show_machine_form(ui, state, &doc, &id);
1024                if let Some(request) = request {
1025                    self.perform(request, state);
1026                }
1027                return;
1028            }
1029            self.open = None;
1030        }
1031        self.push_overlay(state, &doc, self.selected.clone());
1032
1033        // --- the tree ---------------------------------------------------------
1034        let mut clicked: Option<String> = None;
1035        let mut remove: Option<String> = None;
1036        let mut open_operation: Option<String> = None;
1037        // (operation id, currently hidden) from the row menu's Hide / Show toolpath.
1038        let mut toggle_toolpath: Option<(String, bool)> = None;
1039        let row = |ui: &mut egui::Ui, hits: &mut HashMap<String, egui::Rect>, id: &str, text: String, selected: bool, clicked: &mut Option<String>, remove: &mut Option<String>| {
1040            ui.horizontal(|ui| {
1041                let label = ui.selectable_label(selected, crate::theme::data(text));
1042                hits.insert(format!("cam:row:{id}"), label.rect);
1043                if label.clicked() {
1044                    *clicked = Some(id.to_string());
1045                }
1046                label.context_menu(|ui| {
1047                    let delete = ui.add(ui_kit::Button::danger("Delete"));
1048                    hits.insert(format!("cam:menuitem:{id}:delete"), delete.rect);
1049                    if delete.clicked() {
1050                        *remove = Some(id.to_string());
1051                        ui.close();
1052                    }
1053                });
1054            });
1055        };
1056
1057        let setups = egui::CollapsingHeader::new(format!("Setups ({})", doc.setups.len()))
1058            .id_salt("cam-setups")
1059            .default_open(true)
1060            .show(ui, |ui| {
1061                if doc.setups.is_empty() {
1062                    ui.label(egui::RichText::new("No setups \u{2014} press New setup").weak());
1063                }
1064                for setup in &doc.setups {
1065                    let id = setup.id.as_str();
1066                    let ops: Vec<_> = doc.operations_of(id).collect();
1067                    let selected = self.selected.as_deref() == Some(id);
1068                    let header = egui::CollapsingHeader::new(crate::theme::data(setup.name.as_str()))
1069                        .id_salt(("cam-setup", id))
1070                        .default_open(true)
1071                        .show(ui, |ui| {
1072                            if ops.is_empty() {
1073                                ui.label(egui::RichText::new("No operations \u{2014} press New operation").weak());
1074                            }
1075                            for op in ops {
1076                                let op_id = op.id.as_str();
1077                                let status = cam_generate::status_of(state, &doc, op_id);
1078                                let text = format!("{} {}  \u{00b7} {} \u{00b7} {}{}", status.mark(), op.name, op.strategy.kind_name(), tool_handle(&doc, &op.tool), if op.enabled { "" } else { " \u{00b7} off" });
1079                                ui.horizontal(|ui| {
1080                                    let hover = match &status {
1081                                        cam_generate::OpStatus::Ok { motions, cutting_length } => format!("generated: {motions} motions, {cutting_length:.2} cutting"),
1082                                        cam_generate::OpStatus::Stale { motions } => format!("stale: {motions} motions from inputs that have changed; generate again"),
1083                                        cam_generate::OpStatus::Error(e) => format!("failed: {e}"),
1084                                        other => other.word().to_string(),
1085                                    };
1086                                    let label = ui.selectable_label(self.selected.as_deref() == Some(op_id), crate::theme::data(text)).on_hover_text(hover);
1087                                    self.hits.insert(format!("cam:row:{op_id}"), label.rect);
1088                                    if label.double_clicked() {
1089                                        open_operation = Some(op_id.to_string());
1090                                    } else if label.clicked() {
1091                                        clicked = Some(op_id.to_string());
1092                                    }
1093                                    label.context_menu(|ui| {
1094                                        let edit = ui.add(ui_kit::Button::new("Edit operation\u{2026}"));
1095                                        self.hits.insert(format!("cam:menuitem:{op_id}:edit"), edit.rect);
1096                                        if edit.clicked() {
1097                                            open_operation = Some(op_id.to_string());
1098                                            ui.close();
1099                                        }
1100                                        let hidden = self.hidden_toolpaths.contains(op_id);
1101                                        let toggle = ui.add(ui_kit::Button::new(if hidden { "Show toolpath" } else { "Hide toolpath" }));
1102                                        self.hits.insert(format!("cam:menuitem:{op_id}:toolpath"), toggle.rect);
1103                                        if toggle.clicked() {
1104                                            toggle_toolpath = Some((op_id.to_string(), hidden));
1105                                            ui.close();
1106                                        }
1107                                        let delete = ui.add(ui_kit::Button::danger("Delete"));
1108                                        self.hits.insert(format!("cam:menuitem:{op_id}:delete"), delete.rect);
1109                                        if delete.clicked() {
1110                                            remove = Some(op_id.to_string());
1111                                            ui.close();
1112                                        }
1113                                    });
1114                                });
1115                            }
1116                        });
1117                    self.hits.insert(format!("cam:row:{id}"), header.header_response.rect);
1118                    if header.header_response.double_clicked() {
1119                        self.open = Some(id.to_string());
1120                        self.selected = Some(id.to_string());
1121                    } else if header.header_response.clicked() {
1122                        clicked = Some(id.to_string());
1123                    }
1124                    header.header_response.context_menu(|ui| {
1125                        let edit = ui.add(ui_kit::Button::new("Edit setup\u{2026}"));
1126                        self.hits.insert(format!("cam:menuitem:{id}:edit"), edit.rect);
1127                        if edit.clicked() {
1128                            self.open = Some(id.to_string());
1129                            ui.close();
1130                        }
1131                    });
1132                    header.header_response.context_menu(|ui| {
1133                        let delete = ui.add(ui_kit::Button::danger("Delete setup and its operations"));
1134                        self.hits.insert(format!("cam:menuitem:{id}:delete"), delete.rect);
1135                        if delete.clicked() {
1136                            remove = Some(id.to_string());
1137                            ui.close();
1138                        }
1139                    });
1140                    if selected {
1141                        ui.painter().rect_stroke(
1142                            header.header_response.rect,
1143                            2.0,
1144                            egui::Stroke::new(1.0, ui.visuals().selection.stroke.color),
1145                            egui::StrokeKind::Inside,
1146                        );
1147                    }
1148                }
1149            });
1150        self.hits.insert(SECTION_SETUPS.into(), setups.header_response.rect);
1151
1152        let mut post_program: Option<String> = None;
1153        let programs = egui::CollapsingHeader::new(format!("NC Programs ({})", doc.nc_programs.len()))
1154            .id_salt("cam-programs")
1155            .default_open(true)
1156            .show(ui, |ui| {
1157                if doc.nc_programs.is_empty() {
1158                    ui.label(egui::RichText::new("No NC programs \u{2014} add one, then Post\u{2026} it to an NC file").weak());
1159                }
1160                for program in &doc.nc_programs {
1161                    let text = format!("{}  \u{00b7} {} \u{00b7} {} op{}", program.name, program.post, program.operations.len(), if program.operations.len() == 1 { "" } else { "s" });
1162                    ui.horizontal(|ui| {
1163                        let b = ui.add(ui_kit::Button::new("Post\u{2026}").size(ui_kit::Size::Sm)).on_hover_text("Post through the program's post: preview the NC text and save it");
1164                        self.hits.insert(format!("cam:post:program:{}", program.id), b.rect);
1165                        if b.clicked() {
1166                            post_program = Some(program.id.clone());
1167                        }
1168                        row(ui, &mut self.hits, &program.id, text, self.selected.as_deref() == Some(program.id.as_str()), &mut clicked, &mut remove);
1169                    });
1170                }
1171            });
1172        self.hits.insert(SECTION_PROGRAMS.into(), programs.header_response.rect);
1173        if let Some(id) = post_program {
1174            let _ = self.post.open(state, &doc, &id);
1175        }
1176
1177        let mut open_tool: Option<String> = None;
1178        let mut duplicate: Option<String> = None;
1179        let mut to_library: Option<String> = None;
1180        let mut from_library: Option<String> = None;
1181        let mut import = false;
1182        let mut export: Option<&'static str> = None;
1183        let tools = egui::CollapsingHeader::new(format!("Tool Library ({})", doc.tools.len()))
1184            .id_salt("cam-tools")
1185            .default_open(true)
1186            .show(ui, |ui| {
1187                ui.horizontal_wrapped(|ui| {
1188                    let add = ui.menu_button("Add from user library", |ui| {
1189                        if self.user_library.is_none() {
1190                            self.refresh_user_library(store);
1191                        }
1192                        match self.user_library.as_ref() {
1193                            Some(Ok(list)) if list.is_empty() => {
1194                                ui.label(egui::RichText::new("The user library is empty \u{2014} save a tool to it from its row menu").weak());
1195                            }
1196                            Some(Ok(list)) => {
1197                                for (id, name, number) in list.clone() {
1198                                    let entry = ui.add(ui_kit::Button::new(&format!("T{number}  {name}")));
1199                                    self.hits.insert(format!("cam:library:{id}"), entry.rect);
1200                                    if entry.clicked() {
1201                                        from_library = Some(id);
1202                                        ui.close();
1203                                    }
1204                                }
1205                            }
1206                            Some(Err(why)) => {
1207                                ui_kit::status::error(ui, why);
1208                            }
1209                            None => {}
1210                        }
1211                    });
1212                    self.hits.insert("cam:tools:library".into(), add.response.rect);
1213                    if add.response.clicked() {
1214                        self.refresh_user_library(store);
1215                    }
1216                    let import_button = ui.add(ui_kit::Button::new("Import\u{2026}")).on_hover_text("Add the tools of a Fusion 360 export (.json / .tools), a .csv sheet or a library file");
1217                    self.hits.insert("cam:tools:import".into(), import_button.rect);
1218                    import = import_button.clicked();
1219                    let export_doc = ui.add(ui_kit::Button::new("Export")).on_hover_text("Save the document's tools as a library file");
1220                    self.hits.insert("cam:tools:export".into(), export_doc.rect);
1221                    if export_doc.clicked() {
1222                        export = Some("document");
1223                    }
1224                    let export_user = ui.add(ui_kit::Button::new("Export user library")).on_hover_text("Save the user library as a library file");
1225                    self.hits.insert("cam:tools:export-user".into(), export_user.rect);
1226                    if export_user.clicked() {
1227                        export = Some("user");
1228                    }
1229                });
1230                if let Some((ids, issues)) = &self.import_report {
1231                    for issue in issues {
1232                        ui_kit::status::warn(ui, format!("skipped {issue}"));
1233                    }
1234                    let _ = ids;
1235                }
1236                if doc.tools.is_empty() {
1237                    ui.label(egui::RichText::new("No tools \u{2014} press New tool").weak());
1238                }
1239                for tool in &doc.tools {
1240                    let id = tool.id.as_str();
1241                    let text = format!("T{}  {} \u{00b7} {} \u{2300}{}", tool.number, tool.name, tool.kind.as_str(), tool.geometry.diameter);
1242                    ui.horizontal(|ui| {
1243                        let label = ui.selectable_label(self.selected.as_deref() == Some(id), crate::theme::data(text));
1244                        self.hits.insert(format!("cam:row:{id}"), label.rect);
1245                        if label.double_clicked() {
1246                            open_tool = Some(id.to_string());
1247                        } else if label.clicked() {
1248                            clicked = Some(id.to_string());
1249                        }
1250                        label.context_menu(|ui| {
1251                            let edit = ui.add(ui_kit::Button::new("Edit tool\u{2026}"));
1252                            self.hits.insert(format!("cam:menuitem:{id}:edit"), edit.rect);
1253                            if edit.clicked() {
1254                                open_tool = Some(id.to_string());
1255                                ui.close();
1256                            }
1257                            let dup = ui.add(ui_kit::Button::new("Duplicate"));
1258                            self.hits.insert(format!("cam:menuitem:{id}:duplicate"), dup.rect);
1259                            if dup.clicked() {
1260                                duplicate = Some(id.to_string());
1261                                ui.close();
1262                            }
1263                            let save = ui.add(ui_kit::Button::new("Save to user library"));
1264                            self.hits.insert(format!("cam:menuitem:{id}:library"), save.rect);
1265                            if save.clicked() {
1266                                to_library = Some(id.to_string());
1267                                ui.close();
1268                            }
1269                            let delete = ui.add(ui_kit::Button::danger("Delete"));
1270                            self.hits.insert(format!("cam:menuitem:{id}:delete"), delete.rect);
1271                            if delete.clicked() {
1272                                remove = Some(id.to_string());
1273                                ui.close();
1274                            }
1275                        });
1276                    });
1277                }
1278            });
1279        self.hits.insert(SECTION_TOOLS.into(), tools.header_response.rect);
1280
1281        // --- Machines: the document's own machines, each a copy of a built-in --
1282        let mut open_machine: Option<String> = None;
1283        let mut new_machine: Option<String> = None;
1284        let machines = egui::CollapsingHeader::new(format!("Machines ({})", doc.machines.len()))
1285            .id_salt("cam-machines")
1286            .default_open(true)
1287            .show(ui, |ui| {
1288                let add = ui.menu_button("New machine", |ui| {
1289                    for base in brep_cam::kinematics::library::builtin_machines() {
1290                        let id = base.id.as_str().to_string();
1291                        let entry = ui.add(ui_kit::Button::new(&format!("{}  \u{00b7} {}", base.name, cam_machine::kind_tag(&base.kind))));
1292                        self.hits.insert(format!("cam:machines:new:{id}"), entry.rect);
1293                        if entry.clicked() {
1294                            new_machine = Some(id);
1295                            ui.close();
1296                        }
1297                    }
1298                });
1299                self.hits.insert("cam:machines:new".into(), add.response.rect);
1300                if doc.machines.is_empty() {
1301                    ui.label(egui::RichText::new("No machines of this document \u{2014} a setup can name a built-in directly").weak());
1302                }
1303                for machine in &doc.machines {
1304                    let id = machine.id.as_str();
1305                    let used = doc.setups.iter().filter(|s| s.machine.as_ref().is_some_and(|m| m.as_str() == id)).count();
1306                    let text = format!(
1307                        "{}  \u{00b7} {}{}{}",
1308                        machine.name,
1309                        cam_machine::kind_tag(&machine.kind),
1310                        machine.post.as_deref().map(|p| format!(" \u{00b7} {p}")).unwrap_or_default(),
1311                        if used > 0 { format!(" \u{00b7} {used} setup{}", if used == 1 { "" } else { "s" }) } else { String::new() }
1312                    );
1313                    let label = ui.selectable_label(self.selected.as_deref() == Some(id), crate::theme::data(text));
1314                    self.hits.insert(format!("cam:row:{id}"), label.rect);
1315                    if label.double_clicked() {
1316                        open_machine = Some(id.to_string());
1317                    } else if label.clicked() {
1318                        clicked = Some(id.to_string());
1319                    }
1320                    label.context_menu(|ui| {
1321                        let edit = ui.add(ui_kit::Button::new("Edit machine\u{2026}"));
1322                        self.hits.insert(format!("cam:menuitem:{id}:edit"), edit.rect);
1323                        if edit.clicked() {
1324                            open_machine = Some(id.to_string());
1325                            ui.close();
1326                        }
1327                        let delete = ui.add(ui_kit::Button::danger("Delete"));
1328                        self.hits.insert(format!("cam:menuitem:{id}:delete"), delete.rect);
1329                        if delete.clicked() {
1330                            remove = Some(id.to_string());
1331                            ui.close();
1332                        }
1333                    });
1334                }
1335            });
1336        self.hits.insert(SECTION_MACHINES.into(), machines.header_response.rect);
1337        if let Some(base) = new_machine {
1338            match add_machine(state, &base, None) {
1339                Ok(id) => {
1340                    self.notice = None;
1341                    self.selected = Some(id);
1342                }
1343                Err(why) => self.refuse(state, why),
1344            }
1345        }
1346        if let Some(id) = open_machine {
1347            self.selected = Some(id.clone());
1348            self.open = Some(id);
1349        }
1350        if let Some(id) = open_tool {
1351            self.selected = Some(id.clone());
1352            self.open = Some(id);
1353        }
1354        if let Some(id) = duplicate {
1355            match duplicate_tool(state, &id) {
1356                Ok(new_id) => self.selected = Some(new_id),
1357                Err(why) => self.refuse(state, why),
1358            }
1359        }
1360        if let Some(id) = to_library {
1361            let outcome = doc.tool(&id).ok_or_else(|| format!("no tool `{id}`")).and_then(|tool| cam_library::save_tool(store, tool));
1362            match outcome {
1363                Ok(()) => {
1364                    self.notice = Some(format!("{id} saved to the user library"));
1365                    self.user_library = None;
1366                }
1367                Err(why) => self.refuse(state, why),
1368            }
1369        }
1370        if let Some(library_id) = from_library {
1371            match add_tool_from_library(state, store, &library_id) {
1372                Ok(new_id) => self.selected = Some(new_id),
1373                Err(why) => self.refuse(state, why),
1374            }
1375        }
1376        if import {
1377            self.shell.pick_file = Some((IMPORT_TOOLS_TAG.to_string(), "Import tools".to_string()));
1378        }
1379        if let Some(which) = export {
1380            let outcome = if which == "user" { cam_library::export_text(store) } else { export_document_tools(state) };
1381            match outcome {
1382                Ok(text) => self.shell.save_files.push(SaveRequest {
1383                    title: if which == "user" { "Export the user tool library".into() } else { "Export the document's tools".into() },
1384                    file_name: if which == "user" { "user-tools.json".into() } else { "tools.json".into() },
1385                    body: SaveBody::Text(text),
1386                }),
1387                Err(why) => self.refuse(state, why),
1388            }
1389        }
1390
1391        // --- deferred mutations -----------------------------------------------
1392        if let Some(id) = open_operation {
1393            self.selected = Some(id.clone());
1394            self.open = Some(id);
1395        }
1396        if let Some(id) = clicked {
1397            self.selected = if self.selected.as_deref() == Some(id.as_str()) { None } else { Some(id) };
1398        }
1399        if let Some((id, hidden)) = toggle_toolpath {
1400            self.set_toolpath_visible(&id, hidden);
1401        }
1402        if let Some(id) = remove {
1403            match remove_record(state, &id) {
1404                Ok(()) => {
1405                    if self.selected.as_deref() == Some(id.as_str()) {
1406                        self.selected = None;
1407                    }
1408                }
1409                Err(why) => self.refuse(state, why),
1410            }
1411        }
1412        if let Some(request) = request {
1413            self.perform(request, state);
1414        }
1415        // --- the simulation player (lane C17) ---------------------------------
1416        if error.is_none() {
1417            ui.separator();
1418            let setup_hint = self.selected.as_deref().and_then(|id| {
1419                doc.setup(id).map(|_| id.to_string()).or_else(|| doc.operation(id).map(|o| o.setup.to_string()))
1420            });
1421            self.sim.show(ui, state, &doc, setup_hint.as_deref());
1422        }
1423        // --- the NC program post preview (contract C19-27) ---------------------
1424        if let Some((id, patch)) = self.post.show(ui, &doc) {
1425            match set_program_properties(state, &id, &patch) {
1426                Ok(()) => match cam_document(state) {
1427                    Ok(doc) => {
1428                        let _ = self.post.open(state, &doc, &id);
1429                    }
1430                    Err(e) => self.post.error = Some(e),
1431                },
1432                Err(e) => self.post.error = Some(e),
1433            }
1434        }
1435    }
1436
1437    /// Draw setup `id`'s dialog: the shared form over its params, its picks
1438    /// through the engine's CAM picker, the frame it resolves to written back,
1439    /// and the viewport overlay for this setup.
1440    fn show_setup_form(&mut self, ui: &mut egui::Ui, state: &mut EngineState, doc: &CamDocument, id: &str) {
1441        let Some(setup) = doc.setup(id) else { return };
1442        let orientation: SetupOrientation = doc.orientation(id);
1443        let fields = cam_setup::setup_form_fields();
1444        let mut params = cam_setup::setup_form_params(setup, &orientation);
1445        cam_setup::merge_machine_params(&mut params, doc, setup);
1446        let hidden = cam_setup::hidden_fields(&params);
1447        let title = format!("Setup {id}");
1448        let frame_error = self.geometry.get(id).and_then(|g| g.frame.clone().err());
1449        let banner = match (&frame_error, &self.notice) {
1450            (Some(why), _) => Some(FormBanner::error(why.as_str(), ui_kit::status::danger(ui.ctx()))),
1451            (None, Some(notice)) => Some(FormBanner::note(notice.as_str(), ui_kit::status::warning(ui.ctx()))),
1452            (None, None) => None,
1453        };
1454        let picking = state
1455            .ref_select_field()
1456            .filter(|f| f.target == RefSelectTarget::Cam && f.subject == id)
1457            .and_then(|f| self.picking_field.clone().map(|key| (vec![key], f.names)));
1458        let active = picking.as_ref().map(|(path, names)| crate::form::ActivePick { path, names });
1459        if active.is_some() {
1460            state.ref_select_claim();
1461        }
1462        let spec = FormViewSpec {
1463            title: &title,
1464            subtitle: Some(setup.name.as_str()),
1465            fields: &fields,
1466            hidden: Some(&hidden),
1467            banner,
1468            trailing: None,
1469            exit_label: "Return to tree",
1470            extra: None,
1471            rollback: false,
1472            hits_prefix: "cam:",
1473            read_only: None,
1474            picking: active,
1475        };
1476        let was_picking = self.picking_field.is_some();
1477        let out = form_view(ui, &spec, &mut params, Some(&mut self.hits));
1478        let anchor = self.hits.get("cam:form:feature").map(|rect| rect.min).unwrap_or(egui::Pos2::ZERO);
1479        self.hits.insert(format!("cam:form:setup:{id}"), egui::Rect::from_min_size(anchor, egui::Vec2::ZERO));
1480        self.push_overlay(state, doc, Some(id.to_string()));
1481        if let Some(activate) = out.ref_activate {
1482            let key = activate.path.first().cloned().unwrap_or_default();
1483            match begin_setup_pick(state, id, &key) {
1484                Ok(()) => {
1485                    self.picking_field = Some(key);
1486                    // The shell finishes an in-form pick nobody claimed this
1487                    // frame; the form draws it focused from the next one.
1488                    state.ref_select_claim();
1489                }
1490                Err(why) => self.refuse(state, why),
1491            }
1492        }
1493        if let Some(index) = out.pick_remove {
1494            state.ref_select_remove(index);
1495        }
1496        if out.pick_done {
1497            state.finish_ref_select();
1498            self.picking_field = None;
1499            if let Some(why) = sync_setup_frame(state, id) {
1500                self.notice = Some(why);
1501            }
1502        }
1503        if out.changed {
1504            self.notice = None;
1505            let coalesce = format!("setup:{id}:form");
1506            if let Err(why) = update_setup(state, id, &params, Some(&coalesce)) {
1507                self.refuse(state, why);
1508            }
1509        }
1510        if out.exit_clicked {
1511            if state.ref_select_active() {
1512                state.finish_ref_select();
1513            }
1514            self.picking_field = None;
1515            self.open = None;
1516        }
1517        if was_picking && !state.ref_select_active() && self.picking_field.is_some() {
1518            // The pick ended outside the form (a single field finishes on its
1519            // first pick, by the shell): the frame follows it here.
1520            self.picking_field = None;
1521            if let Some(why) = sync_setup_frame(state, id) {
1522                self.notice = Some(why);
1523            }
1524        }
1525        if !state.ref_select_active() {
1526            self.picking_field = None;
1527        }
1528    }
1529
1530    /// Draw operation `id`'s dialog: the generic form over its strategy and
1531    /// linking parameters plus the fixed groups; picks through the engine's
1532    /// CAM picker with the owning solid of a picked face filled from the
1533    /// scene; every edit one coalesced undo step.
1534    fn show_operation_form(&mut self, ui: &mut egui::Ui, state: &mut EngineState, doc: &CamDocument, id: &str) {
1535        let Some(operation) = doc.operation(id) else { return };
1536        let mut fields = cam_operation::operation_form_fields(operation, &doc.tools);
1537        fields.extend(crate::panels::cam_multiaxis::form_fields(doc, operation));
1538        let mut params = cam_operation::operation_form_params(operation);
1539        crate::panels::cam_multiaxis::merge_params(doc, id, &mut params);
1540        let hidden = cam_operation::hidden_fields(&params);
1541        let title = format!("Operation {id}");
1542        let subtitle = format!("{} \u{00b7} {} \u{00b7} {}", operation.strategy.kind_name(), operation.setup, operation.tool);
1543        let problem = cam_operation::strategy_problem(operation);
1544        let banner = match (&self.notice, &problem) {
1545            (Some(n), _) => Some(FormBanner::note(n.as_str(), ui_kit::status::warning(ui.ctx()))),
1546            (None, Some(p)) => Some(FormBanner::note(p.as_str(), ui_kit::status::warning(ui.ctx()))),
1547            (None, None) => None,
1548        };
1549        let picking = state
1550            .ref_select_field()
1551            .filter(|f| f.target == RefSelectTarget::Cam && f.subject == id)
1552            .and_then(|f| self.picking_field.clone().map(|key| (vec!["targets".to_string(), key], f.names)));
1553        let active = picking.as_ref().map(|(path, names)| crate::form::ActivePick { path, names });
1554        if active.is_some() {
1555            state.ref_select_claim();
1556        }
1557        let spec = FormViewSpec {
1558            title: &title,
1559            subtitle: Some(subtitle.as_str()),
1560            fields: &fields,
1561            hidden: Some(&hidden),
1562            banner,
1563            trailing: None,
1564            exit_label: "Return to tree",
1565            extra: None,
1566            rollback: false,
1567            hits_prefix: "cam:",
1568            read_only: None,
1569            picking: active,
1570        };
1571        let was_picking = self.picking_field.is_some();
1572        let out = form_view(ui, &spec, &mut params, Some(&mut self.hits));
1573        let anchor = self.hits.get("cam:form:feature").map(|rect| rect.min).unwrap_or(egui::Pos2::ZERO);
1574        self.hits.insert(format!("cam:form:operation:{id}"), egui::Rect::from_min_size(anchor, egui::Vec2::ZERO));
1575        self.push_overlay(state, doc, Some(operation.setup.as_str().to_string()));
1576        if let Some(activate) = out.ref_activate {
1577            let key = activate.path.last().cloned().unwrap_or_default();
1578            match begin_operation_pick(state, id, &key) {
1579                Ok(()) => {
1580                    self.picking_field = Some(key);
1581                    state.ref_select_claim();
1582                }
1583                Err(why) => self.refuse(state, why),
1584            }
1585        }
1586        if let Some(index) = out.pick_remove {
1587            state.ref_select_remove(index);
1588        }
1589        if out.pick_done {
1590            state.finish_ref_select();
1591            self.picking_field = None;
1592            if let Err(why) = sync_operation_faces(state, id) {
1593                self.refuse(state, why);
1594            }
1595        }
1596        if out.changed {
1597            self.notice = None;
1598            let coalesce = format!("operation:{id}:form");
1599            if let Err(why) = update_operation(state, id, &params, Some(&coalesce)) {
1600                self.refuse(state, why);
1601            }
1602        }
1603        if let Some(index) = out.button_clicked.as_deref().and_then(|key| key.strip_prefix("removeChain")) {
1604            let patch = json!({ "targets": { "chains": { index: { "remove": true } } } });
1605            if let Err(why) = update_operation(state, id, &patch, None) {
1606                self.refuse(state, why);
1607            }
1608        }
1609        if out.exit_clicked {
1610            if state.ref_select_active() {
1611                state.finish_ref_select();
1612            }
1613            self.picking_field = None;
1614            self.open = None;
1615        }
1616        if was_picking && !state.ref_select_active() && self.picking_field.is_some() {
1617            self.picking_field = None;
1618            if let Err(why) = sync_operation_faces(state, id) {
1619                self.refuse(state, why);
1620            }
1621        }
1622        if !state.ref_select_active() {
1623            self.picking_field = None;
1624        }
1625    }
1626
1627    /// Draw tool `id`'s dialog: the shared form over its params; Calculate
1628    /// feeds through C12's calculator; every edit one coalesced undo step.
1629    /// Draw the document machine `id`'s editor: the shared form over the
1630    /// model's machine; every edit one coalesced undo step, refused by field
1631    /// with nothing applied.
1632    fn show_machine_form(&mut self, ui: &mut egui::Ui, state: &mut EngineState, doc: &CamDocument, id: &str) {
1633        let Some(machine) = doc.machines.iter().find(|m| m.id.as_str() == id) else { return };
1634        let fields = cam_machine::machine_form_fields(machine);
1635        let mut params = cam_machine::machine_form_params(machine);
1636        let hidden = cam_machine::hidden_fields(&params);
1637        let title = format!("Machine {id}");
1638        let banner = self.notice.as_ref().map(|n| FormBanner::note(n.as_str(), ui_kit::status::warning(ui.ctx())));
1639        let spec = FormViewSpec {
1640            title: &title,
1641            subtitle: Some(machine.name.as_str()),
1642            fields: &fields,
1643            hidden: Some(&hidden),
1644            banner,
1645            trailing: None,
1646            exit_label: "Return to tree",
1647            extra: None,
1648            rollback: false,
1649            hits_prefix: "cam:",
1650            read_only: None,
1651            picking: None,
1652        };
1653        let out = form_view(ui, &spec, &mut params, Some(&mut self.hits));
1654        let anchor = self.hits.get("cam:form:feature").map(|rect| rect.min).unwrap_or(egui::Pos2::ZERO);
1655        self.hits.insert(format!("cam:form:machine:{id}"), egui::Rect::from_min_size(anchor, egui::Vec2::ZERO));
1656        self.push_overlay(state, doc, None);
1657        if out.changed {
1658            self.notice = None;
1659            let coalesce = format!("machine:{id}:form");
1660            if let Err(why) = update_machine(state, id, &params, Some(&coalesce)) {
1661                self.refuse(state, why);
1662            }
1663        }
1664        if out.exit_clicked {
1665            self.open = None;
1666        }
1667    }
1668
1669    fn show_tool_form(&mut self, ui: &mut egui::Ui, state: &mut EngineState, store: &dyn ModelStore, doc: &CamDocument, id: &str) {
1670        let Some(tool) = doc.tool(id) else { return };
1671        let fields = cam_tool::tool_form_fields();
1672        let mut params = cam_tool::tool_form_params(tool);
1673        if let Some(material) = &self.feeds_material {
1674            params["feedsMaterial"] = json!(material);
1675        }
1676        let hidden = cam_tool::hidden_fields(&params);
1677        let title = format!("Tool {id}");
1678        let banner = self.notice.as_ref().map(|n| FormBanner::note(n.as_str(), ui_kit::status::warning(ui.ctx())));
1679        let spec = FormViewSpec {
1680            title: &title,
1681            subtitle: Some(tool.name.as_str()),
1682            fields: &fields,
1683            hidden: Some(&hidden),
1684            banner,
1685            trailing: None,
1686            exit_label: "Return to tree",
1687            extra: None,
1688            rollback: false,
1689            hits_prefix: "cam:",
1690            read_only: None,
1691            picking: None,
1692        };
1693        let out = form_view(ui, &spec, &mut params, Some(&mut self.hits));
1694        let anchor = self.hits.get("cam:form:feature").map(|rect| rect.min).unwrap_or(egui::Pos2::ZERO);
1695        self.hits.insert(format!("cam:form:tool:{id}"), egui::Rect::from_min_size(anchor, egui::Vec2::ZERO));
1696        self.push_overlay(state, doc, None);
1697        if out.changed {
1698            self.notice = None;
1699            // The work material is the calculator's input, not the tool's.
1700            self.feeds_material = params.get("feedsMaterial").and_then(Value::as_str).map(str::to_string);
1701            let coalesce = format!("tool:{id}:form");
1702            if let Err(why) = update_tool(state, id, &params, Some(&coalesce)) {
1703                self.refuse(state, why);
1704            }
1705        }
1706        if out.button_clicked.as_deref() == Some("calculateFeeds") {
1707            let material = params.get("feedsMaterial").and_then(Value::as_str).unwrap_or("aluminium").to_string();
1708            match calculate_tool_feeds(state, id, &material) {
1709                Ok(adjustments) => {
1710                    self.notice = Some(if adjustments.is_empty() { format!("feeds calculated for {material}") } else { format!("feeds calculated for {material}: {}", adjustments.join("; ")) });
1711                }
1712                Err(why) => self.refuse(state, why),
1713            }
1714        }
1715        if out.exit_clicked {
1716            self.open = None;
1717            self.user_library = None;
1718        }
1719        let _ = store;
1720    }
1721
1722    /// Push (or clear) the viewport overlay for setup `id`: its stock box and
1723    /// its frame's triad. Unchanged geometry is not re-sent.
1724    fn push_overlay(&mut self, state: &mut EngineState, doc: &CamDocument, id: Option<String>) {
1725        self.refresh_geometry(state);
1726        let group = id
1727            .as_deref()
1728            .filter(|id| doc.setup(id).is_some())
1729            .and_then(|id| self.geometry.get(id))
1730            .map(|geometry| {
1731                let frame = geometry.frame.clone().unwrap_or_default();
1732                cam_setup::overlay_group(&frame, geometry.stock)
1733            })
1734            .unwrap_or_else(|| json!({ "name": "cam-setup" }));
1735        let key = (group.to_string(), state.cam.results_stamp, self.selected.clone(), self.scrub.map(f64::to_bits), self.hidden_stamp);
1736        if self.overlay_key.as_ref() == Some(&key) {
1737            return;
1738        }
1739        self.overlay_key = Some(key);
1740        // Every generated toolpath, the selected operation's at full strength
1741        // with the scrub marker; a result that is gone takes its group away.
1742        let mut groups = vec![group];
1743        let mut live: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
1744        for (op, result) in &state.cam.results {
1745            if self.hidden_toolpaths.contains(op) {
1746                continue;
1747            }
1748            if let Some(toolpath) = &result.toolpath {
1749                let selected = self.selected.as_deref() == Some(op.as_str());
1750                let operation = doc.operation(op);
1751                let to_model = operation.and_then(|o| doc.setup(o.setup.as_str())).map(|s| s.machine_to_model()).unwrap_or_default();
1752                let profile = if selected && self.scrub.is_some() {
1753                    operation.and_then(|o| doc.tool(o.tool.as_str())).and_then(cam_generate::tool_profile)
1754                } else {
1755                    None
1756                };
1757                groups.push(cam_generate::toolpath_group(op, Some(toolpath), selected, if selected { self.scrub } else { None }, &to_model, profile.as_ref()));
1758                live.insert(op.clone());
1759            }
1760        }
1761        for gone in self.overlay_ops.difference(&live) {
1762            groups.push(cam_generate::toolpath_group(gone, None, false, None, &RigidTransform::default(), None));
1763        }
1764        self.overlay_ops = live;
1765        let json = json!({ "groups": groups }).to_string();
1766        if json != self.overlay {
1767            let _ = state.widgets.set_overlay_json(&json);
1768            state.dirty = true;
1769            self.overlay = json;
1770        }
1771    }
1772
1773    /// The per-frame widget rects for the headed verifier.
1774    pub fn hits_json(&self) -> String {
1775        let mut all = self.hits.clone();
1776        all.extend(self.sim.hit_rects().iter().map(|(k, r)| (k.clone(), *r)));
1777        all.extend(self.post.hit_rects().iter().map(|(k, r)| (k.clone(), *r)));
1778        crate::automation::hit_rects::hits_json(&all)
1779    }
1780
1781    /// Drop the published rects: the dock calls this for a pane it did not
1782    /// draw this frame, whose widgets are not on screen.
1783    pub fn clear_hits(&mut self) {
1784        self.hits.clear();
1785        self.sim.clear_hits();
1786    }
1787}
1788
1789pub static HIT_KEYS: &[HitKeyDoc] = &[
1790    HitKeyDoc { panel: "cam", prefix: "cam:auto:", meaning: "automatic programming preview, feature checkboxes, create and close", command: Some("cam_autoprogram") },
1791    HitKeyDoc { panel: "cam", prefix: "panel:clip", meaning: "the visible region of the pane (scroll_into_view scrolls a cam:* widget inside it)", command: None },
1792    HitKeyDoc { panel: "cam", prefix: "cam:new:setup", meaning: "add a setup (the toolbar's New setup)", command: Some("cam_add_setup") },
1793    HitKeyDoc { panel: "cam", prefix: "cam:new:tool", meaning: "add a tool to the document's library (the toolbar's New tool)", command: Some("cam_add_tool") },
1794    HitKeyDoc { panel: "cam", prefix: "cam:new:operation", meaning: "add an operation to the selected setup with the selected tool (the toolbar's New operation)", command: Some("cam_add_operation") },
1795    HitKeyDoc { panel: "cam", prefix: "cam:generate", meaning: "generate the toolpaths of every operation that needs it (the toolbar's Generate)", command: Some("cam_generate") },
1796    HitKeyDoc { panel: "cam", prefix: "cam:progress", meaning: "the generation line under the header: the operation generating, its phase and count, the queue; after a cancel, what was cancelled", command: None },
1797    HitKeyDoc { panel: "cam", prefix: "cam:cancel", meaning: "cancel the generation: the queue is dropped at once, the operation in flight stops at its next chunk where the runner can", command: Some("cam_cancel") },
1798    HitKeyDoc { panel: "cam", prefix: "cam:error", meaning: "why the document's `cam` block cannot be read (every edit is refused until it is repaired)", command: None },
1799    HitKeyDoc { panel: "cam", prefix: "cam:notice", meaning: "what the last action said that was not a record (a refusal, a count)", command: None },
1800    HitKeyDoc { panel: "cam", prefix: "cam:section:", meaning: "a section header (cam:section:setups, cam:section:programs, cam:section:tools, cam:section:machines) \u{2014} click folds it", command: None },
1801    HitKeyDoc { panel: "cam", prefix: "cam:machines:", meaning: "the Machines section's New machine menu (cam:machines:new) and, while it is open, one entry per built-in machine to copy (cam:machines:new:<built-in id>)", command: Some("cam_add_machine") },
1802    HitKeyDoc { panel: "cam", prefix: "cam:row:", meaning: "a setup, operation, NC program, tool or document machine row (cam:row:<id>) \u{2014} a click selects it (again to clear); right-click for its menu", command: Some("cam_select") },
1803    HitKeyDoc { panel: "cam", prefix: "cam:menuitem:", meaning: "one entry of the OPEN row menu (cam:menuitem:<id>:delete; a setup's or an operation's :edit; an operation's :toolpath = Hide / Show toolpath; a machine's :edit; a tool's :edit, :duplicate and :library) \u{2014} published only while the menu is up", command: Some("cam_remove") },
1804    HitKeyDoc { panel: "cam", prefix: "cam:form:", meaning: "the open setup, tool, operation or machine dialog (cam:form:setup:<id>, cam:form:tool:<id>, cam:form:operation:<id>, cam:form:machine:<id>, cam:form:feature, cam:form:return)", command: Some("cam_open") },
1805    HitKeyDoc { panel: "cam", prefix: "cam:field:", meaning: "one control of the open dialog (cam:field:<path>, nested paths joined by `.`, plus #activate on a reference field): a setup's name, wcsNumber, zRef, xRef, originRef, stockKind and its parameters, clearance, retract, feed, targets, protected; a tool's name, number, kind, description, material, the geometry, holderFamily/holderBore/holderHeight, spindleRpm, spindleDirection, cuttingFeed, plungeFeed, feedsMaterial, calculateFeeds, coolant; an operation's name, enabled, strategyKind, tool, feedsOverride, feeds.*, targets.targetSolids / driveFaces / avoidFaces / protectedSolids, targets.chainEdges / chainProfile (pickers that add a chain), the chain list targets.chains.<i>.source.kind / summary / closed / reversed / side / offset / regions / startSet / start and its targets.removeChain<i> button, heightsOverride, heights.*, tolerance, stockToLeave.*, strategy.* (its strategy's parameters) and linking.*; a document machine's name, kind, post, toolChangeSeconds, spindle.*, feed.*, accelerationSet, travelSet, travel.min / max, kinematics, yAxis, axes.<i>.name / direction / origin / limitsSet / limitsMin / limitsMax and collision (read only)", command: Some("cam_update_setup") },
1806    HitKeyDoc { panel: "cam", prefix: "cam:tools:", meaning: "the Tool Library section's actions: cam:tools:library (the Add-from-user-library menu), cam:tools:import (the file chooser), cam:tools:export (the document's tools as a library file), cam:tools:export-user", command: Some("cam_library") },
1807    HitKeyDoc { panel: "cam", prefix: "cam:library:", meaning: "one entry of the OPEN Add-from-user-library menu (cam:library:<library tool id>) \u{2014} published only while the menu is up", command: Some("cam_library") },
1808];
1809