From a5e0fe3ec4bcc3e7158fa203ca238d5ec7a9bc6e Mon Sep 17 00:00:00 2001 From: Nathan Dane Date: Tue, 20 Oct 2026 10:30:05 +0200 Subject: [PATCH] Parameters, Configuration Table, Crash Reports and Appearance redesign (step 8 of #2016, after the cleanup PR) --- ATTRIBUTION.md | 2 + assets/icons/ui/design/requested_icons.txt | 4 +- .../icons/ui/design/svg/flat/export_tray.svg | 4 + .../icons/ui/design/svg/flat/import_tray.svg | 4 + assets/icons/ui/source/glyphs.rs | 9 - assets/locales/en.json | 10 + assets/locales/ja.json | 10 + assets/locales/zh.json | 10 + assets/styles/ui/palettes.rs | 48 +- crates/ui-egui/src/agent_chat/panel.rs | 8 +- crates/ui-egui/src/agent_cursor.rs | 13 +- crates/ui-egui/src/bom_panel.rs | 31 +- crates/ui-egui/src/browser.rs | 33 +- crates/ui-egui/src/browser_canvas.rs | 3 +- crates/ui-egui/src/colour_vision_tests.rs | 5 +- crates/ui-egui/src/configuration_rules_ui.rs | 221 +++---- crates/ui-egui/src/configurations_ui.rs | 508 +++++++++------- crates/ui-egui/src/crash_ui.rs | 143 +++-- crates/ui-egui/src/dialogs.rs | 14 +- crates/ui-egui/src/dialogs_appearance.rs | 84 ++- crates/ui-egui/src/dialogs_assembly.rs | 8 +- crates/ui-egui/src/dialogs_dense.rs | 3 + crates/ui-egui/src/dialogs_library.rs | 56 +- crates/ui-egui/src/dialogs_library_tests.rs | 24 + crates/ui-egui/src/dialogs_motion.rs | 27 +- crates/ui-egui/src/expression_complete.rs | 13 +- crates/ui-egui/src/frame.rs | 14 +- crates/ui-egui/src/manage_dialogs_tests.rs | 294 +++++++++- crates/ui-egui/src/palette.rs | 2 +- crates/ui-egui/src/params_dialog.rs | 204 +++++-- crates/ui-egui/src/plugins.rs | 4 +- crates/ui-egui/src/prefs.rs | 16 +- crates/ui-egui/src/space_mouse_calibration.rs | 23 +- crates/ui-egui/src/theme.rs | 6 + crates/ui-egui/src/theme_files.rs | 4 +- crates/ui-egui/src/timeline_left.rs | 14 +- crates/ui-egui/src/toolbar.rs | 33 +- crates/ui-egui/src/toolbar_custom.rs | 6 + crates/ui-egui/src/ui_kit/actions.rs | 135 ++++- crates/ui-egui/src/ui_kit/checks.rs | 79 +++ crates/ui-egui/src/ui_kit/checks_tests.rs | 445 ++++++++++++++ crates/ui-egui/src/ui_kit/choice.rs | 200 ++++--- crates/ui-egui/src/ui_kit/color.rs | 216 +++++++ crates/ui-egui/src/ui_kit/color_tests.rs | 223 +++++++ crates/ui-egui/src/ui_kit/disclosure.rs | 36 ++ crates/ui-egui/src/ui_kit/disclosure_tests.rs | 98 ++++ crates/ui-egui/src/ui_kit/fields.rs | 254 +++++--- crates/ui-egui/src/ui_kit/fields_tests.rs | 45 ++ crates/ui-egui/src/ui_kit/gallery.rs | 265 ++++++++- crates/ui-egui/src/ui_kit/layout.rs | 152 ++++- crates/ui-egui/src/ui_kit/layout_tests.rs | 2 +- crates/ui-egui/src/ui_kit/metrics.rs | 26 +- crates/ui-egui/src/ui_kit/mod.rs | 12 +- crates/ui-egui/src/ui_kit/panel.rs | 62 +- crates/ui-egui/src/ui_kit/panel_tests.rs | 2 +- crates/ui-egui/src/ui_kit/reports.rs | 126 ++++ crates/ui-egui/src/ui_kit/reports_tests.rs | 51 ++ crates/ui-egui/src/ui_kit/slider_tests.rs | 132 +++++ crates/ui-egui/src/ui_kit/status.rs | 8 +- crates/ui-egui/src/ui_kit/table.rs | 308 ++++++++-- crates/ui-egui/src/ui_kit/table_tests.rs | 306 ++++++++++ crates/ui-egui/src/ui_kit/text.rs | 4 +- crates/ui-egui/src/ui_kit_guard_tests.rs | 546 +++++++++++++++++- crates/ui-egui/src/viewport.rs | 10 +- crates/ui-egui/src/workspace.rs | 7 +- crates/ui-egui/tests/disclosure_render.rs | 63 ++ crates/ui-egui/tests/parameter_enter.rs | 19 +- crates/ui-egui/tests/popup_owner_capture.rs | 178 ++++++ crates/ui-egui/tests/popup_regressions.rs | 148 +++++ .../tests/scenarios/s23_configurations.json | 7 +- .../scenarios/s60_appearance_overrides.json | 2 + crates/ui-egui/tests/support/raster.rs | 103 ++++ docs/ui-kit.md | 166 +++++- 73 files changed, 5428 insertions(+), 923 deletions(-) create mode 100644 assets/icons/ui/design/svg/flat/export_tray.svg create mode 100644 assets/icons/ui/design/svg/flat/import_tray.svg create mode 100644 crates/ui-egui/src/ui_kit/checks.rs create mode 100644 crates/ui-egui/src/ui_kit/checks_tests.rs create mode 100644 crates/ui-egui/src/ui_kit/color.rs create mode 100644 crates/ui-egui/src/ui_kit/color_tests.rs create mode 100644 crates/ui-egui/src/ui_kit/disclosure.rs create mode 100644 crates/ui-egui/src/ui_kit/disclosure_tests.rs create mode 100644 crates/ui-egui/src/ui_kit/reports.rs create mode 100644 crates/ui-egui/src/ui_kit/reports_tests.rs create mode 100644 crates/ui-egui/src/ui_kit/slider_tests.rs create mode 100644 crates/ui-egui/src/ui_kit/table_tests.rs create mode 100644 crates/ui-egui/tests/disclosure_render.rs create mode 100644 crates/ui-egui/tests/popup_owner_capture.rs create mode 100644 crates/ui-egui/tests/popup_regressions.rs create mode 100644 crates/ui-egui/tests/support/raster.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index c4afb4b30..7c58ea581 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -294,6 +294,8 @@ Editable drawing code, native projects and shipped exports are collected under ` | assets/icons/ui/design/svg/flat/agent_link.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/offset_two_sides.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/offset_symmetric.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/import_tray.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | +| assets/icons/ui/design/svg/flat/export_tray.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/placeholder.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/plane.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | | assets/icons/ui/design/svg/model/plane_angle.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 | diff --git a/assets/icons/ui/design/requested_icons.txt b/assets/icons/ui/design/requested_icons.txt index 57761b34e..b50b03259 100644 --- a/assets/icons/ui/design/requested_icons.txt +++ b/assets/icons/ui/design/requested_icons.txt @@ -80,8 +80,6 @@ decal false delete false delete_face false dimension false -disclosure_closed false -disclosure_open false draft false draft_analysis false drive false @@ -93,6 +91,7 @@ environment_map false error false explode false export false +export_tray false extend false extrude false eye false @@ -113,6 +112,7 @@ hem false hole false home false import false +import_tray false include false infinite false inspect false diff --git a/assets/icons/ui/design/svg/flat/export_tray.svg b/assets/icons/ui/design/svg/flat/export_tray.svg new file mode 100644 index 000000000..f37257fc5 --- /dev/null +++ b/assets/icons/ui/design/svg/flat/export_tray.svg @@ -0,0 +1,4 @@ + + Export Tray + + diff --git a/assets/icons/ui/design/svg/flat/import_tray.svg b/assets/icons/ui/design/svg/flat/import_tray.svg new file mode 100644 index 000000000..474cab3ff --- /dev/null +++ b/assets/icons/ui/design/svg/flat/import_tray.svg @@ -0,0 +1,4 @@ + + Import Tray + + diff --git a/assets/icons/ui/source/glyphs.rs b/assets/icons/ui/source/glyphs.rs index 6650a38c0..e2dda8574 100644 --- a/assets/icons/ui/source/glyphs.rs +++ b/assets/icons/ui/source/glyphs.rs @@ -154,12 +154,3 @@ pub(crate) fn radial_centre(p: &egui::Painter, c: Pos2, direction: Option<(egui: p.circle_filled(c, 3.0, t.text_dim); } } - -pub(crate) fn disclosure(p: &egui::Painter, ar: Rect, open: bool, ink: Color32) { - let pts = if open { - vec![pos2(ar.left() + 2.0, ar.top() + 4.0), pos2(ar.right() - 2.0, ar.top() + 4.0), pos2(ar.center().x, ar.bottom() - 3.0)] - } else { - vec![pos2(ar.left() + 4.0, ar.top() + 2.0), pos2(ar.right() - 3.0, ar.center().y), pos2(ar.left() + 4.0, ar.bottom() - 2.0)] - }; - p.add(egui::Shape::convex_polygon(pts, ink, Stroke::NONE)); -} diff --git a/assets/locales/en.json b/assets/locales/en.json index 03d07f885..a10c00206 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -760,6 +760,13 @@ "cmd.view_navigate": "Navigate View", "cmd.view_rename": "Rename Named View", "cmd.view_save": "New Named View", + "color.copy": "Click to copy color values", + "color.edit": "Click to edit color", + "color.gamma": "Showing color values in 0-255 gamma space", + "color.hue": "Hue", + "color.linear": "Showing color values in 0-1 linear space", + "color.saturation_value": "Saturation and value", + "color.selected": "Selected color", "contact.components_count": "{count} components", "contact.enabled_label": "enabled", "coupling.gear_1": "Gear 1", @@ -1066,6 +1073,8 @@ "ui.3d_sketch": "3D Sketch", "ui.activate": "Activate", "ui.active_component": "Active component", + "ui.add_configuration": "Add configuration", + "ui.add_parameter": "Add parameter", "ui.agent_chat": "Agent chat", "ui.agent_chat_add": "Attach files", "ui.agent_chat_add_file": "Choose a file…", @@ -1421,6 +1430,7 @@ "ui.frame_rate": "Frame rate", "ui.front": "Front", "ui.fully_constrained": "Fully constrained", + "ui.function": "Function", "ui.general": "General", "ui.graphics": "Graphics", "ui.graphics_custom": "Custom", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index e063b9cf0..28ee085e1 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -760,6 +760,13 @@ "cmd.view_navigate": "ビューナビゲーション", "cmd.view_rename": "名前付きビューの名前を変更", "cmd.view_save": "新規名前付きビュー", + "color.copy": "クリックして色の値をコピー", + "color.edit": "クリックして色を編集", + "color.gamma": "0〜255のガンマ空間で色の値を表示", + "color.hue": "色相", + "color.linear": "0〜1の線形空間で色の値を表示", + "color.saturation_value": "彩度と明度", + "color.selected": "選択した色", "contact.components_count": "{count}個のコンポーネント", "contact.enabled_label": "有効", "coupling.gear_1": "ギア 1", @@ -1066,6 +1073,8 @@ "ui.3d_sketch": "3D スケッチ", "ui.activate": "アクティブ化", "ui.active_component": "アクティブなコンポーネント", + "ui.add_configuration": "構成を追加", + "ui.add_parameter": "パラメーターを追加", "ui.agent_chat": "エージェントチャット", "ui.agent_chat_add": "ファイルを添付", "ui.agent_chat_add_file": "ファイルを選択…", @@ -1421,6 +1430,7 @@ "ui.frame_rate": "フレームレート", "ui.front": "正面", "ui.fully_constrained": "完全拘束", + "ui.function": "関数", "ui.general": "一般", "ui.graphics": "グラフィックス", "ui.graphics_custom": "カスタム", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index 95c61608d..ba2be6adc 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -760,6 +760,13 @@ "cmd.view_navigate": "导航视图", "cmd.view_rename": "重命名命名视图", "cmd.view_save": "新建命名视图", + "color.copy": "单击复制颜色值", + "color.edit": "单击编辑颜色", + "color.gamma": "以 0–255 伽马空间显示颜色值", + "color.hue": "色相", + "color.linear": "以 0–1 线性空间显示颜色值", + "color.saturation_value": "饱和度和明度", + "color.selected": "所选颜色", "contact.components_count": "{count} 个组件", "contact.enabled_label": "已启用", "coupling.gear_1": "齿轮 1", @@ -1066,6 +1073,8 @@ "ui.3d_sketch": "3D 草图", "ui.activate": "激活", "ui.active_component": "活动组件", + "ui.add_configuration": "添加配置", + "ui.add_parameter": "添加参数", "ui.agent_chat": "智能体聊天", "ui.agent_chat_add": "附加文件", "ui.agent_chat_add_file": "选择文件…", @@ -1421,6 +1430,7 @@ "ui.frame_rate": "帧率", "ui.front": "前视", "ui.fully_constrained": "完全约束", + "ui.function": "函数", "ui.general": "常规", "ui.graphics": "图形", "ui.graphics_custom": "自定义", diff --git a/assets/styles/ui/palettes.rs b/assets/styles/ui/palettes.rs index edcdf1272..1a6b86eb3 100644 --- a/assets/styles/ui/palettes.rs +++ b/assets/styles/ui/palettes.rs @@ -38,20 +38,25 @@ impl Tokens { font_article_heading: 17.0, font_title: 22.0, font_display: 26.0, - control_height: 24.0, - control_radius: 5, + control_height: 28.0, + form_ink: Color32::from_rgb(27, 36, 48), + form_dim: Color32::from_rgb(74, 88, 104), + form_primary: Color32::from_rgb(35, 110, 173), + form_error: Color32::from_rgb(161, 52, 44), + form_error_fill: Color32::from_rgb(252, 239, 237), + control_radius: 6, form_label_width: 70.0, form_gap_y: 5.0, - form_footer_height: 38.0, - form_header_height: 30.0, + form_footer_height: 48.0, + form_header_height: 40.0, form_card_width: 264.0, - form_icon_size: 18.0, - form_close_size: 22.0, - form_inset: 7.0, + form_icon_size: 19.0, + form_close_size: 26.0, + form_inset: 9.0, form_icon_inset: 4.5, form_section_icon_size: 11.0, form_checkbox_height: 22.0, - form_button_height: 26.0, + form_button_height: 28.0, sketch_palette_width: 232.0, sketch_mode_size: 36.0, sketch_mode_radius: 7, @@ -130,7 +135,7 @@ impl Tokens { sketch_point_free: Color32::from_rgb(30, 90, 200), section_cap: Color32::from_rgb(214, 128, 72), dialog_bg: Color32::from_rgb(250, 251, 252), - dialog_border: Color32::from_rgb(208, 212, 220), + dialog_border: Color32::from_rgb(213, 219, 227), chip: Color32::from_rgb(38, 120, 218), heading_bg: Color32::from_rgb(218, 223, 231), subheading_bg: Color32::from_rgb(234, 237, 242), @@ -147,13 +152,13 @@ impl Tokens { app_bar_hover_strong: Color32::from_rgba_unmultiplied_const(255, 255, 255, 40), app_bar_tab_active: Color32::from_rgb(53, 59, 71), dialog_body: Color32::from_rgb(255, 255, 255), - dialog_footer: Color32::from_rgb(246, 248, 250), + dialog_footer: Color32::from_rgb(244, 246, 249), dialog_rule: Color32::from_rgb(230, 234, 240), control_fill: Color32::from_rgb(255, 255, 255), control_border: Color32::from_rgb(195, 203, 214), dialog_label: Color32::from_rgb(58, 70, 86), selected_ink: Color32::from_rgb(26, 80, 127), - selected_bg: Color32::from_rgb(227, 240, 251), + selected_bg: Color32::from_rgb(232, 241, 250), timeline_item: Color32::WHITE, timeline_item_error: Color32::from_rgb(250, 220, 220), timeline_marker: Color32::from_rgb(70, 76, 88), @@ -215,20 +220,20 @@ impl Tokens { t.font_article_heading = 17.0; t.font_title = 22.0; t.font_display = 26.0; - t.control_height = 24.0; - t.control_radius = 5; + t.control_height = 28.0; + t.control_radius = 6; t.form_label_width = 70.0; t.form_gap_y = 5.0; - t.form_footer_height = 38.0; - t.form_header_height = 30.0; + t.form_footer_height = 48.0; + t.form_header_height = 40.0; t.form_card_width = 264.0; - t.form_icon_size = 18.0; - t.form_close_size = 22.0; - t.form_inset = 7.0; + t.form_icon_size = 19.0; + t.form_close_size = 26.0; + t.form_inset = 9.0; t.form_icon_inset = 4.5; t.form_section_icon_size = 11.0; t.form_checkbox_height = 22.0; - t.form_button_height = 26.0; + t.form_button_height = 28.0; t.sketch_palette_width = 232.0; t.sketch_mode_size = 36.0; t.sketch_mode_radius = 7; @@ -300,6 +305,11 @@ impl Tokens { t.box_crossing = Color32::from_rgb(80, 200, 120); t.bend_up = Color32::from_rgb(110, 200, 120); t.bend_down = Color32::from_rgb(240, 150, 80); + t.form_ink = t.text; + t.form_dim = t.text_dim; + t.form_primary = t.accent; + t.form_error = t.error; + t.form_error_fill = t.timeline_item_error; t } diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 4b9c7ef9d..0b108f177 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -361,7 +361,7 @@ fn glyph_button(ui: &mut egui::Ui, kind: &str, tip: &str) -> egui::Response { let p = ui.painter(); match kind { "minimize" => { - p.line_segment([c + vec2(-5.0, 4.0), c + vec2(5.0, 4.0)], s); + ui_kit::disclosure(p, c, true, t.text); } "close" => { p.line_segment([c + vec2(-4.5, -4.5), c + vec2(4.5, 4.5)], s); @@ -417,7 +417,7 @@ fn strip(app: &mut SolveApp, ui: &mut egui::Ui) { if resp.hovered() { ui.painter().rect_filled(button, 4.0, t.hover); } - crate::icons::paint(ui.painter(), button.shrink(4.0), "agent_chat", t.icon, t.icon_fill, t.accent); + ui_kit::disclosure(ui.painter(), button.center(), false, t.text); let state = app.agent_chat.state(); ui.painter().circle_filled(pos2(r.center().x, button.bottom() + 10.0), 3.5, state_color(state)); let waiting = app.agent_chat.waiting(); @@ -1362,6 +1362,10 @@ fn tool_card(ui: &mut egui::Ui, n: usize, title: &str, kind: &str, status: Optio let id = ui.make_persistent_id(("sc_agent_tool", n)); let mut state_ = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, false); let head = ui.horizontal(|ui| { + if output.is_some() { + let (rect, _) = ui.allocate_exact_size(vec2(t.form_section_icon_size, t.form_section_icon_size), Sense::hover()); + ui_kit::disclosure(ui.painter(), rect.center(), state_.is_open(), t.text_dim); + } status_dot(ui, color, filled); // The state and kind keep their room at the right; the title is cut short before them. ui.with_layout(Layout::right_to_left(Align::Center), |ui| { diff --git a/crates/ui-egui/src/agent_cursor.rs b/crates/ui-egui/src/agent_cursor.rs index 11f08fd35..3e929fa2c 100644 --- a/crates/ui-egui/src/agent_cursor.rs +++ b/crates/ui-egui/src/agent_cursor.rs @@ -101,9 +101,16 @@ pub fn speed_slider(ui: &mut egui::Ui, speed: &mut Speed) -> egui::Response { Speed::Times(x) => x.clamp(1.0, 5.0), Speed::Instant => 5.5, }; - let r = crate::ui_kit::formatted_slider(ui, &mut v, 1.0..=5.5, 0.5, |v| { - if v > 5.25 { crate::i18n::tr_label("Instant").into() } else { Speed::Times(v).label() } - }); + let r = crate::ui_kit::slider( + ui, + &mut v, + 1.0..=5.5, + crate::ui_kit::Slider { + step: Some(0.5), + format: |v| if v > 5.25 { crate::i18n::tr_label("Instant").into() } else { Speed::Times(v).label() }, + ..Default::default() + }, + ); if r.changed() { *speed = if v > 5.25 { Speed::Instant } else { Speed::Times(v) }; } diff --git a/crates/ui-egui/src/bom_panel.rs b/crates/ui-egui/src/bom_panel.rs index 6694eef3a..d57c05522 100644 --- a/crates/ui-egui/src/bom_panel.rs +++ b/crates/ui-egui/src/bom_panel.rs @@ -91,15 +91,24 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let (mut export, mut apply_row) = (None, None); let title = RichText::new(crate::i18n::tr_label("Bill of Materials")).strong().size(t.font_button); crate::frame::window(ctx, title, crate::frame::Width::Wide).id(egui::Id::new("sc_bom")).open(&mut open).resizable(true).show(ctx, |ui| { - ui.horizontal(|ui| { + ui.horizontal_wrapped(|ui| { let was = (d.top, d.by_definition, d.group_children); - ui.selectable_value(&mut d.top, false, "Parts only"); - ui.selectable_value(&mut d.top, true, "Top level"); + let mut levels = usize::from(d.top); + let levels_width = crate::ui_kit::ContentWidth::button(ui, "Parts only").max(crate::ui_kit::ContentWidth::button(ui, "Top level")) * 2.0; + ui.allocate_ui(egui::vec2(levels_width, crate::ui_kit::row_height()), |ui| { + crate::ui_kit::segmented(ui, &mut levels, &["Parts only", "Top level"], Default::default()); + }); + d.top = levels == 1; ui.separator(); - ui.selectable_value(&mut d.by_definition, false, "By part number"); - ui.selectable_value(&mut d.by_definition, true, "By definition"); + let mut grouping = usize::from(d.by_definition); + let grouping_width = + crate::ui_kit::ContentWidth::button(ui, "By part number").max(crate::ui_kit::ContentWidth::button(ui, "By definition")) * 2.0; + ui.allocate_ui(egui::vec2(grouping_width, crate::ui_kit::row_height()), |ui| { + crate::ui_kit::segmented(ui, &mut grouping, &["By part number", "By definition"], Default::default()); + }); + d.by_definition = grouping == 1; ui.separator(); - ui.checkbox(&mut d.group_children, "Sub-parts in their part's row"); + crate::ui_kit::checkbox(ui, "Sub-parts in their part's row", &mut d.group_children); if was != (d.top, d.by_definition, d.group_children) { d.picked = None; } @@ -113,7 +122,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui.end_row(); for (i, row) in rows.iter().enumerate() { let picked = d.picked == Some(i); - if ui.selectable_label(picked, text(row, "item")).clicked() { + if crate::ui_kit::list_picker(ui, &i.to_string(), &text(row, "item"), picked).clicked() { d.picked = if picked { None } else { Some(i) }; d.fields = [text(row, "part_number"), text(row, "description"), text(row, "revision")]; } @@ -141,11 +150,13 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { egui::Grid::new("sc_bom_edit").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { for (label, field) in ["Part number", "Description", "Revision"].into_iter().zip(d.fields.iter_mut()) { ui.label(label); - ui.add(egui::TextEdit::singleline(field).desired_width(280.0)); + ui.allocate_ui(egui::vec2(280.0, crate::ui_kit::row_height()), |ui| { + crate::ui_kit::cell_editor(ui, ui.make_persistent_id(label), field, label, false); + }); ui.end_row(); } }); - if ui.button("Apply").clicked() { + if crate::ui_kit::button(ui, "Apply", crate::ui_kit::Button::Normal).clicked() { apply_row = Some(row.clone()); } } @@ -155,7 +166,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui.separator(); ui.horizontal(|ui| { for (label, ext) in [("Export CSV…", "csv"), ("Export JSON…", "json")] { - if ui.button(label).clicked() { + if crate::ui_kit::button(ui, label, crate::ui_kit::Button::Normal).clicked() { export = Some(ext); } } diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index cc51563fd..2d043d03b 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -6,7 +6,6 @@ //! viewport, a double-click on a sketch edits it, and a right-click opens the item's menu //! ([`crate::context_menu`]). -use crate::fonts::RichTextExt as _; #[cfg(test)] #[path = "occurrence_ui_tests.rs"] mod occurrence_ui_tests; @@ -31,7 +30,7 @@ mod model_tests; use crate::icons::glyphs::badge; use std::collections::BTreeSet; -use egui::{Color32, FontId, Pos2, Rect, RichText, Sense, Stroke, pos2, vec2}; +use egui::{Color32, FontId, Pos2, Rect, Sense, Stroke, pos2, vec2}; use serde_json::{Value, json}; use solidcraft_engine::Sel; use solidcraft_engine::doc::FeatureKind; @@ -394,9 +393,7 @@ pub(crate) fn draw_row(ui: &mut egui::Ui, id: egui::Id, row: &Row) -> RowResp { let hover_on = resp.hover_pos().map_or(0, at); // Fold arrow. if let Some(open) = row.fold { - let ar = Rect::from_center_size(pos2(x + 6.0, cy), vec2(12.0, 12.0)); - let strength = if hover_on == 1 { 1.0 } else { 0.7 }; - icons::paint_icon(ui.painter(), ar, if open { "disclosure_open" } else { "disclosure_closed" }, strength); + crate::ui_kit::disclosure(ui.painter(), pos2(x + 6.0, cy), open, if hover_on == 1 { t.text } else { t.text_dim }); out.fold = resp.clicked() && click_on == 1; crate::scenario::publish_handle(&format!("fold:{}", row.label), fold_r.center()); } @@ -708,9 +705,22 @@ fn browser_panel(app: &mut SolveApp, ui: &mut egui::Ui, timeline_above: bool) { ui.painter().hline(rect.x_range(), rect.center().y, egui::Stroke::new(1.0, t.border)); crate::scenario::publish_handle("left-history-divider", rect.center()); } - let arrow = if browser_collapsed { "▶" } else { "▼" }; - let response = ui - .add(egui::Button::new(RichText::new(format!("{arrow} BROWSER")).size(t.font_small).semibold().color(t.text_dim)).frame(false)); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), crate::ui_kit::row_height()), Sense::click()); + crate::ui_kit::disclosure( + ui.painter(), + pos2(rect.left() + t.form_section_icon_size / 2.0, rect.center().y), + !browser_collapsed, + t.text_dim, + ); + ui.painter().text( + pos2(rect.left() + t.form_section_icon_size + t.space_8, rect.center().y), + egui::Align2::LEFT_CENTER, + "BROWSER", + crate::fonts::semibold(t.font_small), + t.text_dim, + ); + response + .widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, ui.is_enabled(), !browser_collapsed, "BROWSER")); crate::scenario::publish_handle("left-browser-toggle", response.rect.center()); if response.clicked() { app.preferences.timeline_left_browser_collapsed = !browser_collapsed; @@ -823,12 +833,7 @@ fn browser_header(app: &mut SolveApp, ui: &mut egui::Ui, collapsible: bool) { ui.painter().galley(pos2(rect.left() + t.space_6, rect.center().y - galley.size().y / 2.0), galley, t.text); let mut right = rect.right() - t.space_6; if collapsible { - let chevron = Rect::from_center_size(pos2(right - 5.0, rect.center().y), vec2(12.0, 12.0)); - if collapsed { - crate::icons::paint_ink(ui.painter(), chevron, "chevron", t.text_dim); - } else { - crate::icons::paint_ink_flipped(ui.painter(), chevron, "chevron", t.text_dim); - } + crate::ui_kit::disclosure(ui.painter(), pos2(right - t.form_section_icon_size / 2.0, rect.center().y), !collapsed, t.text_dim); right -= 18.0; } let bodies = app.session.model.state().bodies.len(); diff --git a/crates/ui-egui/src/browser_canvas.rs b/crates/ui-egui/src/browser_canvas.rs index 5894db17f..13407e5cc 100644 --- a/crates/ui-egui/src/browser_canvas.rs +++ b/crates/ui-egui/src/browser_canvas.rs @@ -44,7 +44,8 @@ pub(crate) fn panel(app: &mut SolveApp, ctx: &egui::Context) { changed |= ui_kit::row(ui, crate::i18n::tr_label("Center Y"), |ui| ui_kit::length_field(ui, &mut y, &units, decimals)).changed(); changed |= ui_kit::row(ui, crate::i18n::tr_label("Width"), |ui| ui_kit::length_field(ui, &mut w, &units, decimals)).changed(); changed |= ui_kit::row(ui, crate::i18n::tr_label("Angle"), |ui| ui_kit::angle_field(ui, &mut ang)).changed(); - changed |= ui_kit::row(ui, crate::i18n::tr_label("Opacity"), |ui| ui_kit::slider(ui, &mut op, 0.0..=1.0)).changed(); + changed |= + ui_kit::row(ui, crate::i18n::tr_label("Opacity"), |ui| ui_kit::slider(ui, &mut op, 0.0..=1.0, Default::default())).changed(); if ui_kit::checkbox_row(ui, "flip", crate::i18n::tr_label("Flip"), flip) { flip = !flip; changed = true; diff --git a/crates/ui-egui/src/colour_vision_tests.rs b/crates/ui-egui/src/colour_vision_tests.rs index 0a01ec3e2..69d7512ac 100644 --- a/crates/ui-egui/src/colour_vision_tests.rs +++ b/crates/ui-egui/src/colour_vision_tests.rs @@ -278,6 +278,10 @@ fn groups(t: &Tokens) -> Vec { &[("timeline_item", t.timeline_item), ("timeline_item_error", t.timeline_item_error), ("hover", t.hover), ("accent_soft", t.accent_soft)], &[], ), + group("card text", &[("form_ink", t.form_ink), ("form_error", t.form_error)], &[("dialog_body", t.dialog_body)]), + group("card hints", &[("form_dim", t.form_dim)], &[("dialog_body", t.dialog_body)]), + group("card primary", &[("form_primary", t.form_primary)], &[("dialog_body", t.dialog_body)]), + group("card validation", &[("form_error", t.form_error)], &[("form_error_fill", t.form_error_fill)]), group("UI text", &[("error", t.error), ("warning", t.warning), ("text", t.text)], &[("panel", t.panel)]), group("origin axes", &[("axis_x", t.axis_x), ("axis_y", t.axis_y), ("axis_z", t.axis_z)], &[("viewport_top", t.viewport_top)]), group("view triad", &[("triad[0]", t.triad[0]), ("triad[1]", t.triad[1]), ("triad[2]", t.triad[2])], &[("viewport_top", t.viewport_top)]), @@ -433,7 +437,6 @@ const NO_MEANING: &[(&str, &str)] = &[ ("app_bar_hover_button", "translucent hover chrome"), ("app_bar_hover_strong", "translucent hover chrome"), ("app_bar_tab_active", "the active document tab's surface"), - ("dialog_body", "dense dialog surface"), ("dialog_footer", "dense dialog footer band"), ("dialog_rule", "dense dialog divider"), ("control_fill", "input control fill"), diff --git a/crates/ui-egui/src/configuration_rules_ui.rs b/crates/ui-egui/src/configuration_rules_ui.rs index 6e162ed59..4f5089108 100644 --- a/crates/ui-egui/src/configuration_rules_ui.rs +++ b/crates/ui-egui/src/configuration_rules_ui.rs @@ -12,6 +12,9 @@ pub struct Editor { preview: Option, preview_revision: u64, + pub(super) new_values: std::collections::BTreeMap, + pub(super) adding_row: bool, + pub(super) focus_new_row: bool, pub(super) drafts: std::collections::BTreeMap<(String, String), String>, pub(super) table: Option<(u64, Value)>, } @@ -30,6 +33,9 @@ impl Default for Editor { preview: None, preview_revision: 0, + new_values: Default::default(), + adding_row: false, + focus_new_row: false, drafts: Default::default(), table: None, } @@ -74,7 +80,7 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option, let suppression_features: Vec<(u64, String)> = features.iter().filter(|(id, _)| app.session.doc.configs.columns.contains(&Column::Suppress(*id))).cloned().collect(); ui_kit::divider(ui, "configuration_rules"); - ui_kit::text(ui, crate::i18n::tr_label("Configuration rules"), ui_kit::Text::Report("rules_heading", false)); + ui_kit::text(ui, crate::i18n::tr_label("Configuration rules"), ui_kit::Text::Heading("rules_heading")); ui_kit::text( ui, crate::i18n::tr_label("Rules run from top to bottom. Matched drives change effective values."), @@ -83,15 +89,20 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option, ui_kit::text(ui, crate::i18n::tr_label("Matched restrictions check the final values."), ui_kit::Text::Note("rules_restrictions")); for (index, rule) in rules.iter().enumerate() { ui.push_id(&rule.id, |ui| { - ui.horizontal_wrapped(|ui| { - let mut enabled = rule.enabled; - if ui_kit::checkbox(ui, "", &mut enabled).on_hover_text(crate::i18n::tr_label("Enable rule")).changed() { - let mut r = rule.clone(); - r.enabled = enabled; - *error = app.run("config.rule", json!({"rule":r})).err(); - } - ui_kit::text(ui, &rule.name, ui_kit::Text::Inline); - if ui_kit::button(ui, crate::i18n::tr_label("Edit"), ui_kit::Button::Small).clicked() { + let summary = match &rule.effect { + RuleEffect::DriveParameter { parameter, expression } => format!("Drives {parameter} = {expression}"), + RuleEffect::DriveSuppression { feature, value } => format!( + "Drives suppression {} = {value}", + features.iter().find(|f| f.0 == *feature).map(|f| f.1.as_str()).unwrap_or("missing feature") + ), + RuleEffect::ParameterRange { parameter, minimum, maximum } => format!("Restricts {parameter}: {minimum} through {maximum}"), + RuleEffect::AllowParameterValues { parameter, expressions } => format!("Restricts {parameter}: {}", expressions.join(", ")), + }; + let actions_width = ["Edit", "↑", "↓", "Delete"].iter().map(|label| ui_kit::ContentWidth::button(ui, label)).sum::() + + crate::theme::Tokens::get().space_4 * 3.0; + let mut enabled = rule.enabled; + if ui_kit::summary_row(ui, &rule.name, &summary, &mut enabled, actions_width, |ui| { + if ui_kit::button(ui, crate::i18n::tr_label("Edit"), ui_kit::Button::Normal).clicked() { editor.rule = rule.clone(); } let up = ui_kit::button(ui, "↑", ui_kit::Button::Enabled(index > 0)).on_hover_text(crate::i18n::tr_label("Move earlier")); @@ -105,22 +116,14 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option, { *error = app.run("config.rule", json!({"id":rule.id,"index":index+1})).err(); } - if ui_kit::button(ui, crate::i18n::tr_label("Delete"), ui_kit::Button::Small).clicked() { + if ui_kit::button(ui, crate::i18n::tr_label("Delete"), ui_kit::Button::Normal).clicked() { *error = app.run("config.rule", json!({"id":rule.id,"delete":true})).err(); } - }); - report( - ui, - match &rule.effect { - RuleEffect::DriveParameter { parameter, expression } => format!("Drives {parameter} = {expression}"), - RuleEffect::DriveSuppression { feature, value } => format!( - "Drives suppression {} = {value}", - features.iter().find(|f| f.0 == *feature).map(|f| f.1.as_str()).unwrap_or("missing feature") - ), - RuleEffect::ParameterRange { parameter, minimum, maximum } => format!("Restricts {parameter}: {minimum} through {maximum}"), - RuleEffect::AllowParameterValues { parameter, expressions } => format!("Restricts {parameter}: {}", expressions.join(", ")), - }, - ); + }) { + let mut updated = rule.clone(); + updated.enabled = enabled; + *error = app.run("config.rule", json!({"rule":updated})).err(); + } }); } ui_kit::section(ui, "rule_editor", "Add or edit rule", false, |ui| { @@ -210,96 +213,98 @@ pub(super) fn show(ui: &mut Ui, app: &mut SolveApp, error: &mut Option, *error = result.err(); } }); - let rows: Vec = app.session.doc.configs.rows.iter().map(|r| r.name.clone()).collect(); - if !rows.contains(&editor.row) { - editor.row = app.session.doc.configs.active.clone().or_else(|| rows.first().cloned()).unwrap_or_default(); - } - let previous_row = editor.row.clone(); - ui.vertical(|ui| { - choose(ui, "preview_configuration", &mut editor.row, &rows); - let preview = ui_kit::button(ui, "Preview Row", ui_kit::Button::Enabled(!editor.row.is_empty())); - crate::scenario::publish_handle("config:preview_row", preview.rect.center()); - if preview.clicked() { - match app.session.execute("config.preview", &json!({"row":editor.row})) { - Ok(result) => { - editor.preview = Some(result); - editor.preview_revision = app.session.revision; - *error = None; - } - Err(e) => { - editor.preview = None; - *error = Some(e.to_string()); - } - } + ui_kit::section(ui, "preview", "Preview", true, |ui| { + let rows: Vec = app.session.doc.configs.rows.iter().map(|r| r.name.clone()).collect(); + if !rows.contains(&editor.row) { + editor.row = app.session.doc.configs.active.clone().or_else(|| rows.first().cloned()).unwrap_or_default(); } - }); - if previous_row != editor.row { - editor.preview = None; - } - if let Some(preview) = &editor.preview { - ui_kit::section(ui, "rule_preview", &format!("Preview: {}", preview["active"].as_str().unwrap_or("row")), false, |ui| { - report(ui, crate::i18n::tr_label("Preview leaves the current design unchanged.")); - if let Some(styles) = preview["styles"].as_array() { - for style in styles { - report( - ui, - format!( - "{}: {} (shared definition)", - style["target"].as_str().unwrap_or("Appearance"), - if style["dormant"].as_bool() == Some(true) { "dormant" } else { "resolved" } - ), - ); - } - } - if let Some(trace) = preview["trace"].as_array() { - for entry in trace { - report( - ui, - format!( - "{} — {}", - entry["name"].as_str().unwrap_or("rule"), - if entry["matched"].as_bool() == Some(true) { "matched" } else { "skipped" } - ), - ); - if entry["matched"].as_bool() == Some(true) - && let Ok(effect) = serde_json::from_value::(entry["effect"].clone()) - { - report( - ui, - match effect { - RuleEffect::DriveParameter { parameter, expression } => format!("Driven: {parameter} = {expression}"), - RuleEffect::DriveSuppression { feature, value } => format!( - "Driven: {} is {}", - features.iter().find(|f| f.0 == feature).map(|f| f.1.as_str()).unwrap_or("feature"), - if value { "suppressed" } else { "unsuppressed" } - ), - RuleEffect::ParameterRange { parameter, minimum, maximum } => { - format!("Restricted: {parameter}, {minimum} through {maximum}") - } - RuleEffect::AllowParameterValues { parameter, expressions } => { - format!("Restricted: {parameter}, {}", expressions.join("; ")) - } - }, - ); + let previous_row = editor.row.clone(); + ui.vertical(|ui| { + choose(ui, "preview_configuration", &mut editor.row, &rows); + let preview = ui_kit::button(ui, "Preview Row", ui_kit::Button::Enabled(!editor.row.is_empty())); + crate::scenario::publish_handle("config:preview_row", preview.rect.center()); + if preview.clicked() { + match app.session.execute("config.preview", &json!({"row":editor.row})) { + Ok(result) => { + editor.preview = Some(result); + editor.preview_revision = app.session.revision; + *error = None; } - } - } - if let Some(parameters) = preview["parameters"].as_array() { - for parameter in parameters { - if let Some(name) = parameter["name"].as_str() - && all_parameters.iter().any(|p| p == name) - { - let response = ui_kit::text( - ui, - &format!("{name} = {}", parameter["expression"].as_str().unwrap_or("")), - ui_kit::Text::Report("preview_parameter", false), - ); - crate::scenario::publish_handle(&format!("config:preview:param:{name}"), response.rect.center()); + Err(e) => { + editor.preview = None; + *error = Some(e.to_string()); } } } }); - } + if previous_row != editor.row { + editor.preview = None; + } + if let Some(preview) = &editor.preview { + ui_kit::section(ui, "rule_preview", &format!("Preview: {}", preview["active"].as_str().unwrap_or("row")), false, |ui| { + report(ui, crate::i18n::tr_label("Preview leaves the current design unchanged.")); + if let Some(styles) = preview["styles"].as_array() { + for style in styles { + report( + ui, + format!( + "{}: {} (shared definition)", + style["target"].as_str().unwrap_or("Appearance"), + if style["dormant"].as_bool() == Some(true) { "dormant" } else { "resolved" } + ), + ); + } + } + if let Some(trace) = preview["trace"].as_array() { + for entry in trace { + report( + ui, + format!( + "{} — {}", + entry["name"].as_str().unwrap_or("rule"), + if entry["matched"].as_bool() == Some(true) { "matched" } else { "skipped" } + ), + ); + if entry["matched"].as_bool() == Some(true) + && let Ok(effect) = serde_json::from_value::(entry["effect"].clone()) + { + report( + ui, + match effect { + RuleEffect::DriveParameter { parameter, expression } => format!("Driven: {parameter} = {expression}"), + RuleEffect::DriveSuppression { feature, value } => format!( + "Driven: {} is {}", + features.iter().find(|f| f.0 == feature).map(|f| f.1.as_str()).unwrap_or("feature"), + if value { "suppressed" } else { "unsuppressed" } + ), + RuleEffect::ParameterRange { parameter, minimum, maximum } => { + format!("Restricted: {parameter}, {minimum} through {maximum}") + } + RuleEffect::AllowParameterValues { parameter, expressions } => { + format!("Restricted: {parameter}, {}", expressions.join("; ")) + } + }, + ); + } + } + } + if let Some(parameters) = preview["parameters"].as_array() { + for parameter in parameters { + if let Some(name) = parameter["name"].as_str() + && all_parameters.iter().any(|p| p == name) + { + let response = ui_kit::text( + ui, + &format!("{name} = {}", parameter["expression"].as_str().unwrap_or("")), + ui_kit::Text::Report("preview_parameter", false), + ); + crate::scenario::publish_handle(&format!("config:preview:param:{name}"), response.rect.center()); + } + } + } + }); + } + }); } fn report(ui: &mut Ui, text: impl AsRef) { ui_kit::text(ui, crate::i18n::tr_label(text.as_ref()), ui_kit::Text::Report("rule_report", false)); diff --git a/crates/ui-egui/src/configurations_ui.rs b/crates/ui-egui/src/configurations_ui.rs index f9acef24c..28e315f09 100644 --- a/crates/ui-egui/src/configurations_ui.rs +++ b/crates/ui-egui/src/configurations_ui.rs @@ -60,7 +60,7 @@ pub(super) fn configurations_rows( .chain(std::iter::once(crate::i18n::tr_label("Actions").to_owned())) .collect(); let gap = ui.spacing().item_spacing.x; - let name_width = tb.rows.iter().map(|(name, _)| ui_kit::ContentWidth::label(ui, name)).fold(0.0, f32::max); + let name_width = tb.rows.iter().map(|(name, _)| ui_kit::ContentWidth::name(ui, name)).fold(0.0, f32::max); let status_width = (ui_kit::ContentWidth::label(ui, "Active") + gap + ui_kit::ContentWidth::button(ui, "Apply")) .max(ui_kit::ContentWidth::button(ui, "Activate")); let columns: Vec<_> = labels @@ -68,38 +68,47 @@ pub(super) fn configurations_rows( .enumerate() .map(|(index, label)| { let min_width = if index == 0 { - (name_width + gap + status_width).max(ui_kit::ContentWidth::label(ui, "Remove the column")) - } else if index <= tb.columns.len() { - tb.rows - .iter() - .filter_map(|(_, values)| values.get(index - 1)) - .map(|value| ui_kit::ContentWidth::editor(ui, value)) - .fold(ui_kit::ContentWidth::button(ui, "×"), f32::max) + name_width + gap + status_width + crate::theme::Tokens::get().space_24 } else { - ui_kit::ContentWidth::button(ui, "×") + ui_kit::row_height() * 2.0 + crate::theme::Tokens::get().space_24 }; - ui_kit::Column::new(label, 2.0).min_content_width(min_width) + if index == labels.len() - 1 { + ui_kit::Column::new(label, 0.0) + .icon_only() + .min_content_width(crate::theme::Tokens::get().control_height + crate::theme::Tokens::get().space_12) + } else { + let weight = if index == 0 { + 1.6 + } else { + match tb.columns.get(index - 1).map(|column| column_parts(column).0) { + Some("param") => 0.9, + Some("suppress") => 1.1, + Some("material") => 1.2, + _ => 1.3, + } + }; + ui_kit::Column::new(label, weight).flex().min_content_width(min_width) + } }) .collect(); - ui_kit::table(ui, "configuration_table", &columns, crate::i18n::tr("manage.empty"), |ui, table| { - // The column-action band shares the header's exact widths without posing as a data row. - if !tb.columns.is_empty() { - table.column_actions(ui, |row| { - row.cell(|ui| { - ui_kit::text(ui, crate::i18n::tr_label("Remove the column"), ui_kit::Text::Cell); - }); - for c in &tb.columns { - row.cell(|ui| { - let (kind, name) = column_parts(c); - if ui_kit::button(ui, "×", ui_kit::Button::Normal).on_hover_text(crate::i18n::tr_label("Remove the column")).clicked() { - let key = if kind == "suppress" { "feature" } else { kind }; - run(app, error, "config.column", json!({key:if kind == "face_appearance" {c.as_str()} else {name},"delete":true})); - } - }); + ui_kit::table_custom(ui, "configuration_table", &columns, crate::i18n::tr("manage.empty"), |ui, table| { + table.headers(ui, |ui, index| { + if index == labels.len() - 1 { + column_menu(app, ui, error, &tb.columns); + true + } else if index > 0 { + if let (Some(column), Some(label)) = (tb.columns.get(index - 1), labels.get(index)) + && ui_kit::removable_header(ui, label) + { + let (kind, name) = column_parts(column); + let key = if kind == "suppress" { "feature" } else { kind }; + run(app, error, "config.column", json!({key:if kind == "face_appearance" {column.as_str()} else {name},"delete":true})); } - row.cell(|_| {}); - }); - } + true + } else { + false + } + }); for (name, values) in &tb.rows { let active = tb.active.as_deref() == Some(name.as_str()); table.row(ui, name, active, |row| { @@ -109,11 +118,11 @@ pub(super) fn configurations_rows( egui::vec2(name_width, ui_kit::row_height()), egui::Layout::left_to_right(egui::Align::Center), |ui| { - ui_kit::text(ui, name, ui_kit::Text::Cell); + ui_kit::text(ui, name, ui_kit::Text::NameCell(true)); }, ); if active { - ui_kit::text(ui, crate::i18n::tr_label("Active"), ui_kit::Text::Inline); + ui_kit::active_pill(ui); if v.get("matches").and_then(Value::as_bool) == Some(false) { let apply = ui_kit::button(ui, crate::i18n::tr_label("Apply"), ui_kit::Button::Small); crate::scenario::publish_handle(&format!("config:activate:{name}"), apply.rect.center()); @@ -132,51 +141,14 @@ pub(super) fn configurations_rows( for (column, value) in tb.columns.iter().zip(values) { row.cell(|ui| { let (kind, _) = column_parts(column); - let appearance = matches!(kind, "appearance" | "component_appearance" | "face_appearance"); - let shown = if appearance { - solidcraft_engine::doc::config::appearance_cell(value) - .ok() - .flatten() - .filter(|look| solidcraft_engine::doc::appearance::library(&look.name).as_ref() == Some(look)) - .map(|look| look.name) - .unwrap_or_else(|| value.clone()) - } else { - value.clone() - }; - if kind == "material" || appearance { - let mut choice = None; - ui_kit::action_menu(ui, "Library", |ui| { - let follow = if kind == "appearance" { - "Follow material" - } else if appearance { - "Follow inherited appearance" - } else { - "Default material" - }; - if ui_kit::button(ui, crate::i18n::tr_label(follow), ui_kit::Button::Normal).clicked() { - choice = Some("Default".to_owned()); - ui.close(); - } - let choices: Vec<_> = if kind == "material" { - material_names.iter().filter(|n| *n != "Default").map(String::as_str).collect() - } else { - solidcraft_engine::doc::appearance::LIBRARY.iter().map(|(name, _, _)| *name).collect() - }; - for name in choices { - if ui_kit::button(ui, name, ui_kit::Button::Normal).clicked() { - choice = Some(name.to_owned()); - ui.close(); - } - } - }); - if let Some(choice) = choice { - run(app, error, "config.row", json!({"name":name,"values":{column:choice}})); - } - } + let shown = display_cell(kind, value); let key = (name.clone(), column.clone()); let mut text = rule_editor.drafts.get(&key).cloned().unwrap_or_else(|| shown.clone()); let id = ui.make_persistent_id(&key); - let response = ui_kit::cell_editor(ui, id, &mut text, "", false); + let (response, choice) = value_control(ui, id, &mut text, kind, &material_names); + if let Some(choice) = choice { + run(app, error, "config.row", json!({"name":name,"values":{column:choice}})); + } crate::scenario::publish_handle(&format!("config:cell:{name}:{column}"), response.rect.center()); let focused = response.has_focus(); let completed = crate::params_dialog::complete(ui, &response, &mut text); @@ -193,148 +165,98 @@ pub(super) fn configurations_rows( }); } row.cell(|ui| { - if ui_kit::button(ui, "×", ui_kit::Button::Small).on_hover_text(crate::i18n::tr_label("Delete the row")).clicked() { + if ui_kit::bin_button(ui, "Delete the row").clicked() { run(app, error, "config.row", json!({"name":name,"delete":true})); } }); }); } - }); - // New row (a copy of the active one) and new column. - ui_kit::row(ui, "Configuration", |ui| { - let id = ui.make_persistent_id("new_configuration"); - ui_kit::cell_editor(ui, id, new_row, "new configuration", false); - }); - ui.horizontal_wrapped(|ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); - - if ui_kit::button(ui, crate::i18n::tr_label("Add Row"), ui_kit::Button::Normal) - .on_hover_text(crate::i18n::tr_label("A new configuration, a copy of the active one")) - .clicked() - { - let name = if new_row.trim().is_empty() { - (tb.rows.len() + 1..).map(|k| format!("Configuration{k}")).find(|n| !tb.rows.iter().any(|r| &r.0 == n)).unwrap_or_default() - } else { - new_row.trim().to_string() - }; - let mut p = json!({ "name": name }); - if let Some(a) = &tb.active { - p["from"] = json!(a); - } - run(app, error, "config.row", p); - new_row.clear(); - } - // A column: a parameter's value or a feature's suppression. - let mut options: Vec<(String, Value)> = Vec::new(); - for p in app.session.doc.all_param_exprs() { - if !tb.columns.contains(&format!("param:{}", p.0)) { - options.push((format!("{} (parameter)", p.0), json!({ "param": p.0 }))); - } - } - for f in &app.session.doc.features { - if !tb.columns.contains(&format!("suppress:{}", f.name)) { - options.push((format!("Suppress {}", f.name), json!({ "feature": f.name }))); - } - } - for body in &app.session.model.state().bodies { - for kind in ["material", "appearance"] { - if !tb.columns.contains(&format!("{kind}:{}", body.name)) { - options.push((format!("{} ({kind})", body.name), json!({kind: body.name}))); - } - } - } - for component in &app.session.doc.components { - if component.id != 0 && !tb.columns.contains(&format!("component_appearance:{}", component.id)) { - options.push((format!("{} (component appearance)", component.name), json!({"component_appearance":component.id}))); - } - } - for selected in &app.session.selection { - if let solidcraft_engine::Sel::Face { body, point, .. } = selected { - options.push((format!("Selected face on {body} (shared appearance)"), json!({"face_appearance":{"body":body,"point":point}}))); - } - } - let mut pick: Option = None; - ui_kit::action_menu(ui, "Add Column", |ui| { - egui::ScrollArea::vertical().max_height(ui_kit::row_height() * 12.0).show(ui, |ui| { - for (label, p) in &options { - if ui_kit::button(ui, label.as_str(), ui_kit::Button::Normal).clicked() { - pick = Some(p.clone()); - ui.close(); - } - } - ui_kit::action_menu(ui, "Face Appearance", |ui| { - ui_kit::text( - ui, - crate::i18n::tr_label("Semantic faces share their appearance across instances."), - ui_kit::Text::Note("semantic_faces"), - ); - let state = app.session.model.state(); - for body in &state.bodies { - if body.body.is_mesh() { - continue; - } - ui_kit::action_menu(ui, &format!("Faces on {}", body.name), |ui| { - if let Ok(faces) = body.body.faces((body.body.size() * 2e-3).max(1e-3)) { - let mut seen = std::collections::BTreeSet::new(); - let mesh = body.mesh(); - let mut points = std::collections::BTreeMap::new(); - for (triangle, index) in mesh.triangles.iter().zip(&mesh.tri_face) { - if let std::collections::btree_map::Entry::Vacant(entry) = points.entry(*index as usize) - && let Some([a, b, c]) = mesh.tri(triangle) - { - entry.insert((a + b + c) * (1. / 3.)); - } - } - for face in faces { - // A curved face centroid can lie on another surface. - // Pick an interior triangle point on this actual face. - let Some(point) = points.get(&face.index).copied() else { continue }; - let Ok(target) = app.session.doc.configuration_face_target(body, face.index, point) else { continue }; - let supported = if target.certificate.is_some() { - // Capture read this exact face's current source certificate. - // Enumerate its pieces once in the command, not per menu face. - app.session.doc.certify_config_face(&target).is_ok() - } else { - app.session.doc.configuration_face_indices(body, &target).is_ok() - }; - if !supported || !seen.insert(target.name.clone()) { - continue; - } - let Some((_, role)) = target.name.split_once(':') else { continue }; - if ui_kit::button(ui, role, ui_kit::Button::Normal).clicked() { - pick = Some(json!({"face_appearance":{"target":target}})); - ui.close(); - } - } + if rule_editor.adding_row { + let menu_was_open = egui::Popup::is_any_open(ui.ctx()); + let mut commit = false; + let mut discard = false; + let mut left = false; + let reveal = rule_editor.focus_new_row; + let response = ui + .push_id("configuration_draft", |ui| { + table.row(ui, "new", false, |row| { + row.cell(|ui| { + let id = ui.make_persistent_id("new_configuration"); + let focused = ui.memory(|m| m.has_focus(id) || m.had_focus_last_frame(id)); + let response = ui_kit::cell_editor(ui, id, new_row, "new configuration", false); + crate::scenario::publish_handle("config:new:name", response.rect.center()); + if rule_editor.focus_new_row { + response.request_focus(); + rule_editor.focus_new_row = false; } + commit = focused && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); + left = response.lost_focus(); }); - } - }); - }); - }); - if let Some(p) = pick { - // The first column starts the table (with a Default row of the current values). - let (id, p) = if tb.columns.is_empty() { - ( - "config.configure", - if let Some(n) = p.get("param") { - json!({ "params": [n] }) - } else if let Some(n) = p.get("feature") { - json!({ "features": [n] }) - } else if let Some(n) = p.get("material") { - json!({ "materials": [n] }) - } else if let Some(n) = p.get("component_appearance") { - json!({ "component_appearances": [n] }) - } else if let Some(n) = p.get("face_appearance") { - json!({ "face_appearances": [n] }) - } else { - json!({ "appearances": [p.get("appearance")] }) - }, - ) - } else { - ("config.column", p) - }; - run(app, error, id, p); + let source = tb.rows.iter().find(|(name, _)| tb.active.as_ref() == Some(name)); + for (index, column) in tb.columns.iter().enumerate() { + row.cell(|ui| { + let mut value = rule_editor.new_values.get(column).cloned().unwrap_or_else(|| { + source + .and_then(|(_, values)| values.get(index)) + .map(|value| display_cell(column_parts(column).0, value)) + .unwrap_or_default() + }); + let (kind, _) = column_parts(column); + let (response, choice) = value_control(ui, ui.id().with(column), &mut value, kind, &material_names); + let picked = choice.is_some(); + if let Some(choice) = choice { + value = choice; + } + crate::scenario::publish_handle(&format!("config:new:cell:{column}"), response.rect.center()); + let completed = crate::params_dialog::complete(ui, &response, &mut value); + if response.changed() || completed || picked { + rule_editor.new_values.insert(column.clone(), value); + } + let focused = response.has_focus() || response.lost_focus(); + left |= response.lost_focus(); + commit |= !completed && focused && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); + }); + } + row.cell(|ui| { + discard = ui_kit::bin_button(ui, "Delete the row").clicked(); + }); + }) + }) + .inner; + if reveal { + table.reveal_row(response.rect); + } + let abandoned = new_row.trim().is_empty() + && !menu_was_open + && ui.input(|i| i.pointer.any_click() && i.pointer.interact_pos().is_some_and(|p| !response.rect.contains(p))); + if discard || abandoned { + rule_editor.adding_row = false; + new_row.clear(); + rule_editor.new_values.clear(); + } else if commit || (left && !new_row.trim().is_empty()) { + let name = if new_row.trim().is_empty() { + (tb.rows.len() + 1..).map(|k| format!("Configuration{k}")).find(|n| !tb.rows.iter().any(|r| &r.0 == n)).unwrap_or_default() + } else { + new_row.trim().to_string() + }; + let values: serde_json::Map = + rule_editor.new_values.iter().map(|(col, text)| (col.clone(), cell_value(col, text))).collect(); + let mut params = json!({"name":name}); + if !values.is_empty() { + params["values"] = Value::Object(values); + } + if let Some(active) = &tb.active { + params["from"] = json!(active); + } + run(app, error, "config.row", params); + new_row.clear(); + rule_editor.adding_row = false; + rule_editor.new_values.clear(); + } + } + if table.add_prompt(ui, "Add configuration", "A new configuration, a copy of the active one").clicked() { + rule_editor.adding_row = true; + rule_editor.focus_new_row = true; } }); configuration_rules_ui::show(ui, app, error, rule_editor); @@ -348,12 +270,180 @@ pub(super) fn configurations_rows( } } if let Some(message) = v["style_error"].as_str() { - ui_kit::text(ui, message, ui_kit::Text::Report("style_error", true)); + ui_kit::text(ui, message, ui_kit::Text::Error("style_error")); } if let Some(message) = error { - ui_kit::text(ui, message, ui_kit::Text::Report("config_error", true)); + ui_kit::text(ui, message, ui_kit::Text::Error("config_error")); } // Table cells and rule editors own Enter. As in the legacy wide manager, it // commits an edited cell without also submitting the enclosing card. ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); } + +fn column_menu(app: &mut SolveApp, ui: &mut egui::Ui, error: &mut Option, columns: &[String]) { + let run = |app: &mut SolveApp, error: &mut Option, id: &str, params: Value| { + *error = app.run(id, params).err(); + }; + // A column: a parameter's value or a feature's suppression. + let mut options: Vec<(String, Value)> = Vec::new(); + for p in app.session.doc.all_param_exprs() { + if !columns.contains(&format!("param:{}", p.0)) { + options.push((format!("{} (parameter)", p.0), json!({ "param": p.0 }))); + } + } + for f in &app.session.doc.features { + if !columns.contains(&format!("suppress:{}", f.name)) { + options.push((format!("Suppress {}", f.name), json!({ "feature": f.name }))); + } + } + for body in &app.session.model.state().bodies { + for kind in ["material", "appearance"] { + if !columns.contains(&format!("{kind}:{}", body.name)) { + options.push((format!("{} ({kind})", body.name), json!({kind: body.name}))); + } + } + } + for component in &app.session.doc.components { + if component.id != 0 && !columns.contains(&format!("component_appearance:{}", component.id)) { + options.push((format!("{} (component appearance)", component.name), json!({"component_appearance":component.id}))); + } + } + for selected in &app.session.selection { + if let solidcraft_engine::Sel::Face { body, point, .. } = selected { + options.push((format!("Selected face on {body} (shared appearance)"), json!({"face_appearance":{"body":body,"point":point}}))); + } + } + let mut pick: Option = None; + ui_kit::plus_header(ui, |ui| { + egui::ScrollArea::vertical().max_height(crate::theme::Tokens::get().space_24 * 12.0).show(ui, |ui| { + for (label, p) in &options { + if ui_kit::button(ui, label.as_str(), ui_kit::Button::Normal).clicked() { + pick = Some(p.clone()); + ui.close(); + } + } + ui_kit::action_menu(ui, "Face Appearance", |ui| { + ui_kit::text( + ui, + crate::i18n::tr_label("Semantic faces share their appearance across instances."), + ui_kit::Text::Note("semantic_faces"), + ); + let state = app.session.model.state(); + for body in &state.bodies { + if body.body.is_mesh() { + continue; + } + ui_kit::action_menu(ui, &format!("Faces on {}", body.name), |ui| { + if let Ok(faces) = body.body.faces((body.body.size() * 2e-3).max(1e-3)) { + let mut seen = std::collections::BTreeSet::new(); + let mesh = body.mesh(); + let mut points = std::collections::BTreeMap::new(); + for (triangle, index) in mesh.triangles.iter().zip(&mesh.tri_face) { + if let std::collections::btree_map::Entry::Vacant(entry) = points.entry(*index as usize) + && let Some([a, b, c]) = mesh.tri(triangle) + { + entry.insert((a + b + c) * (1. / 3.)); + } + } + for face in faces { + // A curved face centroid can lie on another surface. + // Pick an interior triangle point on this actual face. + let Some(point) = points.get(&face.index).copied() else { continue }; + let Ok(target) = app.session.doc.configuration_face_target(body, face.index, point) else { continue }; + let supported = if target.certificate.is_some() { + // Capture read this exact face's current source certificate. + // Enumerate its pieces once in the command, not per menu face. + app.session.doc.certify_config_face(&target).is_ok() + } else { + app.session.doc.configuration_face_indices(body, &target).is_ok() + }; + if !supported || !seen.insert(target.name.clone()) { + continue; + } + let Some((_, role)) = target.name.split_once(':') else { continue }; + if ui_kit::button(ui, role, ui_kit::Button::Normal).clicked() { + pick = Some(json!({"face_appearance":{"target":target}})); + ui.close(); + } + } + } + }); + } + }); + }); + }); + if let Some(p) = pick { + // The first column starts the table (with a Default row of the current values). + let (id, p) = if columns.is_empty() { + ( + "config.configure", + if let Some(n) = p.get("param") { + json!({ "params": [n] }) + } else if let Some(n) = p.get("feature") { + json!({ "features": [n] }) + } else if let Some(n) = p.get("material") { + json!({ "materials": [n] }) + } else if let Some(n) = p.get("component_appearance") { + json!({ "component_appearances": [n] }) + } else if let Some(n) = p.get("face_appearance") { + json!({ "face_appearances": [n] }) + } else { + json!({ "appearances": [p.get("appearance")] }) + }, + ) + } else { + ("config.column", p) + }; + run(app, error, id, p); + } +} + +fn display_cell(kind: &str, value: &str) -> String { + if (kind == "material" || matches!(kind, "appearance" | "component_appearance" | "face_appearance")) && value.eq_ignore_ascii_case("Default") { + return String::new(); + } + if matches!(kind, "appearance" | "component_appearance" | "face_appearance") { + solidcraft_engine::doc::config::appearance_cell(value) + .ok() + .flatten() + .filter(|look| solidcraft_engine::doc::appearance::library(&look.name).as_ref() == Some(look)) + .map(|look| look.name) + .unwrap_or_else(|| value.to_owned()) + } else { + value.to_owned() + } +} + +fn value_control(ui: &mut egui::Ui, id: egui::Id, text: &mut String, kind: &str, material_names: &[String]) -> (egui::Response, Option) { + let appearance = matches!(kind, "appearance" | "component_appearance" | "face_appearance"); + let mut choice = None; + let response = if kind == "material" || appearance { + let follow = if kind == "appearance" { + "Follow material" + } else if appearance { + "Follow inherited appearance" + } else { + "Default material" + }; + ui_kit::library_cell(ui, id, text, follow, |ui| { + if ui_kit::button(ui, crate::i18n::tr_label(follow), ui_kit::Button::Normal).clicked() { + choice = Some("Default".to_owned()); + ui.close(); + } + let choices: Vec<_> = if kind == "material" { + material_names.iter().filter(|n| *n != "Default").map(String::as_str).collect() + } else { + solidcraft_engine::doc::appearance::LIBRARY.iter().map(|(name, _, _)| *name).collect() + }; + for name in choices { + if ui_kit::button(ui, name, ui_kit::Button::Normal).clicked() { + choice = Some(name.to_owned()); + ui.close(); + } + } + }) + } else { + ui_kit::cell_editor(ui, id, text, "", false) + }; + (response, choice) +} diff --git a/crates/ui-egui/src/crash_ui.rs b/crates/ui-egui/src/crash_ui.rs index 54f873a04..2fdc613d5 100644 --- a/crates/ui-egui/src/crash_ui.rs +++ b/crates/ui-egui/src/crash_ui.rs @@ -71,52 +71,80 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { .cards(2.0) .actions("", crate::i18n::tr("ui.close"), None) .show(ctx, true, |ui| { - ui_kit::text(ui, crate::i18n::tr("crash.intro"), ui_kit::Text::Note("intro")); + ui.spacing_mut().item_spacing.y = crate::theme::Tokens::get().space_10; + let intro = ui_kit::text(ui, crate::i18n::tr("crash.intro"), ui_kit::Text::Hint("intro")); + crate::scenario::publish_rect("dialog:note:intro", intro.rect); if let Some(d) = app.crashes.dir.clone() { // A long path is cut short (hover shows it all): it must not widen the card. - ui_kit::label_actions(ui, &d, |ui| { - if ui_kit::button(ui, crate::i18n::tr("crash.copy_folder"), ui_kit::Button::Small).clicked() { + ui_kit::path_chip(ui, &d, |ui| { + if ui_kit::icon_label_button(ui, crate::i18n::tr("crash.copy_folder"), "copy", true, false).clicked() { ctx.copy_text(d.clone()); } }); } - ui_kit::divider(ui, "reports"); + // The list/empty-box top border replaces the old divider; retain its geometry alias. + crate::scenario::publish_rect( + "dialog:divider:reports", + egui::Rect::from_min_size(ui.next_widget_position(), egui::vec2(ui.available_width(), 1.0)), + ); if app.crashes.reports.is_empty() { - ui_kit::text(ui, crate::i18n::tr_label("No crash reports."), ui_kit::Text::Note("none")); + ui_kit::empty_box(ui, "none", crate::i18n::tr_label("No crash reports.")); } - egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { - for r in &app.crashes.reports { - let title = report_heading(r); - ui_kit::label_actions(ui, &title, |ui| { - if ui_kit::button(ui, crate::i18n::tr("crash.report"), ui_kit::Button::Small).clicked() { - report = Some(r.id.clone()); + if !app.crashes.reports.is_empty() { + ui_kit::report_list( + ui, + "reports", + crate::theme::Tokens::get().control_height * 10.0 + crate::theme::Tokens::get().space_10 * 4.0, + |ui| { + let last = app.crashes.reports.len().saturating_sub(1); + for (index, r) in app.crashes.reports.iter().enumerate() { + let title = report_heading(r); + ui.push_id(&r.id, |ui| { + ui.spacing_mut().item_spacing.y = crate::theme::Tokens::get().space_6; + ui.add_space(crate::theme::Tokens::get().space_10); + ui_kit::report_header( + ui, + kind_label(&r.kind), + r.count, + r.time.replace('T', " ").trim_end_matches('Z'), + &title, + |ui| { + if ui_kit::bin_button(ui, crate::i18n::tr("ui.delete")).clicked() { + delete = Some(Some(r.id.clone())); + } + ui_kit::icon_label_button(ui, crate::i18n::tr("crash.copy_path"), "copy", true, false) + .clicked() + .then(|| ctx.copy_text(r.path.clone())); + if ui_kit::icon_label_button(ui, crate::i18n::tr("crash.report"), "bug_report", true, false).clicked() { + report = Some(r.id.clone()); + } + }, + ); + let mut detail = r.command.clone().unwrap_or_default(); + if r.replayable { + let sep = if detail.is_empty() { "" } else { " · " }; + detail = format!("{detail}{sep}{}", crate::i18n::tr("crash.replayable")); + } + if !detail.is_empty() { + ui_kit::text(ui, &detail, ui_kit::Text::MonoNote(&format!("detail:{}", r.id))); + } + ui_kit::text(ui, &r.message, ui_kit::Text::Report(&format!("message:{}", r.id), false)); + if r.kind == "unclean_exit" { + ui_kit::text(ui, crate::i18n::tr("crash.unclean_explanation"), ui_kit::Text::Note(&format!("unclean:{}", r.id))); + } + ui.add_space(crate::theme::Tokens::get().space_6); + if index != last { + ui_kit::report_divider(ui, &format!("end:{}", r.id)); + } + }); } - if ui_kit::button(ui, crate::i18n::tr("crash.copy_path"), ui_kit::Button::Small).clicked() { - ctx.copy_text(r.path.clone()); - } - if ui_kit::button(ui, crate::i18n::tr("ui.delete"), ui_kit::Button::Small).clicked() { - delete = Some(Some(r.id.clone())); - } - }); - let mut detail = r.command.clone().unwrap_or_default(); - if r.replayable { - let sep = if detail.is_empty() { "" } else { " · " }; - detail = format!("{detail}{sep}{}", crate::i18n::tr("crash.replayable")); - } - if !detail.is_empty() { - ui_kit::text(ui, &detail, ui_kit::Text::Note(&format!("detail:{}", r.id))); - } - ui_kit::text(ui, &r.message, ui_kit::Text::Report(&format!("message:{}", r.id), false)); - if r.kind == "unclean_exit" { - ui_kit::note(ui, &format!("unclean:{}", r.id), crate::i18n::tr("crash.unclean_explanation")); - } - ui_kit::divider(ui, &format!("end:{}", r.id)); - } - }); + }, + ); + } if !app.crashes.note.is_empty() { ui_kit::text(ui, &app.crashes.note, ui_kit::Text::Note("note")); } - if ui_kit::button(ui, "Delete all", ui_kit::Button::Enabled(!app.crashes.reports.is_empty())).clicked() { + if ui_kit::icon_label_button(ui, crate::i18n::tr_label("Delete all"), "delete", !app.crashes.reports.is_empty(), true).clicked() { delete = Some(None); } }); @@ -274,4 +302,51 @@ mod tests { super::announce(&mut h.app, &[quiet]); assert!(!h.app.crashes.open); } + + #[test] + fn inventory_actions_details_empty_state_and_keyboard_remain_reachable() { + let d = folder("inventory"); + let mut h = crate::scenario::Harness::new(); + h.app.crashes.folder = Some(d.clone()); + super::open(&mut h.app); + h.frames(5); + for handle in [ + "dialog:close", + "dialog:cancel", + "dialog:Close", + "dialog:button::Copy folder path", + "dialog:button::Report…", + "dialog:button::Copy path", + "dialog:button::Delete", + "dialog:button::Delete all", + ] { + assert!(crate::scenario::handle_at(handle).is_some(), "missing {handle}"); + } + for rect in [ + "dialog:note:intro", + "dialog:divider:reports", + "dialog:list:reports", + "dialog:note:detail:20261012-162341-bb60791ed6692f1d", + "dialog:report:message:20261012-162341-bb60791ed6692f1d", + ] { + assert!(crate::scenario::rect_of(rect).is_some(), "missing {rect}"); + } + let title = "2026-10-12 16:23:41 Closed unexpectedly ×2"; + assert!(crate::scenario::handle_at(&format!("dialog:cell:{title}")).is_some()); + assert!(crate::scenario::handle_at(&format!("dialog:cell:{}", d.display())).is_some()); + h.step(&json!({"click":{"handle":"dialog:button::Copy folder path"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:button::Copy path"}})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + assert!(h.app.crashes.open, "Enter has no primary action"); + h.step(&json!({"click":{"handle":"dialog:button::Delete"}})).unwrap(); + h.frames(3); + assert!(h.app.crashes.reports.is_empty()); + assert!(crate::scenario::rect_of("dialog:note:none").is_some()); + assert!(crate::scenario::rect_of("dialog:note:note").is_some()); + h.step(&json!({"click":{"handle":"dialog:button::Delete all"}})).unwrap(); + assert!(h.app.crashes.reports.is_empty()); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(!h.app.crashes.open); + let _ = std::fs::remove_dir_all(d); + } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4ce75d6c3..8b7596649 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -407,8 +407,9 @@ pub struct Dialog { pub profile_selection_changed: bool, /// Give the on-canvas value box the keyboard (and select its text) on the next frame. pub focus: bool, - /// Folded to its header (the "−" glyph). + /// Folded to its header (the shared disclosure chevron). pub collapsed: bool, + reset_scroll: bool, /// Transient display preference; never part of a command or a saved feature. pub preview_enabled: bool, /// Preserve Apply intent across asynchronous evaluation; never a command parameter. @@ -538,6 +539,7 @@ impl Dialog { profile_selection_changed: false, focus: true, collapsed: false, + reset_scroll: true, preview_enabled: true, repeat_after_apply: false, extra: serde_json::Map::new(), @@ -2140,7 +2142,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { app.viewport.dialog_rect = None; } let Some(mut d) = app.dialog.take() else { - if app.tree.redefine.is_none() { + if app.tree.redefine.is_none() && app.params.is_none() { crate::frame::reset_dock_offset(ctx); } return; @@ -2231,7 +2233,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { }; let panel = crate::ui_kit::Panel::new(&heading, egui::Id::new(("sc_dialog", title(&d.kind))), anchor, vp, side, frame).actions(ok_label, close_label); - let panel = if wide { + let panel = if matches!(d.kind, Kind::Appearance(_)) { + panel.width(t.form_card_width + t.form_label_width + t.space_6) + } else if wide { let panel = panel.wide(); if side == crate::frame::Side::Left { let available = app.viewport.palette_rect.map_or(vp.width(), |r| (r.left() - vp.left() - t.space_8).max(0.0)); @@ -2242,6 +2246,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } else { panel }; + let reset_scroll = d.reset_scroll; + let panel = + panel.reset_scroll(reset_scroll && matches!(d.kind, Kind::Appearance(_) | Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. }))); let window = panel.window(); let repeatable = matches!(&d.kind, Kind::SketchModify(k) if crate::sketch_modify_ui::repeatable(k)) && d.editing.is_none() && !d.extra.contains_key("pattern"); @@ -2283,6 +2290,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { } else { panel.feature(ui, heading, applying, valid, body) }; + d.reset_scroll = false; d.collapsed = collapsed; cancel |= closed; if app.issue_report.draft.is_none() { diff --git a/crates/ui-egui/src/dialogs_appearance.rs b/crates/ui-egui/src/dialogs_appearance.rs index a5e22d126..acee40a30 100644 --- a/crates/ui-egui/src/dialogs_appearance.rs +++ b/crates/ui-egui/src/dialogs_appearance.rs @@ -281,7 +281,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &mut [Sel // Apply To: bodies or faces (the input follows). if let Some(component) = &k.component { ui_kit::row(ui, "Apply To", |ui| ui_kit::text(ui, &format!("Component: {component}"), ui_kit::Text::Cell)); - if ui_kit::button(ui, crate::i18n::tr_label("Select bodies or faces instead"), ui_kit::Button::Normal).clicked() { + if ui_kit::row(ui, "", |ui| ui_kit::button(ui, crate::i18n::tr_label("Select bodies or faces instead"), ui_kit::Button::Normal)).clicked() { k.component = None; } } else { @@ -301,10 +301,10 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &mut [Sel k.look = None; k.remove_override = false; } - ui_kit::text(ui, &k.look.clone().unwrap_or_else(|| hex(k.color)), ui_kit::Text::Cell); + ui_kit::text(ui, &k.look.clone().unwrap_or_else(|| hex(k.color)), ui_kit::Text::MonoCell); }); ui_kit::row(ui, "Opacity", |ui| { - if ui.add_enabled_ui(k.pbr.is_none(), |ui| ui_kit::slider(ui, &mut k.opacity, 0.0..=1.0)).inner.changed() { + if ui.add_enabled_ui(k.pbr.is_none(), |ui| ui_kit::slider(ui, &mut k.opacity, 0.0..=1.0, Default::default())).inner.changed() { k.remove_override = false; } }); @@ -339,7 +339,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &mut [Sel } } let picked: Vec = inputs.first().map(|i| i.items.clone()).unwrap_or_default(); - ui.horizontal(|ui| { + ui.horizontal_wrapped(|ui| { let has_target = !picked.is_empty() || k.component.is_some(); if ui_kit::button(ui, "Apply to selection", ui_kit::Button::Enabled(has_target)).clicked() && let Some(p) = selected_params(k, &picked) @@ -372,7 +372,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &mut [Sel // In this design. let used = in_design(app); if !used.is_empty() { - ui_kit::section(ui, "in_design", "In This Design", true, |ui| { + ui_kit::section_count(ui, "in_design", "In This Design", true, Some(used.len()), |ui| { let items: Vec<_> = used.iter().enumerate().collect(); ui_kit::swatch_grid(ui, &items, |ui, (i, (look, n))| { if ui_kit::color_swatch( @@ -622,10 +622,10 @@ mod tests { h.app.start("appearance.assign"); h.frames(3); let before = h.app.dialog.clone().unwrap(); - h.step(&json!({"widget":"»"})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:collapse"}})).unwrap(); assert!(h.app.dialog.as_ref().unwrap().collapsed); assert!(h.widget("Appearance name").is_none()); - h.step(&json!({"widget":"«"})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:collapse"}})).unwrap(); let after = h.app.dialog.as_ref().unwrap(); assert!(!after.collapsed); assert_eq!(format!("{:?}", after.inputs), format!("{:?}", before.inputs)); @@ -676,4 +676,74 @@ mod tests { d.inputs[0].items = vec![Sel::Body { name: "Body2".into() }]; assert_eq!(commands(k, &d.inputs).len(), 1, "changed target still applies on OK"); } + + #[test] + fn inventory_rows_controls_sections_and_component_mode_remain_reachable() { + let mut h = crate::scenario::Harness::new(); + h.call("ui.resize", json!({"width":1600,"height":2000})); + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Body1"],"color":"#abcdef","opacity":0.25,"appearance":"Tinted glass"})).unwrap(); + h.app.session.selection = vec![Sel::Body { name: "Body1".into() }]; + h.app.start("appearance.assign"); + h.frames(5); + for handle in [ + "dialog:Objects", + "dialog:clear:Objects", + "dialog:Apply To", + "dialog:color:Colour", + "dialog:slider:Opacity", + "appearance:pbr", + "appearance:search", + "dialog:section:Local library", + "dialog:section:In This Design", + "dialog:Library", + "dialog:button::Apply to selection", + "dialog:button::Remove override", + "library:export", + "dialog:ok", + "dialog:cancel", + "dialog:collapse", + ] { + assert!(crate::scenario::handle_at(handle).is_some(), "missing {handle}"); + } + for label in ["Objects", "Apply To", "Colour", "Opacity", "Surface response", "Library", "Search"] { + assert!(crate::scenario::rect_of(&format!("dialog:row:{label}")).is_some(), "missing row {label}"); + } + h.step(&json!({"click":{"handle":"dialog:Apply To"}})).unwrap(); + h.frames(2); + for option in ["Bodies", "Faces"] { + assert!(crate::scenario::handle_at(&format!("dialog:Apply To:{option}")).is_some()); + } + h.step(&json!({"click":{"handle":"dialog:Apply To:Bodies"}})).unwrap(); + h.step(&json!({"click":{"handle":"appearance:pbr"}})).unwrap(); + for handle in ["appearance:metallic", "appearance:roughness", "appearance:ior"] { + assert!(crate::scenario::handle_at(handle).is_some(), "missing {handle}"); + } + let Kind::Appearance(k) = &mut h.app.dialog.as_mut().unwrap().kind else { panic!("Appearance") }; + k.component = Some("Example component".into()); + k.note = Some("Appearance applied".into()); + h.frames(4); + assert!(h.widget("Appearance applied").is_some()); + assert!(crate::scenario::handle_at("dialog:button::Select bodies or faces instead").is_some()); + assert!(crate::scenario::handle_at("dialog:cell:Component: Example component").is_some()); + h.step(&json!({"widget":"Select bodies or faces instead"})).unwrap(); + assert!(crate::scenario::handle_at("dialog:Apply To").is_some()); + h.step(&json!({"click":{"handle":"dialog:clear:Objects"}})).unwrap(); + assert!(h.app.dialog.as_ref().unwrap().inputs[0].items.is_empty()); + h.step(&json!({"click":{"handle":"dialog:color:Colour"}})).unwrap(); + h.frames(3); + for handle in [ + "color:format:U8", + "color:format:F", + "color:copy", + "color:channel:R", + "color:channel:G", + "color:channel:B", + "color:sv", + "color:hue", + "color:current", + ] { + assert!(crate::scenario::handle_at(handle).is_some(), "missing {handle}"); + } + } } diff --git a/crates/ui-egui/src/dialogs_assembly.rs b/crates/ui-egui/src/dialogs_assembly.rs index 806c02840..73780d802 100644 --- a/crates/ui-egui/src/dialogs_assembly.rs +++ b/crates/ui-egui/src/dialogs_assembly.rs @@ -630,8 +630,12 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Asm, inputs: &mut [Se let cur = s.doc.eval(v, unit_kind).ok().filter(|x| x.is_finite()).unwrap_or(0.0); let (mut shown, scale) = if angle { (cur.to_degrees(), 1f64.to_degrees()) } else { (cur, 1.0) }; ui.vertical(|ui| { - ui.spacing_mut().slider_width = 160.0; - let r = crate::ui_kit::timeline_slider(ui, &mut shown, lo * scale..=hi * scale, false); + let r = crate::ui_kit::slider( + ui, + &mut shown, + lo * scale..=hi * scale, + crate::ui_kit::Slider { show_value: false, ..Default::default() }, + ); crate::scenario::publish_handle(&format!("drive_slider:{i}"), r.rect.center()); if r.changed() { *v = if angle { format!("{shown:.1} deg") } else { format!("{shown:.2} mm") }; diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rs index 1fabd7c01..f8fcbf837 100644 --- a/crates/ui-egui/src/dialogs_dense.rs +++ b/crates/ui-egui/src/dialogs_dense.rs @@ -134,6 +134,9 @@ fn choose_fillet_type(extra: &mut serde_json::Map, index: usize, pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui: &mut egui::Ui) -> bool { let t = Tokens::get(); let mut enter = false; + if matches!(d.kind, Kind::Appearance(_)) { + ui.spacing_mut().item_spacing.y = t.space_10; + } if matches!(d.kind, Kind::Sketch | Kind::SketchModify(_) | Kind::Text(_) | Kind::TextMove(_) | Kind::EditParam { .. }) { let prompt = if let Some(input) = d.active_input() { tr(hint(input)).to_owned() diff --git a/crates/ui-egui/src/dialogs_library.rs b/crates/ui-egui/src/dialogs_library.rs index 6042a0bf6..6633560dd 100644 --- a/crates/ui-egui/src/dialogs_library.rs +++ b/crates/ui-egui/src/dialogs_library.rs @@ -176,34 +176,36 @@ fn import_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &[SelI ui_kit::text(ui, crate::i18n::tr_label("No matching appearance presets."), ui_kit::Text::Note("library_empty")); } let row_height = ui_kit::row_height(); - egui::ScrollArea::vertical().id_salt("local_library_entries").max_height(row_height * 5.0).show_rows( - ui, - row_height, - appearances.len(), - |ui, range| { - for index in range { - let Some(entry) = appearances.get(index) else { continue }; - if let Definition::Appearance(look) = &entry.definition { - ui.horizontal(|ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); - let [r, g, b] = look.color; - ui_kit::color_swatch(ui, ui.id().with((&entry.id, "sample")), egui::Color32::from_rgb(r, g, b), false, &look.name, ()); - let button = ui_kit::list_picker(ui, &entry.id, &look.name, k.local.selected.as_deref() == Some(entry.id.as_str())) - .on_hover_text(format!( - "Opacity {:.0}% · {} · {}", - look.opacity * 100.0, - entry.provenance.license, - entry.provenance.source_url.as_deref().unwrap_or("Local definition") - )); - crate::scenario::publish_handle(&format!("library:entry:{index}"), button.rect.center()); - if button.clicked() { - k.local.selected = Some(entry.id.clone()); - } - }); + ui_kit::list_frame(ui, "local_library_entries", |ui| { + egui::ScrollArea::vertical().id_salt("local_library_entries").max_height(row_height * 5.0).show_rows( + ui, + row_height, + appearances.len(), + |ui, range| { + for index in range { + let Some(entry) = appearances.get(index) else { continue }; + if let Definition::Appearance(look) = &entry.definition { + ui.horizontal(|ui| { + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); + let [r, g, b] = look.color; + ui_kit::color_thumbnail(ui, ui.id().with((&entry.id, "sample")), egui::Color32::from_rgb(r, g, b), &look.name, ()); + let button = ui_kit::list_picker(ui, &entry.id, &look.name, k.local.selected.as_deref() == Some(entry.id.as_str())) + .on_hover_text(format!( + "Opacity {:.0}% · {} · {}", + look.opacity * 100.0, + entry.provenance.license, + entry.provenance.source_url.as_deref().unwrap_or("Local definition") + )); + crate::scenario::publish_handle(&format!("library:entry:{index}"), button.rect.center()); + if button.clicked() { + k.local.selected = Some(entry.id.clone()); + } + }); + } } - } - }, - ); + }, + ); + }); } let entry = k .local diff --git a/crates/ui-egui/src/dialogs_library_tests.rs b/crates/ui-egui/src/dialogs_library_tests.rs index 3a5debe81..9fb44dd26 100644 --- a/crates/ui-egui/src/dialogs_library_tests.rs +++ b/crates/ui-egui/src/dialogs_library_tests.rs @@ -30,6 +30,30 @@ fn catalog_clicked_load_apply_export_and_ok_keep_one_design_undo_step() { h.frames(3); let undo = h.app.session.undo.len(); h.step(&json!({"widget":"Load library"})).unwrap(); + for handle in [ + "library:path", + "library:load", + "library:search", + "library:entry:0", + "library:apply", + "library:export", + "dialog:button::Open library...", + "dialog:button::Load library", + "dialog:button::Apply library appearance", + "dialog:button::Export design library...", + ] { + assert!(crate::scenario::handle_at(handle).is_some(), "missing {handle}"); + } + for message in + ["Replace existing library file", "Apply your appearance first. Exports assigned appearances and materials created in this design."] + { + assert!(h.widget(message).is_some(), "missing {message}"); + } + h.step(&json!({"click":{"handle":"library:search"}})).unwrap(); + h.step(&json!({"text":"no such appearance"})).unwrap(); + assert!(h.widget("No matching appearance presets.").is_some()); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"key":"Backspace"})).unwrap(); h.step(&json!({"click":{"handle":"library:entry:0"}})).unwrap(); h.step(&json!({"widget":"Apply library appearance"})).unwrap(); assert_eq!(h.app.session.doc.appearances.bodies["Body1"].name, "Warm oak colour"); diff --git a/crates/ui-egui/src/dialogs_motion.rs b/crates/ui-egui/src/dialogs_motion.rs index 169ebf4c1..c4b1684b4 100644 --- a/crates/ui-egui/src/dialogs_motion.rs +++ b/crates/ui-egui/src/dialogs_motion.rs @@ -72,7 +72,7 @@ pub enum Mo { Configurations { new_row: String, error: Option, - rule_editor: configuration_rules_ui::Editor, + rule_editor: Box, }, } @@ -509,8 +509,7 @@ pub fn rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs: &mut [Sel Mo::Explode { name, scale, shown, saved, error } => { text_row(ui, "Name", name, ""); form_row(ui, "Explode", |ui| { - ui.spacing_mut().slider_width = 160.0; - crate::ui_kit::slider(ui, scale, 0.0..=2.0); + crate::ui_kit::slider(ui, scale, 0.0..=2.0, Default::default()); }); let key = ((*scale * 1000.0).round() as u64, 0); if *shown != Some(key) { @@ -602,7 +601,14 @@ fn motion_study_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Mo, inputs: }); form_row(ui, "Step", |ui| { ui.horizontal(|ui| { - if crate::ui_kit::timeline_slider(ui, step, 0.0..=f64::from(total), true).dragged() { + if crate::ui_kit::slider( + ui, + step, + 0.0..=f64::from(total), + crate::ui_kit::Slider { show_value: false, integer: true, ..Default::default() }, + ) + .dragged() + { *playing = false; } }); @@ -887,11 +893,16 @@ mod tests { } h.call( "ui.scroll", - json!({"x":header.center().x,"y":(header.bottom()+footer.top())*0.5,"delta":if at.y > footer.top() {-160.0} else {160.0}}), + json!({"x":header.left()+Tokens::get().space_6,"y":(header.bottom()+footer.top())*0.5,"delta":if at.y >= footer.top()-Tokens::get().space_8 {-160.0} else {160.0}}), ); h.frames(6); } - panic!("could not reveal {handle}"); + panic!( + "could not reveal {handle}: {:?}, header {:?}, footer {:?}", + crate::scenario::handle_at(handle), + crate::scenario::rect_of("dialog:header"), + crate::scenario::rect_of("dialog:footer") + ); } fn click_config_handle(h: &mut crate::scenario::Harness, handle: &str) { @@ -1136,7 +1147,7 @@ mod tests { ])) .unwrap(); harness.frames(4); - for label in ["Configuration", "Active", "Apply", "Add Row", "Add Column"] { + for label in ["Configuration", "Active", "Apply", "Add configuration", "Add Column"] { assert_single_line(&harness, label); } crate::scenario::check(&mut harness, &json!({"windows_fit":{"max_width":Tokens::get().form_card_width * 3.0}})).unwrap(); @@ -1162,7 +1173,7 @@ mod tests { "missing {label}; labels/values: {:?}", tree.nodes.iter().filter_map(|(_, n)| n.label().or(n.value())).collect::>() ); - assert!(bounds.iter().all(|b| b.y1 - b.y0 <= 24.0), "{label} wrapped: {bounds:?}"); + assert!(bounds.iter().all(|b| b.y1 - b.y0 <= Tokens::get().control_height as f64), "{label} wrapped: {bounds:?}"); } } diff --git a/crates/ui-egui/src/expression_complete.rs b/crates/ui-egui/src/expression_complete.rs index 4428f9918..0ef4f7de6 100644 --- a/crates/ui-egui/src/expression_complete.rs +++ b/crates/ui-egui/src/expression_complete.rs @@ -128,11 +128,18 @@ pub(crate) fn complete(ui: &mut egui::Ui, resp: &egui::Response, text: &mut Stri .iter() .map(|suggestion| ui_kit::PopupOption { text: &suggestion.text, + kind: match suggestion.kind.as_str() { + "parameter" => crate::i18n::tr_label("Parameter"), + "function" => crate::i18n::tr("ui.function"), + "unit" => crate::i18n::tr_label("Unit"), + "constant" => crate::i18n::tr("ui.constant"), + _ => &suggestion.kind, + }, detail: &suggestion.detail, color: match suggestion.kind.as_str() { - "parameter" => t.text, - "function" => t.accent, - _ => t.text_dim, + "parameter" => t.form_ink, + "function" => t.form_primary, + _ => t.form_dim, }, }) .collect(); diff --git a/crates/ui-egui/src/frame.rs b/crates/ui-egui/src/frame.rs index 85903515e..5b1bd9442 100644 --- a/crates/ui-egui/src/frame.rs +++ b/crates/ui-egui/src/frame.rs @@ -153,6 +153,7 @@ mod tests { h.step(&json!({"start":"solid.extrude"})).unwrap(); h.frames(10); let dialog = h.app.viewport.dialog_rect.unwrap(); + let dialog_content = crate::scenario::count_of("dialog:body:content_height").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:?}"); @@ -167,7 +168,18 @@ mod tests { 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:?}"); + let short_content = crate::scenario::count_of("dialog:body:content_height").unwrap(); + assert!( + short_content < dialog_content, + "short forms have less content even when both need scrolling: {short_content}, {dialog_content}" + ); + assert!(short.height() <= dialog.height(), "short forms cannot grow taller: {short:?}, {dialog:?}"); + let t = crate::theme::Tokens::get(); + let chrome = f64::from(t.form_header_height + t.form_footer_height + t.form_gap_y * 2.0 + t.space_2); + if short_content + chrome < f64::from(dialog.height()) { + assert!(short.height() < dialog.height(), "unconstrained short forms must shrink: {short:?}, {dialog:?}"); + } + assert!(viewport.expand(1.0).contains_rect(short)); assert!(h.widget("Cancel").is_some()); h.step(&json!({"widget":"Cancel"})).unwrap(); h.step(&json!({"start":"solid.hole"})).unwrap(); diff --git a/crates/ui-egui/src/manage_dialogs_tests.rs b/crates/ui-egui/src/manage_dialogs_tests.rs index 9524247ac..aacd94d3c 100644 --- a/crates/ui-egui/src/manage_dialogs_tests.rs +++ b/crates/ui-egui/src/manage_dialogs_tests.rs @@ -31,6 +31,7 @@ fn painted_text<'a>(output: &'a egui::FullOutput, text: &str, within: egui::Rect fn find<'a>(shape: &'a egui::Shape, text: &str, within: egui::Rect) -> Option<&'a egui::epaint::TextShape> { match shape { egui::Shape::Text(shape) if shape.galley.job.text == text && within.contains(shape.pos) => Some(shape), + egui::Shape::Vec(shapes) => shapes.iter().find_map(|shape| find(shape, text, within)), _ => None, } @@ -46,7 +47,7 @@ fn parameter_columns_fit_controls_and_headers_share_cell_left_edges() { h.app.start("parameters.change"); h.frames(4); let output = painted_frame(&mut h); - for label in ["Name", "Unit", "Expression", "Value", "Comment", "Actions"] { + for label in ["Name", "Unit", "Expression", "Value", "Comment"] { let header = scenario::rect_of(&format!("dialog:column:user:{label}")).unwrap(); let cell = scenario::rect_of(&format!("dialog:table:user:width:cell:{label}")).unwrap(); assert_eq!(header.left(), cell.left(), "{label}: {layout:?}"); @@ -62,8 +63,6 @@ fn parameter_columns_fit_controls_and_headers_share_cell_left_edges() { assert!(unit.width() >= mm.galley.size().x + 2.0 * Tokens::get().space_8 + spacing.icon_width + spacing.icon_spacing); assert!(mm.pos.x + mm.galley.size().x + Tokens::get().space_8 + spacing.icon_width + spacing.icon_spacing <= unit.right()); let actions = scenario::rect_of("dialog:table:user:width:cell:Actions").unwrap(); - let delete = painted_text(&output, "Delete", actions); - assert!(!delete.galley.elided, "Delete must be painted without an ellipsis"); assert!(actions.contains_rect(scenario::rect_of("dialog:button:Actions:Delete").unwrap())); // More content widens the scroll area, never the card. h.call("ui.resize", json!({"width":640,"height":1000})); @@ -81,26 +80,26 @@ fn configuration_columns_align_values_status_and_remove_actions() { h.app.start("config.table"); h.frames(4); let output = painted_frame(&mut h); - for label in ["Configuration", "width", "Actions"] { + for label in ["Configuration", "width"] { let header = scenario::rect_of(&format!("dialog:column:configuration_table:{label}")).unwrap(); - for row in ["Default", "columns"] { - let cell = scenario::rect_of(&format!("dialog:table:configuration_table:{row}:cell:{label}")).unwrap(); - assert_eq!(header.left(), cell.left()); - assert_eq!(header.width(), cell.width()); - } + let cell = scenario::rect_of(&format!("dialog:table:configuration_table:Default:cell:{label}")).unwrap(); + assert_eq!(header.left(), cell.left()); + assert_eq!(header.width(), cell.width()); assert!((painted_text(&output, label, header).pos.x - header.left()).abs() <= 0.5); } let name = scenario::rect_of("dialog:table:configuration_table:Default:cell:Configuration").unwrap(); + assert!(!painted_text(&output, "Default", name).galley.elided, "strong names reserve their measured width"); let active = painted_text(&output, "Active", name); assert!(!active.galley.elided); assert!(active.pos.x + active.galley.size().x <= name.right()); let value = scenario::rect_of("dialog:table:configuration_table:Default:cell:width").unwrap(); assert!(!painted_text(&output, "80 mm", value).galley.elided); - let remove_cell = scenario::rect_of("dialog:table:configuration_table:columns:cell:width").unwrap(); + let remove_cell = scenario::rect_of("dialog:column:configuration_table:width").unwrap(); + assert!(scenario::rect_of("dialog:button:width:×").is_none(), "remove stays hidden until header hover"); + h.step(&json!({"move":[remove_cell.center().x,remove_cell.center().y]})).unwrap(); + h.frames(2); let remove = scenario::rect_of("dialog:button:width:×").unwrap(); assert!(remove_cell.contains_rect(remove)); - let action_label = scenario::rect_of("dialog:table:configuration_table:columns:cell:Configuration").unwrap(); - assert!(!painted_text(&output, "Remove the column", action_label).galley.elided); h.step(&json!({"click":[remove.center().x,remove.center().y]})).unwrap(); assert!(h.app.session.doc.configs.columns.is_empty(), "the column action remains interactive"); } @@ -182,10 +181,13 @@ fn configurations(command: &str) { for label in ["Configuration", "width", "Actions"] { assert!(scenario::rect_of(&format!("dialog:column:configuration_table:{label}")).is_some()); } - assert_eq!(scenario::rect_of("dialog:table:configuration_table:Default").unwrap().height(), Tokens::get().control_height); + assert_eq!(scenario::rect_of("dialog:table:configuration_table:Default").unwrap().height(), crate::ui_kit::table_row_height()); assert!(h.widget("Add Column").is_some()); - assert!(h.widget("Add Row").is_some()); - h.step(&json!({"widget":"Add Row"})).unwrap(); + assert!(h.widget("Add configuration").is_some()); + h.step(&json!({"click":{"handle":"dialog:table:configuration_table:add"}})).unwrap(); + assert_eq!(h.app.session.doc.configs.rows.len(), 1, "add inserts a draft, not a saved row"); + assert_eq!(scenario::rect_of("dialog:table:configuration_table:new").unwrap().height(), crate::ui_kit::table_row_height()); + h.step(&json!({"key":"Enter"})).unwrap(); assert_eq!(h.app.session.doc.configs.rows.len(), 2); h.step(&json!({"click":{"handle":"config:cell:Configuration2:param:width"}})).unwrap(); h.step(&json!({"key":"A","cmd":true})).unwrap(); @@ -269,12 +271,270 @@ fn wide_managers_leave_the_active_sketch_palette_visible() { } #[test] -fn appearance_card_keeps_the_standard_width_with_no_preselection() { +fn appearance_card_keeps_the_approved_width_with_no_preselection() { let mut h = fixture(); h.app.session.selection.clear(); h.app.start("appearance.assign"); h.frames(4); let header = scenario::rect_of("dialog:header").unwrap(); let card = h.ctx.memory(|m| m.area_rect(egui::Id::new(("sc_dialog", "APPEARANCE")))).unwrap(); - assert!(card.width() <= Tokens::get().form_card_width + 2.0, "card {card:?}, header {header:?}"); + let t = Tokens::get(); + let approved = t.form_card_width + t.form_label_width + t.space_6; + assert!((card.width() - approved).abs() <= t.space_2, "card {card:?}, header {header:?}"); +} + +#[test] +fn parameter_inventory_remains_reachable_with_regular_draft_rows() { + let mut h = fixture(); + h.app.start("parameters.change"); + h.frames(4); + for label in ["Filter", "Import…", "Export CSV…", "Export JSON…", "User Parameters", "Model Parameters"] { + assert!(h.widget(label).is_some(), "missing inventory control {label}"); + } + h.step(&json!({"click":{"handle":"dialog:table:user:add"}})).unwrap(); + assert_eq!(scenario::rect_of("dialog:table:user:new").unwrap().height(), crate::ui_kit::table_row_height()); + for label in ["name", "unit", "expression", "comment"] { + assert!(scenario::handle_at(&format!("param:new:{label}")).is_some()); + } + assert_eq!(h.app.params.as_ref().unwrap().new_expr, "10 mm"); + h.step(&json!({"text":"pitch"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + assert_eq!(h.app.session.doc.param("pitch").unwrap().expr, "10 mm"); + assert!(h.app.params.is_some()); + h.step(&json!({"click":{"handle":"dialog:table:user:add"}})).unwrap(); + h.step(&json!({"click":{"handle":"param:new:unit"}})).unwrap(); + for unit in ["mm", "cm", "m", "in", "ft", "deg", "rad", "none", "um"] { + assert!(scenario::handle_at(&format!("dialog:Unit:{unit}")).is_some(), "unit {unit}"); + } + h.step(&json!({"click":{"handle":"dialog:Unit:mm"}})).unwrap(); + h.step(&json!({"click":{"handle":"param:new:expression"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"missing_parameter"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + assert_eq!(scenario::count_of("param:new:valid"), Some(0.0)); + assert!(h.app.params.as_ref().unwrap().error.is_some()); + assert_eq!(h.app.session.doc.params.iter().filter(|p| !p.model).count(), 2); + h.step(&json!({"click":{"handle":"dialog:Filter"}})).unwrap(); + assert!(!h.app.params.as_ref().unwrap().adding, "an abandoned nameless draft disappears"); + h.frames(40); // Separate the rename gesture from preceding clicks (egui also recognizes triple-clicks). + h.step(&json!({"click":{"handle":"param:name:width"},"double":true})).unwrap(); + h.frames(2); + assert!(h.app.params.as_ref().unwrap().renaming.is_some(), "double click enters rename mode"); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"span"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + assert!(h.app.session.doc.param("span").is_some(), "double-click rename still commits"); + h.step(&json!({"click":{"handle":"param:star:span"}})).unwrap(); + assert!(h.widget("Favorites").is_some()); + assert!(scenario::handle_at("param:favorite:span").is_some()); + h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap(); + assert!(h.app.params.is_none()); + assert!(h.app.session.doc.param("pitch").is_some(), "Cancel keeps committed edits"); +} + +#[test] +fn configuration_inventory_keeps_library_rules_preview_and_inline_row_lifecycle() { + let mut h = fixture(); + h.app.run("config.configure", json!({"params":["width"],"materials":["Body1"],"appearances":["Body1"]})).unwrap(); + h.app.start("config.table"); + h.frames(4); + assert!(h.widget("Active").is_some()); + assert!(scenario::rect_of("dialog:menu:Library").is_some()); + h.step(&json!({"click":{"handle":"dialog:menu:Library"}})).unwrap(); + for label in ["Follow material", "ABS - Blue"] { + assert!(h.widget(label).is_some(), "missing library option {label}"); + } + h.step(&json!({"widget":"Follow material"})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:menu:Add Column"}})).unwrap(); + assert!(h.widget("Face Appearance").is_some()); + h.step(&json!({"key":"Escape"})).unwrap(); + assert!(h.app.dialog.is_some(), "menu Escape leaves the card open"); + h.step(&json!({"click":{"handle":"dialog:table:configuration_table:add"}})).unwrap(); + h.step(&json!({"text":"Wide"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + let rows = &h.app.session.doc.configs.rows; + let default = rows.iter().find(|row| row.name == "Default").unwrap(); + let wide = rows.iter().find(|row| row.name == "Wide").unwrap(); + assert_eq!(wide.cells, default.cells, "new rows copy the active configuration"); + h.step(&json!({"click":{"handle":"config:activate:Wide"}})).unwrap(); + assert_eq!(h.app.session.doc.configs.active.as_deref(), Some("Wide")); + h.step(&json!({"click":{"handle":"dialog:table:configuration_table:add"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:section:Add or edit rule"}})).unwrap(); + h.frames(3); + assert!(scenario::rect_of("dialog:table:configuration_table:new").is_none(), "abandoned empty row is dropped"); + assert!(h.widget("Enabled").is_some()); + for label in ["Rule name", "Length units", "When", "Then"] { + assert!(scenario::rect_of(&format!("dialog:row:{label}")).is_some(), "rule inventory {label}"); + } + assert!(scenario::handle_at("config:save_rule").is_some()); + h.step(&json!({"click":{"handle":"dialog:section:Add or edit rule"}})).unwrap(); + h.step(&json!({"click":{"handle":"config:preview_row"}})).unwrap(); + assert!(h.widget("Preview: Default").is_some()); + h.step(&json!({"click":{"handle":"dialog:collapse"}})).unwrap(); + assert!(scenario::handle_at("dialog:ok").is_some(), "fold retains footer actions"); + h.step(&json!({"click":{"handle":"dialog:collapse"}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:button:Actions:Delete"}})).unwrap(); + assert_eq!(h.app.session.doc.configs.rows.len(), 1, "bin retains immediate deletion"); +} + +#[test] +fn draft_bins_do_not_delete_saved_rows_named_new() { + for command in ["parameters.change", "config.table"] { + let mut h = fixture(); + h.app.run("parameters.add", json!({"name":"new","expression":"12 mm"})).unwrap(); + if command == "config.table" { + h.app.run("config.configure", json!({"params":["width"]})).unwrap(); + h.app.run("config.row", json!({"name":"new","from":"Default"})).unwrap(); + } + h.app.start(command); + h.frames(4); + let add = if command == "config.table" { "dialog:table:configuration_table:add" } else { "dialog:table:user:add" }; + h.step(&json!({"click":{"handle":add}})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:button:Actions:Delete"}})).unwrap(); + assert!(h.app.session.doc.param("new").is_some()); + if command == "config.table" { + assert!(h.app.session.doc.configs.rows.iter().any(|row| row.name == "new")); + } else { + assert!(!h.app.params.as_ref().unwrap().adding); + } + } +} + +#[test] +fn invalid_named_parameter_draft_stays_pending_until_the_expression_is_valid() { + let mut h = fixture(); + h.app.start("parameters.change"); + h.frames(4); + h.step(&json!({"click":{"handle":"dialog:table:user:add"}})).unwrap(); + h.step(&json!({"click":{"handle":"param:new:expression"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"missing_parameter"})).unwrap(); + h.step(&json!({"click":{"handle":"param:new:name"}})).unwrap(); + h.step(&json!({"text":"pitch"})).unwrap(); + h.step(&json!({"click":{"handle":"dialog:Filter"}})).unwrap(); + assert!(h.app.params.as_ref().unwrap().adding); + assert!(h.app.session.doc.param("pitch").is_none()); + assert_eq!(scenario::count_of("param:new:valid"), Some(0.0)); + h.step(&json!({"click":{"handle":"param:new:expression"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"5 mm"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); + assert_eq!(h.app.session.doc.param("pitch").unwrap().expr, "5 mm"); + assert!(h.app.params.as_ref().unwrap().adding); + assert!(h.app.params.as_ref().unwrap().new_name.is_empty()); + assert!(scenario::handle_at("param:new:name").is_some(), "successful add focuses the next draft name"); +} + +fn scroll_card(h: &mut Harness, delta: f32) { + let viewport = scenario::rect_of("dialog:body:viewport").unwrap(); + h.call("ui.scroll", json!({"x":viewport.center().x,"y":viewport.center().y,"delta":delta})); + h.frames(40); +} + +fn assert_card_top() { + assert_eq!(scenario::count_of("dialog:body:scroll_y"), Some(0.0)); + let viewport = scenario::rect_of("dialog:body:viewport").unwrap(); + assert!(viewport.contains_rect(scenario::rect_of("dialog:hint:manage").unwrap())); +} + +#[test] +fn parameters_open_at_top_retain_user_scroll_and_reveal_only_requested_drafts() { + for layout in [LayoutMode::Docked, LayoutMode::Floating] { + let mut h = fixture(); + h.call("ui.set", json!({"layout":layout})); + for _ in 0..7 { + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + } + for i in 0..18 { + h.app.run("parameters.add", json!({"name":format!("user{i}"),"expression":"10 mm"})).unwrap(); + } + h.app.run("parameters.favorite", json!({"name":"width","favorite":true})).unwrap(); + h.app.start("parameters.change"); + h.frames(8); + assert_card_top(); + let viewport = scenario::rect_of("dialog:body:viewport").unwrap(); + assert!(viewport.contains_rect(scenario::rect_of("dialog:row:Filter").unwrap())); + assert!(viewport.contains_rect(scenario::rect_of("dialog:section:Favorites").unwrap())); + assert!(!h.app.params.as_ref().unwrap().adding); + assert!(h.ctx.memory(|m| m.focused().is_none())); + scroll_card(&mut h, -400.0); + let offset = scenario::count_of("dialog:body:scroll_y").unwrap(); + assert!(offset > 0.0); + h.frames(8); + assert_eq!(scenario::count_of("dialog:body:scroll_y"), Some(offset)); + h.step(&json!({"click":{"handle":"params:close"}})).unwrap(); + h.app.start("parameters.change"); + h.frames(8); + assert_card_top(); + // Put the add prompt at the bottom edge. The taller draft must be revealed only + // after clicking it, with focus on Name even inside the horizontal table scroller. + let prompt = scenario::rect_of("dialog:table:user:add").unwrap(); + scroll_card(&mut h, viewport.bottom() - prompt.bottom() - 1.0); + let before = scenario::count_of("dialog:body:scroll_y").unwrap(); + h.step(&json!({"click":{"handle":"dialog:table:user:add"}})).unwrap(); + h.frames(40); + assert!(h.app.params.as_ref().unwrap().adding); + let name = scenario::handle_at("param:new:name").unwrap(); + let focused = h.ctx.memory(|m| m.focused()).and_then(|id| h.ctx.read_response(id)).unwrap(); + assert!(focused.rect.contains(name)); + assert!(scenario::rect_of("dialog:body:viewport").unwrap().contains_rect(focused.rect)); + assert!(scenario::count_of("dialog:body:scroll_y").unwrap() > before); + h.step(&json!({"text":"pitch"})).unwrap(); + assert_eq!(h.app.params.as_ref().unwrap().new_name, "pitch"); + h.step(&json!({"key":"Enter"})).unwrap(); + assert_eq!(h.app.session.doc.param("pitch").unwrap().expr, "10 mm"); + } +} + +#[test] +fn configuration_and_appearance_open_at_top_and_retain_user_scroll() { + for command in ["config.table", "appearance.assign"] { + let mut h = fixture(); + h.call("ui.resize", json!({"width":1600,"height":650})); + if command == "config.table" { + h.app.run("config.configure", json!({"params":["width"]})).unwrap(); + for i in 0..20 { + h.app.run("config.row", json!({"name":format!("Row{i}"),"from":"Default"})).unwrap(); + } + } + h.app.start(command); + h.frames(8); + assert_card_top(); + scroll_card(&mut h, -250.0); + let offset = scenario::count_of("dialog:body:scroll_y").unwrap(); + assert!(offset > 0.0, "{command} fixture must overflow"); + h.frames(8); + assert_eq!(scenario::count_of("dialog:body:scroll_y"), Some(offset)); + h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap(); + h.app.start(command); + h.frames(8); + assert_card_top(); + } +} + +#[test] +fn parameters_header_drag_retains_offset_and_bounds_the_card() { + for layout in [LayoutMode::Docked, LayoutMode::Floating] { + let mut h = fixture(); + h.call("ui.set", json!({"layout":layout})); + h.app.start("parameters.change"); + h.frames(6); + let rest = scenario::rect_of("dialog:header").unwrap(); + let title = scenario::handle_at("params:title").unwrap(); + h.call("ui.drag", json!({"x0":title.x,"y0":title.y,"x1":title.x-180.0,"y1":title.y+100.0,"steps":8})); + h.frames(6); + let moved = scenario::rect_of("dialog:header").unwrap(); + assert!((moved.min - rest.min - egui::vec2(-180.0, 100.0)).length() < 2.0, "{layout:?}: {rest:?} -> {moved:?}"); + h.frames(6); + assert_eq!(moved, scenario::rect_of("dialog:header").unwrap(), "offset survives idle frames"); + for delta in [egui::vec2(3000.0, 3000.0), egui::vec2(-3000.0, -3000.0)] { + let title = scenario::handle_at("params:title").unwrap(); + h.call("ui.drag", json!({"x0":title.x,"y0":title.y,"x1":title.x+delta.x,"y1":title.y+delta.y,"steps":8})); + h.frames(6); + let card = scenario::rect_of("dialog:header").unwrap().union(scenario::rect_of("dialog:footer").unwrap()); + let viewport = crate::shell::content_rect(&h.app, h.app.viewport.rect.unwrap()); + assert!(viewport.expand(2.0).contains_rect(card), "{layout:?}: {card:?} outside {viewport:?}"); + assert!(h.app.params.is_some()); + } + } } diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index dfbc92b08..f628b29e9 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -70,7 +70,7 @@ pub fn palette_bar(app: &mut SolveApp, ui: &mut egui::Ui) { ui, |ui| { ui.horizontal_centered(|ui| { - ui.label(RichText::new("›").strong().color(t.accent)); + ui.label(RichText::new(">").strong().color(t.accent)); let r = ui.add( egui::TextEdit::singleline(&mut app.palette.text) // The JSON example keeps its braces here rather than in the catalog, so the diff --git a/crates/ui-egui/src/params_dialog.rs b/crates/ui-egui/src/params_dialog.rs index 20aeaded5..654792d66 100644 --- a/crates/ui-egui/src/params_dialog.rs +++ b/crates/ui-egui/src/params_dialog.rs @@ -24,6 +24,7 @@ const NEW_EXPR: &str = "10 mm"; #[derive(Default)] pub struct ParamsDialog { pub filter: String, + reset_scroll: bool, /// Expressions being edited, by parameter name. pub editing: std::collections::BTreeMap, /// Comments being edited, by parameter name. @@ -31,6 +32,8 @@ pub struct ParamsDialog { /// A parameter being renamed: (old name, new name). pub renaming: Option<(String, String)>, pub new_name: String, + pub adding: bool, + pub focus_new: bool, pub new_unit: usize, pub new_expr: String, pub new_comment: String, @@ -50,7 +53,7 @@ pub struct ParamsDialog { impl ParamsDialog { pub fn new() -> Self { - ParamsDialog { new_expr: NEW_EXPR.into(), ..Default::default() } + ParamsDialog { reset_scroll: true, new_expr: NEW_EXPR.into(), ..Default::default() } } /// The command the live preview should run (a valid expression being edited). pub fn preview_commands(&self) -> Option> { @@ -149,10 +152,11 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { let docked = egui::pos2(side.anchor_x(viewport), top); let moved = crate::frame::dock_offset(ctx, "PARAMETERS"); let anchor = crate::frame::offset_anchor(docked, moved, viewport, side); - let title = crate::i18n::tr_label("PARAMETERS"); + let title = crate::i18n::tr_label("Parameters"); let panel = ui_kit::Panel::new(title, egui::Id::new("sc_params_dialog"), anchor, viewport, side, ui_kit::Panel::feature_frame(ctx, app.ui.layout, side)) - .wide(); + .wide() + .reset_scroll(d.reset_scroll); let panel = if side == crate::frame::Side::Left { let available = palette.map_or(viewport.width(), |r| (r.left() - viewport.left() - crate::theme::Tokens::get().space_8).max(0.0)); panel.width((crate::theme::Tokens::get().form_card_width * 3.0).min(available)) @@ -188,20 +192,20 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui_kit::search_field(ui, id, &mut d.filter, "Filter"); }); ui.horizontal_wrapped(|ui| { - if ui_kit::button(ui, crate::i18n::tr_label("Import…"), ui_kit::Button::Normal) + if ui_kit::icon_label_button(ui, "Import…", "import_tray", true, false) .on_hover_text(crate::i18n::tr_label("CSV or JSON: updates existing parameters, adds new ones")) .clicked() { app.pick_open_command("parameters.import", json!({}), &[]); } for (label, ext) in [("Export CSV…", "csv"), ("Export JSON…", "json")] { - if ui_kit::button(ui, crate::i18n::tr_label(label), ui_kit::Button::Normal).clicked() { + if ui_kit::icon_label_button(ui, label, "export_tray", true, false).clicked() { app.pick_save_command(&format!("parameters.{ext}"), &[ext], "parameters.export", json!({"format": ext})); } } }); if let Some(error) = &d.error { - ui_kit::text(ui, error, ui_kit::Text::Report("parameters_error", true)); + ui_kit::text(ui, error, ui_kit::Text::Error("parameters_error")); } let filter = d.filter.to_ascii_lowercase(); let visible: Vec<_> = all @@ -215,12 +219,11 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { .collect(); let favorites: Vec<_> = visible.iter().copied().filter(|r| r.favorite).collect(); if !favorites.is_empty() { - ui_kit::section(ui, "favorites", "Favorites", true, |ui| table(app, ui, &mut d, &favorites, "fav")); + ui_kit::section_count(ui, "favorites", "Favorites", true, Some(favorites.len()), |ui| table(app, ui, &mut d, &favorites, "fav")); } - ui_kit::section(ui, "users", "User Parameters", true, |ui| { - let users: Vec<_> = visible.iter().copied().filter(|r| r.source == "user").collect(); + let users: Vec<_> = visible.iter().copied().filter(|r| r.source == "user").collect(); + ui_kit::section_count(ui, "users", "User Parameters", true, Some(users.len()), |ui| { table(app, ui, &mut d, &users, "user"); - add_row(app, ui, &mut d); }); ui_kit::section(ui, "models", "Model Parameters", true, |ui| { let mut groups = Vec::new(); @@ -229,14 +232,22 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { groups.push(r.group.clone()); } } - for group in groups { - let members: Vec<_> = visible.iter().copied().filter(|r| r.source != "user" && r.group == group).collect(); - ui_kit::section(ui, ("pgroup", &group), &group, true, |ui| table(app, ui, &mut d, &members, &group)); - } + ui.scope(|ui| { + ui.spacing_mut().indent = crate::theme::Tokens::get().space_14; + ui.indent("model_groups", |ui| { + for group in groups { + let members: Vec<_> = visible.iter().copied().filter(|r| r.source != "user" && r.group == group).collect(); + ui_kit::section_count(ui, ("pgroup", &group), &group, true, Some(members.len()), |ui| { + table(app, ui, &mut d, &members, &group) + }); + } + }); + }); }); ui_kit::ComputeStatus { text: None, busy: false, applying: false } }, ); + d.reset_scroll = false; close = closed || matches!(action, ui_kit::Action::Ok | ui_kit::Action::Cancel); }); // Each cell owns fresh Enter from raw events. The panel itself must not submit on @@ -281,13 +292,15 @@ fn new_check(app: &mut SolveApp, d: &mut ParamsDialog, unit: &str) -> Result = UNITS.iter().map(|unit| unit_label(unit)).collect(); let columns = [ - Column::new("", 1.6), - Column::new("Name", 1.1), - Column::new("Unit", 0.65).min_content_width(ui_kit::ContentWidth::dropdown(ui, &units)), - Column::new("Expression", 1.6), - Column::new("Value", 1.2), - Column::new("Comment", 1.5), - Column::new("Actions", 0.7).min_content_width(ui_kit::ContentWidth::button(ui, "Delete")), + Column::new("", 0.0).min_content_width(crate::theme::Tokens::get().space_24 * 3.0), + Column::new("Name", 1.1).flex(), + Column::new("Unit", 0.65).min_content_width( + ui_kit::ContentWidth::dropdown(ui, &units).max(crate::theme::Tokens::get().space_24 * 3.0 + crate::theme::Tokens::get().space_6), + ), + Column::new("Expression", 1.5).flex(), + Column::new("Value", 1.1).flex(), + Column::new("Comment", 1.2).flex(), + Column::new("Actions", 0.0).icon_only().min_content_width(ui_kit::table_row_height()), ]; ui_kit::table(ui, salt, &columns, crate::i18n::tr("manage.empty"), |ui, table| { for (index, r) in rows.iter().enumerate() { @@ -298,16 +311,18 @@ fn table(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, rows: &[&R table.row_visible(ui, &r.name, false, busy, |row| { row.cell(|ui| { let star = if r.favorite { "★" } else { "☆" }; - if ui_kit::button(ui, star, ui_kit::Button::Small).on_hover_text(crate::i18n::tr_label("Favourite")).clicked() { + ui.spacing_mut().item_spacing.x = 0.0; + let favorite = ui_kit::compact_button(ui, star, "Favourite", true, r.favorite); + crate::scenario::publish_handle(&format!("param:star:{}", r.name), favorite.rect.center()); + if favorite.clicked() { d.error = app.run("parameters.favorite", json!({"name": r.name, "favorite": !r.favorite})).err(); } if salt == "user" { for (glyph, tip, neighbour, side) in [ - ("▲", "Move up", index.checked_sub(1).and_then(|i| rows.get(i)), "before"), - ("▼", "Move down", rows.get(index + 1), "after"), + (ui_kit::MOVE_UP, "Move up", index.checked_sub(1).and_then(|i| rows.get(i)), "before"), + (ui_kit::MOVE_DOWN, "Move down", rows.get(index + 1), "after"), ] { - let response = - ui_kit::button(ui, glyph, ui_kit::Button::Enabled(neighbour.is_some())).on_hover_text(crate::i18n::tr_label(tip)); + let response = ui_kit::compact_button(ui, glyph, tip, neighbour.is_some(), false); crate::scenario::publish_handle(&format!("param:{side}:{}", r.name), response.rect.center()); if response.clicked() && let Some(neighbour) = neighbour @@ -334,7 +349,8 @@ fn table(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, rows: &[&R } } _ => { - let response = ui_kit::text(ui, &r.name, ui_kit::Text::Cell).on_hover_text(crate::i18n::tr_label("Double-click to rename")); + let response = + ui_kit::text(ui, &r.name, ui_kit::Text::NameCell(false)).on_hover_text(crate::i18n::tr_label("Double-click to rename")); crate::scenario::publish_handle(&format!("param:name:{}", r.name), response.rect.center()); if response.double_clicked() { d.renaming = Some((r.name.clone(), r.name.clone())); @@ -352,7 +368,7 @@ fn table(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, rows: &[&R d.error = app.run("parameters.change", json!({"name":r.name,"expression":r.expression,"unit":unit})).err(); } } else { - ui_kit::text(ui, unit_label(&r.unit), ui_kit::Text::Cell); + ui_kit::text(ui, unit_label(&r.unit), ui_kit::Text::MonoCell); } }); let mut expression = d.editing.get(&r.name).cloned().unwrap_or_else(|| r.expression.clone()); @@ -394,7 +410,7 @@ fn table(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, rows: &[&R (Some(Ok(value)), _) => (value.clone(), false), (None, None) => (show_value(r), false), }; - ui_kit::text(ui, &text, ui_kit::Text::Report(&format!("value:{}", r.name), error)).on_hover_text(&text); + ui_kit::text(ui, &text, ui_kit::Text::Value(&format!("value:{}", r.name), error)).on_hover_text(&text); }); row.cell(|ui| { let mut comment = d.comments.get(&r.name).cloned().unwrap_or_else(|| r.comment.clone()); @@ -413,12 +429,21 @@ fn table(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog, rows: &[&R } }); row.cell(|ui| { - if r.source == "user" && ui_kit::button(ui, crate::i18n::tr_label("Delete"), ui_kit::Button::Small).clicked() { + if r.source == "user" && ui_kit::bin_button(ui, "Delete").clicked() { d.error = app.run("parameters.delete", json!({"name":r.name})).err(); } }); }); } + if salt == "user" { + if d.adding { + ui.push_id("parameter_draft", |ui| add_row(app, ui, table, d)); + } + if table.add_prompt(ui, "Add parameter", "Add parameter").clicked() { + d.adding = true; + d.focus_new = true; + } + } }); } @@ -442,39 +467,77 @@ fn enter_for(ui: &mut egui::Ui, focused: bool) -> bool { } /// The add row, one cell per column of the user table it ends. -fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog) { - let mut submit = false; +fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, table: &mut ui_kit::Table<'_>, d: &mut ParamsDialog) { let name_id = ui.make_persistent_id("pnew_name"); let expr_id = ui.make_persistent_id("pnew_expr"); let comment_id = ui.make_persistent_id("pnew_comment"); - let focused_id = ui.memory(|m| [name_id, expr_id, comment_id].into_iter().find(|id| m.has_focus(*id))); - let name = ui_kit::row(ui, "Name", |ui| ui_kit::cell_editor(ui, name_id, &mut d.new_name, "new parameter", false)); - crate::scenario::publish_handle("param:new:name", name.rect.center()); - let units: Vec<_> = UNITS.iter().map(|u| unit_label(u)).collect(); - let unit_response = ui_kit::row(ui, "Unit", |ui| ui_kit::dropdown(ui, "pnew_unit", &mut d.new_unit, &units)); - crate::scenario::publish_handle("param:new:unit", unit_response.rect.center()); - let unit = UNITS.get(d.new_unit).copied().unwrap_or("mm"); - let invalid = new_check(app, d, unit).is_err(); - ui_kit::row(ui, "Expression", |ui| { - let response = ui_kit::cell_editor(ui, expr_id, &mut d.new_expr, "Expression", invalid); - crate::scenario::publish_handle("param:new:expression", response.rect.center()); - let completed = complete(ui, &response, &mut d.new_expr); - submit = !completed && enter_for(ui, focused_id.is_some()); + let focused_id = ui.memory(|m| [name_id, expr_id, comment_id].into_iter().find(|id| m.has_focus(*id) || m.had_focus_last_frame(*id))); + let menu_was_open = egui::Popup::is_any_open(ui.ctx()); + let mut submit = false; + let mut left = false; + let mut discard = false; + let reveal = d.focus_new; + let response = table.row(ui, "new", false, |row| { + row.cell(|_| {}); + row.cell(|ui| { + let response = ui_kit::cell_editor(ui, name_id, &mut d.new_name, "new parameter", false); + crate::scenario::publish_handle("param:new:name", response.rect.center()); + if d.focus_new { + response.request_focus(); + d.focus_new = false; + } + left |= response.lost_focus(); + }); + row.cell(|ui| { + let units: Vec<_> = UNITS.iter().map(|u| unit_label(u)).collect(); + let response = ui_kit::dropdown(ui, "pnew_unit", &mut d.new_unit, &units); + crate::scenario::publish_handle("param:new:unit", response.rect.center()); + }); + let unit = UNITS.get(d.new_unit).copied().unwrap_or("mm"); + row.cell(|ui| { + let invalid = new_check(app, d, unit).is_err(); + let response = ui_kit::cell_editor(ui, expr_id, &mut d.new_expr, "Expression", invalid); + crate::scenario::publish_handle("param:new:expression", response.rect.center()); + let completed = complete(ui, &response, &mut d.new_expr); + submit = !completed && enter_for(ui, focused_id.is_some()); + left |= !completed && response.lost_focus(); + }); + row.cell(|ui| { + let live = new_check(app, d, unit); + let (value, invalid) = match live { + Ok(v) => (v, false), + Err(e) => (e, true), + }; + ui_kit::text(ui, &value, ui_kit::Text::Value("new_value", invalid)).on_hover_text(&value); + }); + row.cell(|ui| { + let response = ui_kit::cell_editor(ui, comment_id, &mut d.new_comment, "Comment", false); + crate::scenario::publish_handle("param:new:comment", response.rect.center()); + left |= response.lost_focus(); + submit |= enter_for(ui, focused_id.is_some()); + }); + row.cell(|ui| { + discard = ui_kit::bin_button(ui, "Delete").clicked(); + }); }); + if reveal { + table.reveal_row(response.rect); + } + let unit = UNITS.get(d.new_unit).copied().unwrap_or("mm"); let live = new_check(app, d, unit); - let (text, error) = match &live { - Ok(value) => (value, false), - Err(message) => (message, true), - }; - ui_kit::row(ui, "Value", |ui| ui_kit::text(ui, text, ui_kit::Text::Report("new_value", error)).on_hover_text(text)); - let comment = ui_kit::row(ui, "Comment", |ui| ui_kit::cell_editor(ui, comment_id, &mut d.new_comment, "Comment", false)); - crate::scenario::publish_handle("param:new:comment", comment.rect.center()); - // Enter from name/comment owns submission too, not the panel footer. - submit |= enter_for(ui, focused_id.is_some()); let valid = !d.new_name.trim().is_empty() && live.is_ok(); - if ui_kit::button(ui, "Add", ui_kit::Button::Enabled(valid)).clicked() || submit { - if let Err(error) = &live { - d.error = Some(error.clone()); + crate::scenario::publish_count("param:new:valid", f64::from(valid)); + let abandoned = d.new_name.trim().is_empty() + && !menu_was_open + && ui.input(|i| i.pointer.any_click() && i.pointer.interact_pos().is_some_and(|p| !response.rect.contains(p))); + if discard || abandoned { + d.adding = false; + d.new_name.clear(); + d.new_comment.clear(); + d.new_expr = NEW_EXPR.into(); + } else if submit || (left && valid) { + if let Err(error) = live { + d.error = Some(error); if let Some(id) = focused_id { ui.memory_mut(|m| m.request_focus(id)); } @@ -484,10 +547,11 @@ fn add_row(app: &mut SolveApp, ui: &mut egui::Ui, d: &mut ParamsDialog) { match app.run("parameters.add", params) { Ok(_) => { d.new_name.clear(); - d.new_expr = NEW_EXPR.into(); d.new_comment.clear(); + d.new_expr = NEW_EXPR.into(); d.error = None; - name.request_focus(); + d.adding = true; + d.focus_new = submit; } Err(error) => { d.error = Some(error); @@ -670,6 +734,8 @@ mod tests { fn the_window_does_not_re_evaluate_every_frame() { let mut h = big_design(); h.step(&json!({"start": "parameters.change"})).unwrap(); + // The redesign only checks a new expression while its inline draft is open. + h.app.params.as_mut().unwrap().adding = true; h.frames(30); let d = h.app.params.as_ref().unwrap(); assert_eq!((d.lists, d.checks), (1, 1), "30 frames of an unchanged design"); @@ -685,4 +751,24 @@ mod tests { let d = h.app.params.as_ref().unwrap(); assert!(d.listed.as_ref().unwrap().1.iter().any(|r| r.name == "p1" && r.comment == "hello")); } + + #[test] + fn model_groups_and_user_tables_fit_their_viewports() { + for screen_width in [760, 900, 1100] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width": screen_width, "height": 1200})); + h.app.run("solid.box", json!({"length": 10, "width": 20, "height": 30})).unwrap(); + h.app.run("solid.box", json!({"length": 40, "width": 50, "height": 60})).unwrap(); + h.app.run("parameters.add", json!({"name": "width", "expression": "10 mm"})).unwrap(); + h.app.run("parameters.favorite", json!({"name": "width", "favorite": true})).unwrap(); + h.app.start("parameters.change"); + h.frames(6); + for id in ["fav", "user", "Box1", "Box2"] { + let viewport = crate::scenario::rect_of(&format!("dialog:table:{id}:viewport")).unwrap(); + let content = crate::scenario::count_of(&format!("dialog:table:{id}:content_width")).unwrap(); + assert!(content <= f64::from(viewport.width().ceil()), "{id} on {screen_width} screen: {content} outside {viewport:?}"); + } + } + } } diff --git a/crates/ui-egui/src/plugins.rs b/crates/ui-egui/src/plugins.rs index 4d9bf4440..697b3e738 100644 --- a/crates/ui-egui/src/plugins.rs +++ b/crates/ui-egui/src/plugins.rs @@ -143,7 +143,7 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) { let path = dir.display().to_string(); ui.add(egui::Label::new(RichText::new(crate::i18n::format("ui.plugins_note", &[("path", &path)])).size(t.font_small).color(t.text_dim)).wrap()); ui.add_space(8.0); - if ui.button(crate::i18n::tr_label("Show in folder")).clicked() { + if crate::ui_kit::button(ui, crate::i18n::tr_label("Show in folder"), crate::ui_kit::Button::Normal).clicked() { // `show_in_folder` opens the parent of the path it is given, so the argument is a name // inside the plugins directory (it need not exist). if let Err(e) = std::fs::create_dir_all(&dir) { @@ -160,7 +160,7 @@ pub fn page(app: &mut SolveApp, ui: &mut egui::Ui) { for plugin in &plugins { let mut on = enabled(app, &plugin.id); ui.horizontal(|ui| { - let check = ui.checkbox(&mut on, ""); + let check = crate::ui_kit::checkbox(ui, "", &mut on); crate::scenario::publish_handle(&format!("prefs:plugin:{}", plugin.id), check.rect.center()); if check.changed() { if on { diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 350de46b4..a646d3be5 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -306,13 +306,13 @@ macro_rules! preference_settings { (@control $app:ident, $ui:ident, $field:ident, enabled_slider($enabled:ident, $label:literal, $range:expr, $step:expr, $format:expr)) => { ui_kit::row($ui, $app.tr_label($label), |ui| { ui.add_enabled_ui($app.preferences.$enabled, |ui| { - ui_kit::formatted_slider(ui, &mut $app.preferences.$field, $range, $step, $format) + ui_kit::slider(ui, &mut $app.preferences.$field, $range, ui_kit::Slider { step: Some($step), format: $format, ..Default::default() }) }).inner }) }; (@control $app:ident, $ui:ident, $field:ident, slider($label:literal, $range:expr, $step:expr, $format:expr, $rect:literal)) => { ui_kit::row($ui, $app.tr($label), |ui| { - let response = ui_kit::formatted_slider(ui, &mut $app.preferences.$field, $range, $step, $format); + let response = ui_kit::slider(ui, &mut $app.preferences.$field, $range, ui_kit::Slider { step: Some($step), format: $format, ..Default::default() }); crate::scenario::publish_rect($rect, response.rect); response }) @@ -1235,7 +1235,12 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { ui_kit::checkbox(ui, crate::i18n::tr_label("Invert"), reverse); } if let Some(speed) = app.preferences.space_mouse_axis_speed.get_mut(axis) { - ui_kit::formatted_slider(ui, speed, 0.0..=3.0, 0.05, |v| format!("{v:.2}×")); + ui_kit::slider( + ui, + speed, + 0.0..=3.0, + ui_kit::Slider { step: Some(0.05), format: |v| format!("{v:.2}×"), ..Default::default() }, + ); } }); }); @@ -1271,12 +1276,11 @@ fn page(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { if let Some(calibration) = device.and_then(|device| app.preferences.space_mouse_calibrations.get_mut(&device)) { ui_kit::row(ui, &label, |ui| { ui.add_enabled_ui(enabled, |ui| { - ui_kit::formatted_slider( + ui_kit::slider( ui, &mut calibration.dead_zone_share, 0.0..=solidcraft_space_mouse::MAX_DEAD_ZONE_SHARE, - 0.01, - |v| format!("{:.0} %", v * 100.0), + ui_kit::Slider { step: Some(0.01), format: |v| format!("{:.0} %", v * 100.0), ..Default::default() }, ) .on_hover_text(tip); }); diff --git a/crates/ui-egui/src/space_mouse_calibration.rs b/crates/ui-egui/src/space_mouse_calibration.rs index 078b0621e..23301277e 100644 --- a/crates/ui-egui/src/space_mouse_calibration.rs +++ b/crates/ui-egui/src/space_mouse_calibration.rs @@ -25,10 +25,11 @@ const STEP_PROMPTS: [&str; 12] = [ /// The dead zone, as a share of full travel, shown as a percentage. pub(crate) fn dead_zone_slider(ui: &mut egui::Ui, share: &mut f32) -> egui::Response { - ui.add( - egui::Slider::new(share, 0.0..=solidcraft_space_mouse::MAX_DEAD_ZONE_SHARE) - .step_by(0.01) - .custom_formatter(|v, _| format!("{:.0} %", v * 100.0)), + crate::ui_kit::slider( + ui, + share, + 0.0..=solidcraft_space_mouse::MAX_DEAD_ZONE_SHARE, + crate::ui_kit::Slider { step: Some(0.01), format: |v| format!("{:.0} %", v * 100.0), ..Default::default() }, ) } @@ -118,7 +119,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { ui.label(egui::RichText::new(app.tr_label(axis)).strong()); } ui.add_space(6.0); - ui.add(egui::ProgressBar::new(progress as f32).text(counter)); + crate::ui_kit::progress(ui, "space_mouse_calibration", progress as f32); + ui.label(counter); if let Some(Ok(calibration)) = result { ui.add_space(6.0); dead_zone_pads(ui, &Calibration { dead_zone_share: dead_zone, ..calibration }, raw); @@ -132,10 +134,13 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { }); ui.add_space(6.0); ui.horizontal(|ui| { - back = ui.add_enabled(stage != Stage::Rest, egui::Button::new(app.tr("ui.back"))).clicked(); - over = matches!(result, Some(Err(_))) && ui.button(app.tr("ui.start_over")).clicked(); - cancel = ui.button(app.tr("ui.cancel")).clicked(); - save = matches!(result, Some(Ok(_))) && ui.button(app.tr("ui.save")).clicked(); + back = ui + .add_enabled_ui(stage != Stage::Rest, |ui| crate::ui_kit::button(ui, app.tr("ui.back"), crate::ui_kit::Button::Normal)) + .inner + .clicked(); + over = matches!(result, Some(Err(_))) && crate::ui_kit::button(ui, app.tr("ui.start_over"), crate::ui_kit::Button::Normal).clicked(); + cancel = crate::ui_kit::button(ui, app.tr("ui.cancel"), crate::ui_kit::Button::Normal).clicked(); + save = matches!(result, Some(Ok(_))) && crate::ui_kit::button(ui, app.tr("ui.save"), crate::ui_kit::Button::Normal).clicked(); }); }); if cancel { diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index a53faf6b7..9f0634904 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -270,6 +270,12 @@ pub struct Tokens { pub font_display: f32, /// Height of dense form controls and rows. pub control_height: f32, + /// Card text, hint, primary and validation colours. + pub form_ink: Color32, + pub form_dim: Color32, + pub form_primary: Color32, + pub form_error: Color32, + pub form_error_fill: Color32, /// Corner radius of dense form controls and actions. pub control_radius: u8, /// Width of the dense form label column. diff --git a/crates/ui-egui/src/theme_files.rs b/crates/ui-egui/src/theme_files.rs index cecd28ff6..b5820c045 100644 --- a/crates/ui-egui/src/theme_files.rs +++ b/crates/ui-egui/src/theme_files.rs @@ -86,7 +86,7 @@ macro_rules! theme_keys { radius_lg: _, radius_xl: _, font_badge: _, font_micro: _, font_panel: _, font_small: _, font_caption: _, font_body: _, font_label: _, font_button: _, font_heading: _, font_triad: _, font_compass: _, font_subtitle: _, font_intro: _, font_article_heading: _, font_title: _, font_display: _, - control_height: _, control_radius: _, form_label_width: _, form_gap_y: _, form_footer_height: _, form_header_height: _, + control_height: _, control_radius: _, form_label_width: _, form_gap_y: _, form_footer_height: _, form_header_height: _, form_card_width: _, form_icon_size: _, form_close_size: _, form_inset: _, form_icon_inset: _, form_section_icon_size: _, form_checkbox_height: _, form_button_height: _, sketch_palette_width: _, sketch_mode_size: _, sketch_mode_radius: _, sketch_mode_border: _, sketch_palette_alpha: _, sketch_mode_tint: _, sketch_footer_icon_size: _, font_section_tracking: _, @@ -110,7 +110,7 @@ theme_keys! { sketch_construction, sketch_centerline, bend_up, bend_down, interference, app_bar_separator, surface_accent, mesh_accent, form_accent, render_accent, on_accent, agent_ok, agent_busy, app_bar_hover_subtle, app_bar_hover_button, app_bar_hover_strong, app_bar_tab_active, - dialog_body, dialog_footer, dialog_rule, control_fill, control_border, dialog_label, selected_ink, selected_bg, + form_ink, form_dim, form_primary, form_error, form_error_fill, dialog_body, dialog_footer, dialog_rule, control_fill, control_border, dialog_label, selected_ink, selected_bg, ], many: [triad, gizmo, continuity, app_bar_icon, logo], icons_one: [ diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index 769e4a84d..bdb8e2db1 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -515,10 +515,7 @@ fn timeline_group_name( let left = rect.left() + 38.0 + offset; let edit_rect = Rect::from_min_max(pos2(left, rect.top() + 1.0), pos2(rect.right() - 3.0, rect.bottom() - 1.0)); let edit_id = ui.id().with(("timeline_group_rename", group.id)); - let response = ui.put( - edit_rect, - egui::TextEdit::singleline(&mut rename.text).id(edit_id).frame(egui::Frame::NONE).text_color(t.text).vertical_align(egui::Align::Center), - ); + let response = crate::ui_kit::inline_name(ui, edit_rect, edit_id, &mut rename.text); crate::scenario::publish_handle(&format!("timeline-folder-rename:{}", group.name), edit_rect.center()); if !rename.focused { if let Some(mut state) = egui::TextEdit::load_state(ui.ctx(), edit_id) { @@ -573,12 +570,7 @@ fn vertical_group_row( } let offset = depth as f32 * 14.0; let centre = pos2(rect.left() + 9.0 + offset, rect.center().y); - let arrow = if open { - vec![centre + vec2(-4.0, -2.0), centre + vec2(4.0, -2.0), centre + vec2(0.0, 3.0)] - } else { - vec![centre + vec2(-2.0, -4.0), centre + vec2(-2.0, 4.0), centre + vec2(3.0, 0.0)] - }; - ui.painter().add(egui::Shape::convex_polygon(arrow, t.text_dim, Stroke::NONE)); + crate::ui_kit::disclosure(ui.painter(), centre, open, t.text_dim); let icon = Rect::from_center_size(pos2(rect.left() + 27.5 + offset, rect.center().y), vec2(17.0, 17.0)); icons::paint(ui.painter(), icon, "folder", t.icon, t.icon_fill, t.accent); let renaming = timeline_group_name(app, ui, group, rect, offset, &t); @@ -725,7 +717,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui) { ui.painter().rect_filled(rect, 3.0, background); } if has_patterns { - crate::icons::glyphs::disclosure(ui.painter(), fold_rect.shrink(3.0), patterns_open, t.text_dim); + crate::ui_kit::disclosure(ui.painter(), fold_rect.center(), patterns_open, t.text_dim); crate::scenario::publish_handle(&format!("timeline-sketch-fold:{name}"), fold_rect.center()); } let icon_rect = diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 022495a59..b0111f1b5 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -911,8 +911,8 @@ fn ribbon_tabs(app: &mut SolveApp, ui: &mut egui::Ui, row: Rect) { } /// The dropdown chevron every ribbon menu shares. -fn chevron(painter: &egui::Painter, at: egui::Pos2, ink: Color32) { - crate::icons::paint_ink(painter, Rect::from_center_size(at, vec2(10.0, 10.0)), "chevron", ink); +fn dropdown_arrow(painter: &egui::Painter, at: egui::Pos2, ink: Color32) { + crate::ui_kit::dropdown_indicator(painter, Rect::from_center_size(at, vec2(10.0, 10.0)), ink); } /// The label colour on a selected tab or open section. @@ -968,7 +968,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let label_width = painter.layout_no_wrap(label.to_string(), FontId::proportional(crate::theme::Tokens::get().font_small), t.text_dim).size().x; ribbon_text(ui, pos2(ws.center().x - 6.0, ws.top() + 89.0), label, t.font_small, t.text_dim, false); - chevron(&painter, pos2(ws.center().x - 6.0 + label_width / 2.0 + 7.0, ws.top() + 89.5), t.text_dim); + dropdown_arrow(&painter, pos2(ws.center().x - 6.0 + label_width / 2.0 + 7.0, ws.top() + 89.5), t.text_dim); if wresp.on_hover_text(app.tr("ui.change_workspace")).clicked() { crate::context_menu::toggle_for(app, ws, ws.left_bottom(), crate::context_menu::Target::Workspace); } @@ -1089,7 +1089,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let acc = command_accent(c.icon); icons::paint(&painter, Rect::from_center_size(br.center() - vec2(0.0, 3.0), vec2(26.0, 26.0)), c.icon, t.icon, t.icon_fill, acc); } - chevron(&painter, pos2(br.center().x, br.bottom() - 3.0), t.text_dim); + dropdown_arrow(&painter, pos2(br.center().x, br.bottom() - 3.0), t.text_dim); let tip = format!("{} ({})", app.tr_label(panel), shown.len().max(cmds.len())); if fresp.on_hover_text(tip).clicked() && enabled_panel { ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("sc_panel_open"), popup_id)); @@ -1162,7 +1162,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let title_y = whole.top() + 39.0; let galley = ribbon_button_galley(&painter, app.tr_label(f.label), ar.width() - 16.0, t.text); painter.galley(pos2(ar.center().x - 4.0, title_y - galley.size().y / 2.0), galley, t.text); - chevron(&painter, pos2(ar.right() - 6.0, title_y + 0.5), t.text_dim); + dropdown_arrow(&painter, pos2(ar.right() - 6.0, title_y + 0.5), t.text_dim); arrow.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, app.tr_label(f.label))); egui::Popup::menu(&arrow).show(|ui| { let variants: Vec<_> = f.commands.iter().filter_map(|id| solidcraft_engine::find_command(id)).collect(); @@ -1257,7 +1257,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { let ink = if panel_open { selected_ink(&accent) } else { t.text_dim }; ribbon_text(ui, lr.center() - vec2(if finish { 0.0 } else { 6.0 }, 0.0), &label, t.font_caption, ink, panel_open || hot); if !finish { - chevron(&painter, pos2(lr.center().x + label_width / 2.0 + 1.0, lr.center().y + 0.5), ink); + dropdown_arrow(&painter, pos2(lr.center().x + label_width / 2.0 + 1.0, lr.center().y + 0.5), ink); } if lresp.clicked() && enabled_panel { ui.ctx().data_mut(|d| { @@ -1382,18 +1382,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) { } for c in cmds { let info = c.info(&app.session); - let response = ui - .add_enabled_ui(info.enabled, |ui| { - let icon = ui.id().with(("overflow_icon", c.id)); - let row = egui::Button::new((egui::Atom::custom(icon, vec2(16.0, 16.0)), c.label)) - .shortcut_text(c.shortcut.unwrap_or("")) - .atom_ui(ui); - if let Some(rect) = row.rect(icon) { - icons::paint_icon(ui.painter(), rect, c.icon, if info.enabled { 1.0 } else { 0.35 }); - } - row.response - }) - .inner; + let response = crate::ui_kit::command_menu_button(ui, c.id, c.label, c.icon, c.shortcut.unwrap_or(""), info.enabled); crate::scenario::publish_handle(&format!("toolbar:{}", c.id), response.rect.center()); if response.clicked() { app.start(c.id); @@ -1793,10 +1782,10 @@ fn drag_ghost(ctx: &egui::Context, id: &str, at: egui::Pos2, removing: bool) { } /// The SELECT panel: what a click in the view picks. -fn selection_filter(app: &mut SolveApp, ui: &mut egui::Ui) { +pub(crate) fn selection_filter(app: &mut SolveApp, ui: &mut egui::Ui) { let t = Tokens::get(); ui.label(egui::RichText::new(crate::i18n::tr_label("Selection filter")).color(t.text_dim).size(t.font_small)); - ui.checkbox(&mut app.ui.pick_bodies, crate::i18n::tr_label("Select bodies (a face picks its body)")); + crate::ui_kit::checkbox(ui, crate::i18n::tr_label("Select bodies (a face picks its body)"), &mut app.ui.pick_bodies); for (k, label) in [ ("faces", "Faces"), ("edges", "Edges"), @@ -1808,7 +1797,7 @@ fn selection_filter(app: &mut SolveApp, ui: &mut egui::Ui) { ("constraints", "Sketch constraints"), ] { let mut on = !app.ui.pick_off.iter().any(|x| x == k); - if ui.checkbox(&mut on, crate::i18n::tr_label(label)).changed() { + if crate::ui_kit::checkbox(ui, crate::i18n::tr_label(label), &mut on).changed() { app.ui.pick_off.retain(|x| x != k); if !on { app.ui.pick_off.push(k.to_string()); @@ -1828,7 +1817,7 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) { } // A dimension value that is taking the keyboard: letters belong to it (a parameter name // starting with L or D), even on the frame before its field holds the focus. - if ctx.egui_wants_keyboard_input() || crate::dim_view::editing() || crate::dialogs_save_mesh::popup_open(ctx) { + if egui::Popup::is_any_open(ctx) || ctx.egui_wants_keyboard_input() || crate::dim_view::editing() || crate::dialogs_save_mesh::popup_open(ctx) { return; } let (keys, mods) = ctx.input(|i| { diff --git a/crates/ui-egui/src/toolbar_custom.rs b/crates/ui-egui/src/toolbar_custom.rs index 54eda06fe..92905e8c7 100644 --- a/crates/ui-egui/src/toolbar_custom.rs +++ b/crates/ui-egui/src/toolbar_custom.rs @@ -281,7 +281,13 @@ pub fn window(app: &mut SolveApp, ctx: &egui::Context) { let tab = app.ui.tab.clone(); let mut changes: Vec<(&'static str, bool)> = Vec::new(); let mut reset_tab = false; + let t = crate::theme::Tokens::get(); + // This long card grows as sections open. A top-left pivot keeps its controls at their + // published positions instead of shifting them after egui measures the taller content. + let origin = + egui::pos2((ctx.content_rect().center().x - t.form_card_width).max(ctx.content_rect().left()), ctx.content_rect().top() + t.space_24 * 2.0); let (closed, action) = ui_kit::Prompt::new(egui::Id::new("sc_toolbar_customize"), "settings", crate::i18n::tr_label("Customize Toolbar")) + .placed(egui::Align2::LEFT_TOP, origin) .cards(2.0) .actions("", "Close", None) .show(ctx, true, |ui| { diff --git a/crates/ui-egui/src/ui_kit/actions.rs b/crates/ui-egui/src/ui_kit/actions.rs index 32327c8b1..cf02d5bda 100644 --- a/crates/ui-egui/src/ui_kit/actions.rs +++ b/crates/ui-egui/src/ui_kit/actions.rs @@ -12,6 +12,10 @@ pub(crate) enum Action { Apply, } +/// Reorder actions are directional navigation, not disclosures. +pub(crate) const MOVE_UP: &str = "▲"; +pub(crate) const MOVE_DOWN: &str = "▼"; + /// Every enabled button shows the pointing hand on hover, as the application's other clickable /// chrome does. A disabled button stays inert and keeps the arrow. fn pointer_on_hover(ui: &Ui, response: &Response) { @@ -22,13 +26,23 @@ fn pointer_on_hover(ui: &Ui, response: &Response) { /// Icon action inside an existing rectangle. Tokens: `form_icon_inset, text, text_dim; icon palette`. pub(crate) fn icon_button_at(ui: &mut Ui, rect: egui::Rect, icon: &str, label: &str) -> Response { + icon_button_colored(ui, rect, icon, label, None) +} + +pub(super) fn icon_button_colored(ui: &mut Ui, rect: egui::Rect, icon: &str, label: &str, ink: Option) -> Response { let t = Tokens::get(); let response = ui.interact(rect, ui.make_persistent_id(("icon_button", icon, label)), egui::Sense::click()); + if response.clicked() { + response.request_focus(); + } + if response.hovered() { + ui.painter().rect_filled(rect, t.control_radius, t.hover); + } crate::icons::paint_ink( ui.painter(), rect.shrink(t.form_icon_inset), icon, - if response.hovered() || response.has_focus() { t.text } else { t.text_dim }, + ink.unwrap_or(if response.hovered() || response.has_focus() { t.form_ink } else { t.form_dim }), ); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), crate::i18n::tr_label(label))); pointer_on_hover(ui, &response); @@ -59,14 +73,14 @@ pub(crate) fn footer(ui: &mut Ui, ok_label: &str, cancel_label: &str, ok_enabled let t = Tokens::get(); let ok_enabled = ok_enabled && !ok_label.is_empty(); // The footer is a full-width band (the card has no margin of its own): its own fill, a rule - // on top, and the buttons right-aligned with 6 pt above/below and 10 pt at the sides. + // on top, and the buttons right-aligned with 10 pt above/below and 12 pt at the sides. let (band, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), t.form_footer_height), egui::Sense::hover()); - let corner = t.radius_lg.saturating_sub(1); + let corner = t.radius_xl.saturating_sub(1); ui.painter().rect_filled(band, egui::CornerRadius { nw: 0, ne: 0, sw: corner, se: corner }, t.dialog_footer); ui.painter().hline(band.x_range(), band.top(), egui::Stroke::new(1.0, t.dialog_rule)); scenario::publish_rect("dialog:footer", band); scenario::publish_count("dialog:ok:enabled", f64::from(ok_enabled && ui.is_enabled())); - let inner = band.shrink2(vec2(t.space_10, t.space_6)); + let inner = band.shrink2(vec2(t.space_12, t.space_10)); scenario::publish_rect("dialog:footer:actions", inner); let mut action = if ui.is_enabled() { keyboard(ui.ctx(), ok_enabled) } else { Action::None }; let mut actions_left = inner.right(); @@ -84,16 +98,16 @@ pub(crate) fn footer(ui: &mut Ui, ok_label: &str, cancel_label: &str, ok_enabled let text = RichText::new(crate::i18n::tr_label(label)).size(t.font_label).color(if primary && ok_enabled { t.on_accent } else if primary { - t.text_dim + t.form_dim } else { - t.text + t.form_ink }); let response = ui.add_enabled( live, egui::Button::new(if primary && ok_enabled { text.bold_face() } else { text }) .selected(marked && !primary) .fill(if primary && ok_enabled { - t.accent + t.form_primary } else if marked { t.selected_bg } else { @@ -101,11 +115,11 @@ pub(crate) fn footer(ui: &mut Ui, ok_label: &str, cancel_label: &str, ok_enabled }) .stroke(egui::Stroke::new( if primary && ok_enabled { 0.0 } else { 1.0 }, - if marked && !primary { t.accent } else { t.control_border }, + if marked && !primary { t.form_primary } else { t.control_border }, )) .wrap_mode(egui::TextWrapMode::Extend) .corner_radius(t.control_radius) - .min_size(vec2(0.0, t.form_button_height)), + .min_size(vec2(if primary { t.space_24 * 3.0 } else { 0.0 }, t.form_button_height)), ); pointer_on_hover(ui, &response); actions_left = actions_left.min(response.rect.left()); @@ -127,7 +141,7 @@ pub(crate) fn footer(ui: &mut Ui, ok_label: &str, cancel_label: &str, ok_enabled let right = (actions_left - t.space_8).max(left); let rect = egui::Rect::from_min_max(egui::pos2(left, inner.top()), egui::pos2(right, inner.bottom())); // Added after the actions, so status changes cannot change the button IDs. - ui.put(rect, egui::Label::new(RichText::new(status).medium().color(t.text_dim)).truncate()); + ui.put(rect, egui::Label::new(RichText::new(status).medium().color(t.form_dim)).truncate()); } action } @@ -165,7 +179,7 @@ pub(crate) fn button_pair(ui: &mut egui::Ui, key: &str, states: [bool; 2], butto egui::StrokeKind::Inside, ); let label = crate::i18n::tr_label(button.label); - let galley = ui.painter().layout_no_wrap(label.to_string(), egui::FontId::proportional(t.font_label), t.text); + let galley = ui.painter().layout_no_wrap(label.to_string(), egui::FontId::proportional(t.font_label), t.form_ink); let icon_width = if button.icon.is_some() { t.sketch_footer_icon_size + t.space_4 } else { 0.0 }; let left = rect.center().x - (galley.size().x + icon_width) / 2.0; let painter = ui.painter().with_clip_rect(ui.clip_rect().intersect(rect)); @@ -179,10 +193,10 @@ pub(crate) fn button_pair(ui: &mut egui::Ui, key: &str, states: [bool; 2], butto icon, t.icon, t.icon_fill, - t.accent, + t.form_primary, ); } - painter.galley(egui::pos2(left + icon_width, rect.center().y - galley.size().y / 2.0), galley, t.text); + painter.galley(egui::pos2(left + icon_width, rect.center().y - galley.size().y / 2.0), galley, t.form_ink); response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, ui.is_enabled(), on, label)); pointer_on_hover(ui, &response); crate::scenario::publish_target(&format!("{key}:{}", button.key), rect); @@ -223,7 +237,7 @@ pub(crate) fn button(ui: &mut Ui, label: impl Into, options: B #[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn primary_button(ui: &mut Ui, label: &str) -> Response { let t = Tokens::get(); - let response = ui.add(egui::Button::new(RichText::new(crate::i18n::tr_label(label)).color(t.on_accent)).fill(t.accent)); + let response = ui.add(egui::Button::new(RichText::new(crate::i18n::tr_label(label)).color(t.on_accent)).fill(t.form_primary)); pointer_on_hover(ui, &response); scenario::publish_target(&format!("dialog:button:{label}"), response.rect); response @@ -245,3 +259,96 @@ pub(crate) fn action_menu(ui: &mut Ui, label: &str, add: impl FnOnce(&mut Ui) scenario::publish_target(&format!("dialog:menu:{label}"), response.response.rect); response } + +/// Borderless compact table actions. Existing star glyphs keep their identities; arrows +/// use the kit chevron rather than a font-dependent triangle. Tokens: form_close_size, +/// space_4, control_radius, form_primary/dim/ink, selected_bg, hover, font_label. +pub(crate) fn compact_button(ui: &mut Ui, glyph: &str, tooltip: &str, enabled: bool, selected: bool) -> Response { + let t = Tokens::get(); + let arrow = matches!(glyph, MOVE_UP | MOVE_DOWN); + let width = if arrow { t.form_close_size - t.space_4 } else { t.form_close_size }; + let response = ui + .add_enabled_ui(enabled, |ui| { + let (rect, response) = ui.allocate_exact_size(vec2(width, t.form_close_size), egui::Sense::click()); + if response.hovered() || selected { + ui.painter().rect_filled(rect, t.control_radius, if selected { t.selected_bg } else { t.hover }); + } + let ink = if !enabled { + t.form_dim.gamma_multiply(0.35) + } else if selected { + t.form_primary + } else { + t.form_dim + }; + if arrow { + let icon = rect.shrink(t.form_icon_inset); + if glyph == MOVE_UP { + crate::icons::paint_ink_flipped(ui.painter(), icon, "chevron", ink); + } else { + crate::icons::paint_ink(ui.painter(), icon, "chevron", ink); + } + } else { + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(t.font_label), ink); + } + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), glyph)); + response + }) + .inner; + publish_button(ui, &response, glyph); + pointer_on_hover(ui, &response); + response.on_hover_text(crate::i18n::tr_label(tooltip)) +} + +/// Secondary action with an existing icon, optionally using the danger ink. Keeps button handles. +pub(crate) fn icon_label_button(ui: &mut Ui, label: &str, icon: &str, enabled: bool, danger: bool) -> Response { + let t = Tokens::get(); + let label = crate::i18n::tr_label(label); + let text_width = ui.painter().layout_no_wrap(label.to_string(), egui::FontId::proportional(t.font_label), t.form_ink).size().x; + let response = ui + .add_enabled_ui(enabled, |ui| { + let (rect, response) = + ui.allocate_exact_size(vec2(text_width + t.space_10 * 2.0 + t.space_14 + t.space_6, t.control_height), egui::Sense::click()); + let ink = if danger { t.form_error } else { t.form_ink }; + ui.painter().rect( + rect, + t.control_radius, + if response.hovered() { t.hover } else { t.control_fill }, + egui::Stroke::new(1.0, t.control_border), + egui::StrokeKind::Inside, + ); + let icon_rect = + egui::Rect::from_center_size(egui::pos2(rect.left() + t.space_10 + t.space_14 / 2.0, rect.center().y), vec2(t.space_14, t.space_14)); + crate::icons::paint_ink(ui.painter(), icon_rect, icon, ink); + super::text::paint_text( + ui, + egui::Rect::from_min_max(egui::pos2(icon_rect.right() + t.space_6, rect.top()), rect.max), + label, + egui::FontId::proportional(t.font_label), + ink, + false, + ); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), label)); + response + }) + .inner; + pointer_on_hover(ui, &response); + let key = format!("dialog:button:{}:{label}", super::layout::label(ui)); + scenario::publish_handle(&key, response.rect.center()); + scenario::publish_rect(&key, response.rect); + response +} + +/// Ribbon overflow action; keeps its native atom identity, shortcut, accessibility and behaviour. +/// Tokens: space_16 and the existing icon palette; button chrome inherits the menu style. +pub(crate) fn command_menu_button(ui: &mut Ui, id: &str, label: &str, icon: &str, shortcut: &str, enabled: bool) -> Response { + ui.add_enabled_ui(enabled, |ui| { + let atom = ui.id().with(("overflow_icon", id)); + let side = Tokens::get().space_16; + let row = egui::Button::new((egui::Atom::custom(atom, vec2(side, side)), label)).shortcut_text(shortcut).atom_ui(ui); + if let Some(rect) = row.rect(atom) { + crate::icons::paint_icon(ui.painter(), rect, icon, if enabled { 1.0 } else { 0.35 }); + } + row.response + }) + .inner +} diff --git a/crates/ui-egui/src/ui_kit/checks.rs b/crates/ui-egui/src/ui_kit/checks.rs new file mode 100644 index 000000000..7dfd00511 --- /dev/null +++ b/crates/ui-egui/src/ui_kit/checks.rs @@ -0,0 +1,79 @@ +//! The only checkbox box and check glyph, shared by inline, palette, grid and menu rows. +use crate::theme::Tokens; +use egui::{Rect, Response, Ui, pos2, vec2}; + +/// Fixed logical size and pixel-aligned origin, independent of a caller's fonts or spacing. +pub(super) fn box_at(ui: &Ui, center: egui::Pos2) -> Rect { + let t = Tokens::get(); + let ppp = ui.ctx().pixels_per_point(); + let min = center - vec2(t.space_14, t.space_14) / 2.0; + Rect::from_min_size(pos2((min.x * ppp).round() / ppp, (min.y * ppp).round() / ppp), vec2(t.space_14, t.space_14)) +} + +/// One path for every tick, including menu rows. Mixed state uses a horizontal bar. +fn paint_check_glyph(painter: &egui::Painter, square: Rect, mixed: bool, ink: egui::Color32) { + let t = Tokens::get(); + let mark = square.shrink(t.space_3); + let points = if mixed { vec![mark.left_center(), mark.right_center()] } else { vec![mark.left_center(), mark.center_bottom(), mark.right_top()] }; + painter.add(egui::Shape::line(points, egui::Stroke::new(t.space_2, ink))); +} + +/// All states use the same geometry. Disabled opacity is inherited from egui's disabled UI. +pub(super) fn paint_box(ui: &Ui, square: Rect, response: &Response, on: bool, mixed: bool) { + let t = Tokens::get(); + let selected = on || mixed; + let border = if selected || response.hovered() || response.has_focus() { t.form_primary } else { t.control_border }; + let fill = if selected { + t.form_primary + } else if response.hovered() { + t.hover + } else { + t.control_fill + }; + ui.painter().rect(square, t.radius_sm, fill, egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); + if selected { + paint_check_glyph(ui.painter(), square, mixed, t.on_accent); + } + if response.has_focus() { + ui.painter().rect_stroke(square.expand(t.space_2), t.radius_sm, egui::Stroke::new(1.0, t.form_primary), egui::StrokeKind::Outside); + } +} + +/// Checkboxes only via ui_kit::checkbox. Labels, accessibility, keyboard and response stay native. +pub(crate) fn checkbox(ui: &mut Ui, label: &str, value: &mut bool) -> Response { + checkbox_indeterminate(ui, label, value, false) +} + +/// Mixed values become checked when activated; the caller owns whether selection is mixed. +/// Tokens: space_14/3/2/6, radius_sm, control_fill/border, form_primary/ink, hover, on_accent. +pub(crate) fn checkbox_indeterminate(ui: &mut Ui, label: &str, value: &mut bool, mixed: bool) -> Response { + let t = Tokens::get(); + let font = egui::FontId::proportional(t.font_label); + let galley = ui.painter().layout_no_wrap(label.to_owned(), font.clone(), t.form_ink); + let gap = if label.is_empty() { 0.0 } else { t.space_6 }; + let width = (t.space_14 + gap + galley.size().x).max(ui.spacing().interact_size.y).min(super::metrics::dimension(ui.available_width())); + let height = ui.spacing().interact_size.y.max(t.space_14).max(galley.size().y); + let (rect, mut response) = ui.allocate_exact_size(vec2(width, height), egui::Sense::click()); + if response.clicked() { + *value = mixed || !*value; + response.mark_changed(); + } + let square = box_at(ui, pos2(rect.left() + t.space_14 / 2.0, rect.center().y)); + paint_box(ui, square, &response, *value, mixed && !response.changed()); + let text_rect = Rect::from_min_max(pos2((square.right() + gap).min(rect.right()), rect.top()), rect.max); + super::text::paint_text(ui, text_rect, label, font, t.form_ink, false); + response.widget_info(|| { + let accessible = if label.is_empty() { crate::i18n::tr_label(super::row_label(ui)) } else { label }; + let mut info = egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), *value, accessible); + if mixed && !response.changed() { + info.selected = None; + } + info + }); + super::layout::publish_geometry(ui, &response); + response +} + +#[cfg(test)] +#[path = "checks_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/ui_kit/checks_tests.rs b/crates/ui-egui/src/ui_kit/checks_tests.rs new file mode 100644 index 000000000..58ad821df --- /dev/null +++ b/crates/ui-egui/src/ui_kit/checks_tests.rs @@ -0,0 +1,445 @@ +use super::*; +use crate::ui_kit::{ + self, + test_support::{frame, key, pointer}, +}; +use egui::Shape; +use serde_json::json; +use std::collections::HashMap; + +#[test] +fn checkbox_keyboard_pointer_disabled_and_mixed() { + for mixed in [false, true] { + for enabled in [false, true] { + for activation in [None, Some(egui::Key::Space), Some(egui::Key::Enter)] { + let ctx = crate::fonts::test_context(); + let mut on = false; + let mut changed = false; + let target = std::cell::Cell::new(Rect::NOTHING); + let mut draw = |ui: &mut Ui| { + ui.add_enabled_ui(enabled, |ui| { + let response = checkbox_indeterminate(ui, "Option", &mut on, mixed); + changed |= response.changed(); + target.set(response.rect); + if activation.is_some() { + response.request_focus(); + } + }); + }; + frame(&ctx, vec![], &mut draw); + if let Some(activation) = activation { + frame(&ctx, key(activation), &mut draw); + } else { + // The label is part of the target, too. + let at = target.get().right_center() - vec2(1.0, 0.0); + frame(&ctx, pointer(at, true), &mut draw); + frame(&ctx, pointer(at, false), &mut draw); + } + assert_eq!(on, enabled, "mixed={mixed}, enabled={enabled}, key={activation:?}"); + assert_eq!(changed, enabled); + } + } + } +} + +fn checkbox_shapes(output: &egui::FullOutput) -> Vec<(Rect, Vec)> { + let t = Tokens::get(); + output + .shapes + .iter() + .filter_map(|clipped| { + let Shape::Rect(box_shape) = &clipped.shape else { return None }; + let square = box_shape.rect; + // Scroll areas also allocate controls below the viewport. Only complete, + // visible boxes have pixels that can be compared to a complete reference. + if !clipped.clip_rect.contains_rect(square) + || square.size() != vec2(t.space_14, t.space_14) + || box_shape.corner_radius != egui::CornerRadius::same(t.radius_sm) + { + return None; + } + let mut shapes = vec![clipped.clone()]; + shapes.extend( + output + .shapes + .iter() + .filter(|candidate| { + matches!(&candidate.shape, Shape::Path(path) + if matches!(path.points.len(), 2 | 3) && path.stroke.width == t.space_2 && path.points.iter().all(|p| square.contains(*p))) + }) + .cloned(), + ); + Some((square, shapes)) + }) + .collect() +} + +/// Small CPU rasteriser for egui's actual tessellated triangles, including the font/icon atlas. +/// This keeps screenshots and pixel comparisons deterministic without requiring a display/GPU. +fn raster( + ctx: &egui::Context, + mut shapes: Vec, + ppp: f32, + bounds: Rect, + textures: &HashMap, +) -> image::RgbaImage { + // Compare pixel-aligned crops in local coordinates. This avoids cancellation + // in barycentric arithmetic at different form/menu screen positions. + let offset = -bounds.min.to_vec2(); + for clipped in &mut shapes { + clipped.shape.translate(offset); + clipped.clip_rect = clipped.clip_rect.translate(offset); + } + let bounds = bounds.translate(offset); + let width = (bounds.width() * ppp).round() as u32; + let height = (bounds.height() * ppp).round() as u32; + let mut pixels = image::RgbaImage::new(width, height); + let cross = |a: egui::Vec2, b: egui::Vec2| a.x * b.y - a.y * b.x; + for clipped in ctx.tessellate(shapes, ppp) { + let egui::epaint::Primitive::Mesh(mesh) = clipped.primitive else { continue }; + let clip = clipped.clip_rect.intersect(bounds); + for triangle in mesh.indices.as_chunks::<3>().0 { + let [a, mut b, mut c] = triangle.map(|i| mesh.vertices[i as usize]); + let signed_area = cross(b.pos - a.pos, c.pos - a.pos); + if signed_area < 0.0 { + std::mem::swap(&mut b, &mut c); + } + let area = signed_area.abs(); + if area.abs() < 1e-6 { + continue; + } + let rect = Rect::from_min_max(a.pos.min(b.pos).min(c.pos), a.pos.max(b.pos).max(c.pos)).intersect(clip); + if !rect.is_positive() { + continue; + } + let min = ((rect.min - bounds.min) * ppp).floor(); + let max = ((rect.max - bounds.min) * ppp).ceil(); + for y in (min.y.max(0.0) as u32)..(max.y as u32).min(height) { + for x in (min.x.max(0.0) as u32)..(max.x as u32).min(width) { + let at = bounds.min + vec2(x as f32 + 0.5, y as f32 + 0.5) / ppp; + if !clip.contains(at) { + continue; + } + let weights = [cross(b.pos - at, c.pos - at) / area, cross(c.pos - at, a.pos - at) / area, cross(a.pos - at, b.pos - at) / area]; + // Half-open triangles avoid double blending their shared edge. + if weights.iter().zip([(b.pos, c.pos), (c.pos, a.pos), (a.pos, b.pos)]).any(|(weight, (a, b))| { + let edge = b - a; + *weight < 0.0 || (*weight == 0.0 && !(edge.y > 0.0 || (edge.y == 0.0 && edge.x < 0.0))) + }) { + continue; + } + let vertices = [a, b, c]; + let mut color = [0.0; 4]; + let mut uv = egui::Vec2::ZERO; + for (v, weight) in vertices.iter().zip(weights) { + uv += v.uv.to_vec2() * weight; + for (dest, channel) in color.iter_mut().zip(v.color.to_array()) { + *dest += f32::from(channel) * weight; + } + } + if let Some(texture) = textures.get(&mesh.texture_id) { + let tx = (uv.x * texture.size[0] as f32).floor().max(0.0) as usize; + let ty = (uv.y * texture.size[1] as f32).floor().max(0.0) as usize; + let texel = texture.pixels[ty.min(texture.size[1] - 1) * texture.size[0] + tx.min(texture.size[0] - 1)]; + for (dest, channel) in color.iter_mut().zip(texel.to_array()) { + *dest *= f32::from(channel) / 255.0; + } + } else { + // Box/tick isolation uses the atlas's white texel, without an atlas. + assert_eq!(a.uv, egui::epaint::WHITE_UV); + assert_eq!(b.uv, egui::epaint::WHITE_UV); + assert_eq!(c.uv, egui::epaint::WHITE_UV); + } + let pixel = pixels.get_pixel_mut(x, y); + let alpha = color[3] / 255.0; + for (dest, channel) in pixel.0.iter_mut().zip(color) { + *dest = (channel + f32::from(*dest) * (1.0 - alpha)).round().clamp(0.0, 255.0) as u8; + } + } + } + } + } + pixels +} + +fn textures_update(textures: &mut HashMap, delta: &egui::TexturesDelta) { + for (id, deltas) in &delta.set { + for delta in deltas { + let egui::ImageData::Color(image) = &delta.image; + if let Some([x, y]) = delta.pos { + let existing = textures.get_mut(id).expect("partial texture has a base"); + for row in 0..image.height() { + let offset = (y + row) * existing.width() + x; + existing.pixels[offset..offset + image.width()].copy_from_slice(&image.pixels[row * image.width()..(row + 1) * image.width()]); + } + } else { + textures.insert(*id, image.as_ref().clone()); + } + } + } +} + +fn surface( + ui: &mut Ui, + name: &str, + app: &mut crate::SolveApp, + editor: &mut crate::dialogs_motion::Mo, + appearance: &mut crate::dialogs_appearance::Ap, + inputs: &mut [crate::selection::SelInput], +) { + ui.set_width(if name == "appearance" { 340.0 } else { 760.0 }); + match name { + "config" => ui_kit::scope(ui, |ui| { + let id = ui.make_persistent_id("rule_editor"); + ui.ctx().data_mut(|d| d.insert_persisted(id, true)); + crate::dialogs_motion::rows(app, ui, editor, &mut []); + }), + "appearance" => ui_kit::scope(ui, |ui| { + crate::dialogs_appearance::rows(app, ui, appearance, inputs); + }), + "preferences" => crate::prefs::show(app, ui.ctx()), + "menu" => { + crate::context_menu::menu_frame(ui, |ui| crate::toolbar::selection_filter(app, ui)); + } + _ => panic!("unknown surface {name}"), + } +} + +#[test] +fn actual_config_appearance_preferences_and_menu_boxes_and_ticks_match_at_1x_2x() { + let previous = crate::theme::is_dark(); + let evidence = std::env::var_os("SOLIDCRAFT_CHECKBOX_EVIDENCE").map(std::path::PathBuf::from); + for dark in [false, true] { + crate::theme::set_dark(dark); + for ppp in [1.0, 2.0] { + let reference_ctx = crate::fonts::test_context(); + reference_ctx.set_pixels_per_point(ppp); + let mut references = Vec::new(); + for on in [false, true] { + for disabled in [false, true] { + let mut value = on; + let mut output = reference_ctx.run_ui(Default::default(), |ui| { + ui.add_enabled_ui(!disabled, |ui| { + checkbox(ui, "Reference", &mut value); + }); + }); + let (square, shapes) = checkbox_shapes(&output).remove(0); + references.push((square, shapes.clone(), raster(&reference_ctx, shapes, ppp, square, &HashMap::new()))); + output.textures_delta.clear(); + } + } + for name in ["config", "appearance", "preferences", "menu"] { + let ctx = crate::fonts::test_context(); + ctx.set_pixels_per_point(ppp); + ctx.set_visuals(if dark { egui::Visuals::dark() } else { egui::Visuals::light() }); + let mut app = crate::SolveApp::new(Default::default(), Default::default()); + app.home.open = false; + app.ui.dark = dark; + app.run("parameters.add", json!({"name":"width", "expression":"10 mm"})).unwrap(); + app.run("config.configure", json!({"params":["width"]})).unwrap(); + app.run("config.rule", json!({"rule":{"id":"width_rule","name":"Width rule", "enabled":true, "condition":{"type":"always"},"effect":{"type":"drive_parameter", "parameter":"width","expression":"12 mm"}}})).unwrap(); + let mut editor = crate::dialogs_motion::Mo::Configurations { new_row: String::new(), error: None, rule_editor: Default::default() }; + let Some((crate::dialogs::Kind::Appearance(mut appearance), mut inputs)) = + crate::dialogs_appearance::start(&app, "appearance.assign") + else { + panic!("appearance fixture"); + }; + appearance.pbr = Some(Default::default()); + appearance.local.overwrite = true; + app.ui.pick_bodies = true; + if name == "preferences" { + crate::prefs::open_at(&mut app, crate::prefs::PAGE_GRAPHICS); + } + let mut textures = HashMap::new(); + let mut final_output = None; + for _ in 0..3 { + crate::scenario::clear_handles(); + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(1000.0, 1300.0))), ..Default::default() }, + |ui| surface(ui, name, &mut app, &mut editor, &mut appearance, &mut inputs), + ); + textures_update(&mut textures, &output.textures_delta); + output.textures_delta.clear(); + final_output = Some(output); + } + let output = final_output.unwrap(); + let boxes = checkbox_shapes(&output); + assert!(boxes.len() >= if matches!(name, "config" | "appearance") { 2 } else { 1 }, "{name}: missing actual checkbox controls"); + let mut ticks = 0; + for (square, shapes) in boxes { + let checked = shapes.len() > 1; + ticks += usize::from(checked); + let Shape::Rect(box_shape) = &shapes[0].shape else { + panic!("checkbox box"); + }; + let opaque_fill = if checked { Tokens::get().form_primary } else { Tokens::get().control_fill }; + let disabled = box_shape.fill.a() < opaque_fill.a(); + let (reference_square, reference_shapes, reference_pixels) = &references[usize::from(checked) * 2 + usize::from(disabled)]; + // Compare the actual path, independent of a form/menu's placement. + if checked { + let (Shape::Path(actual), Shape::Path(reference)) = (&shapes[1].shape, &reference_shapes[1].shape) else { + panic!("tick path"); + }; + let normalized = |points: &[egui::Pos2], min| points.iter().map(|p| *p - min).collect::>(); + assert_eq!( + normalized(&actual.points, square.min), + normalized(&reference.points, reference_square.min), + "{name}: tick geometry" + ); + assert_eq!(actual.stroke, reference.stroke, "{name}: tick stroke"); + } + let pixels = raster(&ctx, shapes, ppp, square, &HashMap::new()); + let max_difference = pixels.as_raw().iter().zip(reference_pixels.as_raw()).map(|(a, b)| a.abs_diff(*b)).max().unwrap(); + assert!(max_difference <= 1, "{name}: box/check pixel difference {max_difference}, dark={dark}, ppp={ppp}"); + } + assert!(ticks > 0, "{name}: must exercise checked rows"); + if let Some(dir) = &evidence { + std::fs::create_dir_all(dir).unwrap(); + let mut image = raster(&ctx, output.shapes, ppp, Rect::from_min_size(egui::Pos2::ZERO, vec2(1000.0, 1300.0)), &textures); + let background = Tokens::get().dialog_body.to_array(); + for pixel in image.pixels_mut() { + let remaining = 1.0 - f32::from(pixel.0[3]) / 255.0; + for (dest, back) in pixel.0.iter_mut().zip(background) { + *dest = (f32::from(*dest) + f32::from(back) * remaining).round() as u8; + } + } + image.save(dir.join(format!("{name}-{}-{ppp}x.png", if dark { "dark" } else { "light" }))).unwrap(); + } + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn grid_palette_inline_and_menu_share_every_box_state() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + for ppp in [1.0, 2.0] { + for on in [false, true] { + for state in ["idle", "hover", "focus", "disabled"] { + let mut reference = None; + for variant in ["inline", "grid", "palette", "menu"] { + let ctx = crate::fonts::test_context(); + ctx.set_pixels_per_point(ppp); + let mut at = None; + let mut final_output = None; + for pass in 0..4 { + let events = if state == "hover" && pass > 0 { + vec![egui::Event::PointerMoved(at.unwrap())] + } else if state == "focus" && pass == 1 { + key(egui::Key::Tab) + } else { + vec![] + }; + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 120.0))), + events, + focused: true, + ..Default::default() + }, + |ui| { + ui_kit::scope(ui, |ui| { + ui.add_enabled_ui(state != "disabled", |ui| { + let mut value = on; + match variant { + "grid" => ui_kit::checkbox_grid(ui, &mut [("Option", &mut value)], 1), + "palette" => { + ui_kit::checkbox_row(ui, "option", "Option", value); + } + "menu" => { + crate::context_menu::menu_frame(ui, |ui| { + checkbox(ui, "Option", &mut value); + }); + } + _ => { + checkbox(ui, "Option", &mut value); + } + } + }); + }); + }, + ); + output.textures_delta.clear(); + let boxes = checkbox_shapes(&output); + assert_eq!(boxes.len(), 1, "{variant}, {state}"); + at = Some(boxes[0].0.center()); + final_output = Some(output); + } + let output = final_output.unwrap(); + let (square, shapes) = checkbox_shapes(&output).remove(0); + if state == "focus" { + assert!( + output + .shapes + .iter() + .any(|shape| matches!(&shape.shape, Shape::Rect(r) if r.rect == square.expand(Tokens::get().space_2))), + "{variant}: must actually focus" + ); + } + if state == "hover" && !on { + let Shape::Rect(r) = &shapes[0].shape else { + panic!("box"); + }; + assert_eq!(r.fill, Tokens::get().hover, "{variant}: must actually hover"); + } + let pixels = raster(&ctx, shapes, ppp, square, &HashMap::new()); + if let Some(reference) = &reference { + assert_eq!(pixels, *reference, "{variant}: {state}, on={on}, dark={dark}, ppp={ppp}"); + } else { + reference = Some(pixels); + } + } + } + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn checkbox_accessibility_preserves_label_checked_and_mixed_metadata() { + for mixed in [false, true] { + let ctx = crate::fonts::test_context(); + ctx.enable_accesskit(); + let mut value = false; + let mut before = None; + let mut after = None; + for pass in 0..4 { + let events = match pass { + 1 => key(egui::Key::Tab), + 3 => key(egui::Key::Space), + _ => vec![], + }; + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 120.0))), + events, + focused: true, + ..Default::default() + }, + |ui| { + checkbox_indeterminate(ui, "Enabled", &mut value, mixed); + }, + ); + output.textures_delta.clear(); + for event in output.platform_output.events { + match event { + egui::output::OutputEvent::FocusGained(info) => before = Some(info), + egui::output::OutputEvent::Clicked(info) | egui::output::OutputEvent::ValueChanged(info) => after = Some(info), + _ => {} + } + } + } + let before = before.expect("checkbox gains keyboard focus"); + assert_eq!(before.typ, egui::WidgetType::Checkbox); + assert_eq!(before.label.as_deref(), Some("Enabled")); + assert_eq!(before.selected, if mixed { None } else { Some(false) }); + let after = after.expect("activation publishes the changed checked state"); + assert_eq!(after.typ, egui::WidgetType::Checkbox); + assert_eq!(after.label.as_deref(), Some("Enabled")); + assert_eq!(after.selected, Some(true)); + } +} diff --git a/crates/ui-egui/src/ui_kit/choice.rs b/crates/ui-egui/src/ui_kit/choice.rs index c500344b6..7d9ca3558 100644 --- a/crates/ui-egui/src/ui_kit/choice.rs +++ b/crates/ui-egui/src/ui_kit/choice.rs @@ -13,15 +13,18 @@ use egui::{Ui, vec2}; pub(crate) struct Segments<'a> { pub states: &'a [bool], pub compact: bool, + pub primary: bool, } pub(crate) fn segmented(ui: &mut Ui, selected: &mut usize, options: &[&str], config: Segments<'_>) -> bool { - let Segments { states, compact } = config; + let Segments { states, compact, primary } = config; let t = Tokens::get(); let segment_width = dimension(ui.available_width()) / options.len().max(1) as f32; let widest = options .iter() - .map(|option| ui.painter().layout_no_wrap(crate::i18n::tr_label(option).to_string(), crate::fonts::semibold(t.font_label), t.text).size().x) + .map(|option| { + ui.painter().layout_no_wrap(crate::i18n::tr_label(option).to_string(), crate::fonts::semibold(t.font_label), t.form_ink).size().x + }) .fold(0.0, f32::max); if !compact && widest + 2.0 * t.space_8 > segment_width { let before = *selected; @@ -44,17 +47,40 @@ pub(crate) fn segmented(ui: &mut Ui, selected: &mut usize, options: &[&str], con se: if index + 1 == options.len() { t.control_radius } else { 0 }, }; if on || response.hovered() { - ui.painter().rect_filled(segment, rounding, if on { t.selected_bg } else { t.hover }); + ui.painter().rect_filled( + segment, + rounding, + if on && primary { + t.form_primary + } else if on { + t.selected_bg + } else { + t.hover + }, + ); } if index > 0 { ui.painter().vline(segment.left(), segment.y_range(), egui::Stroke::new(1.0, t.control_border)); } let font = if on { crate::fonts::semibold(t.font_label) } else { egui::FontId::proportional(t.font_label) }; - let galley = ui.painter().layout_no_wrap((*option).to_string(), font.clone(), t.text); + let galley = ui.painter().layout_no_wrap((*option).to_string(), font.clone(), t.form_ink); let text_rect = egui::Rect::from_min_size(egui::pos2(segment.center().x - galley.size().x / 2.0, segment.top()), vec2(galley.size().x, segment.height())); let text_rect = if compact { text_rect.intersect(segment.shrink2(vec2(t.space_4, 0.0))) } else { text_rect }; - paint_text(ui, text_rect, option, font, if on { t.selected_ink } else { t.text }, false); + paint_text( + ui, + text_rect, + option, + font, + if on && primary { + t.on_accent + } else if on { + t.selected_ink + } else { + t.form_ink + }, + false, + ); response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, ui.is_enabled(), on, *option)); scenario::publish_handle(&format!("dialog:{}:{option}", label(ui)), segment.center()); if response.on_hover_text(*option).clicked() { @@ -104,7 +130,7 @@ pub(crate) fn segmented_icons(ui: &mut Ui, selected: &mut usize, options: &[Icon // A square icon area inside the segment: dash gaps and dots need the room to read apart. let side = (segment.width().min(segment.height()) - t.space_4).max(t.space_12); let icon_rect = egui::Rect::from_center_size(segment.center(), vec2(side, side)); - crate::icons::paint(ui.painter(), icon_rect, option.icon, t.icon, t.icon_fill, t.accent); + crate::icons::paint(ui.painter(), icon_rect, option.icon, t.icon, t.icon_fill, t.form_primary); response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, ui.is_enabled(), on, option.key)); scenario::publish_handle(&format!("dialog:{}:{}", label(ui), option.key), segment.center()); let response = response.on_hover_text(&option.tip); @@ -132,25 +158,12 @@ pub(crate) fn checkbox_grid(ui: &mut Ui, items: &mut [(&str, &mut bool)], column **value = !**value; response.mark_changed(); } - let square = egui::Rect::from_center_size(egui::pos2(rect.left() + t.space_14 / 2.0, rect.center().y), vec2(t.space_14, t.space_14)); - ui.painter().rect( - square, - t.radius_sm, - if **value { t.accent } else { t.control_fill }, - egui::Stroke::new(1.0, if **value { t.accent } else { t.control_border }), - egui::StrokeKind::Inside, - ); - if **value { - let mark = square.shrink(t.space_3); - ui.painter().add(egui::Shape::line( - vec![mark.left_center(), mark.center_bottom(), mark.right_top()], - egui::Stroke::new(t.space_2, t.on_accent), - )); - } + let square = super::checks::box_at(ui, egui::pos2(rect.left() + t.space_14 / 2.0, rect.center().y)); + super::checks::paint_box(ui, square, &response, **value, false); let translated = crate::i18n::tr_label(label); let text = if translated == "Tangent Chain" { "Tangent chain" } else { translated }; let text_rect = egui::Rect::from_min_max(egui::pos2((square.right() + t.space_6).min(rect.right()), rect.top()), rect.max); - paint_text(ui, text_rect, text, egui::FontId::proportional(t.font_body), t.text, false); + paint_text(ui, text_rect, text, egui::FontId::proportional(t.font_body), t.form_ink, false); response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), **value, translated)); scenario::publish_target_as(&format!("dialog:{label}"), &format!("dialog:checkbox:{label}"), rect); } @@ -169,41 +182,21 @@ pub(crate) fn options(ui: &mut Ui, id: &str, items: &mut [(&str, &mut bool)]) { pub(crate) fn checkbox_row(ui: &mut egui::Ui, key: &str, label: &str, on: bool) -> bool { let t = Tokens::get(); let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), t.control_height), egui::Sense::click()); - let square = egui::Rect::from_center_size(egui::pos2(rect.right() - t.space_14 / 2.0, rect.center().y), vec2(t.space_14, t.space_14)); + let square = super::checks::box_at(ui, egui::pos2(rect.right() - t.space_14 / 2.0, rect.center().y)); if response.hovered() || response.has_focus() { ui.painter().rect_filled(rect, t.control_radius, t.hover); } - ui.painter().rect( - square, - t.radius_sm, - if on { t.accent } else { t.control_fill }, - egui::Stroke::new(1.0, if on { t.accent } else { t.control_border }), - egui::StrokeKind::Inside, - ); - if on { - let mark = square.shrink(t.space_3); - ui.painter() - .add(egui::Shape::line(vec![mark.left_center(), mark.center_bottom(), mark.right_top()], egui::Stroke::new(t.space_2, t.on_accent))); - } + super::checks::paint_box(ui, square, &response, on, false); let label = crate::i18n::tr_label(label); let painter = ui .painter() .with_clip_rect(ui.clip_rect().intersect(egui::Rect::from_min_max(rect.min, egui::pos2(square.left() - t.space_6, rect.bottom())))); - painter.text(rect.left_center(), egui::Align2::LEFT_CENTER, label, egui::FontId::proportional(t.font_label), t.text); + painter.text(rect.left_center(), egui::Align2::LEFT_CENTER, label, egui::FontId::proportional(t.font_label), t.form_ink); response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Checkbox, ui.is_enabled(), on, label)); crate::scenario::publish_target(&format!("sketch_palette:toggle:{key}"), rect); response.on_hover_text(label).clicked() } -/// Standard inline checkbox; inherits scope's font_label, accent, control and text tokens. -/// Use checkbox_row for a full-width label-left/box-right palette option. -/// Inline native checkbox retaining existing accessibility and sizing. Tokens: `scope control/font/accent tokens`. -pub(crate) fn checkbox(ui: &mut Ui, label: &str, value: &mut bool) -> egui::Response { - let response = ui.checkbox(value, label); - super::layout::publish_geometry(ui, &response); - response -} - /// Compact bold/italic toggles for text. Tokens: scope font/control tokens. /// The glyphs keep the familiar B/I treatment; accessible names use translated style names. pub(crate) fn text_emphasis(ui: &mut Ui, bold: &mut bool, italic: &mut bool) { @@ -264,7 +257,7 @@ pub(crate) fn toggle_icon(ui: &mut Ui, row: &str, label: &str, selected: &mut bo let t = Tokens::get(); let response = ui.add(egui::Button::new("").selected(*selected).min_size(vec2(t.space_24 + t.space_4, t.control_height)).sense(egui::Sense::CLICK)); - crate::icons::paint(ui.painter(), response.rect.shrink(t.space_3), icon, t.icon, t.icon_fill, t.accent); + crate::icons::paint(ui.painter(), response.rect.shrink(t.space_3), icon, t.icon, t.icon_fill, t.form_primary); response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, *selected, crate::i18n::tr_label(label))); crate::scenario::publish_handle(&format!("dialog:{row}:{label}"), response.rect.center()); if response.clone().on_hover_text(crate::i18n::tr_label(label)).clicked() { @@ -300,20 +293,28 @@ pub(crate) fn color_swatch( let t = crate::theme::Tokens::get(); let response = ui .dnd_drag_source(id, payload, |ui| { - let (rect, _) = ui.allocate_exact_size(egui::vec2(t.control_height, t.control_height), egui::Sense::hover()); + let side = t.control_height + t.space_6; + let (allocation, _) = ui.allocate_exact_size(egui::vec2(side, side), egui::Sense::hover()); + let rect = allocation.shrink(t.space_2); + if selected { + ui.painter().rect_stroke(allocation, t.radius_lg, egui::Stroke::new(t.space_2, t.form_primary), egui::StrokeKind::Inside); + } + ui.painter().rect_filled(rect, t.control_radius, t.control_fill); if color.a() < u8::MAX { - let half = rect.width() / 2.0; - for offset in [egui::Vec2::ZERO, egui::vec2(half, half)] { - ui.painter().rect_filled(egui::Rect::from_min_size(rect.min + offset, egui::vec2(half, half)), 0.0, t.hover); + let tile = rect.width() / 6.0; + for y in 0..6 { + for x in 0..6 { + if (x + y) % 2 == 0 { + ui.painter().rect_filled( + egui::Rect::from_min_size(rect.min + vec2(x as f32 * tile, y as f32 * tile), vec2(tile, tile)), + 0.0, + t.border, + ); + } + } } } - ui.painter().rect( - rect, - t.control_radius, - color, - egui::Stroke::new(if selected { t.space_2 } else { 1.0 }, if selected { t.accent } else { t.border }), - egui::StrokeKind::Inside, - ); + ui.painter().rect(rect, t.control_radius, color, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); }) .response; let response = ui.interact(response.rect, id.with("click"), egui::Sense::click()).on_hover_text(tip); @@ -326,9 +327,9 @@ pub(crate) fn color_swatch( /// Wrapped samples with common token spacing. Keeps native drag-and-drop payloads intact. pub(crate) fn swatch_grid(ui: &mut Ui, values: &[T], mut each: impl FnMut(&mut Ui, &T)) { let t = Tokens::get(); - let columns = ((super::metrics::dimension(ui.available_width()) + t.space_4) / (t.control_height + t.space_4)).floor().clamp(1.0, 64.0) as usize; + let columns = ((super::metrics::dimension(ui.available_width()) + t.space_2) / (t.control_height + t.space_8)).floor().clamp(1.0, 64.0) as usize; ui.vertical(|ui| { - ui.spacing_mut().item_spacing = vec2(t.space_4, t.space_4); + ui.spacing_mut().item_spacing = vec2(t.space_2, t.space_2); for row in values.chunks(columns.max(1)) { ui.horizontal(|ui| { for value in row { @@ -343,6 +344,7 @@ pub(crate) fn swatch_grid(ui: &mut Ui, values: &[T], mut each: impl FnMut(&mu pub(crate) struct PopupOption<'a> { pub text: &'a str, pub detail: &'a str, + pub kind: &'a str, pub color: egui::Color32, } @@ -359,28 +361,70 @@ pub(crate) fn popup_list( let t = crate::theme::Tokens::get(); let mut chosen = None; let area = crate::frame::area(id).order(egui::Order::Tooltip).fixed_pos(anchor.left_bottom() + egui::vec2(0.0, t.space_2)).show(ctx, |ui| { - egui::Frame::popup(ui.style()).show(ui, |ui| { - super::scope(ui, |ui| { - ui.set_width(anchor.width().max(t.form_label_width * 2.0)); - for (index, option) in options.iter().enumerate() { - let response = ui - .add_sized( - egui::vec2(ui.available_width(), t.control_height), - egui::Button::selectable(index == selected, egui::RichText::new(option.text).color(option.color)), - ) - .on_hover_text(option.detail); - crate::scenario::publish_handle(&format!("dialog:suggestion:{index}"), response.rect.center()); - if index == selected { + egui::Frame::popup(ui.style()) + .fill(t.control_fill) + .stroke(egui::Stroke::new(1.0, t.dialog_border)) + .corner_radius(t.radius_lg) + .inner_margin(t.space_4) + .show(ui, |ui| { + super::scope(ui, |ui| { + ui.set_width(anchor.width().max(t.form_card_width - t.space_16 * 2.0 - t.space_2)); + for (index, option) in options.iter().enumerate() { + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), t.control_height), egui::Sense::click()); + let picked = index == selected; + if picked || response.hovered() { + ui.painter().rect_filled(rect, t.control_radius, if picked { t.selected_bg } else { t.hover }); + } + let inner = rect.shrink2(vec2(t.space_8, 0.0)); + let kind = crate::i18n::tr_label(option.kind); + let kind_width = super::metrics::label_width(ui, kind); + let text_rect = egui::Rect::from_min_max( + inner.min, + egui::pos2((inner.right() - kind_width - t.space_8).max(inner.left()), inner.bottom()), + ); + super::text::paint_text( + ui, + text_rect, + option.text, + egui::FontId::monospace(t.font_body), + if picked { t.form_primary } else { option.color }, + false, + ); + ui.painter().text( + inner.right_center(), + egui::Align2::RIGHT_CENTER, + kind, + egui::FontId::proportional(t.font_small), + t.form_dim, + ); + response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, ui.is_enabled(), picked, option.text)); + let response = response.on_hover_text(option.detail); + crate::scenario::publish_handle(&format!("dialog:suggestion:{index}"), response.rect.center()); + if response.clicked() { + chosen = Some(index); + } + } + super::divider(ui, "completion_detail"); + if let Some(option) = options.get(selected) { super::text(ui, option.detail, super::Text::Note("completion_detail")); } - if response.clicked() { - chosen = Some(index); - } - } - super::text(ui, hint, super::Text::Note("completion_hint")); - }) - }); + super::text(ui, hint, super::Text::Note("completion_hint")); + }) + }); }); crate::scenario::publish_rect("dialog:suggestions", area.response.rect); chosen } + +/// Compact draggable library thumbnail, retaining the caller's distinct payload type. +/// Tokens: space_16, radius_sm, border. +#[cfg(any(not(target_arch = "wasm32"), test))] +pub(crate) fn color_thumbnail(ui: &mut Ui, id: egui::Id, color: egui::Color32, tip: &str, payload: T) -> egui::Response { + let t = Tokens::get(); + ui.dnd_drag_source(id, payload, |ui| { + let (rect, _) = ui.allocate_exact_size(vec2(t.space_16, t.space_16), egui::Sense::hover()); + ui.painter().rect(rect, t.radius_sm, color, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + }) + .response + .on_hover_text(tip) +} diff --git a/crates/ui-egui/src/ui_kit/color.rs b/crates/ui-egui/src/ui_kit/color.rs new file mode 100644 index 000000000..81434ee9d --- /dev/null +++ b/crates/ui-egui/src/ui_kit/color.rs @@ -0,0 +1,216 @@ +//! Opaque document RGB editing. Interface paint uses tokens; the gradients are colour data. +use super::{layout::label, metrics::dimension}; +use crate::{i18n, scenario, theme::Tokens}; +use egui::{Color32, Response, Sense, Ui, ecolor::HsvaGamma, pos2, vec2}; + +fn publish(key: &str, response: &Response) { + scenario::publish_rect(key, response.rect); + scenario::publish_handle(key, response.rect.center()); +} + +/// Shared colour button and outside-click-dismissed popover. Retains the enclosing row handle. +pub(crate) fn color_field(ui: &mut Ui, rgb: &mut [u8; 3]) -> Response { + let t = Tokens::get(); + let (rect, mut response) = ui.allocate_exact_size(vec2(t.control_height + t.space_6, t.control_height), Sense::click()); + ui.painter().rect( + rect, + t.control_radius, + crate::theme::srgb(rgb.map(|c| f32::from(c) / 255.0)), + egui::Stroke::new(1.0, t.control_border), + egui::StrokeKind::Inside, + ); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ColorButton, ui.is_enabled(), i18n::tr("color.edit"))); + publish(&format!("dialog:color:{}", label(ui)), &response); + let mut edited = false; + egui::Popup::menu(&response) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .width(t.form_card_width + t.space_24 + t.space_12) + .frame( + egui::Frame::popup(ui.style()) + .fill(t.control_fill) + .stroke(egui::Stroke::new(1.0, t.border)) + .corner_radius(t.radius_xl) + .inner_margin(t.space_12), + ) + .show(|ui| { + super::scope(ui, |ui| { + edited = color_popover(ui, rgb); + }); + }); + if edited { + response.mark_changed(); + } + let response = response.on_hover_cursor(egui::CursorIcon::PointingHand); + if ui.style().explanation_tooltips { response.on_hover_text(i18n::tr("color.edit")) } else { response } +} + +/// Popover body, also rendered independently by the gallery. Format is global, alpha is opaque. +/// Tokens: form_card_width, control_*, form_*, on_accent, border, radius_xl, font_small, space_*. +pub(crate) fn color_popover(ui: &mut Ui, rgb: &mut [u8; 3]) -> bool { + let t = Tokens::get(); + ui.style_mut().drag_value_text_style = egui::TextStyle::Monospace; + let id = ui.id().with("color_hsv"); + let color = crate::theme::srgb(rgb.map(|c| f32::from(c) / 255.0)); + // Retain hue for black/grey, and sub-byte precision while dragging. + let (saved, hsv) = ui.ctx().data(|d| d.get_temp::<([u8; 3], HsvaGamma)>(id)).unwrap_or((*rgb, color.into())); + let mut hsv = if saved == *rgb { hsv } else { color.into() }; + let before = hsv; + let mut linear = ui.global_style().visuals.numeric_color_space == egui::style::NumericColorSpace::Linear; + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = t.space_10; + ui.horizontal(|ui| { + let mut selected = usize::from(linear); + ui.allocate_ui(vec2(t.control_height * 3.0, t.control_height), |ui| { + super::segmented(ui, &mut selected, &["U8", "F"], super::Segments { compact: true, primary: true, ..Default::default() }); + let rect = ui.min_rect(); + for (index, key) in ["color.gamma", "color.linear"].iter().enumerate() { + let rect = + egui::Rect::from_min_size(rect.min + vec2(index as f32 * rect.width() / 2.0, 0.0), vec2(rect.width() / 2.0, rect.height())); + ui.interact(rect, ui.id().with(("format_tip", index)), Sense::hover()).on_hover_text(i18n::tr(key)); + scenario::publish_handle(&format!("color:format:{}", if index == 0 { "U8" } else { "F" }), rect.center()); + } + }); + linear = selected == 1; + if selected != usize::from(ui.global_style().visuals.numeric_color_space == egui::style::NumericColorSpace::Linear) { + ui.ctx().all_styles_mut(|s| { + s.visuals.numeric_color_space = + if linear { egui::style::NumericColorSpace::Linear } else { egui::style::NumericColorSpace::GammaByte } + }); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let (rect, _) = ui.allocate_exact_size(vec2(t.form_close_size, t.form_close_size), Sense::hover()); + let copy = super::icon_button_at(ui, rect, "copy", i18n::tr("color.copy")); + publish("color:copy", ©); + if copy.clicked() { + let [r, g, b] = *rgb; + let [lr, lg, lb, _] = egui::Rgba::from(color).to_array(); + ui.ctx().copy_text(if linear { format!("{lr:.03}, {lg:.03}, {lb:.03}") } else { format!("{r}, {g}, {b}") }); + } + }); + }); + let mut channels = if linear { + let [r, g, b, _] = egui::Rgba::from(color).to_array(); + [r as f64, g as f64, b as f64] + } else { + rgb.map(f64::from) + }; + let mut edited = false; + ui.columns(3, |columns| { + for ((ui, channel), name) in columns.iter_mut().zip(channels.iter_mut()).zip(["R", "G", "B"]) { + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = t.space_3; + ui.add(egui::Label::new(egui::RichText::new(name).size(t.font_small).color(t.form_dim))); + let response = ui.add_sized( + vec2(dimension(ui.available_width()), t.control_height), + egui::DragValue::new(channel) + .range(0.0..=if linear { 1.0 } else { 255.0 }) + .speed(if linear { 0.003 } else { 0.5 }) + .custom_parser(crate::prefs::parse_number) + .custom_formatter(move |v, _| if linear { format!("{v:.03}") } else { format!("{v:.0}") }), + ); + response.widget_info(|| { + let mut info = egui::WidgetInfo::drag_value(ui.is_enabled(), *channel); + info.label = Some(name.into()); + info + }); + publish(&format!("color:channel:{name}"), &response); + edited |= response.changed(); + }); + } + }); + if edited { + let [r, g, b] = channels; + *rgb = if linear { + let color = Color32::from(egui::Rgba::from_rgb(r as f32, g as f32, b as f32)); + [color.r(), color.g(), color.b()] + } else { + channels.map(|v| v.round() as u8) + }; + hsv = crate::theme::srgb(rgb.map(|c| f32::from(c) / 255.0)).into(); + } + let width = dimension(ui.available_width()); + let (square, response) = ui.allocate_exact_size(vec2(width, t.control_height * 7.0 + t.space_4), Sense::click_and_drag()); + if (response.clicked() || response.dragged()) + && let Some(pos) = response.interact_pointer_pos() + { + hsv.s = ((pos.x - square.left()) / square.width()).clamp(0.0, 1.0); + hsv.v = (1.0 - (pos.y - square.top()) / square.height()).clamp(0.0, 1.0); + edited = true; + } + gradient(ui, square, |x, y| Color32::from(HsvaGamma { h: hsv.h, s: x, v: 1.0 - y, a: 1.0 })); + marker(ui, pos2(square.left() + hsv.s * square.width(), square.bottom() - hsv.v * square.height()), t.space_6); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Other, ui.is_enabled(), i18n::tr("color.saturation_value"))); + publish("color:sv", &response); + response.on_hover_text(i18n::tr("color.saturation_value")); + let (hue, response) = ui.allocate_exact_size(vec2(width, t.space_14), Sense::click_and_drag()); + if (response.clicked() || response.dragged()) + && let Some(pos) = response.interact_pointer_pos() + { + hsv.h = ((pos.x - hue.left()) / hue.width()).clamp(0.0, 1.0); + edited = true; + } + gradient(ui, hue, |x, _| Color32::from(HsvaGamma { h: x, s: 1.0, v: 1.0, a: 1.0 })); + marker(ui, pos2(hue.left() + hsv.h * hue.width(), hue.center().y), t.space_8); + response.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), f64::from(hsv.h), i18n::tr("color.hue"))); + publish("color:hue", &response); + response.on_hover_text(i18n::tr("color.hue")); + if edited { + let c = Color32::from(hsv); + *rgb = [c.r(), c.g(), c.b()]; + } + let (strip, response) = ui.allocate_exact_size(vec2(width, t.form_close_size), Sense::hover()); + ui.painter().rect( + strip, + t.control_radius, + crate::theme::srgb(rgb.map(|c| f32::from(c) / 255.0)), + egui::Stroke::new(1.0, t.control_border), + egui::StrokeKind::Inside, + ); + publish("color:current", &response); + response.on_hover_text(i18n::tr("color.selected")); + }); + ui.ctx().data_mut(|d| d.insert_temp(id, (*rgb, hsv))); + scenario::publish_rect("color:popover", ui.min_rect()); + hsv != before +} + +fn marker(ui: &Ui, at: egui::Pos2, radius: f32) { + let t = Tokens::get(); + ui.painter().circle_stroke(at, radius, egui::Stroke::new(t.space_3, t.border)); + ui.painter().circle_stroke(at, radius, egui::Stroke::new(1.0, t.on_accent)); +} + +fn gradient(ui: &Ui, rect: egui::Rect, color: impl Fn(f32, f32) -> Color32) { + let mut mesh = egui::Mesh::default(); + // Bounded tessellation gives perceptually even HSV gamma gradients. + const STEPS: u32 = 32; + let radius = f32::from(Tokens::get().control_radius).min(rect.width() / 2.0).min(rect.height() / 2.0); + let mut rows: Vec = (0..=STEPS).map(|y| rect.height() * y as f32 / STEPS as f32).collect(); + // Extra samples follow each corner arc even on the tall SV square. Each row spans only + // the rounded silhouette; colours use actual coordinates, preserving the HSV mapping. + for step in 0..=8 { + let y = radius * (1.0 - (step as f32 * std::f32::consts::FRAC_PI_2 / 8.0).cos()); + rows.extend([y, rect.height() - y]); + } + rows.sort_by(f32::total_cmp); + rows.dedup(); + for (row, y) in rows.iter().copied().enumerate() { + let dy = (radius - y.min(rect.height() - y)).max(0.0); + let inset = radius - (radius * radius - dy * dy).max(0.0).sqrt(); + for x in 0..=STEPS { + let px = inset + (rect.width() - 2.0 * inset) * x as f32 / STEPS as f32; + mesh.colored_vertex(rect.min + vec2(px, y), color(px / rect.width(), y / rect.height())); + if row > 0 && x < STEPS { + let i = (row as u32 - 1) * (STEPS + 1) + x; + mesh.add_triangle(i, i + 1, i + STEPS + 1); + mesh.add_triangle(i + 1, i + STEPS + 2, i + STEPS + 1); + } + } + } + ui.painter().add(egui::Shape::mesh(mesh)); + ui.painter().rect_stroke(rect, Tokens::get().control_radius, egui::Stroke::new(1.0, Tokens::get().control_border), egui::StrokeKind::Inside); +} + +#[cfg(test)] +#[path = "color_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/ui_kit/color_tests.rs b/crates/ui-egui/src/ui_kit/color_tests.rs new file mode 100644 index 000000000..0e63da664 --- /dev/null +++ b/crates/ui-egui/src/ui_kit/color_tests.rs @@ -0,0 +1,223 @@ +use super::*; +use crate::ui_kit::test_support::pointer; + +fn frame(ctx: &egui::Context, events: Vec, mut add: impl FnMut(&mut Ui) -> R) { + crate::ui_kit::test_support::frame(ctx, events, |ui| { + add(ui); + }); +} + +fn click(ctx: &egui::Context, key: &str, rgb: &mut [u8; 3]) { + let at = scenario::handle_at(key).unwrap_or_else(|| panic!("missing {key}")); + frame(ctx, pointer(at, true), |ui| color_popover(ui, rgb)); + frame(ctx, pointer(at, false), |ui| color_popover(ui, rgb)); +} + +#[test] +fn format_toggle_is_global_and_does_not_change_colour() { + let ctx = crate::fonts::test_context(); + let mut rgb = [204, 208, 214]; + frame(&ctx, vec![], |ui| color_popover(ui, &mut rgb)); + click(&ctx, "color:format:F", &mut rgb); + assert_eq!(ctx.style_of(egui::Theme::Light).visuals.numeric_color_space, egui::style::NumericColorSpace::Linear); + assert_eq!(rgb, [204, 208, 214]); + click(&ctx, "color:format:U8", &mut rgb); + assert_eq!(ctx.style_of(egui::Theme::Light).visuals.numeric_color_space, egui::style::NumericColorSpace::GammaByte); +} + +#[test] +fn square_and_hue_drag_edit_opaque_rgb() { + let ctx = crate::fonts::test_context(); + let mut rgb = [255, 0, 0]; + frame(&ctx, vec![], |ui| color_popover(ui, &mut rgb)); + let square = scenario::rect_of("color:sv").unwrap(); + let pos = egui::pos2(square.right(), square.top()); + frame(&ctx, pointer(pos, true), |ui| color_popover(ui, &mut rgb)); + frame(&ctx, vec![egui::Event::PointerMoved(square.center())], |ui| color_popover(ui, &mut rgb)); + frame(&ctx, pointer(square.center(), false), |ui| color_popover(ui, &mut rgb)); + let expected = Color32::from(HsvaGamma { h: 0.0, s: 0.5, v: 0.5, a: 1.0 }); + assert_eq!(rgb, [expected.r(), expected.g(), expected.b()]); + let hue = scenario::rect_of("color:hue").unwrap(); + frame(&ctx, pointer(hue.left_center(), true), |ui| color_popover(ui, &mut rgb)); + let pos = egui::pos2(hue.left() + hue.width() / 3.0, hue.center().y); + frame(&ctx, vec![egui::Event::PointerMoved(pos)], |ui| color_popover(ui, &mut rgb)); + frame(&ctx, pointer(pos, false), |ui| color_popover(ui, &mut rgb)); + let expected = Color32::from(HsvaGamma { h: 1.0 / 3.0, s: 0.5, v: 0.5, a: 1.0 }); + assert_eq!(rgb, [expected.r(), expected.g(), expected.b()]); +} + +#[test] +fn popover_opens_and_outside_click_closes() { + let ctx = crate::fonts::test_context(); + let mut rgb = [100, 120, 140]; + frame(&ctx, vec![], |ui| { + color_field(ui, &mut rgb); + }); + let at = scenario::handle_at("dialog:color:").unwrap(); + for pressed in [true, false] { + frame(&ctx, pointer(at, pressed), |ui| { + color_field(ui, &mut rgb); + }); + } + frame(&ctx, vec![], |ui| { + color_field(ui, &mut rgb); + }); + assert!(scenario::rect_of("color:popover").is_some()); + for pressed in [true, false] { + frame(&ctx, pointer(egui::pos2(315.0, 395.0), pressed), |ui| { + color_field(ui, &mut rgb); + }); + } + frame(&ctx, vec![], |ui| { + color_field(ui, &mut rgb); + }); + assert!(scenario::rect_of("color:popover").is_none()); +} + +#[test] +fn channel_edits_use_gamma_bytes_or_linear_values_and_copy_in_the_active_format() { + use crate::ui_kit::test_support::key; + for linear in [false, true] { + let ctx = crate::fonts::test_context(); + let mut rgb = [10, 20, 30]; + frame(&ctx, vec![], |ui| color_popover(ui, &mut rgb)); + if linear { + click(&ctx, "color:format:F", &mut rgb); + } + let at = scenario::handle_at("color:channel:R").unwrap(); + // DragValue switches to its text editor on a click; Ctrl/Cmd+A replaces the channel. + for pressed in [true, false] { + frame(&ctx, pointer(at, pressed), |ui| color_popover(ui, &mut rgb)); + } + let modifiers = egui::Modifiers { command: true, ctrl: true, ..Default::default() }; + frame( + &ctx, + vec![ + egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers }, + egui::Event::Text(if linear { "0.5" } else { "128" }.into()), + ], + |ui| color_popover(ui, &mut rgb), + ); + frame(&ctx, key(egui::Key::Enter), |ui| color_popover(ui, &mut rgb)); + assert_eq!(rgb, if linear { [188, 20, 30] } else { [128, 20, 30] }); + let copy = scenario::handle_at("color:copy").unwrap(); + frame(&ctx, pointer(copy, true), |ui| color_popover(ui, &mut rgb)); + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 400.0))), + events: pointer(copy, false), + focused: true, + ..Default::default() + }, + |ui| { + ui.set_width(280.0); + crate::ui_kit::scope(ui, |ui| color_popover(ui, &mut rgb)); + }, + ); + let [r, g, b] = rgb; + let [lr, lg, lb, _] = egui::Rgba::from(Color32::from_rgb(r, g, b)).to_array(); + let want = if linear { format!("{lr:.03}, {lg:.03}, {lb:.03}") } else { format!("{r}, {g}, {b}") }; + assert!( + output.platform_output.commands.iter().any(|c| matches!(c,egui::OutputCommand::CopyText(text) if text == &want)), + "{:?}", + output.platform_output.commands + ); + output.textures_delta.clear(); + } +} + +#[test] +fn changing_the_hue_of_grey_still_reports_a_manual_colour_edit() { + let ctx = crate::fonts::test_context(); + let mut rgb = [128, 128, 128]; + frame(&ctx, vec![], |ui| { + color_field(ui, &mut rgb); + }); + let at = scenario::handle_at("dialog:color:").unwrap(); + for pressed in [true, false] { + frame(&ctx, pointer(at, pressed), |ui| { + color_field(ui, &mut rgb); + }); + } + frame(&ctx, vec![], |ui| { + color_field(ui, &mut rgb); + }); + let hue = scenario::rect_of("color:hue").unwrap().center(); + frame(&ctx, pointer(hue, true), |ui| { + color_field(ui, &mut rgb); + }); + let mut changed = false; + frame(&ctx, pointer(hue, false), |ui| { + changed |= color_field(ui, &mut rgb).changed(); + }); + assert!(changed, "a hue edit clears the panel's named look even at zero saturation"); + assert_eq!(rgb, [128, 128, 128]); +} + +/// Rasterise the actual tessellated colour geometry at a physical pixel centre. All three +/// controls use the white atlas texel, so interpolated vertex colour is the fragment colour. +fn pixel(primitives: &[egui::ClippedPrimitive], at: egui::Pos2) -> [f32; 4] { + let mut pixel = [0.0; 4]; + let cross = |a: egui::Vec2, b: egui::Vec2| a.x * b.y - a.y * b.x; + for clipped in primitives { + if !clipped.clip_rect.contains(at) { + continue; + } + let egui::epaint::Primitive::Mesh(mesh) = &clipped.primitive else { continue }; + for triangle in mesh.indices.as_chunks::<3>().0 { + let [a, b, c] = triangle.map(|i| mesh.vertices[i as usize]); + let area = cross(b.pos - a.pos, c.pos - a.pos); + if area.abs() < 1e-6 { + continue; + } + let weights = [cross(b.pos - at, c.pos - at) / area, cross(c.pos - at, a.pos - at) / area, cross(a.pos - at, b.pos - at) / area]; + if weights.iter().any(|w| *w < 0.0) { + continue; + } + let mut src = [0.0; 4]; + for (vertex, weight) in [a, b, c].iter().zip(weights) { + for (channel, value) in src.iter_mut().zip(vertex.color.to_array()) { + *channel += f32::from(value) / 255.0 * weight; + } + } + for (dest, value) in pixel.iter_mut().zip(src) { + *dest = value + *dest * (1.0 - src[3]); + } + } + } + pixel +} + +#[test] +fn rendered_square_hue_and_current_strip_leave_rounded_corner_pixels_clear() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + for ppp in [1.0, 2.0] { + let ctx = crate::fonts::test_context(); + ctx.set_pixels_per_point(ppp); + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 500.0))), ..Default::default() }, + |ui| { + ui.set_width(280.0); + crate::ui_kit::scope(ui, |ui| color_popover(ui, &mut [80, 150, 90])); + }, + ); + output.textures_delta.clear(); + let primitives = ctx.tessellate(output.shapes, output.pixels_per_point); + for key in ["color:sv", "color:hue", "color:current"] { + let rect = scenario::rect_of(key).unwrap(); + // Sample the physical pixel just inside each bounding-box corner. The + // rounded outline and gradient must both leave this pixel transparent. + for corner in [rect.left_top(), rect.right_top(), rect.left_bottom(), rect.right_bottom()] { + let delta = rect.center() - corner; + let inward = vec2(delta.x.signum(), delta.y.signum()); + let at = corner + inward * (0.5 / ppp); + assert!(pixel(&primitives, at)[3] < 0.01, "{key} corner {at:?}, dark={dark}, ppp={ppp}"); + } + assert!(pixel(&primitives, rect.center())[3] > 0.99, "{key} still paints its interior"); + } + } + } + crate::theme::set_dark(previous); +} diff --git a/crates/ui-egui/src/ui_kit/disclosure.rs b/crates/ui-egui/src/ui_kit/disclosure.rs new file mode 100644 index 000000000..62ed11754 --- /dev/null +++ b/crates/ui-egui/src/ui_kit/disclosure.rs @@ -0,0 +1,36 @@ +//! One disclosure drawing for sections, trees, cards and window folds. +use crate::theme::Tokens; +use egui::{Color32, Painter, Pos2, Rect, Response, Ui, vec2}; + +/// Content visible: down. Content hidden: right. No animation, matching kit sections. +/// Tokens: form_section_icon_size; the caller supplies a semantic ink token. +pub(crate) fn disclosure(painter: &Painter, center: Pos2, open: bool, ink: Color32) { + let size = Tokens::get().form_section_icon_size; + let rect = Rect::from_center_size(center, vec2(size, size)); + crate::icons::paint_ink(painter, rect, if open { "chevron" } else { "chevron_right" }, ink); +} + +/// Fold action in existing chrome. Stable identity across state changes, with the caller's +/// translated tooltip and scenario handles. Tokens: control_radius, hover, form_ink/dim. +pub(crate) fn disclosure_button_at(ui: &mut Ui, rect: Rect, open: bool, label: &str) -> Response { + let t = Tokens::get(); + let response = ui.interact(rect, ui.make_persistent_id("disclosure_button"), egui::Sense::click()); + if response.clicked() { + response.request_focus(); + } + if response.hovered() { + ui.painter().rect_filled(rect, t.control_radius, t.hover); + } + disclosure(ui.painter(), rect.center(), open, if response.hovered() || response.has_focus() { t.form_ink } else { t.form_dim }); + response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, ui.is_enabled(), open, label)); + response.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(label) +} + +/// Dropdowns always point down, independently of popup state. Preserve their existing size. +pub(crate) fn dropdown_indicator(painter: &Painter, rect: Rect, ink: Color32) { + crate::icons::paint_ink(painter, rect, "chevron", ink); +} + +#[cfg(test)] +#[path = "disclosure_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/ui_kit/disclosure_tests.rs b/crates/ui-egui/src/ui_kit/disclosure_tests.rs new file mode 100644 index 000000000..2d3c15798 --- /dev/null +++ b/crates/ui-egui/src/ui_kit/disclosure_tests.rs @@ -0,0 +1,98 @@ +use crate::{icon_svg, scenario, theme::Tokens, ui_kit::*}; +use egui::{ColorImage, Pos2, Rect, vec2}; + +fn assert_glyph( + ctx: &egui::Context, + mut output: egui::FullOutput, + textures: &std::collections::HashMap, + at: Pos2, + open: bool, +) { + let t = Tokens::get(); + let size = t.form_section_icon_size; + let px = size.round() as u32; + // Compare the pixels actually uploaded by the widget against the specified SVG id, + // not a helper's return value or its state. Also check the mesh uses those pixels + // at the control's position without the former vertical flip. + let id = if open { "chevron" } else { "chevron_right" }; + let master = icon_svg::resolve(id).master; + let image = + icon_svg::render(icon_svg::doc_for(master, px).unwrap(), icon_svg::Look { dark: true, accent: None, vision: crate::theme::vision() }, px) + .unwrap(); + let mut expected = ColorImage::from_rgba_premultiplied([px as usize, px as usize], image.data()); + for pixel in &mut expected.pixels { + *pixel = t.form_dim.gamma_multiply(f32::from(pixel.a()) / 255.0); + } + let texture = textures + .iter() + .find_map(|(id, image)| (image == &expected).then_some(*id)) + .expect("widget must upload the specified disclosure SVG pixels at token size and ink"); + let meshes = ctx.tessellate(std::mem::take(&mut output.shapes), output.pixels_per_point); + let bounds = Rect::from_center_size(at, vec2(size + 2.0, size + 2.0)); + assert!( + meshes.iter().any(|clipped| { + let egui::epaint::Primitive::Mesh(mesh) = &clipped.primitive else { return false }; + mesh.texture_id == texture && bounds.contains_rect(mesh.calc_bounds()) && mesh.vertices.iter().all(|v| (v.pos.y < at.y) == (v.uv.y < 0.5)) + }), + "specified glyph must actually be drawn, without flipping, at {at:?}" + ); + output.textures_delta.clear(); +} + +#[test] +fn section_card_and_floating_window_folds_render_down_when_open_right_when_closed() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + for open in [false, true] { + for surface in ["section", "card", "window"] { + let ctx = crate::fonts::test_context(); + ctx.set_visuals(if dark { egui::Visuals::dark() } else { egui::Visuals::light() }); + let viewport = Rect::from_min_size(Pos2::ZERO, vec2(700.0, 500.0)); + let mut textures = std::collections::HashMap::new(); + // Windows need measuring passes before their first visible frame. + for pass in 0..3 { + let mut output = ctx.run_ui(egui::RawInput { screen_rect: Some(viewport), ..Default::default() }, |ui| { + ui.set_width(Tokens::get().form_card_width); + if surface == "section" { + section(ui, "section", "Advanced", open, |_| {}); + } else if surface == "card" { + collapsible_header(ui, "fillet", "Fillet", &mut !open, || {}); + } else { + Panel::new( + "Fillet", + egui::Id::new("window"), + egui::pos2(20.0, 20.0), + viewport, + crate::frame::Side::Left, + egui::Frame::NONE, + ) + .window() + .show(ui.ctx(), |ui| collapsible_header(ui, "fillet", "Fillet", &mut !open, || {})); + } + }); + for (id, deltas) in &output.textures_delta.set { + for delta in deltas { + let egui::ImageData::Color(image) = &delta.image; + if delta.pos.is_none() { + textures.insert(*id, image.as_ref().clone()); + } + } + } + output.textures_delta.clear(); + if pass != 2 { + continue; + } + let at = if surface == "section" { + let rect = scenario::rect_of("dialog:section:Advanced").unwrap(); + egui::pos2(rect.left() + Tokens::get().form_section_icon_size / 2.0, rect.center().y) + } else { + scenario::handle_at("dialog:collapse").unwrap() + }; + assert_glyph(&ctx, output, &textures, at, open); + } + } + } + } + crate::theme::set_dark(previous); +} diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs index eb14df913..0adde2223 100644 --- a/crates/ui-egui/src/ui_kit/fields.rs +++ b/crates/ui-egui/src/ui_kit/fields.rs @@ -7,6 +7,13 @@ use super::{ use crate::{scenario, theme::Tokens}; use egui::{Response, RichText, Ui, vec2}; +/// One alignment policy for every kit text input. Align the galley itself rather than +/// approximating font metrics with integer margins (Plex Mono and Sans differ). +fn text_input(edit: egui::TextEdit<'_>) -> egui::TextEdit<'_> { + let t = Tokens::get(); + edit.vertical_align(egui::Align::Center).margin(vec2(t.form_inset, 0.0)).min_size(vec2(0.0, t.control_height)) +} + /// Expression editor with the application's existing completion and number-focus behaviour. /// Values carry their own unit text ("20 mm", "45 deg"): there is no unit suffix. Returns accepted Enter. /// Tokens: `control_height, control_fill, form_inset, font_label, space_4; scope tokens`. @@ -49,12 +56,11 @@ pub(crate) fn multiline_text_field(ui: &mut Ui, label: &str, id: egui::Id, value let t = Tokens::get(); let response = ui.add_sized( vec2(dimension(ui.available_width()), row_height() * 3.0), - egui::TextEdit::multiline(value) + text_input(egui::TextEdit::multiline(value)) .id(id) .desired_rows(3) .font(egui::FontId::monospace(t.font_label)) - .background_color(t.control_fill) - .margin(vec2(t.form_inset, 0.0)), + .background_color(t.control_fill), ); publish(ui, &response, egui::WidgetType::TextEdit); response @@ -90,7 +96,7 @@ pub(crate) fn searchable_dropdown( .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show_ui(ui, |ui| { let search = ui.add( - egui::TextEdit::singleline(filter) + text_input(egui::TextEdit::singleline(filter)) .id_salt(format!("{id}_search")) .hint_text(crate::i18n::tr_label("Search")) .desired_width(f32::INFINITY), @@ -137,18 +143,9 @@ fn editor(ui: &mut Ui, value: &mut String, hint: &str, completion: bool) -> (boo let t = Tokens::get(); let width = dimension(ui.available_width()); let font = egui::FontId::monospace(t.font_label); - let line_height = ui.fonts_mut(|fonts| fonts.row_height(&font)) + ui.spacing().extra_text_line_spacing; - // Plex Mono's taller metrics must fit the 24 pt field without pushing the next row down. - // Margins use whole logical pixels; round down so the editor cannot grow beyond its row. - let margin_y = ((row_height() - line_height) * 0.5).floor().clamp(0.0, t.space_4); let response = ui.add_sized( vec2(width, row_height()), - egui::TextEdit::singleline(value) - .hint_text(hint) - .font(font) - .background_color(t.control_fill) - .margin(vec2(t.form_inset, margin_y)) - .clip_text(true), + text_input(egui::TextEdit::singleline(value)).hint_text(hint).font(font).background_color(t.control_fill).clip_text(true), ); crate::theme::TabAccent::number_focus(ui, &response); let label = crate::i18n::tr_label(label(ui)); @@ -165,7 +162,7 @@ fn editor(ui: &mut Ui, value: &mut String, hint: &str, completion: bool) -> (boo /// The one dropdown arrow every kit dropdown draws (the kit chevron, dimmed), instead of egui's triangle. fn dropdown_arrow(ui: &Ui, rect: egui::Rect, _visuals: &egui::style::WidgetVisuals, _open: bool) { - crate::icons::paint_ink(ui.painter(), rect, "chevron", Tokens::get().text_dim); + super::dropdown_indicator(ui.painter(), rect, Tokens::get().text_dim); } /// Native dropdown with kit arrow and scenario option handles. Tokens: `text_dim; scope control/font tokens`. @@ -185,7 +182,7 @@ pub(crate) fn dropdown(ui: &mut Ui, id: &str, selected: &mut usize, options: &[& pub(crate) fn dropdown_menu(ui: &mut Ui, id: impl egui::AsIdSalt, current: &str, add: impl FnOnce(&mut Ui)) -> Response { let response = egui::ComboBox::from_id_salt(id) .width(dimension(ui.available_width())) - .height(Tokens::get().control_height * 14.0) + .height(Tokens::get().space_24 * 14.0) .selected_text(current) .icon(dropdown_arrow) .show_ui(ui, add) @@ -204,13 +201,22 @@ pub(crate) fn selection_field(ui: &mut Ui, text: &str, options: Selection) -> Re let Selection { active, filled } = options; let t = Tokens::get(); let (rect, response) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), row_height()), egui::Sense::CLICK); - ui.painter().rect(rect, t.control_radius, t.selected_bg, egui::Stroke::new(if active { 1.0 } else { 0.0 }, t.accent), egui::StrokeKind::Inside); + if active && !filled { + ui.painter().rect_filled(rect, t.control_radius, t.selected_bg); + } + ui.painter().rect( + if active && !filled { rect.shrink(t.space_2) } else { rect }, + t.control_radius, + if filled { t.selected_bg } else { t.control_fill }, + egui::Stroke::new(1.0, if active || filled { t.form_primary } else { t.control_border }), + egui::StrokeKind::Inside, + ); let end = if filled { t.space_24 } else { t.space_8 }; let text_rect = egui::Rect::from_min_max( rect.min + vec2(t.form_inset.min(rect.width()), 0.0), egui::pos2((rect.right() - end).max(rect.left() + t.form_inset.min(rect.width())), rect.bottom()), ); - paint_text(ui, text_rect, text, crate::fonts::medium(t.font_label), if filled { t.selected_ink } else { t.text_dim }, false); + paint_text(ui, text_rect, text, crate::fonts::medium(t.font_label), if filled { t.selected_ink } else { t.form_dim }, false); publish(ui, &response, egui::WidgetType::Button); scenario::publish_rect(&format!("dialog:field:{}", label(ui)), rect); scenario::publish_count(&format!("dialog:selection:{}:filled", label(ui)), f64::from(filled)); @@ -257,19 +263,33 @@ pub(crate) fn cell_editor(ui: &mut Ui, id: egui::Id, value: &mut String, hint: & /// Stable-ID cell/name editor with a caller-supplied character cap. Tokens: cell_editor tokens. pub(crate) fn bounded_cell_editor(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str, invalid: bool, limit: usize) -> Response { + cell_editor_frame(ui, id, value, hint, invalid, limit, true) +} + +fn cell_editor_frame(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str, invalid: bool, limit: usize, frame: bool) -> Response { let t = Tokens::get(); - let response = ui.add_sized( - vec2(dimension(ui.available_width()), row_height()), - egui::TextEdit::singleline(value) - .char_limit(limit) - .id(id) - .hint_text(crate::i18n::tr_label(hint)) - .font(egui::FontId::monospace(t.font_label)) - .background_color(t.control_fill) - .text_color(if invalid { t.error } else { t.text }) - .margin(vec2(t.form_inset, 0.0)) - .clip_text(true), - ); + let editor = text_input(egui::TextEdit::singleline(value)) + .char_limit(limit) + .id(id) + .hint_text(crate::i18n::tr_label(hint)) + .font(if frame { egui::FontId::monospace(t.font_label) } else { egui::FontId::proportional(t.font_label) }) + .background_color(if invalid { t.form_error_fill } else { t.control_fill }) + .text_color(if invalid { t.form_error } else { t.form_ink }) + .clip_text(true); + let editor = if invalid { + editor.frame( + egui::Frame::NONE + .inner_margin(egui::Margin::symmetric(t.form_inset as i8, 0)) + .fill(t.form_error_fill) + .stroke(egui::Stroke::new(1.0, t.form_error)) + .corner_radius(t.control_radius), + ) + } else if frame { + editor + } else { + editor.frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(t.space_8 as i8, 0))) + }; + let response = ui.add_sized(vec2(dimension(ui.available_width()), row_height()), editor); publish(ui, &response, egui::WidgetType::TextEdit); response.widget_info(|| { let mut info = egui::WidgetInfo::labeled(egui::WidgetType::TextEdit, ui.is_enabled(), crate::i18n::tr_label(label(ui))); @@ -285,26 +305,83 @@ pub(crate) fn search_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint: cell_editor(ui, id, value, hint, false) } -/// Native colour chooser under the shared form styling. Colour is document data. -pub(crate) fn color_field(ui: &mut Ui, rgb: &mut [u8; 3]) -> Response { - let response = ui.color_edit_button_srgb(rgb); - scenario::publish_target(&format!("dialog:color:{}", label(ui)), response.rect); - response +/// Behaviour of the one kit slider. Appearance is always owned by `slider`. +/// Values/ranges stay in caller units; formatting never rounds saved values during drawing. +pub(crate) struct Slider { + pub step: Option, + pub format: fn(f64) -> String, + pub show_value: bool, + pub integer: bool, } -/// Continuous scalar control. Formatting never rounds saved values during drawing. -/// Tokens: control_height, space_24/4, scope control/font tokens. -pub(crate) fn slider(ui: &mut Ui, value: &mut f64, range: std::ops::RangeInclusive) -> Response { - let t = Tokens::get(); - ui.spacing_mut().slider_width = dimension(ui.available_width() - t.space_24 - t.space_24 - t.space_4); - let response = ui.add(egui::Slider::new(value, range).max_decimals_opt(None).custom_formatter(|v, _| format!("{v:.2}"))); - scenario::publish_target(&format!("dialog:slider:{}", label(ui)), response.rect); - response +impl Default for Slider { + fn default() -> Self { + Self { step: None, format: |v| format!("{v:.2}"), show_value: true, integer: false } + } +} + +/// The only slider element, including stepped preferences and editor-free timeline controls. +/// Native input, keyboard routing, enabled state and accessibility; one token-painted track/thumb. +/// Tokens: control_height, space_24/8/4/2, dialog_body/rule, control_fill, form_primary. +pub(crate) fn slider(ui: &mut Ui, value: &mut T, range: std::ops::RangeInclusive, options: Slider) -> Response { + // Own form styling even in callers such as the viewport menu which have no kit scope. + super::scope(ui, |ui| { + let t = Tokens::get(); + ui.style_mut().drag_value_text_style = egui::TextStyle::Monospace; + let limits = (range.start().to_f64(), range.end().to_f64()); + let reserved = if options.show_value { + // Reserve the actual formatted editor, including suffixes and localized Instant. + // Endpoints keep its width stable as a preference is dragged through its range. + let font = egui::TextStyle::Monospace.resolve(ui.style()); + let text_width = [limits.0, limits.1, value.to_f64()] + .into_iter() + .map(|v| ui.painter().layout_no_wrap((options.format)(v), font.clone(), t.form_ink).size().x.ceil()) + .fold(0.0, f32::max); + let editor_width = (text_width + ui.spacing().button_padding.x * 2.0).max(ui.spacing().interact_size.x); + (editor_width + ui.spacing().item_spacing.x).max(t.space_24 * 2.0 + t.space_4) + } else { + t.space_4 + }; + ui.spacing_mut().slider_width = dimension(ui.available_width() - reserved); + let mut widget = egui::Slider::new(value, range).show_value(options.show_value).handle_shape(egui::style::HandleShape::Circle); + if options.show_value { + widget = widget.custom_formatter(move |v, _| (options.format)(v)); + } + if let Some(step) = options.step { + widget = widget.step_by(step); + } + if options.integer { + widget = widget.integer(); + } + let response = ui.add(widget); + let slider = egui::Rect::from_min_size(response.rect.min, vec2(ui.spacing().slider_width, response.rect.height())); + let mut background = ui.painter().clone(); + background.set_opacity(if ui.is_visible() { 1.0 } else { 0.0 }); + background.rect_filled(slider, 0.0, t.dialog_body); + // Match egui's native input range (handle_radius = thickness / 2.5), so the + // painted thumb stays under the pointer even at the two ends of the range. + let input_radius = ui.text_style_height(&egui::TextStyle::Body).max(ui.spacing().interact_size.y) / 2.5; + let track = egui::Rect::from_center_size(slider.center(), vec2((slider.width() - input_radius * 2.0).max(0.0), t.space_4)); + let fraction = if limits.1 != limits.0 { ((value.to_f64() - limits.0) / (limits.1 - limits.0)).clamp(0.0, 1.0) as f32 } else { 0.0 }; + let center = egui::pos2(egui::lerp(track.x_range(), fraction), track.center().y); + ui.painter().rect_filled(track, t.control_radius, t.dialog_rule); + ui.painter().rect_filled(egui::Rect::from_min_max(track.min, egui::pos2(center.x, track.bottom())), t.control_radius, t.form_primary); + ui.painter().circle(center, t.space_8, t.control_fill, egui::Stroke::new(t.space_2, t.form_primary)); + publish(ui, &response, egui::WidgetType::Slider); + response.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), value.to_f64(), crate::i18n::tr_label(label(ui)))); + scenario::publish_rect(&format!("dialog:slider_track:{}", label(ui)), slider); + scenario::publish_target(&format!("dialog:slider:{}", label(ui)), response.rect); + response + }) } /// Locale-aware bounded scalar field, used for dimensionless material properties. pub(crate) fn scalar_field(ui: &mut Ui, value: &mut f64, range: std::ops::RangeInclusive) -> Response { - let response = ui.add(egui::DragValue::new(value).range(range).speed(0.01).custom_parser(crate::prefs::parse_number)); + ui.style_mut().drag_value_text_style = egui::TextStyle::Monospace; + let response = ui.add_sized( + vec2(dimension(ui.available_width()), row_height()), + egui::DragValue::new(value).range(range).speed(0.01).custom_parser(crate::prefs::parse_number), + ); scenario::publish_target(&format!("dialog:scalar:{}", label(ui)), response.rect); response } @@ -330,13 +407,12 @@ pub(crate) fn text_area(ui: &mut Ui, label: &str, id: egui::Id, value: &mut Stri let t = Tokens::get(); let response = ui.add_sized( vec2(dimension(ui.available_width()), row_height() * rows.clamp(1, 16) as f32), - egui::TextEdit::multiline(value) + text_input(egui::TextEdit::multiline(value)) .id(id) .desired_rows(rows.clamp(1, 16)) .char_limit(limit) .font(egui::FontId::monospace(t.font_label)) - .background_color(t.control_fill) - .margin(vec2(t.form_inset, 0.0)), + .background_color(t.control_fill), ); response.widget_info(|| { let mut info = egui::WidgetInfo::labeled(egui::WidgetType::TextEdit, ui.is_enabled(), label); @@ -352,13 +428,12 @@ pub(crate) fn password_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint let t = Tokens::get(); let response = ui.add_sized( vec2(dimension(ui.available_width()), row_height()), - egui::TextEdit::singleline(value) + text_input(egui::TextEdit::singleline(value)) .id(id) .password(true) .hint_text(hint) .font(egui::FontId::monospace(t.font_label)) - .background_color(t.control_fill) - .margin(vec2(t.form_inset, 0.0)), + .background_color(t.control_fill), ); publish(ui, &response, egui::WidgetType::TextEdit); response @@ -383,37 +458,19 @@ pub(crate) fn number_field( response } -/// Stepped slider retaining caller units/formatting (percent, multiplier, seconds). -/// Tokens: control_height, space_24/4, scope control/font tokens. -pub(crate) fn formatted_slider( - ui: &mut Ui, - value: &mut T, - range: std::ops::RangeInclusive, - step: f64, - format: impl Fn(f64) -> String + 'static, -) -> Response { - let t = Tokens::get(); - ui.spacing_mut().slider_width = dimension(ui.available_width() - t.space_24 * 2.0 - t.space_4); - let response = ui.add(egui::Slider::new(value, range).step_by(step).custom_formatter(move |v, _| format(v))); - response.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), value.to_f64(), crate::i18n::tr_label(label(ui)))); - super::layout::publish_geometry(ui, &response); - response -} - /// Growing plain-text message editor; its parent owns scrolling and Enter routing. /// Tokens: control_fill, form_inset, font_label. Use text_area for bounded data input. #[cfg(any(not(target_arch = "wasm32"), test))] pub(crate) fn message_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str) -> Response { let t = Tokens::get(); ui.add( - egui::TextEdit::multiline(value) + text_input(egui::TextEdit::multiline(value)) .id(id) .hint_text(hint) .desired_rows(2) .desired_width(f32::INFINITY) .font(egui::FontId::proportional(t.font_label)) - .background_color(t.control_fill) - .margin(vec2(t.form_inset, t.space_4)), + .background_color(t.control_fill), ) } @@ -428,31 +485,24 @@ fn length_drag<'a>(value: &'a mut f64, units: &str, decimals: u8) -> egui::DragV .custom_parser(move |text| crate::prefs::parse_length_mm(text, scale)) } -/// Timeline/drive slider without a numeric editor; the owning surface shows its value. -/// Whole steps round only while manipulating a timeline. Tokens: control_height, space_4. -pub(crate) fn timeline_slider(ui: &mut Ui, value: &mut f64, range: std::ops::RangeInclusive, whole_steps: bool) -> Response { - ui.spacing_mut().slider_width = dimension(ui.available_width() - Tokens::get().space_4); - let slider = egui::Slider::new(value, range).show_value(false); - let response = ui.add(if whole_steps { slider.integer() } else { slider }); - publish(ui, &response, egui::WidgetType::Slider); - response.widget_info(|| egui::WidgetInfo::slider(ui.is_enabled(), *value, crate::i18n::tr_label(label(ui)))); - response -} - /// Placement editor whose owner routes Enter and Tab (including rejected expressions). /// Completion remains with the caller. Tokens: cell_editor tokens. pub(crate) fn placement_field(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str) -> Response { let t = Tokens::get(); + let font = egui::FontId::proportional(t.font_body); + // Canvas editors must retain their native hit target: enlarging it intercepts nearby + // sketch picks. Keep the former line + space_2 above/below, with shared galley alignment. + let height = ui.fonts_mut(|fonts| fonts.row_height(&font)) + ui.spacing().extra_text_line_spacing + t.space_4; let response = ui.add( - egui::TextEdit::singleline(value) + text_input(egui::TextEdit::singleline(value)) .id(id) + .min_size(vec2(0.0, height)) .desired_width(t.control_height * 3.0 - t.space_6) .return_key(None) .event_filter(egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, ..Default::default() }) - .font(egui::FontId::proportional(t.font_body)) + .font(font) .background_color(t.control_fill) - .text_color(t.text) - .margin(vec2(t.space_4, t.space_2)) + .text_color(t.form_ink) .clip_text(true), ); publish(ui, &response, egui::WidgetType::TextEdit); @@ -464,3 +514,37 @@ pub(crate) fn placement_field(ui: &mut Ui, id: egui::Id, value: &mut String, hin crate::theme::TabAccent::number_focus(ui, &response); response.on_hover_text(crate::i18n::tr_label(hint)) } + +/// Attached Library dropdown and text editor inside one bordered control. +/// The caller retains draft, completion and commit ownership. +pub(crate) fn library_cell(ui: &mut Ui, id: egui::Id, value: &mut String, hint: &str, menu: impl FnOnce(&mut Ui)) -> Response { + let t = Tokens::get(); + let (rect, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), row_height()), egui::Sense::hover()); + ui.painter().rect(rect, t.control_radius, t.control_fill, egui::Stroke::new(1.0, t.control_border), egui::StrokeKind::Inside); + let split = (rect.right() - t.space_24).max(rect.left()); + let field = egui::Rect::from_min_max(rect.min, egui::pos2(split, rect.bottom())); + let response = ui + .scope_builder(egui::UiBuilder::new().max_rect(field).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| { + ui.set_clip_rect(ui.clip_rect().intersect(field)); + cell_editor_frame(ui, id, value, hint, false, usize::MAX, false) + }) + .inner; + let button = egui::Rect::from_min_max(egui::pos2(split, rect.top()), rect.max); + ui.painter().vline(split, rect.y_range(), egui::Stroke::new(1.0, t.dialog_rule)); + let library = super::icon_button_at(ui, button, "chevron", "Library"); + scenario::publish_handle("dialog:menu:Library", button.center()); + scenario::publish_rect("dialog:menu:Library", button); + let popup = egui::Popup::menu(&library); + let open = popup.is_open(); + popup.show(|ui| super::scope(ui, menu)); + if open { + ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)); + } + if value.is_empty() { response.on_hover_text(crate::i18n::tr_label(hint)) } else { response } +} + +/// Inline tree-name editor in caller-owned geometry; preserves its native focus and selection ID. +/// Tokens: text. The caller retains commit/cancel and select-all behavior. +pub(crate) fn inline_name(ui: &mut Ui, rect: egui::Rect, id: egui::Id, value: &mut String) -> Response { + ui.put(rect, egui::TextEdit::singleline(value).id(id).frame(egui::Frame::NONE).text_color(Tokens::get().text).vertical_align(egui::Align::Center)) +} diff --git a/crates/ui-egui/src/ui_kit/fields_tests.rs b/crates/ui-egui/src/ui_kit/fields_tests.rs index e22650f4e..032a64b78 100644 --- a/crates/ui-egui/src/ui_kit/fields_tests.rs +++ b/crates/ui-egui/src/ui_kit/fields_tests.rs @@ -4,6 +4,51 @@ use crate::ui_kit::*; use crate::scenario; use egui::Ui; +#[test] +fn every_text_input_centres_its_galley_for_mono_and_proportional_fonts() { + for case in ["expression", "plain", "cell", "invalid", "library", "placement", "password", "multiline", "area", "message"] { + let ctx = crate::fonts::test_context(); + let mut value = "Centred".to_owned(); + let mut rect = egui::Rect::NOTHING; + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + ui.set_width(280.0); + scope(ui, |ui| { + let id = ui.id().with(case); + rect = match case { + "expression" | "plain" => super::editor(ui, &mut value, "", case == "expression").2.rect, + "cell" | "invalid" => cell_editor(ui, id, &mut value, "", case == "invalid").rect, + "library" => library_cell(ui, id, &mut value, "", |_| {}).rect, + "placement" => placement_field(ui, id, &mut value, "").rect, + "password" => password_field(ui, id, &mut value, "").rect, + "multiline" => multiline_text_field(ui, "Text", id, &mut value).rect, + "area" => text_area(ui, "Text", id, &mut value, 3, 100).rect, + _ => message_field(ui, id, &mut value, "").rect, + }; + }); + }); + output.textures_delta.clear(); + let galley = output + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.job.text == value || (case == "password" && !text.galley.is_empty()) => Some(text), + _ => None, + }) + .unwrap_or_else(|| panic!("{case}: missing text")); + let center = galley.pos.y + galley.galley.rect.center().y; + assert!((center - rect.center().y).abs() < 0.01, "{case}: galley centre {center} differs from field {rect:?}"); + if case == "placement" { + let font = egui::FontId::proportional(crate::theme::Tokens::get().font_body); + let native = ctx.fonts_mut(|fonts| fonts.row_height(&font)) + + ctx.style_of(egui::Theme::Light).spacing.extra_text_line_spacing + + crate::theme::Tokens::get().space_4; + assert_eq!(rect.height(), native, "canvas editor retains its native hit target"); + } else if !matches!(case, "multiline" | "area" | "message") { + assert_eq!(rect.height(), crate::theme::Tokens::get().control_height, "{case}"); + } + } +} + #[test] fn tab_visits_expression_fields_in_row_order() { let ctx = crate::fonts::test_context(); diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs index 136008e31..403546218 100644 --- a/crates/ui-egui/src/ui_kit/gallery.rs +++ b/crates/ui-egui/src/ui_kit/gallery.rs @@ -28,6 +28,146 @@ macro_rules! element { // One entry per element/variant: names, rendering and geometry expectations stay together. const ELEMENTS: &[Element] = &[ + element!("mono_note", |ui, _| { + text(ui, "solid.fillet · replayable", Text::MonoNote("sample")); + }), + element!("color_thumbnail", |ui, _| { + color_thumbnail(ui, ui.id().with("thumb"), Tokens::get().accent, "Sample", ()); + }), + element!("list_frame", |ui, _| { + list_frame(ui, "sample", |ui| { + text(ui, "Sample", Text::Cell); + }); + }), + element!("segmented_primary", |ui, s| { + segmented(ui, &mut s.selected, &["U8", "F"], Segments { primary: true, ..Default::default() }); + }), + element!("color_popover", |ui, _| { + color_popover(ui, &mut [204, 208, 214]); + }), + element!("report_list", |ui, _| { + report_list(ui, "sample", 120.0, |ui| { + report_header(ui, "Internal error", 3, "2026-10-18 21:04:12", "Report", |ui| { + bin_button(ui, "Delete"); + }); + text(ui, "solid.fillet · replayable", Text::MonoNote("sample")); + }); + }), + element!("path_chip", |ui, _| { + path_chip(ui, "/reports", |ui| { + button(ui, "Copy path", Button::Normal); + }); + }), + element!("empty_box", |ui, _| { + empty_box(ui, "empty", "No crash reports."); + }), + element!("report_header", |ui, _| { + report_header(ui, "Internal error", 3, "2026-10-18 21:04:12", "Report", |ui| { + bin_button(ui, "Delete"); + }); + }), + element!("parameter_import", |ui, _| { + icon_label_button(ui, "Import…", "import_tray", true, false); + }), + element!("parameter_export_csv", |ui, _| { + icon_label_button(ui, "Export CSV…", "export_tray", true, false); + }), + element!("parameter_export_json", |ui, _| { + icon_label_button(ui, "Export JSON…", "export_tray", true, false); + }), + element!("icon_label_button", |ui, _| { + icon_label_button(ui, "Copy path", "copy", true, false); + }), + element!("section_count", |ui, _| { + section_count(ui, "count", "Parameters", false, Some(5), |_| {}); + }), + element!("bin_button", |ui, _| { + bin_button(ui, "Delete"); + }), + element!("active_pill", |ui, _| { + active_pill(ui); + }), + element!("library_cell", |ui, s| { + library_cell(ui, ui.id().with("library"), &mut s.value, "Default material", |ui| { + button(ui, "Steel", Button::Normal); + }); + }), + element!("add_prompt", "dialog:table:add_prompt:add", Some("dialog:table:add_prompt:add"), |ui, _| { + table(ui, "add_prompt", &[Column::new("Name", 1.0).flex()], "Empty", |ui, table| { + table.add_prompt(ui, "Add configuration", "Add configuration"); + }); + }), + element!("removable_header", |ui, _| { + ui.allocate_ui(vec2(140.0, row_height()), |ui| { + removable_header(ui, "Width"); + }); + }), + element!("plus_header", |ui, _| { + ui.allocate_ui(vec2(140.0, row_height()), |ui| { + ui.set_min_size(vec2(140.0, row_height())); + plus_header(ui, |_| {}); + }); + }), + element!("table_custom", |ui, _| { + table_custom(ui, "custom", &[Column::new("Name", 1.0)], "Empty", |ui, table| { + table.headers(ui, |_, _| false); + table.add_prompt(ui, "Add parameter", "Add parameter"); + }); + }), + element!("table_row_height", |ui, _| { + ui.allocate_space(vec2(table_row_height(), table_row_height())); + }), + element!("summary_row", |ui, s| { + summary_row(ui, "Rule", "Drives width = 120 mm", &mut s.checked, ContentWidth::button(ui, "Edit"), |ui| { + button(ui, "Edit", Button::Normal); + }); + }), + element!("compact_button", |ui, _| { + compact_button(ui, "▲", "Move up", true, false); + }), + element!("error", |ui, _| { + text(ui, "Invalid expression", Text::Error("gallery")); + }), + element!("table_flex", |ui, s| { + table( + ui, + "flex", + &[Column::new("Name", 1.0).flex(), Column::new("Expression", 1.5).flex(), Column::new("Actions", 0.0).icon_only()], + "Empty", + |ui, table| { + table.row(ui, "row", false, |row| { + row.cell(|ui| { + text(ui, "Width", Text::Cell); + }); + row.cell(|ui| { + cell_editor(ui, ui.id().with("expression"), &mut s.value, "Expression", false); + }); + row.cell(|ui| { + bin_button(ui, "Delete"); + }); + }); + table.add_prompt(ui, "Add parameter", "Add parameter"); + }, + ); + }), + element!("cell_name", |ui, _| { + text(ui, "Width", Text::NameCell(false)); + }), + element!("cell_name_strong", |ui, _| { + text(ui, "Default", Text::NameCell(true)); + }), + element!("text_heading", |ui, _| { + text(ui, "Configuration rules", Text::Heading("gallery")); + }), + element!("cell_mono", |ui, _| { + text(ui, "mm", Text::MonoCell); + }), + element!("cell_value", |ui, _| { + text(ui, "80.0000 mm", Text::Value("gallery_value", false)); + }), + element!("cell_value_error", |ui, _| { + text(ui, "Unknown parameter", Text::Value("gallery_value_error", true)); + }), element!("scope", |ui, _| { scope(ui, |ui| { ui.allocate_space(vec2(row_height(), row_height())); @@ -39,8 +179,8 @@ const ELEMENTS: &[Element] = &[ element!("header_height", |ui, _| { ui.allocate_space(vec2(header_height(), header_height())); }), - element!("timeline_slider", |ui, _| { - timeline_slider(ui, &mut 12.0, 0.0..=100.0, true); + element!("slider_integer_without_editor", |ui, _| { + slider(ui, &mut 12.0, 0.0..=100.0, Slider { show_value: false, integer: true, ..Default::default() }); }), element!("placement_field", |ui, s| { placement_field(ui, ui.id().with("placement"), &mut s.value, "Distance"); @@ -54,8 +194,8 @@ const ELEMENTS: &[Element] = &[ element!("number_field", |ui, _| { number_field(ui, &mut 3_u32, 1..=200, 1.0, ""); }), - element!("formatted_slider", |ui, _| { - formatted_slider(ui, &mut 1.0, 0.5..=2.5, 0.05, |v| format!("{:.0} %", v * 100.0)); + element!("slider_percent", |ui, _| { + slider(ui, &mut 1.0, 0.5..=2.5, Slider { step: Some(0.05), format: |v| format!("{:.0} %", v * 100.0), ..Default::default() }); }), element!("dropdown_menu", |ui, _| { dropdown_menu(ui, "gallery_menu", "Preset", |ui| { @@ -68,6 +208,12 @@ const ELEMENTS: &[Element] = &[ element!("text_lines", |ui, _| { text_lines(ui, "gallery", "Licence\nSecond line"); }), + element!("report_divider", "dialog:divider:gallery_report", None, |ui, _| { + report_list(ui, "gallery_report", row_height() * 3.0, |ui| { + text(ui, "Report message", Text::Report("gallery_report", false)); + report_divider(ui, "gallery_report"); + }); + }), element!("table", "dialog:table:gallery:row", None, |ui, s| { table(ui, "gallery", &[Column::new("Name", 1.0), Column::new("Expression", 1.5)], "No rows", |ui, table| { table.row(ui, "row", true, |row| { @@ -107,7 +253,10 @@ const ELEMENTS: &[Element] = &[ color_field(ui, &mut [120, 150, 180]); }), element!("slider", |ui, _| { - slider(ui, &mut 0.5, 0.0..=1.0); + slider(ui, &mut 0.5, 0.0..=1.0, Default::default()); + }), + element!("slider_disabled", |ui, _| { + ui.add_enabled_ui(false, |ui| slider(ui, &mut 0.5, 0.0..=1.0, Default::default())); }), element!("scalar_field", |ui, _| { scalar_field(ui, &mut 0.5, 0.0..=1.0); @@ -140,6 +289,31 @@ const ELEMENTS: &[Element] = &[ element!("header", "dialog:header", Some("dialog:close"), |ui, _| { header(ui, "fillet", "Fillet", || {}); }), + element!("disclosure", |ui, _| { + let t = Tokens::get(); + for open in [true, false] { + let (rect, _) = ui.allocate_exact_size(vec2(t.form_close_size, t.form_close_size), egui::Sense::hover()); + disclosure(ui.painter(), rect.center(), open, t.form_dim); + } + }), + element!("disclosure_button_at", |ui, _| { + let t = Tokens::get(); + for open in [true, false] { + let (rect, _) = ui.allocate_exact_size(vec2(t.form_close_size, t.form_close_size), egui::Sense::hover()); + ui.push_id(open, |ui| disclosure_button_at(ui, rect, open, crate::i18n::tr_label(if open { "Collapse" } else { "Expand" }))); + } + }), + element!("dropdown_indicator", |ui, _| { + let t = Tokens::get(); + let (rect, _) = ui.allocate_exact_size(vec2(t.form_section_icon_size, t.form_section_icon_size), egui::Sense::hover()); + dropdown_indicator(ui.painter(), rect, t.form_dim); + }), + element!("collapsible_header_closed", "dialog:header", Some("dialog:collapse"), |ui, _| { + collapsible_header(ui, "fillet", "Fillet", &mut true, || {}); + }), + element!("section_open", "dialog:section:Advanced", Some("dialog:section:Advanced"), |ui, _| { + section(ui, "gallery_open", "Advanced", true, |_| {}); + }), element!("collapsible_header", "dialog:header", Some("dialog:collapse"), |ui, _| { collapsible_header(ui, "fillet", "Fillet", &mut false, || {}); }), @@ -176,6 +350,10 @@ const ELEMENTS: &[Element] = &[ element!("value_pair_named", "dialog:row:Position", Some("dialog:Distance X"), |ui, s| { value_pair(ui, "Position", [&mut s.value, &mut s.second], ["X", "Y"], Some(["Distance X", "Distance Y"])); }), + element!("inline_name", |ui, s| { + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), row_height()), egui::Sense::hover()); + inline_name(ui, rect, ui.id().with("inline_name"), &mut s.value); + }), element!("field", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, s| { row(ui, "Gallery", |ui| { field(ui, &mut s.value); @@ -246,6 +424,48 @@ const ELEMENTS: &[Element] = &[ checkbox(ui, "Option", &mut s.checked); }); }), + element!("checkbox_off", |ui, _| { + checkbox(ui, "Option", &mut false); + }), + element!("checkbox_disabled_on", |ui, _| { + ui.add_enabled_ui(false, |ui| checkbox(ui, "Option", &mut true)); + }), + element!("checkbox_disabled_off", |ui, _| { + ui.add_enabled_ui(false, |ui| checkbox(ui, "Option", &mut false)); + }), + element!("checkbox_indeterminate", |ui, _| { + checkbox_indeterminate(ui, "Option", &mut false, true); + }), + element!("checkbox_disabled_mixed", |ui, _| { + ui.add_enabled_ui(false, |ui| checkbox_indeterminate(ui, "Option", &mut false, true)); + }), + element!("checkbox_focused", |ui, _| { + egui::Frame::new().inner_margin(Tokens::get().space_4).show(ui, |ui| { + checkbox(ui, "Option", &mut true).request_focus(); + }); + }), + element!("checkbox_focused_off", |ui, _| { + egui::Frame::new().inner_margin(Tokens::get().space_4).show(ui, |ui| { + checkbox(ui, "Option", &mut false).request_focus(); + }); + }), + element!("checkbox_focused_mixed", |ui, _| { + egui::Frame::new().inner_margin(Tokens::get().space_4).show(ui, |ui| { + checkbox_indeterminate(ui, "Option", &mut false, true).request_focus(); + }); + }), + element!("checkbox_hovered", |ui, _| { + checkbox(ui, "Option", &mut false); + }), + element!("checkbox_hovered_on", |ui, _| { + checkbox(ui, "Option", &mut true); + }), + element!("checkbox_hovered_mixed", |ui, _| { + checkbox_indeterminate(ui, "Option", &mut false, true); + }), + element!("command_menu_button", |ui, _| { + command_menu_button(ui, "save", "Save", "save", "Ctrl+S", true); + }), element!("primary_button", "dialog:row:Gallery", Some("dialog:button:Create"), |ui, _| { row(ui, "Gallery", |ui| { primary_button(ui, "Create"); @@ -341,7 +561,7 @@ const ELEMENTS: &[Element] = &[ ui.id().with("popup"), anchor, 0, - &[PopupOption { text: "Width", detail: "10 mm", color: Tokens::get().text }], + &[PopupOption { kind: "parameter", text: "Width", detail: "10 mm", color: Tokens::get().text }], "Choose", ); // The popup is on a separate layer; reserve its painted allocation for the same checks. @@ -365,12 +585,21 @@ fn every_element_has_geometry_and_stays_in_its_allocation_in_both_themes() { let name = element.name; let ctx = crate::fonts::test_context(); ctx.set_visuals(if dark { egui::Visuals::dark() } else { egui::Visuals::light() }); - for _ in 0..3 { + for pass in 0..3 { + let events = if element.name.starts_with("checkbox_hovered") && pass > 0 { + vec![egui::Event::PointerMoved(scenario::rect_of("gallery:allocation").expect("hover allocation").center())] + } else { + vec![] + }; scenario::clear_handles(); let mut allocation = egui::Rect::NOTHING; let mut published = ("", None); let mut output = ctx.run_ui( - egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 600.0))), ..Default::default() }, + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 600.0))), + events, + ..Default::default() + }, |ui| { ui.set_width(320.0); allocation = ui @@ -610,8 +839,8 @@ fn popup_suggestions_and_selectable_lists_keep_click_selection() { egui::Rect::from_min_size(egui::pos2(10.0, 10.0), vec2(220.0, 24.0)), 0, &[ - PopupOption { text: "width", detail: "Parameter · 10 mm", color: Tokens::get().text }, - PopupOption { text: "height", detail: "Parameter · 20 mm", color: Tokens::get().text }, + PopupOption { kind: "parameter", text: "width", detail: "Parameter · 10 mm", color: Tokens::get().text }, + PopupOption { kind: "parameter", text: "height", detail: "Parameter · 20 mm", color: Tokens::get().text }, ], "Choose", ); @@ -655,7 +884,7 @@ fn many_draggable_samples_wrap_inside_the_available_width() { }); }); assert_eq!(rects.len(), 20); - assert!(rects.iter().all(|rect| rect.right() <= bounds.right() && rect.width() == Tokens::get().control_height)); + assert!(rects.iter().all(|rect| rect.right() <= bounds.right() && rect.width() == Tokens::get().control_height + Tokens::get().space_6)); assert!(rects.last().unwrap().top() > rects.first().unwrap().top(), "samples must wrap to additional rows"); } @@ -664,7 +893,19 @@ fn gallery_covers_every_inline_element() { let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/ui_kit"); let names: std::collections::BTreeSet<_> = ELEMENTS.iter().map(|e| e.name).collect(); assert_eq!(names.len(), ELEMENTS.len(), "duplicate gallery entries"); - for file in ["actions.rs", "choice.rs", "fields.rs", "layout.rs", "metrics.rs", "status.rs", "table.rs"] { + for file in [ + "actions.rs", + "checks.rs", + "choice.rs", + "color.rs", + "disclosure.rs", + "fields.rs", + "layout.rs", + "metrics.rs", + "reports.rs", + "status.rs", + "table.rs", + ] { let source = std::fs::read_to_string(root.join(file)).unwrap(); let ast = syn::parse_file(&source).unwrap(); for item in ast.items { diff --git a/crates/ui-egui/src/ui_kit/layout.rs b/crates/ui-egui/src/ui_kit/layout.rs index c90dc27c6..6612d767c 100644 --- a/crates/ui-egui/src/ui_kit/layout.rs +++ b/crates/ui-egui/src/ui_kit/layout.rs @@ -17,8 +17,10 @@ pub(crate) fn scope(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { ui.spacing_mut().button_padding = vec2(t.space_8, t.space_4); ui.style_mut().text_styles.insert(egui::TextStyle::Body, egui::FontId::proportional(t.font_label)); ui.style_mut().text_styles.insert(egui::TextStyle::Button, egui::FontId::proportional(t.font_label)); + ui.style_mut().text_styles.insert(egui::TextStyle::Monospace, egui::FontId::monospace(t.font_body)); let visuals = ui.visuals_mut(); - visuals.selection.stroke = egui::Stroke::new(1.0, t.accent); + visuals.weak_text_color = Some(t.form_dim); + visuals.selection.stroke = egui::Stroke::new(1.0, t.form_primary); visuals.selection.bg_fill = t.selected_bg; visuals.widgets.noninteractive.bg_stroke = egui::Stroke::new(1.0, t.dialog_rule); for state in [&mut visuals.widgets.inactive, &mut visuals.widgets.hovered, &mut visuals.widgets.active, &mut visuals.widgets.open] { @@ -27,7 +29,7 @@ pub(crate) fn scope(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> R { state.bg_stroke = egui::Stroke::new(1.0, t.control_border); state.corner_radius = t.control_radius.into(); state.expansion = 0.0; - state.fg_stroke.color = t.text; + state.fg_stroke.color = t.form_ink; } ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); add(ui) @@ -47,7 +49,7 @@ pub(super) fn publish(ui: &Ui, response: &Response, kind: egui::WidgetType) { publish_geometry(ui, response); } -/// Aligned label/control row, 24 pt today. Tokens: `control_height, form_label_width, font_label, dialog_label, space_8`. +/// Aligned label/control row, 28 pt. Tokens: `control_height, form_label_width, font_label, dialog_label, space_8`. pub(crate) fn row(ui: &mut Ui, text: &str, control: impl FnOnce(&mut Ui) -> R) -> R { sized_row(ui, text, row_height(), control) } @@ -84,7 +86,7 @@ pub(super) fn sized_row(ui: &mut Ui, text: &str, height: f32, control: impl F ui.add(egui::Label::new(RichText::new(crate::i18n::tr_label(text)).size(t.font_label).color(t.dialog_label)).truncate()) .on_hover_text(crate::i18n::tr_label(text)); }); - let control_rect = egui::Rect::from_min_max(egui::pos2((label_rect.right() + t.space_8).min(rect.right()), rect.top()), rect.max); + let control_rect = egui::Rect::from_min_max(egui::pos2((label_rect.right() + label_gap(width)).min(rect.right()), rect.top()), rect.max); let result = ui .scope_builder( egui::UiBuilder::new() @@ -113,22 +115,32 @@ pub(crate) fn caption(ui: &mut Ui, aligned_to: &str, text: &str) { let t = Tokens::get(); let width = dimension(ui.available_width()); let (rect, _) = ui.allocate_exact_size(vec2(width, t.form_icon_size), egui::Sense::hover()); - let left = (rect.left() + label_column(ui, aligned_to, width) + t.space_8).min(rect.right()); + let left = (rect.left() + label_column(ui, aligned_to, width) + label_gap(width)).min(rect.right()); let text_rect = egui::Rect::from_min_max(egui::pos2(left, rect.top()), rect.max); - paint_text(ui, text_rect, text, egui::FontId::proportional(t.font_small), t.text_dim, false); + paint_text(ui, text_rect, text, egui::FontId::proportional(t.font_small), t.form_dim, false); scenario::publish_rect(&format!("dialog:caption:{aligned_to}"), text_rect); } /// Memory belongs to the enclosing dialog ID; animation is avoided so each row keeps its fixed height. /// Persisted disclosure with a rule and uppercase title. Tokens: `control_height, space_2, radius_sm, hover, dialog_rule, form_section_icon_size, form_gap_y, font_caption, font_section_tracking, text_dim`. pub(crate) fn section(ui: &mut Ui, id: impl egui::AsIdSalt, title: &str, default_open: bool, add: impl FnOnce(&mut Ui) -> R) -> Option { + section_count(ui, id, title, default_open, None, add) +} + +/// Section heading with an optional count badge; disclosure state uses the same identity. +pub(crate) fn section_count( + ui: &mut Ui, + id: impl egui::AsIdSalt, + title: &str, + default_open: bool, + count: Option, + add: impl FnOnce(&mut Ui) -> R, +) -> Option { let t = Tokens::get(); ui.add_space(t.space_2); let id = ui.make_persistent_id(id); let mut open = ui.ctx().data_mut(|data| data.get_persisted::(id)).unwrap_or(default_open); let (rect, response) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), row_height()), egui::Sense::click()); - // The section's top rule is the border of its header row. - ui.painter().hline(rect.x_range(), rect.top(), egui::Stroke::new(1.0, t.dialog_rule)); if response.hovered() || response.has_focus() { ui.painter().rect_filled(rect.shrink2(vec2(0.0, 1.0)), t.radius_sm, t.hover); } @@ -136,9 +148,33 @@ pub(crate) fn section(ui: &mut Ui, id: impl egui::AsIdSalt, title: &str, defa egui::pos2(rect.left() + t.form_section_icon_size / 2.0, rect.center().y), vec2(t.form_section_icon_size, t.form_section_icon_size), ); - crate::icons::paint_ink(ui.painter(), icon_rect, if open { "chevron" } else { "chevron_right" }, t.text_dim); + super::disclosure(ui.painter(), icon_rect.center(), open, t.form_dim); let text_rect = egui::Rect::from_min_max(egui::pos2((icon_rect.right() + t.form_gap_y).min(rect.right()), rect.top()), rect.max); - paint_text(ui, text_rect, &crate::i18n::tr_label(title).to_uppercase(), crate::fonts::semibold(t.font_caption), t.text_dim, true); + let caption = crate::i18n::tr_label(title).to_uppercase(); + let badge_value = count.map(|count| count.to_string()); + let badge_width = badge_value.as_ref().map_or(0.0, |value| label_width(ui, value) + t.space_12); + let reserved = if badge_value.is_some() { badge_width + t.space_12 } else { 0.0 }; + let title_width = label_width(ui, &caption).min((text_rect.width() - reserved).max(0.0)); + let title_rect = egui::Rect::from_min_max(text_rect.min, egui::pos2(text_rect.left() + title_width, text_rect.bottom())); + paint_text(ui, title_rect, &caption, crate::fonts::semibold(t.font_caption), t.form_dim, true); + let mut rule_left = title_rect.right() + t.space_12; + if let Some(value) = badge_value { + let width = badge_width.min((rect.right() - rule_left).max(0.0)); + let badge = egui::Rect::from_min_size(egui::pos2(rule_left.min(rect.right()), rect.center().y - t.space_10), vec2(width, t.space_10 * 2.0)); + ui.painter().rect_filled(badge, t.radius_xl, t.dialog_footer); + ui.painter().with_clip_rect(ui.clip_rect().intersect(badge)).text( + badge.center(), + egui::Align2::CENTER_CENTER, + value, + egui::FontId::proportional(t.font_small), + t.form_dim, + ); + scenario::publish_rect(&format!("dialog:section:{title}:count"), badge); + rule_left = badge.right() + t.space_12; + } + if rule_left < rect.right() { + ui.painter().hline(rule_left..=rect.right(), rect.center().y, egui::Stroke::new(1.0, t.dialog_rule)); + } response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::CollapsingHeader, ui.is_enabled(), open, crate::i18n::tr_label(title))); scenario::publish_handle(&format!("dialog:section:{title}"), response.rect.center()); scenario::publish_rect(&format!("dialog:section:{title}"), rect); @@ -157,7 +193,7 @@ pub(crate) fn list_row(ui: &mut Ui, key: &str, text: &str) -> Response { let (rect, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), row_height()), egui::Sense::hover()); let remove = egui::Rect::from_min_max(egui::pos2((rect.right() - row_height()).max(rect.left()), rect.top()), rect.max); let label = egui::Rect::from_min_max(rect.min, egui::pos2((remove.left() - t.space_8).max(rect.left()), rect.bottom())); - paint_text(ui, label, text, egui::FontId::proportional(t.font_label), t.text, false); + paint_text(ui, label, text, egui::FontId::proportional(t.font_label), t.form_ink, false); let response = ui.push_id(key, |ui| super::icon_button_at(ui, remove, "close", "Remove")).inner; scenario::publish_rect(&format!("dialog:list:{key}"), rect); scenario::publish_handle(&format!("dialog:list:{key}:remove"), remove.center()); @@ -189,16 +225,17 @@ pub(super) fn publish_geometry(ui: &Ui, response: &Response) { #[path = "layout_tests.rs"] mod tests; -/// Large read-only licence/report with equal-height virtualized lines and horizontal overflow. +/// Large read-only licence/report with equal-height virtualized lines. Long lines elide; +/// hovering exposes the full line without introducing a horizontal scrollbar. /// Tokens: font_small, text, control_height. Only visible lines are laid out. pub(crate) fn text_lines(ui: &mut Ui, id: &str, text: &str) { let t = Tokens::get(); let lines: Vec<_> = text.lines().collect(); let font = egui::FontId::monospace(t.font_small); let height = ui.fonts_mut(|f| f.row_height(&font)); - let response = egui::ScrollArea::both().id_salt(id).max_height(t.control_height * 15.0).show_rows(ui, height, lines.len(), |ui, rows| { + let response = egui::ScrollArea::vertical().id_salt(id).max_height(t.control_height * 15.0).show_rows(ui, height, lines.len(), |ui, rows| { for line in lines.get(rows).unwrap_or_default() { - ui.add(egui::Label::new(RichText::new(*line).font(font.clone()).color(t.text)).extend()); + ui.add(egui::Label::new(RichText::new(*line).font(font.clone()).color(t.form_ink)).truncate()).on_hover_text(*line); } }); scenario::publish_rect(&format!("dialog:lines:{id}"), response.inner_rect); @@ -208,50 +245,111 @@ pub(crate) fn text_lines(ui: &mut Ui, id: &str, text: &str) { pub(crate) enum Text<'a> { Hint(&'a str), Note(&'a str), + MonoNote(&'a str), Report(&'a str, bool), + Error(&'a str), + Heading(&'a str), Inline, Cell, + NameCell(bool), + MonoCell, + Value(&'a str, bool), } pub(crate) fn text(ui: &mut Ui, text: &str, style: Text<'_>) -> Response { let t = Tokens::get(); - let fixed = matches!(style, Text::Hint(_) | Text::Cell); + let fixed = matches!(style, Text::Cell | Text::NameCell(_) | Text::MonoCell | Text::Value(_, _)); let ink = match style { - Text::Hint(_) | Text::Note(_) => t.text_dim, - Text::Report(_, true) => t.error, - _ => t.text, + Text::Hint(_) | Text::Note(_) | Text::MonoNote(_) => t.form_dim, + Text::Report(_, true) | Text::Value(_, true) | Text::Error(_) => t.form_error, + _ => t.form_ink, + }; + let font = match style { + Text::NameCell(true) => crate::fonts::semibold(t.font_label), + Text::NameCell(false) => crate::fonts::medium(t.font_label), + Text::Heading(_) => crate::fonts::semibold(t.font_button), + Text::MonoCell | Text::Value(_, _) => egui::FontId::monospace(t.font_body), + Text::MonoNote(_) => egui::FontId::monospace(t.font_small), + Text::Hint(_) | Text::Error(_) => egui::FontId::proportional(t.font_body), + Text::Note(_) => egui::FontId::proportional(t.font_small), + _ => egui::FontId::proportional(t.font_label), }; - let font = egui::FontId::proportional(if matches!(style, Text::Hint(_) | Text::Note(_)) { t.font_small } else { t.font_label }); let response = if fixed { let (rect, response) = ui.allocate_exact_size( vec2(dimension(ui.available_width()), row_height()), - if matches!(style, Text::Cell) { egui::Sense::click() } else { egui::Sense::hover() }, + if matches!(style, Text::Value(_, _)) { egui::Sense::hover() } else { egui::Sense::click() }, ); paint_text(ui, rect, text, font, ink, false); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), text)); response.on_hover_text(text) - } else if matches!(style, Text::Note(_)) { + } else if matches!(style, Text::Error(_)) { + egui::Frame::NONE + .fill(t.form_error_fill) + .corner_radius(t.control_radius) + .inner_margin(egui::Margin::symmetric(t.form_inset as i8, t.space_6 as i8)) + .show(ui, |ui| { + ui.set_min_width(dimension(ui.available_width())); + ui.add(egui::Label::new(RichText::new(text).font(font).color(ink)).wrap()) + }) + .inner + } else if matches!(style, Text::Hint(_) | Text::Note(_) | Text::MonoNote(_)) { let width = dimension(ui.available_width()); let galley = ui.painter().layout(text.to_owned(), font, ink, width); - let (rect, response) = ui.allocate_exact_size(vec2(width, galley.size().y + t.space_4 * 2.0), egui::Sense::hover()); - ui.painter().galley(egui::pos2(rect.left(), rect.top() + t.space_4), galley, ink); + let padding = if matches!(style, Text::Note(_) | Text::MonoNote(_)) { t.space_4 } else { 0.0 }; + let (rect, response) = ui.allocate_exact_size(vec2(width, galley.size().y + padding * 2.0), egui::Sense::hover()); + ui.painter().galley(egui::pos2(rect.left(), rect.top() + padding), galley, ink); response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), text)); response } else { let label = egui::Label::new(RichText::new(text).font(font).color(ink)); ui.add(if matches!(style, Text::Inline) { label.truncate() } else { label.wrap() }) }; + let response = if matches!(style, Text::Hint(_)) { response.on_hover_text(text) } else { response }; let (kind, key) = match style { Text::Hint(key) => ("hint", key), - Text::Note(key) => ("note", key), - Text::Report(key, _) => ("report", key), + Text::Note(key) | Text::MonoNote(key) => ("note", key), + Text::Report(key, _) | Text::Value(key, _) | Text::Error(key) | Text::Heading(key) => ("report", key), Text::Inline => ("inline", text), - Text::Cell => ("cell", text), + Text::Cell | Text::MonoCell | Text::NameCell(_) => ("cell", text), }; let id = format!("dialog:{kind}:{key}"); scenario::publish_rect(&id, response.rect); - if !matches!(style, Text::Note(_)) { + if !matches!(style, Text::Note(_) | Text::MonoNote(_)) { scenario::publish_handle(&id, response.rect.center()); } response } + +/// A two-line named item beside an enable checkbox and compact actions. +/// Tokens: control_height, space_4/8/16, dialog_rule/footer, form_ink/dim, font_label/small. +pub(crate) fn summary_row(ui: &mut Ui, name: &str, summary: &str, enabled: &mut bool, actions_width: f32, actions: impl FnOnce(&mut Ui)) -> bool { + let t = Tokens::get(); + let (rect, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), row_height() + t.space_16), egui::Sense::hover()); + ui.painter().rect(rect, t.radius_lg, t.dialog_body, egui::Stroke::new(1.0, t.dialog_rule), egui::StrokeKind::Inside); + let check = egui::Rect::from_min_size(rect.min + vec2(t.space_6, 0.0), vec2(t.space_24, rect.height())); + let changed = ui + .scope_builder(egui::UiBuilder::new().max_rect(check).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| { + super::checkbox(ui, "", enabled).on_hover_text(crate::i18n::tr_label("Enable rule")).changed() + }) + .inner; + let right = (rect.right() - dimension(actions_width) - t.space_6).max(check.right()); + let text = egui::Rect::from_min_max( + egui::pos2(check.right() + t.space_4, rect.top()), + egui::pos2((right - t.space_8).max(check.right() + t.space_4), rect.bottom()), + ); + let title = egui::Rect::from_min_max(text.min, egui::pos2(text.right(), text.center().y)); + let detail = egui::Rect::from_min_max(egui::pos2(text.left(), text.center().y), text.max); + paint_text(ui, title, name, crate::fonts::semibold(t.font_label), t.form_ink, false); + paint_text(ui, detail, summary, egui::FontId::proportional(t.font_small), t.form_dim, false); + let response = ui.interact(text, ui.id().with("summary"), egui::Sense::hover()).on_hover_text(summary); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), format!("{name}: {summary}"))); + scenario::publish_rect(&format!("dialog:inline:{name}"), title); + scenario::publish_rect("dialog:report:rule_report", detail); + ui.scope_builder( + egui::UiBuilder::new() + .max_rect(egui::Rect::from_min_max(egui::pos2(right, rect.top()), rect.max)) + .layout(egui::Layout::left_to_right(egui::Align::Center)), + actions, + ); + changed +} diff --git a/crates/ui-egui/src/ui_kit/layout_tests.rs b/crates/ui-egui/src/ui_kit/layout_tests.rs index a67394856..b6fb0e488 100644 --- a/crates/ui-egui/src/ui_kit/layout_tests.rs +++ b/crates/ui-egui/src/ui_kit/layout_tests.rs @@ -24,7 +24,7 @@ fn row_height_and_label_column_are_fixed_for_long_labels_and_expressions() { let control = scenario::rect_of("dialog:control:Radius").unwrap(); assert_eq!(first.height(), Tokens::get().control_height); assert_eq!(second.height(), Tokens::get().control_height); - // The design's grid: 24 pt controls with a 5 pt row gap and a 70 pt label column (wider only for long labels). + // The design's grid: 28 pt controls with a 5 pt row gap and a 70 pt label column (wider only for long labels). assert!( (second.top() - first.bottom() - Tokens::get().form_gap_y).abs() < 0.01, "Plex Mono fields must retain the row gap: {first:?}, {second:?}" diff --git a/crates/ui-egui/src/ui_kit/metrics.rs b/crates/ui-egui/src/ui_kit/metrics.rs index c1b5bab1c..649500e64 100644 --- a/crates/ui-egui/src/ui_kit/metrics.rs +++ b/crates/ui-egui/src/ui_kit/metrics.rs @@ -41,6 +41,12 @@ impl ContentWidth { label_width(ui, text) } + /// Width of a strong configuration name, using the same font as its table cell. + pub(crate) fn name(ui: &Ui, text: &str) -> f32 { + let t = Tokens::get(); + ui.painter().layout_no_wrap(text.to_owned(), crate::fonts::semibold(t.font_label), t.form_ink).size().x.ceil() + } + pub(crate) fn button(ui: &Ui, label: &str) -> f32 { label_width(ui, label) + 2.0 * ui.spacing().button_padding.x } @@ -49,11 +55,6 @@ impl ContentWidth { let text = options.iter().map(|text| label_width(ui, text)).fold(0.0, f32::max); text + 2.0 * ui.spacing().button_padding.x + ui.spacing().icon_width + ui.spacing().icon_spacing } - - pub(crate) fn editor(ui: &Ui, value: &str) -> f32 { - let t = Tokens::get(); - ui.painter().layout_no_wrap(value.to_owned(), egui::FontId::monospace(t.font_label), t.text).size().x.ceil() + 2.0 * t.form_inset - } } /// Width of a table header column, measured directly: it never touches the form's shared label-column state. @@ -72,7 +73,9 @@ pub(super) fn header_column(ui: &Ui, text: &str) -> f32 { /// Shared label width, capped at 1.6x. Tokens: `form_label_width, font_label, dialog_label, space_4`. pub(super) fn label_column(ui: &Ui, text: &str, row_width: f32) -> f32 { let t = Tokens::get(); - let base = t.form_label_width; + // Wide manager cards use the approved 104 pt label column; compact cards retain room + // for their existing controls. Both sizes derive from the same form/spacing tokens. + let base = if row_width >= t.form_card_width + t.space_24 * 2.0 { t.form_label_width + t.space_24 + t.space_10 } else { t.form_label_width }; let natural = label_width(ui, text); let widest = match ui.stack().iter().find(|node| node.tags().contains(FORM)).map(|node| node.id) { Some(form) => { @@ -98,3 +101,14 @@ pub(super) fn label_column(ui: &Ui, text: &str, row_width: f32) -> f32 { #[cfg(test)] #[path = "metrics_tests.rs"] mod tests; + +/// Table rows leave four points above/below the shared control. Tokens: control_height, space_8. +pub(crate) fn table_row_height() -> f32 { + Tokens::get().control_height + Tokens::get().space_8 +} + +/// Label/control gutter for the same responsive form grid as label_column. +pub(super) fn label_gap(width: f32) -> f32 { + let t = Tokens::get(); + if width >= t.form_card_width + t.space_24 * 2.0 { t.space_10 } else { t.space_8 } +} diff --git a/crates/ui-egui/src/ui_kit/mod.rs b/crates/ui-egui/src/ui_kit/mod.rs index 4c801aa7a..5d7fd2d4f 100644 --- a/crates/ui-egui/src/ui_kit/mod.rs +++ b/crates/ui-egui/src/ui_kit/mod.rs @@ -2,29 +2,39 @@ //! `Panel` owns card composition; rows own aligned label/control columns and retain egui focus. //! Geometry, typography and colours come from `theme::Tokens`. See `docs/ui-kit.md`. mod actions; +mod checks; mod choice; +mod color; +mod disclosure; mod fields; mod layout; mod metrics; pub(crate) mod panel; +mod reports; mod status; mod table; mod text; pub(crate) use actions::*; +pub(crate) use checks::*; pub(crate) use choice::*; +pub(crate) use color::*; +pub(crate) use disclosure::*; pub(crate) use fields::*; pub(crate) use layout::*; -pub(crate) use metrics::{ContentWidth, header_height, row_height}; +pub(crate) use metrics::{ContentWidth, header_height, row_height, table_row_height}; pub(crate) use panel::{ComputeStatus, FeatureOptions, Panel, Part, Prompt}; #[cfg(test)] pub(crate) use panel::{collapsible_header, header}; +pub(crate) use reports::*; pub(crate) use status::*; pub(crate) use table::*; #[cfg(test)] mod gallery; #[cfg(test)] +mod slider_tests; +#[cfg(test)] #[path = "test_support_tests.rs"] mod test_support; diff --git a/crates/ui-egui/src/ui_kit/panel.rs b/crates/ui-egui/src/ui_kit/panel.rs index 1497a3eeb..8d3f7259d 100644 --- a/crates/ui-egui/src/ui_kit/panel.rs +++ b/crates/ui-egui/src/ui_kit/panel.rs @@ -9,7 +9,7 @@ pub(crate) fn header(ui: &mut Ui, icon: &str, title: &str, on_close: impl FnOnce } /// Optional fold action for managers which historically hide their inputs without losing edits. -/// Tokens: header tokens and space_4; retains the legacy chevron accessibility identities. +/// Tokens: header tokens and space_4; retains the dialog:collapse scenario handle. pub(crate) fn collapsible_header(ui: &mut Ui, icon: &str, title: &str, collapsed: &mut bool, on_close: impl FnOnce()) { header_impl(ui, icon, title, Some(collapsed), on_close); } @@ -17,9 +17,9 @@ pub(crate) fn collapsible_header(ui: &mut Ui, icon: &str, title: &str, collapsed fn header_impl(ui: &mut Ui, icon: &str, title: &str, collapsed: Option<&mut bool>, on_close: impl FnOnce()) { let t = Tokens::get(); let (rect, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), header_height()), egui::Sense::hover()); - // Design: padding 0 8 0 10, an 18 pt icon, a 7 pt gap, a 22 pt close button. + // Shared card chrome: 12 pt left inset, 19 pt icon, 8 pt gap and 26 pt close target. let icon_rect = egui::Rect::from_center_size( - egui::pos2(rect.left() + t.space_10 + t.form_icon_size / 2.0, rect.center().y), + egui::pos2(rect.left() + t.space_12 + t.form_icon_size / 2.0, rect.center().y), vec2(t.form_icon_size, t.form_icon_size), ); crate::icons::paint_icon(ui.painter(), icon_rect, icon, 1.0); @@ -34,8 +34,7 @@ fn header_impl(ui: &mut Ui, icon: &str, title: &str, collapsed: Option<&mut bool } let right = if let Some(collapsed) = collapsed { let fold = egui::Rect::from_min_size(egui::pos2(close_rect.left() - t.form_close_size - t.space_4, close_rect.top()), close_rect.size()); - let response = icon_button_at(ui, fold, if *collapsed { "chevron" } else { "chevron_right" }, if *collapsed { "«" } else { "»" }) - .on_hover_text(crate::i18n::tr_label(if *collapsed { "Expand" } else { "Collapse" })); + let response = super::disclosure_button_at(ui, fold, !*collapsed, crate::i18n::tr_label(if *collapsed { "Expand" } else { "Collapse" })); scenario::publish_handle("dialog:collapse", response.rect.center()); if response.clicked() { *collapsed = !*collapsed; @@ -44,9 +43,9 @@ fn header_impl(ui: &mut Ui, icon: &str, title: &str, collapsed: Option<&mut bool } else { close_rect.left() }; - let left = (icon_rect.right() + t.form_inset).min(right); + let left = (icon_rect.right() + t.space_8).min(right); let title_rect = egui::Rect::from_min_max(egui::pos2(left, rect.top()), egui::pos2(right.max(left), rect.bottom())); - paint_text(ui, title_rect, title, crate::fonts::semibold(t.font_label), t.text, false); + paint_text(ui, title_rect, title, crate::fonts::semibold(t.font_heading), t.form_ink, false); let title_response = ui.interact(title_rect, ui.make_persistent_id("title_text"), egui::Sense::hover()); title_response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), title)); scenario::publish_rect("dialog:header", rect); @@ -65,6 +64,7 @@ pub(crate) struct Panel<'a> { width: f32, ok: &'a str, cancel: &'a str, + reset_scroll: bool, } pub(crate) struct FeatureOptions<'a> { @@ -94,7 +94,7 @@ impl<'a> Panel<'a> { pub(crate) fn feature_frame(ctx: &egui::Context, layout: crate::shell::LayoutMode, side: crate::frame::Side) -> egui::Frame { let t = Tokens::get(); if layout == crate::shell::LayoutMode::Floating { - crate::frame::shell_card(t.dialog_body).inner_margin(0.0) + crate::frame::shell_card(t.dialog_body).stroke(egui::Stroke::new(1.0, t.dialog_border)).corner_radius(t.radius_xl).inner_margin(0.0) } else { crate::frame::dock_frame(ctx, side).fill(t.dialog_body).inner_margin(0.0) } @@ -111,7 +111,13 @@ impl<'a> Panel<'a> { } pub(crate) fn new(title: &'a str, id: egui::Id, anchor: egui::Pos2, viewport: egui::Rect, side: crate::frame::Side, frame: egui::Frame) -> Self { - Self { title, id, anchor, viewport, side, frame, width: Tokens::get().form_card_width, ok: "OK", cancel: "Cancel" } + Self { title, id, anchor, viewport, side, frame, width: Tokens::get().form_card_width, ok: "OK", cancel: "Cancel", reset_scroll: false } + } + + /// A newly opened manager starts at its first section. Later frames retain user scrolling. + pub(crate) fn reset_scroll(mut self, reset: bool) -> Self { + self.reset_scroll = reset; + self } pub(crate) fn width(mut self, width: f32) -> Self { @@ -141,7 +147,9 @@ impl<'a> Panel<'a> { } crate::frame::Side::Left => self.anchor.x.clamp(viewport.left(), viewport.right() - width), }; - egui::pos2(x, self.anchor.y.clamp(viewport.top(), viewport.bottom())) + let chrome = + Tokens::get().form_header_height + Tokens::get().form_footer_height + self.frame.total_margin().sum().y + crate::shell::SHELL_GAP; + egui::pos2(x, self.anchor.y.clamp(viewport.top(), (viewport.bottom() - chrome).max(viewport.top()))) } pub(crate) fn window(&self) -> egui::Window<'a> { @@ -232,28 +240,33 @@ impl<'a> Panel<'a> { let fields_height = (bottom - ui.cursor().top() - footer_height).max(0.0); let fields_rect = egui::Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), fields_height)); let state = if collapsed.as_deref().copied().unwrap_or(false) { + scenario::publish_count("dialog:body:content_height", 0.0); ComputeStatus { text: None, busy: disabled, applying: disabled } } else { ui.scope_builder(egui::UiBuilder::new().max_rect(fields_rect), |ui| { - egui::ScrollArea::vertical() - .id_salt("feature_fields") - .min_scrolled_height(0.0) - .max_height(fields_height) - .show(ui, |ui| { + if self.reset_scroll { + // Clear persisted offset, animation and momentum once per opening. + egui::scroll_area::State::default().store(ui.ctx(), ui.make_persistent_id(egui::IdSalt::new("feature_fields"))); + } + let scroll = + egui::ScrollArea::vertical().id_salt("feature_fields").min_scrolled_height(0.0).max_height(fields_height).show(ui, |ui| { if disabled { ui.disable(); } egui::Frame::NONE .inner_margin(egui::Margin { - left: t.space_10 as i8, - right: t.space_10 as i8, - top: t.space_8 as i8, - bottom: t.space_6 as i8, + left: t.space_12 as i8, + right: t.space_12 as i8, + top: t.space_12 as i8, + bottom: t.space_12 as i8, }) .show(ui, body) .inner - }) - .inner + }); + scenario::publish_count("dialog:body:content_height", f64::from(scroll.content_size.y)); + scenario::publish_count("dialog:body:scroll_y", f64::from(scroll.state.offset.y)); + scenario::publish_rect("dialog:body:viewport", scroll.inner_rect); + scroll.inner }) .inner }; @@ -416,8 +429,9 @@ impl<'a> Prompt<'a> { /// `valid` enables the primary action. pub(crate) fn show(self, ctx: &egui::Context, valid: bool, body: impl FnOnce(&mut Ui)) -> (bool, super::Action) { let t = Tokens::get(); - let frame = crate::frame::shell_card(t.dialog_body).inner_margin(0.0); - let inner_width = (self.width - frame.total_margin().sum().x).max(0.0); + let frame = + crate::frame::shell_card(t.dialog_body).stroke(egui::Stroke::new(1.0, t.dialog_border)).corner_radius(t.radius_xl).inner_margin(0.0); + let inner_width = (self.width.min(ctx.content_rect().width()) - frame.total_margin().sum().x).max(0.0); let window = egui::Window::new(self.title) .enabled(!crate::issue_report::cad_input_blocked()) .id(self.id) @@ -441,7 +455,7 @@ impl<'a> Prompt<'a> { let mut close = false; header(ui, self.icon, self.title, || close = true); egui::Frame::NONE - .inner_margin(egui::Margin { left: t.space_10 as i8, right: t.space_10 as i8, top: t.space_8 as i8, bottom: t.space_6 as i8 }) + .inner_margin(egui::Margin { left: t.space_12 as i8, right: t.space_12 as i8, top: t.space_12 as i8, bottom: t.space_12 as i8 }) .show(ui, body); if !self.enter_submits { ui.ctx().input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); diff --git a/crates/ui-egui/src/ui_kit/panel_tests.rs b/crates/ui-egui/src/ui_kit/panel_tests.rs index 2847fdbe6..f1aed0152 100644 --- a/crates/ui-egui/src/ui_kit/panel_tests.rs +++ b/crates/ui-egui/src/ui_kit/panel_tests.rs @@ -34,7 +34,7 @@ fn heading_weight_field_surfaces_and_disclosures_follow_tokens_in_both_themes() assert_eq!(text.galley.job.sections.first().unwrap().format.font_id.family, egui::FontFamily::Monospace); } if text.galley.job.text == "Fillet" { - assert_eq!(text.galley.job.sections.first().unwrap().format.font_id, crate::fonts::semibold(t.font_label)); + assert_eq!(text.galley.job.sections.first().unwrap().format.font_id, crate::fonts::semibold(t.font_heading)); *title += 1; } if text.galley.job.text == "OPTIONS" { diff --git a/crates/ui-egui/src/ui_kit/reports.rs b/crates/ui-egui/src/ui_kit/reports.rs new file mode 100644 index 000000000..e5103f6b0 --- /dev/null +++ b/crates/ui-egui/src/ui_kit/reports.rs @@ -0,0 +1,126 @@ +//! Read-only report and library containers, sharing the form's typography and actions. +use crate::{scenario, theme::Tokens}; +use egui::{Ui, vec2}; + +/// Bordered list with a bounded scroll viewport. Tokens: dialog_rule, radius_md, space_10. +pub(crate) fn report_list(ui: &mut Ui, key: &str, height: f32, add: impl FnOnce(&mut Ui) -> R) -> R { + list_frame(ui, key, |ui| { + let output = egui::ScrollArea::vertical() + .id_salt(("report_list", key)) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::VisibleWhenNeeded) + .content_margin(egui::Margin::ZERO) + .auto_shrink([false, true]) + .max_height(height) + .show(ui, add); + scenario::publish_rect(&format!("dialog:list:{key}:viewport"), output.inner_rect); + scenario::publish_count(&format!("dialog:list:{key}:content_width"), f64::from(output.content_size.x)); + output.inner + }) +} + +/// Full-width report hairline across the list's text inset. Tokens: space_10, dialog_rule. +pub(crate) fn report_divider(ui: &mut Ui, key: &str) { + let t = Tokens::get(); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width().max(0.0), 1.0), egui::Sense::hover()); + let rect = rect.expand2(vec2(t.space_10, 0.0)); + let clip = ui.clip_rect().expand2(vec2(t.space_10, 0.0)); + ui.painter().with_clip_rect(clip).hline(rect.x_range(), rect.top(), egui::Stroke::new(1.0, t.dialog_rule)); + scenario::publish_rect(&format!("dialog:divider:{key}"), rect); +} + +/// List border around a caller-owned virtualised viewport. Tokens: dialog_rule, control_radius, space_10. +pub(crate) fn list_frame(ui: &mut Ui, key: &str, add: impl FnOnce(&mut Ui) -> R) -> R { + let t = Tokens::get(); + let response = egui::Frame::NONE + .stroke(egui::Stroke::new(1.0, t.dialog_rule)) + .corner_radius(t.control_radius) + .inner_margin(egui::Margin::symmetric(t.space_10 as i8, 0)) + .show(ui, |ui| { + // Frame already subtracts its border and padding from the content width. + ui.set_min_width(ui.available_width().max(0.0)); + add(ui) + }); + scenario::publish_rect(&format!("dialog:list:{key}"), response.response.rect); + response.inner +} + +#[cfg(test)] +#[path = "reports_tests.rs"] +mod tests; + +/// Read-only monospace path chip with an adjacent action. Retains the path cell handle. +pub(crate) fn path_chip(ui: &mut Ui, path: &str, add: impl FnOnce(&mut Ui)) { + let t = Tokens::get(); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = t.space_8; + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + add(ui); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width().max(0.0), t.control_height), egui::Sense::hover()); + ui.painter().rect(rect, t.control_radius, t.dialog_footer, egui::Stroke::new(1.0, t.dialog_rule), egui::StrokeKind::Inside); + super::text::paint_text(ui, rect.shrink2(vec2(t.space_8, 0.0)), path, egui::FontId::monospace(t.font_small), t.form_dim, false); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), path)); + response.on_hover_text(path); + let key = format!("dialog:cell:{path}"); + scenario::publish_handle(&key, rect.center()); + scenario::publish_rect(&key, rect); + }); + }); +} + +/// Empty-list dashed outline and centred caption. Retains the note rectangle. +pub(crate) fn empty_box(ui: &mut Ui, key: &str, message: &str) { + let t = Tokens::get(); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width().max(0.0), t.control_height * 3.0), egui::Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), message)); + let points = [rect.left_top(), rect.right_top(), rect.right_bottom(), rect.left_bottom(), rect.left_top()]; + ui.painter().extend(egui::Shape::dashed_line(&points, egui::Stroke::new(1.0, t.control_border), t.space_4, t.space_3)); + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, message, egui::FontId::proportional(t.font_label), t.form_dim); + scenario::publish_rect(&format!("dialog:note:{key}"), rect); +} + +/// Kind/count above UTC time, alongside actions. The legacy combined-title cell remains an alias. +pub(crate) fn report_header(ui: &mut Ui, kind: &str, count: u64, time: &str, alias: &str, actions: impl FnOnce(&mut Ui)) { + let t = Tokens::get(); + let height = t.control_height + t.space_8; + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + actions(ui); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width().max(0.0), height), egui::Sense::hover()); + let title = egui::Rect::from_min_size(rect.min, vec2(rect.width(), height / 2.0)); + let count_text = if count > 1 { format!("×{count}") } else { String::new() }; + let pill_width = if count > 1 { + ui.painter().layout_no_wrap(count_text.clone(), egui::FontId::proportional(t.font_small), t.form_dim).size().x + t.space_12 + } else { + 0.0 + }; + let kind_width = ui.painter().layout_no_wrap(kind.to_string(), crate::fonts::semibold(t.font_label), t.form_ink).size().x; + let end = (title.left() + kind_width).min((title.right() - pill_width - t.space_6).max(title.left())); + super::text::paint_text( + ui, + egui::Rect::from_min_max(title.min, egui::pos2(end, title.bottom())), + kind, + crate::fonts::semibold(t.font_label), + t.form_ink, + false, + ); + if count > 1 { + let pill = egui::Rect::from_min_size(egui::pos2(end + t.space_6, title.top()), vec2(pill_width, title.height())); + ui.painter().rect_filled(pill, t.control_radius, t.dialog_footer); + ui.painter().text(pill.center(), egui::Align2::CENTER_CENTER, count_text, egui::FontId::proportional(t.font_small), t.form_dim); + } + super::text::paint_text( + ui, + egui::Rect::from_min_max(egui::pos2(rect.left(), title.bottom()), rect.max), + time, + egui::FontId::monospace(t.font_small), + t.form_dim, + false, + ); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), alias)); + response.on_hover_text(alias); + let key = format!("dialog:cell:{alias}"); + scenario::publish_rect(&key, rect); + scenario::publish_handle(&key, rect.center()); + }); + }); +} diff --git a/crates/ui-egui/src/ui_kit/reports_tests.rs b/crates/ui-egui/src/ui_kit/reports_tests.rs new file mode 100644 index 000000000..596bbb6e6 --- /dev/null +++ b/crates/ui-egui/src/ui_kit/reports_tests.rs @@ -0,0 +1,51 @@ +use super::*; +use crate::ui_kit::{self, test_support as harness}; + +#[test] +fn fitting_crash_rows_stay_inside_list_and_enclosing_horizontal_viewport() { + for ppp in [1.0, 1.25, 2.0] { + for width in [340.0, 499.0, 500.3, 524.0, 760.0] { + for count in [1, 12] { + let ctx = crate::fonts::test_context(); + ctx.set_pixels_per_point(ppp); + for _ in 0..3 { + harness::frame(&ctx, vec![], |ui| { + ui.set_width(width); + ui.spacing_mut().scroll.content_margin = egui::Margin::same(1); + let outer = + egui::ScrollArea::horizontal().max_width((width * ppp).floor() / ppp).content_margin(egui::Margin::ZERO).show(ui, |ui| { + report_list(ui, "reports", 160.0, |ui| { + for index in 0..count { + ui.push_id(index, |ui| { + ui.add_space(Tokens::get().space_10); + report_header(ui, "Internal error in a command", 3, "2026-10-18 21:04:12", "Report", |ui| { + ui_kit::bin_button(ui, "Delete"); + ui_kit::icon_label_button(ui, "Copy path", "copy", true, false); + ui_kit::icon_label_button(ui, "Report…", "bug_report", true, false); + }); + ui_kit::text(ui, "solid.fillet · replayable", ui_kit::Text::MonoNote("detail")); + ui_kit::text( + ui, + "The radius produced a degenerate face while rebuilding Fillet2.", + ui_kit::Text::Report("message", false), + ); + ui_kit::divider(ui, "end"); + }); + } + }); + }); + assert!( + outer.content_size.x <= outer.inner_rect.width().ceil(), + "{width} at {ppp}, {count} rows: {:?} outside {:?}", + outer.content_size, + outer.inner_rect + ); + }); + let viewport = scenario::rect_of("dialog:list:reports:viewport").unwrap(); + let content = scenario::count_of("dialog:list:reports:content_width").unwrap() as f32; + assert!(content <= viewport.width().ceil(), "{width} at {ppp}, {count} rows: content {content}, viewport {viewport:?}"); + } + } + } + } +} diff --git a/crates/ui-egui/src/ui_kit/slider_tests.rs b/crates/ui-egui/src/ui_kit/slider_tests.rs new file mode 100644 index 000000000..b9323a9b8 --- /dev/null +++ b/crates/ui-egui/src/ui_kit/slider_tests.rs @@ -0,0 +1,132 @@ +use super::*; +use crate::{scenario, theme::Tokens}; +use egui::{Rect, Ui, pos2, vec2}; + +#[test] +fn every_slider_option_uses_the_same_token_thumb_in_both_themes() { + let previous = crate::theme::is_dark(); + for dark in [false, true] { + crate::theme::set_dark(dark); + for (show_value, integer, enabled) in [(true, false, true), (true, false, false), (false, true, true)] { + for formatted in [false, true] { + let ctx = crate::fonts::test_context(); + let t = Tokens::get(); + let mut value: f64 = 1.0; + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 200.0))), ..Default::default() }, + |ui| { + scope(ui, |ui| { + ui.add_enabled_ui(enabled, |ui| { + slider( + ui, + &mut value, + 0.0..=2.0, + Slider { + step: formatted.then_some(0.05), + format: if formatted { |v| format!("{:.0} %", v * 100.0) } else { |v| format!("{v:.2}") }, + show_value, + integer, + }, + ); + }); + }); + }, + ); + output.textures_delta.clear(); + let thumb = output + .shapes + .iter() + .rev() + .find_map(|s| match &s.shape { + egui::Shape::Circle(c) if c.radius == t.space_8 => Some(c), + _ => None, + }) + .expect("shared kit thumb"); + assert_eq!(thumb.stroke.width, t.space_2); + // Disabled chrome uses egui's standard painter fade; geometry stays identical. + if enabled { + assert_eq!(thumb.fill, t.control_fill); + assert_eq!(thumb.stroke.color, t.form_primary); + } + assert_eq!(value, 1.0); + } + } + } + crate::theme::set_dark(previous); +} + +#[test] +fn slider_steps_endpoints_disabled_input_and_hidden_editor_keep_native_behaviour() { + for (show_value, integer, enabled) in [(true, false, true), (false, true, true), (true, false, false)] { + let ctx = crate::fonts::test_context(); + let mut value: f64 = 1.0; + let (min, max) = if integer { (0.0, 4.0) } else { (0.5, 2.5) }; + let track = std::cell::Cell::new(Rect::NOTHING); + let mut draw = |ui: &mut Ui| { + ui.add_enabled_ui(enabled, |ui| { + let response = slider(ui, &mut value, min..=max, Slider { step: Some(0.05), show_value, integer, ..Default::default() }); + track.set(scenario::rect_of("dialog:slider_track:").expect("slider track")); + assert_eq!(response.rect.height(), Tokens::get().control_height); + }); + }; + test_support::frame(&ctx, vec![], &mut draw); + let hit = track.get(); + let at = pos2(hit.left() + hit.width() * 0.61, hit.center().y); + test_support::frame(&ctx, test_support::pointer(at, true), &mut draw); + test_support::frame(&ctx, test_support::pointer(at, false), &mut draw); + if enabled { + assert!(value > 1.0 && value < max); + if integer { + assert_eq!(value.fract(), 0.0); + } else { + assert!((value / 0.05 - (value / 0.05).round()).abs() < 1e-8); + } + } else { + assert_eq!(value, 1.0); + } + // Rebuild the closure after inspecting the model, and reach both ends by pointer. + for (at, expected) in [(hit.left_center(), min), (hit.right_center(), max)] { + let mut draw = |ui: &mut Ui| { + ui.add_enabled_ui(enabled, |ui| { + slider(ui, &mut value, min..=max, Slider { step: Some(0.05), show_value, integer, ..Default::default() }); + }); + }; + test_support::frame(&ctx, test_support::pointer(at, true), &mut draw); + test_support::frame(&ctx, test_support::pointer(at, false), &mut draw); + if enabled { + assert!((value - expected).abs() < 1e-8); + } + } + } +} + +#[test] +fn continuous_slider_drawing_preserves_precision_and_all_scenario_aliases() { + let ctx = crate::fonts::test_context(); + let mut value = 0.123456789; + test_support::frame(&ctx, vec![], |ui| { + row(ui, "Opacity", |ui| { + slider(ui, &mut value, 0.0..=1.0, Default::default()); + }); + }); + assert_eq!(value, 0.123456789); + let rect = scenario::rect_of("dialog:slider:Opacity").expect("opacity slider rect"); + assert!(rect.contains(scenario::handle_at("dialog:slider:Opacity").expect("opacity slider handle"))); + assert!(scenario::rect_of("dialog:widget:Opacity").is_some()); +} + +#[test] +fn formatted_slider_editor_fits_without_shifting_the_track_during_a_scale_drag() { + let ctx = crate::fonts::test_context(); + let mut widths = Vec::new(); + for mut value in [0.5, 1.0, 1.5, 2.5] { + test_support::frame(&ctx, vec![], |ui| { + let right = ui.available_rect_before_wrap().right(); + let response = + slider(ui, &mut value, 0.5..=2.5, Slider { step: Some(0.05), format: |v| format!("{:.0} %", v * 100.0), ..Default::default() }); + assert!(response.rect.right() <= right, "formatted editor must fit: {:?} > {right}", response.rect); + widths.push(scenario::rect_of("dialog:slider_track:").expect("slider track").width()); + }); + } + assert!(widths.windows(2).all(|pair| pair[0] == pair[1]), "dragging must not move the input range: {widths:?}"); +} diff --git a/crates/ui-egui/src/ui_kit/status.rs b/crates/ui-egui/src/ui_kit/status.rs index 1ebf102d6..e53433fc6 100644 --- a/crates/ui-egui/src/ui_kit/status.rs +++ b/crates/ui-egui/src/ui_kit/status.rs @@ -28,13 +28,13 @@ pub(crate) fn status_header(ui: &mut egui::Ui, key: &str, name: &str, status: St }); ui.horizontal(|ui| { let (dot, _) = ui.allocate_exact_size(vec2(t.space_10, t.space_10), egui::Sense::hover()); - ui.painter().circle_filled(dot.center(), t.space_10 / 2.0, if status.complete { t.text } else { t.accent }); - ui.add(egui::Label::new(RichText::new(status.text).size(t.font_label).color(t.text_dim)).wrap()); + ui.painter().circle_filled(dot.center(), t.space_10 / 2.0, if status.complete { t.form_ink } else { t.form_primary }); + ui.add(egui::Label::new(RichText::new(status.text).size(t.font_label).color(t.form_dim)).wrap()); }); let (meter, _) = ui.allocate_exact_size(vec2(ui.available_width(), t.space_6), egui::Sense::hover()); ui.painter().rect_filled(meter, t.space_3, t.dialog_rule); if fraction > 0.0 { - ui.painter().rect_filled(egui::Rect::from_min_size(meter.min, vec2(meter.width() * fraction, meter.height())), t.space_3, t.text); + ui.painter().rect_filled(egui::Rect::from_min_size(meter.min, vec2(meter.width() * fraction, meter.height())), t.space_3, t.form_ink); } crate::scenario::publish_rect(&format!("{key}:meter"), meter); crate::scenario::publish_count(&format!("{key}:constrained_fraction"), f64::from(fraction)); @@ -54,7 +54,7 @@ pub(crate) fn progress(ui: &mut egui::Ui, key: &str, fraction: f32) -> egui::Res let (bar, response) = ui.allocate_exact_size(vec2(ui.available_width().max(0.0), t.space_6), egui::Sense::hover()); ui.painter().rect_filled(bar, t.space_3, t.dialog_rule); if fraction > 0.0 { - ui.painter().rect_filled(egui::Rect::from_min_size(bar.min, vec2(bar.width() * fraction, bar.height())), t.space_3, t.accent); + ui.painter().rect_filled(egui::Rect::from_min_size(bar.min, vec2(bar.width() * fraction, bar.height())), t.space_3, t.form_primary); } response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ProgressIndicator, ui.is_enabled(), format!("{:.0}%", fraction * 100.0))); crate::scenario::publish_rect(&format!("dialog:progress:{key}"), bar); diff --git a/crates/ui-egui/src/ui_kit/table.rs b/crates/ui-egui/src/ui_kit/table.rs index c4c0a6c03..d09956e6c 100644 --- a/crates/ui-egui/src/ui_kit/table.rs +++ b/crates/ui-egui/src/ui_kit/table.rs @@ -8,11 +8,26 @@ pub(crate) struct Column<'a> { label: &'a str, width: f32, min_content_width: f32, + icon_only: bool, + flexible: bool, } impl<'a> Column<'a> { pub(crate) fn new(label: &'a str, width: f32) -> Self { - Self { label, width, min_content_width: 0.0 } + Self { label, width, min_content_width: 0.0, icon_only: false, flexible: false } + } + + /// Share the remaining visible table width using this column's width as its weight. + /// Explicit minimums keep editors usable and allow horizontal scrolling on small cards. + pub(crate) fn flex(mut self) -> Self { + self.flexible = true; + self + } + + /// Retain the column identity for automation without a visible action heading. + pub(crate) fn icon_only(mut self) -> Self { + self.icon_only = true; + self } /// Keep enough room for the measured cell controls, even in a narrow scrolling card. @@ -27,47 +42,145 @@ pub(crate) struct Table<'a> { widths: Vec, id: String, rows: usize, + empty: String, + empty_shown: bool, + reveal: Option, } -/// Header, horizontally scrolling body and empty state. Rows are exactly control_height. +/// Header, horizontally scrolling body and empty state. Regular rows use table_row_height. /// Tokens: form_label_width, font_label, dialog_label, space_4/8, dialog_rule, text/dim, selected_bg. pub(crate) fn table(ui: &mut Ui, id: &str, columns: &[Column<'_>], empty: &str, add: impl FnOnce(&mut Ui, &mut Table<'_>) -> R) -> R { - let t = Tokens::get(); - let widths: Vec<_> = - columns.iter().map(|c| (header_column(ui, c.label) * dimension(c.width)).max(label_width(ui, c.label)).max(c.min_content_width)).collect(); - let mut table = Table { columns, widths, id: id.to_owned(), rows: 0 }; - egui::ScrollArea::horizontal() - .id_salt(id) - .auto_shrink([false, true]) - .show(ui, |ui| { - let width = table.width(); - let (rect, _) = ui.allocate_exact_size(vec2(width, row_height()), egui::Sense::hover()); - let mut left = rect.left(); - for (column, width) in table.columns.iter().zip(&table.widths) { - let cell = egui::Rect::from_min_size(egui::pos2(left, rect.top()), vec2(*width, rect.height())); - ui.scope_builder(egui::UiBuilder::new().max_rect(cell).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| { - ui.set_clip_rect(ui.clip_rect().intersect(cell)); - ui.add( - egui::Label::new(egui::RichText::new(crate::i18n::tr_label(column.label)).size(t.font_label).color(t.text_dim)).truncate(), - ) - .on_hover_text(crate::i18n::tr_label(column.label)); - }); - scenario::publish_rect(&format!("dialog:column:{id}:{}", column.label), cell); - left = cell.right() + t.space_8; - } - ui.painter().hline(rect.x_range(), rect.bottom(), egui::Stroke::new(1.0, t.dialog_rule)); + table_custom(ui, id, columns, empty, |ui, table| { + table.headers(ui, |_, _| false); + add(ui, table) + }) +} + +/// The same table grid with caller-supplied header actions through Table::headers. +/// Custom cells own their actions; all body rows share the same widths and metrics. +pub(crate) fn table_custom(ui: &mut Ui, id: &str, columns: &[Column<'_>], empty: &str, add: impl FnOnce(&mut Ui, &mut Table<'_>) -> R) -> R { + let mut reveal = None; + let output = egui::ScrollArea::horizontal().id_salt(("table", id)).content_margin(egui::Margin::ZERO).auto_shrink([false, true]).show_viewport( + ui, + |ui, viewport| { + // ScrollArea snaps its content rect. Measure here, after that rounding and any + // enclosing list margins, and never allocate more than the actual viewport. + let ppp = ui.ctx().pixels_per_point().max(0.5); + let available = (dimension(ui.available_width()).min(viewport.width()) * ppp).floor() / ppp; + let mut table = Table { + columns, + widths: column_widths(ui, columns, available), + id: id.to_owned(), + rows: 0, + empty: empty.to_owned(), + empty_shown: false, + reveal: None, + }; + ui.spacing_mut().item_spacing.y = 0.0; let result = add(ui, &mut table); - if table.rows == 0 { + if table.rows == 0 && !table.empty_shown { super::text(ui, empty, super::Text::Note(id)); } + reveal = table.reveal; result + }, + ); + scenario::publish_rect(&format!("dialog:table:{id}:viewport"), output.inner_rect); + scenario::publish_count(&format!("dialog:table:{id}:content_width"), f64::from(output.content_size.x)); + // The nested horizontal ScrollArea consumes vertical scroll targets too. Request the + // reveal here so it reaches the card's vertical scroller, only after an explicit action. + if let Some(rect) = reveal { + ui.scroll_to_rect(rect, None); + } + output.inner +} + +fn column_widths(ui: &Ui, columns: &[Column<'_>], available: f32) -> Vec { + let t = Tokens::get(); + let mut widths: Vec<_> = columns + .iter() + .map(|c| { + if c.flexible || c.icon_only { + c.min_content_width.max(t.control_height) + } else { + (header_column(ui, c.label) * dimension(c.width)).max(label_width(ui, c.label)).max(c.min_content_width) + } }) - .inner + .collect(); + let fixed: f32 = columns.iter().zip(&widths).filter(|(c, _)| !c.flexible).map(|(_, w)| *w).sum(); + let mut remaining = (available - fixed - t.space_8 * (columns.len().saturating_sub(1) + 2) as f32).max(0.0); + let mut sharing: Vec<_> = columns.iter().map(|c| c.flexible && dimension(c.width) > 0.0).collect(); + // Freeze columns at their control minimum before sharing the remaining width. The bounded + // passes also keep a hostile design with many columns from creating an unbounded loop. + for _ in 0..columns.len().min(64) { + let weight: f32 = columns.iter().zip(&sharing).filter(|(_, share)| **share).map(|(c, _)| dimension(c.width)).sum(); + if weight <= 0.0 { + break; + } + let available = remaining; + let mut frozen = false; + for ((column, width), share) in columns.iter().zip(&mut widths).zip(&mut sharing) { + if *share && *width > available * dimension(column.width) / weight { + *share = false; + remaining = (remaining - *width).max(0.0); + frozen = true; + } + } + if !frozen { + for ((column, width), share) in columns.iter().zip(&mut widths).zip(&sharing) { + if *share { + *width = remaining * dimension(column.width) / weight; + } + } + break; + } + } + // Round cumulative column edges, not each width independently: independent rounding + // can add a pixel to an otherwise exactly fitting grid and create a scrollbar. + let ppp = ui.ctx().pixels_per_point().max(0.5); + let mut edge = 0.0; + let mut rounded_edge = 0.0; + for width in &mut widths { + edge += *width; + let next = (edge * ppp).round() / ppp; + *width = next - rounded_edge; + rounded_edge = next; + } + widths } impl Table<'_> { + /// Reveal a newly inserted row through the enclosing card's vertical scroller. + pub(crate) fn reveal_row(&mut self, rect: egui::Rect) { + self.reveal = Some(rect); + } + + pub(crate) fn headers(&self, ui: &mut Ui, mut header: impl FnMut(&mut Ui, usize) -> bool) { + let t = Tokens::get(); + let width = self.width(); + let (rect, _) = ui.allocate_exact_size(vec2(width, row_height()), egui::Sense::hover()); + let ppp = ui.ctx().pixels_per_point().max(0.5); + let mut left = (rect.left() * ppp).round() / ppp + t.space_8; + for (index, (column, width)) in self.columns.iter().zip(&self.widths).enumerate() { + let cell = egui::Rect::from_min_size(egui::pos2(left, rect.top()), vec2(*width, rect.height())); + ui.scope_builder( + egui::UiBuilder::new().id_salt((&self.id, "header", index)).max_rect(cell).layout(egui::Layout::left_to_right(egui::Align::Center)), + |ui| { + ui.set_clip_rect(ui.clip_rect().intersect(cell)); + if !header(ui, index) && !column.icon_only { + header_label(ui, column.label); + } + }, + ); + scenario::publish_rect(&format!("dialog:column:{}:{}", self.id, column.label), cell); + left = cell.right() + t.space_8; + } + ui.painter().hline(rect.x_range(), rect.bottom(), egui::Stroke::new(1.0, t.dialog_rule)); + ui.advance_cursor_after_rect(rect); + } + fn width(&self) -> f32 { - self.widths.iter().sum::() + Tokens::get().space_8 * self.widths.len().saturating_sub(1) as f32 + self.widths.iter().sum::() + Tokens::get().space_8 * (self.widths.len().saturating_sub(1) + 2) as f32 } /// A selectable row with independently interactive cells and actions. @@ -77,33 +190,55 @@ impl Table<'_> { /// Keep off-screen rows' space without building their cells. Force active drafts to stay live. pub(crate) fn row_visible(&mut self, ui: &mut Ui, key: &str, selected: bool, force: bool, add: impl FnOnce(&mut TableRow<'_>)) -> Response { - let response = self.row_content(ui, key, Some(selected), force, add); + let response = self.row_content(ui, key, selected, force, add); self.rows += 1; response } - /// A non-selectable column-action band attached to the header, using the same cell grid. - pub(crate) fn column_actions(&mut self, ui: &mut Ui, add: impl FnOnce(&mut TableRow<'_>)) { - self.row_content(ui, "columns", None, true, add); + /// The last, slim dashed line. Clicking asks the owner to insert a regular draft row. + pub(crate) fn add_prompt(&mut self, ui: &mut Ui, label: &str, tooltip: &str) -> Response { + let t = Tokens::get(); + if self.rows == 0 && !self.empty_shown { + super::text(ui, &self.empty, super::Text::Note(&self.id)); + self.empty_shown = true; + } + let (rect, response) = ui.allocate_exact_size(vec2(self.width(), row_height() - t.space_4), egui::Sense::click()); + let stroke = egui::Stroke::new(1.0, t.control_border); + let mut outline = Vec::new(); + egui::epaint::tessellator::path::rounded_rectangle(&mut outline, rect.shrink(stroke.width * 0.5), f32::from(t.control_radius).into()); + if let Some(first) = outline.first().copied() { + outline.push(first); + } + ui.painter().add(egui::Shape::dashed_line(&outline, stroke, t.space_4, t.space_3)); + let icon = egui::Rect::from_center_size(egui::pos2(rect.left() + t.space_16, rect.center().y), vec2(t.space_14, t.space_14)); + crate::icons::paint_ink(ui.painter(), icon, "plus", t.form_dim); + super::text::paint_text( + ui, + egui::Rect::from_min_max(egui::pos2(icon.right() + t.space_6, rect.top()), rect.max), + crate::i18n::tr_label(label), + egui::FontId::proportional(t.font_label), + t.form_dim, + false, + ); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), crate::i18n::tr_label(label))); + scenario::publish_handle(&format!("dialog:table:{}:add", self.id), rect.center()); + scenario::publish_rect(&format!("dialog:table:{}:add", self.id), rect); + response.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(crate::i18n::tr_label(tooltip)) } - fn row_content(&self, ui: &mut Ui, key: &str, selected: Option, force: bool, add: impl FnOnce(&mut TableRow<'_>)) -> Response { + fn row_content(&self, ui: &mut Ui, key: &str, selected: bool, force: bool, add: impl FnOnce(&mut TableRow<'_>)) -> Response { let t = Tokens::get(); - let sense = if selected.is_some() { egui::Sense::click() } else { egui::Sense::hover() }; - let (rect, response) = ui.allocate_exact_size(vec2(self.width(), row_height()), sense); + let (rect, response) = ui.allocate_exact_size(vec2(self.width(), super::table_row_height()), egui::Sense::click()); if !force && !ui.is_rect_visible(rect) { return response; } - if let Some(selected) = selected { - if selected || response.hovered() { - ui.painter().rect_filled(rect, t.control_radius, if selected { t.selected_bg } else { t.hover }); - } - response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, ui.is_enabled(), selected, key)); - } else { - ui.painter().rect_filled(rect, 0.0, t.dialog_footer); - ui.painter().hline(rect.x_range(), rect.bottom(), egui::Stroke::new(1.0, t.dialog_rule)); + if selected || (ui.is_enabled() && ui.rect_contains_pointer(rect)) { + ui.painter().rect_filled(rect, t.control_radius, if selected { t.selected_bg } else { t.hover }); } + response.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, ui.is_enabled(), selected, key)); scenario::publish_rect(&format!("dialog:table:{}:{key}", self.id), rect); + let ppp = ui.ctx().pixels_per_point().max(0.5); + let left = (rect.left() * ppp).round() / ppp + t.space_8; ui.push_id((&self.id, key), |ui| { add(&mut TableRow { ui, @@ -111,10 +246,11 @@ impl Table<'_> { columns: self.columns, rect, column: 0, - left: rect.left(), + left, id: format!("dialog:table:{}:{key}", self.id), }); }); + ui.advance_cursor_after_rect(rect); response } } @@ -163,3 +299,85 @@ pub(crate) fn label_actions(ui: &mut Ui, text: &str, add: impl FnOnce(&mut Ui)) }); add(ui); } + +/// Table heading text. Tokens: font_small, form_dim. +fn header_label(ui: &mut Ui, label: &str) { + let t = Tokens::get(); + ui.add(egui::Label::new(egui::RichText::new(crate::i18n::tr_label(label)).size(t.font_small).strong().color(t.form_dim)).truncate()) + .on_hover_text(crate::i18n::tr_label(label)); +} + +/// Column removal appears inside the hovered header only. Keeps the former × button handle. +pub(crate) fn removable_header(ui: &mut Ui, label: &str) -> bool { + let t = Tokens::get(); + let rect = ui.max_rect(); + let hovered = ui.rect_contains_pointer(rect); + if hovered { + ui.painter().rect_filled(rect, t.control_radius, t.dialog_footer); + } + let button = egui::Rect::from_center_size(egui::pos2(rect.right() - t.space_10, rect.center().y), vec2(t.space_10 * 2.0, t.space_10 * 2.0)); + let text_rect = egui::Rect::from_min_max(rect.min, egui::pos2(if hovered { button.left() } else { rect.right() }, rect.bottom())); + ui.scope_builder(egui::UiBuilder::new().max_rect(text_rect), |ui| header_label(ui, label)); + if !hovered { + return false; + } + let response = super::actions::icon_button_colored(ui, button, "close", "Remove the column", Some(t.form_error)); + scenario::publish_handle(&format!("dialog:button:{label}:×"), button.center()); + scenario::publish_rect(&format!("dialog:button:{label}:×"), button); + response.clicked() +} + +/// Icon-only row delete. The old Actions handles remain aliases for the bin target. +pub(crate) fn bin_button(ui: &mut Ui, tooltip: &str) -> Response { + let t = Tokens::get(); + let (rect, _) = ui.allocate_exact_size(vec2(t.control_height, t.control_height), egui::Sense::hover()); + let response = super::actions::icon_button_colored(ui, rect, "delete", tooltip, Some(t.form_error)); + for (row, label) in + [("Actions", "Delete"), ("Actions", "×"), (super::layout::label(ui), crate::i18n::tr_label("Delete")), (super::layout::label(ui), "×")] + { + let key = format!("dialog:button:{row}:{label}"); + scenario::publish_handle(&key, rect.center()); + scenario::publish_rect(&key, rect); + } + response +} + +/// Last header cell opens the unchanged column menu. Hover brackets indicate insertion. +pub(crate) fn plus_header(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> Option { + let t = Tokens::get(); + let rect = egui::Rect::from_center_size(ui.max_rect().center(), vec2(t.form_close_size - t.space_4, t.form_close_size - t.space_4)); + let response = super::actions::icon_button_colored(ui, rect, "plus", "Add Column", Some(t.form_dim)); + if response.hovered() { + ui.painter().rect_filled(rect, t.control_radius, t.selected_bg); + crate::icons::paint_ink(ui.painter(), rect.shrink(t.form_icon_inset), "plus", t.form_primary); + for x in [rect.left() - t.form_gap_y, rect.right() + t.form_gap_y] { + ui.painter().vline(x, rect.y_range(), egui::Stroke::new(t.space_2, t.form_primary)); + } + } + scenario::publish_handle("dialog:menu:Add Column", rect.center()); + scenario::publish_rect("dialog:menu:Add Column", rect); + let popup = egui::Popup::menu(&response); + let open = popup.is_open(); + let result = popup.show(|ui| super::scope(ui, add)).map(|r| r.inner); + if open { + ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)); + } + result +} + +/// Active configuration status, on the same line as the name and optional Apply action. +pub(crate) fn active_pill(ui: &mut Ui) { + let t = Tokens::get(); + let label = crate::i18n::tr_label("Active"); + let width = label_width(ui, label) + t.space_16; + let (rect, response) = ui.allocate_exact_size(vec2(width, t.font_small + t.space_6), egui::Sense::hover()); + ui.painter().rect(rect, t.radius_xl, t.control_fill, egui::Stroke::new(1.0, t.control_border), egui::StrokeKind::Inside); + super::text::paint_text(ui, rect.shrink2(vec2(t.space_8, 0.0)), label, crate::fonts::semibold(t.font_small), t.form_primary, false); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, ui.is_enabled(), label)); + scenario::publish_handle(&format!("dialog:inline:{label}"), rect.center()); + scenario::publish_rect(&format!("dialog:inline:{label}"), rect); +} + +#[cfg(test)] +#[path = "table_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/ui_kit/table_tests.rs b/crates/ui-egui/src/ui_kit/table_tests.rs new file mode 100644 index 000000000..4a4b48a53 --- /dev/null +++ b/crates/ui-egui/src/ui_kit/table_tests.rs @@ -0,0 +1,306 @@ +use super::*; +use crate::ui_kit::{self, test_support as harness}; + +#[test] +fn fitting_flex_tables_have_no_horizontal_scrollbar_at_card_widths_and_pixel_scales() { + for ppp in [1.0, 1.25, 2.0] { + for width in [260.0, 319.0, 320.0, 499.0, 500.3, 748.0, 749.0, 762.0] { + let ctx = crate::fonts::test_context(); + ctx.set_pixels_per_point(ppp); + for _ in 0..3 { + harness::frame(&ctx, vec![], |ui| { + ui.set_width(width); + // Include a non-zero inherited scroll margin: the grid owns its insets. + ui.spacing_mut().scroll.content_margin = egui::Margin::same(1); + table( + ui, + "fit", + &[Column::new("Name", 1.1).flex(), Column::new("Expression", 1.5).flex(), Column::new("Value", 1.1).flex()], + "Empty", + |ui, table| { + table.row(ui, "row", false, |row| { + row.cell(|ui| { + ui_kit::text(ui, "Width", ui_kit::Text::Cell); + }); + row.cell(|ui| { + ui_kit::cell_editor(ui, ui.id().with("value"), &mut "10 mm".into(), "", false); + }); + row.cell(|ui| { + ui_kit::text(ui, "10 mm", ui_kit::Text::MonoCell); + }); + }); + table.add_prompt(ui, "Add parameter", "Add parameter"); + }, + ); + }); + } + let viewport = scenario::rect_of("dialog:table:fit:viewport").unwrap(); + let content = scenario::count_of("dialog:table:fit:content_width").unwrap() as f32; + assert!(content <= viewport.width().ceil(), "{width} at {ppp}: content {content}, viewport {viewport:?}"); + let row = scenario::rect_of("dialog:table:fit:row").unwrap(); + let first = scenario::rect_of("dialog:table:fit:row:cell:Name").unwrap(); + let last = scenario::rect_of("dialog:table:fit:row:cell:Value").unwrap(); + assert_eq!(first.left() - row.left(), Tokens::get().space_8); + assert!( + (row.right() - last.right() - Tokens::get().space_8).abs() <= egui::emath::GUI_ROUNDING, + "width {width} at {ppp}: row {row:?} last {last:?}" + ); + for label in ["Name", "Expression", "Value"] { + let header = scenario::rect_of(&format!("dialog:column:fit:{label}")).unwrap(); + let cell = scenario::rect_of(&format!("dialog:table:fit:row:cell:{label}")).unwrap(); + assert_eq!(header.x_range(), cell.x_range()); + } + } + } +} + +#[test] +fn genuinely_wide_tables_keep_horizontal_scrolling() { + let ctx = crate::fonts::test_context(); + harness::frame(&ctx, vec![], |ui| { + table(ui, "overflow", &[Column::new("Name", 1.0).flex().min_content_width(400.0)], "Empty", |ui, table| { + table.row(ui, "row", false, |row| { + row.cell(|ui| ui_kit::text(ui, "Name", ui_kit::Text::Cell)); + }); + }); + }); + assert!( + scenario::count_of("dialog:table:overflow:content_width").unwrap() + > f64::from(scenario::rect_of("dialog:table:overflow:viewport").unwrap().width().ceil()) + ); +} + +#[test] +fn row_hover_paints_under_every_interactive_child_and_respects_clip_and_enabled() { + let ctx = crate::fonts::test_context(); + let mut value = "10 mm".to_owned(); + let mut selected = 0; + let mut draw = |ui: &mut Ui| { + ui.set_width(600.0); + table( + ui, + "hover", + &[ + Column::new("Text", 1.0).flex(), + Column::new("Field", 1.0).flex(), + Column::new("Choice", 1.0).flex(), + Column::new("Action", 1.0).flex(), + ], + "Empty", + |ui, table| { + table.row(ui, "row", false, |row| { + row.cell(|ui| { + ui_kit::text(ui, "Width", ui_kit::Text::Cell); + }); + row.cell(|ui| { + ui_kit::cell_editor(ui, ui.id().with("value"), &mut value, "", false); + }); + row.cell(|ui| { + ui_kit::dropdown(ui, "choice", &mut selected, &["mm", "in"]); + }); + row.cell(|ui| { + ui_kit::button(ui, "Delete", ui_kit::Button::Normal); + }); + }); + }, + ); + }; + let mut output = ctx + .run_ui(egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, 400.0))), ..Default::default() }, |ui| { + ui_kit::scope(ui, &mut draw) + }); + output.textures_delta.clear(); + let row = scenario::rect_of("dialog:table:hover:row").unwrap(); + let mut targets = vec![row.left_center() + vec2(1.0, 0.0)]; + for handle in ["dialog:cell:Width", "dialog:Field", "dialog:Choice", "dialog:button:Action:Delete"] { + targets.push(scenario::handle_at(handle).unwrap()); + } + for (enabled, clipped) in [(true, false), (false, false), (true, true)] { + for at in &targets { + for _ in 0..2 { + let mut output = ctx.run_ui(egui::RawInput { events: vec![egui::Event::PointerMoved(*at)], ..Default::default() }, |ui| { + if clipped { + ui.set_clip_rect(egui::Rect::from_min_max(egui::Pos2::ZERO, row.left_top())); + } + ui.add_enabled_ui(enabled, |ui| ui_kit::scope(ui, &mut draw)); + }); + output.textures_delta.clear(); + let highlight = output + .shapes + .iter() + .any(|shape| matches!(&shape.shape, egui::Shape::Rect(paint) if paint.rect == row && paint.fill == Tokens::get().hover)); + assert_eq!(highlight, enabled && !clipped, "pointer {at:?}, enabled {enabled}, clipped {clipped}"); + } + } + } +} + +#[test] +fn add_prompt_is_short_rounded_and_uses_a_hand_cursor() { + let ctx = crate::fonts::test_context(); + let mut draw = |ui: &mut Ui| { + table(ui, "prompt", &[Column::new("Name", 1.0).flex()], "Empty", |ui, table| { + table.add_prompt(ui, "Add configuration", "Add configuration"); + }); + }; + harness::frame(&ctx, vec![], &mut draw); + let rect = scenario::rect_of("dialog:table:prompt:add").unwrap(); + assert_eq!(rect.height(), row_height() - Tokens::get().space_4); + assert_eq!(harness::frame_cursor(&ctx, rect.center(), &mut draw), egui::CursorIcon::PointingHand); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + ui.set_width(280.0); + ui_kit::scope(ui, draw); + }); + output.textures_delta.clear(); + // The dashed outline follows a rounded path and leaves each rectangular corner empty. + let shapes = output.shapes.iter().flat_map(|s| match &s.shape { + egui::Shape::Vec(shapes) => shapes.as_slice(), + shape => std::slice::from_ref(shape), + }); + let dashed = shapes + .filter_map(|shape| match shape { + egui::Shape::LineSegment { points, stroke } if stroke.color == Tokens::get().control_border => Some(points), + _ => None, + }) + .collect::>(); + assert!(!dashed.is_empty()); + for corner in [rect.left_top(), rect.right_top(), rect.left_bottom(), rect.right_bottom()] { + assert!(dashed.iter().flat_map(|points| points.iter()).all(|p| p.distance(corner) > f32::from(Tokens::get().control_radius) * 0.2)); + } +} + +#[test] +fn hover_remove_bin_prompt_and_plus_menu_share_one_grid() { + for dark in [false, true] { + let ctx = crate::fonts::test_context(); + ctx.set_visuals(if dark { egui::Visuals::dark() } else { egui::Visuals::light() }); + let mut pending = false; + let mut removed = false; + let mut deleted = false; + let mut menu_open = false; + let mut draw = |ui: &mut Ui| { + table_custom( + ui, + "shared", + &[Column::new("Name", 1.0), Column::new("Actions", 0.0).icon_only().min_content_width(40.0)], + "Empty", + |ui, table| { + table.headers(ui, |ui, index| { + if index == 0 { + removed |= removable_header(ui, "Name"); + } else { + plus_header(ui, |ui| { + menu_open = true; + ui_kit::text(ui, "Column choices", ui_kit::Text::Inline); + }); + } + true + }); + if pending { + table.row(ui, "draft", false, |row| { + row.cell(|ui| { + ui_kit::cell_editor(ui, ui.id().with("name"), &mut String::new(), "Name", false); + }); + row.cell(|ui| { + deleted |= bin_button(ui, "Delete").clicked(); + }); + }); + } + if table.add_prompt(ui, "Add parameter", "Add parameter").clicked() { + pending = true; + } + }, + ); + }; + for _ in 0..3 { + harness::frame(&ctx, vec![], &mut draw); + } + assert!(scenario::handle_at("dialog:button:Name:×").is_none()); + let header = scenario::rect_of("dialog:column:shared:Name").unwrap(); + harness::frame(&ctx, vec![egui::Event::PointerMoved(header.center())], &mut draw); + let remove = scenario::handle_at("dialog:button:Name:×").unwrap(); + assert!(header.contains(remove)); + harness::frame(&ctx, harness::pointer(remove, true), &mut draw); + harness::frame(&ctx, harness::pointer(remove, false), &mut draw); + let add = scenario::handle_at("dialog:table:shared:add").unwrap(); + harness::frame(&ctx, harness::pointer(add, true), &mut draw); + harness::frame(&ctx, harness::pointer(add, false), &mut draw); + harness::frame(&ctx, vec![], &mut draw); + let row = scenario::rect_of("dialog:table:shared:draft").unwrap(); + assert_eq!(row.height(), crate::ui_kit::table_row_height()); + assert!(scenario::rect_of("dialog:column:shared:Name").unwrap().bottom() <= row.top()); + assert!(row.bottom() <= scenario::rect_of("dialog:table:shared:add").unwrap().top()); + let bin = scenario::handle_at("dialog:button:Actions:Delete").unwrap(); + assert!(row.contains(bin)); + harness::frame(&ctx, harness::pointer(bin, true), &mut draw); + harness::frame(&ctx, harness::pointer(bin, false), &mut draw); + let plus = scenario::handle_at("dialog:menu:Add Column").unwrap(); + harness::frame(&ctx, harness::pointer(plus, true), &mut draw); + harness::frame(&ctx, harness::pointer(plus, false), &mut draw); + harness::frame(&ctx, vec![], &mut draw); + assert!(pending && removed && deleted && menu_open); + } +} + +#[test] +fn add_column_is_small_and_unfilled_until_hovered() { + let ctx = crate::fonts::test_context(); + let draw = |ui: &mut Ui| { + ui.allocate_ui(egui::vec2(40.0, 36.0), |ui| { + ui.set_min_size(egui::vec2(40.0, 36.0)); + plus_header(ui, |_| {}); + }); + }; + let render = |events| { + let mut output = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { + ui_kit::scope(ui, draw); + }); + output.textures_delta.clear(); + output + }; + let out = render(vec![]); + let rect = scenario::rect_of("dialog:menu:Add Column").unwrap(); + assert!((20.0..=22.0).contains(&rect.width())); + assert_eq!(rect.width(), rect.height()); + let fills = + |out: &egui::FullOutput| out.shapes.iter().filter(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.rect == rect && r.fill.a() != 0)).count(); + assert_eq!(fills(&out), 0, "idle add-column has no background"); + let out = render(vec![egui::Event::PointerMoved(rect.center())]); + assert!(out.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.rect == rect && r.fill == Tokens::get().selected_bg))); + let guides = out.shapes.iter().filter(|s| matches!(&s.shape, egui::Shape::LineSegment { points, stroke } if points[0].x == points[1].x && stroke.color == Tokens::get().form_primary)).count(); + assert_eq!(guides, 2, "hover retains both insertion guides"); +} + +#[test] +fn horizontal_bar_is_painted_only_for_actual_table_overflow() { + for overflow in [false, true] { + let ctx = crate::fonts::test_context(); + ctx.global_style_mut(|style| style.spacing.scroll = egui::style::ScrollStyle::solid()); + for frame in 0..4 { + let mut output = ctx.run_ui( + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 400.0))), ..Default::default() }, + |ui| { + ui.set_width(280.0); + ui_kit::scope(ui, |ui| { + let column = Column::new("Name", 1.0).flex().min_content_width(if overflow { 400.0 } else { 0.0 }); + table(ui, "bar", &[column], "Empty", |ui, table| { + table.row(ui, "row", false, |row| { + row.cell(|ui| ui_kit::text(ui, "Width", ui_kit::Text::Cell)); + }); + }); + }); + }, + ); + output.textures_delta.clear(); + let bottom = scenario::rect_of("dialog:table:bar:row").unwrap().bottom(); + let bar = output.shapes.iter().any(|shape| { + matches!(&shape.shape, + egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() > 100.0 && r.rect.height() <= 10.0 + && r.rect.top() >= bottom && r.rect.bottom() <= bottom + 20.0) + }); + if frame == 3 { + assert_eq!(bar, overflow); + } + } + } +} diff --git a/crates/ui-egui/src/ui_kit/text.rs b/crates/ui-egui/src/ui_kit/text.rs index bc24a1d35..483a2a0ff 100644 --- a/crates/ui-egui/src/ui_kit/text.rs +++ b/crates/ui-egui/src/ui_kit/text.rs @@ -10,7 +10,9 @@ pub(super) fn paint_text(ui: &Ui, rect: egui::Rect, text: &str, font: egui::Font if spaced { format.extra_letter_spacing = size * Tokens::get().font_section_tracking; } - let job = egui::text::LayoutJob::single_section(text.to_string(), format); + let mut job = egui::text::LayoutJob::single_section(text.to_string(), format); + job.wrap.max_width = rect.width().max(0.0); + job.wrap.max_rows = 1; let galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); // Snap to whole device pixels: a fractional origin blurs every glyph edge. let ppp = ui.ctx().pixels_per_point().max(0.5); diff --git a/crates/ui-egui/src/ui_kit_guard_tests.rs b/crates/ui-egui/src/ui_kit_guard_tests.rs index 6111bb158..776fec5fa 100644 --- a/crates/ui-egui/src/ui_kit_guard_tests.rs +++ b/crates/ui-egui/src/ui_kit_guard_tests.rs @@ -188,7 +188,7 @@ fn removed_legacy_helpers_stay_removed() { &["secondary_button", "small_button", "enabled_button", "footer_impl", "footer_with_status", "footer_selected", "icon_button"], ), ("ui_kit/choice.rs", &["segments", "segmented_states", "segmented_compact"]), - ("ui_kit/fields.rs", &["selection_field_state", "value_pair_named"]), + ("ui_kit/fields.rs", &["selection_field_state", "value_pair_named", "formatted_slider", "timeline_slider"]), ("ui_kit/layout.rs", &["hint", "note", "text_block", "inline_text", "contains"]), ("ui_kit/table.rs", &["cell_text"]), ]; @@ -242,3 +242,547 @@ fn guard_detects_editor_constructors_aliases_and_legacy_declarations() { ); assert_eq!(legacy_declarations("fn docked_on() {}", &["docked_on"]), ["docked_on"]); } + +/// Broader than the dense-panel guard: sliders and numeric fields have no caller exceptions, +/// including app entry points and files which do not already import the kit. +#[derive(Default)] +struct SliderGuard { + aliases: Vec, + slider_aliases: Vec, + found: Vec, + constructors: usize, + slider_constructors: usize, + paints: bool, + track: bool, + thumb: bool, +} + +impl<'ast> Visit<'ast> for SliderGuard { + fn visit_item_fn(&mut self, item: &'ast syn::ItemFn) { + if item.attrs.iter().any(|a| a.path().is_ident("test")) { + return; + } + let mut function = Self { aliases: self.aliases.clone(), slider_aliases: self.slider_aliases.clone(), ..Self::default() }; + function.visit_block(&item.block); + let name = item.sig.ident.to_string(); + if function.paints && (name.contains("slider") || (function.track && function.thumb)) { + function.found.push(format!("{name}: slider track/thumb painting outside the kit")); + } + self.found.extend(function.found); + self.constructors += function.constructors; + self.slider_constructors += function.slider_constructors; + } + + fn visit_item_mod(&mut self, item: &'ast syn::ItemMod) { + if !item.attrs.iter().any(|a| a.path().is_ident("cfg") && a.parse_args::().is_ok_and(|p| p.is_ident("test"))) { + visit::visit_item_mod(self, item); + } + } + + fn visit_expr_call(&mut self, call: &'ast syn::ExprCall) { + if let syn::Expr::Path(path) = call.func.as_ref() { + let names: Vec<_> = path.path.segments.iter().map(|s| s.ident.to_string()).collect(); + if !names.iter().any(|n| n == "ui_kit") && names.iter().any(|n| matches!(n.as_str(), "Slider" | "DragValue") || self.aliases.contains(n)) + { + self.constructors += 1; + if names.iter().any(|n| n == "Slider" || self.slider_aliases.contains(n)) { + self.slider_constructors += 1; + } + self.found.push(names.join("::")); + } + } + visit::visit_expr_call(self, call); + } + + fn visit_expr_method_call(&mut self, call: &'ast syn::ExprMethodCall) { + let method = call.method.to_string(); + if matches!(method.as_str(), "rect" | "rect_filled" | "circle" | "circle_filled" | "line_segment" | "add" | "extend") { + self.paints = true; + // Only painting arguments identify a track/thumb. A panel's resize_rail call, + // camera track_hold call or publish_handle call is not slider painting. + #[derive(Default)] + struct PaintNames { + track: bool, + thumb: bool, + } + impl<'ast> Visit<'ast> for PaintNames { + fn visit_ident(&mut self, ident: &'ast syn::Ident) { + let name = ident.to_string().to_ascii_lowercase(); + let words: Vec<_> = name.split('_').collect(); + self.track |= words.iter().any(|w| matches!(*w, "track" | "rail")); + self.thumb |= words.iter().any(|w| matches!(*w, "thumb" | "knob" | "handle")); + } + } + let mut names = PaintNames::default(); + for arg in &call.args { + names.visit_expr(arg); + } + self.track |= names.track; + self.thumb |= names.thumb || matches!(method.as_str(), "circle" | "circle_filled"); + } + visit::visit_expr_method_call(self, call); + } +} + +fn slider_guard(source: &str) -> SliderGuard { + let ast = syn::parse_file(source).unwrap(); + #[derive(Default)] + struct Imports { + widgets: Vec, + sliders: Vec, + } + impl<'ast> Visit<'ast> for Imports { + fn visit_use_tree(&mut self, tree: &'ast syn::UseTree) { + if let syn::UseTree::Rename(rename) = tree + && matches!(rename.ident.to_string().as_str(), "Slider" | "DragValue") + { + self.widgets.push(rename.rename.to_string()); + if rename.ident == "Slider" { + self.sliders.push(rename.rename.to_string()); + } + } + visit::visit_use_tree(self, tree); + } + } + let mut imports = Imports::default(); + imports.visit_file(&ast); + let mut guard = SliderGuard { aliases: imports.widgets, slider_aliases: imports.sliders, ..SliderGuard::default() }; + guard.visit_file(&ast); + guard +} + +#[test] +fn all_ui_and_apps_use_the_one_kit_slider_and_numeric_fields() { + fn scan(dir: &Path, kit: &Path, failures: &mut Vec, constructors: &mut usize) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + scan(&path, kit, failures, constructors); + } else if path.extension().is_some_and(|e| e == "rs") { + let source = std::fs::read_to_string(&path).unwrap(); + let guard = slider_guard(&source); + if path.starts_with(kit) { + // One native slider constructor inside the kit, too: another kit helper must + // not quietly introduce a different appearance. Numeric field constructors + // are legitimate here and are counted separately below. + *constructors += guard.slider_constructors; + } else if !guard.found.is_empty() { + failures.push(format!("{}: {:?}", path.display(), guard.found)); + } + } + } + } + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + let kit = root.join("src/ui_kit"); + let mut failures = Vec::new(); + let mut constructors = 0; + scan(&root.join("src"), &kit, &mut failures, &mut constructors); + scan(&root.join("../../apps"), &kit, &mut failures, &mut constructors); + failures.sort(); + assert!(failures.is_empty(), "Sliders only via ui_kit::slider; numeric fields via the kit:\n{}", failures.join("\n")); + assert_eq!(constructors, 1, "The kit must define exactly one native slider"); +} + +#[test] +fn slider_guard_rejects_raw_aliases_and_second_painters_without_rejecting_callers() { + let guard = slider_guard( + r#" + fn caller(ui: &mut Ui) { + crate::ui_kit::slider(ui, value, range, Default::default()); + } + fn raw(ui: &mut Ui) { + use egui::{Slider as Scrubber, DragValue as Number}; + ui.add(Scrubber::new(value, range)); + ui.add(Number::new(value)); + ui.add(egui::Slider::new(value, range)); + } + fn other_slider(ui: &mut Ui) { ui.painter().add(shape); } + fn scrub(ui: &mut Ui) { + ui.painter().rect_filled(track, radius, color); + ui.painter().circle_filled(at, radius, color); + } + fn after_tests(ui: &mut Ui) { ui.add(egui::DragValue::new(value)); } + #[cfg(test)] mod tests { fn ignored() { ui.add(egui::Slider::new(value, range)); } } + "#, + ); + assert_eq!(guard.found.len(), 6, "{:?}", guard.found); + assert_eq!(guard.constructors, 4); +} + +/// Checkbox/radio policy applies to every UI/app file, even one without a kit import. +#[derive(Default)] +struct CheckGuard { + aliases: Vec, + found: Vec, + paints: bool, + mark: bool, + bottom: bool, + right_top: bool, +} + +impl<'ast> Visit<'ast> for CheckGuard { + fn visit_item_mod(&mut self, item: &'ast syn::ItemMod) { + if !item.attrs.iter().any(|a| a.path().is_ident("cfg") && a.parse_args::().is_ok_and(|p| p.is_ident("test"))) { + visit::visit_item_mod(self, item); + } + } + + fn visit_item_fn(&mut self, item: &'ast syn::ItemFn) { + if item.attrs.iter().any(|a| a.path().is_ident("test")) { + return; + } + let mut function = Self { aliases: self.aliases.clone(), ..Default::default() }; + function.visit_block(&item.block); + let name = item.sig.ident.to_string().to_lowercase(); + if function.paints + && (function.mark + || (function.bottom && function.right_top) + || ["checkbox", "checkmark", "check_mark", "check_glyph", "paint_tick"].iter().any(|s| name.contains(s))) + { + function.found.push(format!("{name}: check glyph painting outside ui_kit")); + } + self.found.extend(function.found); + } + + fn visit_ident(&mut self, ident: &'ast syn::Ident) { + let name = ident.to_string().to_lowercase(); + self.mark |= ["checkmark", "check_mark", "check_glyph", "tick_path", "tick_points"].iter().any(|s| name.contains(s)); + } + + fn visit_expr_method_call(&mut self, call: &'ast syn::ExprMethodCall) { + let method = call.method.to_string(); + if matches!(method.as_str(), "checkbox" | "radio" | "radio_value" | "selectable_label" | "selectable_value" | "toggle_value") { + self.found.push(format!(".{method}")); + } + self.paints |= matches!(method.as_str(), "line_segment" | "add" | "extend" | "text" | "galley"); + self.bottom |= method == "center_bottom"; + self.right_top |= method == "right_top"; + visit::visit_expr_method_call(self, call); + } + + fn visit_expr_call(&mut self, call: &'ast syn::ExprCall) { + if let syn::Expr::Path(path) = call.func.as_ref() { + let names: Vec<_> = path.path.segments.iter().map(|s| s.ident.to_string()).collect(); + if names.iter().any(|n| matches!(n.as_str(), "Checkbox" | "RadioButton") || self.aliases.contains(n)) { + self.found.push(names.join("::")); + } + } + visit::visit_expr_call(self, call); + } + + fn visit_type_path(&mut self, path: &'ast syn::TypePath) { + // A type alias must not hide a native constructor from the call-path check. + if path.path.segments.iter().any(|s| matches!(s.ident.to_string().as_str(), "Checkbox" | "RadioButton")) { + self.found.push("native check/radio type outside ui_kit".into()); + } + visit::visit_type_path(self, path); + } + + fn visit_macro(&mut self, mac: &'ast syn::Macro) { + // syn leaves vec! arguments opaque; the former duplicate painters put their + // three landmarks inside that macro rather than ordinary call arguments. + let tokens = mac.tokens.to_string(); + self.bottom |= tokens.contains("center_bottom"); + self.right_top |= tokens.contains("right_top"); + visit::visit_macro(self, mac); + } + + fn visit_lit_str(&mut self, literal: &'ast syn::LitStr) { + if literal.value().chars().any(|c| matches!(c, '✓' | '✔' | '☑' | '✅' | '🗸' | '🗹')) { + self.found.push("font check glyph outside ui_kit".into()); + } + } +} + +fn check_guard(source: &str) -> Vec { + #[derive(Default)] + struct Imports(Vec); + impl<'ast> Visit<'ast> for Imports { + fn visit_use_tree(&mut self, tree: &'ast syn::UseTree) { + if let syn::UseTree::Rename(rename) = tree + && matches!(rename.ident.to_string().as_str(), "Checkbox" | "RadioButton") + { + self.0.push(rename.rename.to_string()); + } + visit::visit_use_tree(self, tree); + } + } + let ast = syn::parse_file(source).unwrap(); + let mut imports = Imports::default(); + imports.visit_file(&ast); + let mut guard = CheckGuard { aliases: imports.0, ..Default::default() }; + guard.visit_file(&ast); + guard.found +} + +#[test] +fn all_ui_and_apps_use_kit_checkboxes_and_the_single_check_glyph() { + fn scan(dir: &Path, kit: &Path, failures: &mut Vec) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path == kit { + continue; + } + if path.is_dir() { + scan(&path, kit, failures); + } else if path.extension().is_some_and(|e| e == "rs") { + let found = check_guard(&std::fs::read_to_string(&path).unwrap()); + if !found.is_empty() { + failures.push(format!("{}: {found:?}", path.display())); + } + } + } + } + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + let kit = root.join("src/ui_kit"); + let mut failures = Vec::new(); + scan(&root.join("src"), &kit, &mut failures); + scan(&root.join("../../apps"), &kit, &mut failures); + failures.sort(); + assert!(failures.is_empty(), "Checkboxes only via ui_kit::checkbox; no caller allowances:\n{}", failures.join("\n")); +} + +#[test] +fn check_guard_rejects_raw_controls_aliases_unicode_and_duplicate_tick_painters() { + let found = check_guard( + r#" + fn raw(ui: &mut Ui) { + use egui::{Checkbox as Check, RadioButton as Radio}; + ui.checkbox(value, "Name"); + ui.radio(true, "Name"); + ui.radio_value(value, 1, "Name"); + ui.selectable_label(on, "Name"); + ui.selectable_value(value, 1, "Name"); + ui.toggle_value(value, "Name"); + ui.add(Check::new(value, "Name")); + ui.add(Radio::new(true, "Name")); + ui.add(egui::Checkbox::new(value, "Name")); + ui.label("\u{2713}"); + } + fn paint_checkmark(ui: &mut Ui) { ui.painter().line_segment(points, stroke); } + fn anonymous(ui: &mut Ui) { + ui.painter().add(Shape::line(vec![r.left_center(), r.center_bottom(), r.right_top()], stroke)); + } + fn named(ui: &mut Ui) { ui.painter().add(tick_path); } + fn caller(ui: &mut Ui) { crate::ui_kit::checkbox(ui, "Name", value); } + #[cfg(test)] mod tests { fn sample(ui: &mut Ui) { ui.checkbox(value, "✓"); } } + fn after_tests(ui: &mut Ui) { ui.radio(true, "Name"); } + "#, + ); + assert_eq!(found.len(), 14, "{found:?}"); +} + +#[test] +fn check_guard_rejects_native_type_aliases() { + assert_eq!(check_guard("type Check<'a> = egui::Checkbox<'a>; fn draw() { Check::new(value, name); }").len(), 1); + assert_eq!(check_guard("type Radio = egui::RadioButton<'static>; fn draw() { Radio::new(true, name); }").len(), 1); +} + +/// No parallel disclosure painter, font glyph, native header or raw disclosure icon. +/// Dropdowns and submenu navigation have separate semantics and remain kit/native controls. +#[derive(Default)] +struct DisclosureGuard { + found: Vec, + aliases: Vec, + paints: bool, + triangle: bool, + state: bool, + definitions: usize, +} + +impl<'ast> Visit<'ast> for DisclosureGuard { + fn visit_item_mod(&mut self, item: &'ast syn::ItemMod) { + if !item.attrs.iter().any(|a| a.path().is_ident("cfg") && a.parse_args::().is_ok_and(|p| p.is_ident("test"))) { + visit::visit_item_mod(self, item); + } + } + + fn visit_item_fn(&mut self, item: &'ast syn::ItemFn) { + if item.attrs.iter().any(|a| a.path().is_ident("test")) { + return; + } + let mut function = Self { aliases: self.aliases.clone(), ..Default::default() }; + function.visit_block(&item.block); + let name = item.sig.ident.to_string(); + if name == "disclosure" { + self.definitions += 1; + } + if function.paints && (name.contains("disclosure") || name.contains("chevron") || (function.triangle && function.state)) { + function.found.push(format!("{name}: disclosure painting outside ui_kit")); + } + self.found.extend(function.found); + } + + fn visit_expr_path(&mut self, path: &'ast syn::ExprPath) { + // State values, not unrelated geometry names such as Shape::closed_line. + self.state |= path.path.is_ident("open") || path.path.is_ident("closed") || path.path.is_ident("collapsed") || path.path.is_ident("expanded"); + visit::visit_expr_path(self, path); + } + + fn visit_expr_if(&mut self, expr: &'ast syn::ExprIf) { + fn glyph(block: &syn::Block) -> bool { + matches!(block.stmts.last(), Some(syn::Stmt::Expr(syn::Expr::Lit(lit), None)) + if matches!(&lit.lit, syn::Lit::Str(text) if matches!(text.value().as_str(), "«" | "»" | ">" | "<" | "v" | "^"))) + } + #[derive(Default)] + struct State(bool); + impl<'ast> Visit<'ast> for State { + fn visit_ident(&mut self, ident: &'ast syn::Ident) { + self.0 |= + ident.to_string().split('_').any(|part| matches!(part, "open" | "closed" | "collapsed" | "expanded" | "folded" | "minimized")); + } + } + let mut state = State::default(); + state.visit_expr(&expr.cond); + if state.0 + && (glyph(&expr.then_branch) + || expr.else_branch.as_ref().is_some_and(|(_, other)| matches!(other.as_ref(), syn::Expr::Block(block) if glyph(&block.block)))) + { + self.found.push("conditional font disclosure glyph outside ui_kit".into()); + } + visit::visit_expr_if(self, expr); + } + + fn visit_expr_method_call(&mut self, call: &'ast syn::ExprMethodCall) { + let name = call.method.to_string(); + if matches!(name.as_str(), "collapsing" | "show_header" | "show_toggle_button") + || (name == "collapsible" + && !matches!(call.args.first(), Some(syn::Expr::Lit(lit)) if matches!(lit.lit, syn::Lit::Bool(ref b) if !b.value))) + { + self.found.push(format!(".{name}: native disclosure")); + } + self.paints |= matches!(name.as_str(), "line_segment" | "add" | "extend" | "text" | "galley" | "image"); + visit::visit_expr_method_call(self, call); + } + + fn visit_expr_call(&mut self, call: &'ast syn::ExprCall) { + if let syn::Expr::Path(path) = call.func.as_ref() { + let names: Vec<_> = path.path.segments.iter().map(|s| s.ident.to_string()).collect(); + if names.iter().any(|n| n == "CollapsingHeader" || self.aliases.contains(n)) { + self.found.push("native disclosure header".into()); + } + if names.last().is_some_and(|n| n == "paint_default_icon") { + self.found.push("native disclosure painter outside ui_kit".into()); + } + self.triangle |= names.iter().any(|n| n == "convex_polygon"); + if names.last().is_some_and(|n| n.starts_with("paint") || n.starts_with("icon_button")) { + #[derive(Default)] + struct Icon(bool); + impl<'ast> Visit<'ast> for Icon { + fn visit_lit_str(&mut self, lit: &'ast syn::LitStr) { + self.0 |= matches!(lit.value().as_str(), "chevron" | "chevron_right" | "disclosure_open" | "disclosure_closed"); + } + } + let mut icon = Icon::default(); + for arg in &call.args { + icon.visit_expr(arg); + } + if icon.0 { + self.found.push("raw disclosure icon outside ui_kit".into()); + } + } + } + visit::visit_expr_call(self, call); + } + + fn visit_lit_str(&mut self, lit: &'ast syn::LitStr) { + // Single glyphs, or a glyph-only pair used as state alternatives. Text such as + // "▶ Play" is a playback label, not a font-based disclosure. + if !lit.value().is_empty() + && lit.value().chars().all(|c| matches!(c, '▾' | '▸' | '▶' | '▼' | '◀' | '▲' | '⌄' | '⌃' | '❯' | '❮' | '›' | '‹' | '∨' | '∧')) + { + self.found.push("font disclosure glyph outside ui_kit".into()); + } + } + + fn visit_macro(&mut self, mac: &'ast syn::Macro) { + // vec!/format! arguments are otherwise opaque to syn's expression visitor. + if let Ok(args) = mac.parse_body_with(syn::punctuated::Punctuated::::parse_terminated) { + for arg in args { + self.visit_expr(&arg); + } + } + } +} + +fn disclosure_guard(source: &str) -> DisclosureGuard { + #[derive(Default)] + struct Imports(Vec); + impl<'ast> Visit<'ast> for Imports { + fn visit_use_tree(&mut self, tree: &'ast syn::UseTree) { + if let syn::UseTree::Rename(rename) = tree + && rename.ident == "CollapsingHeader" + { + self.0.push(rename.rename.to_string()); + } + visit::visit_use_tree(self, tree); + } + } + let ast = syn::parse_file(source).unwrap(); + let mut imports = Imports::default(); + imports.visit_file(&ast); + let mut guard = DisclosureGuard { aliases: imports.0, ..Default::default() }; + guard.visit_file(&ast); + guard +} + +#[test] +fn all_disclosures_use_the_one_kit_chevron_without_allowances() { + fn scan(dir: &Path, kit: &Path, failures: &mut Vec, definitions: &mut usize) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + scan(&path, kit, failures, definitions); + } else if path.extension().is_some_and(|e| e == "rs") { + let guard = disclosure_guard(&std::fs::read_to_string(&path).unwrap()); + *definitions += guard.definitions; + if !path.starts_with(kit) && !guard.found.is_empty() { + failures.push(format!("{}: {:?}", path.display(), guard.found)); + } + } + } + } + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + let kit = root.join("src/ui_kit"); + let mut failures = Vec::new(); + let mut definitions = 0; + scan(&root.join("src"), &kit, &mut failures, &mut definitions); + scan(&root.join("../../apps"), &kit, &mut failures, &mut definitions); + scan(&root.join("../../assets/icons/ui/source"), &kit, &mut failures, &mut definitions); + assert!(failures.is_empty(), "Disclosures only through ui_kit::disclosure:\n{}", failures.join("\n")); + assert_eq!(definitions, 1, "Exactly one disclosure painter, including inside ui_kit"); +} + +#[test] +fn disclosure_guard_rejects_duplicate_icons_native_headers_font_glyphs_and_painting() { + let found = disclosure_guard( + r#" + use egui::CollapsingHeader as Fold; + fn raw(ui: &mut Ui) { + Fold::new("Title"); + ui.collapsing("Title", |_| {}); + paint_ink(p, r, if open { "chevron" } else { "chevron_right" }, ink); + paint_icon(p, r, "disclosure_open", 1.0); + ui.label(if open { "\u{25bc}" } else { "\u{25b6}" }); + } + fn paint_disclosure(ui: &mut Ui) { ui.painter().line_segment(points, stroke); } + fn raw_triangle(ui: &mut Ui, open: bool) { + let arrow = if open { down } else { right }; + ui.painter().add(Shape::convex_polygon(arrow, ink, Stroke::NONE)); + } + #[cfg(test)] mod tests { fn ignored(ui: &mut Ui) { ui.collapsing("Title", |_| {}); } } + fn after(ui: &mut Ui) { ui.collapsing("Title", |_| {}); } + fn caller(ui: &mut Ui) { crate::ui_kit::disclosure(ui.painter(), center, open, ink); } + fn dropdown(ui: &mut Ui) { crate::ui_kit::dropdown_indicator(ui.painter(), r, ink); } + "#, + ) + .found; + assert_eq!(found.len(), 9, "{found:?}"); +} + +#[test] +fn disclosure_guard_distinguishes_overflow_and_playback_from_conditional_folds() { + assert!(disclosure_guard(r#"fn show(ui: &mut Ui) { ui.menu_button("»", |_| {}); ui.label("▶ Play"); }"#).found.is_empty()); + assert_eq!(disclosure_guard(r#"fn show(ui: &mut Ui) { ui.label(if collapsed { "«" } else { "»" }); }"#).found.len(), 1); + assert_eq!(disclosure_guard("fn show(ui: &mut Ui) { egui::collapsing_header::paint_default_icon(ui, open, response); }").found.len(), 1); +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 1098f5bef..4cf6e35b9 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -3878,25 +3878,25 @@ fn view_menu(app: &mut SolveApp, ui: &mut egui::Ui, button: Rect) -> bool { ui.label(app.tr("ui.graphics_preset")); crate::prefs::graphics_preset_selector(app, ui); ui.separator(); - ui.checkbox(&mut app.ui.show_grid, crate::i18n::tr_label("Grid")); - ui.checkbox(&mut app.ui.ground_shadow, crate::i18n::tr_label("Ground shadow")); + crate::ui_kit::checkbox(ui, crate::i18n::tr_label("Grid"), &mut app.ui.show_grid); + crate::ui_kit::checkbox(ui, crate::i18n::tr_label("Ground shadow"), &mut app.ui.ground_shadow); crate::prefs::ambient_occlusion_checkbox(app, ui, "Ambient occlusion"); ui.separator(); let s = &mut app.ui.agent_cursor; - let show = ui.checkbox(&mut s.show, crate::i18n::tr_label("Show Agent Cursor")); + let show = crate::ui_kit::checkbox(ui, crate::i18n::tr_label("Show Agent Cursor"), &mut s.show); crate::scenario::publish_handle("view:agent_cursor", show.rect.center()); ui.add_enabled_ui(s.show, |ui| { ui.horizontal(|ui| { ui.label(crate::i18n::tr_label("Speed")); crate::agent_cursor::speed_slider(ui, &mut s.speed); }); - ui.checkbox(&mut s.follow_camera, crate::i18n::tr_label("Follow camera (Look At sketches)")); + crate::ui_kit::checkbox(ui, crate::i18n::tr_label("Follow camera (Look At sketches)"), &mut s.follow_camera); }); // The agent chat panel, once the chat is turned on in Preferences. if crate::agent_chat::shown(app) { ui.separator(); let mut open = app.agent_chat.open; - let r = ui.checkbox(&mut open, crate::agent_chat::panel_tip()); + let r = crate::ui_kit::checkbox(ui, &crate::agent_chat::panel_tip(), &mut open); crate::scenario::publish_handle("view:agent_chat", r.rect.center()); if r.changed() { app.agent_chat.open = open; diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rs index 1b86c6d97..02c0691d5 100644 --- a/crates/ui-egui/src/workspace.rs +++ b/crates/ui-egui/src/workspace.rs @@ -685,12 +685,13 @@ mod tests { assert!(h.app.dialog.is_none()); assert!(h.widget("User Parameters").is_some()); assert!(h.widget("Model Parameters").is_some()); - // Exercise the editor's Add button, not a script-only parameter command. + // Exercise the inline draft row through the public add prompt and Enter. + h.step(&json!({"click":{"handle":"dialog:table:user:add"}})).unwrap(); let parameters = h.app.params.as_mut().unwrap(); parameters.new_name = "width".into(); parameters.new_expr = "25 mm".into(); h.frames(3); - h.step(&json!({"widget":"Add"})).unwrap(); + h.step(&json!({"key":"Enter"})).unwrap(); let values = h.app.session.execute("parameters.list", &json!({})).unwrap(); assert!(values["parameters"].as_array().unwrap().iter().any(|p| p["name"] == "width" && p["value"] == 25.0)); h.step(&json!({"click":{"handle":"params:close"}})).unwrap(); @@ -702,7 +703,7 @@ mod tests { Some(crate::dialogs::Kind::Motion(crate::dialogs_motion::Mo::Configurations { .. })) )); assert!(h.widget("Add Column").is_some()); - assert!(h.widget("Add Row").is_some()); + assert!(h.widget("Add configuration").is_some()); } /// Shared assembly, sheet and plastic commands remain reachable in their ribbon sections. diff --git a/crates/ui-egui/tests/disclosure_render.rs b/crates/ui-egui/tests/disclosure_render.rs new file mode 100644 index 000000000..67f0e7aa4 --- /dev/null +++ b/crates/ui-egui/tests/disclosure_render.rs @@ -0,0 +1,63 @@ +//! Actual app evidence for disclosure states, rendered from egui meshes without a GPU. +#[path = "support/raster.rs"] +mod raster; + +use egui::{ColorImage, Rect, TextureId}; +use serde_json::json; +use solidcraft_ui_egui::{ + scenario::{self, Harness}, + shell::LayoutMode, + theme, +}; +use std::collections::HashMap; + +#[test] +fn appearance_and_browser_folds_keep_handles_and_render_both_states() { + let previous = theme::is_dark(); + let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/disclosure-review"); + std::fs::create_dir_all(&dir).unwrap(); + for dark in [false, true] { + let mut h = Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":1100,"height":1500})); + h.call("ui.set", json!({"dark":dark})); + h.app.ui.layout = LayoutMode::Floating; + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Body1".into() }]; + h.app.start("appearance.assign"); + h.frames(3); + for open in [true, false] { + if !open { + h.step(&json!({"click":{"handle":"dialog:collapse"}})).unwrap(); + h.step(&json!({"click":{"handle":"browser:header"}})).unwrap(); + } + assert_eq!(h.app.dialog.as_ref().unwrap().collapsed, !open); + assert_eq!(h.app.tree.panel_collapsed, !open); + assert_eq!(scenario::handle_at("fold:Bodies").is_some(), open); + assert_eq!(scenario::handle_at("appearance:search").is_some(), open); + // Fresh context transfers all textures to the software renderer, including fonts. + h.ctx = egui::Context::default(); + solidcraft_ui_egui::fonts::setup_fonts(&h.ctx); + theme::apply(&h.ctx); + let mut textures: HashMap = HashMap::new(); + for _ in 0..8 { + raster::paint(&mut h, &mut textures, vec![]); + } + let output = raster::paint(&mut h, &mut textures, vec![]); + let screenshot = raster::raster(&mut h, &textures, output); + let mode = if dark { "dark" } else { "light" }; + let state = if open { "open" } else { "closed" }; + screenshot.save(dir.join(format!("{mode}-{state}.png"))).unwrap(); + for (name, rect) in + [("appearance", scenario::rect_of("dialog:header").unwrap()), ("browser", scenario::rect_of("browser:header").unwrap())] + { + let bounds = rect.intersect(Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(screenshot.width() as f32, screenshot.height() as f32))); + image::imageops::crop_imm(&screenshot, bounds.left() as u32, bounds.top() as u32, bounds.width() as u32, bounds.height() as u32) + .to_image() + .save(dir.join(format!("{mode}-{state}-{name}.png"))) + .unwrap(); + } + } + } + theme::set_dark(previous); +} diff --git a/crates/ui-egui/tests/parameter_enter.rs b/crates/ui-egui/tests/parameter_enter.rs index 2c5c545bd..de7d7e10c 100644 --- a/crates/ui-egui/tests/parameter_enter.rs +++ b/crates/ui-egui/tests/parameter_enter.rs @@ -10,6 +10,7 @@ fn open() -> Harness { h.call("ui.start", json!({"command":"parameters.change"})); h.frames(3); assert!(h.app.params.is_some()); + h.step(&json!({"click":{"handle":"dialog:table:user:add"}})).unwrap(); h } fn fill(h: &mut Harness, field: &str, text: &str) { @@ -28,8 +29,8 @@ fn enter(h: &mut Harness, repeat: bool) { #[test] fn parameter_enter_adds_once_and_focuses_next_name() { let mut h = open(); - fill(&mut h, "name", "width"); fill(&mut h, "expression", "25 mm"); + fill(&mut h, "name", "width"); let undo = h.app.session.undo.len(); enter(&mut h, false); assert_eq!(h.app.session.undo.len(), undo + 1); @@ -52,8 +53,8 @@ fn parameter_enter_invalid_preserves_draft_and_other_rows() { let mut h = open(); h.app.session.execute("parameters.add", &json!({"name":"existing","expression":"10 mm"})).unwrap(); h.frames(3); - fill(&mut h, "name", "bad"); fill(&mut h, "expression", "missing + 1 mm"); + fill(&mut h, "name", "bad"); let saved = h.app.session.doc.to_json(); let undo = h.app.session.undo.len(); enter(&mut h, false); @@ -63,8 +64,8 @@ fn parameter_enter_invalid_preserves_draft_and_other_rows() { assert_eq!(d.new_name, "bad"); assert_eq!(d.new_expr, "missing + 1 mm"); assert!(d.error.is_some()); - fill(&mut h, "expression", "15 mm"); fill(&mut h, "name", "existing"); + fill(&mut h, "expression", "15 mm"); enter(&mut h, false); assert_eq!(h.app.session.doc.to_json(), saved); assert!(h.app.params.as_ref().unwrap().error.is_some()); @@ -74,12 +75,15 @@ fn parameter_enter_edits_expression_without_adding_draft() { let mut h = open(); h.app.session.execute("parameters.add", &json!({"name":"width","expression":"10 mm"})).unwrap(); h.frames(3); + // A named draft with an invalid expression stays pending on focus loss. + fill(&mut h, "expression", "missing + 1 mm"); fill(&mut h, "name", "unsubmitted"); let undo = h.app.session.undo.len(); h.run(&json!([{"click":{"handle":"param:width"}}, {"key":"A","cmd":true}, {"text":"20 mm"}])).unwrap(); enter(&mut h, false); assert_eq!(h.app.session.undo.len(), undo + 1); assert_eq!(h.app.params.as_ref().unwrap().new_name, "unsubmitted"); + assert!(h.app.params.as_ref().unwrap().error.is_none(), "Enter in the existing row never attempts the invalid draft"); let result = h.app.session.execute("parameters.list", &json!({})).unwrap(); let ps = result["parameters"].as_array().unwrap(); assert!(ps.iter().any(|p| p["name"] == "width" && p["expression"] == "20 mm")); @@ -95,14 +99,19 @@ fn parameter_enter_edits_expression_without_adding_draft() { #[test] fn parameter_enter_comment_uses_selected_unit_and_unrelated_focus_does_not_submit() { let mut h = open(); - fill(&mut h, "name", "length"); h.run(&json!([{"click":{"handle":"param:new:unit"}}, {"widget":"cm"}])).unwrap(); fill(&mut h, "expression", "2 cm"); fill(&mut h, "comment", "Overall length"); + fill(&mut h, "expression", "missing + 1 mm"); + fill(&mut h, "name", "length"); let undo = h.app.session.undo.len(); h.run(&json!([{"click":{"handle":"params:title"}}])).unwrap(); + // Make the pending expression valid while unrelated focus is retained, without firing + // the newly approved focus-loss commit route. Unrelated Enter must still do nothing. + h.app.params.as_mut().unwrap().new_expr = "2 cm".into(); enter(&mut h, false); assert_eq!(h.app.session.undo.len(), undo); + assert!(h.app.params.as_ref().unwrap().error.is_none(), "unrelated Enter never attempts the pending draft"); h.run(&json!([{"click":{"handle":"param:new:comment"}}])).unwrap(); enter(&mut h, false); let result = h.app.session.execute("parameters.list", &json!({})).unwrap(); @@ -131,8 +140,8 @@ fn parameter_rename_arrow_keys_move_cursor_and_keep_editing() { fn parameter_add_resets_expression_for_next_row() { let mut h = open(); let initial = h.app.params.as_ref().unwrap().new_expr.clone(); - fill(&mut h, "name", "width"); fill(&mut h, "expression", "25 mm"); + fill(&mut h, "name", "width"); enter(&mut h, false); let result = h.app.session.execute("parameters.list", &json!({})).unwrap(); assert!(result["parameters"].as_array().unwrap().iter().any(|p| p["name"] == "width" && p["expression"] == "25 mm")); diff --git a/crates/ui-egui/tests/popup_owner_capture.rs b/crates/ui-egui/tests/popup_owner_capture.rs new file mode 100644 index 000000000..73417ea2a --- /dev/null +++ b/crates/ui-egui/tests/popup_owner_capture.rs @@ -0,0 +1,178 @@ +//! Temporary visual review: rasterise the app's actual egui meshes without WindowServer. +use egui::{ColorImage, TextureId, pos2, vec2}; +use serde_json::json; +use solidcraft_ui_egui::{ + dialogs::Kind, + scenario::{self, Harness}, +}; +use std::collections::HashMap; + +fn paint(h: &mut Harness, textures: &mut HashMap, events: Vec) -> egui::FullOutput { + let time = h.ctx.cumulative_frame_nr() as f64 / 15.0; + let mut out = h.ctx.run_ui( + egui::RawInput { + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1100.0, 1500.0))), + focused: true, + events, + ..Default::default() + }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + for (id, deltas) in &out.textures_delta.set { + for delta in deltas { + let egui::ImageData::Color(image) = &delta.image; + if let Some([x, y]) = delta.pos { + let dest = textures.get_mut(id).unwrap(); + let dest_width = dest.width(); + for row in 0..image.height() { + for col in 0..image.width() { + dest.pixels[(y + row) * dest_width + x + col] = image.pixels[row * image.width() + col]; + } + } + } else { + textures.insert(*id, (**image).clone()); + } + } + } + out.textures_delta.clear(); + out +} + +fn save(h: &mut Harness, textures: &HashMap, out: egui::FullOutput, path: &str) { + let (width, height) = (1100u32, 1500u32); + let mut pixels = vec![255u8; (width * height * 4) as usize]; + let primitives = h.ctx.tessellate(out.shapes, out.pixels_per_point); + for clipped in primitives { + let egui::epaint::Primitive::Mesh(mesh) = clipped.primitive else { continue }; + let Some(texture) = textures.get(&mesh.texture_id) else { continue }; + for indices in mesh.indices.as_chunks::<3>().0 { + let [a, b, c] = [mesh.vertices[indices[0] as usize], mesh.vertices[indices[1] as usize], mesh.vertices[indices[2] as usize]]; + let cross = |u: egui::Vec2, v: egui::Vec2| u.x * v.y - u.y * v.x; + let area = cross(b.pos - a.pos, c.pos - a.pos); + if area.abs() < 1e-6 { + continue; + } + let left = a.pos.x.min(b.pos.x).min(c.pos.x).max(clipped.clip_rect.left()).max(0.0).floor() as u32; + let right = a.pos.x.max(b.pos.x).max(c.pos.x).min(clipped.clip_rect.right()).min(width as f32).ceil() as u32; + let top = a.pos.y.min(b.pos.y).min(c.pos.y).max(clipped.clip_rect.top()).max(0.0).floor() as u32; + let bottom = a.pos.y.max(b.pos.y).max(c.pos.y).min(clipped.clip_rect.bottom()).min(height as f32).ceil() as u32; + for y in top..bottom { + for x in left..right { + let p = pos2(x as f32 + 0.5, y as f32 + 0.5); + let w = [cross(b.pos - p, c.pos - p) / area, cross(c.pos - p, a.pos - p) / area, cross(a.pos - p, b.pos - p) / area]; + if w.iter().any(|v| *v < -1e-5) { + continue; + } + let uv = a.uv.to_vec2() * w[0] + b.uv.to_vec2() * w[1] + c.uv.to_vec2() * w[2]; + let tx = (uv.x * texture.width() as f32 - 0.5).clamp(0.0, texture.width() as f32 - 1.0); + let ty = (uv.y * texture.height() as f32 - 0.5).clamp(0.0, texture.height() as f32 - 1.0); + let (ix, iy) = (tx.floor() as usize, ty.floor() as usize); + let get = |x: usize, y: usize| texture.pixels[y * texture.width() + x].to_array().map(|v| v as f32 / 255.0); + let samples = [ + get(ix, iy), + get((ix + 1).min(texture.width() - 1), iy), + get(ix, (iy + 1).min(texture.height() - 1)), + get((ix + 1).min(texture.width() - 1), (iy + 1).min(texture.height() - 1)), + ]; + let (fx, fy) = (tx.fract(), ty.fract()); + let col = [a.color.to_array(), b.color.to_array(), c.color.to_array()]; + let mut src = [0.0; 4]; + for i in 0..4 { + let tex = samples[0][i] * (1.0 - fx) * (1.0 - fy) + + samples[1][i] * fx * (1.0 - fy) + + samples[2][i] * (1.0 - fx) * fy + + samples[3][i] * fx * fy; + src[i] = tex * (col[0][i] as f32 * w[0] + col[1][i] as f32 * w[1] + col[2][i] as f32 * w[2]) / 255.0; + } + let base = ((y * width + x) * 4) as usize; + for i in 0..3 { + pixels[base + i] = ((src[i] + pixels[base + i] as f32 / 255.0 * (1.0 - src[3])) * 255.0).clamp(0.0, 255.0) as u8; + } + } + } + } + } + image::save_buffer(path, &pixels, width, height, image::ColorType::Rgba8).unwrap(); +} + +#[test] +fn capture() { + let directory = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/popup-review"); + let root = directory.to_str().unwrap(); + std::fs::create_dir_all(root).unwrap(); + let crashes = format!("{root}/crashes"); + let id = "20261018-210412-bb60791ed6692f1d"; + std::fs::create_dir_all(format!("{crashes}/{id}")).unwrap(); + std::fs::write(format!("{crashes}/{id}/report.json"),json!({"format":"solidcraft-crash/1","id":id,"kind":"command_panic","count":3,"first_seen":"2026-10-18T21:04:12Z","message":"The radius produced a degenerate face while rebuilding Fillet2.","command":{"command":"solid.fillet","params":{"radius":2}},"backtrace":[],"app":{"version":"0.16.1"},"system":{}}).to_string()).unwrap(); + std::fs::write(format!("{crashes}/{id}/replay.json"), "{}").unwrap(); + for dark in [false, true] { + for mode in ["crash", "appearance", "params", "config", "prefs"] { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1100,"height":1500})); + h.call("ui.set", json!({"dark":dark})); + h.app.home.open = false; + if mode == "crash" || mode == "empty" { + h.app.crashes.folder = Some(std::path::PathBuf::from(if mode == "empty" { format!("{root}/empty") } else { crashes.clone() })); + h.call("ui.help", json!({"item":"crashes"})); + } else if mode == "params" || mode == "config" { + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.run("parameters.add", json!({"name":"width","expression":"10 mm"})).unwrap(); + if mode == "config" { + h.app.run("config.configure", json!({"params":["width"]})).unwrap(); + h.app.start("config.table"); + } else { + h.app.start("parameters.change"); + } + } else if mode == "prefs" { + h.call("ui.preferences", json!({})); + } else { + h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); + h.app.run("appearance.assign", json!({"bodies":["Body1"],"color":"#ccd0d6","appearance":"Aluminum - Satin","opacity":1.0})).unwrap(); + h.app.session.selection = vec![solidcraft_engine::Sel::Body { name: "Body1".into() }]; + let path = format!("{root}/review-library.json"); + h.app.run("library.export", json!({"path":path,"overwrite":true})).unwrap(); + h.app.start("appearance.assign"); + let Kind::Appearance(k) = &mut h.app.dialog.as_mut().unwrap().kind else { panic!() }; + k.local.path = path.clone(); + k.local.catalog = Some(solidcraft_engine::io::catalog::Catalog::read(&path).unwrap()); + k.local.selected = k.local.catalog.as_ref().and_then(|c| c.entries.first()).map(|e| e.id.clone()); + k.note = Some("Appearance applied".into()); + if mode == "pbr" { + k.pbr = Some(Default::default()); + k.component = Some("Plate".into()); + } + } + h.ctx = egui::Context::default(); + solidcraft_ui_egui::fonts::setup_fonts(&h.ctx); + let mut textures = HashMap::new(); + for _ in 0..6 { + paint(&mut h, &mut textures, vec![]); + } + let theme = if dark { "dark" } else { "light" }; + let out = paint(&mut h, &mut textures, vec![]); + save(&mut h, &textures, out, &format!("{root}/{mode}-{theme}.png")); + if mode == "appearance" { + let at = scenario::handle_at("dialog:color:Colour").unwrap(); + for pressed in [true, false] { + paint( + &mut h, + &mut textures, + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + for _ in 0..3 { + paint(&mut h, &mut textures, vec![]); + } + let out = paint(&mut h, &mut textures, vec![]); + save(&mut h, &textures, out, &format!("{root}/picker-{theme}.png")); + } + } + } +} diff --git a/crates/ui-egui/tests/popup_regressions.rs b/crates/ui-egui/tests/popup_regressions.rs new file mode 100644 index 000000000..9d655e13e --- /dev/null +++ b/crates/ui-egui/tests/popup_regressions.rs @@ -0,0 +1,148 @@ +//! Raster checks for the real Parameters and Crash Reports cards at device scales. +#[path = "support/raster.rs"] +mod raster; + +use egui::{ColorImage, Rect, TextureId, pos2}; +use serde_json::json; +use solidcraft_ui_egui::{ + scenario::{self, Harness}, + theme::Tokens, +}; +use std::collections::HashMap; + +fn setup(dark: bool, ppp: f32) -> Harness { + let mut h = Harness::new(); + h.call("ui.resize", json!({"width":1100,"height":1500})); + h.call("ui.set", json!({"dark":dark})); + h.app.home.open = false; + h.app.preferences.ui_scale = ppp; + h +} + +fn capture(h: &mut Harness, name: &str) -> (image::RgbaImage, egui::FullOutput) { + // Control calls run layout frames. A fresh context ensures this renderer receives + // the initial font atlas and every icon texture, including the white fill texel. + h.ctx = egui::Context::default(); + h.ctx.set_pixels_per_point(h.app.preferences.ui_scale); + solidcraft_ui_egui::fonts::setup_fonts(&h.ctx); + solidcraft_ui_egui::theme::apply(&h.ctx); + let mut textures: HashMap = HashMap::new(); + for _ in 0..8 { + raster::paint(h, &mut textures, vec![]); + } + if name.starts_with("crash-") { + // ScrollAreaOutput reports the viewport before auto-shrink; use the painted list bounds. + let viewport = + scenario::rect_of("dialog:list:reports:viewport").unwrap().intersect(scenario::rect_of("dialog:list:reports").unwrap().shrink(1.0)); + let at = if name.ends_with("true") { viewport.right_top() + egui::vec2(-1.0, 4.0) } else { viewport.right_bottom() - egui::vec2(4.0, 1.0) }; + for _ in 0..8 { + raster::paint(h, &mut textures, vec![egui::Event::PointerMoved(at)]); + } + } + let out = raster::paint(h, &mut textures, vec![]); + let image = raster::raster(h, &textures, out.clone()); + let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/popup-regressions"); + std::fs::create_dir_all(&dir).unwrap(); + let card = scenario::rect_of("dialog:window") + .unwrap_or_else(|| scenario::rect_of("dialog:header").unwrap().union(scenario::rect_of("dialog:footer").unwrap())); + let ppp = h.ctx.pixels_per_point(); + crop(&image, card, ppp).save(dir.join(format!("{name}.png"))).unwrap(); + (image, out) +} + +fn crop(image: &image::RgbaImage, rect: Rect, ppp: f32) -> image::RgbaImage { + image::imageops::crop_imm( + image, + (rect.left() * ppp).max(0.0) as u32, + (rect.top() * ppp).max(0.0) as u32, + (rect.width() * ppp) as u32, + (rect.height() * ppp) as u32, + ) + .to_image() +} + +#[test] +fn parameter_transfer_buttons_use_existing_distinct_tray_arrows_at_1x_and_2x() { + for dark in [false, true] { + for ppp in [1.0, 2.0] { + let mut h = setup(dark, ppp); + h.app.start("parameters.change"); + let (image, out) = capture(&mut h, &format!("parameters-{dark}-{ppp}x")); + let meshes = h.ctx.tessellate(out.shapes, ppp); + let t = Tokens::get(); + for (label, id) in [("Import…", "import_tray"), ("Export CSV…", "export_tray"), ("Export JSON…", "export_tray")] { + let button = scenario::rect_of(&format!("dialog:button::{label}")).unwrap(); + let expected = format!("icon:{id}:{}", (t.space_14 * ppp) as u32); + assert_ne!(solidcraft_ui_egui::icon_svg::resolve(id).master, "placeholder"); + assert!( + meshes.iter().any(|clipped| match &clipped.primitive { + egui::epaint::Primitive::Mesh(mesh) => + h.ctx.tex_manager().read().meta(mesh.texture_id).is_some_and(|meta| meta.name == expected) + && mesh.vertices.iter().any(|v| button.contains(v.pos)), + _ => false, + }), + "{label} must render {expected} inside its own button" + ); + let dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/popup-regressions"); + crop(&image, button, ppp).save(dir.join(format!("{id}-{label}-{dark}-{ppp}x.png"))).unwrap(); + } + assert_ne!(solidcraft_ui_egui::icon_svg::resolve("import_tray").master, solidcraft_ui_egui::icon_svg::resolve("export_tray").master); + } + } +} + +const REPORT: &str = "20261018-210412-bb60791ed6692f1d"; + +#[test] +fn crash_card_has_no_horizontal_bar_but_long_reports_still_scroll_vertically() { + for dark in [false, true] { + for ppp in [1.0, 2.0] { + for long in [false, true] { + let mut h = setup(dark, ppp); + let folder = h.dir.join("crashes"); + for (id, message) in [ + (REPORT, "The radius produced a degenerate face while rebuilding Fillet2.".to_owned()), + ("20261017-210412-bb60791ed6692f1d", "Long report line.\n".repeat(800)), + ] + .into_iter() + .take(if long { 2 } else { 1 }) + { + std::fs::create_dir_all(folder.join(id)).unwrap(); + std::fs::write(folder.join(id).join("report.json"), json!({"format":"solidcraft-crash/1", "id":id, "kind":"command_panic", "count":3, + "first_seen":"2026-10-18T21:04:12Z", "message":message,"command":{"command":"solid.fillet","params":{"radius":2}}, "backtrace":[], "app":{"version":"0.16.1"}, "system":{}}).to_string()).unwrap(); + } + h.app.crashes.folder = Some(folder); + h.call("ui.help", json!({"item":"crashes"})); + let (image, _) = capture(&mut h, &format!("crash-{dark}-{ppp}x-long-{long}")); + let viewport = scenario::rect_of("dialog:list:reports:viewport") + .unwrap() + .intersect(scenario::rect_of("dialog:list:reports").unwrap().shrink(1.0)); + let message = scenario::rect_of(&format!("dialog:report:message:{REPORT}")).unwrap(); + let below = Rect::from_min_max( + pos2(viewport.left() + 2.0, message.bottom() + 1.0), + pos2(viewport.right() - 12.0, (message.bottom() + 20.0).min(viewport.bottom())), + ); + let divider = scenario::rect_of(&format!("dialog:divider:end:{REPORT}")); + if long { + // A divider separates reports only; it is a full-width hairline. + let divider = divider.unwrap(); + let frame = scenario::rect_of("dialog:list:reports").unwrap(); + assert!((divider.left() - frame.left() - 1.0).abs() <= 1.0 / ppp); + assert!((frame.right() - divider.right() - 1.0).abs() <= 1.0 / ppp); + assert_eq!(divider.height(), 1.0); + } else { + assert!(divider.is_none(), "no divider after the last report"); + } + let bar = Tokens::get().form_ink.to_array(); + assert_eq!( + crop(&image, below, ppp).pixels().filter(|p| p.0 == bar).count(), + 0, + "no scrollbar pixels below the message: dark={dark}, ppp={ppp}, long={long}" + ); + let right = Rect::from_min_max(pos2(viewport.right() - 4.0, viewport.top() + 2.0), pos2(viewport.right(), viewport.bottom() - 2.0)); + let bar_pixels = crop(&image, right, ppp).pixels().filter(|p| p.0 == bar).count(); + assert_eq!(bar_pixels > 0, long, "vertical scrollbar pixels: {bar_pixels}, long={long}, dark={dark}, ppp={ppp}"); + } + } + } +} diff --git a/crates/ui-egui/tests/scenarios/s23_configurations.json b/crates/ui-egui/tests/scenarios/s23_configurations.json index df923be53..121ece3c6 100644 --- a/crates/ui-egui/tests/scenarios/s23_configurations.json +++ b/crates/ui-egui/tests/scenarios/s23_configurations.json @@ -81,13 +81,16 @@ "start": "config.configure" }, { - "widget": "Add Column" + "click": {"handle":"dialog:menu:Add Column"} }, { "widget": "d1" }, { - "widget": "Add Row" + "click": {"handle":"dialog:table:configuration_table:add"} + }, + { + "key": "Enter" }, { "widget": "40 mm", diff --git a/crates/ui-egui/tests/scenarios/s60_appearance_overrides.json b/crates/ui-egui/tests/scenarios/s60_appearance_overrides.json index 5aa97296d..6a40fdb08 100644 --- a/crates/ui-egui/tests/scenarios/s60_appearance_overrides.json +++ b/crates/ui-egui/tests/scenarios/s60_appearance_overrides.json @@ -5,6 +5,8 @@ {"call": "ui.menu", "params": {"x": 300, "y": 300, "target": {"type": "body", "name": "Body1"}}}, {"call": "ui.menuPick", "params": {"item": "Appearance"}}, {"expect": {"dialog": "Appearance", "shown": "Remove override"}}, + {"note": "The shared 28 px controls make this card scroll; reveal Search inside its body."}, + {"call": "ui.scroll", "params": {"x": 1345, "y": 650, "delta": -400}}, {"click": {"handle": "appearance:search"}}, {"text": "no-such-appearance"}, {"expect": {"shown": "No matching appearances"}}, diff --git a/crates/ui-egui/tests/support/raster.rs b/crates/ui-egui/tests/support/raster.rs new file mode 100644 index 000000000..a31c1ff65 --- /dev/null +++ b/crates/ui-egui/tests/support/raster.rs @@ -0,0 +1,103 @@ +//! Deterministic software rasterisation of the actual egui meshes and texture uploads. +use egui::{ColorImage, TextureId, pos2, vec2}; + +use solidcraft_ui_egui::scenario::Harness; +use std::collections::HashMap; + +pub fn paint(h: &mut Harness, textures: &mut HashMap, events: Vec) -> egui::FullOutput { + let time = h.ctx.cumulative_frame_nr() as f64 / 15.0; + let mut out = h.ctx.run_ui( + egui::RawInput { + time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1100.0, 1500.0))), + focused: true, + events, + ..Default::default() + }, + |ui| { + h.app.logic(ui.ctx()); + h.app.ui(ui); + }, + ); + for (id, deltas) in &out.textures_delta.set { + for delta in deltas { + let egui::ImageData::Color(image) = &delta.image; + if let Some([x, y]) = delta.pos { + let dest = textures.get_mut(id).unwrap(); + let dest_width = dest.width(); + for row in 0..image.height() { + for col in 0..image.width() { + dest.pixels[(y + row) * dest_width + x + col] = image.pixels[row * image.width() + col]; + } + } + } else { + textures.insert(*id, (**image).clone()); + } + } + } + out.textures_delta.clear(); + out +} + +pub fn raster(h: &mut Harness, textures: &HashMap, out: egui::FullOutput) -> image::RgbaImage { + let ppp = out.pixels_per_point; + let (width, height) = ((1100.0 * ppp) as u32, (1500.0 * ppp) as u32); + let mut pixels = vec![255u8; (width * height * 4) as usize]; + let primitives = h.ctx.tessellate(out.shapes, out.pixels_per_point); + for clipped in primitives { + let egui::epaint::Primitive::Mesh(mesh) = clipped.primitive else { continue }; + let Some(texture) = textures.get(&mesh.texture_id) else { continue }; + let clip = clipped.clip_rect * ppp; + for indices in mesh.indices.as_chunks::<3>().0 { + let [a, b, c] = [indices[0], indices[1], indices[2]].map(|i| { + let mut v = mesh.vertices[i as usize]; + v.pos = pos2(v.pos.x * ppp, v.pos.y * ppp); + v + }); + let cross = |u: egui::Vec2, v: egui::Vec2| u.x * v.y - u.y * v.x; + let area = cross(b.pos - a.pos, c.pos - a.pos); + if area.abs() < 1e-6 { + continue; + } + let left = a.pos.x.min(b.pos.x).min(c.pos.x).max(clip.left()).max(0.0).floor() as u32; + let right = a.pos.x.max(b.pos.x).max(c.pos.x).min(clip.right()).min(width as f32).ceil() as u32; + let top = a.pos.y.min(b.pos.y).min(c.pos.y).max(clip.top()).max(0.0).floor() as u32; + let bottom = a.pos.y.max(b.pos.y).max(c.pos.y).min(clip.bottom()).min(height as f32).ceil() as u32; + for y in top..bottom { + for x in left..right { + let p = pos2(x as f32 + 0.5, y as f32 + 0.5); + let w = [cross(b.pos - p, c.pos - p) / area, cross(c.pos - p, a.pos - p) / area, cross(a.pos - p, b.pos - p) / area]; + if w.iter().any(|v| *v < -1e-5) { + continue; + } + let uv = a.uv.to_vec2() * w[0] + b.uv.to_vec2() * w[1] + c.uv.to_vec2() * w[2]; + let tx = (uv.x * texture.width() as f32 - 0.5).clamp(0.0, texture.width() as f32 - 1.0); + let ty = (uv.y * texture.height() as f32 - 0.5).clamp(0.0, texture.height() as f32 - 1.0); + let (ix, iy) = (tx.floor() as usize, ty.floor() as usize); + let get = |x: usize, y: usize| texture.pixels[y * texture.width() + x].to_array().map(|v| v as f32 / 255.0); + let samples = [ + get(ix, iy), + get((ix + 1).min(texture.width() - 1), iy), + get(ix, (iy + 1).min(texture.height() - 1)), + get((ix + 1).min(texture.width() - 1), (iy + 1).min(texture.height() - 1)), + ]; + let (fx, fy) = (tx.fract(), ty.fract()); + let col = [a.color.to_array(), b.color.to_array(), c.color.to_array()]; + let mut src = [0.0; 4]; + for i in 0..4 { + let tex = samples[0][i] * (1.0 - fx) * (1.0 - fy) + + samples[1][i] * fx * (1.0 - fy) + + samples[2][i] * (1.0 - fx) * fy + + samples[3][i] * fx * fy; + src[i] = tex * (col[0][i] as f32 * w[0] + col[1][i] as f32 * w[1] + col[2][i] as f32 * w[2]) / 255.0; + } + let base = ((y * width + x) * 4) as usize; + for i in 0..3 { + pixels[base + i] = ((src[i] + pixels[base + i] as f32 / 255.0 * (1.0 - src[3])) * 255.0).clamp(0.0, 255.0) as u8; + } + } + } + } + } + image::RgbaImage::from_raw(width, height, pixels).unwrap() +} diff --git a/docs/ui-kit.md b/docs/ui-kit.md index dada43c09..ace38a738 100644 --- a/docs/ui-kit.md +++ b/docs/ui-kit.md @@ -7,8 +7,12 @@ preferences, manager cards, prompts and the sketch palette. Import through ## Composition and rules - Colours, typography, dimensions and spacing come from `theme::Tokens`. +- Sliders only via `ui_kit::slider`; `Slider` options change behaviour, never appearance. + Raw sliders and duplicate track/thumb painters are forbidden in the UI and apps. - `scope(ui, add)` supplies form styling. `row(ui, label, add)` aligns labels and - controls at `control_height` (24 pt today). Labels widen from `form_label_width` + controls at `control_height` (28 pt). Wide manager rows use a 104 pt label basis + with a 10 pt gutter, derived from the compact 70 pt basis and spacing tokens. + Compact rows retain their 8 pt gutter. Labels widen from the appropriate basis to at most 1.6 times that width and never exceed half the row. - `expr_row`, `hint_row`, `text_row` and `choice_row` compose `row` with the existing expression, hinted expression, plain text and dropdown controls. They preserve row order, @@ -23,6 +27,12 @@ preferences, manager cards, prompts and the sketch palette. Import through action. It returns `(close_pressed, Action)`. - Callers supply data and enabled state, then dispatch existing commands. Editors leave their established completion, Enter, Tab and commit ownership unchanged. +- Every text input uses the kit's shared `text_input` policy: symmetric horizontal + `form_inset`, zero vertical margin and centred galley alignment. Font metrics + therefore centre both mono and proportional text within the allocated field, + including invalid and attached Library fields, without per-caller offsets. + Canvas placement editors retain their native line-height plus `space_4` hit + target so nearby sketch picks are not intercepted; alignment stays shared. - Scenario handles and accessible labels are API. Consolidated options preserve the former geometry, wrapping, native metadata and publication keys. @@ -34,10 +44,10 @@ table. Panel/Prompt compositions also have dedicated geometry and interaction te | Module / element | Use and options | Main tokens | | --- | --- | --- | -| metrics: `row_height`, `header_height` | Shared control/header heights | `control_height`, `form_header_height` | +| metrics: `row_height`, `table_row_height`, `header_height` | Shared control/header heights | `control_height`, `space_8`, `form_header_height` | | layout: `scope`, `row` | Form styling and aligned label/control columns | `form_label_width`, `form_gap_y`, `control_*`, `font_label`, `dialog_label`, `space_4/8` | | `caption` | Dim caption aligned beneath a control | `font_small`, `text_dim`, label-column tokens | -| `section`, `divider` | Persisted disclosure and full-width rule | `control_height`, `dialog_rule`, `font_caption`, tracking, spacing | +| `section`, `section_count`, `divider` | Persisted small-caps disclosure with chevron, optional count badge and trailing hairline; full-width rule | `control_height`, `dialog_rule`, `font_caption`, tracking, spacing | | `list_row` | Picked item with a remove target | `control_height`, `font_label`, icon/spacing tokens | | `text`, `Text` | Hint, note, report, inline or cell text; see variants below | `font_small/label`, `text/dim/error`, `control_height`, `space_4` | | `text_lines` | Virtualized read-only licence/report lines, horizontal overflow | `font_small`, `text`, `control_height` | @@ -46,46 +56,51 @@ table. Panel/Prompt compositions also have dedicated geometry and interaction te | `multiline_text_field` | Three-line plain-text row with stable focus ID | field/row tokens | | `password_field` | Stable secret editor; excludes the secret from scenario/accessibility metadata | field tokens | | `message_field` | Growing message editor; owner retains scroll and Enter routing | field tokens | -| `cell_editor`, `bounded_cell_editor`, `search_field` | Stable-ID inline/search editors; bounded variant caps Unicode characters | field tokens, `text/error` | +| `cell_editor`, `bounded_cell_editor`, `search_field`, `library_cell` | Stable-ID inline/search editors; bounded variant caps Unicode characters; `library_cell` attaches a Library dropdown inside the editor border | field tokens, `text/error` | | `text_area` | Bounded multiline JSON/data editor | field tokens | | `dropdown`, `dropdown_menu` | Indexed choices or caller-supplied menu controls | `control_height`, `text_dim`, form tokens | | `searchable_dropdown`, `SearchOption` | Filtered choices, custom-value action and pending message | dropdown tokens | | `selection_field`, `Selection` | Selection chip with explicit `active` and `filled` state | `selected_bg/ink`, `accent`, `control_*`, `form_inset`, `space_8/24` | | `value_pair` | Paired captions/expressions; optional independent field names | row/field tokens, `space_8` | -| `fraction_field`, `scalar_field` | Locale-aware bounded dimensionless values | form control/font tokens | +| `fraction_field`, `scalar_field` | Locale-aware bounded dimensionless values; scalar fields fill their control column | form control/font tokens | | `number_field` | Integer/decimal field with caller range, drag speed and suffix | form control/font tokens | | `length_field`, `angle_field` | Length in design units, angle in degrees | form control/font tokens | -| `slider`, `formatted_slider` | Continuous slider or stepped preference slider with caller formatting | `control_height`, form control/font tokens | -| `timeline_slider` | Slider without editor; optional whole-step manipulation | `control_height`, `space_4` | +| `slider` + `Slider` options | One token-painted track/thumb over native slider/value interaction; optional step, caller formatting, whole-step manipulation and hidden value editor | `control_height`, `space_24/8/4/2`, form control/font tokens | | `placement_field` | Stable focus ID; drawing tool owns Enter/Tab validation and completion | `control_fill`, `font_body`, `text`, `control_height`, spacing | -| `color_field` | Document RGB chooser, retaining egui's internal HSV/RGB popup | form control/font tokens | -| choice: `segmented`, `Segments` | Equal text choices; `states` supplies mixed selection, `compact` clips instead of falling back to a dropdown | `control_*`, `selected_bg/ink`, `font_label`, `space_4/8` | +| `color_field`, `color_popover` | Opaque document RGB swatch and kit popover; global U8/F segments, copy, gamma-byte or linear RGB fields, painter-drawn HSV square/hue and current strip; outside click dismisses | `control_*`, `form_*`, `border`, `on_accent`, `space_*` | +| choice: `segmented`, `Segments` | Equal text choices; `states` supplies mixed selection, `compact` clips instead of falling back to a dropdown, `primary` uses accent/on-accent for the selected segment | `control_*`, `selected_bg/ink`, `font_label`, `space_4/8` | | `segmented_icons`, `IconSegment` | Equal icon choices and mixed states | segment tokens, icon palette | -| `checkbox`, `checkbox_row`, `checkbox_grid`, `options` | Inline, full-row, bounded-column or disclosed checkbox choices | `control_*`, `accent`, `on_accent`, typography/spacing | +| `checkbox`, `checkbox_indeterminate`, `checkbox_row`, `checkbox_grid`, `options` | One box/tick painter for inline, mixed, full-row, grid and menu choices | `space_14/3/2`, `radius_sm`, `control_fill/border`, `form_primary/ink`, `hover`, `on_accent` | | `text_emphasis` | Bold/italic with translated accessible names | form control/font tokens | | `tool_choices`, `ToolChoice`, `toggle_icon` | Wrapped command modes or independent icon toggles | sketch mode/icon tokens, `accent` | | `list_picker` | Selectable row with caller identity and native checked state | `control_height`, form selection tokens | | `popup_list`, `PopupOption` | Focus-neutral suggestions; owner retains keyboard routing | `space_2`, `form_label_width`, `control_height`, form tokens | -| `color_swatch`, `swatch_grid` | Wrapped draggable document colours with caller payloads | `control_height/radius`, `border`, `accent`, `hover`, `space_4` | +| `color_swatch`, `swatch_grid`, `color_thumbnail` | 30 pt draggable samples, 6 pt grid step gap, selected outer ring and checker pattern under transparent colours; caller payloads retained; local-library thumbnails use 16 pt | `control_height/radius`, `border`, `form_primary`, `control_fill`, `space_2/6/8` | | actions: `button`, `Button` | Secondary action: `Normal`, `Small`, or `Enabled(bool)` | native sizing, form font/control tokens | | `primary_button` | Accent action outside a footer | `accent`, `on_accent`, form tokens | | `icon_button_at` | Icon action inside a supplied rectangle | `form_icon_inset`, `text/dim`, icon palette | | `button_pair`, `PairButton` | Equal secondary actions, optional icons and selected state | `form_button_height`, control/selection/icon tokens | | `footer`, `Footer`, `Action` | OK/Cancel with optional Apply, compute status or selected action | `form_footer/button_height`, `dialog_footer/rule`, `control_*`, `accent`, spacing | | `keyboard` | Esc cancels, unowned Enter submits when valid | none | -| `action_menu` | Nested dense action menu | form control/font tokens | -| table: `table`, `Column`, `Table::row`, `Table::column_actions`, `TableRow::cell` | Left-aligned headers/cells, horizontal overflow, selectable rows, attached column-action band and empty state; `Column::new(label, width)` uses label-column multiples, `min_content_width(points)` reserves measured control content | label-column tokens, `control_height`, `dialog_rule/footer`, `selected_bg`, spacing | +| `action_menu`, `command_menu_button` | Nested dense action menu or ribbon overflow action retaining its icon, shortcut and enabled state | form control/font tokens, `space_16`, icon palette | +| table: `table`, `table_custom`, `Column`, `Table::headers`, `Table::row`, `TableRow::cell`, `Table::add_prompt` | Left-aligned headers/cells, horizontal overflow, selected/hover rows and empty state. `table_custom` supplies header actions through `headers`. `Column::flex` shares remaining width by weight, freezing columns at their control minimums before redistributing the remaining space; `Column::icon_only` hides the heading while retaining its automation identity. `add_prompt` is the final slim dashed line and requests a regular draft row from its owner; `Column::new(label, width)` uses label-column multiples, `min_content_width(points)` reserves measured control content; `ContentWidth::name` measures strong configuration names | label-column tokens, `control_height`, `dialog_rule/footer`, `selected_bg`, spacing | +| `removable_header`, `plus_header`, `bin_button`, `active_pill` | Hover-only column removal, anchored Add Column menu with insertion brackets, icon-only immediate deletion and active-row status. Bins preserve `dialog:button:Actions:Delete` and `:×`; header removal preserves `dialog:button:LABEL:×`. | `control_*`, `form_*`, `selected_bg`, spacing | +| `compact_button`, `summary_row` | Borderless stars and chevrons with enabled/selected states; named two-line rule summary beside an enable checkbox and compact actions. | `form_close_size`, `control_*`, `form_*`, typography and spacing | | `label_actions` | Clipped row name beside compact actions | `control_height`, form font/spacing tokens | | status: `status_header`, `StatusHeader` | Supplied icon/name/status and constraint meter | `font_label`, `text/dim`, `accent`, sketch/header tokens | | `progress` | Clamped determinate progress | `space_3/6`, `dialog_rule`, `accent` | -`text(ui, text, options)` preserves five existing text behaviors: +`text(ui, text, options)` supports the existing text behaviors and the new error band: | Option | Layout and scenario publication | | --- | --- | -| `Text::Hint(key)` | One fixed row; tooltip, rect and handle `dialog:hint:KEY` | -| `Text::Note(key)` | Wrapping small dim text with vertical padding; rect `dialog:note:KEY` | +| `Text::Hint(key)` | Wrapping 12 pt hint; rect and handle `dialog:hint:KEY` | +| `Text::Note(key)`, `Text::MonoNote(key)` | Wrapping small dim text (optional monospace) with vertical padding; rect `dialog:note:KEY` | +| `Text::Error(key)` | Wrapping full-width error band with tinted background and padding; retains `dialog:report:KEY` | | `Text::Report(key, error)` | Native wrapping label, optional error colour; rect/handle `dialog:report:KEY` | +| `Text::Heading(key)` | Semibold body heading; retains `dialog:report:KEY` | +| `Text::NameCell(strong)` | Medium/semibold clipped clickable name; retains `dialog:cell:TEXT` | +| `Text::MonoCell`, `Text::Value(key, error)` | Monospace unit/value cells; clipped to one row with full tooltips. Value/error cells retain `dialog:report:KEY`. | | `Text::Inline` | Native truncated label; rect/handle `dialog:inline:TEXT` | | `Text::Cell` | Fixed-height clipped clickable cell with tooltip; rect/handle `dialog:cell:TEXT` | @@ -115,3 +130,122 @@ Clippy, wasm, i18n, assets, icons and layers still apply. See [remaining coverage boundaries](manage-ui-kit-audit.md) for specialised surfaces that remain outside the kit and why. + +## Popup presentation and draft rows + +All kit cards use 28 pt controls, a 40 pt title band (14 pt semibold title, +19 pt command icon and 26 pt close/fold targets), and a 48 pt footer with +28 pt actions. Table rows are `control_height + space_8` (36 pt), independent +of control height. Bodies use 12 pt insets. Width limits and scroll boundaries +remain owned by Panel/Prompt. Titles retain the supplied case. + +The `form_ink`, `form_dim`, `form_primary`, `form_error` and `form_error_fill` +colour keys match the approved light cards. Dark values follow existing text, +accent and error palette roles; every role is exported by theme files and measured +by the colour-vision checks. Invalid fields include both error text and a tinted +surface. Long variable-height lists can use `Prompt::placed` with a top-left pivot to +keep their painted controls and scenario targets aligned as they grow. +Completion lists use the approved 230 pt minimum width (derived from card and +spacing tokens), show kind labels on the right, selected details beneath +the list, and the existing keyboard hint. + +Parameters and Configuration Table use this one table grid, including Favorites +and each model group. The grid has `space_8` horizontal insets within the row +highlight, shared by headers and cells, plus `space_8` column gaps. Flexible widths +are measured inside the scroll viewport and rounded by cumulative column edges; +fitting content does not acquire a horizontal scrollbar from independent rounding +or inherited scroll margins. Explicit minimum widths still allow genuine overflow. +The viewport and measured content width publish `dialog:table:TABLE:viewport` and +`dialog:table:TABLE:content_width` for geometry checks. Hover uses the clipped row +rectangle, including interactive children, while preserving child click ownership. +Their add prompts publish `dialog:table:TABLE:add`, use `control_height - space_4` +height, a dashed `control_radius` outline and a pointing-hand cursor. +Clicking creates a regular unsaved row, focuses its name and exposes the existing +field controls and bin. Enter or valid focus loss commits through the existing +commands; abandoning a nameless row drops it. Configuration Enter with an empty +name retains ConfigurationN naming and copies the active row. Parameter validity +is published as `param:new:valid`; invalid expressions cannot commit on focus loss. +The natural scrolling body height is published as `dialog:body:content_height`, +so geometry tests distinguish content size from the viewport cap. +After a successful parameter add, a fresh empty draft retains Name focus for +continuous keyboard entry; leaving that empty row drops it. +Parameter draft fields retain `param:new:name/unit/expression/comment`. +Configuration drafts publish `config:new:name`; existing `config:cell:ROW:COLUMN`, +activation, rule and preview handles remain. The header plus retains +`dialog:menu:Add Column`, including the existing menu nesting. The old separate +Add forms and column-removal band have been removed. + + +Crash Reports uses `report_list` (bordered bounded scroll), `report_header` (kind, +count pill and mono UTC time), `path_chip` (clipped mono path and adjacent action), +`empty_box` (dashed empty state), and `icon_label_button` (secondary icon/text, +optional danger ink). These use `dialog_rule/footer`, `control_*`, `form_*`, +`font_label/small` and spacing tokens. The report header retains the combined-title +cell alias; bins retain the previous Delete handle. Report actions remain immediate. +`list_frame` supplies the same border to virtualised library rows. +The list frame owns its border and horizontal padding; the report viewport adds +no inherited scroll margin. Report list measurements publish +`dialog:list:KEY:viewport` and `dialog:list:KEY:content_width`. Reports use vertical +scrolling; the horizontal rule beneath each report remains a divider. +Appearance uses a 340 pt card derived from card/label/spacing tokens, with the +104 pt label basis where space permits, 10 pt body gaps, and a count on In This Design. + +Colour popovers retain `dialog:color:ROW` and add `color:format:U8/F`, +`color:copy`, `color:channel:R/G/B`, `color:sv`, `color:hue`, `color:current` +and the `color:popover` rectangle. Format changes update egui's global numeric +colour presentation without changing RGB. Linear fields edit linear RGB, not +normalised gamma bytes. HSV state preserves hue at zero saturation/value and +sub-byte precision during drags. Gradient colours are document colour data; +all interface chrome uses existing paired light/dark tokens. + +Sliders only via `ui_kit::slider`, everywhere in `crates/ui-egui/src` and `apps`. +The element owns its form styling even when called from a viewport menu. +`Slider` options select behaviour, never appearance: range and values remain in caller +units, `step` preserves stepping, `format` preserves suffixes/display mapping, +`integer` rounds manipulation and `show_value: false` hides the editor. Disabled +sliders use `ui.add_enabled_ui`; tooltips attach to the returned response. Preferences +UI scale still applies only after the pointer is released. There are no alternative +slider helpers, raw `egui::Slider` callers, or custom track/thumb painters outside +the kit. The source guard scans both trees without an allowance table; the gallery +covers continuous, percent/stepped, integer/no-editor and disabled states in both themes. +Numeric fields use the existing kit `scalar_field`, `length_field`, `angle_field` +or `number_field` rather than constructing a raw `egui::DragValue` at a caller. + +Parameters retains its bounded header drag offset while the manager is open, +including frames without a regular feature dialog. The shared Panel bound reserves +header and footer space at the bottom edge. Import and both export actions use +`icon_label_button` with the existing `import`/`export` arrow icons and unchanged +command routing and scenario identities. The gallery includes all three actions. +The Add Column target is `form_close_size - space_4` (22 pt) square: idle paint is +only `form_dim` ink; hover adds the selected accent fill and insertion guides. +HSV gradients use a rounded mesh silhouette sampled along `control_radius` arcs; +the current-colour strip uses the same rounded radius. Render tests sample all +four corner pixels and opaque interiors of all three surfaces at 1× and 2× in +both themes. + +Checkboxes only via `ui_kit::checkbox`, everywhere in `crates/ui-egui/src` and +`apps`. `checkbox_row`, `checkbox_grid` and menu checkbox rows share its single +box painter and `paint_check_glyph` path. The box is `space_14` square with +`radius_sm` corners, a `control_border` outline and `control_fill` background. +Checked/mixed boxes use `form_primary` and `on_accent`; hover uses `hover` and +an accent border, focus adds a `space_2` outset ring, and disabled controls inherit +egui's disabled opacity. Geometry never depends on caller font or native icon size. +`checkbox_indeterminate` represents a mixed selection with a bar and activates to +checked. Space/Enter, accessible checked state, tooltips and scenario handles are +retained. Exclusive choices use existing kit segments/dropdowns/list pickers; +there are no radio controls. The recursive guard rejects native checkbox/radio +constructors (including aliases), raw toggle methods and duplicate check glyph +painters across both trees without allowances. Offscreen checks compare actual +box and tick geometry/pixels across form, grid, palette and menu call sites at +1×/2× in both themes. + +Disclosure chevrons point **down when open** (content visible) and **right when +closed** (content hidden). Only `ui_kit::disclosure` draws them, using the original +`chevron` / `chevron_right` SVGs at `form_section_icon_size`, without animation +(as in kit section headers). Sections, nested groups, Browser trees, card headers, +window folds and the Assistant strip all follow this rule. Keep existing scenario +handles, including `dialog:collapse`, and translated Collapse/Expand tooltips. +Dropdown arrows always point down; submenu arrows point right. Playback, reorder, +window management and overflow controls are not disclosures. The source guard scans +UI, apps and compiled asset glyphs without caller allowances; render tests inspect +the actual icon textures used by sections, card folds and window folds.