diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 7a429b385..50b54e053 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -730,8 +730,8 @@ fn browser_panel(app: &mut SolveApp, ui: &mut egui::Ui, timeline_above: bool) { } /// The tree on a translucent card over the workspace, instead of a column that takes width from -/// it (Preferences: "Float it over the workspace"). Drawn before the central view, in a layer -/// above it, so the viewport keeps the whole window and the card sits on top of it. +/// it (Preferences: "Float it over the workspace"). The card occupies the content below the +/// ribbon in either shell layout, leaving the viewport projection unchanged. pub fn floating(app: &mut SolveApp, ui: &mut egui::Ui, viewport: egui::Rect) { let t = Tokens::get(); app.tree.order.clear(); @@ -760,6 +760,7 @@ pub fn floating(app: &mut SolveApp, ui: &mut egui::Ui, viewport: egui::Rect) { }); }, ); + app.shell.browser = Some(card.response.rect); crate::scenario::publish_rect("browser:float", card.response.rect); finish_browser(app, ui, acts); } @@ -2277,7 +2278,7 @@ pub fn dims_overlay(app: &SolveApp, ctx: &egui::Context) { /// Where the browser's panels open: the viewport's top left corner. fn panel_pos(app: &SolveApp) -> Pos2 { - app.viewport.rect.map(|r| r.left_top() + vec2(16.0, 16.0)).unwrap_or(pos2(270.0, 140.0)) + app.viewport.rect.map(|r| crate::shell::content_rect(app, r).left_top() + vec2(16.0, 16.0)).unwrap_or(pos2(270.0, 140.0)) } /// The Capture Position question stands for saving. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index a6944e88b..6a96c74ae 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1178,7 +1178,10 @@ fn draw_revolve( } } if to_mode { - crate::frame::area(egui::Id::new("sc_canvas_area")).fixed_pos(box_at).order(egui::Order::Foreground).show(ui.ctx(), |ui| { + // This badge is read-only. Its placement follows the model and can overlap the + // command dialog, whose buttons must keep receiving clicks. + let area = crate::frame::area(egui::Id::new("sc_canvas_area")).fixed_pos(box_at).order(egui::Order::Foreground).interactable(false); + area.show(ui.ctx(), |ui| { egui::Frame::popup(ui.style()).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { let text = if extent.curved_to { "To surface".into() diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 529cc1fa1..5a06ffd63 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -2420,8 +2420,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { // Physical materials: the library's, then the design's own (material.create). let material_names = app.session.doc.material_names(); let t = Tokens::get(); - let vp = app.viewport.rect.unwrap_or_else(|| ctx.content_rect()); - let top = (vp.top() + crate::viewport::AXIS_VIEW_CLEARANCE).min((vp.bottom() - 360.0).max(vp.top())); + let vp = crate::shell::content_rect(app, app.viewport.rect.unwrap_or_else(|| ctx.content_rect())); // The Sketch Palette owns the right edge for as long as a sketch is being edited. A dialog // started there docks at the left instead, so neither panel hides the other. let side = if crate::sketch_palette::editing(app) && crate::sketch_palette::fits_beside_a_dialog(app, ctx) { @@ -2429,6 +2428,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } else { crate::frame::Side::Right }; + let top = crate::shell::panel_top(app, vp, vp.bottom(), side); // Dragged by its title band, the dialog keeps that offset from its docked place while it // is open (#1335), kept inside the viewport. let moved = crate::frame::dock_offset(ctx, title(&d.kind)); diff --git a/crates/ui-egui/src/dialogs_sheet_tests.rs b/crates/ui-egui/src/dialogs_sheet_tests.rs index 01d6f5875..92646293a 100644 --- a/crates/ui-egui/src/dialogs_sheet_tests.rs +++ b/crates/ui-egui/src/dialogs_sheet_tests.rs @@ -6,12 +6,14 @@ use crate::Services; use crate::dialogs::{apply_commands, for_feature as edit_dialog}; /// A 100 x 60 base flange on XY (2.5 mm steel). -fn plate() -> SolveApp { +fn plate(mode: crate::shell::LayoutMode) -> SolveApp { let mut s = Session::default(); s.execute("sketch.create", &json!({"plane": "XY", "name": "Base"})).unwrap(); s.execute("sketch.rectangle.two_point", &json!({"p0": [0, 0], "p1": [100, 60]})).unwrap(); s.execute("sketch.finish", &json!({})).unwrap(); - SolveApp::new(s, Services::default()) + let mut app = SolveApp::new(s, Services::default()); + app.ui.layout = mode; + app } fn run_all(app: &mut SolveApp, c: Vec<(String, Value)>) { @@ -24,350 +26,377 @@ fn run_all(app: &mut SolveApp, c: Vec<(String, Value)>) { /// dialog's height, angle and bend position; Edit Feature brings the edges back. #[test] fn flange_follows_the_picks() { - let mut app = plate(); - let sk = app.session.doc.features[0].id; - app.session.selection = vec![Sel::Profile { sketch: sk, index: 0 }]; - app.start("sheet.flange"); - let d = app.dialog.clone().unwrap(); - let c = apply_commands(&app, &d).unwrap(); - assert_eq!(c[0].1["type"], "base"); - assert_eq!(c[0].1["profiles"], json!([0])); - run_all(&mut app, c); - assert_eq!(app.session.model.state().sheets.len(), 1); - // Four edge flanges at once, 20 high, outside. - let edges: Vec = [[50.0, 0.0, 2.5], [50.0, 60.0, 2.5], [0.0, 30.0, 2.5], [100.0, 30.0, 2.5]] - .iter() - .filter_map(|p| edge_sel(&app.session, Vec3::new(p[0], p[1], p[2]))) - .collect(); - assert_eq!(edges.len(), 4); - app.session.selection = edges; - app.start("sheet.flange"); - let mut d = app.dialog.clone().unwrap(); - if let Kind::Sheet(Sm::Flange { height, position, .. }) = &mut d.kind { - *height = "20 mm".into(); - *position = 1; + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut app = plate(mode); + let sk = app.session.doc.features[0].id; + app.session.selection = vec![Sel::Profile { sketch: sk, index: 0 }]; + app.start("sheet.flange"); + let d = app.dialog.clone().unwrap(); + let c = apply_commands(&app, &d).unwrap(); + assert_eq!(c[0].1["type"], "base"); + assert_eq!(c[0].1["profiles"], json!([0])); + run_all(&mut app, c); + assert_eq!(app.session.model.state().sheets.len(), 1); + // Four edge flanges at once, 20 high, outside. + let edges: Vec = [[50.0, 0.0, 2.5], [50.0, 60.0, 2.5], [0.0, 30.0, 2.5], [100.0, 30.0, 2.5]] + .iter() + .filter_map(|p| edge_sel(&app.session, Vec3::new(p[0], p[1], p[2]))) + .collect(); + assert_eq!(edges.len(), 4); + app.session.selection = edges; + app.start("sheet.flange"); + let mut d = app.dialog.clone().unwrap(); + if let Kind::Sheet(Sm::Flange { height, position, .. }) = &mut d.kind { + *height = "20 mm".into(); + *position = 1; + } + assert_eq!(d.primary().map(|p| p.0), Some("Height"), "the arrow drives the height"); + assert!(arrow(&app, &d).is_some_and(|n| n.dist(Vec3::Z) < 1e-9), "edge flanges rise out of the sheet"); + let c = apply_commands(&app, &d).unwrap(); + assert_eq!(c[0].1["type"], "edge"); + assert_eq!(c[0].1["edges"].as_array().map(Vec::len), Some(4)); + assert_eq!(c[0].1["position"], "outside"); + run_all(&mut app, c); + let f = app.session.doc.features.last().unwrap().clone(); + let e = edit_dialog(&app, f.id, None).unwrap(); + assert_eq!(e.inputs[0].items.len(), 4); + assert!(matches!(&e.kind, Kind::Sheet(Sm::Flange { ty: 1, position: 1, .. }))); + // Rebuilt in place. + let c = apply_commands(&app, &e).unwrap(); + assert_eq!(c[0].0, "timeline.redefine"); + assert_eq!(c[0].1["params"]["height"], "20 mm"); + // Flat pattern: four bends; Unfold previews. + let flat = app.session.execute("sheet.flat_pattern", &json!({})).unwrap(); + assert_eq!(flat["bends"].as_array().map(Vec::len), Some(4), "{flat}"); + app.dialog = None; + app.start("sheet.unfold"); + assert_eq!(apply_commands(&app, app.dialog.as_ref().unwrap()).unwrap()[0].0, "sheet.unfold"); } - assert_eq!(d.primary().map(|p| p.0), Some("Height"), "the arrow drives the height"); - assert!(arrow(&app, &d).is_some_and(|n| n.dist(Vec3::Z) < 1e-9), "edge flanges rise out of the sheet"); - let c = apply_commands(&app, &d).unwrap(); - assert_eq!(c[0].1["type"], "edge"); - assert_eq!(c[0].1["edges"].as_array().map(Vec::len), Some(4)); - assert_eq!(c[0].1["position"], "outside"); - run_all(&mut app, c); - let f = app.session.doc.features.last().unwrap().clone(); - let e = edit_dialog(&app, f.id, None).unwrap(); - assert_eq!(e.inputs[0].items.len(), 4); - assert!(matches!(&e.kind, Kind::Sheet(Sm::Flange { ty: 1, position: 1, .. }))); - // Rebuilt in place. - let c = apply_commands(&app, &e).unwrap(); - assert_eq!(c[0].0, "timeline.redefine"); - assert_eq!(c[0].1["params"]["height"], "20 mm"); - // Flat pattern: four bends; Unfold previews. - let flat = app.session.execute("sheet.flat_pattern", &json!({})).unwrap(); - assert_eq!(flat["bends"].as_array().map(Vec::len), Some(4), "{flat}"); - app.dialog = None; - app.start("sheet.unfold"); - assert_eq!(apply_commands(&app, app.dialog.as_ref().unwrap()).unwrap()[0].0, "sheet.unfold"); } /// Hem takes edges and an optional gap; rules make and pick a rule with its expressions. #[test] fn hem_and_rules() { - let mut app = plate(); - app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); - app.session.selection = edge_sel(&app.session, Vec3::new(50.0, 0.0, 2.5)).into_iter().collect(); - app.start("sheet.hem"); - let d = app.dialog.clone().unwrap(); - let c = apply_commands(&app, &d).unwrap(); - assert_eq!(c[0].1["length"], "5 mm"); - assert!(c[0].1.get("gap").is_none(), "the rule's gap"); - run_all(&mut app, c); - app.dialog = None; - app.start("sheet.manage_rules"); - let mut d = app.dialog.clone().unwrap(); - if let Kind::Sheet(Sm::Rules { pick, name, values, loaded, .. }) = &mut d.kind { - *pick = 1; - *loaded = Some(1); - *name = "Alu".into(); - *values = vec![ - "1.5 mm".into(), - "0.4".into(), - "Thickness".into(), - "Thickness".into(), - "Thickness".into(), - "Thickness".into(), - "Thickness".into(), - "Thickness".into(), - ]; + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut app = plate(mode); + app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); + app.session.selection = edge_sel(&app.session, Vec3::new(50.0, 0.0, 2.5)).into_iter().collect(); + app.start("sheet.hem"); + let d = app.dialog.clone().unwrap(); + let c = apply_commands(&app, &d).unwrap(); + assert_eq!(c[0].1["length"], "5 mm"); + assert!(c[0].1.get("gap").is_none(), "the rule's gap"); + run_all(&mut app, c); + app.dialog = None; + app.start("sheet.manage_rules"); + let mut d = app.dialog.clone().unwrap(); + if let Kind::Sheet(Sm::Rules { pick, name, values, loaded, .. }) = &mut d.kind { + *pick = 1; + *loaded = Some(1); + *name = "Alu".into(); + *values = vec![ + "1.5 mm".into(), + "0.4".into(), + "Thickness".into(), + "Thickness".into(), + "Thickness".into(), + "Thickness".into(), + "Thickness".into(), + "Thickness".into(), + ]; + } + let c = apply_commands(&app, &d).unwrap(); + assert_eq!(c[0].1["name"], "Alu"); + assert_eq!(c[0].1["thickness"], "1.5 mm"); + run_all(&mut app, c); + assert!(app.session.doc.sheet.rules.iter().any(|r| r.name == "Alu")); } - let c = apply_commands(&app, &d).unwrap(); - assert_eq!(c[0].1["name"], "Alu"); - assert_eq!(c[0].1["thickness"], "1.5 mm"); - run_all(&mut app, c); - assert!(app.session.doc.sheet.rules.iter().any(|r| r.name == "Alu")); } #[test] fn flat_exports_use_the_save_picker() { - use std::sync::{Arc, Mutex}; - let mut app = plate(); - app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); - let picks = Arc::new(Mutex::new(Vec::new())); - let captured = picks.clone(); - app.services.pick_save = Some(Box::new(move |name, extensions| { - captured.lock().unwrap().push((name.to_string(), extensions.iter().map(|x| x.to_string()).collect::>())); - Box::pin(std::future::ready(None)) - })); - assert_eq!(export_flat(&mut app, "Base", "csv"), "Choose an export file…"); - crate::file_picker::tick(&mut app, &egui::Context::default()); - assert_eq!(export_flat(&mut app, "Base", "dxf"), "Choose an export file…"); - crate::file_picker::tick(&mut app, &egui::Context::default()); - let picks = picks.lock().unwrap(); - assert!(picks[0].0.ends_with("-Base.csv")); - assert_eq!(picks[0].1, vec!["csv"]); - assert!(picks[1].0.ends_with("-Base.dxf")); - assert_eq!(picks[1].1, vec!["dxf"]); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + use std::sync::{Arc, Mutex}; + let mut app = plate(mode); + app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); + let picks = Arc::new(Mutex::new(Vec::new())); + let captured = picks.clone(); + app.services.pick_save = Some(Box::new(move |name, extensions| { + captured.lock().unwrap().push((name.to_string(), extensions.iter().map(|x| x.to_string()).collect::>())); + Box::pin(std::future::ready(None)) + })); + assert_eq!(export_flat(&mut app, "Base", "csv"), "Choose an export file…"); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert_eq!(export_flat(&mut app, "Base", "dxf"), "Choose an export file…"); + crate::file_picker::tick(&mut app, &egui::Context::default()); + let picks = picks.lock().unwrap(); + assert!(picks[0].0.ends_with("-Base.csv")); + assert_eq!(picks[0].1, vec!["csv"]); + assert!(picks[1].0.ends_with("-Base.dxf")); + assert_eq!(picks[1].1, vec!["dxf"]); + } } #[test] fn shallow_pocket_overlay_labels_depth_without_drawing_a_through_void() { - let mut app = plate(); - app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); - app.run("sketch.create", json!({"plane": "XY", "name": "Pocket"})).unwrap(); - app.run("sketch.rectangle.two_point", json!({"p0": [20, 20], "p1": [30, 30]})).unwrap(); - app.run("sketch.finish", json!({})).unwrap(); - app.run("solid.extrude", json!({"sketch": "Pocket", "distance": 1, "operation": "cut"})).unwrap(); - let flat = app.session.execute("sheet.flat_pattern", &json!({})).unwrap(); - assert_eq!(flat["cutouts"], json!([])); - assert_eq!(flat["pockets"][0]["depth_mm"], 1.0); - app.start("sheet.flat_pattern"); - let mut dialog = app.dialog.clone().unwrap(); - let Kind::Sheet(Sm::FlatPattern { data, .. }) = &mut dialog.kind else { panic!("flat dialog") }; - *data = Some(Ok(flat)); - let ctx = egui::Context::default(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::new("flat-pocket-test"))); - assert!(overlay(&mut app, &painter, Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0)), &dialog)); - }); - output.textures_delta.clear(); - let texts: Vec<&str> = output - .shapes - .iter() - .filter_map(|s| match &s.shape { - egui::Shape::Text(text) => Some(text.galley.text()), - _ => None, - }) - .collect(); - assert!(texts.contains(&"Bottom pocket: 1.00 mm deep")); - assert!(texts.contains(&"Pocket boundary (material remains)")); - let paths: Vec<_> = output - .shapes - .iter() - .filter_map(|s| match &s.shape { - egui::Shape::Path(path) => Some(path), - _ => None, - }) - .collect(); - assert!(!paths.is_empty(), "the retained sheet outline is drawn"); - assert!(paths.iter().all(|p| p.fill == Color32::TRANSPARENT), "pockets must not be rendered as filled voids"); - let lines = output.shapes.iter().filter(|s| matches!(s.shape, egui::Shape::LineSegment { .. })).count(); - assert!(lines > 6, "pocket contours and legend use dashed lines, not through-cut strokes"); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut app = plate(mode); + app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); + app.run("sketch.create", json!({"plane": "XY", "name": "Pocket"})).unwrap(); + app.run("sketch.rectangle.two_point", json!({"p0": [20, 20], "p1": [30, 30]})).unwrap(); + app.run("sketch.finish", json!({})).unwrap(); + app.run("solid.extrude", json!({"sketch": "Pocket", "distance": 1, "operation": "cut"})).unwrap(); + let flat = app.session.execute("sheet.flat_pattern", &json!({})).unwrap(); + assert_eq!(flat["cutouts"], json!([])); + assert_eq!(flat["pockets"][0]["depth_mm"], 1.0); + app.start("sheet.flat_pattern"); + let mut dialog = app.dialog.clone().unwrap(); + let Kind::Sheet(Sm::FlatPattern { data, .. }) = &mut dialog.kind else { panic!("flat dialog") }; + *data = Some(Ok(flat)); + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::new("flat-pocket-test"))); + assert!(overlay(&mut app, &painter, Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0)), &dialog)); + }); + output.textures_delta.clear(); + let texts: Vec<&str> = output + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Text(text) => Some(text.galley.text()), + _ => None, + }) + .collect(); + assert!(texts.contains(&"Bottom pocket: 1.00 mm deep")); + assert!(texts.contains(&"Pocket boundary (material remains)")); + let paths: Vec<_> = output + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Path(path) => Some(path), + _ => None, + }) + .collect(); + assert!(!paths.is_empty(), "the retained sheet outline is drawn"); + assert!(paths.iter().all(|p| p.fill == Color32::TRANSPARENT), "pockets must not be rendered as filled voids"); + let lines = output.shapes.iter().filter(|s| matches!(s.shape, egui::Shape::LineSegment { .. })).count(); + assert!(lines > 6, "pocket contours and legend use dashed lines, not through-cut strokes"); + } } #[test] fn flat_pattern_islands_fit_before_the_actual_command_panel() { - let mut app = plate(); - app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); - app.run("sketch.create", json!({"plane": "XY", "name": "Retain"})).unwrap(); - for x in [20, 60] { - app.run("sketch.rectangle.two_point", json!({"p0": [x, 20], "p1": [x + 10, 30]})).unwrap(); - } - app.run("sketch.finish", json!({})).unwrap(); - app.run("solid.extrude", json!({"sketch": "Retain", "profiles": "all", "through_all": true, "direction": "symmetric", "operation": "intersect"})) + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut app = plate(mode); + app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); + app.run("sketch.create", json!({"plane": "XY", "name": "Retain"})).unwrap(); + for x in [20, 60] { + app.run("sketch.rectangle.two_point", json!({"p0": [x, 20], "p1": [x + 10, 30]})).unwrap(); + } + app.run("sketch.finish", json!({})).unwrap(); + app.run( + "solid.extrude", + json!({"sketch": "Retain", "profiles": "all", "through_all": true, "direction": "symmetric", "operation": "intersect"}), + ) .unwrap(); - let flat = app.session.execute("sheet.flat_pattern", &json!({})).unwrap(); - assert_eq!(flat["outline"].as_array().unwrap().len(), 2); - app.start("sheet.flat_pattern"); - let mut dialog = app.dialog.clone().unwrap(); - let Kind::Sheet(Sm::FlatPattern { data, .. }) = &mut dialog.kind else { panic!("flat dialog") }; - *data = Some(Ok(flat)); - let ctx = egui::Context::default(); - let id = egui::Id::new(("sc_dialog", "FLAT PATTERN")); - let mut output = egui::FullOutput::default(); - for _ in 0..3 { - output = ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), ..Default::default() }, |ui| { - crate::frame::docked("FLAT PATTERN", id, pos2(1400.0, 294.0), 540.0, crate::frame::Width::Normal).min_width(360.0).show(ui.ctx(), |ui| { - ui.label("Flat size: 50 × 10 × 2.5 mm"); - }); - let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Background, egui::Id::new("island-fit"))); - assert!(overlay( - &mut app, - &painter, - Rect::from_min_max(pos2(250.0, crate::toolbar::APP_BAR_HEIGHT + crate::toolbar::RIBBON_HEIGHT), pos2(1400.0, 832.0)), - &dialog - )); - }); - output.textures_delta.clear(); + let flat = app.session.execute("sheet.flat_pattern", &json!({})).unwrap(); + assert_eq!(flat["outline"].as_array().unwrap().len(), 2); + app.start("sheet.flat_pattern"); + let mut dialog = app.dialog.clone().unwrap(); + let Kind::Sheet(Sm::FlatPattern { data, .. }) = &mut dialog.kind else { panic!("flat dialog") }; + *data = Some(Ok(flat)); + let ctx = egui::Context::default(); + let id = egui::Id::new(("sc_dialog", "FLAT PATTERN")); + let mut output = egui::FullOutput::default(); + for _ in 0..3 { + output = + ctx.run_ui(egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), ..Default::default() }, |ui| { + crate::frame::docked("FLAT PATTERN", id, pos2(1400.0, 294.0), 540.0, crate::frame::Width::Normal).min_width(360.0).show( + ui.ctx(), + |ui| { + ui.label("Flat size: 50 × 10 × 2.5 mm"); + }, + ); + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Background, egui::Id::new("island-fit"))); + assert!(overlay( + &mut app, + &painter, + Rect::from_min_max(pos2(250.0, crate::toolbar::APP_BAR_HEIGHT + crate::toolbar::RIBBON_HEIGHT), pos2(1400.0, 832.0)), + &dialog + )); + }); + output.textures_delta.clear(); + } + let panel = ctx.memory(|m| m.area_rect(id)).unwrap(); + let outlines: Vec<_> = output + .shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Path(p) if p.closed && p.fill == Color32::TRANSPARENT => Some(p), + _ => None, + }) + .collect(); + assert_eq!(outlines.len(), 2, "both retained islands are drawn"); + assert!( + outlines.iter().flat_map(|p| &p.points).all(|p| p.x <= panel.left() - 19.0), + "both complete islands must remain exposed before the command panel: {panel:?}" + ); } - let panel = ctx.memory(|m| m.area_rect(id)).unwrap(); - let outlines: Vec<_> = output - .shapes - .iter() - .filter_map(|s| match &s.shape { - egui::Shape::Path(p) if p.closed && p.fill == Color32::TRANSPARENT => Some(p), - _ => None, - }) - .collect(); - assert_eq!(outlines.len(), 2, "both retained islands are drawn"); - assert!( - outlines.iter().flat_map(|p| &p.points).all(|p| p.x <= panel.left() - 19.0), - "both complete islands must remain exposed before the command panel: {panel:?}" - ); } #[test] fn coincident_top_and_bottom_pocket_depths_share_a_readable_annotation() { - let mut app = plate(); - app.run("sheet.flange", json!({"sketch":"Base"})).unwrap(); - app.run("sketch.create", json!({"plane":"XY","name":"Retain"})).unwrap(); - app.run("sketch.rectangle.two_point", json!({"p0":[20,20],"p1":[30,30]})).unwrap(); - app.run("sketch.finish", json!({})).unwrap(); - app.run("solid.extrude", json!({"sketch":"Retain","distance":1,"start_offset":0.5,"operation":"intersect"})).unwrap(); - let flat = app.session.execute("sheet.flat_pattern", &json!({})).unwrap(); - assert_eq!(flat["cutouts"], json!([])); - assert_eq!(flat["pockets"].as_array().unwrap().len(), 2); - let doc = app.session.doc.to_json(); - app.start("sheet.flat_pattern"); - let mut dialog = app.dialog.clone().unwrap(); - let Kind::Sheet(Sm::FlatPattern { data, .. }) = &mut dialog.kind else { panic!("flat dialog") }; - *data = Some(Ok(flat)); - let ctx = egui::Context::default(); - let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { - let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::new("coincident-pocket-test"))); - assert!(overlay(&mut app, &painter, Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0)), &dialog)); - }); - output.textures_delta.clear(); - let labels: Vec<_> = output - .shapes - .iter() - .filter_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.text().contains("pocket:") => Some(text.galley.text()), - _ => None, - }) - .collect(); - assert_eq!(labels.len(), 1, "coincident depths must not overwrite one another"); - assert!(labels[0].contains("Top pocket: 1.00 mm deep")); - assert!(labels[0].contains("Bottom pocket: 0.50 mm deep")); - assert!(labels[0].contains('\n')); - assert_eq!(app.session.doc.to_json(), doc); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut app = plate(mode); + app.run("sheet.flange", json!({"sketch":"Base"})).unwrap(); + app.run("sketch.create", json!({"plane":"XY","name":"Retain"})).unwrap(); + app.run("sketch.rectangle.two_point", json!({"p0":[20,20],"p1":[30,30]})).unwrap(); + app.run("sketch.finish", json!({})).unwrap(); + app.run("solid.extrude", json!({"sketch":"Retain","distance":1,"start_offset":0.5,"operation":"intersect"})).unwrap(); + let flat = app.session.execute("sheet.flat_pattern", &json!({})).unwrap(); + assert_eq!(flat["cutouts"], json!([])); + assert_eq!(flat["pockets"].as_array().unwrap().len(), 2); + let doc = app.session.doc.to_json(); + app.start("sheet.flat_pattern"); + let mut dialog = app.dialog.clone().unwrap(); + let Kind::Sheet(Sm::FlatPattern { data, .. }) = &mut dialog.kind else { panic!("flat dialog") }; + *data = Some(Ok(flat)); + let ctx = egui::Context::default(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Middle, egui::Id::new("coincident-pocket-test"))); + assert!(overlay(&mut app, &painter, Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0)), &dialog)); + }); + output.textures_delta.clear(); + let labels: Vec<_> = output + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text().contains("pocket:") => Some(text.galley.text()), + _ => None, + }) + .collect(); + assert_eq!(labels.len(), 1, "coincident depths must not overwrite one another"); + assert!(labels[0].contains("Top pocket: 1.00 mm deep")); + assert!(labels[0].contains("Bottom pocket: 0.50 mm deep")); + assert!(labels[0].contains('\n')); + assert_eq!(app.session.doc.to_json(), doc); + } } #[test] fn pocket_export_button_uses_the_picker_and_preserves_depth_layers() { - let mut h = crate::scenario::Harness::new(); - for (command, params) in [ - ("sketch.create", json!({"plane":"XY","name":"Base"})), - ("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[100,60]})), - ("sketch.finish", json!({})), - ("sheet.flange", json!({"sketch":"Base"})), - ("sketch.create", json!({"plane":"XY","name":"Pocket"})), - ("sketch.rectangle.two_point", json!({"p0":[20,20],"p1":[30,30]})), - ("sketch.finish", json!({})), - ("solid.extrude", json!({"sketch":"Pocket","distance":1,"operation":"cut"})), - ] { - h.app.run(command, params).unwrap(); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = crate::scenario::Harness::new(); + h.call("ui.set", json!({"layout":mode})); + for (command, params) in [ + ("sketch.create", json!({"plane":"XY","name":"Base"})), + ("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[100,60]})), + ("sketch.finish", json!({})), + ("sheet.flange", json!({"sketch":"Base"})), + ("sketch.create", json!({"plane":"XY","name":"Pocket"})), + ("sketch.rectangle.two_point", json!({"p0":[20,20],"p1":[30,30]})), + ("sketch.finish", json!({})), + ("solid.extrude", json!({"sketch":"Pocket","distance":1,"operation":"cut"})), + ] { + h.app.run(command, params).unwrap(); + } + let path = h.dir.join("picked-pocket.dxf"); + let chosen = path.to_string_lossy().into_owned(); + h.app.services.pick_save = Some(Box::new(move |name, extensions| { + assert!(name.ends_with("-Body1.dxf")); + assert_eq!(extensions, &["dxf"]); + Box::pin(std::future::ready(Some(chosen.clone()))) + })); + h.app.start("sheet.flat_pattern"); + h.settle(); + let undo = h.app.session.undo.len(); + h.step(&json!({"widget":"Export DXF…"})).unwrap(); + let exported = std::fs::read_to_string(&path).expect("actual Export DXF button writes the picker destination"); + assert!(exported.contains("POCKET_BOTTOM_Z0.000000_TO_1.000000_MM")); + assert!(exported.contains("OUTLINE")); + assert_eq!(h.app.session.undo.len(), undo, "export does not alter the part"); + assert!(h.app.dialog.is_some(), "export keeps the flat viewer open"); } - let path = h.dir.join("picked-pocket.dxf"); - let chosen = path.to_string_lossy().into_owned(); - h.app.services.pick_save = Some(Box::new(move |name, extensions| { - assert!(name.ends_with("-Body1.dxf")); - assert_eq!(extensions, &["dxf"]); - Box::pin(std::future::ready(Some(chosen.clone()))) - })); - h.app.start("sheet.flat_pattern"); - h.settle(); - let undo = h.app.session.undo.len(); - h.step(&json!({"widget":"Export DXF…"})).unwrap(); - let exported = std::fs::read_to_string(&path).expect("actual Export DXF button writes the picker destination"); - assert!(exported.contains("POCKET_BOTTOM_Z0.000000_TO_1.000000_MM")); - assert!(exported.contains("OUTLINE")); - assert_eq!(h.app.session.undo.len(), undo, "export does not alter the part"); - assert!(h.app.dialog.is_some(), "export keeps the flat viewer open"); } #[test] #[cfg(not(target_arch = "wasm32"))] fn bend_table_picker_writes_the_current_body() { - let mut app = plate(); - app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); - app.run("sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20})).unwrap(); - let body = app.session.model.state().sheets[0].body.clone(); - let path = std::env::temp_dir().join(format!("solidcraft-bend-table-{}.csv", std::process::id())); - let output = path.to_string_lossy().into_owned(); - let chosen = output.clone(); - app.services.pick_save = Some(Box::new(move |_, extensions| { - assert_eq!(extensions, &["csv"]); - Box::pin(std::future::ready(Some(chosen.clone()))) - })); - let undo = app.session.undo.len(); - assert_eq!(export_flat(&mut app, &body, "csv"), "Choose an export file…"); - crate::file_picker::tick(&mut app, &egui::Context::default()); - assert_eq!(app.status.as_ref().map(|s| &s.0), Some(&format!("Exported {output}"))); - let contents = std::fs::read_to_string(&path).unwrap(); - std::fs::remove_file(&path).unwrap(); - assert_eq!(contents.lines().count(), 2); - assert!(contents.contains(",90.000000000,up,2.500000000,"), "{contents}"); - assert_eq!(app.session.undo.len(), undo); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut app = plate(mode); + app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); + app.run("sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20})).unwrap(); + let body = app.session.model.state().sheets[0].body.clone(); + let path = std::env::temp_dir().join(format!("solidcraft-bend-table-{}.csv", std::process::id())); + let output = path.to_string_lossy().into_owned(); + let chosen = output.clone(); + app.services.pick_save = Some(Box::new(move |_, extensions| { + assert_eq!(extensions, &["csv"]); + Box::pin(std::future::ready(Some(chosen.clone()))) + })); + let undo = app.session.undo.len(); + assert_eq!(export_flat(&mut app, &body, "csv"), "Choose an export file…"); + crate::file_picker::tick(&mut app, &egui::Context::default()); + assert_eq!(app.status.as_ref().map(|s| &s.0), Some(&format!("Exported {output}"))); + let contents = std::fs::read_to_string(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + assert_eq!(contents.lines().count(), 2); + assert!(contents.contains(",90.000000000,up,2.500000000,"), "{contents}"); + assert_eq!(app.session.undo.len(), undo); + } } /// The rule manager's shape selector: picked in the dialog, the shape reaches the rule and the part /// made with it, and the dialog shows it the next time. #[test] fn rules_dialog_picks_the_corner_relief_shape() { - let mut h = crate::scenario::Harness::new(); - h.app - .run( - "sheet.manage_rules", - json!({"name": "AL2", "thickness": "2 mm", "k_factor": 0.5, "bend_radius": "1 mm", "gap": "0.5 mm", "active": true}), - ) - .unwrap(); - h.app.run("sketch.create", json!({"plane": "XY", "name": "Base"})).unwrap(); - h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [120, 90]})).unwrap(); - h.app.run("sketch.finish", json!({})).unwrap(); - h.app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); - h.app.run("sheet.flange", json!({"edges": [[60, 0, 2], [120, 45, 2], [60, 90, 2], [0, 45, 2]], "height": 20, "angle": "72 deg"})).unwrap(); - // The rounds in the base of the tray, and the shape the open dialog shows. - let rounds = |app: &SolveApp| { - let state = app.session.model.state(); - state.sheets.last().map(|s| s.base.outer.segs.iter().filter(|g| matches!(g, solidcraft_engine::geom::Seg2::Arc { .. })).count()) - }; - let shown = |app: &SolveApp| match app.dialog.as_ref().map(|d| &d.kind) { - Some(Kind::Sheet(Sm::Rules { relief, .. })) => Some(*relief), - _ => None, - }; - assert_eq!(rounds(&h.app), Some(0)); - h.step(&json!({"start": "sheet.manage_rules"})).unwrap(); - h.frames(3); - assert_eq!(shown(&h.app), Some(0), "a rule starts with the notch"); - h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape"}})).unwrap(); - h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape:Round"}})).unwrap(); - assert_eq!(shown(&h.app), Some(1)); - h.step(&json!({"widget": "OK"})).unwrap(); - assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog); - assert_eq!(h.app.session.doc.sheet_rule(None).corner_relief_shape, "round"); - assert_eq!(rounds(&h.app), Some(4), "one round at each corner of the tray"); - h.step(&json!({"start": "sheet.manage_rules"})).unwrap(); - h.frames(3); - assert_eq!(shown(&h.app), Some(1), "the dialog shows the rule's shape"); - // The tear: no relief in the base, both ends of all four bends torn. - h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape"}})).unwrap(); - h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape:Tear"}})).unwrap(); - assert_eq!(shown(&h.app), Some(3)); - h.step(&json!({"widget": "OK"})).unwrap(); - assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog); - assert_eq!(h.app.session.doc.sheet_rule(None).corner_relief_shape, "tear"); - let torn = h.app.session.model.state().sheets.last().map(|s| s.flanges.iter().filter(|f| f.tear == (true, true)).count()); - assert_eq!((rounds(&h.app), torn), (Some(0), Some(4))); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = crate::scenario::Harness::new(); + h.call("ui.set", json!({"layout":mode})); + h.app + .run( + "sheet.manage_rules", + json!({"name": "AL2", "thickness": "2 mm", "k_factor": 0.5, "bend_radius": "1 mm", "gap": "0.5 mm", "active": true}), + ) + .unwrap(); + h.app.run("sketch.create", json!({"plane": "XY", "name": "Base"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [120, 90]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); + h.app.run("sheet.flange", json!({"edges": [[60, 0, 2], [120, 45, 2], [60, 90, 2], [0, 45, 2]], "height": 20, "angle": "72 deg"})).unwrap(); + // The rounds in the base of the tray, and the shape the open dialog shows. + let rounds = |app: &SolveApp| { + let state = app.session.model.state(); + state.sheets.last().map(|s| s.base.outer.segs.iter().filter(|g| matches!(g, solidcraft_engine::geom::Seg2::Arc { .. })).count()) + }; + let shown = |app: &SolveApp| match app.dialog.as_ref().map(|d| &d.kind) { + Some(Kind::Sheet(Sm::Rules { relief, .. })) => Some(*relief), + _ => None, + }; + assert_eq!(rounds(&h.app), Some(0)); + h.step(&json!({"start": "sheet.manage_rules"})).unwrap(); + h.frames(3); + assert_eq!(shown(&h.app), Some(0), "a rule starts with the notch"); + h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape"}})).unwrap(); + h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape:Round"}})).unwrap(); + assert_eq!(shown(&h.app), Some(1)); + h.step(&json!({"widget": "OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog); + assert_eq!(h.app.session.doc.sheet_rule(None).corner_relief_shape, "round"); + assert_eq!(rounds(&h.app), Some(4), "one round at each corner of the tray"); + h.step(&json!({"start": "sheet.manage_rules"})).unwrap(); + h.frames(3); + assert_eq!(shown(&h.app), Some(1), "the dialog shows the rule's shape"); + // The tear: no relief in the base, both ends of all four bends torn. + h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape"}})).unwrap(); + h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape:Tear"}})).unwrap(); + assert_eq!(shown(&h.app), Some(3)); + h.step(&json!({"widget": "OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog); + assert_eq!(h.app.session.doc.sheet_rule(None).corner_relief_shape, "tear"); + let torn = h.app.session.model.state().sheets.last().map(|s| s.flanges.iter().filter(|f| f.tear == (true, true)).count()); + assert_eq!((rounds(&h.app), torn), (Some(0), Some(4))); + } } /// The rule manager's rectangular relief, on a base whose corners are not square: the shape and @@ -433,80 +462,86 @@ fn the_rule_manager_relieves_a_corner_that_is_not_square() { /// a shape and a size reach the feature, Edit Feature shows them again, and Rule takes them back. #[test] fn flange_dialog_picks_a_corner_relief_of_its_own() { - let mut h = crate::scenario::Harness::new(); - h.app - .run( - "sheet.manage_rules", - json!({"name": "AL2", "thickness": "2 mm", "k_factor": 0.5, "bend_radius": "1 mm", "gap": "0.5 mm", "active": true}), - ) - .unwrap(); - h.app.run("sketch.create", json!({"plane": "XY", "name": "Base"})).unwrap(); - h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [120, 90]})).unwrap(); - h.app.run("sketch.finish", json!({})).unwrap(); - h.app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); - let edges: Vec = [[60.0, 0.0, 2.0], [0.0, 45.0, 2.0]].iter().filter_map(|p| edge_sel(&h.app.session, Vec3::new(p[0], p[1], p[2]))).collect(); - assert_eq!(edges.len(), 2); - h.app.session.selection = edges; - h.app.start("sheet.flange"); - h.frames(3); - let shown = |app: &SolveApp| match app.dialog.as_ref().map(|d| &d.kind) { - Some(Kind::Sheet(Sm::Flange { relief, relief_size, .. })) => Some((*relief, relief_size.clone())), - _ => None, - }; - let relief = |app: &SolveApp| match &app.session.doc.features.last().map(|f| &f.kind) { - Some(FeatureKind::SheetFlange { corner_relief_shape, corner_relief, .. }) => Some((corner_relief_shape.clone(), corner_relief.clone())), - _ => None, - }; - // Untouched, the dialog asks for nothing: the rule's relief. - assert_eq!(shown(&h.app), Some((0, String::new()))); - let d = h.app.dialog.clone().unwrap(); - let c = apply_commands(&h.app, &d).unwrap(); - assert!(c[0].1.get("corner_relief_shape").is_none() && c[0].1.get("corner_relief").is_none(), "{}", c[0].1); - // Round from the selector, 6 mm in the size row. - h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape"}})).unwrap(); - h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape:Round"}})).unwrap(); - assert_eq!(shown(&h.app), Some((2, String::new()))); - if let Some(Kind::Sheet(Sm::Flange { relief_size, .. })) = h.app.dialog.as_mut().map(|d| &mut d.kind) { - *relief_size = "6 mm".into(); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = crate::scenario::Harness::new(); + h.call("ui.set", json!({"layout":mode})); + h.app + .run( + "sheet.manage_rules", + json!({"name": "AL2", "thickness": "2 mm", "k_factor": 0.5, "bend_radius": "1 mm", "gap": "0.5 mm", "active": true}), + ) + .unwrap(); + h.app.run("sketch.create", json!({"plane": "XY", "name": "Base"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [120, 90]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); + let edges: Vec = + [[60.0, 0.0, 2.0], [0.0, 45.0, 2.0]].iter().filter_map(|p| edge_sel(&h.app.session, Vec3::new(p[0], p[1], p[2]))).collect(); + assert_eq!(edges.len(), 2); + h.app.session.selection = edges; + h.app.start("sheet.flange"); + h.frames(3); + let shown = |app: &SolveApp| match app.dialog.as_ref().map(|d| &d.kind) { + Some(Kind::Sheet(Sm::Flange { relief, relief_size, .. })) => Some((*relief, relief_size.clone())), + _ => None, + }; + let relief = |app: &SolveApp| match &app.session.doc.features.last().map(|f| &f.kind) { + Some(FeatureKind::SheetFlange { corner_relief_shape, corner_relief, .. }) => Some((corner_relief_shape.clone(), corner_relief.clone())), + _ => None, + }; + // Untouched, the dialog asks for nothing: the rule's relief. + assert_eq!(shown(&h.app), Some((0, String::new()))); + let d = h.app.dialog.clone().unwrap(); + let c = apply_commands(&h.app, &d).unwrap(); + assert!(c[0].1.get("corner_relief_shape").is_none() && c[0].1.get("corner_relief").is_none(), "{}", c[0].1); + // Round from the selector, 6 mm in the size row. + h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape"}})).unwrap(); + h.step(&json!({"click": {"handle": "dialog:Corner Relief Shape:Round"}})).unwrap(); + assert_eq!(shown(&h.app), Some((2, String::new()))); + if let Some(Kind::Sheet(Sm::Flange { relief_size, .. })) = h.app.dialog.as_mut().map(|d| &mut d.kind) { + *relief_size = "6 mm".into(); + } + let d = h.app.dialog.clone().unwrap(); + let c = apply_commands(&h.app, &d).unwrap(); + assert_eq!((&c[0].1["corner_relief_shape"], &c[0].1["corner_relief"]), (&json!("round"), &json!("6 mm"))); + h.step(&json!({"widget": "OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog); + assert_eq!(relief(&h.app), Some((Some("round".into()), Some("6 mm".into())))); + assert!(h.app.session.model.results.iter().all(|r| r.error.is_none() && r.warning.is_none()), "{:?}", h.app.session.model.results); + let arcs = |app: &SolveApp| { + app.session + .model + .state() + .sheets + .last() + .map(|s| s.base.outer.segs.iter().filter(|g| matches!(g, solidcraft_engine::geom::Seg2::Arc { .. })).count()) + }; + assert_eq!(arcs(&h.app), Some(1), "the round is cut at the one corner the two flanges make"); + // Edit Feature shows both again; Rule and an empty size take the feature back to the rule's relief. + let id = h.app.session.doc.features.last().map(|f| f.id).unwrap(); + let mut e = edit_dialog(&h.app, id, None).unwrap(); + assert!(matches!(&e.kind, Kind::Sheet(Sm::Flange { relief: 2, relief_size, .. }) if relief_size == "6 mm")); + let c = apply_commands(&h.app, &e).unwrap(); + assert_eq!((&c[0].1["params"]["corner_relief_shape"], &c[0].1["params"]["corner_relief"]), (&json!("round"), &json!("6 mm"))); + if let Kind::Sheet(Sm::Flange { relief, relief_size, .. }) = &mut e.kind { + *relief = 0; + relief_size.clear(); + } + let commands = apply_commands(&h.app, &e).unwrap(); + run_all(&mut h.app, commands); + assert_eq!(relief(&h.app), Some((None, None))); + assert_eq!(arcs(&h.app), Some(0)); } - let d = h.app.dialog.clone().unwrap(); - let c = apply_commands(&h.app, &d).unwrap(); - assert_eq!((&c[0].1["corner_relief_shape"], &c[0].1["corner_relief"]), (&json!("round"), &json!("6 mm"))); - h.step(&json!({"widget": "OK"})).unwrap(); - assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog); - assert_eq!(relief(&h.app), Some((Some("round".into()), Some("6 mm".into())))); - assert!(h.app.session.model.results.iter().all(|r| r.error.is_none() && r.warning.is_none()), "{:?}", h.app.session.model.results); - let arcs = |app: &SolveApp| { - app.session - .model - .state() - .sheets - .last() - .map(|s| s.base.outer.segs.iter().filter(|g| matches!(g, solidcraft_engine::geom::Seg2::Arc { .. })).count()) - }; - assert_eq!(arcs(&h.app), Some(1), "the round is cut at the one corner the two flanges make"); - // Edit Feature shows both again; Rule and an empty size take the feature back to the rule's relief. - let id = h.app.session.doc.features.last().map(|f| f.id).unwrap(); - let mut e = edit_dialog(&h.app, id, None).unwrap(); - assert!(matches!(&e.kind, Kind::Sheet(Sm::Flange { relief: 2, relief_size, .. }) if relief_size == "6 mm")); - let c = apply_commands(&h.app, &e).unwrap(); - assert_eq!((&c[0].1["params"]["corner_relief_shape"], &c[0].1["params"]["corner_relief"]), (&json!("round"), &json!("6 mm"))); - if let Kind::Sheet(Sm::Flange { relief, relief_size, .. }) = &mut e.kind { - *relief = 0; - relief_size.clear(); - } - let commands = apply_commands(&h.app, &e).unwrap(); - run_all(&mut h.app, commands); - assert_eq!(relief(&h.app), Some((None, None))); - assert_eq!(arcs(&h.app), Some(0)); } #[test] fn pocket_depth_labels_follow_inches_without_changing_flat_data() { - let mut app = plate(); - app.run("document.units", json!({"units":"in"})).unwrap(); - assert_eq!(super::pocket_label(&app, &json!({"side":"top","depth_mm":25.4*0.1234})).as_deref(), Some("Top pocket: 0.1234 in deep")); - assert!(super::pocket_label(&app, &json!({"side":"top","depth_mm":-1})).is_none()); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut app = plate(mode); + app.run("document.units", json!({"units":"in"})).unwrap(); + assert_eq!(super::pocket_label(&app, &json!({"side":"top","depth_mm":25.4*0.1234})).as_deref(), Some("Top pocket: 0.1234 in deep")); + assert!(super::pocket_label(&app, &json!({"side":"top","depth_mm":-1})).is_none()); + } } /// Edges with an angle and/or a height of their own: the texts of the dialog's rows per edge @@ -514,61 +549,63 @@ fn pocket_depth_labels_follow_inches_without_changing_flat_data() { /// brings them back and rebuilds the same flanges. #[test] fn edge_flanges_can_have_an_angle_and_a_height_of_their_own() { - let mut app = plate(); - app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); - let edges: Vec = [[50.0, 0.0, 2.5], [50.0, 60.0, 2.5], [0.0, 30.0, 2.5], [100.0, 30.0, 2.5]] - .iter() - .filter_map(|p| edge_sel(&app.session, Vec3::new(p[0], p[1], p[2]))) - .collect(); - assert_eq!(edges.len(), 4); - let point = |i: usize| if let Sel::Edge { point, .. } = &edges[i] { *point } else { Vec3::ZERO }; - app.session.selection = edges.clone(); - app.start("sheet.flange"); - let mut d = app.dialog.clone().unwrap(); - if let Kind::Sheet(Sm::Flange { height, angle, own, .. }) = &mut d.kind { - *height = "20 mm".into(); - *angle = "75 deg".into(); - // The second edge: its own angle; the fourth: both; the third: texts left blank. - own.push((point(1), "100 deg".into(), String::new())); - own.push((point(3), "90 deg".into(), "15 mm".into())); - own.push((point(2), " ".into(), String::new())); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut app = plate(mode); + app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); + let edges: Vec = [[50.0, 0.0, 2.5], [50.0, 60.0, 2.5], [0.0, 30.0, 2.5], [100.0, 30.0, 2.5]] + .iter() + .filter_map(|p| edge_sel(&app.session, Vec3::new(p[0], p[1], p[2]))) + .collect(); + assert_eq!(edges.len(), 4); + let point = |i: usize| if let Sel::Edge { point, .. } = &edges[i] { *point } else { Vec3::ZERO }; + app.session.selection = edges.clone(); + app.start("sheet.flange"); + let mut d = app.dialog.clone().unwrap(); + if let Kind::Sheet(Sm::Flange { height, angle, own, .. }) = &mut d.kind { + *height = "20 mm".into(); + *angle = "75 deg".into(); + // The second edge: its own angle; the fourth: both; the third: texts left blank. + own.push((point(1), "100 deg".into(), String::new())); + own.push((point(3), "90 deg".into(), "15 mm".into())); + own.push((point(2), " ".into(), String::new())); + } + let c = apply_commands(&app, &d).unwrap(); + assert_eq!( + c[0].1["edges"], + json!([pt(point(0)), {"point": pt(point(1)), "angle": "100 deg"}, pt(point(2)), {"point": pt(point(3)), "angle": "90 deg", "height": "15 mm"}]), + "no text or a blank one: a plain point" + ); + run_all(&mut app, c); + let bends = app.session.execute("sheet.flat_pattern", &json!({})).unwrap()["bends"].clone(); + let angles: Vec = bends.as_array().unwrap().iter().map(|b| b["angle_deg"].as_f64().unwrap().round()).collect(); + assert_eq!(angles, [75.0, 100.0, 75.0, 90.0], "{bends}"); + assert!(app.session.model.results.iter().all(|r| r.error.is_none()), "{:?}", app.session.model.results); + // Edit Feature: the edges and their own values come back, and OK rebuilds the same part. + let f = app.session.doc.features.last().unwrap().clone(); + let mut e = edit_dialog(&app, f.id, None).unwrap(); + assert_eq!(e.inputs[0].items.len(), 4); + let Kind::Sheet(Sm::Flange { own, .. }) = &e.kind else { panic!("not a flange dialog") }; + assert_eq!(own.len(), 2, "{own:?}"); + assert!(own.iter().any(|o| o.0.dist(point(1)) < 1e-9 && o.1 == "100 deg" && o.2.is_empty()), "{own:?}"); + assert!(own.iter().any(|o| o.0.dist(point(3)) < 1e-9 && o.1 == "90 deg" && o.2 == "15 mm"), "{own:?}"); + let volume = |app: &mut SolveApp| app.session.execute("inspect.measure", &json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap(); + let before = volume(&mut app); + let c = apply_commands(&app, &e).unwrap(); + assert_eq!(c[0].0, "timeline.redefine"); + assert_eq!(c[0].1["params"]["edges"][1], json!({"point": pt(point(1)), "angle": "100 deg"})); + assert_eq!(c[0].1["params"]["edges"][3]["height"], "15 mm"); + run_all(&mut app, c); + let after = volume(&mut app); + assert!((after - before).abs() < 1e-6 * before, "{after} vs {before}"); + // Taking edges out of the selection leaves each value with its edge. + e.inputs[0].items.remove(2); + e.inputs[0].items.remove(0); + let c = apply_commands(&app, &e).unwrap(); + assert_eq!( + c[0].1["params"]["edges"], + json!([{"point": pt(point(1)), "angle": "100 deg"}, {"point": pt(point(3)), "angle": "90 deg", "height": "15 mm"}]) + ); } - let c = apply_commands(&app, &d).unwrap(); - assert_eq!( - c[0].1["edges"], - json!([pt(point(0)), {"point": pt(point(1)), "angle": "100 deg"}, pt(point(2)), {"point": pt(point(3)), "angle": "90 deg", "height": "15 mm"}]), - "no text or a blank one: a plain point" - ); - run_all(&mut app, c); - let bends = app.session.execute("sheet.flat_pattern", &json!({})).unwrap()["bends"].clone(); - let angles: Vec = bends.as_array().unwrap().iter().map(|b| b["angle_deg"].as_f64().unwrap().round()).collect(); - assert_eq!(angles, [75.0, 100.0, 75.0, 90.0], "{bends}"); - assert!(app.session.model.results.iter().all(|r| r.error.is_none()), "{:?}", app.session.model.results); - // Edit Feature: the edges and their own values come back, and OK rebuilds the same part. - let f = app.session.doc.features.last().unwrap().clone(); - let mut e = edit_dialog(&app, f.id, None).unwrap(); - assert_eq!(e.inputs[0].items.len(), 4); - let Kind::Sheet(Sm::Flange { own, .. }) = &e.kind else { panic!("not a flange dialog") }; - assert_eq!(own.len(), 2, "{own:?}"); - assert!(own.iter().any(|o| o.0.dist(point(1)) < 1e-9 && o.1 == "100 deg" && o.2.is_empty()), "{own:?}"); - assert!(own.iter().any(|o| o.0.dist(point(3)) < 1e-9 && o.1 == "90 deg" && o.2 == "15 mm"), "{own:?}"); - let volume = |app: &mut SolveApp| app.session.execute("inspect.measure", &json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap(); - let before = volume(&mut app); - let c = apply_commands(&app, &e).unwrap(); - assert_eq!(c[0].0, "timeline.redefine"); - assert_eq!(c[0].1["params"]["edges"][1], json!({"point": pt(point(1)), "angle": "100 deg"})); - assert_eq!(c[0].1["params"]["edges"][3]["height"], "15 mm"); - run_all(&mut app, c); - let after = volume(&mut app); - assert!((after - before).abs() < 1e-6 * before, "{after} vs {before}"); - // Taking edges out of the selection leaves each value with its edge. - e.inputs[0].items.remove(2); - e.inputs[0].items.remove(0); - let c = apply_commands(&app, &e).unwrap(); - assert_eq!( - c[0].1["params"]["edges"], - json!([{"point": pt(point(1)), "angle": "100 deg"}, {"point": pt(point(3)), "angle": "90 deg", "height": "15 mm"}]) - ); } /// Convert takes a fixed face and, for a solid or shelled body, its bend edges; Edit Feature @@ -611,8 +648,8 @@ fn convert_takes_the_fixed_face_and_the_bend_edges() { // ---- flat pattern navigation ---- -fn flat_app(preset: &str) -> SolveApp { - let mut app = plate(); +fn flat_app(preset: &str, mode: crate::shell::LayoutMode) -> SolveApp { + let mut app = plate(mode); app.run("sheet.flange", json!({"sketch": "Base"})).unwrap(); let flat = app.session.execute("sheet.flat_pattern", &json!({})).unwrap(); app.start("sheet.flat_pattern"); @@ -652,82 +689,85 @@ fn frame(app: &mut SolveApp, ctx: &egui::Context, time: &mut f64, mods: egui::Mo /// cursor. The flat view never orbits. #[test] fn flat_pattern_pans_and_zooms_like_the_design_viewport() { - use egui::{Event, Modifiers, PointerButton}; - let none = Modifiers::NONE; - let chords = [none, Modifiers::SHIFT, Modifiers::CTRL, Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT]; - for preset in crate::prefs::NAV_PRESETS.iter().map(|p| p.id) { - for (reverse, to_cursor) in [(false, true), (true, true), (false, false)] { - let (flat_ctx, design_ctx) = (egui::Context::default(), egui::Context::default()); - let mut flat = flat_app(preset); - let mut design = flat_app(preset); - design.dialog = None; - for app in [&mut flat, &mut design] { - app.preferences.zoom_reverse = reverse; - app.preferences.zoom_to_cursor = to_cursor; - } - let (mut ft, mut dt) = (0.0, 0.0); - frame(&mut flat, &flat_ctx, &mut ft, none, vec![]); - frame(&mut flat, &flat_ctx, &mut ft, none, vec![]); - assert!(flat.flat_view.fitted); - // The Design viewport starts from the flat view's camera: top-down, orthographic. - design.cam = flat.flat_view.cam; - design.ui.perspective = false; - let design_before = flat.cam; - let (mut panned, mut zoomed) = (0, 0); - let at = pos2(300.0, 250.0); - for button in [PointerButton::Primary, PointerButton::Middle, PointerButton::Secondary] { - for mods in chords { - let mode = crate::prefs::nav_mode(&flat, button.into_nav(), mods); - if !matches!(mode, Some(crate::viewport::NavMode::Pan | crate::viewport::NavMode::Zoom)) { - continue; - } - let before = flat.flat_view.cam; - let mut both = |events: Vec, mods: Modifiers, flat: &mut SolveApp, design: &mut SolveApp| { - frame(flat, &flat_ctx, &mut ft, mods, events.clone()); - frame(design, &design_ctx, &mut dt, mods, events); - }; - both(vec![Event::PointerMoved(at)], mods, &mut flat, &mut design); - both(vec![Event::PointerButton { pos: at, button, pressed: true, modifiers: mods }], mods, &mut flat, &mut design); - let mut p = at; - for _ in 0..5 { - p += vec2(14.0, -9.0); - both(vec![Event::PointerMoved(p)], mods, &mut flat, &mut design); - } - both(vec![Event::PointerButton { pos: p, button, pressed: false, modifiers: mods }], mods, &mut flat, &mut design); - for _ in 0..10 { - both(vec![], none, &mut flat, &mut design); - } - assert!(same_view(&flat.flat_view.cam, &design.cam), "{preset}: {button:?} drag with {mods:?} ({mode:?})"); - assert_ne!(flat.flat_view.cam, before, "{preset}: {button:?} drag with {mods:?} moves the flat view"); - if mode == Some(crate::viewport::NavMode::Pan) { - panned += 1 - } else { - zoomed += 1 - } - flat.flat_view.cam = before; - design.cam = before; + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + use egui::{Event, Modifiers, PointerButton}; + let none = Modifiers::NONE; + let chords = [none, Modifiers::SHIFT, Modifiers::CTRL, Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT]; + for preset in crate::prefs::NAV_PRESETS.iter().map(|p| p.id) { + for (reverse, to_cursor) in [(false, true), (true, true), (false, false)] { + let (flat_ctx, design_ctx) = (egui::Context::default(), egui::Context::default()); + let mut flat = flat_app(preset, mode); + let mut design = flat_app(preset, mode); + design.dialog = None; + for app in [&mut flat, &mut design] { + app.preferences.zoom_reverse = reverse; + app.preferences.zoom_to_cursor = to_cursor; } - } - assert!(panned + zoomed >= 1, "{preset}: the preset has a pan or zoom drag"); - // The wheel zooms (to the cursor when asked), identically. - let before = flat.flat_view.cam; - let wheel = Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, 3.0), modifiers: none, phase: egui::TouchPhase::Move }; - for (app, ctx, t) in [(&mut flat, &flat_ctx, &mut ft), (&mut design, &design_ctx, &mut dt)] { - frame(app, ctx, t, none, vec![Event::PointerMoved(at)]); - frame(app, ctx, t, none, vec![wheel.clone()]); - for _ in 0..30 { - frame(app, ctx, t, none, vec![]); + let (mut ft, mut dt) = (0.0, 0.0); + frame(&mut flat, &flat_ctx, &mut ft, none, vec![]); + frame(&mut flat, &flat_ctx, &mut ft, none, vec![]); + assert!(flat.flat_view.fitted); + // The Design viewport starts from the flat view's camera: top-down, orthographic. + design.cam = flat.flat_view.cam; + design.ui.perspective = false; + let design_before = flat.cam; + let (mut panned, mut zoomed) = (0, 0); + let at = pos2(300.0, 250.0); + for button in [PointerButton::Primary, PointerButton::Middle, PointerButton::Secondary] { + for mods in chords { + let mode = crate::prefs::nav_mode(&flat, button.into_nav(), mods); + if !matches!(mode, Some(crate::viewport::NavMode::Pan | crate::viewport::NavMode::Zoom)) { + continue; + } + let before = flat.flat_view.cam; + let mut both = |events: Vec, mods: Modifiers, flat: &mut SolveApp, design: &mut SolveApp| { + frame(flat, &flat_ctx, &mut ft, mods, events.clone()); + frame(design, &design_ctx, &mut dt, mods, events); + }; + both(vec![Event::PointerMoved(at)], mods, &mut flat, &mut design); + both(vec![Event::PointerButton { pos: at, button, pressed: true, modifiers: mods }], mods, &mut flat, &mut design); + let mut p = at; + for _ in 0..5 { + p += vec2(14.0, -9.0); + both(vec![Event::PointerMoved(p)], mods, &mut flat, &mut design); + } + both(vec![Event::PointerButton { pos: p, button, pressed: false, modifiers: mods }], mods, &mut flat, &mut design); + for _ in 0..10 { + both(vec![], none, &mut flat, &mut design); + } + assert!(same_view(&flat.flat_view.cam, &design.cam), "{preset}: {button:?} drag with {mods:?} ({mode:?})"); + assert_ne!(flat.flat_view.cam, before, "{preset}: {button:?} drag with {mods:?} moves the flat view"); + if mode == Some(crate::viewport::NavMode::Pan) { + panned += 1 + } else { + zoomed += 1 + } + flat.flat_view.cam = before; + design.cam = before; + } } + assert!(panned + zoomed >= 1, "{preset}: the preset has a pan or zoom drag"); + // The wheel zooms (to the cursor when asked), identically. + let before = flat.flat_view.cam; + let wheel = + Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, 3.0), modifiers: none, phase: egui::TouchPhase::Move }; + for (app, ctx, t) in [(&mut flat, &flat_ctx, &mut ft), (&mut design, &design_ctx, &mut dt)] { + frame(app, ctx, t, none, vec![Event::PointerMoved(at)]); + frame(app, ctx, t, none, vec![wheel.clone()]); + for _ in 0..30 { + frame(app, ctx, t, none, vec![]); + } + } + assert_ne!(flat.flat_view.cam.distance, before.distance, "{preset}: the wheel zooms the flat view"); + assert!(same_view(&flat.flat_view.cam, &design.cam), "{preset} reverse {reverse} cursor {to_cursor}: wheel zoom"); + assert_eq!(flat.flat_view.cam.distance < before.distance, !reverse, "{preset}: reverse zoom flips the wheel"); + if to_cursor { + assert!(flat.flat_view.cam.target.dist(before.target) > 1e-6, "{preset}: zoom to the cursor moves the target"); + } + assert_eq!(flat.flat_view.cam.pitch, before.pitch); + assert_eq!(flat.flat_view.cam.yaw, before.yaw); + assert_eq!(flat.cam, design_before, "{preset}: the Design camera is untouched"); } - assert_ne!(flat.flat_view.cam.distance, before.distance, "{preset}: the wheel zooms the flat view"); - assert!(same_view(&flat.flat_view.cam, &design.cam), "{preset} reverse {reverse} cursor {to_cursor}: wheel zoom"); - assert_eq!(flat.flat_view.cam.distance < before.distance, !reverse, "{preset}: reverse zoom flips the wheel"); - if to_cursor { - assert!(flat.flat_view.cam.target.dist(before.target) > 1e-6, "{preset}: zoom to the cursor moves the target"); - } - assert_eq!(flat.flat_view.cam.pitch, before.pitch); - assert_eq!(flat.flat_view.cam.yaw, before.yaw); - assert_eq!(flat.cam, design_before, "{preset}: the Design camera is untouched"); } } } @@ -749,66 +789,73 @@ impl IntoNav for egui::PointerButton { /// camera and selection alone. #[test] fn design_camera_is_unchanged_while_the_flat_pattern_has_focus() { - use egui::{Event, Modifiers, PointerButton}; - let none = Modifiers::NONE; - for preset in crate::prefs::NAV_PRESETS.iter().map(|p| p.id) { - let ctx = egui::Context::default(); - let mut app = flat_app(preset); - let mut t = 0.0; - frame(&mut app, &ctx, &mut t, none, vec![]); - let cam = app.cam; - let at = pos2(300.0, 250.0); - for button in [PointerButton::Primary, PointerButton::Middle, PointerButton::Secondary] { - for mods in [none, Modifiers::SHIFT, Modifiers::CTRL, Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT] { - frame(&mut app, &ctx, &mut t, mods, vec![Event::PointerMoved(at)]); - frame(&mut app, &ctx, &mut t, mods, vec![Event::PointerButton { pos: at, button, pressed: true, modifiers: mods }]); - for i in 1..6 { - frame(&mut app, &ctx, &mut t, mods, vec![Event::PointerMoved(at + vec2(14.0, -9.0) * i as f32)]); - } - frame(&mut app, &ctx, &mut t, mods, vec![Event::PointerButton { pos: at, button, pressed: false, modifiers: mods }]); - } - } - let wheel = Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, 3.0), modifiers: none, phase: egui::TouchPhase::Move }; - frame(&mut app, &ctx, &mut t, none, vec![wheel]); - frame(&mut app, &ctx, &mut t, none, vec![Event::Zoom(1.3)]); - for _ in 0..30 { + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + use egui::{Event, Modifiers, PointerButton}; + let none = Modifiers::NONE; + for preset in crate::prefs::NAV_PRESETS.iter().map(|p| p.id) { + let ctx = egui::Context::default(); + let mut app = flat_app(preset, mode); + let mut t = 0.0; frame(&mut app, &ctx, &mut t, none, vec![]); + let cam = app.cam; + let at = pos2(300.0, 250.0); + for button in [PointerButton::Primary, PointerButton::Middle, PointerButton::Secondary] { + for mods in [none, Modifiers::SHIFT, Modifiers::CTRL, Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT] { + frame(&mut app, &ctx, &mut t, mods, vec![Event::PointerMoved(at)]); + frame(&mut app, &ctx, &mut t, mods, vec![Event::PointerButton { pos: at, button, pressed: true, modifiers: mods }]); + for i in 1..6 { + frame(&mut app, &ctx, &mut t, mods, vec![Event::PointerMoved(at + vec2(14.0, -9.0) * i as f32)]); + } + frame(&mut app, &ctx, &mut t, mods, vec![Event::PointerButton { pos: at, button, pressed: false, modifiers: mods }]); + } + } + let wheel = Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: vec2(0.0, 3.0), modifiers: none, phase: egui::TouchPhase::Move }; + frame(&mut app, &ctx, &mut t, none, vec![wheel]); + frame(&mut app, &ctx, &mut t, none, vec![Event::Zoom(1.3)]); + for _ in 0..30 { + frame(&mut app, &ctx, &mut t, none, vec![]); + } + assert_eq!(app.cam, cam, "{preset}: the Design camera stays put under the flat pattern"); + assert!(app.session.selection.is_empty(), "{preset}: nothing underneath is selected"); + assert_eq!(app.flat_view.cam.pitch, app.flat_view.cam.pitch.clamp(1.5, 2.0), "{preset}: still looking straight down"); } - assert_eq!(app.cam, cam, "{preset}: the Design camera stays put under the flat pattern"); - assert!(app.session.selection.is_empty(), "{preset}: nothing underneath is selected"); - assert_eq!(app.flat_view.cam.pitch, app.flat_view.cam.pitch.clamp(1.5, 2.0), "{preset}: still looking straight down"); } } /// Fit and Home frame the flat pattern (not the model), and leave the Design camera alone. #[test] fn fit_and_home_frame_the_flat_pattern() { - let ctx = egui::Context::default(); - let mut app = flat_app("fusion"); - let mut t = 0.0; - let none = egui::Modifiers::NONE; - frame(&mut app, &ctx, &mut t, none, vec![]); - let fitted = app.flat_view.cam; - // The 100 x 60 pattern sits inside the view with room for the command panel. - let scale = 600.0 / (2.0 * fitted.half_height()); - assert!(100.0 * scale < 800.0 && 60.0 * scale < 600.0 && 100.0 * scale > 200.0, "fits: {scale}"); - let design = app.cam; - for view in ["fit", "home"] { - app.flat_view.cam.pan(120.0, -80.0, 600.0); - app.flat_view.cam.zoom_at(0.3, None); - assert_ne!(app.flat_view.cam, fitted); - app.animate_view(view); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let ctx = egui::Context::default(); + let mut app = flat_app("fusion", mode); + let mut t = 0.0; + let none = egui::Modifiers::NONE; frame(&mut app, &ctx, &mut t, none, vec![]); - assert!(app.flat_view.cam.target.dist(fitted.target) < 1e-9 && (app.flat_view.cam.distance - fitted.distance).abs() < 1e-9, "{view} refits"); - assert_eq!(app.cam, design, "{view} leaves the Design camera alone"); + let fitted = app.flat_view.cam; + // The 100 x 60 pattern sits inside the view with room for the command panel. + let scale = 600.0 / (2.0 * fitted.half_height()); + assert!(100.0 * scale < 800.0 && 60.0 * scale < 600.0 && 100.0 * scale > 200.0, "fits: {scale}"); + let design = app.cam; + for view in ["fit", "home"] { + app.flat_view.cam.pan(120.0, -80.0, 600.0); + app.flat_view.cam.zoom_at(0.3, None); + assert_ne!(app.flat_view.cam, fitted); + app.animate_view(view); + frame(&mut app, &ctx, &mut t, none, vec![]); + assert!( + app.flat_view.cam.target.dist(fitted.target) < 1e-9 && (app.flat_view.cam.distance - fitted.distance).abs() < 1e-9, + "{view} refits" + ); + assert_eq!(app.cam, design, "{view} leaves the Design camera alone"); + } + app.flat_view.cam.pan(50.0, 50.0, 600.0); + app.fit_view(); + frame(&mut app, &ctx, &mut t, none, vec![]); + assert!(app.flat_view.cam.target.dist(fitted.target) < 1e-9, "fit_view refits"); + // Closing the dialog returns the viewport to the Design camera, and reopening refits. + app.flat_view.cam.pan(50.0, 50.0, 600.0); + app.dialog = None; + frame(&mut app, &ctx, &mut t, none, vec![]); + assert!(!app.flat_view.fitted); } - app.flat_view.cam.pan(50.0, 50.0, 600.0); - app.fit_view(); - frame(&mut app, &ctx, &mut t, none, vec![]); - assert!(app.flat_view.cam.target.dist(fitted.target) < 1e-9, "fit_view refits"); - // Closing the dialog returns the viewport to the Design camera, and reopening refits. - app.flat_view.cam.pan(50.0, 50.0, 600.0); - app.dialog = None; - frame(&mut app, &ctx, &mut t, none, vec![]); - assert!(!app.flat_view.fitted); } diff --git a/crates/ui-egui/src/extrude_edit_tests.rs b/crates/ui-egui/src/extrude_edit_tests.rs index 05600cfe6..5a2dab69a 100644 --- a/crates/ui-egui/src/extrude_edit_tests.rs +++ b/crates/ui-egui/src/extrude_edit_tests.rs @@ -304,6 +304,8 @@ fn symmetric_total_distance_preview_handle_drag_apply_and_reopen_agree() { let mut h = make(json!({"direction":"symmetric","distance":"100 mm","convention":convention})); h.call("ui.view", json!({"view":"fit"})); h.frames(4); + // Leave room above the fitted solid to grow the arrow without entering the ribbon. + h.app.cam.distance *= 1.5; open(&mut h); let expected_tip = h.at(&json!({"world":[5,5,cap]})).unwrap(); let handle = h.at(&json!({"handle":"arrow"})).unwrap(); diff --git a/crates/ui-egui/src/frame.rs b/crates/ui-egui/src/frame.rs index e9ee18701..d80da2b25 100644 --- a/crates/ui-egui/src/frame.rs +++ b/crates/ui-egui/src/frame.rs @@ -243,84 +243,90 @@ pub fn right_aligned(ui: &mut Ui, total: f32, width: f32, add: impl FnOnce(&m mod tests { #[test] fn feature_forms_use_available_height_and_keep_actions_visible() { - use crate::scenario::Harness; - use serde_json::json; - for (width, height, scale) in [(1400.0, 900.0, 1.0), (1400.0, 950.0, 2.0)] { - let mut h = Harness::new(); - h.app.preferences.ui_scale = scale; - h.call("ui.resize", json!({"width":width / scale,"height":height / scale})); - h.app.run("sketch.create", json!({"plane":"XY","name":"Base"})).unwrap(); - h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[10,10]})).unwrap(); - h.app.run("sketch.finish", json!({})).unwrap(); - h.step(&json!({"start":"solid.extrude"})).unwrap(); - h.frames(10); - let dialog = h.app.viewport.dialog_rect.unwrap(); - let viewport = h.app.viewport.rect.unwrap(); - assert!(dialog.height() > 230.0, "scale={scale}: {dialog:?}"); - assert!(viewport.expand(1.0).contains_rect(dialog), "scale={scale}: {dialog:?} outside {viewport:?}"); - assert!(h.widget("Distance").is_some(), "distance must be visible without scrolling"); - if scale == 1.0 { - assert!(h.widget("Operation").is_some(), "operation must be visible without scrolling"); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + use crate::scenario::Harness; + use serde_json::json; + for (width, height, scale) in [(1400.0, 900.0, 1.0), (1400.0, 950.0, 2.0)] { + let mut h = Harness::new(); + h.call("ui.set", json!({"layout":mode})); + h.app.preferences.ui_scale = scale; + h.call("ui.resize", json!({"width":width / scale,"height":height / scale})); + h.app.run("sketch.create", json!({"plane":"XY","name":"Base"})).unwrap(); + h.app.run("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[10,10]})).unwrap(); + h.app.run("sketch.finish", json!({})).unwrap(); + h.step(&json!({"start":"solid.extrude"})).unwrap(); + h.frames(10); + let dialog = h.app.viewport.dialog_rect.unwrap(); + let viewport = h.app.viewport.rect.unwrap(); + assert!(dialog.height() > 230.0, "scale={scale}: {dialog:?}"); + assert!(viewport.expand(1.0).contains_rect(dialog), "scale={scale}: {dialog:?} outside {viewport:?}"); + assert!(h.widget("Distance").is_some(), "distance must be visible without scrolling"); + if scale == 1.0 { + assert!(h.widget("Operation").is_some(), "operation must be visible without scrolling"); + } + assert!(dialog.contains(crate::scenario::handle_at("dialog:OK").unwrap())); + assert!(h.widget("Cancel").is_some(), "cancel must be visible without scrolling"); + h.step(&json!({"widget":"Cancel"})).unwrap(); + assert!(h.app.dialog.is_none()); + h.step(&json!({"start":"solid.shell"})).unwrap(); + h.frames(8); + let short = h.app.viewport.dialog_rect.unwrap(); + assert!(short.height() < dialog.height(), "short forms should shrink: {short:?}, {dialog:?}"); + assert!(h.widget("Cancel").is_some()); + h.step(&json!({"widget":"Cancel"})).unwrap(); + h.step(&json!({"start":"solid.hole"})).unwrap(); + if let Some(crate::dialogs::Dialog { kind: crate::dialogs::Kind::Hole { kind, opts, .. }, .. }) = h.app.dialog.as_mut() { + *kind = 1; + opts.tapped = true; + } + h.frames(8); + let long = h.app.viewport.dialog_rect.unwrap(); + assert!(viewport.expand(1.0).contains_rect(long), "long form clipped: {long:?}"); + assert!(h.widget("Cancel").is_some(), "long-form actions must stay visible"); + assert!(long.contains(crate::scenario::handle_at("dialog:OK").unwrap())); + h.step(&json!({"widget":"Cancel"})).unwrap(); + assert!(h.app.dialog.is_none()); } - assert!(dialog.contains(crate::scenario::handle_at("dialog:OK").unwrap())); - assert!(h.widget("Cancel").is_some(), "cancel must be visible without scrolling"); - h.step(&json!({"widget":"Cancel"})).unwrap(); - assert!(h.app.dialog.is_none()); - h.step(&json!({"start":"solid.shell"})).unwrap(); - h.frames(8); - let short = h.app.viewport.dialog_rect.unwrap(); - assert!(short.height() < dialog.height(), "short forms should shrink: {short:?}, {dialog:?}"); - assert!(h.widget("Cancel").is_some()); - h.step(&json!({"widget":"Cancel"})).unwrap(); - h.step(&json!({"start":"solid.hole"})).unwrap(); - if let Some(crate::dialogs::Dialog { kind: crate::dialogs::Kind::Hole { kind, opts, .. }, .. }) = h.app.dialog.as_mut() { - *kind = 1; - opts.tapped = true; - } - h.frames(8); - let long = h.app.viewport.dialog_rect.unwrap(); - assert!(viewport.expand(1.0).contains_rect(long), "long form clipped: {long:?}"); - assert!(h.widget("Cancel").is_some(), "long-form actions must stay visible"); - assert!(long.contains(crate::scenario::handle_at("dialog:OK").unwrap())); - h.step(&json!({"widget":"Cancel"})).unwrap(); - assert!(h.app.dialog.is_none()); } } /// #1335: a dialog keeps its size while its Select chip is hovered, and its title band /// drags it; it opens docked again after it closes. #[test] fn a_docked_dialog_keeps_its_size_under_the_pointer_and_moves_by_its_title() { - use crate::scenario::Harness; - use serde_json::json; - let mut h = Harness::new(); - h.call("ui.resize", json!({"width":1400.0,"height":900.0})); - h.step(&json!({"start":"sketch.create"})).unwrap(); - h.frames(6); - let rest = h.app.viewport.dialog_rect.unwrap(); - let chip = crate::scenario::handle_at("dialog:Plane").unwrap(); - h.call("ui.move", json!({"x": chip.x, "y": chip.y})); - h.frames(6); - let hovered = h.app.viewport.dialog_rect.unwrap(); - assert!((hovered.size() - rest.size()).length() < 0.01, "hovering resized the dialog: {rest:?} -> {hovered:?}"); - // Drag the published title band, independent of similarly labelled toolbar controls. - let title = crate::scenario::handle_at("dialog:title").unwrap(); - h.call("ui.drag", json!({"x0": title.x, "y0": title.y, "x1": title.x - 300.0, "y1": title.y + 120.0, "steps": 8})); - h.frames(4); - let moved = h.app.viewport.dialog_rect.unwrap(); - assert!((moved.min - rest.min - egui::vec2(-300.0, 120.0)).length() < 2.0, "{rest:?} -> {moved:?}"); - assert!(h.app.dialog.is_some(), "dragging the title keeps the dialog open"); - // Dragged far off, it stays on screen. - let title = crate::scenario::handle_at("dialog:title").unwrap(); - h.call("ui.drag", json!({"x0": title.x, "y0": title.y, "x1": title.x + 3000.0, "y1": title.y + 3000.0, "steps": 8})); - h.frames(4); - let viewport = h.app.viewport.rect.unwrap(); - assert!(viewport.contains(h.app.viewport.dialog_rect.unwrap().min)); - h.step(&json!({"key":"Escape"})).unwrap(); - h.frames(2); - assert!(h.app.dialog.is_none()); - h.step(&json!({"start":"sketch.create"})).unwrap(); - h.frames(6); - assert!((h.app.viewport.dialog_rect.unwrap().min - rest.min).length() < 0.01, "a new dialog opens docked"); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + use crate::scenario::Harness; + use serde_json::json; + let mut h = Harness::new(); + h.call("ui.set", json!({"layout":mode})); + h.call("ui.resize", json!({"width":1400.0,"height":900.0})); + h.step(&json!({"start":"sketch.create"})).unwrap(); + h.frames(6); + let rest = h.app.viewport.dialog_rect.unwrap(); + let chip = crate::scenario::handle_at("dialog:Plane").unwrap(); + h.call("ui.move", json!({"x": chip.x, "y": chip.y})); + h.frames(6); + let hovered = h.app.viewport.dialog_rect.unwrap(); + assert!((hovered.size() - rest.size()).length() < 0.01, "hovering resized the dialog: {rest:?} -> {hovered:?}"); + // Drag the published title band, independent of similarly labelled toolbar controls. + let title = crate::scenario::handle_at("dialog:title").unwrap(); + h.call("ui.drag", json!({"x0": title.x, "y0": title.y, "x1": title.x - 300.0, "y1": title.y + 120.0, "steps": 8})); + h.frames(4); + let moved = h.app.viewport.dialog_rect.unwrap(); + assert!((moved.min - rest.min - egui::vec2(-300.0, 120.0)).length() < 2.0, "{rest:?} -> {moved:?}"); + assert!(h.app.dialog.is_some(), "dragging the title keeps the dialog open"); + // Dragged far off, it stays on screen. + let title = crate::scenario::handle_at("dialog:title").unwrap(); + h.call("ui.drag", json!({"x0": title.x, "y0": title.y, "x1": title.x + 3000.0, "y1": title.y + 3000.0, "steps": 8})); + h.frames(4); + let viewport = h.app.viewport.rect.unwrap(); + assert!(viewport.contains(h.app.viewport.dialog_rect.unwrap().min)); + h.step(&json!({"key":"Escape"})).unwrap(); + h.frames(2); + assert!(h.app.dialog.is_none()); + h.step(&json!({"start":"sketch.create"})).unwrap(); + h.frames(6); + assert!((h.app.viewport.dialog_rect.unwrap().min - rest.min).length() < 0.01, "a new dialog opens docked"); + } } /// Windows are made in this file only, so none can skip the width limits. diff --git a/crates/ui-egui/src/infinite_line_display_tests.rs b/crates/ui-egui/src/infinite_line_display_tests.rs index bbb3bcc54..fc0cb52e3 100644 --- a/crates/ui-egui/src/infinite_line_display_tests.rs +++ b/crates/ui-egui/src/infinite_line_display_tests.rs @@ -27,10 +27,15 @@ fn it_is_drawn_from_edge_to_edge_of_the_view() { let ss = st.sketch(h.app.session.active_sketch.unwrap()).unwrap(); let i = ss.sketch.curve_index("inf").unwrap(); let parts = super::curve_parts(&ss.sketch, i, &ss.plane, &proj, 1.0); - let xs: Vec = parts.iter().flatten().filter_map(|p| proj.to_screen(*p)).map(|p| p.x).collect(); - let (lo, hi) = xs.iter().fold((f32::MAX, f32::MIN), |(lo, hi), x| (lo.min(*x), hi.max(*x))); - // Its two points are a few pixels apart; drawn, it spans the view. - assert!(lo <= rect.left() + 2.0 && hi >= rect.right() - 2.0, "drawn from {lo} to {hi} in {rect:?}"); + let screen: Vec<_> = parts.iter().flatten().filter_map(|p| proj.to_screen(*p)).collect(); + let (first, last) = (screen.first().unwrap(), screen.last().unwrap()); + // Its two defining points are a few pixels apart; drawn, it spans the view. At the + // default isometric angle a wide viewport clips the line at the top and bottom instead + // of the left and right, so either pair of edges is valid. + for point in [first, last] { + assert!(rect.expand(2.0).contains(*point) && !rect.shrink(2.0).contains(*point), "endpoint {point:?} must reach an edge of {rect:?}"); + } + assert!(first.distance(*last) >= rect.width().min(rect.height()) - 4.0, "line must span the view: {screen:?} in {rect:?}"); } #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4f6ea1107..57d861d52 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -158,6 +158,7 @@ pub mod save_job; pub mod scenario; pub mod select_other; pub mod selection; +pub mod shell; #[cfg(test)] mod shell_face_sketch_ui_tests; pub mod shortcut_box; @@ -228,6 +229,8 @@ pub use control::{ControlRequest, ControlResponse}; #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct UiState { + /// Automation-only shell mode; never persisted in preferences. + pub layout: shell::LayoutMode, /// Ribbon tab; contextual SKETCH and SHEET METAL join the seven design tabs. pub tab: String, /// Last contextual body/sketch, only used to select on entry. @@ -265,6 +268,7 @@ pub struct UiState { impl Default for UiState { fn default() -> Self { UiState { + layout: Default::default(), tab: "MODEL".into(), ribbon_context: None, show_browser: true, @@ -324,6 +328,7 @@ pub struct Services { pub struct SolveApp { pub session: Session, pub ui: UiState, + pub(crate) shell: shell::State, pub cam: Camera, /// A view change in progress (axis view, Home, Fit); any mouse navigation cancels it. pub cam_anim: Option, @@ -486,6 +491,7 @@ impl SolveApp { SolveApp { session, ui: UiState::default(), + shell: Default::default(), cam: Camera::default(), cam_anim: None, now: 0.0, @@ -1487,16 +1493,42 @@ impl SolveApp { return; } } - toolbar::toolbar(self, ui); - theme::TabAccent::publish(self, ui.ctx()); + let floating = self.ui.layout == shell::LayoutMode::Floating; let show_timeline = self.ui.show_timeline && !render_workspace::active(self); let left_timeline = show_timeline && self.preferences.timeline_left; + if !floating { + toolbar::toolbar(self, ui); + } + theme::TabAccent::publish(self, ui.ctx()); if show_timeline && !left_timeline { timeline::timeline(self, ui); } palette::palette_bar(self, ui); - // A floating browser keeps the workspace the whole width: it is drawn over the view below. + // A floating browser keeps the workspace the whole width and covers viewport input. let browser_float = self.ui.show_browser && self.preferences.browser_float; + if !browser_float { + self.shell.browser = None; + } + let full = ui.available_rect_before_wrap(); + if floating { + let cards = shell::Cards::new(full, self.ui.layout); + self.shell.cards = vec![cards.workspace, cards.ribbon]; + // Draw the scene first, then let the unchanged panel layouts cover it. The + // viewport keeps its full projection even underneath the browser and cards. + preview::update(self, ui.ctx()); + let blocked = ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| shell::covered(self, p)); + let mut viewport_ui = ui.new_child(egui::UiBuilder::new().max_rect(full).id_salt("floating_viewport")); + if blocked { + // Disabled only to shield the scene from input under a card or menu; it must + // not fade, or the whole viewport dims whenever the pointer is over the shell. + viewport_ui.visuals_mut().disabled_alpha = 1.0; + viewport_ui.disable(); + } + self.show_workspace(&mut viewport_ui); + shell::paint_top_corners(ui.painter(), full, theme::Tokens::get().app_bar); + toolbar::toolbar(self, ui); + theme::TabAccent::publish(self, ui.ctx()); + } if self.ui.show_browser && !browser_float { if left_timeline { browser::browser_below_timeline(self, ui); @@ -1510,17 +1542,26 @@ impl SolveApp { render_workspace::panel(self, ui); } agent_chat::show(self, ui); - preview::update(self, ui.ctx()); if browser_float { - // The room the central view is about to take, before it takes it. + // The remaining content starts below the ribbon in either shell layout. let viewport = ui.available_rect_before_wrap(); browser::floating(self, ui, viewport); } egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| { - if render_workspace::active(self) { - render_workspace::show(self, ui); + if floating { + let content = ui.max_rect(); + self.shell.content = Some(content); + self.shell.panels = [ + egui::Rect::from_min_max(egui::pos2(full.left(), content.top()), egui::pos2(content.left(), full.bottom())), + egui::Rect::from_min_max(egui::pos2(content.right(), content.top()), full.max), + ] + .into_iter() + .filter(|r| r.is_positive()) + .collect(); + viewport::refresh_layout(self, ui.ctx().pixels_per_point()); } else { - viewport::show(self, ui); + preview::update(self, ui.ctx()); + self.show_workspace(ui); } }); dialogs::show(self, ui.ctx()); @@ -1542,6 +1583,14 @@ impl SolveApp { toolbar_custom::window(self, ui.ctx()); } + fn show_workspace(&mut self, ui: &mut egui::Ui) { + if render_workspace::active(self) { + render_workspace::show(self, ui); + } else { + viewport::show(self, ui); + } + } + fn drain_control(&mut self, ctx: &egui::Context) { /// Requests run on this thread, so a flood would starve rendering. The rest stay /// queued for the next frame. diff --git a/crates/ui-egui/src/navigation.rs b/crates/ui-egui/src/navigation.rs index 657d5d423..982bf9fdb 100644 --- a/crates/ui-egui/src/navigation.rs +++ b/crates/ui-egui/src/navigation.rs @@ -272,6 +272,7 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e i.pointer.delta(), ) }); + let hover = hover.filter(|p| !crate::shell::covered(app, *p)); // The right button belongs to the marking menu while it is open. let secondary_down = secondary_down && app.viewport.context_menu.is_none(); // The axis view handles its own clicks; the model underneath must not see them. @@ -280,7 +281,7 @@ pub(crate) fn handle(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect, resp: &e // hit test also counts the model as under the pointer a few points past its own edge and // inside a window's or a list's edge (#678), so the pointer must be in the viewport too, // with no window or menu above it. - let inside = resp.contains_pointer() && ui.rect_contains_pointer(rect) && hover.is_some_and(|p| !axes.contains(p)); + let inside = ui.is_enabled() && resp.contains_pointer() && ui.rect_contains_pointer(rect) && hover.is_some_and(|p| !axes.contains(p)); app.viewport.mouse = hover.filter(|_| inside); // Sketch snap suppression is set once in `viewport::show` from preferences. middle_double_click(app, ui, inside); diff --git a/crates/ui-egui/src/navigation_cube.rs b/crates/ui-egui/src/navigation_cube.rs index fa7f4ff38..f3525f9e8 100644 --- a/crates/ui-egui/src/navigation_cube.rs +++ b/crates/ui-egui/src/navigation_cube.rs @@ -155,7 +155,7 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) { let t = Tokens::get().navigation_cube(active); crate::scenario::publish_count("navigation_cube:active", f64::from(u8::from(active))); let faces = facets(&app.cam, c, HALF * f64::from(scale)); - let hover = ui.input(|i| i.pointer.hover_pos()).filter(|_| ui.rect_contains_pointer(rect)); + let hover = ui.input(|i| i.pointer.hover_pos()).filter(|p| ui.is_enabled() && ui.rect_contains_pointer(rect) && !crate::shell::covered(app, *p)); let hovered = if orbiting { None } else { hover.and_then(|p| hit(&faces, p)) }; let painter = ui.painter_at(outer); paint_cube(&painter, &faces, hovered, t, true, scale); diff --git a/crates/ui-egui/src/pattern_arrow_tests.rs b/crates/ui-egui/src/pattern_arrow_tests.rs index 6aad4a42d..68d7a11ee 100644 --- a/crates/ui-egui/src/pattern_arrow_tests.rs +++ b/crates/ui-egui/src/pattern_arrow_tests.rs @@ -29,6 +29,9 @@ fn a_sketch_pattern_drags_its_second_spacing_square_to_the_first() { {"click": {"sketch": [5, 0]}} ])) .unwrap(); + // Keep both arrows in the exposed viewport beside the left dialog. The full-bleed + // projection otherwise puts Spacing 2 under the dialog's top edge. + h.call("ui.camera", json!({"target":[-30,0,0]})); h.settle(); let (Some(a1), Some(a2)) = (handle_at("arrow"), handle_at("arrow2")) else { panic!("both arrows: {:?} {:?}", handle_at("arrow"), handle_at("arrow2")); @@ -36,6 +39,8 @@ fn a_sketch_pattern_drags_its_second_spacing_square_to_the_first() { // Looking down on XY, the first direction (sketch x) points right and the second (square to // it) up the screen: the arrows share their base, so each lies along its own axis. assert!(a1.x > a2.x + 10.0 && (a2.y - a1.y).abs() > 10.0, "arrow {a1:?}, arrow2 {a2:?}"); + assert!(!crate::shell::covered(&h.app, a1)); + assert!(!crate::shell::covered(&h.app, a2)); let (spacing, spacing2) = spacings(&h); // Dragging the second arrow further out sets Spacing 2 only. h.call("ui.drag", json!({"x0": a2.x, "y0": a2.y, "x1": a2.x, "y1": a2.y - 60.0, "steps": 6})); diff --git a/crates/ui-egui/src/revolve_edit_tests.rs b/crates/ui-egui/src/revolve_edit_tests.rs index fa5699604..7a82ba996 100644 --- a/crates/ui-egui/src/revolve_edit_tests.rs +++ b/crates/ui-egui/src/revolve_edit_tests.rs @@ -128,7 +128,10 @@ fn second_active_occurrence_noop_preserves_definition_axis_target_and_instances( assert!(placed.mesh().triangles.len() > 10); assert_eq!(placed.mesh().bounds(), before.iter().find(|(_, bounds)| bounds.center().x > 50.0).unwrap().1); assert!(h.widget("↖ Custom Axis").is_some()); + // In the floating shell the read-only Sweep badge overlaps OK at this placement. + // It must not intercept the dialog's click or leave the timeline rolled back. h.step(&json!({"widget":"OK"})).unwrap(); + assert!(h.app.dialog.is_none(), "OK must apply even underneath the Sweep badge"); assert_eq!(serde_json::to_value(&h.app.session.doc.find_feature("Turn").unwrap().kind).unwrap(), original); let after: Vec<_> = h.app.session.world_state().bodies.iter().map(|b| (b.name.clone(), b.mesh().bounds())).collect(); assert_eq!(after, before); diff --git a/crates/ui-egui/src/shell.rs b/crates/ui-egui/src/shell.rs new file mode 100644 index 000000000..3f4cd186a --- /dev/null +++ b/crates/ui-egui/src/shell.rs @@ -0,0 +1,125 @@ +//! Transient shell geometry shared by automation, drawing and viewport occlusion. +use egui::{Rect, pos2, vec2}; +use serde::{Deserialize, Serialize}; + +use crate::{SolveApp, theme::Tokens, toolbar}; + +/// Shell frame selected by automation for this session. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum LayoutMode { + #[default] + Floating, + Docked, +} + +/// The gap from the viewport edge to the floating cards and between the cards. +pub(crate) const SHELL_GAP: f32 = 7.0; + +/// The viewport's top corners are rounded concentrically with the cards: the card margin plus the +/// card radius. +pub(crate) fn corner_radius() -> f32 { + SHELL_GAP + f32::from(Tokens::get().radius_lg) +} + +/// Fill the two concave corners where the application bar flows into the viewport's top edge, so +/// the viewport reads as a rounded surface under the bar. +pub(crate) fn paint_top_corners(painter: &egui::Painter, viewport: Rect, color: egui::Color32) { + let r = corner_radius().min(viewport.width() / 2.0).min(viewport.height() / 2.0); + if !(r.is_finite() && r > 0.5) { + return; + } + const STEPS: usize = 32; + for left in [true, false] { + let (corner, centre, dir) = if left { + (viewport.left_top(), pos2(viewport.left() + r, viewport.top() + r), -1.0) + } else { + (viewport.right_top(), pos2(viewport.right() - r, viewport.top() + r), 1.0) + }; + let mut mesh = egui::Mesh::default(); + mesh.colored_vertex(corner, color); + for i in 0..=STEPS { + // From the top tangent point round to the side tangent point. + let a = std::f32::consts::FRAC_PI_2 * i as f32 / STEPS as f32; + mesh.colored_vertex(pos2(centre.x + dir * r * a.sin(), centre.y - r * a.cos()), color); + } + for i in 0..STEPS as u32 { + mesh.add_triangle(0, i + 1, i + 2); + } + painter.add(egui::Shape::mesh(mesh)); + } +} + +#[derive(Clone, Copy, Debug)] +pub(crate) struct Cards { + pub workspace: Rect, + pub ribbon: Rect, + pub bottom: f32, +} + +impl Cards { + pub fn new(available: Rect, mode: LayoutMode) -> Self { + let margin = if mode == LayoutMode::Floating { SHELL_GAP } else { 0.0 }; + let gap = if mode == LayoutMode::Floating { SHELL_GAP } else { 1.0 }; + let left = available.left() + margin; + let top = available.top() + margin; + let right = (available.right() - margin).max(left); + let workspace = Rect::from_min_size( + pos2(left, top), + vec2(toolbar::WORKSPACE_WIDTH.min((right - left).max(0.0)), toolbar::RIBBON_HEIGHT - if mode == LayoutMode::Docked { 1.0 } else { 0.0 }), + ); + let ribbon = Rect::from_min_max(pos2((workspace.right() + gap).min(right), top), pos2(right, top + toolbar::RIBBON_HEIGHT)); + Self { workspace, ribbon, bottom: ribbon.bottom() + margin } + } +} + +/// Shell panels measured after drawing the full-bleed viewport. No design or preferences data. +#[derive(Default)] +pub(crate) struct State { + pub cards: Vec, + pub panels: Vec, + pub content: Option, + pub browser: Option, +} + +/// One source of occlusion for navigation, picking, overlays and fit. +pub(crate) fn covered_rects(app: &SolveApp) -> Vec { + let mut rects = Vec::new(); + if app.ui.layout == LayoutMode::Floating { + rects.extend(app.shell.cards.iter().copied()); + rects.extend(app.shell.panels.iter().copied()); + } + rects.extend(app.shell.browser.filter(|_| app.ui.show_browser && app.preferences.browser_float)); + rects.extend(app.viewport.palette_rect.filter(|_| app.session.active_sketch.is_some())); + rects.extend(app.viewport.dialog_rect.filter(|_| app.dialog.is_some())); + rects.retain(|r| r.is_finite() && r.is_positive()); + rects +} + +pub(crate) fn covered(app: &SolveApp, p: egui::Pos2) -> bool { + covered_rects(app).iter().any(|r| r.contains(p)) +} + +/// The former central panel remains the anchor for controls and docked panels. +pub(crate) fn content_rect(app: &SolveApp, viewport: Rect) -> Rect { + if app.ui.layout == LayoutMode::Floating { app.shell.content.unwrap_or(viewport).intersect(viewport) } else { viewport } +} + +pub(crate) fn panel_top(app: &SolveApp, viewport: Rect, bottom: f32, side: crate::frame::Side) -> f32 { + let content = content_rect(app, viewport); + if app.ui.layout == LayoutMode::Floating && side == crate::frame::Side::Right { + // Preserve measured compass clearance when there is room; reclaim it on short + // views with the same 360 px panel budget as Docked. + app.viewport + .layout + .as_ref() + .map_or(content.top(), |l| if l.axis_view.is_positive() { l.axis_view.bottom().min(bottom) } else { content.top() }) + .min((bottom - 360.0).max(content.top())) + } else { + (viewport.top() + crate::viewport::AXIS_VIEW_CLEARANCE).min((bottom - 360.0).max(viewport.top())) + } +} + +#[cfg(test)] +#[path = "shell_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/shell_tests.rs b/crates/ui-egui/src/shell_tests.rs new file mode 100644 index 000000000..870878128 --- /dev/null +++ b/crates/ui-egui/src/shell_tests.rs @@ -0,0 +1,240 @@ +use super::*; +use crate::scenario::{Harness, rect_of}; +use serde_json::json; + +#[test] +fn modes_are_transient_and_available_to_control_and_scenarios() { + let mut h = Harness::new(); + assert_eq!(h.app.ui.layout, LayoutMode::Floating); + let prefs = serde_json::to_value(&h.app.preferences).unwrap(); + let doc = h.app.session.doc.to_json(); + h.step(&json!({"call":"ui.set", "params":{"layout":"docked"}})).unwrap(); + assert_eq!(h.app.ui.layout, LayoutMode::Docked); + h.step(&json!({"call":"ui.set", "params":{"layout":"invalid"},"fail":true})).unwrap(); + assert_eq!(h.app.ui.layout, LayoutMode::Docked); + h.call("ui.set", json!({"layout":"floating"})); + assert_eq!(h.app.ui.layout, LayoutMode::Floating); + assert_eq!(h.app.session.doc.to_json(), doc); + assert_eq!(serde_json::to_value(&h.app.preferences).unwrap(), prefs); +} + +#[test] +fn both_modes_keep_their_geometry_and_fit_clear_of_covered_rects() { + for mode in [LayoutMode::Docked, LayoutMode::Floating] { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1400,"height":900})); + h.call("ui.set", json!({"layout":mode})); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + h.settle(); + let viewport = h.app.viewport.rect.unwrap(); + let workspace = rect_of("ribbon:workspace").unwrap(); + let toolbar = rect_of("toolbar").unwrap(); + if mode == LayoutMode::Floating { + let ribbon = rect_of("ribbon:card").unwrap(); + assert_eq!(viewport.left(), 0.0); + assert_eq!(viewport.top(), toolbar::APP_BAR_HEIGHT); + assert_eq!(workspace.left(), SHELL_GAP); + assert_eq!(workspace.top(), viewport.top() + SHELL_GAP); + assert_eq!(ribbon.left() - workspace.right(), SHELL_GAP); + assert_eq!(ribbon.right(), viewport.right() - SHELL_GAP); + assert!(!covered(&h.app, pos2(4.0, workspace.center().y))); + assert!(!covered(&h.app, pos2(workspace.right() + 2.0, workspace.center().y))); + assert!(covered(&h.app, workspace.center())); + assert!(covered(&h.app, ribbon.center())); + } else { + assert_eq!(toolbar.top(), toolbar::APP_BAR_HEIGHT); + assert_eq!(viewport.top(), toolbar.bottom()); + assert_eq!(toolbar.height(), toolbar::RIBBON_HEIGHT); + assert_eq!(workspace.left(), 0.0); + assert!(covered_rects(&h.app).is_empty()); + } + h.app.fit_view(); + h.settle(); + let layout = h.app.viewport.layout.as_ref().unwrap(); + for covered in covered_rects(&h.app) { + assert!(!layout.drawable.intersect(covered).is_positive(), "{layout:?} {covered:?}"); + } + let projection = crate::viewport::projection(&h.app, viewport); + for point in [solidcraft_engine::geom::Vec3::ZERO, solidcraft_engine::geom::Vec3::new(40.0, 30.0, 20.0)] { + assert!(layout.drawable.contains(projection.to_screen(point).unwrap())); + } + h.app.start("solid.extrude"); + h.settle(); + if mode == LayoutMode::Floating { + assert!(h.app.viewport.dialog_rect.unwrap().top() >= h.app.viewport.layout.as_ref().unwrap().axis_view.bottom()); + } + } +} + +#[test] +fn cards_block_model_hover_wheel_and_drag_but_the_gap_remains_viewport() { + let mut h = Harness::new(); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + h.settle(); + let ribbon = rect_of("ribbon:card").unwrap(); + // Blank space at the right, away from the search and command buttons. + let at = pos2(ribbon.right() - 12.0, ribbon.bottom() - 28.0); + let camera = h.app.cam; + let doc = h.app.session.doc.to_json(); + h.call("ui.move", json!({"x":at.x,"y":at.y})); + assert!(h.app.viewport.hover.is_none()); + assert!(h.app.viewport.mouse.is_none()); + h.call("ui.scroll", json!({"x":at.x,"y":at.y,"delta":120})); + h.call("ui.drag", json!({"x0":at.x,"y0":at.y,"x1":at.x-30.0,"y1":at.y+15.0,"button":"middle","steps":6})); + assert_eq!(h.app.cam, camera); + assert!(h.app.viewport.boxsel.is_none()); + assert_eq!(h.app.session.doc.to_json(), doc); + let gap = pos2(4.0, ribbon.center().y); + h.call("ui.move", json!({"x":gap.x,"y":gap.y})); + assert_eq!(h.app.viewport.mouse, Some(gap)); +} + +#[test] +fn floating_sketch_palette_and_compass_share_measured_clearance() { + for style in crate::prefs::NavigatorStyle::ALL { + for (width, height, scale) in [(1400.0, 900.0, 1.0), (700.0, 720.0, 2.0)] { + let mut h = Harness::new(); + h.app.preferences.navigator_style = style; + h.call("ui.resize", json!({"width":width,"height":height})); + h.call("ui.prefs", json!({"ui_scale":scale})); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[0,0],[20,0]]})).unwrap(); + h.settle(); + h.app.fit_view(); + h.settle(); + let layout = h.app.viewport.layout.as_ref().unwrap(); + let palette = h.app.viewport.palette_rect.unwrap(); + assert!(palette.top() >= layout.axis_view.bottom(), "{style:?} {palette:?} {layout:?}"); + assert!(layout.viewport.expand(1.0).contains_rect(palette), "{palette:?} {layout:?}"); + assert!(palette.contains(crate::scenario::handle_at("sketch_palette:finish").unwrap())); + let proj = crate::viewport::projection(&h.app, layout.viewport); + for point in [solidcraft_engine::geom::Vec3::ZERO, solidcraft_engine::geom::Vec3::new(20.0, 0.0, 0.0)] { + assert!(layout.drawable.contains(proj.to_screen(point).unwrap()), "{layout:?}"); + } + if width > 1000.0 { + let content = layout.content; + h.app.start("solid.extrude"); + h.settle(); + let dialog = h.app.viewport.dialog_rect.unwrap(); + let expected_top = (content.top() + crate::viewport::AXIS_VIEW_CLEARANCE).min((content.bottom() - 360.0).max(content.top())); + assert!((dialog.left() - content.left()).abs() < 1.0); + assert!((dialog.top() - expected_top).abs() < 1.0, "left dialogs retain their existing top: {dialog:?}"); + } + } + } +} + +#[test] +fn short_floating_palette_stays_in_viewport() { + for style in crate::prefs::NavigatorStyle::ALL { + for height in [475, 385, 300] { + let mut h = Harness::new(); + h.app.preferences.navigator_style = style; + h.call("ui.resize", json!({"width":700,"height":height})); + h.call("ui.prefs", json!({"ui_scale":2.0})); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + // Main's open/untied-end feedback also consumes footer space. + for points in [[[0, 0], [10, 0]], [[10, 0], [10, 10]], [[10, 10], [0, 10]], [[0, 10], [0, 0]], [[20, 0], [30, 5]]] { + h.app.run("sketch.line", json!({"points":points,"infer":false,"connect":false})).unwrap(); + } + // Include the extra Feature Options section in the tiny-height case. + if height == 300 { + h.app.start("sketch.rectangle.two_point"); + } + h.settle(); + let viewport = h.app.viewport.rect.unwrap(); + let palette = h.app.viewport.palette_rect.unwrap(); + assert!( + viewport.contains_rect(palette), + "{style:?}, height={height}: {palette:?} extends beyond {viewport:?}, right={:.9}, bottom={:.9}", + palette.right(), + palette.bottom() + ); + let compass = h.app.viewport.layout.as_ref().unwrap().axis_view; + if compass.is_positive() { + assert!(palette.top() < compass.bottom(), "short panels reclaim compass space"); + } + let finish = crate::scenario::handle_at("sketch_palette:finish").unwrap(); + if !palette.contains(finish) { + // Once reclaiming is insufficient, the whole palette must scroll to Finish. + h.call("ui.scroll", json!({"x":palette.center().x,"y":palette.center().y,"delta":-1200})); + h.frames(20); + } + let finish = crate::scenario::handle_at("sketch_palette:finish").unwrap(); + assert!(palette.contains(finish), "Finish Sketch must be reachable: {style:?}, height={height}, {finish:?} in {palette:?}"); + h.call("ui.click", json!({"x":finish.x,"y":finish.y})); + assert!(h.app.session.active_sketch.is_none(), "Finish Sketch must work after scrolling"); + } + } +} + +#[test] +fn selection_drag_released_over_a_card_leaves_no_rubber_band() { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1400,"height":900})); + h.settle(); + let ribbon = rect_of("ribbon:card").unwrap(); + let viewport = h.app.viewport.rect.unwrap(); + h.call( + "ui.drag", + json!({"x0":viewport.right()-20.0,"y0":viewport.bottom()-100.0, + "x1":ribbon.right()-12.0,"y1":ribbon.bottom()-28.0,"steps":12}), + ); + assert!(h.app.viewport.boxsel.is_none()); + assert!(h.app.session.selection.is_empty()); +} + +#[test] +fn floating_browser_clears_cards_shields_input_and_can_dock_again() { + for mode in [LayoutMode::Floating, LayoutMode::Docked] { + for timeline_left in [false, true] { + let mut h = Harness::new(); + h.call("ui.set", json!({"layout":mode})); + h.app.preferences.timeline_left = timeline_left; + h.app.preferences.browser_float = true; + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + h.settle(); + let browser = rect_of("browser:float").unwrap(); + let toolbar = rect_of("toolbar").unwrap(); + assert!(browser.top() >= toolbar.bottom(), "{mode:?}: {browser:?} must clear {toolbar:?}"); + assert!(crate::scenario::handle_at("row:Untitled").is_some()); + assert!(crate::scenario::handle_at("left-browser-rail").is_none()); + assert!(covered(&h.app, browser.center())); + let viewport = h.app.viewport.rect.unwrap(); + // A left-side history still takes a column in Docked mode. + if mode == LayoutMode::Floating || !timeline_left { + assert_eq!(viewport.left(), 0.0); + } else { + assert!(viewport.left() > 0.0); + } + if mode == LayoutMode::Floating { + assert_eq!(viewport.top(), toolbar::APP_BAR_HEIGHT); + assert!(!browser.intersect(rect_of("ribbon:card").unwrap()).is_positive()); + } + h.app.fit_view(); + h.settle(); + assert!(!h.app.viewport.layout.as_ref().unwrap().drawable.intersect(browser).is_positive()); + let camera = h.app.cam; + let doc = h.app.session.doc.to_json(); + let at = browser.center(); + h.call("ui.move", json!({"x":at.x,"y":at.y})); + assert!(h.app.viewport.hover.is_none()); + assert!(h.app.viewport.mouse.is_none()); + h.call("ui.scroll", json!({"x":at.x,"y":at.y,"delta":120})); + h.call("ui.drag", json!({"x0":at.x,"y0":at.y,"x1":at.x+20.0,"y1":at.y+10.0,"button":"middle","steps":6})); + assert_eq!(h.app.cam, camera); + assert_eq!(h.app.session.doc.to_json(), doc); + // The browser remains interactive above the shielded viewport. + h.step(&json!({"click":{"chevron":"Origin"}})).unwrap(); + assert!(crate::browser::drawn_rows().iter().any(|(name, _, _, open)| name == "Origin" && *open == Some(true))); + h.app.preferences.browser_float = false; + h.settle(); + assert!(h.app.shell.browser.is_none()); + assert!(rect_of("browser:float").is_none()); + let rail = crate::scenario::handle_at("left-browser-rail").unwrap(); + let width = h.app.preferences.browser_width; + h.call("ui.drag", json!({"x0":rail.x,"y0":rail.y,"x1":rail.x+60.0,"y1":rail.y,"steps":6})); + assert!(h.app.preferences.browser_width > width + 30.0); + } + } +} diff --git a/crates/ui-egui/src/sketch_corner_ui_tests.rs b/crates/ui-egui/src/sketch_corner_ui_tests.rs index 0df701c34..5a2b629fb 100644 --- a/crates/ui-egui/src/sketch_corner_ui_tests.rs +++ b/crates/ui-egui/src/sketch_corner_ui_tests.rs @@ -495,6 +495,9 @@ fn fully_constrained_center_rectangle_corners_can_be_picked_and_filleted() { h.frames(2); h.step(&json!({"start":"sketch.fillet"})).unwrap(); h.frames(2); + // Fit after opening the dialog so all four corners clear the shell and both panels. + h.app.fit_view(); + h.settle(); for corner in [[-20, -15, 0], [20, -15, 0], [20, 15, 0], [-20, 15, 0]] { h.step(&json!({"click":{"world":corner}})).unwrap(); h.frames(2); diff --git a/crates/ui-egui/src/sketch_guidance_ui_tests.rs b/crates/ui-egui/src/sketch_guidance_ui_tests.rs index 88c8cd3ab..6b47ec4a3 100644 --- a/crates/ui-egui/src/sketch_guidance_ui_tests.rs +++ b/crates/ui-egui/src/sketch_guidance_ui_tests.rs @@ -124,6 +124,8 @@ fn sketch_dialog_mirror_refuses_external_and_curved_references() { #[test] fn sketch_dialog_box_selection_adds_replaces_and_preserves_reference() { let mut h = fixture(); + // Put every selection box between the left dialog and the right Sketch Palette. + step(&mut h, json!({"call":"ui.camera","params":{"target":[-40,0,0],"distance":150}})); step(&mut h, json!({"call":"engine.execute","params":{"command":"sketch.line","params":{"points":[[-50,-20],[-40,-20]]}}})); step(&mut h, json!({"start":"sketch.mirror"})); step(&mut h, json!({"call":"ui.dialogInput","params":{"index":1}})); diff --git a/crates/ui-egui/src/sketch_palette.rs b/crates/ui-egui/src/sketch_palette.rs index 276fccf7e..355ecd7e7 100644 --- a/crates/ui-egui/src/sketch_palette.rs +++ b/crates/ui-egui/src/sketch_palette.rs @@ -248,7 +248,7 @@ fn width(vp: egui::Rect) -> f32 { /// The viewport the palette docks into. fn viewport(app: &SolveApp, ctx: &egui::Context) -> egui::Rect { - app.viewport.rect.unwrap_or_else(|| ctx.content_rect()) + crate::shell::content_rect(app, app.viewport.rect.unwrap_or_else(|| ctx.content_rect())) } /// Is a sketch being edited? That is the palette's own condition. @@ -364,8 +364,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let vp = viewport(app, ctx); let bottom = vp.bottom().min(ctx.content_rect().bottom()) - 8.0; // Prefer the space below Axis View, but reclaim it on short/HiDPI views. - let top = (vp.top() + crate::viewport::AXIS_VIEW_CLEARANCE).min((bottom - 360.0).max(vp.top())); - let anchor = egui::pos2(vp.right(), top); + let top = crate::shell::panel_top(app, vp, bottom, crate::frame::Side::Right); + // Area rounds its left edge to a physical pixel; leave room for that rounding. + let anchor = egui::pos2(vp.right() - 0.5 / ctx.pixels_per_point(), top); let frame = crate::frame::dock_frame(ctx, crate::frame::Side::Right); let shown = |k: &str| match k { "grid" => !opts.hide_grid, @@ -402,186 +403,205 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let width = width(vp); ui.set_width(width); ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap); - let line = ui.text_style_height(&egui::TextStyle::Body); - let gap = ui.spacing().item_spacing.y; - crate::frame::heading(ui, Level::Title, width, |ui| { - let folded = FOLDED.with(Cell::get); - if ui.add(egui::Button::new(RichText::new(if folded { "+" } else { "−" }).size(14.0)).frame(false)).clicked() { - FOLDED.with(|f| f.set(!folded)); - } - ui.label(RichText::new(app.tr("ui.heading_sketch_palette")).strong().size(12.5)); - }); - if FOLDED.with(Cell::get) { - return; - } - // Feature Options sits above Options: the modes of the creation tool that is running. - if let Some((family, current)) = feature { - let ffold = FEATURE_FOLDED.with(Cell::get); - crate::frame::heading(ui, Level::Section, width, |ui| { - let (tri_rect, tri_resp) = ui.allocate_exact_size(vec2(14.0, 14.0), egui::Sense::click()); - disclosure_triangle(ui.painter(), tri_rect.center(), !ffold, t.text); - crate::scenario::publish_handle("sketch_palette:feature_fold", tri_rect.center()); - let label_resp = ui.add(egui::Label::new(RichText::new(app.tr("ui.feature_options")).size(12.0)).sense(egui::Sense::click())); - if tri_resp.clicked() || label_resp.clicked() { - FEATURE_FOLDED.with(|f| f.set(!ffold)); + // The options list normally scrolls on its own to keep Finish Sketch visible. + // When even the headings and footer cannot fit, scroll the whole palette. + let available_height = (bottom - anchor.y - frame.inner_margin.sum().y - 2.0 * frame.stroke.width).max(0.0); + let scroll_palette = bottom - anchor.y < 360.0; + let mut contents = |ui: &mut egui::Ui| { + let content_top = ui.cursor().top(); + let line = ui.text_style_height(&egui::TextStyle::Body); + let gap = ui.spacing().item_spacing.y; + crate::frame::heading(ui, Level::Title, width, |ui| { + let folded = FOLDED.with(Cell::get); + if ui.add(egui::Button::new(RichText::new(if folded { "+" } else { "−" }).size(14.0)).frame(false)).clicked() { + FOLDED.with(|f| f.set(!folded)); } + ui.label(RichText::new(app.tr("ui.heading_sketch_palette")).strong().size(12.5)); }); - if !ffold { - let section = ui.vertical(|ui| feature_row(app, ui, width, family, current)); - start = section.inner; - crate::scenario::publish_rect("sketch_palette:feature_options", section.response.rect); + if FOLDED.with(Cell::get) { + return; } - ui.add_space(2.0); - } - let ofold = OPTIONS_FOLDED.with(Cell::get); - crate::frame::heading(ui, Level::Section, width, |ui| { - let (tri_rect, tri_resp) = ui.allocate_exact_size(vec2(14.0, 14.0), egui::Sense::click()); - disclosure_triangle(ui.painter(), tri_rect.center(), !ofold, t.text); - crate::scenario::publish_handle("sketch_palette:options_fold", tri_rect.center()); - let label_resp = ui.add(egui::Label::new(RichText::new(app.tr("ui.options")).size(12.0)).sense(egui::Sense::click())); - if tri_resp.clicked() || label_resp.clicked() { - OPTIONS_FOLDED.with(|f| f.set(!ofold)); - } - }); - if !ofold { - // Keep room for the footer: status heading and line, a line, Finish Sketch, a line. - let ends_rows = if open_ends > 0 { line + gap } else { 0.0 } + if untied_ends > 0 { ui.spacing().interact_size.y + gap } else { 0.0 }; - let footer = 5.0 * line + ui.spacing().interact_size.y + 6.0 * gap + 8.0 + ends_rows; - let options_height = (bottom - ui.cursor().top() - footer).max(24.0); - let options = - egui::ScrollArea::vertical().id_salt("sc_palette_options").max_height(options_height).auto_shrink([false, true]).show(ui, |ui| { - // Every row below: its label at the left, its control right-aligned at the - // same column (`frame::right_aligned`), so every row lines up instead of - // each control sitting wherever its label happened to end. - ui.vertical(|ui| { - ui.horizontal(|ui| { - ui.label(app.tr("ui.linetype")); - // Taller and wider than the old text-only buttons. Construction and - // Centerline need a round dot and a clear gap to read apart. 30 by - // 20 px left too little square room for either. - let btn_w = 36.0; - let group_w = 4.0 * btn_w + 3.0 * ui.spacing().item_spacing.x; - crate::frame::right_aligned(ui, width, group_w, |ui| { - ui.horizontal(|ui| { - // With a selection: its line type, and a click converts it; - // without: the mode new curves are drawn in. Each button - // still carries its old glyph as hidden (transparent) text. - // That keeps its hit target, size and accessible name - // exactly as before. A drawn icon (icons.rs) paints over it. - // Construction and Centerline always draw in the theme's - // construction orange. Normal's icon never changes with the - // accent colour. It stays neutral in every case. - let current = mode(app); - for (i, (label, icon, tip)) in [ - ("—", "normal", "Normal"), - ("- -", "construction", "Construction"), - ("-·-", "centerline", "Centerline"), - ("↔", "infinite", "Infinite"), - ] - .iter() - .enumerate() - { - let on = if has_curves { selected_types.get(i).copied().unwrap_or(false) } else { current == i as u8 }; - let tr_tip = app.tr_label(tip); - let hover = if has_curves { - crate::i18n::format("sketch.make_selection", &[("linetype", tr_tip)]) - } else { - crate::i18n::format("sketch.draw_curves", &[("linetype", tr_tip)]) - }; - let btn = egui::Button::new(RichText::new(*label).color(Color32::TRANSPARENT)) - .selected(on) - .min_size(vec2(btn_w, 28.0)); - let resp = ui.add(btn).on_hover_text(hover); - let accent = if *icon == "normal" { t.icon } else { t.construction_geom }; - // A square icon area. The button's own rect is - // text-shaped, wider than tall. A flattened diagonal - // leaves less room for a dash pattern's gaps to read. - let side = (resp.rect.width().min(resp.rect.height()) - 3.0).max(12.0); - let icon_rect = egui::Rect::from_center_size(resp.rect.center(), vec2(side, side)); - crate::icons::paint(ui.painter(), icon_rect, icon, t.icon, t.icon_fill, accent); - if resp.clicked() { - linetype = Some(i as u8); - } - } - }); - }); - }); - ui.horizontal(|ui| { - // One label, one icon button (the "lookat" glyph already used on the - // viewport's own navigation overlay): not the word "Look At" twice. - // The button carries no visible text of its own; `labelled_by` gives - // it the row's own label as its accessible name, so a screen reader - // still hears "Look At" the way the old text button said it. - let label_resp = ui.label(app.tr("ui.look_at")); - let icon_w = 28.0; - let resp = crate::frame::right_aligned(ui, width, icon_w, |ui| { - let r = ui.add(egui::Button::new("").min_size(vec2(icon_w, 20.0))); - let side = (r.rect.width().min(r.rect.height()) - 4.0).max(12.0); - let icon_rect = egui::Rect::from_center_size(r.rect.center(), vec2(side, side)); - crate::icons::paint(ui.painter(), icon_rect, "lookat", t.icon, t.icon_fill, t.accent); - crate::scenario::publish_handle("sketch_palette:look_at", r.rect.center()); - r.labelled_by(label_resp.id) - }); - let resp = resp.on_hover_text(app.tr("ui.look_at")); - if resp.clicked() { - look = true; - } - }); - }); - for (k, label) in TOGGLES { - ui.horizontal(|ui| { - // The label is still part of the toggle: clicking it flips the - // checkbox too, same as before the checkbox moved to its own column. - let label_resp = ui.add(egui::Label::new(app.tr_label(label)).sense(egui::Sense::click())); - let mut on = shown(k); - let box_w = ui.spacing().interact_size.y; - let cb = crate::frame::right_aligned(ui, width, box_w, |ui| { - ui.add(egui::Checkbox::without_text(&mut on)).labelled_by(label_resp.id) - }); - if cb.changed() { - set = Some((k.to_string(), on)); - } else if label_resp.clicked() { - set = Some((k.to_string(), !on)); - } - }); + // Feature Options sits above Options: the modes of the creation tool that is running. + if let Some((family, current)) = feature { + let ffold = FEATURE_FOLDED.with(Cell::get); + crate::frame::heading(ui, Level::Section, width, |ui| { + let (tri_rect, tri_resp) = ui.allocate_exact_size(vec2(14.0, 14.0), egui::Sense::click()); + disclosure_triangle(ui.painter(), tri_rect.center(), !ffold, t.text); + crate::scenario::publish_handle("sketch_palette:feature_fold", tri_rect.center()); + let label_resp = ui.add(egui::Label::new(RichText::new(app.tr("ui.feature_options")).size(12.0)).sense(egui::Sense::click())); + if tri_resp.clicked() || label_resp.clicked() { + FEATURE_FOLDED.with(|f| f.set(!ffold)); } }); - crate::scenario::publish_rect("sketch_palette:options", options.inner_rect); - } - ui.add_space(4.0); - // The status changes when the sketch needs attention, so it gets its own heading. - crate::frame::heading(ui, Level::Section, width, |ui| { - ui.label(RichText::new(app.tr("ui.sketch_status")).size(12.0)); - }); - ui.label(RichText::new(crate::i18n::tr_dyn(&dof_line)).color(if ok { t.sketch_accent } else { t.text_dim })); - // Where a profile can fail (the viewport rings and diamonds them). - if open_ends > 0 { - let text = crate::i18n::format("sketch.open_ends", &[("count", &open_ends.to_string())]); - ui.label(RichText::new(text).color(t.warning)).on_hover_text(app.tr("ui.open_ends_tip")); - } - if untied_ends > 0 { - ui.horizontal(|ui| { - let text = crate::i18n::format("sketch.untied_ends", &[("count", &untied_ends.to_string())]); - ui.label(RichText::new(text).color(t.warning)).on_hover_text(app.tr("ui.untied_ends_tip")); - let button = ui.button(app.tr("ui.tie_ends")).on_hover_text(app.tr("ui.tie_ends_tip")); - crate::scenario::publish_handle("sketch_palette:tie_ends", button.rect.center()); - if button.clicked() { - tie = true; + if !ffold { + let section = ui.vertical(|ui| feature_row(app, ui, width, family, current)); + start = section.inner; + crate::scenario::publish_rect("sketch_palette:feature_options", section.response.rect); + } + ui.add_space(2.0); + } + let ofold = OPTIONS_FOLDED.with(Cell::get); + crate::frame::heading(ui, Level::Section, width, |ui| { + let (tri_rect, tri_resp) = ui.allocate_exact_size(vec2(14.0, 14.0), egui::Sense::click()); + disclosure_triangle(ui.painter(), tri_rect.center(), !ofold, t.text); + crate::scenario::publish_handle("sketch_palette:options_fold", tri_rect.center()); + let label_resp = ui.add(egui::Label::new(RichText::new(app.tr("ui.options")).size(12.0)).sense(egui::Sense::click())); + if tri_resp.clicked() || label_resp.clicked() { + OPTIONS_FOLDED.with(|f| f.set(!ofold)); } }); - } - // One line between the status and Finish Sketch, and below it to the edge. - ui.add_space((line - gap).max(0.0)); - // A row as tall as the button, so the gap below it is just the line. - ui.allocate_ui_with_layout(vec2(ui.available_width(), 0.0), egui::Layout::right_to_left(egui::Align::Min), |ui| { - let button = ui.add(egui::Button::new(RichText::new(app.tr("ui.finish_sketch")).color(t.on_accent)).fill(t.accent)); - crate::scenario::publish_rect("sketch_palette:finish", button.rect); - crate::scenario::publish_handle("sketch_palette:finish", button.rect.center()); - if button.clicked() { - finish = true; + if !ofold { + // Keep room for the footer: status heading and line, a line, Finish Sketch, a line. + let ends_rows = if open_ends > 0 { line + gap } else { 0.0 } + if untied_ends > 0 { ui.spacing().interact_size.y + gap } else { 0.0 }; + let footer = 5.0 * line + ui.spacing().interact_size.y + 6.0 * gap + 8.0 + ends_rows; + let options_height = + if scroll_palette { available_height - (ui.cursor().top() - content_top) - footer } else { bottom - ui.cursor().top() - footer } + .max(24.0); + let options = + egui::ScrollArea::vertical().id_salt("sc_palette_options").max_height(options_height).auto_shrink([false, true]).show(ui, |ui| { + // Every row below: its label at the left, its control right-aligned at the + // same column (`frame::right_aligned`), so every row lines up instead of + // each control sitting wherever its label happened to end. + ui.vertical(|ui| { + ui.horizontal(|ui| { + ui.label(app.tr("ui.linetype")); + // Taller and wider than the old text-only buttons. Construction and + // Centerline need a round dot and a clear gap to read apart. 30 by + // 20 px left too little square room for either. + let btn_w = 36.0; + let group_w = 4.0 * btn_w + 3.0 * ui.spacing().item_spacing.x; + crate::frame::right_aligned(ui, width, group_w, |ui| { + ui.horizontal(|ui| { + // With a selection: its line type, and a click converts it; + // without: the mode new curves are drawn in. Each button + // still carries its old glyph as hidden (transparent) text. + // That keeps its hit target, size and accessible name + // exactly as before. A drawn icon (icons.rs) paints over it. + // Construction and Centerline always draw in the theme's + // construction orange. Normal's icon never changes with the + // accent colour. It stays neutral in every case. + let current = mode(app); + for (i, (label, icon, tip)) in [ + ("—", "normal", "Normal"), + ("- -", "construction", "Construction"), + ("-·-", "centerline", "Centerline"), + ("↔", "infinite", "Infinite"), + ] + .iter() + .enumerate() + { + let on = if has_curves { selected_types.get(i).copied().unwrap_or(false) } else { current == i as u8 }; + let tr_tip = app.tr_label(tip); + let hover = if has_curves { + crate::i18n::format("sketch.make_selection", &[("linetype", tr_tip)]) + } else { + crate::i18n::format("sketch.draw_curves", &[("linetype", tr_tip)]) + }; + let btn = egui::Button::new(RichText::new(*label).color(Color32::TRANSPARENT)) + .selected(on) + .min_size(vec2(btn_w, 28.0)); + let resp = ui.add(btn).on_hover_text(hover); + let accent = if *icon == "normal" { t.icon } else { t.construction_geom }; + // A square icon area. The button's own rect is + // text-shaped, wider than tall. A flattened diagonal + // leaves less room for a dash pattern's gaps to read. + let side = (resp.rect.width().min(resp.rect.height()) - 3.0).max(12.0); + let icon_rect = egui::Rect::from_center_size(resp.rect.center(), vec2(side, side)); + crate::icons::paint(ui.painter(), icon_rect, icon, t.icon, t.icon_fill, accent); + if resp.clicked() { + linetype = Some(i as u8); + } + } + }); + }); + }); + ui.horizontal(|ui| { + // One label, one icon button (the "lookat" glyph already used on the + // viewport's own navigation overlay): not the word "Look At" twice. + // The button carries no visible text of its own; `labelled_by` gives + // it the row's own label as its accessible name, so a screen reader + // still hears "Look At" the way the old text button said it. + let label_resp = ui.label(app.tr("ui.look_at")); + let icon_w = 28.0; + let resp = crate::frame::right_aligned(ui, width, icon_w, |ui| { + let r = ui.add(egui::Button::new("").min_size(vec2(icon_w, 20.0))); + let side = (r.rect.width().min(r.rect.height()) - 4.0).max(12.0); + let icon_rect = egui::Rect::from_center_size(r.rect.center(), vec2(side, side)); + crate::icons::paint(ui.painter(), icon_rect, "lookat", t.icon, t.icon_fill, t.accent); + crate::scenario::publish_handle("sketch_palette:look_at", r.rect.center()); + r.labelled_by(label_resp.id) + }); + let resp = resp.on_hover_text(app.tr("ui.look_at")); + if resp.clicked() { + look = true; + } + }); + }); + for (k, label) in TOGGLES { + ui.horizontal(|ui| { + // The label is still part of the toggle: clicking it flips the + // checkbox too, same as before the checkbox moved to its own column. + let label_resp = ui.add(egui::Label::new(app.tr_label(label)).sense(egui::Sense::click())); + let mut on = shown(k); + let box_w = ui.spacing().interact_size.y; + let cb = crate::frame::right_aligned(ui, width, box_w, |ui| { + ui.add(egui::Checkbox::without_text(&mut on)).labelled_by(label_resp.id) + }); + if cb.changed() { + set = Some((k.to_string(), on)); + } else if label_resp.clicked() { + set = Some((k.to_string(), !on)); + } + }); + } + }); + crate::scenario::publish_rect("sketch_palette:options", options.inner_rect); } - }); - ui.add_space((line - margin_bottom).max(0.0)); + ui.add_space(4.0); + // The status changes when the sketch needs attention, so it gets its own heading. + crate::frame::heading(ui, Level::Section, width, |ui| { + ui.label(RichText::new(app.tr("ui.sketch_status")).size(12.0)); + }); + ui.label(RichText::new(crate::i18n::tr_dyn(&dof_line)).color(if ok { t.sketch_accent } else { t.text_dim })); + // Where a profile can fail (the viewport rings and diamonds them). + if open_ends > 0 { + let text = crate::i18n::format("sketch.open_ends", &[("count", &open_ends.to_string())]); + ui.label(RichText::new(text).color(t.warning)).on_hover_text(app.tr("ui.open_ends_tip")); + } + if untied_ends > 0 { + ui.horizontal(|ui| { + let text = crate::i18n::format("sketch.untied_ends", &[("count", &untied_ends.to_string())]); + ui.label(RichText::new(text).color(t.warning)).on_hover_text(app.tr("ui.untied_ends_tip")); + let button = ui.button(app.tr("ui.tie_ends")).on_hover_text(app.tr("ui.tie_ends_tip")); + crate::scenario::publish_handle("sketch_palette:tie_ends", button.rect.center()); + if button.clicked() { + tie = true; + } + }); + } + // One line between the status and Finish Sketch, and below it to the edge. + ui.add_space((line - gap).max(0.0)); + // A row as tall as the button, so the gap below it is just the line. + ui.allocate_ui_with_layout(vec2(ui.available_width(), 0.0), egui::Layout::right_to_left(egui::Align::Min), |ui| { + let button = ui.add(egui::Button::new(RichText::new(app.tr("ui.finish_sketch")).color(t.on_accent)).fill(t.accent)); + crate::scenario::publish_rect("sketch_palette:finish", button.rect); + crate::scenario::publish_handle("sketch_palette:finish", button.rect.center()); + if button.clicked() { + finish = true; + } + }); + ui.add_space((line - margin_bottom).max(0.0)); + }; + if scroll_palette { + egui::ScrollArea::vertical() + .id_salt("sc_palette_content") + .max_height(available_height) + .min_scrolled_height(0.0) + .auto_shrink([false, true]) + .show(ui, contents); + } else { + contents(ui); + } }); app.viewport.palette_rect = response.map(|r| r.response.rect); if let Some(r) = app.viewport.palette_rect { diff --git a/crates/ui-egui/src/sketch_text_handles.rs b/crates/ui-egui/src/sketch_text_handles.rs index 3f643a5f6..8c1ac01a4 100644 --- a/crates/ui-egui/src/sketch_text_handles.rs +++ b/crates/ui-egui/src/sketch_text_handles.rs @@ -433,6 +433,9 @@ mod tests { #[test] fn dragging_a_corner_resizes_the_text_in_one_undo_step() { let (mut h, link) = setup(); + // Both the initial handle and the doubled text must stay below the floating ribbon. + h.app.cam.distance = 90.0; + h.frames(3); let before = (h.app.session.doc.to_json(), h.app.session.undo.len()); let f = frame(&h.app, &link).unwrap(); // Pull the top right corner out to twice the frame: the bottom left stays put. @@ -461,7 +464,8 @@ mod tests { let result = h.app.run("sketch.text", json!({"text":"II","at":[0,0],"height":"tall"})).unwrap(); let link = result["link"].as_str().unwrap().to_owned(); h.call("ui.view", json!({"view":"top"})); - h.app.cam.distance = 60.0; + // Keep the rotated resize target clear of the floating ribbon too. + h.app.cam.distance = 90.0; h.app.session.selection = vec![Sel::SketchCurve { id: result["curves"][0].as_str().unwrap().into() }]; h.frames(3); let height_expr = |h: &Harness| { diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 853e9227c..b3f62ce06 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -403,6 +403,11 @@ pub struct Tokens { } impl Tokens { + /// Subtle shell elevation, derived from the semantic application-bar colour. + pub(crate) fn shell_shadow(self) -> egui::Shadow { + egui::Shadow { offset: [0, self.space_2 as i8], blur: self.space_8 as u8, spread: 0, color: self.app_bar.gamma_multiply(0.18) } + } + /// The tokens of the current theme and colour vision mode. pub fn get() -> Tokens { Tokens::themed(is_dark(), vision()) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index d0665c7fe..3379cb4fe 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -92,9 +92,11 @@ pub const COLLAPSED_WIDTH: f32 = 72.0; /// The gap after each panel (its separator). const PANEL_GAP: f32 = 1.0; pub const TAB_ROW_HEIGHT: f32 = 30.0; +/// Distance from the ribbon card's edges to the first tab and the search field. +const RIBBON_TAB_INSET: f32 = 4.0; pub const GROUP_HEIGHT: f32 = 86.0; pub const RIBBON_HEIGHT: f32 = TAB_ROW_HEIGHT + GROUP_HEIGHT + 1.0; -const WORKSPACE_WIDTH: f32 = 88.0; +pub(crate) const WORKSPACE_WIDTH: f32 = 88.0; const BUTTON_HEIGHT: f32 = 60.0; const BUTTON_GAP: f32 = 3.0; const BUTTON_MIN_WIDTH: f32 = 54.0; @@ -791,12 +793,20 @@ fn ribbon_tabs(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect) { + tabs.len().saturating_sub(1) as f32 * 2.0 + tabs.iter().filter(|tab| matches!(**tab, "SKETCH" | "SHEET METAL")).count() as f32 * 6.0; let search_width = if row.width() >= tabs_width + 188.0 + 16.0 { 188.0 } else { 24.0 }; - let search = Rect::from_min_size(pos2((row.right() - search_width - 6.0).max(row.left()), row.top() + 3.0), vec2(search_width, 24.0)); + // The first tab and the search field sit the same distance from the card's top, left and right + // edges, so their outer corners are concentric with the card's corners. + let floating = app.ui.layout == crate::shell::LayoutMode::Floating; + let inset = RIBBON_TAB_INSET; + let corner = if floating { t.radius_lg.saturating_sub(inset as u8).max(2) } else { 5 }; + let search = Rect::from_min_size( + pos2((row.right() - search_width - inset).max(row.left()), row.top() + inset), + vec2(search_width, TAB_ROW_HEIGHT - 2.0 * inset), + ); let resp = ui.interact(search, ui.id().with("ribbon_search"), Sense::click()); crate::scenario::publish_handle("ribbon:search", search.center()); crate::scenario::publish_rect("ribbon:search", search); ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("sc_ribbon_search"), search)); - ui.painter().rect(search, 5.0, t.field, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + ui.painter().rect(search, corner, t.field, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); // The existing zoom glyph is the icon system's magnifier; no new artwork. icons::paint_icon(ui.painter(), Rect::from_center_size(search.left_center() + vec2(12.0, 0.0), vec2(16.0, 16.0)), "zoom", 1.0); let label = app.tr_label("Search commands"); @@ -817,7 +827,7 @@ fn ribbon_tabs(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect) { d.insert_temp(id, state); changed }); - let span = Rect::from_min_max(row.left_top() + vec2(4.0, 0.0), pos2((search.left() - 6.0).max(row.left() + 4.0), row.bottom())); + let span = Rect::from_min_max(row.left_top() + vec2(inset, 0.0), pos2((search.left() - 6.0).max(row.left() + inset), row.bottom())); ui.scope_builder(egui::UiBuilder::new().max_rect(span), |ui| { ui.set_clip_rect(span); egui::ScrollArea::horizontal() @@ -833,7 +843,7 @@ fn ribbon_tabs(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect) { if contextual { x += 6.0; } - let tr = Rect::from_min_size(pos2(x, all.top() + 3.0), vec2(width, 24.0)); + let tr = Rect::from_min_size(pos2(x, all.top() + inset), vec2(width, TAB_ROW_HEIGHT - 2.0 * inset)); let active = app.ui.tab == tab; if active && changed { ui.scroll_to_rect(tr, Some(egui::Align::Center)); @@ -850,7 +860,7 @@ fn ribbon_tabs(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect) { } else { Color32::TRANSPARENT }; - ui.painter().rect_filled(tr, t.radius_sm.saturating_add(1), fill); + ui.painter().rect_filled(tr, corner, fill); ribbon_text( ui, tr.center(), @@ -912,21 +922,43 @@ fn selected_ink(accent: &crate::theme::TabAccent) -> Color32 { pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); crate::workspace::sync_context(app); - egui::Panel::top("sc_toolbar").exact_size(RIBBON_HEIGHT).show_separator_line(false).frame(egui::Frame::NONE.fill(t.toolbar)).show(ui, |ui| { - let r = ui.max_rect(); + let floating = app.ui.layout == crate::shell::LayoutMode::Floating; + let cards = crate::shell::Cards::new(ui.available_rect_before_wrap(), app.ui.layout); + let height = if floating { cards.bottom - ui.available_rect_before_wrap().top() } else { RIBBON_HEIGHT }; + let fill = if floating { Color32::TRANSPARENT } else { t.toolbar }; + egui::Panel::top("sc_toolbar").exact_size(height).show_separator_line(false).frame(egui::Frame::NONE.fill(fill)).show(ui, |ui| { + let r = if floating { Rect::from_min_max(cards.workspace.min, cards.ribbon.max) } else { ui.max_rect() }; + let ws = if floating { cards.workspace } else { Rect::from_min_size(r.left_top(), vec2(WORKSPACE_WIDTH, RIBBON_HEIGHT - 1.0)) }; + let ribbon_left = if floating { cards.ribbon.left() } else { ws.right() + 1.0 }; + if floating { + for card in [ws, cards.ribbon] { + let frame = egui::Frame::NONE.fill(t.toolbar).stroke(Stroke::new(1.0, t.border)).corner_radius(t.radius_lg).shadow(t.shell_shadow()); + ui.painter().add(frame.paint(card)); + // Blank card space owns clicks as well as its buttons. + ui.interact(card, ui.id().with(("shell_card", card.left().to_bits())), Sense::click_and_drag()); + } + crate::scenario::publish_rect("ribbon:card", cards.ribbon); + } let painter = ui.painter().clone(); - let bg = ui.interact(r, ui.id().with("toolbar_bg"), Sense::click()); + let bg = ui.interact(if floating { cards.ribbon } else { r }, ui.id().with("toolbar_bg"), Sense::click()); if bg.secondary_clicked() { crate::context_menu::open_for(app, bg.interact_pointer_pos().unwrap_or(r.left_bottom()), crate::context_menu::Target::Toolbar); } - let ws = Rect::from_min_size(r.left_top(), vec2(WORKSPACE_WIDTH, RIBBON_HEIGHT - 1.0)); let wresp = ui.interact(ws, ui.id().with("workspace_switcher"), Sense::click()); let open = app.viewport.context_menu.is_some() && app.menu.target == crate::context_menu::Target::Workspace; if wresp.hovered() || open { - painter.rect_filled(ws, 0.0, t.hover); + painter.rect_filled(ws, if floating { t.radius_lg } else { 0 }, t.hover); + } + // Keep the accent straight while leaving the floating card's top corners round. + let accent_inset = if floating { f32::from(t.radius_lg) } else { 0.0 }; + painter.rect_filled( + Rect::from_min_size(ws.left_top() + vec2(accent_inset, 0.0), vec2((ws.width() - 2.0 * accent_inset).max(0.0), t.space_3)), + egui::CornerRadius { nw: 0, ne: 0, sw: if floating { 2 } else { 0 }, se: if floating { 2 } else { 0 } }, + t.accent, + ); + if !floating { + painter.line_segment([ws.right_top(), ws.right_bottom()], Stroke::new(1.0, t.border)); } - painter.rect_filled(Rect::from_min_size(ws.left_top(), vec2(WORKSPACE_WIDTH, 3.0)), 0.0, t.accent); - painter.line_segment([ws.right_top(), ws.right_bottom()], Stroke::new(1.0, t.border)); let render = crate::render_workspace::active(app); let workspace_icon = if render { "ws_render" } else { "ws_design" }; icons::paint_icon(&painter, Rect::from_center_size(pos2(ws.center().x, ws.top() + 39.0), vec2(30.0, 30.0)), workspace_icon, 1.0); @@ -942,7 +974,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { crate::scenario::publish_rect("workspace_switcher", ws); crate::scenario::publish_rect("ribbon:workspace", ws); crate::scenario::publish_handle("ribbon:workspace", ws.center()); - ribbon_tabs(app, ui, Rect::from_min_max(pos2(ws.right() + 1.0, r.top()), pos2(r.right(), r.top() + TAB_ROW_HEIGHT))); + ribbon_tabs(app, ui, Rect::from_min_max(pos2(ribbon_left, r.top()), pos2(r.right(), r.top() + TAB_ROW_HEIGHT))); // Panels. let tab = app.ui.tab.clone(); // The command whose tool or dialog is open right now, shown pressed in the toolbar. @@ -953,7 +985,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { (None, Some(_)) => app.last_command.as_ref().map(|(id, _)| id.clone()), _ => None, }; - let mut px = r.left() + WORKSPACE_WIDTH + 1.0; + let mut px = ribbon_left; let top = r.top() + TAB_ROW_HEIGHT; let mut drop: Option<(&'static str, &'static str, Option<&'static str>)> = None; let mut menu: Option<(egui::Pos2, &'static str)> = None; @@ -1199,7 +1231,13 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { } } // A 20 px label row is also the section's existing command-list button. - let lr = Rect::from_min_size(pos2(px + 3.0, top + GROUP_HEIGHT - SECTION_HEIGHT - 3.0), vec2((width - 6.0).max(0.0), SECTION_HEIGHT)); + // The group area ends 1 px above the card's bottom edge, so the highlight is + // RIBBON_TAB_INSET from the card's bottom edge (and from its left edge in the first + // section): its corner is concentric with the card's. + let lr = Rect::from_min_size( + pos2(px + RIBBON_TAB_INSET, top + GROUP_HEIGHT - SECTION_HEIGHT - (RIBBON_TAB_INSET - 1.0)), + vec2((width - 2.0 * RIBBON_TAB_INSET).max(0.0), SECTION_HEIGHT), + ); let lresp = ui.interact(lr, ui.id().with(("panel", panel)), Sense::click()); crate::scenario::publish_handle(&format!("panel:{tab}:{panel}"), lr.center()); crate::scenario::publish_handle(&format!("ribbon:section:{tab}:{panel}"), lr.center()); @@ -1355,7 +1393,9 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { response.response.on_hover_text(crate::i18n::tr_label("More toolbar panels")); }); } - painter.line_segment([pos2(r.left(), r.bottom() - 0.5), pos2(r.right(), r.bottom() - 0.5)], Stroke::new(1.0, t.border)); + if !floating { + painter.line_segment([pos2(r.left(), r.bottom() - 0.5), pos2(r.right(), r.bottom() - 0.5)], Stroke::new(1.0, t.border)); + } // Dragging a command: its icon follows the pointer; a toolbar button dragged off the // toolbar (or into the open drop-down) shows it will be removed. let pointer = ui.input(|i| i.pointer.latest_pos()); @@ -2346,23 +2386,26 @@ mod dropdown_tests { /// reached with the arrow keys and comes into view. #[test] fn a_tall_drop_down_scrolls_inside_a_short_window() { - let mut h = crate::scenario::Harness::new(); - h.app.home.open = false; - h.call("ui.resize", json!({"width":1200,"height":320})); - h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); - h.frames(4); - h.step(&json!({"click":{"handle":"panel:SKETCH:CREATE"}})).unwrap(); - h.frames(4); - let menu = crate::scenario::rect_of("toolbar_dropdown").expect("the drop-down is open"); - assert!(menu.bottom() <= 320.0, "the drop-down runs past the window: {menu:?}"); - assert!(crate::scenario::handle_at("dropdown:sketch.text").is_some_and(|p| !menu.contains(p)), "Text starts below the fold"); - // Up from no focus goes to the last enabled row; it scrolls into view. - h.step(&json!({"key":"ArrowUp"})).unwrap(); - h.frames(10); - let hot = crate::scenario::handles("dropdown_hot:"); - let [(_, at)] = hot.as_slice() else { panic!("one highlighted row: {hot:?}") }; - let menu = crate::scenario::rect_of("toolbar_dropdown").unwrap(); - assert!(menu.contains(*at), "the focused last row is out of view: {at:?} in {menu:?}"); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.set", json!({"layout":mode})); + h.call("ui.resize", json!({"width":1200,"height":320})); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.frames(4); + h.step(&json!({"click":{"handle":"panel:SKETCH:CREATE"}})).unwrap(); + h.frames(4); + let menu = crate::scenario::rect_of("toolbar_dropdown").expect("the drop-down is open"); + assert!(menu.bottom() <= 320.0, "the drop-down runs past the window: {menu:?}"); + assert!(crate::scenario::handle_at("dropdown:sketch.text").is_some_and(|p| !menu.contains(p)), "Text starts below the fold"); + // Up from no focus goes to the last enabled row; it scrolls into view. + h.step(&json!({"key":"ArrowUp"})).unwrap(); + h.frames(10); + let hot = crate::scenario::handles("dropdown_hot:"); + let [(_, at)] = hot.as_slice() else { panic!("one highlighted row: {hot:?}") }; + let menu = crate::scenario::rect_of("toolbar_dropdown").unwrap(); + assert!(menu.contains(*at), "the focused last row is out of view: {at:?} in {menu:?}"); + } } /// Every row of a drop-down is shown when the window has room, even after a shorter list was diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 5d56643c2..cf0840a26 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -2527,8 +2527,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { // A two-point shape being dragged out (#1630) follows the pointer and ends where it is let go, // even over the shape's own dimension box, which rides along beside the pointer. if let Some(from) = app.viewport.draw_drag { - let at = ui.input(|i| i.pointer.latest_pos()).filter(|p| rect.contains(*p)); - if resp.drag_stopped() { + let at = ui.input(|i| i.pointer.latest_pos()).filter(|p| rect.contains(*p) && !crate::shell::covered(app, *p)); + if resp.drag_stopped() || !primary_down { app.viewport.draw_drag = None; if let Some(p) = at && app.tool.as_ref().is_some_and(|t| t.pts.len() == 1) @@ -2884,6 +2884,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if resp.drag_started_by(egui::PointerButton::Primary) && let Some(a) = ui.input(|i| i.pointer.press_origin()) && rect.contains(a) + && !crate::shell::covered(app, a) && !axes.contains(a) { crate::joint_drag::start(app, &proj, a); @@ -2913,10 +2914,16 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if resp.dragged_by(egui::PointerButton::Primary) && let (Some(a), Some(b)) = (origin, hover) && rect.contains(a) + && !crate::shell::covered(app, a) && !axes.contains(a) { app.viewport.boxsel = Some(BoxSel::from_drag(a, b)); } + // A shell card disables its underlying widgets. The release still ends a + // rubber band even when egui no longer sends drag_stopped to the viewport. + if !primary_down && !inside { + app.viewport.boxsel = None; + } if resp.drag_stopped() && let Some(bx) = app.viewport.boxsel.take() { @@ -2975,7 +2982,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { if let Some(since) = app.computing_since() { let seconds = ((crate::now_ms() - since) / 1000.0).floor().max(0.0); let text = crate::i18n::format("dialog.computing", &[("seconds", &format!("{seconds:.0}"))]); - let pos = pos2(rect.left() + 12.0, rect.bottom() - 76.0); + let pos = pos2(crate::shell::content_rect(app, rect).left() + 12.0, rect.bottom() - 76.0); let galley = painter.layout_no_wrap(text, FontId::proportional(t.font_label), t.text); let r = Rect::from_min_size(pos, galley.size() + vec2(34.0, 8.0)); painter.rect_filled(r, t.radius_sm, t.overlay); @@ -2986,7 +2993,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) { // Status chip. if let Some((msg, at, err)) = app.status.clone() { if crate::now_ms() - at < 6000.0 { - let pos = pos2(rect.left() + 12.0, rect.bottom() - 46.0); + let pos = pos2(crate::shell::content_rect(app, rect).left() + 12.0, rect.bottom() - 46.0); let galley = painter.layout_no_wrap(msg, FontId::proportional(t.font_label), if err { t.error } else { t.text }); let r = Rect::from_min_size(pos, galley.size() + vec2(16.0, 8.0)); painter.rect_filled(r, t.radius_sm, t.overlay); @@ -3444,7 +3451,7 @@ fn overlays(app: &SolveApp, painter: &egui::Painter, proj: &Proj) { } loose_end_markers(sk, &ss.ends, &ss.plane, painter, proj, &t); // Sketch status. - if let Some(r) = app.viewport.rect { + if let Some(r) = app.viewport.layout.as_ref().map(|l| l.content) { let msg = if !ss.report.ok() { format!("{} — constraints conflict", ss.name) } else if ss.report.dof == 0 { @@ -3509,12 +3516,13 @@ pub(crate) fn scene_palette(dark: bool, mode: crate::theme::ColorVision) -> soli pub(crate) fn refresh_layout(app: &mut SolveApp, scale: f32) { if let Some(rect) = app.viewport.rect { - let docks: Vec<_> = - [app.viewport.palette_rect.filter(|_| app.session.active_sketch.is_some()), app.viewport.dialog_rect.filter(|_| app.dialog.is_some())] - .into_iter() - .flatten() - .collect(); - app.viewport.layout = Some(crate::viewport_layout::Layout::new(rect, &docks, scale, app.preferences.navigator_style)); + let docks = crate::shell::covered_rects(app); + let content = crate::shell::content_rect(app, rect); + app.viewport.layout = Some(if app.ui.layout == crate::shell::LayoutMode::Docked { + crate::viewport_layout::Layout::new(rect, &docks, scale, app.preferences.navigator_style) + } else { + crate::viewport_layout::Layout::with_content(rect, content, &docks, scale, app.preferences.navigator_style) + }); } } @@ -3555,7 +3563,7 @@ fn axis_view_orbit(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) -> bool { let p = &i.pointer; (p.primary_pressed(), p.primary_down(), p.is_decidedly_dragging(), p.press_origin(), p.interact_pos(), i.modifiers.shift) }); - if pressed && ui.rect_contains_pointer(rect) { + if pressed && ui.is_enabled() && ui.rect_contains_pointer(rect) && !pos.is_some_and(|p| crate::shell::covered(app, p)) { app.viewport.axis_drag = origin.filter(|p| match app.preferences.navigator_style { crate::prefs::NavigatorStyle::Axes => axis_rect(app, rect).contains(*p), crate::prefs::NavigatorStyle::Cube => { @@ -3598,7 +3606,7 @@ fn signed_axis_view(app: &mut SolveApp, ui: &mut egui::Ui, rect: Rect) { let c = axis_center(app, rect); let orbiting = axis_view_orbit(app, ui, rect); let tips = axis_tips(&app.cam, c); - let hover = ui.input(|i| i.pointer.hover_pos()).filter(|_| ui.rect_contains_pointer(rect)); + let hover = ui.input(|i| i.pointer.hover_pos()).filter(|p| ui.is_enabled() && ui.rect_contains_pointer(rect) && !crate::shell::covered(app, *p)); let hovered = if orbiting { None } else { hover.and_then(|p| axis_hit(&tips, p)) }; let painter = ui.painter_at(rect); if orbiting || hover.is_some_and(|p| axis_rect(app, rect).contains(p)) { @@ -5892,8 +5900,14 @@ mod tests { h.frames(20); h.app.cam != before }; - for smooth in [true, false] { + for (layout, smooth) in [ + (crate::shell::LayoutMode::Floating, true), + (crate::shell::LayoutMode::Floating, false), + (crate::shell::LayoutMode::Docked, true), + (crate::shell::LayoutMode::Docked, false), + ] { let mut h = Harness::new(); + h.call("ui.set", json!({"layout":layout})); h.app.preferences.smooth_wheel_zoom = smooth; h.app.preferences.zoom_to_cursor = false; h.call("engine.execute", json!({"command": "solid.box", "params": {"length": 40, "width": 30, "height": 20}})); @@ -5931,18 +5945,21 @@ mod tests { h.call("ui.move", field.clone()); h.call("ui.click", field); assert!(handle_at(item).is_none(), "the list must close"); - let (mid, x) = (vp.center().y, vp.left() + vp.width() * 0.25); + // The full floating viewport extends under the browser; its exposed content + // edge is the boundary between the panel and navigable model in either layout. + let content = crate::shell::content_rect(&h.app, vp); + let (mid, x) = (content.center().y, content.left() + content.width() * 0.25); for p in [ pos2(dialog.left() + 2.0, dialog.center().y), pos2(dialog.center().x, dialog.bottom() - 2.0), - pos2(vp.left() - 2.0, mid), + pos2(content.left() - 2.0, mid), pos2(x, vp.bottom() + 2.0), ] { assert!(!wheel(&mut h, p, 60.0), "smooth {smooth}: the wheel at {p:?} off the model ({vp:?}, dialog {dialog:?}) zoomed it"); assert!(h.app.viewport.mouse.is_none(), "the model must not see the pointer at {p:?}"); } // The model itself still zooms right next to them. - for p in [pos2(dialog.left() - 2.0, dialog.center().y), pos2(vp.left() + 2.0, mid), pos2(x, vp.bottom() - 2.0)] { + for p in [pos2(dialog.left() - 2.0, dialog.center().y), pos2(content.left() + 2.0, mid), pos2(x, vp.bottom() - 2.0)] { assert!(wheel(&mut h, p, 60.0), "smooth {smooth}: the wheel at {p:?} on the model ({vp:?}) must zoom it"); assert_eq!(h.app.viewport.mouse, Some(p)); assert!(gestures(&mut h, p), "a pinch and a two-finger scroll at {p:?} on the model must move it"); diff --git a/crates/ui-egui/src/viewport_layout.rs b/crates/ui-egui/src/viewport_layout.rs index 973b0e7e5..1e1c6d672 100644 --- a/crates/ui-egui/src/viewport_layout.rs +++ b/crates/ui-egui/src/viewport_layout.rs @@ -7,6 +7,7 @@ use solidcraft_engine::render::Camera; pub(crate) struct Layout { pub viewport: Rect, pub drawable: Rect, + pub content: Rect, pub axis_view: Rect, pub navigation: Rect, } @@ -15,7 +16,7 @@ pub(crate) struct Layout { fn free_rect(view: Rect, obstacles: &[Rect]) -> Rect { let mut xs = vec![view.left(), view.right()]; let mut ys = vec![view.top(), view.bottom()]; - let obstacles: Vec<_> = obstacles.iter().take(8).map(|r| r.intersect(view)).filter(|r| r.is_positive() && r.is_finite()).collect(); + let obstacles: Vec<_> = obstacles.iter().take(16).map(|r| r.intersect(view)).filter(|r| r.is_positive() && r.is_finite()).collect(); for r in &obstacles { xs.extend([r.left(), r.right()]); ys.extend([r.top(), r.bottom()]); @@ -40,17 +41,21 @@ fn free_rect(view: Rect, obstacles: &[Rect]) -> Rect { impl Layout { pub fn new(viewport: Rect, docks: &[Rect], scale: f32, style: crate::prefs::NavigatorStyle) -> Self { + Self::with_content(viewport, viewport, docks, scale, style) + } + + pub fn with_content(viewport: Rect, content: Rect, docks: &[Rect], scale: f32, style: crate::prefs::NavigatorStyle) -> Self { let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 }; - let mut obstacles: Vec<_> = docks.iter().take(6).copied().filter(|r| r.is_finite()).map(|r| r.expand(4.0)).collect(); + let mut obstacles: Vec<_> = docks.iter().take(14).copied().filter(|r| r.is_finite()).map(|r| r.expand(4.0)).collect(); // Navigation is anchored to the viewport, never to transient dialog space. - let available = viewport; + let available = content; let cube_size = super::viewport::axis_view_size(style); let mut axis_view = if available.width() >= cube_size && available.height() >= cube_size { Rect::from_min_size(pos2(available.right() - cube_size, available.top()), vec2(cube_size, cube_size)) } else { Rect::NOTHING }; - let nav_space = viewport; + let nav_space = content; let columns = ((nav_space.width() - 10.0) / 30.0).floor().clamp(1.0, 10.0); let nav_height = (10.0 / columns).ceil() * 30.0; let navigation = if nav_space.width() >= columns * 30.0 + 10.0 && nav_space.height() >= nav_height + 7.0 { @@ -61,9 +66,9 @@ impl Layout { // On tiny viewports keep the bottom controls usable rather than overlapping them. // This decision depends only on viewport size, never on an overlay. if axis_view.intersect(navigation).is_positive() { - let compact = (navigation.top() - viewport.top() - 4.0).min(cube_size); + let compact = (navigation.top() - content.top() - 4.0).min(cube_size); axis_view = if style == crate::prefs::NavigatorStyle::Cube && compact >= 96.0 { - Rect::from_min_size(pos2(viewport.right() - compact, viewport.top()), vec2(compact, compact)) + Rect::from_min_size(pos2(content.right() - compact, content.top()), vec2(compact, compact)) } else { Rect::NOTHING }; @@ -75,7 +80,7 @@ impl Layout { obstacles.push(navigation); } let drawable = free_rect(viewport, &obstacles).shrink(16.0 / scale); - Self { viewport, drawable, axis_view, navigation } + Self { viewport, drawable, content, axis_view, navigation } } } diff --git a/crates/ui-egui/src/viewport_layout_tests.rs b/crates/ui-egui/src/viewport_layout_tests.rs index ff2d81352..060fcdfb7 100644 --- a/crates/ui-egui/src/viewport_layout_tests.rs +++ b/crates/ui-egui/src/viewport_layout_tests.rs @@ -41,44 +41,55 @@ fn thin_rotated_bounds_fit_using_the_original_full_projection() { #[test] fn measured_palette_fit_exposes_endpoints_and_layout_changes_preserve_manual_view() { - let mut h = Harness::new(); - h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); - h.app.run("sketch.line", json!({"points":[[0,0],[20,0]]})).unwrap(); - h.call("ui.view", json!({"view":"top"})); - h.settle(); - for (scale, width, height) in [(1.0, 1400.0, 900.0), (2.0, 700.0, 475.0), (2.0, 700.0, 385.0), (1.0, 900.0, 720.0)] { - h.call("ui.prefs", json!({"ui_scale":scale})); - h.call("ui.resize", json!({"width":width,"height":height})); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.call("ui.set", json!({"layout":mode})); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.line", json!({"points":[[0,0],[20,0]]})).unwrap(); + h.call("ui.view", json!({"view":"top"})); h.settle(); - let before = h.app.session.doc.to_json(); - let undo = h.app.session.undo.len(); - h.app.fit_view(); - h.settle(); - let layout = h.app.viewport.layout.as_ref().unwrap(); - let palette = h.app.viewport.palette_rect.unwrap(); - assert!(layout.drawable.width() >= 80.0 && layout.drawable.height() >= 30.0, "{layout:?}"); - assert!(layout.axis_view.is_positive() && layout.navigation.is_positive(), "{layout:?}"); - assert!(palette.width() <= 260.0, "{palette:?}"); - let projection = crate::viewport::projection(&h.app, layout.viewport); - for point in [Vec3::ZERO, Vec3::new(20.0, 0.0, 0.0)] { - let p = projection.to_screen(point).unwrap(); - assert!(layout.drawable.contains(p), "endpoint {p:?} outside {layout:?}"); - assert!(!palette.contains(p)); - assert!(!layout.axis_view.contains(p)); - assert!(!layout.navigation.contains(p)); + for (scale, width, height) in [(1.0, 1400.0, 900.0), (2.0, 700.0, 475.0), (2.0, 700.0, 385.0), (1.0, 900.0, 720.0)] { + h.call("ui.prefs", json!({"ui_scale":scale})); + h.call("ui.resize", json!({"width":width,"height":height})); + h.settle(); + let before = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.app.fit_view(); + h.settle(); + let layout = h.app.viewport.layout.as_ref().unwrap(); + let palette = h.app.viewport.palette_rect.unwrap(); + assert!(layout.drawable.width() >= 80.0 && layout.drawable.height() >= 30.0, "{layout:?}"); + // Floating's card margins leave less content height at 385 px. The compass + // intentionally disappears when it cannot fit above the bottom navigation. + assert!( + layout.axis_view.is_positive() + || layout.content.height() + < crate::viewport::axis_view_size(h.app.preferences.navigator_style) + layout.navigation.height() + 11.0, + "{layout:?}" + ); + assert!(layout.navigation.is_positive(), "{layout:?}"); + assert!(palette.width() <= 260.0, "{palette:?}"); + let projection = crate::viewport::projection(&h.app, layout.viewport); + for point in [Vec3::ZERO, Vec3::new(20.0, 0.0, 0.0)] { + let p = projection.to_screen(point).unwrap(); + assert!(layout.drawable.contains(p), "endpoint {p:?} outside {layout:?}"); + assert!(!palette.contains(p)); + assert!(!layout.axis_view.contains(p)); + assert!(!layout.navigation.contains(p)); + } + let fitted = h.app.cam; + h.app.fit_view(); + h.settle(); + assert_eq!(h.app.cam, fitted); + h.app.cancel_view_animation(); + h.app.cam.pan(13.0, -19.0, 500.0); + let manual = h.app.cam; + h.call("ui.resize", json!({"width":width+20.0,"height":height})); + h.settle(); + assert_eq!(h.app.cam, manual); + assert_eq!(h.app.session.doc.to_json(), before); + assert_eq!(h.app.session.undo.len(), undo); } - let fitted = h.app.cam; - h.app.fit_view(); - h.settle(); - assert_eq!(h.app.cam, fitted); - h.app.cancel_view_animation(); - h.app.cam.pan(13.0, -19.0, 500.0); - let manual = h.app.cam; - h.call("ui.resize", json!({"width":width+20.0,"height":height})); - h.settle(); - assert_eq!(h.app.cam, manual); - assert_eq!(h.app.session.doc.to_json(), before); - assert_eq!(h.app.session.undo.len(), undo); } } @@ -98,124 +109,143 @@ fn hostile_or_empty_fit_keeps_the_existing_camera_valid() { #[test] fn fit_home_animation_and_manual_takeover_use_one_layout_solution() { - let mut h = Harness::new(); - h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); - h.app.run("sketch.circle.center", json!({"center":[0,0],"radius":1})).unwrap(); - h.settle(); - for view in ["fit", "home"] { - h.app.preferences.look_at_anim = false; - h.app.animate_view(view); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.call("ui.set", json!({"layout":mode})); + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.circle.center", json!({"center":[0,0],"radius":1})).unwrap(); h.settle(); - let immediate = h.app.cam; - h.app.cam.pan(50.0, 10.0, 400.0); - h.app.preferences.look_at_anim = true; - h.app.animate_view(view); + for view in ["fit", "home"] { + h.app.preferences.look_at_anim = false; + h.app.animate_view(view); + h.settle(); + let immediate = h.app.cam; + h.app.cam.pan(50.0, 10.0, 400.0); + h.app.preferences.look_at_anim = true; + h.app.animate_view(view); + h.settle(); + assert_eq!(h.app.cam, immediate); + } + h.app.fit_view(); + h.app.cancel_view_animation(); + h.app.cam.pan(7.0, 13.0, 400.0); + let takeover = h.app.cam; h.settle(); - assert_eq!(h.app.cam, immediate); + assert_eq!(h.app.cam, takeover); } - h.app.fit_view(); - h.app.cancel_view_animation(); - h.app.cam.pan(7.0, 13.0, 400.0); - let takeover = h.app.cam; - h.settle(); - assert_eq!(h.app.cam, takeover); } #[test] fn measured_navigator_targets_home_and_drag_work_beside_the_palette_at_hidpi() { - for style in crate::prefs::NavigatorStyle::ALL { - for (scale, width, height) in [(1.0, 900.0, 720.0), (2.0, 700.0, 475.0), (2.0, 700.0, 385.0)] { - let mut h = Harness::new(); - h.call("ui.prefs", json!({"navigator_style":style})); - h.app.preferences.look_at_anim = false; - h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); - h.app.run("sketch.circle.center", json!({"center":[0,0],"radius":1})).unwrap(); - h.call("ui.prefs", json!({"ui_scale":scale})); - h.call("ui.resize", json!({"width":width,"height":height})); - h.app.fit_view(); - h.settle(); - let baseline = h.app.session.doc.to_json(); - let undo = h.app.session.undo.len(); - h.call("ui.view", json!({"view":"front"})); - let layout = h.app.viewport.layout.as_ref().unwrap().clone(); - let palette = h.app.viewport.palette_rect.unwrap(); - let outer = crate::scenario::rect_of("axis_view:outer").unwrap(); - let home = crate::scenario::rect_of("axis_view:home").unwrap(); - assert_eq!(outer, layout.axis_view); - assert!(outer.contains_rect(home)); - assert!(layout.viewport.contains_rect(outer)); - assert_eq!(outer.right_top(), layout.viewport.right_top()); - if outer.intersect(palette).is_positive() { - // Short palettes may cover the fixed anchor; covered controls never steal input. - let covered = outer.intersect(palette).center(); - let camera = h.app.cam; - h.call("ui.click", json!({"x":covered.x,"y":covered.y})); - assert_eq!(h.app.cam, camera); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + for style in crate::prefs::NavigatorStyle::ALL { + for (scale, width, height) in [(1.0, 900.0, 720.0), (2.0, 700.0, 475.0), (2.0, 700.0, 385.0)] { + let mut h = Harness::new(); + h.call("ui.set", json!({"layout":mode})); + h.call("ui.prefs", json!({"navigator_style":style})); + h.app.preferences.look_at_anim = false; + h.app.run("sketch.create", json!({"plane":"XY"})).unwrap(); + h.app.run("sketch.circle.center", json!({"center":[0,0],"radius":1})).unwrap(); + h.call("ui.prefs", json!({"ui_scale":scale})); + h.call("ui.resize", json!({"width":width,"height":height})); + h.app.fit_view(); + h.settle(); + let baseline = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.call("ui.view", json!({"view":"front"})); + let layout = h.app.viewport.layout.as_ref().unwrap().clone(); + let palette = h.app.viewport.palette_rect.unwrap(); + if !layout.axis_view.is_positive() { + // Floating's smaller content at tiny heights cannot fit the compass; + // the navigation bar takes priority in both layouts. + assert!(layout.content.height() < crate::viewport::axis_view_size(style) + layout.navigation.height() + 11.0, "{layout:?}"); + assert!(layout.navigation.is_positive()); + assert!(crate::scenario::rect_of("axis_view:outer").is_none()); + assert_eq!(h.app.session.doc.to_json(), baseline); + assert_eq!(h.app.session.undo.len(), undo); + continue; + } + let outer = crate::scenario::rect_of("axis_view:outer").unwrap(); + let home = crate::scenario::rect_of("axis_view:home").unwrap(); + assert_eq!(outer, layout.axis_view); + assert!(outer.contains_rect(home)); + assert!(layout.viewport.contains_rect(outer)); + assert_eq!(outer.right_top(), layout.content.right_top()); + if outer.intersect(palette).is_positive() { + // Short palettes may cover the fixed anchor; covered controls never steal input. + let covered = outer.intersect(palette).center(); + let camera = h.app.cam; + h.call("ui.click", json!({"x":covered.x,"y":covered.y})); + assert_eq!(h.app.cam, camera); + assert!(h.app.viewport.axis_drag.is_none()); + assert_eq!(crate::scenario::rect_of("axis_view:outer").unwrap(), outer); + assert_eq!(h.app.session.doc.to_json(), baseline); + assert_eq!(h.app.session.undo.len(), undo); + continue; + } + assert!(!layout.navigation.intersect(outer).is_positive()); + if style == crate::prefs::NavigatorStyle::Cube { + let front = crate::scenario::handle_at("navigation_cube:front").unwrap(); + assert!(outer.contains(front)); + let up = crate::scenario::handle_at("navigation_cube:control:up").unwrap(); + h.call("ui.click", json!({"x":up.x,"y":up.y})); + assert!(h.app.cam.back().dist(Vec3::Z) < 1e-5); + let top = crate::scenario::handle_at("navigation_cube:top").unwrap(); + h.call("ui.click", json!({"x":top.x,"y":top.y})); + assert!(h.app.cam.back().dist(Vec3::Z) < 1e-5); + } else { + let z = crate::scenario::handle_at("axis_view:z").unwrap(); + assert!(outer.contains(z)); + h.call("ui.click", json!({"x":z.x,"y":z.y})); + assert!(h.app.cam.back().dist(Vec3::Z) < 1e-5); + let z = crate::scenario::handle_at("axis_view:z").unwrap(); + h.call("ui.click", json!({"x":z.x,"y":z.y})); + assert!(h.app.cam.back().dist(-Vec3::Z) < 1e-5); + } + h.call("ui.view", json!({"view":"front"})); + h.app.viewport.nav = Some(crate::viewport::NavMode::Pan); + let before = h.app.cam; + let c = h.app.viewport.layout.as_ref().unwrap().axis_view.center(); + h.call("ui.drag", json!({"x0":c.x,"y0":c.y,"x1":c.x+24.0,"y1":c.y+8.0,"steps":8})); + assert!((h.app.cam.yaw - before.yaw - 24.0 * 0.008).abs() < 1e-6); + assert!((h.app.cam.pitch - before.pitch - 8.0 * 0.008).abs() < 1e-6); + assert_eq!(h.app.cam.target, before.target); + assert_eq!(h.app.cam.distance, before.distance); assert!(h.app.viewport.axis_drag.is_none()); - assert_eq!(crate::scenario::rect_of("axis_view:outer").unwrap(), outer); + assert!(h.app.viewport.boxsel.is_none()); + let home = crate::scenario::handle_at("axis_view:home").unwrap(); + h.call("ui.click", json!({"x":home.x,"y":home.y})); + let mut iso = h.app.cam; + iso.set_view(StandardView::Iso); + assert_eq!((h.app.cam.yaw, h.app.cam.pitch), (iso.yaw, iso.pitch)); assert_eq!(h.app.session.doc.to_json(), baseline); assert_eq!(h.app.session.undo.len(), undo); - continue; + assert!(h.app.session.selection.is_empty()); } - assert!(!layout.navigation.intersect(outer).is_positive()); - if style == crate::prefs::NavigatorStyle::Cube { - let front = crate::scenario::handle_at("navigation_cube:front").unwrap(); - assert!(outer.contains(front)); - let up = crate::scenario::handle_at("navigation_cube:control:up").unwrap(); - h.call("ui.click", json!({"x":up.x,"y":up.y})); - assert!(h.app.cam.back().dist(Vec3::Z) < 1e-5); - let top = crate::scenario::handle_at("navigation_cube:top").unwrap(); - h.call("ui.click", json!({"x":top.x,"y":top.y})); - assert!(h.app.cam.back().dist(Vec3::Z) < 1e-5); - } else { - let z = crate::scenario::handle_at("axis_view:z").unwrap(); - assert!(outer.contains(z)); - h.call("ui.click", json!({"x":z.x,"y":z.y})); - assert!(h.app.cam.back().dist(Vec3::Z) < 1e-5); - let z = crate::scenario::handle_at("axis_view:z").unwrap(); - h.call("ui.click", json!({"x":z.x,"y":z.y})); - assert!(h.app.cam.back().dist(-Vec3::Z) < 1e-5); - } - h.call("ui.view", json!({"view":"front"})); - h.app.viewport.nav = Some(crate::viewport::NavMode::Pan); - let before = h.app.cam; - let c = h.app.viewport.layout.as_ref().unwrap().axis_view.center(); - h.call("ui.drag", json!({"x0":c.x,"y0":c.y,"x1":c.x+24.0,"y1":c.y+8.0,"steps":8})); - assert!((h.app.cam.yaw - before.yaw - 24.0 * 0.008).abs() < 1e-6); - assert!((h.app.cam.pitch - before.pitch - 8.0 * 0.008).abs() < 1e-6); - assert_eq!(h.app.cam.target, before.target); - assert_eq!(h.app.cam.distance, before.distance); - assert!(h.app.viewport.axis_drag.is_none()); - assert!(h.app.viewport.boxsel.is_none()); - let home = crate::scenario::handle_at("axis_view:home").unwrap(); - h.call("ui.click", json!({"x":home.x,"y":home.y})); - let mut iso = h.app.cam; - iso.set_view(StandardView::Iso); - assert_eq!((h.app.cam.yaw, h.app.cam.pitch), (iso.yaw, iso.pitch)); - assert_eq!(h.app.session.doc.to_json(), baseline); - assert_eq!(h.app.session.undo.len(), undo); - assert!(h.app.session.selection.is_empty()); } } } #[test] fn immediate_standard_view_cancels_fit_before_the_measured_frame() { - let mut h = Harness::new(); - h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); - let baseline = h.app.session.doc.to_json(); - let undo = h.app.session.undo.len(); - h.app.cam.set_view(StandardView::Iso); - h.app.fit_view(); - assert!(h.app.pending_fit.is_some(), "Fit awaits the measured overlay frame"); - let mut front = h.app.cam; - front.set_view(StandardView::Front); - h.call("ui.view", json!({"view":"front"})); - h.settle(); - assert!(h.app.pending_fit.is_none()); - assert_eq!(h.app.cam, front, "the later frame must keep the explicitly requested view"); - assert_eq!(h.app.session.doc.to_json(), baseline); - assert_eq!(h.app.session.undo.len(), undo); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.call("ui.set", json!({"layout":mode})); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); + let baseline = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + h.app.cam.set_view(StandardView::Iso); + h.app.fit_view(); + assert!(h.app.pending_fit.is_some(), "Fit awaits the measured overlay frame"); + let mut front = h.app.cam; + front.set_view(StandardView::Front); + h.call("ui.view", json!({"view":"front"})); + h.settle(); + assert!(h.app.pending_fit.is_none()); + assert_eq!(h.app.cam, front, "the later frame must keep the explicitly requested view"); + assert_eq!(h.app.session.doc.to_json(), baseline); + assert_eq!(h.app.session.undo.len(), undo); + } } #[test] @@ -245,34 +275,37 @@ fn navigation_anchors_ignore_positioned_resized_and_covering_dialogs() { #[test] fn opening_different_command_dialogs_keeps_published_navigation_positions() { - let mut h = Harness::new(); - h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); - h.settle(); - let axis = crate::scenario::rect_of("axis_view:outer").unwrap(); - let nav = crate::scenario::rect_of("nav:outer").unwrap(); - let camera = h.app.cam; - let baseline = h.app.session.doc.to_json(); - let undo = h.app.session.undo.len(); - for command in ["solid.extrude", "solid.fillet", "inspect.measure"] { - h.app.start(command); + for mode in [crate::shell::LayoutMode::Floating, crate::shell::LayoutMode::Docked] { + let mut h = Harness::new(); + h.call("ui.set", json!({"layout":mode})); + h.app.run("solid.box", json!({"length":40,"width":30,"height":20})).unwrap(); h.settle(); - assert!(h.app.dialog.is_some(), "{command}"); - assert!(h.app.viewport.dialog_rect.is_some(), "dialog must be measured"); - assert_eq!(crate::scenario::rect_of("axis_view:outer").unwrap(), axis, "{command}"); - assert_eq!(crate::scenario::rect_of("nav:outer").unwrap(), nav, "{command}"); - assert_eq!(h.app.cam, camera); - let pan = pos2(nav.left() + 5.0 + 2.0 * 30.0 + 13.0, nav.top() + 15.0); - assert!(!h.app.viewport.dialog_rect.unwrap().contains(pan)); - h.app.viewport.nav = None; - h.call("ui.click", json!({"x":pan.x,"y":pan.y})); - assert_eq!(h.app.viewport.nav, Some(crate::viewport::NavMode::Pan), "fixed navigation stays usable beside {command}"); - h.app.dialog = None; - h.settle(); - assert_eq!(crate::scenario::rect_of("axis_view:outer").unwrap(), axis); - assert_eq!(crate::scenario::rect_of("nav:outer").unwrap(), nav); + let axis = crate::scenario::rect_of("axis_view:outer").unwrap(); + let nav = crate::scenario::rect_of("nav:outer").unwrap(); + let camera = h.app.cam; + let baseline = h.app.session.doc.to_json(); + let undo = h.app.session.undo.len(); + for command in ["solid.extrude", "solid.fillet", "inspect.measure"] { + h.app.start(command); + h.settle(); + assert!(h.app.dialog.is_some(), "{command}"); + assert!(h.app.viewport.dialog_rect.is_some(), "dialog must be measured"); + assert_eq!(crate::scenario::rect_of("axis_view:outer").unwrap(), axis, "{command}"); + assert_eq!(crate::scenario::rect_of("nav:outer").unwrap(), nav, "{command}"); + assert_eq!(h.app.cam, camera); + let pan = pos2(nav.left() + 5.0 + 2.0 * 30.0 + 13.0, nav.top() + 15.0); + assert!(!h.app.viewport.dialog_rect.unwrap().contains(pan)); + h.app.viewport.nav = None; + h.call("ui.click", json!({"x":pan.x,"y":pan.y})); + assert_eq!(h.app.viewport.nav, Some(crate::viewport::NavMode::Pan), "fixed navigation stays usable beside {command}"); + h.app.dialog = None; + h.settle(); + assert_eq!(crate::scenario::rect_of("axis_view:outer").unwrap(), axis); + assert_eq!(crate::scenario::rect_of("nav:outer").unwrap(), nav); + } + assert_eq!(h.app.session.doc.to_json(), baseline); + assert_eq!(h.app.session.undo.len(), undo); } - assert_eq!(h.app.session.doc.to_json(), baseline); - assert_eq!(h.app.session.undo.len(), undo); } #[test] diff --git a/crates/ui-egui/tests/scenarios/s37_construction_geometries_toggle.json b/crates/ui-egui/tests/scenarios/s37_construction_geometries_toggle.json index b2f9cb823..67d1ce6ef 100644 --- a/crates/ui-egui/tests/scenarios/s37_construction_geometries_toggle.json +++ b/crates/ui-egui/tests/scenarios/s37_construction_geometries_toggle.json @@ -8,6 +8,7 @@ {"call": "engine.execute", "params": {"command": "sketch.construction", "params": {"curves": ["l5"], "value": true}}}, {"call": "engine.execute", "params": {"command": "sketch.centerline", "params": {"curves": ["l6"], "value": true}}}, {"call": "ui.view", "params": {"view": "top"}}, + {"call": "ui.view", "params": {"view": "fit"}}, {"expect": {"shown": "Construction Geometries"}}, {"expect": {"query": {"command": "sketch.options", "path": ["options", "show_construction"], "value": true}}}, diff --git a/crates/ui-egui/tests/scenarios/sketch_pattern_circular_center.json b/crates/ui-egui/tests/scenarios/sketch_pattern_circular_center.json index 8f024092c..a5f50511a 100644 --- a/crates/ui-egui/tests/scenarios/sketch_pattern_circular_center.json +++ b/crates/ui-egui/tests/scenarios/sketch_pattern_circular_center.json @@ -5,7 +5,8 @@ {"call":"engine.execute","params":{"command":"sketch.point","params":{"point":[0,0],"id":"axis_center"}}}, {"call":"engine.execute","params":{"command":"sketch.constraint.fix","params":{"entities":["axis_center"]}}}, {"call":"ui.view","params":{"view":"top"}}, - {"call":"ui.camera","params":{"target":[25,0,0],"distance":120}}, + {"note":"Keep the seed and centre exposed beside the left pattern dialog in the full-bleed shell."}, + {"call":"ui.camera","params":{"target":[-20,0,0],"distance":180}}, {"start":"sketch.pattern.circular"}, {"click":{"sketch":[42,0]}}, {"click":{"handle":"dialog:Center"}}, diff --git a/crates/ui-egui/tests/ui_layout.rs b/crates/ui-egui/tests/ui_layout.rs index 0baefd9c8..0b1b42362 100644 --- a/crates/ui-egui/tests/ui_layout.rs +++ b/crates/ui-egui/tests/ui_layout.rs @@ -72,6 +72,7 @@ fn docked_ribbon_geometry_and_search() { use solidcraft_ui_egui::{scenario::handle_at, toolbar}; for theme in ["light", "dark"] { let mut h = harness(); + h.call("ui.set", json!({"layout":"docked"})); h.app.preferences.theme = theme.into(); for width in [1600.0, 640.0, 320.0] { h.call("ui.resize", json!({"width":width,"height":1000})); @@ -85,7 +86,7 @@ fn docked_ribbon_geometry_and_search() { assert_eq!(workspace.width(), 88.0); assert_eq!(workspace.top(), ribbon.top()); assert_eq!(workspace.bottom(), ribbon.bottom() - 1.0); - assert_eq!(search.height(), 24.0); + assert_eq!(search.height(), 22.0); assert_eq!(search.width(), if width == 1600.0 { 188.0 } else { 24.0 }); assert!(ribbon.contains_rect(search)); assert!(search.left() > workspace.right()); @@ -123,19 +124,22 @@ fn docked_ribbon_geometry_and_search() { #[test] fn finish_sketch_stays_at_the_right_when_groups_collapse() { use solidcraft_ui_egui::scenario::handle_at; - let mut h = Harness::new(); - h.call("engine.execute", json!({"command":"sketch.create","params":{"plane":"XY"}})); - for width in [1600.0, 640.0, 320.0] { - h.call("ui.resize", json!({"width":width,"height":1000})); - h.frames(5); - let ribbon = rect_of("toolbar").unwrap(); - let exit = rect_of("ribbon:section:SKETCH:FINISH SKETCH").unwrap(); - let finish = rect_of("button:sketch.finish").unwrap(); - assert_eq!(exit.right(), ribbon.right() - 3.0); - assert!(ribbon.contains_rect(finish)); - assert!(finish.bottom() < exit.top()); - assert!(handle_at("tab:SKETCH").is_some(), "the selected contextual tab scrolls into view"); + for layout in ["docked", "floating"] { + let mut h = Harness::new(); + h.call("ui.set", json!({"layout":layout})); + h.call("engine.execute", json!({"command":"sketch.create","params":{"plane":"XY"}})); + for width in [1600.0, 640.0, 320.0] { + h.call("ui.resize", json!({"width":width,"height":1000})); + h.frames(5); + let ribbon = rect_of("toolbar").unwrap(); + let exit = rect_of("ribbon:section:SKETCH:FINISH SKETCH").unwrap(); + let finish = rect_of("button:sketch.finish").unwrap(); + assert_eq!(exit.right(), ribbon.right() - 4.0); + assert!(ribbon.contains_rect(finish)); + assert!(finish.bottom() < exit.top()); + assert!(handle_at("tab:SKETCH").is_some(), "the selected contextual tab scrolls into view"); + } + h.step(&json!({"click":{"handle":"button:sketch.finish"}})).unwrap(); + assert!(h.app.session.active_sketch.is_none()); } - h.step(&json!({"click":{"handle":"button:sketch.finish"}})).unwrap(); - assert!(h.app.session.active_sketch.is_none()); } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f2c29879b..dcf72886f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -122,7 +122,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox. | Method | Params | Notes | |---|---|---| | `ui.inspect` | — | UI state, pending file picker (`file_picker_busy`; compatibility alias `file_dialog_open`, no path), what is hidden (`visibility`: bodies, origin and construction items, sketches, joints (`hidden_joints`, joint ids); set it with the `browser.visibility` command), viewport rect, camera, active tool/dialog, the status line (`status`: text and whether it is an error), hover, renderer, timings, live preview (`active`, `busy`, `error`, `ms`, bodies it stands in for) | -| `ui.set` | any `UiState` field (`tab`, `perspective`, `showGrid`, `dark`, …), and `hiddenBodies`, `hiddenOrigin`, `hiddenSketches`, `shownSketches`, `hiddenJoints`, `hiddenFolders` (whole lists; `browser.visibility` changes single items) | `dark: false` switches to the light theme | +| `ui.set` | any `UiState` field (`tab`, `perspective`, `showGrid`, `dark`, `layout`, …), and `hiddenBodies`, `hiddenOrigin`, `hiddenSketches`, `shownSketches`, `hiddenJoints`, `hiddenFolders` (whole lists; `browser.visibility` changes single items) | `dark: false` switches to the light theme; `layout: "floating"` (default) or `"docked"` selects the transient shell layout without saving a preference. Scenarios use `{"call":"ui.set","params":{"layout":"docked"}}` | | `ui.view` | `view`: `front`, `back`, `top`, `bottom`, `left`, `right`, `iso`, `home`, `fit`; `animate` (bool, default false: snap) | | | `ui.camera` | `target?`: `[x, y, z]` (mm), `yaw?`, `pitch?`, `roll?` (radians), `distance?` (mm), `fov?`, `up?`; `fit?`: `true`, `false` or `[occurrence id or name…]` (`root`: the bodies outside every component) | the viewport's orbit camera: it looks at `target` from `distance` away; `yaw` 0 looks along +Y (from the front), `pitch` is the elevation (±π/2: straight down or up), `roll` turns the image. Fields given are set first (the others keep their values), then `fit` frames the listed occurrences (or everything), keeping the direction. The reply, passed back, sets the same view again, so a framing can be stored and replayed. `fov` and `up` follow the perspective setting (`ui.set`) and the up axis preference (`ui.prefs`) and can't change here; a refused field changes nothing | | `ui.start` | `command`, `params?` | like a toolbar click: starts the sketch tool or dialog for the command. `params` sets what the dialog opens on, and nothing runs until OK: `joint.drive` takes `joint` (id or name; without it, the joint picked in the browser, else the first joint that moves) and `values` (numbers in degrees or millimetres, or expressions); `motion.study` takes `study` (id or name), which opens that study to edit and chart. A command that takes no params is refused before it starts; a param the dialog doesn't take is refused and the dialog closes |