diff --git a/assets/locales/pending/sketch-state-icon.json b/assets/locales/pending/sketch-state-icon.json new file mode 100644 index 000000000..8a8a8bd9f --- /dev/null +++ b/assets/locales/pending/sketch-state-icon.json @@ -0,0 +1,60 @@ +{ + "en": { + "history.sketch_under_constrained": "Under constrained ({count} degrees of freedom)", + "history.sketch_under_constrained_one": "Under constrained ({count} degree of freedom)", + "prefs.sketch_state_icons": "Sketch icons in the color of their state", + "prefs.sketch_state_icons_note": "In History and the browser, a sketch's icon takes the color of its state (under constrained, fully constrained or conflicting) and its tooltip names the state. Off: every sketch has the same icon." + }, + "en-GB": { + "prefs.sketch_state_icons": "Sketch icons in the colour of their state", + "prefs.sketch_state_icons_note": "In History and the browser, a sketch's icon takes the colour of its state (under constrained, fully constrained or conflicting) and its tooltip names the state. Off: every sketch has the same icon." + }, + "de": { + "history.sketch_under_constrained": "Unterbestimmt ({count} Freiheitsgrade)", + "history.sketch_under_constrained_one": "Unterbestimmt ({count} Freiheitsgrad)", + "prefs.sketch_state_icons": "Skizzensymbole in der Farbe ihres Zustands", + "prefs.sketch_state_icons_note": "Im Verlauf und im Browser nimmt das Symbol einer Skizze die Farbe ihres Zustands an (unterbestimmt, vollständig bestimmt oder im Konflikt), und ihr Tooltip nennt den Zustand. Aus: Alle Skizzen haben dasselbe Symbol." + }, + "ja": { + "history.sketch_under_constrained": "拘束不足(自由度 {count})", + "history.sketch_under_constrained_one": "拘束不足(自由度 {count})", + "prefs.sketch_state_icons": "スケッチアイコンを状態の色で表示", + "prefs.sketch_state_icons_note": "履歴とブラウザーで、スケッチのアイコンがその状態(拘束不足、完全拘束、競合)の色になり、ツールチップに状態が表示されます。オフ: すべてのスケッチが同じアイコンになります。" + }, + "ko": { + "history.sketch_under_constrained": "구속 부족 (자유도 {count}개)", + "history.sketch_under_constrained_one": "구속 부족 (자유도 {count}개)", + "prefs.sketch_state_icons": "스케치 아이콘을 상태 색상으로 표시", + "prefs.sketch_state_icons_note": "이력과 브라우저에서 스케치 아이콘이 상태(구속 부족, 완전 구속, 충돌)의 색상을 띠고 도구 설명에 상태가 표시됩니다. 끄기: 모든 스케치가 같은 아이콘을 사용합니다." + }, + "nl": { + "history.sketch_under_constrained": "Onderbeperkt ({count} vrijheidsgraden)", + "history.sketch_under_constrained_one": "Onderbeperkt ({count} vrijheidsgraad)", + "prefs.sketch_state_icons": "Schetspictogrammen in de kleur van hun staat", + "prefs.sketch_state_icons_note": "In de geschiedenis en de browser krijgt het pictogram van een schets de kleur van zijn staat (onderbeperkt, volledig beperkt of conflicterend) en noemt de tooltip de staat. Uit: elke schets heeft hetzelfde pictogram." + }, + "zh": { + "history.sketch_under_constrained": "欠约束({count} 个自由度)", + "history.sketch_under_constrained_one": "欠约束({count} 个自由度)", + "prefs.sketch_state_icons": "以草图状态的颜色显示草图图标", + "prefs.sketch_state_icons_note": "在历史和浏览器中,草图图标采用其状态(欠约束、完全约束或冲突)的颜色,工具提示会说明状态。关闭:所有草图使用相同的图标。" + }, + "ar": { + "history.sketch_under_constrained": "قيود ناقصة ({count} درجات حرية)", + "history.sketch_under_constrained_one": "قيود ناقصة ({count} درجة حرية)", + "prefs.sketch_state_icons": "أيقونات الرسومات بلون حالتها", + "prefs.sketch_state_icons_note": "في السجل والمستعرض، تأخذ أيقونة الرسم لون حالته (قيود ناقصة، مقيّد بالكامل أو متعارض) ويذكر تلميحه الحالة. عند الإيقاف: لكل الرسومات الأيقونة نفسها." + }, + "he": { + "history.sketch_under_constrained": "אילוצים חסרים ({count} דרגות חופש)", + "history.sketch_under_constrained_one": "אילוצים חסרים (דרגת חופש {count})", + "prefs.sketch_state_icons": "סמלי סקיצות בצבע המצב שלהן", + "prefs.sketch_state_icons_note": "בהיסטוריה ובדפדפן, סמל הסקיצה מקבל את צבע המצב שלה (אילוצים חסרים, מאולצת במלואה או סותרת) וחלונית העזרה מציינת את המצב. כבוי: לכל הסקיצות אותו סמל." + }, + "vi": { + "history.sketch_under_constrained": "Thiếu ràng buộc ({count} bậc tự do)", + "history.sketch_under_constrained_one": "Thiếu ràng buộc ({count} bậc tự do)", + "prefs.sketch_state_icons": "Biểu tượng bản phác theo màu trạng thái", + "prefs.sketch_state_icons_note": "Trong Lịch sử và trình duyệt, biểu tượng của bản phác lấy màu trạng thái của nó (thiếu ràng buộc, ràng buộc đủ hoặc xung đột) và chú thích nêu trạng thái. Tắt: mọi bản phác có cùng biểu tượng." + } +} diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs index 395b7c7ee..0badd47f0 100644 --- a/crates/ui-egui/src/browser.rs +++ b/crates/ui-egui/src/browser.rs @@ -2012,6 +2012,8 @@ struct Entry { visible: bool, selected: bool, color: Option, + /// A sketch's solve state: its icon's colour and its tooltip (#7245). + sketch_state: Option, locked: bool, sel: Option, target: Option, @@ -2032,6 +2034,7 @@ impl Entry { visible: !app.session.visibility.hidden_bodies.contains(&world), selected: app.session.selection.iter().any(|s| matches!(s, Sel::Body { name } if name == &world)), color: None, + sketch_state: None, locked: app.session.visibility.locked_bodies.contains(&world), sel: Some(Sel::Body { name: world.clone() }), target: Some(Target::Body { name: world.clone() }), @@ -2042,6 +2045,7 @@ impl Entry { fn sketch(app: &SolveApp, f: &solidcraft_engine::doc::Feature) -> Self { let t = Tokens::get(); let active = app.session.active_sketch == Some(f.id); + let sketch_state = app.session.model.state().sketch(f.id).map(crate::sketch_state::SketchState::of); let lost = app.session.model.result(f.id).is_some_and(|result| result.error.is_some()) && matches!(app.session.doc.sketch_face_attachment(f.id, &app.session.model), solidcraft_engine::doc::FaceAttachmentStatus::Lost { .. }); Self { @@ -2060,6 +2064,7 @@ impl Entry { visible: sketch_visible(app, f.id), selected: active || app.session.selection.iter().any(|s| matches!(s, Sel::Feature { id } if *id == f.id)), color: if lost { Some(t.error) } else { active.then_some(t.sketch_accent) }, + sketch_state, locked: false, sel: Some(Sel::Feature { id: f.id }), target: Some(Target::Sketch { id: f.id }), @@ -2084,6 +2089,7 @@ impl Entry { visible: !app.session.visibility.hidden_origin.contains(&f.name), selected: app.session.selection.contains(&sel), color: None, + sketch_state: None, locked: false, sel: Some(sel), target: Some(Target::Plane { id: f.id }), @@ -2457,6 +2463,9 @@ fn entry_row( _ => e.locked, }; let badges: &[&str] = if locked { &["lock"] } else { &[] }; + // Cached with the evaluated model; the preference is read as the row is drawn. + let sketch_state = e.sketch_state.filter(|_| app.preferences.sketch_state_icons); + let state_tip = sketch_state.map(crate::sketch_state::SketchState::text); let r = draw_row( ui, ui.id().with(("item", &e.row_key)), @@ -2474,6 +2483,8 @@ fn entry_row( swatch: appearance.swatch, secondary: &appearance.name, count: &appearance.count, + icon_ink: sketch_state.and_then(|state| state.ink(&Tokens::get())), + tip: state_tip.as_deref(), badges, mark, ..Default::default() diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e6a6bd27c..5b984979f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -252,6 +252,7 @@ pub mod sketch_palette; mod sketch_pattern_tree; #[cfg(test)] mod sketch_side_ui_tests; +mod sketch_state; pub(crate) mod sketch_text; mod sketch_text_handles; mod sketch_text_move; diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 40ac55452..a212a5cbd 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1111,6 +1111,9 @@ preference_settings! { sketch_tracking_guides: bool = true, PAGE_SKETCH; /// Whether Alt/Option also frees gizmo / canvas manipulator arrows (Primary always does). manipulator_free_alt: bool = true, PAGE_SKETCH; + /// A sketch's icon in History and the browser takes the colour of its solve state, and its + /// tooltip names the state (#7245). Off: every sketch has the same icon, as before. + sketch_state_icons: bool = true, PAGE_SKETCH => check_id("prefs.sketch_state_icons"); /// A sketch tool's shortcut pressed again before the first point steps to the tool's next /// creation mode (#2459). Off (the default): the key starts the tool again, as it always has. shortcut_cycles_modes: bool = false, PAGE_SKETCH; @@ -4483,6 +4486,7 @@ mod tests { ("look_at_anim", json!(false), PAGE_NAVIGATION), ("selection_shift_add_only", json!(true), PAGE_SKETCH), ("suppress_sketch_snap", json!(ModifierCombo::NONE), PAGE_SKETCH), + ("sketch_state_icons", json!(false), PAGE_SKETCH), ("sketch_tracking_guides", json!(false), PAGE_SKETCH), ("msaa", json!(8), PAGE_GRAPHICS), ]; diff --git a/crates/ui-egui/src/prefs/sketch.rs b/crates/ui-egui/src/prefs/sketch.rs index 3c95f6ce9..d9fa0da15 100644 --- a/crates/ui-egui/src/prefs/sketch.rs +++ b/crates/ui-egui/src/prefs/sketch.rs @@ -15,6 +15,9 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { .on_hover_text(crate::i18n::tr_label( "Before the first point, pressing a sketch tool's shortcut again steps through its creation modes. Off: it starts the tool again.", )); + // Sketch icons in the colour of their solve state (#7245). + let check = setting::sketch_state_icons(app, ui).on_hover_text(app.tr("prefs.sketch_state_icons_note")); + crate::scenario::publish_target("prefs:sketch_state_icons", check.rect); let dimension = setting::sketch_auto_dimensions(app, ui); crate::scenario::publish_handle("prefs:sketch_auto_dimensions", dimension.rect.center()); ui.add_enabled_ui(app.preferences.sketch_auto_dimensions, |ui| { diff --git a/crates/ui-egui/src/sketch_state.rs b/crates/ui-egui/src/sketch_state.rs new file mode 100644 index 000000000..3a1649450 --- /dev/null +++ b/crates/ui-egui/src/sketch_state.rs @@ -0,0 +1,110 @@ +//! A sketch's solve state on its rows (#7245): the History strip, the left History and the +//! browser's Sketches folder draw the sketch icon in the colour the sketch's own curves take in +//! that state (under constrained: `sketch`; fully constrained: `sketch_fixed`; constraints +//! conflict: `error`), and the row's tooltip names the state. An empty sketch keeps its icon as +//! it is. +//! +//! The states come from the solves the model already holds ([`SolvedSketch::report`]): the +//! History reads them in one pass per frame, the browser when it re-indexes an evaluated model. +//! Drawing a row never solves anything. A sketch the model holds no solve for (rolled back behind +//! the history marker) keeps its icon too. The Sketch preference `sketch_state_icons` (on by +//! default) turns it all off: then every sketch row looks as before. +//! +//! [`SolvedSketch::report`]: solidcraft_engine::doc::SolvedSketch + +use std::collections::HashMap; + +use egui::Color32; + +use crate::SolveApp; +use crate::theme::Tokens; + +/// A sketch's state as its last solve reports it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum SketchState { + /// Nothing drawn in it yet. + Empty, + /// Degrees of freedom remain. + Under(usize), + Full, + /// The constraints conflict (the solve failed). + Conflict, +} + +impl SketchState { + pub(crate) fn of(ss: &solidcraft_engine::doc::SolvedSketch) -> SketchState { + if !ss.report.ok() { + SketchState::Conflict + } else if ss.sketch.curves.is_empty() && ss.sketch.wires.is_empty() { + SketchState::Empty + } else if ss.report.dof == 0 { + SketchState::Full + } else { + SketchState::Under(ss.report.dof) + } + } + + /// The icon's colour: the one the sketch's curves take in this state. The conflict colour is + /// the error red (the `sketch_conflict` token of #7244, once it lands, is the one to use). + /// None for an empty sketch: its icon is drawn as usual. + pub(crate) fn ink(self, t: &Tokens) -> Option { + match self { + SketchState::Empty => None, + SketchState::Under(_) => Some(t.sketch), + SketchState::Full => Some(t.sketch_fixed), + SketchState::Conflict => Some(t.error), + } + } + + /// The state in words, for the row's tooltip. + pub(crate) fn text(self) -> String { + match self { + SketchState::Empty => crate::i18n::tr("ui.no_geometry_yet").to_string(), + SketchState::Under(dof) => crate::i18n::format( + if dof == 1 { "history.sketch_under_constrained_one" } else { "history.sketch_under_constrained" }, + &[("count", &dof.to_string())], + ), + SketchState::Full => crate::i18n::tr("ui.fully_constrained").to_string(), + SketchState::Conflict => crate::i18n::tr("ui.constraints_conflict").to_string(), + } + } +} + +/// Every solved sketch's state, by its feature id: one pass over the model's solved sketches. +#[derive(Default)] +pub(crate) struct SketchStates(HashMap); + +impl SketchStates { + /// Nothing while the preference is off. + pub(crate) fn of(app: &SolveApp) -> SketchStates { + if !app.preferences.sketch_state_icons { + return SketchStates::default(); + } + let st = app.session.model.state(); + SketchStates(st.sketches.iter().map(|ss| (ss.feature, SketchState::of(ss))).collect()) + } + + pub(crate) fn get(&self, sketch: u64) -> Option { + self.0.get(&sketch).copied() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn states_ink_their_icons_in_the_sketch_colours_and_name_themselves() { + for t in [Tokens::light(), Tokens::dark()] { + assert_eq!(SketchState::Under(3).ink(&t), Some(t.sketch)); + assert_eq!(SketchState::Full.ink(&t), Some(t.sketch_fixed)); + assert_eq!(SketchState::Conflict.ink(&t), Some(t.error)); + assert_eq!(SketchState::Empty.ink(&t), None); + } + assert_eq!(SketchState::Under(1).text(), "Under constrained (1 degree of freedom)"); + assert_eq!(SketchState::Under(4).text(), "Under constrained (4 degrees of freedom)"); + assert_eq!(SketchState::Full.text(), "Fully constrained"); + assert_eq!(SketchState::Conflict.text(), "Constraints conflict"); + assert_eq!(SketchState::Empty.text(), "No geometry yet"); + } +} diff --git a/crates/ui-egui/src/timeline.rs b/crates/ui-egui/src/timeline.rs index 7eadd82ae..9d831649b 100644 --- a/crates/ui-egui/src/timeline.rs +++ b/crates/ui-egui/src/timeline.rs @@ -573,7 +573,10 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { let mut hovered: Option = None; let mut edit: Option = None; let mut marker_rect: Option = None; + // Each sketch's solve state, read once for the strip (#7245). + let sketch_states = crate::sketch_state::SketchStates::of(app); for (i, (id, name, icon, suppressed, ty, kind)) in feats.iter().enumerate() { + let sketch_state = matches!(kind, TimelineKind::Sketch).then(|| sketch_states.get(*id)).flatten(); if i == marker { marker_rect = Some(Rect::from_min_size(pos2(x, r.top() + 5.0), vec2(t.space_12, r.height() - 10.0))); x += t.space_16; @@ -605,6 +608,7 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { error: err.is_some(), warning: warn.is_some(), reference: false, + ink: sketch_state.and_then(|state| state.ink(&t)), // A dragged feature takes the colour of its drop bar. accent: if drag == Some(Drag::Feature(*id)) { crate::theme::TabAccent::for_tab(&t, "SKETCH") } else { accent }, } @@ -613,6 +617,10 @@ fn timeline_contents(app: &mut SolveApp, ui: &mut egui::Ui, floating: bool) { p.circle_filled(pos2(br.center().x, br.bottom() + t.space_3), t.space_2, accent.color); } let mut tip = status_text(name, ty, err.as_deref(), warn.as_deref()); + if let Some(state) = sketch_state { + tip.push('\n'); + tip.push_str(&state.text()); + } if let Some(r) = res { tip += &format!("\n{:.1} ms", r.ms); } diff --git a/crates/ui-egui/src/timeline_left.rs b/crates/ui-egui/src/timeline_left.rs index 85bff8c55..ceb11513b 100644 --- a/crates/ui-egui/src/timeline_left.rs +++ b/crates/ui-egui/src/timeline_left.rs @@ -1096,6 +1096,8 @@ struct Rows<'a> { drag: Option, hovered: Option, edit: Option, + /// Each sketch's solve state, read once for the column (#7245). + sketch_states: crate::sketch_state::SketchStates, } fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { @@ -1137,6 +1139,7 @@ fn vertical_features(app: &mut SolveApp, ui: &mut egui::Ui, names: bool) { let from_view = [crate::timeline::hovered_feature(app), crate::timeline::picked_feature(app)]; let drag_id = ui.id().with("tl_vertical_drag"); let mut rows = Rows { + sketch_states: crate::sketch_state::SketchStates::of(app), names, under_feature, features: &features, @@ -1327,6 +1330,7 @@ fn feature_row(app: &mut SolveApp, ui: &mut egui::Ui, rows: &mut Rows, index: us let listed = (row_kind == RowKind::Own).then(|| plan.row_at(index)).flatten().map(|row| row.listed.as_slice()).filter(|listed| !listed.is_empty()); let has_patterns = !reference && matches!(kind, TimelineKind::Sketch) && crate::sketch_pattern_tree::has_patterns(app, id); + let sketch_state = matches!(kind, TimelineKind::Sketch).then(|| rows.sketch_states.get(id)).flatten(); // One fold per row: a feature's listed sketches, or a sketch's patterns. let fold = match listed { Some(_) => Some((sketches_key(id), false)), @@ -1383,6 +1387,7 @@ fn feature_row(app: &mut SolveApp, ui: &mut egui::Ui, rows: &mut Rows, index: us error: error.is_some(), warning: warning.is_some(), reference, + ink: sketch_state.and_then(|state| state.ink(&t)), accent: crate::theme::TabAccent::for_tab(&t, if dragged { "SKETCH" } else { &app.ui.tab }), } .paint(ui.painter(), chip, style); @@ -1417,6 +1422,9 @@ fn feature_row(app: &mut SolveApp, ui: &mut egui::Ui, rows: &mut Rows, index: us if error.is_some() || warning.is_some() { tip.push_str(&format!("\n{}", crate::timeline::status_text(name, ty, error.as_deref(), warning.as_deref()))); } + if let Some(state) = sketch_state { + tip.push_str(&format!("\n{}", state.text())); + } crate::ui_kit::text(ui, &tip, crate::ui_kit::Text::Value("history", false)); // A value row is one line: where the sketch is listed gets a row of its own. if let Some(host) = listed_under.filter(|_| reference) { diff --git a/crates/ui-egui/src/timeline_marks_tests.rs b/crates/ui-egui/src/timeline_marks_tests.rs index 163ee50a3..add485368 100644 --- a/crates/ui-egui/src/timeline_marks_tests.rs +++ b/crates/ui-egui/src/timeline_marks_tests.rs @@ -77,3 +77,177 @@ fn a_failed_feature_is_marked_in_the_feature_history() { let got = marked(&mut app, crate::timeline_left::left_timeline, |item, d| (d.y - item.y).abs() < 1.5 && d.x > item.x); assert_eq!(got, want, "an error mark on each failed feature and on no other"); } + +/// Three sketches, one in each state (#7245): Guide is under constrained, Fixed is fully +/// constrained, and Reach's constraints conflict once `w` moves Guide's line out of its 12 mm +/// line's reach. +fn sketch_states_design() -> crate::scenario::Harness { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + let app = &mut h.app; + app.run("parameters.add", json!({"name": "w", "expression": "10 mm"})).unwrap(); + app.run("sketch.create", json!({"plane": "XY", "name": "Guide"})).unwrap(); + app.run("sketch.line", json!({"points": [[10, -30], [10, 30]], "ids": ["guide"], "connect": false})).unwrap(); + app.run("sketch.constraint.horizontal_vertical", json!({"line": "guide", "mode": "vertical"})).unwrap(); + app.run("sketch.dimension", json!({"entities": ["origin", "guide.start"], "type": "horizontal", "value": "w"})).unwrap(); + app.run("sketch.finish", json!({})).unwrap(); + app.run("sketch.create", json!({"plane": "XY", "name": "Reach"})).unwrap(); + let projected = app.run("sketch.project", json!({"refs": [{"sketch": "Guide", "curve": "guide"}]})).unwrap()["links"][0]["curves"][0] + .as_str() + .unwrap() + .to_string(); + let line = app.run("sketch.line", json!({"points": [[0, 0], [10, -(44.0_f64).sqrt()]]})).unwrap()["curves"][0].as_str().unwrap().to_string(); + app.run("sketch.dimension", json!({"entities": [line], "value": 12})).unwrap(); + app.run("sketch.constraint.coincident", json!({"a": format!("{line}.end"), "b": projected})).unwrap(); + app.run("sketch.finish", json!({})).unwrap(); + app.run("sketch.create", json!({"plane": "XY", "name": "Fixed"})).unwrap(); + let rectangle = app.run("sketch.rectangle.two_point", json!({"p0": [30, 0], "p1": [50, 20]})).unwrap(); + app.run("sketch.constraint.fix", json!({"entities": rectangle["curves"]})).unwrap(); + app.run("sketch.finish", json!({})).unwrap(); + app.run("parameters.change", json!({"name": "w", "expression": "20 mm"})).unwrap(); + h.settle(); + h +} + +/// One frame of the app on a fresh context, so that every icon's texture is uploaded again: the +/// frame's shapes, and each uploaded texture's opaque colours. +fn fresh_frame(h: &mut crate::scenario::Harness) -> (Vec, std::collections::HashMap>) { + h.ctx = crate::fonts::test_context(); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1000.0)); + let mut textures = std::collections::HashMap::new(); + let mut shapes = Vec::new(); + for _ in 0..2 { + let app = &mut h.app; + let out = h.ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }); + for (id, delta) in out.textures_delta.set.iter().flat_map(|(id, deltas)| deltas.iter().map(move |d| (id, d))) { + let egui::ImageData::Color(image) = &delta.image; + let mut colours: Vec<[u8; 4]> = image.pixels.iter().filter(|p| p.a() == 255).map(|p| p.to_array()).collect(); + colours.sort_unstable(); + colours.dedup(); + textures.insert(*id, colours); + } + shapes = out.shapes; + } + (shapes, textures) +} + +/// The opaque colours of the icon image drawn on the row at `at` (its centre's height), `size` +/// points square, nearest `at` (a History chip's own icon; a browser row's eye is 15 points). +fn icon_colours( + shapes: &[egui::epaint::ClippedShape], + textures: &std::collections::HashMap>, + at: Pos2, + size: std::ops::RangeInclusive, +) -> Vec<[u8; 4]> { + let mut best: Option<(f32, egui::TextureId)> = None; + for clipped in shapes { + each(&clipped.shape, &mut |s| { + if let Shape::Mesh(m) = s { + let b = m.calc_bounds(); + let distance = (b.center().x - at.x).abs(); + if (b.center().y - at.y).abs() < 1.5 && size.contains(&b.width()) && best.is_none_or(|(d, _)| distance < d) { + best = Some((distance, m.texture_id)); + } + } + }); + } + let (_, id) = best.unwrap_or_else(|| panic!("no icon image on the row at {at:?}")); + textures.get(&id).cloned().unwrap_or_else(|| panic!("the icon's texture {id:?} was not uploaded")) +} + +#[test] +fn a_sketchs_icon_takes_its_states_colour_in_both_histories_and_the_browser() { + let mut h = sketch_states_design(); + let st = h.app.session.model.state(); + let report = |name: &str| st.sketches.iter().find(|s| s.name == name).map(|s| s.report.clone()).unwrap(); + assert!(report("Guide").ok() && report("Guide").dof > 0); + assert!(report("Fixed").ok() && report("Fixed").dof == 0); + assert!(!report("Reach").ok(), "{:?}", report("Reach")); + let states = crate::sketch_state::SketchStates::of(&h.app); + let t = crate::theme::Tokens::get(); + let want = [("Guide", t.sketch), ("Fixed", t.sketch_fixed), ("Reach", t.error)]; + for (name, colour) in want { + let id = h.app.session.doc.find_feature(name).unwrap().id; + assert_eq!(states.get(id).and_then(|s| s.ink(&t)), Some(colour), "{name}"); + } + // Bottom History (20-point icons in 28-point chips) and the browser's Sketches folder + // (16-point icons beside 15-point eyes). + h.app.tree.expanded.insert("c0/sketches".into()); + let (shapes, textures) = fresh_frame(&mut h); + for (name, colour) in want { + let chip = crate::scenario::handle_at(&format!("timeline:{name}")).unwrap(); + assert_eq!(icon_colours(&shapes, &textures, chip, 19.0..=21.0), vec![colour.to_array()], "{name}: History strip"); + let row = crate::scenario::handle_at(&format!("row:{name}")).unwrap(); + assert_eq!(icon_colours(&shapes, &textures, row, 15.5..=16.5), vec![colour.to_array()], "{name}: browser"); + } + let extrude_free = icon_colours(&shapes, &textures, crate::scenario::handle_at("row:Origin").unwrap(), 15.5..=16.5); + assert!(extrude_free.len() > 1, "other rows keep their artwork"); + // The left History, in either width. + h.app.preferences.timeline_left = true; + for names in [false, true] { + h.app.preferences.timeline_left_width = if names { 260.0 } else { 56.0 }; + let (shapes, textures) = fresh_frame(&mut h); + for (name, colour) in want { + let chip = crate::scenario::handle_at(&format!("timeline:{name}")).unwrap(); + assert_eq!(icon_colours(&shapes, &textures, chip, 14.0..=20.0), vec![colour.to_array()], "{name}: left History, names {names}"); + } + } + // Preference off: every sketch's icon is its artwork again, as before. + h.app.preferences.sketch_state_icons = false; + h.app.preferences.timeline_left = false; + assert!(crate::sketch_state::SketchStates::of(&h.app).get(h.app.session.doc.find_feature("Guide").unwrap().id).is_none()); + let (shapes, textures) = fresh_frame(&mut h); + let (mut chips, mut rows) = (Vec::new(), Vec::new()); + for (name, _) in want { + let chip = crate::scenario::handle_at(&format!("timeline:{name}")).unwrap(); + let row = crate::scenario::handle_at(&format!("row:{name}")).unwrap(); + chips.push(icon_colours(&shapes, &textures, chip, 19.0..=21.0)); + rows.push(icon_colours(&shapes, &textures, row, 15.5..=16.5)); + } + for icons in [chips, rows] { + assert!(icons.iter().all(|colours| colours.len() > 1), "the sketch artwork, not one ink: {icons:?}"); + assert!(icons.windows(2).all(|w| w[0] == w[1]), "every sketch's icon alike"); + } +} + +/// Every text one frame paints. +fn painted_texts(h: &mut crate::scenario::Harness) -> Vec { + h.frame(); + let mut texts = Vec::new(); + for clipped in &h.shapes { + each(&clipped.shape, &mut |s| { + if let Shape::Text(t) = s { + texts.push(t.galley.text().to_string()); + } + }); + } + texts +} + +#[test] +fn a_sketch_rows_tooltip_names_its_state() { + let mut h = sketch_states_design(); + h.app.tree.expanded.insert("c0/sketches".into()); + h.settle(); + for (handle, want) in [("timeline:Reach", "Constraints conflict"), ("row:Fixed", "Fully constrained")] { + h.step(&json!({"move": {"handle": handle}})).unwrap(); + h.frames(60); + let texts = painted_texts(&mut h); + assert!(texts.iter().any(|t| t.contains(want)), "{handle}: no `{want}` in {texts:?}"); + } + h.step(&json!({"move": {"handle": "timeline:Guide"}})).unwrap(); + h.frames(60); + let texts = painted_texts(&mut h); + assert!(texts.iter().any(|t| t.contains("Under constrained (") && t.contains("degrees of freedom)")), "{texts:?}"); + // Preference off: the tooltips are as before. + h.app.preferences.sketch_state_icons = false; + for (handle, gone) in [("timeline:Reach", "Constraints conflict"), ("row:Fixed", "Fully constrained")] { + h.step(&json!({"move": {"handle": handle}})).unwrap(); + h.frames(60); + let texts = painted_texts(&mut h); + assert!(!texts.iter().any(|t| t.contains(gone)), "{handle}: `{gone}` in {texts:?}"); + } +} diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs index fead21e91..c3fde5aa6 100644 --- a/crates/ui-egui/src/ui_kit/gallery.rs +++ b/crates/ui-egui/src/ui_kit/gallery.rs @@ -2042,6 +2042,7 @@ fn confirm_radial_and_history_rows_keep_multitone_artwork() { warning: false, reference: false, accent: crate::theme::TabAccent::for_tab(&Tokens::get(), "MODEL"), + ink: None, } .paint( ui.painter(), diff --git a/crates/ui-egui/src/ui_kit/history.rs b/crates/ui-egui/src/ui_kit/history.rs index 56d048d8a..2b86582af 100644 --- a/crates/ui-egui/src/ui_kit/history.rs +++ b/crates/ui-egui/src/ui_kit/history.rs @@ -68,6 +68,8 @@ pub(crate) struct HistoryChip<'a> { /// its name is in secondary text. pub reference: bool, pub accent: TabAccent, + /// Draw the icon in this one colour instead of its artwork: a sketch's solve state (#7245). + pub ink: Option, } /// Share the feature classification across chips and name rows. Surface aliases also @@ -136,7 +138,10 @@ impl HistoryChip<'_> { }; let icon = Rect::from_center_size(if names { pos2(rect.left() + t.space_8 + side / 2.0, rect.center().y) } else { rect.center() }, vec2(side, side)); - icons::paint_accented(&p, icon, self.icon, feature_icon_accent(self.kind, self.icon), 1.0); + match self.ink { + Some(ink) => icons::paint_ink(&p, icon, self.icon, ink), + None => icons::paint_accented(&p, icon, self.icon, feature_icon_accent(self.kind, self.icon), 1.0), + } if names { let ink = if self.selected { self.accent.ink @@ -573,6 +578,7 @@ mod tests { warning: false, reference: false, accent, + ink: None, } .paint(ui.painter(), rect, style) }); @@ -634,6 +640,7 @@ mod tests { warning: false, reference: false, accent: TabAccent::for_tab(&t, "MODEL"), + ink: None, } .paint(ui.painter(), rect, style); } diff --git a/crates/ui-egui/src/ui_kit/tree.rs b/crates/ui-egui/src/ui_kit/tree.rs index 916a51259..fb1279865 100644 --- a/crates/ui-egui/src/ui_kit/tree.rs +++ b/crates/ui-egui/src/ui_kit/tree.rs @@ -32,6 +32,10 @@ pub(crate) struct Row<'a> { pub(crate) selected: bool, pub(crate) dim: bool, pub(crate) color: Option, + /// Draw the icon in this one colour instead of its artwork (a sketch's solve state, #7245). + pub(crate) icon_ink: Option, + /// The row's tooltip (a sketch's solve state), after its full name when that is cut short. + pub(crate) tip: Option<&'a str>, /// Component rows: is it the active one? pub(crate) radio: Option, /// Trailing badges: "lock", "pin". @@ -213,7 +217,11 @@ pub(crate) fn tree_row(ui: &mut egui::Ui, id: egui::Id, row: &Row) -> RowResp { let ir = Rect::from_min_size(pos2(x, cy - 8.0), vec2(t.space_16, t.space_16)); // Icons are full-colour images (a tint colour only sets their opacity): a hidden or // faded row draws its icon faint, like its label. - icons::paint_icon(ui.painter(), ir, row.icon, if row.dim { DIM_ICON_OPACITY } else { 1.0 }); + let opacity = if row.dim { DIM_ICON_OPACITY } else { 1.0 }; + match row.icon_ink { + Some(ink) => icons::paint_ink(ui.painter(), ir, row.icon, ink.gamma_multiply(opacity)), + None => icons::paint_icon(ui.painter(), ir, row.icon, opacity), + } x += 21.0; } if let Some(color) = row.swatch { @@ -298,13 +306,15 @@ pub(crate) fn tree_row(ui: &mut egui::Ui, id: egui::Id, row: &Row) -> RowResp { 3 => Some(if row.radio == Some(true) { crate::i18n::tr("ui.active_component") } else { crate::i18n::tr("ui.activate") }), _ => None, }; - let resp = match tip { - Some(t) => resp.on_hover_text(t), - None if !row.secondary.is_empty() || !row.count.is_empty() => { + let resp = match (tip, row.tip) { + (Some(t), _) => resp.on_hover_text(t), + (None, Some(state)) if elided => resp.on_hover_text(format!("{label_display}\n{state}")), + (None, Some(state)) => resp.on_hover_text(state), + (None, None) if !row.secondary.is_empty() || !row.count.is_empty() => { resp.on_hover_text(format!("{label_display}\n{}\n{}", row.secondary, row.count)) } - None if elided => resp.on_hover_text(label_display.to_string()), - None => resp, + (None, None) if elided => resp.on_hover_text(label_display.to_string()), + (None, None) => resp, }; out.on_control = press_on != 0 || over_action(ui.input(|i| i.pointer.press_origin())); out.clicked = resp.clicked() && click_on == 0 && !action_click; diff --git a/docs/book/src/guide/ui-tour.md b/docs/book/src/guide/ui-tour.md index c182ca876..afad748fd 100644 --- a/docs/book/src/guide/ui-tour.md +++ b/docs/book/src/guide/ui-tour.md @@ -103,7 +103,11 @@ the dialog's title row, right of the title, where they stay while sections open and close; Cancel then also takes the place of the close button. Enter and Esc work as before. - **Timeline** (bottom). Every feature in order. Double-click to edit, drag the marker to roll - back, and drag features to reorder them. Preferences can put the timeline vertically at the + back, and drag features to reorder them. A sketch's icon, here and in the browser, takes the + colour of its state: the sketch colour while it is under constrained, the fully constrained + colour, or red while its constraints conflict; its tooltip names the state (Preferences › + Sketch › **Sketch icons in the colour of their state**, on by default, turns this off). + Preferences can put the timeline vertically at the far left of the viewport, beside the browser. Its seam handle switches between icon chips and compact feature names; the browser can collapse to a rail beside either width. Docked under the browser, the two share the column: drag the seam between them to give either diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d597ad809..031b1856a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -355,6 +355,7 @@ One setting per line, sorted by name. A change that adds a setting adds its own - `sketch_auto_dimensions` (default false: each shape drawn in a sketch gets all its dimensions at the sizes drawn, as `sketch.draw.dimensioned` with `as_drawn`; typed values win) - `sketch_auto_locate` (default false; with `sketch_auto_dimensions`, new shapes are also placed from the sketch origin until fully constrained, as `sketch.draw.dimensioned` with `locate`) - `sketch_exit_view` (`keep` (default: the view stays where it is when a sketch ends), `previous` (back to the view from before the sketch), `unless_rotated` (back unless the sketch view was turned)) +- `sketch_state_icons` (default true: a sketch's icon in History and the browser takes the colour of its solve state, `sketch` under constrained, `sketch_fixed` fully constrained, `error` while its constraints conflict, and its tooltip names the state; false: every sketch row's icon and tooltip as before, #7245) - `sketch_tab_always` (default false: the SKETCH tab stays in the ribbon right after MODEL while no sketch is open; a tool in its CREATE or REFERENCE section then opens Create Sketch, on the selected plane or planar face or else on the plane picked next, and starts in the new sketch, #7904) - `smooth_wheel_zoom` (default true) - `stand_up_unknown` (`note` (default: a file whose header names no program known to save Y up and whose bodies seem to lie on their back (their flat area across Y outweighs their flat area facing down Z) gets a small note over the view, "Did this part open the wrong way up?", with Stand it up, Don't ask again and Close as the handles `stand_up:stand`, `stand_up:never` and `stand_up:dismiss`; it goes by itself after 10 seconds and never blocks input), `ask` (the "Stand this part up?" dialog for every file from another program, SolidWorks too, without looking at how it rests, as before #7717), `off` (no offer); otherwise a SolidWorks file gets the dialog, or the note when its bodies clearly stand on Z already)