diff --git a/assets/locales/pending/preferences-appearance.json b/assets/locales/pending/preferences-appearance.json new file mode 100644 index 000000000..f39d6bb88 --- /dev/null +++ b/assets/locales/pending/preferences-appearance.json @@ -0,0 +1,118 @@ +{ + "ar": { + "prefs.appearance.colour_vision_help": "يغيّر الألوان ذات الدلالة: حالات الرسم والمحاور والثنيات والتحليلات والأيقونات.", + "prefs.appearance.desktop_only": "لسطح المكتب فقط", + "prefs.appearance.follow_help": "يعيد التحميل عندما تعيد أداة أخرى كتابة الملف.", + "prefs.appearance.interface_scale": "مقياس الواجهة", + "prefs.appearance.next_themes": "السمات التالية", + "prefs.appearance.option_count": "{count} خيارات", + "prefs.appearance.option_count_one": "{count} خيار", + "prefs.appearance.previous_themes": "السمات السابقة", + "prefs.appearance.theme_count": "{count} سمات", + "prefs.appearance.theme_own": "ألوان السمة", + "prefs.appearance.viewport_colours": "ألوان العرض ثلاثي الأبعاد", + "prefs.appearance.viewport_logo": "منفذ العرض والشعار" + }, + "de": { + "prefs.appearance.colour_vision_help": "Ändert die bedeutungstragenden Farben: Skizzenzustände, Achsen, Biegungen, Analysen und Symbole.", + "prefs.appearance.desktop_only": "Nur Desktop", + "prefs.appearance.follow_help": "Wird neu geladen, wenn ein anderes Werkzeug die Datei überschreibt.", + "prefs.appearance.interface_scale": "Oberflächenskalierung", + "prefs.appearance.next_themes": "Nächste Designs", + "prefs.appearance.option_count": "{count} Optionen", + "prefs.appearance.option_count_one": "{count} Option", + "prefs.appearance.previous_themes": "Vorherige Designs", + "prefs.appearance.theme_count": "{count} Designs", + "prefs.appearance.theme_own": "Eigene Designfarben", + "prefs.appearance.viewport_colours": "Farben der 3D-Ansicht", + "prefs.appearance.viewport_logo": "Ansichtsfenster und Logo" + }, + "en": { + "prefs.appearance.colour_vision_help": "Changes the colors that carry a meaning: sketch states, axes, bends, analyses and icons.", + "prefs.appearance.desktop_only": "Desktop only", + "prefs.appearance.follow_help": "Reloads when another tool rewrites the file.", + "prefs.appearance.interface_scale": "Interface scale", + "prefs.appearance.next_themes": "Next themes", + "prefs.appearance.option_count": "{count} options", + "prefs.appearance.option_count_one": "{count} option", + "prefs.appearance.previous_themes": "Previous themes", + "prefs.appearance.theme_count": "{count} themes", + "prefs.appearance.theme_own": "Theme's own", + "prefs.appearance.viewport_colours": "3D view colors", + "prefs.appearance.viewport_logo": "Viewport and logo" + }, + "en-GB": { + "prefs.appearance.colour_vision_help": "Changes the colours that carry a meaning: sketch states, axes, bends, analyses and icons.", + "prefs.appearance.viewport_colours": "3D view colours" + }, + "he": { + "prefs.appearance.colour_vision_help": "משנה צבעים בעלי משמעות: מצבי סקיצה, צירים, כיפופים, ניתוחים וסמלים.", + "prefs.appearance.desktop_only": "למחשב בלבד", + "prefs.appearance.follow_help": "טוען מחדש כאשר כלי אחר משכתב את הקובץ.", + "prefs.appearance.interface_scale": "קנה מידה של הממשק", + "prefs.appearance.next_themes": "ערכות העיצוב הבאות", + "prefs.appearance.option_count": "{count} אפשרויות", + "prefs.appearance.option_count_one": "{count} אפשרות", + "prefs.appearance.previous_themes": "ערכות העיצוב הקודמות", + "prefs.appearance.theme_count": "{count} ערכות עיצוב", + "prefs.appearance.theme_own": "צבעי ערכת העיצוב", + "prefs.appearance.viewport_colours": "צבעי תצוגת תלת־ממד", + "prefs.appearance.viewport_logo": "חלון התצוגה והלוגו" + }, + "ja": { + "prefs.appearance.colour_vision_help": "意味を持つ色を変更します:スケッチ状態、軸、曲げ、解析、アイコン。", + "prefs.appearance.desktop_only": "デスクトップのみ", + "prefs.appearance.follow_help": "別のツールがファイルを書き換えると再読み込みします。", + "prefs.appearance.interface_scale": "インターフェースの倍率", + "prefs.appearance.next_themes": "次のテーマ", + "prefs.appearance.option_count": "{count} 個のオプション", + "prefs.appearance.option_count_one": "{count} 個のオプション", + "prefs.appearance.previous_themes": "前のテーマ", + "prefs.appearance.theme_count": "{count} 個のテーマ", + "prefs.appearance.theme_own": "テーマ独自", + "prefs.appearance.viewport_colours": "3D ビューの色", + "prefs.appearance.viewport_logo": "ビューポートとロゴ" + }, + "ko": { + "prefs.appearance.colour_vision_help": "의미를 전달하는 색상을 변경합니다: 스케치 상태, 축, 굽힘, 분석 및 아이콘.", + "prefs.appearance.desktop_only": "데스크톱 전용", + "prefs.appearance.follow_help": "다른 도구가 파일을 다시 쓰면 다시 불러옵니다.", + "prefs.appearance.interface_scale": "인터페이스 배율", + "prefs.appearance.next_themes": "다음 테마", + "prefs.appearance.option_count": "옵션 {count}개", + "prefs.appearance.option_count_one": "옵션 {count}개", + "prefs.appearance.previous_themes": "이전 테마", + "prefs.appearance.theme_count": "테마 {count}개", + "prefs.appearance.theme_own": "테마 자체", + "prefs.appearance.viewport_colours": "3D 보기 색상", + "prefs.appearance.viewport_logo": "뷰포트 및 로고" + }, + "vi": { + "prefs.appearance.colour_vision_help": "Thay đổi các màu mang ý nghĩa: trạng thái phác thảo, trục, đường uốn, phân tích và biểu tượng.", + "prefs.appearance.desktop_only": "Chỉ máy tính", + "prefs.appearance.follow_help": "Tải lại khi công cụ khác ghi lại tệp.", + "prefs.appearance.interface_scale": "Tỷ lệ giao diện", + "prefs.appearance.next_themes": "Giao diện tiếp theo", + "prefs.appearance.option_count": "{count} tùy chọn", + "prefs.appearance.option_count_one": "{count} tùy chọn", + "prefs.appearance.previous_themes": "Giao diện trước", + "prefs.appearance.theme_count": "{count} giao diện", + "prefs.appearance.theme_own": "Theo giao diện", + "prefs.appearance.viewport_colours": "Màu khung nhìn 3D", + "prefs.appearance.viewport_logo": "Khung nhìn và logo" + }, + "zh": { + "prefs.appearance.colour_vision_help": "更改具有含义的颜色:草图状态、坐标轴、折弯、分析和图标。", + "prefs.appearance.desktop_only": "仅限桌面", + "prefs.appearance.follow_help": "其他工具重写文件时重新加载。", + "prefs.appearance.interface_scale": "界面缩放", + "prefs.appearance.next_themes": "下一个主题", + "prefs.appearance.option_count": "{count} 个选项", + "prefs.appearance.option_count_one": "{count} 个选项", + "prefs.appearance.previous_themes": "上一个主题", + "prefs.appearance.theme_count": "{count} 个主题", + "prefs.appearance.theme_own": "主题自身", + "prefs.appearance.viewport_colours": "3D 视图颜色", + "prefs.appearance.viewport_logo": "视口和徽标" + } +} diff --git a/crates/ui-egui/src/colour_vision_tests.rs b/crates/ui-egui/src/colour_vision_tests.rs index 49af46750..0ffe15b27 100644 --- a/crates/ui-egui/src/colour_vision_tests.rs +++ b/crates/ui-egui/src/colour_vision_tests.rs @@ -1147,33 +1147,86 @@ fn ui_prefs_sets_each_mode_and_refuses_anything_else() { /// colours. The status chips beside it keep theirs in every mode. #[test] fn the_sample_previews_the_mode_being_chosen() { - let mut h = crate::scenario::Harness::new(); - crate::prefs::control(&mut h.app, &json!({"open": "Interface"})).unwrap(); - let lines = |h: &crate::scenario::Harness| { - let mut out = BTreeSet::new(); - for s in &h.shapes { - crate::test_support::each_shape(&s.shape, &mut |shape| { - if let egui::Shape::LineSegment { stroke, .. } = shape { - out.insert(stroke.color.to_array()); - } - }); - } - out - }; - for mode in [ColorVision::Protan, ColorVision::Tritan, ColorVision::Off] { - crate::prefs::control(&mut h.app, &json!({"color_vision": mode.id()})).unwrap(); - h.frames(2); - let (want, off) = (Tokens::get_in(mode), Tokens::get_in(ColorVision::Off)); - let painted = lines(&h); - for (name, c) in [("axis_x", want.axis_x), ("axis_y", want.axis_y), ("sketch_locked", want.sketch_locked)] { - assert!(painted.contains(&c.to_array()), "{mode:?}: the sample draws {name} {c:?}"); - } - if mode != ColorVision::Off { - let changed = [(want.axis_x, off.axis_x), (want.sketch_locked, off.sketch_locked)]; - assert!(changed.iter().any(|(a, b)| a != b), "{mode:?} recolours what the sample shows"); + for base in ["light", "dark"] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + crate::prefs::control(&mut h.app, &json!({"theme":base,"language":"en","open":"Interface"})).unwrap(); + h.frames(3); + for mode in ColorVision::ALL { + let handle = format!("prefs:color_vision:{}", mode.id()); + crate::prefs::reveal_preference(&mut h, &handle); + h.step(&json!({"click":{"handle":handle}})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.color_vision, mode, "the real Appearance segments edit the preference"); + crate::prefs::reveal_preference(&mut h, "prefs:colour_vision_samples"); + let (want, off) = (Tokens::get_in(mode), Tokens::get_in(ColorVision::Off)); + if mode != ColorVision::Off { + assert!( + want.axis_x != off.axis_x || want.sketch_locked != off.sketch_locked, + "{base} {mode:?}: axis X or locked sketch geometry must differ from Off" + ); + } + // The shared painter clips each figure to its fitted cell. Isolate those actual + // page shapes by that clip, preserving their order and geometry. Cropping the whole + // page still tessellates unrelated atlas content, which requires its real textures. + // Rounded vector shapes also use atlas-backed discs, so retain the rendered page's atlas. + let textures = std::collections::HashMap::from([(egui::TextureId::default(), h.ctx.fonts(|fonts| fonts.image()))]); + let images: Vec<_> = (0..6) + .map(|i| { + let cell = crate::scenario::rect_of(&format!("prefs:colour_vision_sample:{i}")).unwrap(); + let artwork: Vec<_> = h + .shapes + .iter() + .filter(|shape| shape.clip_rect.min.distance(cell.min) < 0.01 && shape.clip_rect.max.distance(cell.max) < 0.01) + .cloned() + .collect(); + assert!(!artwork.is_empty(), "{base} {mode:?}: sample {i} has actual cell-clipped artwork"); + crate::ui_kit::raster_test_shapes(&h.ctx, artwork, 1.0, cell, &textures) + }) + .collect(); + let near = |actual: [u8; 4], expected: egui::Color32| actual.into_iter().zip(expected.to_array()).all(|(a, b)| a.abs_diff(b) <= 2); + let pixel = |i: usize, x, y, colour| { + assert!( + near(images[i].get_pixel(x, y).0, colour), + "{base} {mode:?}: sample {i} pixel {x},{y} must be {colour:?}, got {:?}", + images[i].get_pixel(x, y) + ); + }; + pixel(0, 42, 22, want.sketch_locked); + pixel(1, 42, 22, want.sketch_projected); + pixel(2, 40, 34, want.axis_x); + pixel(2, 14, 20, want.axis_y); + // The canonical bends are dashed. Require visible runs in each semantic colour. + for (colour, y) in [(want.bend_up, 14), (want.bend_down, 30)] { + assert!((12..72).any(|x| near(images[3].get_pixel(x, y).0, colour)), "{base} {mode:?}: bend stroke {colour:?}"); + } + pixel(4, 18, 18, crate::theme::srgb(want.analysis.draft[0])); + pixel(4, 40, 18, crate::theme::srgb(want.analysis.draft[1])); + pixel(4, 2, 2, want.figure_ground); + let negative = crate::theme::srgb(want.analysis.draft[2]); + let hatch = crate::theme::srgb(want.analysis.draft[2].map(|c| c * 0.6)); + let draft = &images[4]; + let band: Vec<_> = (54..74).flat_map(|x| (24..34).map(move |y| draft.get_pixel(x, y).0)).collect(); + assert!(band.iter().any(|p| near(*p, negative)), "{base} {mode:?}: Draft retains its negative analysis colour"); + assert!(band.iter().any(|p| near(*p, hatch)), "{base} {mode:?}: Draft hatching is visible, including Off"); + // Both diagonals must be visible inside the error box; a blank rounded box fails. + for (x, y) in [(38, 19), (46, 18), (38, 25), (46, 25)] { + pixel(5, x, y, want.error); + } + pixel(5, 24, 22, want.timeline_item_error); + let area = crate::scenario::rect_of("prefs:colour_vision_samples").unwrap(); + let page = crate::scenario::rect_of("prefs:page_body").unwrap(); + assert!(page.expand(1.0).contains_rect(area)); + for i in 0..6 { + let cell = crate::scenario::rect_of(&format!("prefs:colour_vision_sample:{i}")).unwrap(); + assert!(area.contains_rect(cell)); + assert_eq!(cell.size(), egui::vec2(84.0, 44.0)); + } + assert_eq!(crate::scenario::rects("prefs:status_sample:").len(), 4); } + crate::prefs::control(&mut h.app, &json!({"button":"cancel"})).unwrap(); + assert_eq!(h.app.preferences.color_vision, ColorVision::Off); } - crate::prefs::control(&mut h.app, &json!({"button": "cancel"})).unwrap(); } #[test] diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rs index 7b958aa01..258860c97 100644 --- a/crates/ui-egui/src/prefs.rs +++ b/crates/ui-egui/src/prefs.rs @@ -1901,68 +1901,94 @@ fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) { let mut chosen: Option = None; let mut action: Option<&str> = None; let mut import_tile = None; - ui_kit::theme_rail( - ui, - |ui| { - for (id, label) in &choices { - let palette = match id.as_str() { - "light" | "system" => Tokens::light(), - "dark" => Tokens::dark(), - _ => crate::theme_files::find(id, &app.preferences.custom_themes) - .map(|f| resolved_theme(&app.preferences, f)) - .unwrap_or_else(Tokens::dark), - }; - let custom = app.preferences.custom_themes.iter().any(|t| t.id == *id); - let note = app.tr(if id == "system" { - "prefs.follows_os" - } else if custom { - "prefs.imported_file" - } else { - "prefs.built_in" - }); - let response = ui_kit::option_card( - ui, + let t = Tokens::get(); + let width = t.space_24 * 3.0 + t.space_16; + let height = t.space_24 * 4.0; + let dark_sample = ui_kit::ThemeSample::from_tokens(&Tokens::dark()); + let carousel_id = "appearance_themes"; + // Reveal the active theme after a programmatic selection or import too. + let selection_key = ui.make_persistent_id((carousel_id, "selection")); + let carousel_key = ui.make_persistent_id(carousel_id); + ui.data_mut(|data| { + if data.get_temp::(selection_key).as_deref() != Some(app.preferences.theme.as_str()) { + let index = choices.iter().position(|(id, _)| id == &app.preferences.theme).unwrap_or(0); + data.insert_temp(carousel_key, index.saturating_sub(1)); + data.insert_temp(selection_key, app.preferences.theme.clone()); + } + }); + let mut item = |ui: &mut egui::Ui, index: usize| { + if let Some((id, label)) = choices.get(index) { + let palette = match id.as_str() { + "light" | "system" => Tokens::light(), + "dark" => Tokens::dark(), + _ => crate::theme_files::find(id, &app.preferences.custom_themes) + .map(|f| resolved_theme(&app.preferences, f)) + .unwrap_or_else(Tokens::dark), + }; + let custom = app.preferences.custom_themes.iter().any(|t| t.id == *id); + let note = app.tr(if id == "system" { + "prefs.follows_os" + } else if custom { + "prefs.imported_file" + } else { + "prefs.built_in" + }); + let options = crate::theme_files::find(id, &app.preferences.custom_themes) + .is_some_and(|file| !crate::theme_options::offered(file, crate::theme_options::PROVIDERS).is_empty()); + if crate::prefs_search::querying(ui) && !crate::prefs_search::visible(ui, &[label, note]) { + return; + } + let sample = ui_kit::ThemeSample::from_tokens(&palette); + let response = ui_kit::picture_card( + ui, + &ui_kit::Card { label, - Some(note), - !following && app.preferences.theme == *id, - true, - ui_kit::PreferenceFigure::Theme { palette: palette.into(), system: id == "system" }, - ); - if crate::theme_files::find(id, &app.preferences.custom_themes) - .is_some_and(|file| !crate::theme_options::offered(file, crate::theme_options::PROVIDERS).is_empty()) - { - ui_kit::theme_options_badge(ui, response.rect, app.tr("prefs.theme_options_badge")); - crate::scenario::publish_rect(&format!("prefs:theme_options_badge:{id}"), response.rect); - } - crate::scenario::publish_target(&format!("prefs:theme_tile:{id}"), response.rect); - crate::scenario::publish_target(&format!("prefs:theme:{id}"), response.rect); - if !following && app.preferences.theme == *id { - crate::scenario::publish_target("prefs:theme", response.rect); - } - if response.clicked() { - chosen = Some(id.clone()); - } - ui_kit::Menu::context(&response, |ui| { - ui_kit::Menu::show(ui, Tokens::get().form_card_width, |ui| { - if ui_kit::MenuItem::new("theme_export", app.tr_label("Export…"), "export").show(ui).clicked() { - tile_action = Some(("export", id.clone())); + sub: Some(note), + selected: !following && app.preferences.theme == *id, + enabled: true, + options: options.then(|| app.tr("prefs.theme_options_badge")), + check: false, + aspect: 124.0 / 76.0, + figure: &|p, rect| { + if id == "system" { + ui_kit::paint_theme_system(p, rect, &sample, &dark_sample); + } else { + ui_kit::paint_theme_thumbnail(p, rect, &sample); + } + }, + }, + width.min(ui.available_width()), + ); + if options { + crate::scenario::publish_rect(&format!("prefs:theme_options_badge:{id}"), response.rect); + } + crate::scenario::publish_target(&format!("prefs:theme_tile:{id}"), response.rect); + crate::scenario::publish_target(&format!("prefs:theme:{id}"), response.rect); + if !following && app.preferences.theme == *id { + crate::scenario::publish_target("prefs:theme", response.rect); + } + if response.clicked() { + chosen = Some(id.clone()); + } + ui_kit::Menu::context(&response, |ui| { + ui_kit::Menu::show(ui, Tokens::get().form_card_width, |ui| { + if ui_kit::MenuItem::new("theme_export", app.tr_label("Export…"), "export").show(ui).clicked() { + tile_action = Some(("export", id.clone())); + ui.close(); + } + if custom { + let mut remove = ui_kit::MenuItem::new("theme_remove", app.tr_label("Remove"), "delete"); + remove.danger = true; + if remove.show(ui).clicked() { + tile_action = Some(("remove", id.clone())); ui.close(); } - if custom { - let mut remove = ui_kit::MenuItem::new("theme_remove", app.tr_label("Remove"), "delete"); - remove.danger = true; - if remove.show(ui).clicked() { - tile_action = Some(("remove", id.clone())); - ui.close(); - } - } - }); + } }); - } - }, - |ui| { - let tile = ui_kit::theme_import_tile(ui, app.tr_label("Import…"), app.tr("prefs.theme_file_or_paste")) - .on_hover_text(app.tr("prefs.theme_import_hint")); + }); + } else { + let tile = + ui_kit::theme_import_tile(ui, app.tr_label("Import…"), app.tr("prefs.theme_file")).on_hover_text(app.tr("prefs.theme_import_hint")); import_tile = Some(tile.rect); if tile.clicked() { action = Some("import"); @@ -1977,8 +2003,24 @@ fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) { } }); }); - }, - ); + } + }; + if crate::prefs_search::suppress_chrome(ui) { + for index in 0..=choices.len() { + item(ui, index); + } + } else { + ui_kit::carousel(ui, carousel_id, choices.len() + 1, width, height, &mut item); + for (label, handle, help) in [ + ("prefs.carousel_previous", "prefs:theme_previous", "prefs.appearance.previous_themes"), + ("prefs.carousel_next", "prefs:theme_next", "prefs.appearance.next_themes"), + ] { + if let Some(rect) = crate::scenario::rect_of(&format!("prefs:carousel:{}", crate::i18n::tr(label))) { + crate::scenario::publish_target(handle, rect); + ui.interact(rect, ui.make_persistent_id((handle, "help")), egui::Sense::hover()).on_hover_text(app.tr(help)); + } + } + } app.prefs_window.import_tile = import_tile; if let Some((kind, id)) = tile_action { action = Some(kind); @@ -1988,6 +2030,7 @@ fn theme_row(app: &mut SolveApp, ui: &mut egui::Ui) { // Choosing a theme stops following a file (#7573). stop_following(app); select_theme(app, &id); + ui.data_mut(|data| data.insert_temp(selection_key, id)); } match action { Some("import") => app.pick_open_for(&["json"], |app, path| { @@ -2036,28 +2079,30 @@ fn follow_row(app: &mut SolveApp, ui: &mut egui::Ui) { let launch = app.prefs_window.follow.launch.is_some(); let error = app.prefs_window.follow.error().map(str::to_string); let (mut choose, mut stop) = (false, false); - // The setting's name is longer than the label column: it leads the row's own line. - ui_kit::row(ui, "", |ui| { - // On a narrow page the buttons drop to a second line rather than widening the page. - let narrow = ui.available_width() < Tokens::get().form_card_width; - ui.horizontal_wrapped(|ui| { - ui_kit::text(ui, app.tr("prefs.theme_follow"), ui_kit::Text::Inline); - if narrow { - ui.end_row(); + ui.horizontal_wrapped(|ui| { + ui.add_enabled_ui(FOLLOW_AVAILABLE, |ui| { + let mut on = !path.is_empty(); + let check = ui_kit::checkbox(ui, app.tr("prefs.theme_follow"), &mut on); + crate::scenario::publish_target("prefs:theme_follow_toggle", check.rect); + if check.changed() { + if on { + choose = true; + } else { + stop = true; + } } - let choose_button = ui_kit::button(ui, app.tr_label("Choose…"), ui_kit::Button::Small); - crate::scenario::publish_target("prefs:theme_follow", choose_button.rect); - choose = choose_button.clicked(); - let stop_button = ui_kit::button(ui, app.tr("prefs.theme_follow_stop"), ui_kit::Button::Enabled(!path.is_empty())); - stop = stop_button.clicked(); - let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string()); - let shown = name.unwrap_or_else(|| app.tr("prefs.theme_follow_off").to_string()); - ui_kit::text(ui, &shown, ui_kit::Text::Inline).on_hover_text(&path); + ui_kit::help_icon(ui, app.tr("prefs.appearance.follow_help")); + let button = ui_kit::button(ui, app.tr_label("Choose…"), ui_kit::Button::Small); + crate::scenario::publish_target("prefs:theme_follow", button.rect); + choose |= button.clicked(); }); + ui_kit::settings_state_badge(ui, app.tr("prefs.appearance.desktop_only"), ui_kit::SettingsBadgeTone::Neutral); + if !path.is_empty() { + let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + ui_kit::settings_inline_note(ui, &name); + ui_kit::help_icon(ui, app.tr(if launch { "prefs.theme_follow_launch" } else { "prefs.theme_follow_note" })).on_hover_text(&path); + } }); - if !path.is_empty() { - ui_kit::text(ui, app.tr(if launch { "prefs.theme_follow_launch" } else { "prefs.theme_follow_note" }), ui_kit::Text::Hint("theme_follow")); - } if let Some(error) = error.filter(|_| !path.is_empty()) { ui_kit::text(ui, &crate::i18n::format("prefs.theme_follow_error", &[("error", &error)]), ui_kit::Text::Error("theme_follow")); } @@ -2077,7 +2122,7 @@ fn follow_row(app: &mut SolveApp, ui: &mut egui::Ui) { /// The interface font (#1290): the built-in font first, then the installed families, with a /// search box. The choice applies at once, like the other preferences. fn ui_font_row(app: &mut SolveApp, ui: &mut egui::Ui) { - let builtin = app.tr_label("Built-in").to_string(); + let builtin = crate::i18n::format("sketch_text.builtin_font", &[("family", "IBM Plex Sans")]); let current = if app.preferences.ui_font.trim().is_empty() { builtin.clone() } else { app.preferences.ui_font.clone() }; let families = crate::sketch_text::families(ui.ctx()); let mut values = vec![(String::new(), builtin.clone(), "prefs:font_builtin".to_string())]; @@ -2085,17 +2130,21 @@ fn ui_font_row(app: &mut SolveApp, ui: &mut egui::Ui) { values.extend(families.iter().map(|family| (family.clone(), family.clone(), format!("prefs:font:{family}")))); } let options: Vec<_> = values.iter().map(|(value, label, handle)| ui_kit::SearchOption { value, label, handle: Some(handle) }).collect(); - let chosen = ui_kit::searchable_dropdown( - ui, - "pref_ui_font", - ¤t, - &mut app.prefs_window.font_filter, - &options, - None, - families.is_none().then(|| crate::i18n::tr_label("Listing the installed fonts…")), - ); - if let Some(rect) = crate::scenario::rect_of(&format!("dialog:widget:{}", crate::i18n::tr("prefs.font"))) { - crate::scenario::publish_handle("prefs:ui_font", rect.center()); + let chosen = ui_kit::named_control(ui, app.tr_label("Interface font"), |ui| { + ui_kit::searchable_dropdown( + ui, + "pref_ui_font", + ¤t, + &mut app.prefs_window.font_filter, + &options, + None, + families.is_none().then(|| crate::i18n::tr_label("Listing the installed fonts…")), + ) + }); + if let Some(rect) = crate::scenario::rect_of(&format!("dialog:widget:{}", crate::i18n::tr_label("Interface font"))) { + crate::scenario::publish_target("prefs:ui_font", rect); + crate::scenario::publish_target(&format!("dialog:{}", app.tr("prefs.font")), rect); + crate::scenario::publish_rect(&format!("dialog:widget:{}", app.tr("prefs.font")), rect); } if let Some(name) = chosen { if name.is_empty() || crate::fonts::ui_font(&name).is_some() { @@ -3763,7 +3812,7 @@ fn theme_options_row(app: &mut SolveApp, ui: &mut egui::Ui) { } let (mut values, _) = effective_theme_options(&app.preferences, file); let before = values.clone(); - let reset = ui_kit::theme_options_list(ui, &file.id, &file.name, &rows, &mut values); + let reset = ui_kit::settings_card(ui, |ui| ui_kit::theme_options_list(ui, &file.id, &file.name, &rows, &mut values)).inner; let changes: BTreeMap<_, _> = values.into_iter().filter(|(id, value)| before.get(id) != Some(value)).collect(); if reset || !changes.is_empty() { let update = if reset { json!({}) } else { json!(changes) }; @@ -6432,7 +6481,15 @@ mod tests { h.app.home.open = false; h.call("ui.prefs", json!({"theme": "dark", "open": "Interface"})); h.frames(2); - super::reveal_preference(&mut h, "dialog:Import…"); + // The Import card is the last one in the theme carousel: page it into view. + for _ in 0..40 { + if h.app.prefs_window.import_tile.is_some() { + break; + } + h.step(&json!({"click":{"handle":"prefs:theme_next"}})).unwrap(); + h.frames(2); + } + assert!(h.app.prefs_window.import_tile.is_some(), "the Import card is reachable in the theme carousel"); let (root, out) = (h.dir.join("root"), h.dir.join("out")); std::fs::create_dir_all(&root).unwrap(); std::fs::create_dir_all(&out).unwrap(); @@ -6530,6 +6587,128 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn appearance_sections_and_carousel_use_real_data_and_stay_in_the_page() { + for base in ["light", "dark"] { + for screen in [740, 1600] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":screen,"height":1100})); + h.call("ui.prefs", json!({"theme":base,"language":"en","open":"Appearance"})); + h.frames(4); + let page = crate::scenario::rect_of("prefs:page_body").unwrap(); + let mut previous: Option = None; + for key in ["theme", "viewport_logo", "scale", "colour_vision"] { + let section = crate::scenario::rect_of(&format!("prefs:section:{key}")).unwrap(); + assert!(section.left() >= page.left() - 1.0 && section.right() <= page.right() + 1.0); + if let Some(bottom) = previous { + assert!((section.top() - bottom - 38.0).abs() <= 1.0, "{base} width={screen}: {key}"); + } + previous = Some(crate::scenario::rect_of(&format!("prefs:section:{key}:body")).unwrap().bottom()); + } + let choices = theme_choices(&h.app); + let count = format!("{} themes", choices.len()); + let mut painted_count = false; + for shape in &h.shapes { + crate::test_support::each_shape(&shape.shape, &mut |shape| { + if let egui::Shape::Text(text) = shape { + painted_count |= text.galley.job.text == count; + } + }); + } + assert!(painted_count, "count comes from actual themes"); + for _ in 0..choices.len() + 1 { + h.step(&json!({"click":{"handle":"prefs:theme_previous"}})).unwrap(); + h.frames(2); + } + let mut found = std::collections::BTreeSet::new(); + for _ in 0..choices.len() + 1 { + for (id, _) in &choices { + if let Some(rect) = crate::scenario::rect_of(&format!("prefs:theme:{id}")) { + assert!(page.expand(1.0).contains_rect(rect), "{base} width={screen}: {id} {rect:?}"); + assert!((rect.width() - 88.0).abs() <= 1.0); + found.insert(id.clone()); + } + } + if let Some(import) = h.app.prefs_window.import_tile { + assert!(page.expand(1.0).contains_rect(import)); + break; + } + h.step(&json!({"click":{"handle":"prefs:theme_next"}})).unwrap(); + h.frames(2); + } + assert_eq!(found, choices.into_iter().map(|(id, _)| id).collect()); + assert!(h.app.prefs_window.import_tile.is_some(), "Import is the last carousel card"); + assert_eq!(h.app.preferences.theme, base, "scrolling does not select a theme"); + assert_eq!(h.app.preferences.ui_scale, 1.0); + assert_eq!(h.app.preferences.viewport_background, None); + assert_eq!(h.app.preferences.viewport_theme, crate::theme::ViewportTheme::Theme); + assert!(!h.app.preferences.logo_accent); + assert!(h.app.preferences.theme_follow.is_empty() && h.app.preferences.ui_font.is_empty()); + assert_eq!(h.app.preferences.color_vision, crate::theme::ColorVision::Off); + h.call("ui.prefs", json!({"button":"cancel"})); + } + } + } + + #[test] + fn appearance_controls_edit_real_fields_and_cancel_restores_them() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":1600,"height":1100})); + h.call("ui.prefs", json!({"language":"en"})); + h.call("ui.prefs", json!({"open":"Interface"})); + h.frames(3); + assert_eq!(h.app.prefs_window.section, PAGE_APPEARANCE, "legacy alias remains supported"); + let before = h.app.preferences.clone(); + for (handle, expected) in + [("prefs:viewport_theme:light", crate::theme::ViewportTheme::Light), ("prefs:viewport_theme:dark", crate::theme::ViewportTheme::Dark)] + { + super::reveal_preference(&mut h, handle); + h.step(&json!({"click":{"handle":handle}})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.viewport_theme, expected); + } + super::reveal_preference(&mut h, "dialog:Background:Color"); + h.step(&json!({"click":{"handle":"dialog:Background:Color"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.viewport_background, Some([255, 255, 255])); + super::reveal_preference(&mut h, "prefs:viewport_background_hex"); + h.step(&json!({"click":{"handle":"prefs:viewport_background_hex"}})).unwrap(); + h.step(&json!({"key":"A","cmd":true})).unwrap(); + h.step(&json!({"text":"#123456"})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.viewport_background, Some([0x12, 0x34, 0x56])); + super::reveal_preference(&mut h, "prefs:viewport_background_picker"); + h.step(&json!({"click":{"handle":"prefs:viewport_background_picker"}})).unwrap(); + h.frames(2); + assert!(crate::scenario::rect_of("color:popover").is_some(), "the standard picker opens beside the hex editor"); + h.step(&json!({"click":{"handle":"color:spin:R:up"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.viewport_background, Some([0x13, 0x34, 0x56]), "picker edits the same RGB as hex"); + h.step(&json!({"click":{"handle":"prefs:viewport_background_hex"}})).unwrap(); + h.frames(2); + assert!(h.widget("#133456").is_some(), "a picker edit refreshes the inline hex field"); + super::reveal_preference(&mut h, "dialog:Logo:Accent"); + h.step(&json!({"click":{"handle":"dialog:Logo:Accent"}})).unwrap(); + h.frames(2); + assert!(h.app.preferences.logo_accent); + for (percent, scale) in [(75, 0.75), (100, 1.0), (110, 1.1), (125, 1.25), (150, 1.5), (200, 2.0)] { + let handle = format!("prefs:scale_preset:{percent}"); + // Rescaling may leave the presets above the current vertical scroll position. + let page = crate::scenario::rect_of("prefs:page_body").unwrap(); + h.call("ui.scroll", json!({"x":page.center().x,"y":page.center().y,"delta":5000})); + h.frames(20); + super::reveal_preference(&mut h, &handle); + h.step(&json!({"click":{"handle":handle}})).unwrap(); + h.frames(4); + assert!((h.app.preferences.ui_scale - scale).abs() < 0.001); + } + h.call("ui.prefs", json!({"button":"cancel"})); + h.frames(2); + assert_eq!(h.app.preferences, before); + } + fn theme_options_fixture(base: &str, count: usize) -> serde_json::Value { let fixtures: serde_json::Value = serde_json::from_str(include_str!("../tests/fixtures/theme-options.json")).unwrap(); fixtures[format!("{base}-{count}")].clone() @@ -6542,10 +6721,23 @@ mod tests { let mut h = crate::scenario::Harness::new(); h.app.home.open = false; h.call("ui.resize", json!({"width":1600,"height":1100})); - let out = h.call("ui.prefs", json!({"theme_import":theme_options_fixture(base, count),"open":"Interface"})); + let fixture = theme_options_fixture(base, count); + // The 12-cell fixture also declares a composite child, counted in the header. + let option_count = fixture["options"].as_array().expect("fixture option definitions").len(); + let out = h.call("ui.prefs", json!({"theme_import":fixture,"open":"Interface"})); assert!(out["error"].is_null(), "{out}"); h.frames(3); assert_eq!(crate::scenario::rect_of("prefs:theme_options_header").is_some(), count > 0, "{base} {count}"); + let caption = if option_count == 1 { "1 option".to_owned() } else { format!("{option_count} options") }; + let mut painted_count = 0; + for shape in &h.shapes { + crate::test_support::each_shape(&shape.shape, &mut |shape| { + if let egui::Shape::Text(text) = shape { + painted_count += usize::from(text.galley.job.text == caption); + } + }); + } + assert_eq!(painted_count, usize::from(count > 0), "{base}: the real option count paints the exact singular/plural caption once"); let id = format!("options-{base}-{count}"); assert_eq!(crate::scenario::rect_of(&format!("prefs:theme_options_badge:{id}")).is_some(), count > 0); assert_eq!(crate::scenario::handle_at("prefs:theme_options_more").is_some(), count == 12); @@ -6558,14 +6750,14 @@ mod tests { ); assert!(crate::scenario::handle_at("prefs:theme_options_reset").is_none()); if count == 0 { - let strip = crate::scenario::rect_of("dialog:hint:tab_accent").unwrap(); + let viewport = crate::scenario::rect_of("prefs:section:viewport_logo").unwrap(); let mut unknown = theme_options_fixture(base, count); unknown["options"] = json!([{"id":"blur","type":"range","default":0}]); h.call("ui.prefs", json!({"theme_import":unknown})); h.frames(2); assert!(crate::scenario::rect_of("prefs:theme_options_header").is_none()); assert!(crate::scenario::rect_of(&format!("prefs:theme_options_badge:{id}")).is_none()); - assert_eq!(crate::scenario::rect_of("dialog:hint:tab_accent").unwrap(), strip, "unknown providers add no gap or notice"); + assert_eq!(crate::scenario::rect_of("prefs:section:viewport_logo").unwrap(), viewport, "unknown providers add no gap or notice"); } if count == 12 { assert!(crate::scenario::rect_of("prefs:theme_option:outline").is_none()); @@ -7380,6 +7572,61 @@ mod tests { assert!(crate::scenario::rect_of("prefs:ok").is_some()); } + #[test] + fn appearance_popups_own_escape_restore_focus_and_leave_cancel_to_the_next_escape() { + for font in [true, false] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":1600,"height":1100})); + h.call("ui.prefs", json!({"language":"en","theme":"dark"})); + let before = h.app.preferences.clone(); + h.call("ui.prefs", json!({"open":"Appearance"})); + h.frames(3); + reveal_preference(&mut h, "prefs:viewport_theme:light"); + h.step(&json!({"click":{"handle":"prefs:viewport_theme:light"}})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.viewport_theme, crate::theme::ViewportTheme::Light); + let (target, popup) = if font { + ("prefs:ui_font", "dialog:Interface font search") + } else { + reveal_preference(&mut h, "dialog:Background:Color"); + h.step(&json!({"click":{"handle":"dialog:Background:Color"}})).unwrap(); + h.frames(2); + ("prefs:viewport_background_picker", "color:popover") + }; + reveal_preference(&mut h, target); + let body = crate::scenario::rect_of("prefs:page_body").unwrap(); + let rect = crate::scenario::rect_of(target).unwrap(); + assert!(body.contains_rect(rect), "{target} is visible before clicking"); + let edited = h.app.preferences.clone(); + assert_ne!(edited, before); + h.step(&json!({"click":{"handle":target}})).unwrap(); + h.frames(2); + assert!(crate::scenario::handle_at(popup).is_some() || crate::scenario::rect_of(popup).is_some(), "{target} opens its real popup"); + h.step(&json!({"key":"Escape"})).unwrap(); + h.frames(2); + assert!(h.app.prefs_window.open && h.app.prefs_window.section == PAGE_APPEARANCE); + assert!(h.app.prefs_window.snapshot.is_some()); + assert_eq!(h.app.preferences, edited, "dismissing {target} retains live changes"); + assert!(crate::scenario::handle_at(popup).is_none() && crate::scenario::rect_of(popup).is_none()); + // No pointer input: the actual combo/swatch must have regained keyboard focus. + h.step(&json!({"key":"Enter"})).unwrap(); + h.frames(2); + assert!( + crate::scenario::handle_at(popup).is_some() || crate::scenario::rect_of(popup).is_some(), + "{target} reopens from its restored focus" + ); + h.step(&json!({"key":"Escape"})).unwrap(); + h.frames(2); + assert!(h.app.prefs_window.open && h.app.prefs_window.snapshot.is_some()); + assert_eq!(h.app.preferences, edited); + h.step(&json!({"key":"Escape"})).unwrap(); + h.frames(2); + assert!(!h.app.prefs_window.open && h.app.prefs_window.snapshot.is_none()); + assert_eq!(h.app.preferences, before, "Escape with no popup cancels and restores the original snapshot"); + } + } + /// Letters typed in the font list's own Search box narrow the list. Preferences' search takes /// typing only when no text field has the keyboard, so it must not take these. #[test] @@ -7391,9 +7638,12 @@ mod tests { h.step(&json!({"text": "font"})).expect("search"); h.frames(3); let combo = crate::scenario::handle_at("prefs:ui_font").expect("the search finds the font row"); + let body = crate::scenario::rect_of("prefs:page_body").expect("the Preferences page body"); + let picker = crate::scenario::rect_of("prefs:ui_font").expect("the font picker bounds"); + assert!(body.contains_rect(picker) && picker.contains(combo), "the font picker is inside the visible page before clicking"); h.call("ui.click", json!({"x":combo.x,"y":combo.y})); h.frames(2); - let search = format!("dialog:{} search", crate::i18n::tr("prefs.font")); + let search = format!("dialog:{} search", crate::i18n::tr_label("Interface font")); let field = crate::scenario::handle_at(&search).expect("the font list is open"); h.call("ui.click", json!({"x":field.x,"y":field.y})); h.frames(2); @@ -8071,35 +8321,36 @@ mod tests { .collect() } - /// The Interface page's tab colour strip names each tab as the ribbon does, in every language. + /// The shipped ribbon uses the same localized tab names as workspace metadata. #[test] - fn tab_accent_strip_names_the_tabs_as_the_ribbon_does() { - use crate::workspace::tab_name; - fn texts(shape: &egui::Shape, out: &mut Vec) { - match shape { - egui::Shape::Text(text) => out.push(text.galley.job.text.clone()), - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| texts(shape, out)), - _ => {} - } - } - let h = crate::scenario::Harness::new(); + fn ribbon_names_the_tabs_as_workspace_metadata_does() { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", json!({"width":2400,"height":1000})); for (lang, want) in [ ("en", ["Model", "Surface", "Mesh", "Form", "Sheet Metal", "Render"]), ("de", ["Modell", "Fläche", "Mesh", "Form", "Blech", "Rendern"]), ("fr", ["Modèle", "Surface", "Maillage", "Forme", "Tôlerie", "Rendu"]), ] { + h.app.preferences.language = lang.into(); + h.frames(3); let _scope = crate::i18n::scope(lang); - let got = ["MODEL", "SURFACE", "MESH", "FORM", "SHEET METAL", "RENDER"].map(tab_name); - assert_eq!(got, want, "{lang}"); - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(900.0, 200.0)); - let mut out = h.ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { - crate::ui_kit::scope(ui, crate::ui_kit::tab_accent_strip); - }); - out.textures_delta.clear(); + for (id, name) in ["MODEL", "SURFACE", "MESH", "FORM", "SHEET METAL", "RENDER"].into_iter().zip(want) { + assert_eq!(crate::workspace::tab_name(id), name, "{lang}"); + assert_eq!(crate::toolbar::ribbon_label(&h.app, id), name, "{lang}"); + } let mut painted = Vec::new(); - out.shapes.iter().for_each(|shape| texts(&shape.shape, &mut painted)); - for name in want { - assert!(painted.iter().any(|p| p == name), "{lang}: the strip paints {painted:?}, not {name}"); + for shape in &h.shapes { + crate::test_support::each_shape(&shape.shape, &mut |shape| { + if let egui::Shape::Text(text) = shape { + painted.push(text.galley.job.text.clone()); + } + }); + } + for id in crate::workspace::visible_tabs(&h.app) { + let name = crate::toolbar::ribbon_label(&h.app, id); + assert!(crate::scenario::handle_at(&format!("tab:{id}")).is_some(), "{lang}: real ribbon tab {id}"); + assert!(painted.contains(&name), "{lang}: the ribbon paints {painted:?}, not {name}"); } } } diff --git a/crates/ui-egui/src/prefs/interface.rs b/crates/ui-egui/src/prefs/interface.rs index 92421bac7..46e704dfc 100644 --- a/crates/ui-egui/src/prefs/interface.rs +++ b/crates/ui-egui/src/prefs/interface.rs @@ -2,136 +2,199 @@ use super::*; pub(super) fn appearance(app: &mut SolveApp, ui: &mut egui::Ui, t: &Tokens) { - ui_kit::settings_heading_with_tag( - ui, - app.tr("prefs.structure.appearance"), - app.tr("prefs.structure.appearance_note"), - Some(crate::settings_profiles::tag), - ); - ui_kit::settings_section(ui, "theme", app.tr("ui.theme"), |ui| { - theme_row(app, ui); - theme_options_row(app, ui); - ui_kit::tab_accent_strip(ui); - // The 3D view in the theme's colours, or the Light or Dark theme's (#4146). - ui_kit::settings_form(ui, t.form_label_width + t.space_16 + t.space_6, |ui| { - let label = app.tr("prefs.viewport"); - ui_kit::row(ui, label, |ui| { - let views = crate::theme::ViewportTheme::ALL; - let labels: Vec<_> = views.iter().map(|v| crate::i18n::tr(v.label_id())).collect(); - let mut selected = views.iter().position(|v| *v == app.preferences.viewport_theme).unwrap_or(0); - if ui_kit::settings_segments(ui, label, &mut selected, &labels) - && let Some(view) = views.get(selected) - { - app.preferences.viewport_theme = *view; - } - }); - // The view's background: the theme's gradient, or one colour of the user's (#7688). - let label = app.tr("prefs.viewport_background"); - ui_kit::row(ui, label, |ui| { - let labels = [crate::i18n::tr("prefs.viewport_background_theme"), crate::i18n::tr("prefs.viewport_background_colour")]; - let mut selected = usize::from(app.preferences.viewport_background.is_some()); - if ui_kit::settings_segments(ui, label, &mut selected, &labels) { - app.preferences.viewport_background = (selected == 1).then_some([255, 255, 255]); - } - if let Some(colour) = &mut app.preferences.viewport_background { - ui_kit::color_field(ui, colour); - } - }); - // The logo in the theme's own logo colours or in its accent. - let label = app.tr("prefs.logo"); - ui_kit::row(ui, label, |ui| { - let labels = [crate::i18n::tr("prefs.logo_theme"), crate::i18n::tr("prefs.logo_accent")]; - let mut selected = usize::from(app.preferences.logo_accent); - if ui_kit::settings_segments(ui, label, &mut selected, &labels) { - app.preferences.logo_accent = selected == 1; - } - }); - // A theme file another tool writes, reloaded when it changes (#7573). - if FOLLOW_AVAILABLE { - follow_row(app, ui); - } - }); - }); - ui_kit::settings_section(ui, "scale", app.tr("prefs.scale_text"), |ui| { - ui_kit::settings_pair( + ui_kit::settings_page(ui, |ui| { + ui_kit::settings_heading_with_tag( ui, - |ui| { - let response = ui_kit::slider( - ui, - &mut app.preferences.ui_scale, - 0.5..=2.5, - ui_kit::Slider { step: Some(0.05), format: |v| format!("{:.0} %", v * 100.0), ..Default::default() }, - ); - crate::scenario::publish_target("prefs:scale", response.rect); - ui.horizontal_wrapped(|ui| { - let locale = crate::i18n::Locale::for_language(&app.preferences.language); - for value in [0.75, 1.0, 1.1, 1.25, 1.5, 2.0] { - let percent = format!("{:.0}", value * 100.0); - if ui_kit::button( - ui, - locale.format("prefs.structure.scale_percent", &[("percent", &percent)]), - if (app.preferences.ui_scale - value).abs() < 0.001 { ui_kit::Button::SmallSelected } else { ui_kit::Button::Small }, - ) - .clicked() - { - app.preferences.ui_scale = value; + app.tr("prefs.structure.appearance"), + app.tr("prefs.structure.appearance_note"), + Some(crate::settings_profiles::tag), + ); + let count = crate::i18n::format("prefs.appearance.theme_count", &[("count", &theme_choices(app).len().to_string())]); + ui_kit::settings_section_count(ui, "theme", app.tr("ui.theme"), Some(&count), |ui| { + theme_row(app, ui); + theme_options_row(app, ui); + }); + ui_kit::settings_section(ui, "viewport_logo", app.tr("prefs.appearance.viewport_logo"), |ui| { + // The 3D view in the theme's colours, or the Light or Dark theme's (#4146). + ui_kit::settings_form(ui, t.space_24 * 6.0 + t.space_6, |ui| { + // The view's background: the theme's gradient, or one colour of the user's (#7688). + let label = app.tr("prefs.viewport_background"); + let labels = [crate::i18n::tr("prefs.viewport_background_theme"), crate::i18n::tr("prefs.viewport_background_colour")]; + let segments_width = (labels.iter().map(|label| ui_kit::ContentWidth::name(ui, label)).fold(0.0, f32::max) + t.space_16) * 2.0; + let label_width = (t.space_24 * 6.0 + t.space_6).min(ui.available_width() * 0.6); + let available = (ui.available_width() - label_width - t.space_14).max(0.0); + let narrow = available < segments_width + t.control_height + t.space_6 + t.space_24 * 4.0 + ui.spacing().item_spacing.x * 2.0; + let colour_controls = |ui: &mut egui::Ui, app: &mut SolveApp| { + let enabled = app.preferences.viewport_background.is_some(); + let mut rgb = app.preferences.viewport_background.unwrap_or([255, 255, 255]); + ui.add_enabled_ui(enabled, |ui| { + let response = ui_kit::color_field(ui, &mut rgb); + crate::scenario::publish_target("prefs:viewport_background_picker", response.rect); + if response.changed() { + app.preferences.viewport_background = Some(rgb); + } + }); + let saved = app.preferences.viewport_background; + let key = ui.make_persistent_id("appearance_background_hex"); + let (last, mut hex) = ui + .data(|data| data.get_temp::<(Option<[u8; 3]>, String)>(key)) + .unwrap_or_else(|| (saved, crate::dialogs_appearance::hex(saved.unwrap_or([255, 255, 255])))); + if last != saved { + hex = crate::dialogs_appearance::hex(saved.unwrap_or([255, 255, 255])); + } + ui.add_enabled_ui(saved.is_some(), |ui| { + ui_kit::settings_control_width(ui, t.space_24 * 4.0, |ui| { + let response = ui_kit::cell_editor(ui, key.with("edit"), &mut hex, app.tr("color.hex_hint"), false); + crate::scenario::publish_target("prefs:viewport_background_hex", response.rect); + if response.changed() + && let Some(colour) = crate::dialogs_appearance::parse_color(&json!(hex)) + { + app.preferences.viewport_background = Some(colour); + } + }); + }); + ui.data_mut(|data| data.insert_temp(key, (app.preferences.viewport_background, hex))); + }; + let shown = ui_kit::row(ui, label, |ui| { + let mut selected = usize::from(app.preferences.viewport_background.is_some()); + if ui_kit::settings_segments(ui, label, &mut selected, &labels) { + app.preferences.viewport_background = (selected == 1).then_some([255, 255, 255]); + } + if !narrow { + colour_controls(ui, app); + } + ui.is_visible() + }); + if narrow && shown { + ui_kit::below_row_control(ui, label, ui.available_width(), |ui| { + ui.horizontal_wrapped(|ui| colour_controls(ui, app)); + }); + } + let label = app.tr("prefs.appearance.viewport_colours"); + ui_kit::row(ui, label, |ui| { + let views = crate::theme::ViewportTheme::ALL; + let labels = [app.tr("prefs.appearance.theme_own"), app.tr("ui.light"), app.tr("ui.dark")]; + let mut selected = views.iter().position(|v| *v == app.preferences.viewport_theme).unwrap_or(0); + if ui_kit::settings_segments(ui, label, &mut selected, &labels) + && let Some(view) = views.get(selected) + { + app.preferences.viewport_theme = *view; + } + for (view, caption) in views.into_iter().zip(labels) { + if let Some(at) = crate::scenario::handle_at(&format!("dialog:{label}:{caption}")) { + let id = view.id(); + crate::scenario::publish_handle(&format!("prefs:viewport_theme:{id}"), at); + crate::scenario::publish_handle(&format!("dialog:{}:{}", app.tr("prefs.viewport"), app.tr(view.label_id())), at); } } }); - ui_kit::text(ui, app.tr("prefs.scale_note"), ui_kit::Text::Hint("scale")); - app.preferences.ui_scale - }, - ui_kit::scale_specimen, - ); - ui_kit::divider(ui, "scale_font"); - if !cfg!(target_arch = "wasm32") { - ui_kit::settings_font_row(ui, crate::i18n::tr("prefs.font"), |ui, part| { - if part == 0 { - ui_font_row(app, ui); - return; - } - if ui_kit::button(ui, app.tr("prefs.choose_font"), ui_kit::Button::Normal).clicked() { - app.pick_open_for(&["ttf", "otf", "ttc"], |app, path| { - if let Some(path) = path { - if crate::fonts::ui_font(&path).is_some() { - app.preferences.ui_font = path; - } else { - app.set_status(crate::i18n::tr("prefs.font_unreadable"), true); + // The logo in the theme's own logo colours or in its accent. + let label = app.tr("prefs.logo"); + ui_kit::row(ui, label, |ui| { + let labels = [crate::i18n::tr("prefs.logo_theme"), crate::i18n::tr("prefs.logo_accent")]; + let mut selected = usize::from(app.preferences.logo_accent); + if ui_kit::settings_segments(ui, label, &mut selected, &labels) { + app.preferences.logo_accent = selected == 1; + } + }); + // A theme file another tool writes, reloaded when it changes (#7573). + follow_row(app, ui); + }); + }); + ui_kit::settings_section(ui, "scale", app.tr("prefs.scale_text"), |ui| { + ui_kit::settings_pair( + ui, + |ui| { + ui_kit::settings_form(ui, 0.0, |ui| { + ui_kit::row(ui, app.tr("prefs.appearance.interface_scale"), |ui| { + let response = ui_kit::named_control(ui, app.tr("prefs.appearance.interface_scale"), |ui| { + ui_kit::slider( + ui, + &mut app.preferences.ui_scale, + 0.5..=2.5, + ui_kit::Slider { step: Some(0.05), format: |v| format!("{:.0} %", v * 100.0), ..Default::default() }, + ) + }) + .on_hover_text(app.tr("prefs.scale_note")); + crate::scenario::publish_target("prefs:scale", response.rect); + }); + }); + ui.horizontal_wrapped(|ui| { + let locale = crate::i18n::Locale::for_language(&app.preferences.language); + for value in [0.75, 1.0, 1.1, 1.25, 1.5, 2.0] { + let percent = format!("{:.0}", value * 100.0); + let chip = ui_kit::button( + ui, + locale.format("prefs.structure.scale_percent", &[("percent", &percent)]), + if (app.preferences.ui_scale - value).abs() < 0.001 { ui_kit::Button::SmallSelected } else { ui_kit::Button::Small }, + ); + crate::scenario::publish_target(&format!("prefs:scale_preset:{percent}"), chip.rect); + if chip.clicked() { + app.preferences.ui_scale = value; } } }); - } - if ui_kit::button(ui, app.tr_label("Reset"), ui_kit::Button::Ghost).clicked() { - app.preferences.ui_font.clear(); - } - }); - ui_kit::font_specimen(ui, app.tr("prefs.font_sample")); - ui_kit::text(ui, app.tr("prefs.font_fallback"), ui_kit::Text::Hint("font_fallback")); - } - }); - ui_kit::settings_section(ui, "colour_vision", app.tr("ui.colour_vision"), |ui| { - let mode = app.preferences.color_vision; - ui.horizontal_wrapped(|ui| { - let modes = crate::theme::ColorVision::ALL; - let labels: Vec<_> = modes.iter().map(|m| crate::i18n::tr(m.label_id())).collect(); - let mut selected = modes.iter().position(|m| *m == mode).unwrap_or(0); - if ui_kit::settings_segments(ui, app.tr("ui.colour_vision_mode"), &mut selected, &labels) - && let Some(mode) = modes.get(selected) - { - app.preferences.color_vision = *mode; + app.preferences.ui_scale + }, + ui_kit::scale_specimen, + ); + ui_kit::divider(ui, "scale_font"); + if !cfg!(target_arch = "wasm32") { + ui_kit::settings_font_row(ui, crate::i18n::tr("prefs.font"), |ui, part| { + if part == 0 { + ui_font_row(app, ui); + return; + } + if ui_kit::button(ui, app.tr("prefs.choose_font"), ui_kit::Button::Normal).clicked() { + app.pick_open_for(&["ttf", "otf", "ttc"], |app, path| { + if let Some(path) = path { + if crate::fonts::ui_font(&path).is_some() { + app.preferences.ui_font = path; + } else { + app.set_status(crate::i18n::tr("prefs.font_unreadable"), true); + } + } + }); + } + if ui_kit::button(ui, app.tr_label("Reset"), ui_kit::Button::Ghost).clicked() { + app.preferences.ui_font.clear(); + } + }); + ui.scope(|ui| ui_kit::font_specimen(ui, app.tr("prefs.font_sample"))).response.on_hover_text(app.tr("prefs.font_fallback")); + } + }); + ui_kit::settings_section(ui, "colour_vision", app.tr("ui.colour_vision"), |ui| { + let mode = app.preferences.color_vision; + ui_kit::settings_form(ui, t.form_label_width, |ui| { + ui_kit::settings_row_help(ui, app.tr("ui.colour_vision_mode"), app.tr("prefs.appearance.colour_vision_help"), |ui| { + let modes = crate::theme::ColorVision::ALL; + let labels: Vec<_> = modes.iter().map(|m| crate::i18n::tr(m.label_id())).collect(); + let mut selected = modes.iter().position(|m| *m == mode).unwrap_or(0); + if ui_kit::settings_segments(ui, app.tr("ui.colour_vision_mode"), &mut selected, &labels) + && let Some(mode) = modes.get(selected) + { + app.preferences.color_vision = *mode; + } + if let Some(rect) = crate::scenario::rect_of(&format!("dialog:segments:{}", app.tr("ui.colour_vision_mode"))) { + crate::scenario::publish_target("prefs:color_vision", rect); + } + for mode in crate::theme::ColorVision::ALL { + if let Some(at) = + crate::scenario::handle_at(&format!("dialog:{}:{}", app.tr("ui.colour_vision_mode"), app.tr(mode.label_id()))) + { + crate::scenario::publish_handle(&format!("prefs:color_vision:{}", mode.id()), at); + } + } + }); + }); + ui_kit::status_palette_sample(ui, app.preferences.color_vision); + // What the modes recolour, in the mode being chosen (#7152): the status chips above keep + // their colours in every mode. + ui_kit::colour_vision_sample(ui, &crate::theme::Tokens::get_in(app.preferences.color_vision)); + if app.preferences.color_vision != mode { + ui.ctx().request_repaint(); } - if let Some(rect) = crate::scenario::rect_of(&format!("dialog:segments:{}", app.tr("ui.colour_vision_mode"))) { - crate::scenario::publish_target("prefs:color_vision", rect); - } - ui_kit::status_palette_sample(ui, app.preferences.color_vision); }); - // What the modes recolour, in the mode being chosen (#7152): the status chips above keep - // their colours in every mode. - ui_kit::colour_vision_sample(ui, &crate::theme::Tokens::get_in(app.preferences.color_vision)); - if app.preferences.color_vision != mode { - ui.ctx().request_repaint(); - } - ui_kit::text(ui, app.tr("ui.colour_vision_note"), ui_kit::Text::Hint("colour_vision")); }); } diff --git a/crates/ui-egui/src/prefs_search.rs b/crates/ui-egui/src/prefs_search.rs index 5e7c0b63e..3e525f718 100644 --- a/crates/ui-egui/src/prefs_search.rs +++ b/crates/ui-egui/src/prefs_search.rs @@ -740,6 +740,58 @@ pub(crate) fn follow(ui: &Ui, label: &str, rect: Rect) { mod tests { use super::*; + #[test] + fn appearance_controls_keep_one_search_result_and_their_page() { + use egui::accesskit::Role; + for width in [520, 1600] { + let mut h = crate::scenario::Harness::new(); + h.app.home.open = false; + h.call("ui.resize", serde_json::json!({"width":width,"height":1100})); + h.call("ui.prefs", serde_json::json!({"language":"en","open":"Appearance"})); + for (query, label, native) in [ + ("3D view colors", "3D view colors", None), + ("Interface scale", "Interface scale", Some((Role::Slider, "Interface scale", "prefs:scale"))), + ("Follow a theme file", "Follow a theme file", None), + ("Background", "Background", Some((Role::Button, "Color", "dialog:Background:Color"))), + ("Font", "Font", Some((Role::ComboBox, "Interface font", "prefs:ui_font"))), + ] { + h.app.prefs_window.filter = query.into(); + h.frames(5); + let (_, _, hits) = nav(&h.ctx); + let matching: Vec<_> = hits.iter().filter(|hit| hit.label == label).collect(); + assert_eq!(matching.len(), 1, "width={width}: {query} needs exactly one real navigation hit"); + assert_eq!(matching[0].page, crate::prefs::PAGE_APPEARANCE); + let at = h.widget(label).unwrap(); + let body = crate::scenario::rect_of("prefs:page_body").unwrap(); + assert!(body.contains(egui::pos2(at[0] as f32, at[1] as f32))); + if let Some((role, name, target)) = native { + let tree = h.output.accesskit_update.as_ref().unwrap(); + let controls: Vec<_> = + tree.nodes.iter().filter(|(_, node)| !node.is_disabled() && node.role() == role && node.label() == Some(name)).collect(); + assert_eq!(controls.len(), 1, "width={width}: {query} must expose one enabled native {name} control"); + let bounds = controls[0].1.bounds().unwrap(); + let centre = egui::pos2(((bounds.x0 + bounds.x1) / 2.0) as f32, ((bounds.y0 + bounds.y1) / 2.0) as f32); + let rect = crate::scenario::rect_of(target).unwrap(); + assert!(body.contains_rect(rect) && rect.contains(centre), "width={width}: {name} is visible at its real target"); + if name == "Interface scale" { + let row = crate::scenario::rect_of("dialog:row:Interface scale").unwrap(); + assert!((rect.left() - row.left()).abs() <= 1.0, "accessible-only name reserves no label column"); + } + if name == "Color" { + h.step(&serde_json::json!({"click":{"handle":target}})).unwrap(); + h.frames(2); + assert_eq!(h.app.preferences.viewport_background, Some([255, 255, 255]), "the search hit edits the real setting"); + } + if name == "Interface font" { + h.step(&serde_json::json!({"click":{"handle":target}})).unwrap(); + h.frames(2); + assert!(crate::scenario::handle_at("prefs:font_builtin").is_some(), "real searchable font picker opens at either width"); + } + } + } + } + } + #[test] fn search_matches_a_label_a_subsequence_and_the_english_source() { assert!(matches_text("zoom", &["Reverse zoom direction"])); diff --git a/crates/ui-egui/src/ui_kit/color.rs b/crates/ui-egui/src/ui_kit/color.rs index 3f181be17..2295c5cf0 100644 --- a/crates/ui-egui/src/ui_kit/color.rs +++ b/crates/ui-egui/src/ui_kit/color.rs @@ -76,7 +76,7 @@ fn color_field_inner(ui: &mut Ui, rgb: &mut [u8; 3], opacity: Option<&mut f64>, 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; - Container::new(ui.ctx(), Surface::Popup) + let popup = Container::new(ui.ctx(), Surface::Popup) .menu(&response) .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .width(t.form_card_width + t.space_24 + t.space_12) @@ -92,6 +92,9 @@ fn color_field_inner(ui: &mut Ui, rgb: &mut [u8; 3], opacity: Option<&mut f64>, edited = if opacity.is_some() || mixed { color_popover_with_opacity(ui, rgb, opacity, mixed) } else { color_popover(ui, rgb) }; }); }); + if popup.is_some() && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + response.request_focus(); + } if edited { response.mark_changed(); } diff --git a/crates/ui-egui/src/ui_kit/fields.rs b/crates/ui-egui/src/ui_kit/fields.rs index 54ff001a2..e2d3ebb7c 100644 --- a/crates/ui-egui/src/ui_kit/fields.rs +++ b/crates/ui-egui/src/ui_kit/fields.rs @@ -207,51 +207,53 @@ fn searchable_dropdown_with( } else { combo.icon(dropdown_arrow) }; - let response = combo - .show_ui(ui, |ui| { - let search = ui.add( - text_input(egui::TextEdit::singleline(filter)) - .id_salt(format!("{id}_search")) - .hint_text(crate::i18n::tr_label("Search")) - .desired_width(f32::INFINITY), - ); - // Preferences types into its own search only while no field has the keyboard. - if search.has_focus() { - crate::prefs_search::note_key_sink(ui.ctx()); + let popup = combo.show_ui(ui, |ui| { + let search = ui.add( + text_input(egui::TextEdit::singleline(filter)) + .id_salt(format!("{id}_search")) + .hint_text(crate::i18n::tr_label("Search")) + .desired_width(f32::INFINITY), + ); + // Preferences types into its own search only while no field has the keyboard. + if search.has_focus() { + crate::prefs_search::note_key_sink(ui.ctx()); + } + scenario::publish_handle(&format!("dialog:{row} search"), search.rect.center()); + if let Some(custom) = custom { + let response = ui.selectable_label(false, custom); + scenario::publish_handle(&format!("dialog:{row} file"), response.rect.center()); + if response.clicked() { + chosen = Some(filter.trim().to_owned()); + ui.close(); } - scenario::publish_handle(&format!("dialog:{row} search"), search.rect.center()); - if let Some(custom) = custom { - let response = ui.selectable_label(false, custom); - scenario::publish_handle(&format!("dialog:{row} file"), response.rect.center()); - if response.clicked() { - chosen = Some(filter.trim().to_owned()); - ui.close(); + return; + } + let query = filter.to_lowercase(); + egui::ScrollArea::vertical() + .id_salt(format!("{id}_list")) + .max_height(Tokens::get().space_24 * 10.0) + .min_scrolled_height(Tokens::get().space_24 * 10.0) + .auto_shrink([false, false]) + .show(ui, |ui| { + for option in options.iter().filter(|o| o.label.to_lowercase().contains(&query)) { + let response = ui.selectable_label(current == option.label, option.label); + if let Some(handle) = option.handle { + scenario::publish_handle(handle, response.rect.center()); + } + if response.clicked() { + chosen = Some(option.value.to_owned()); + ui.close(); + } } - return; - } - let query = filter.to_lowercase(); - egui::ScrollArea::vertical() - .id_salt(format!("{id}_list")) - .max_height(Tokens::get().space_24 * 10.0) - .min_scrolled_height(Tokens::get().space_24 * 10.0) - .auto_shrink([false, false]) - .show(ui, |ui| { - for option in options.iter().filter(|o| o.label.to_lowercase().contains(&query)) { - let response = ui.selectable_label(current == option.label, option.label); - if let Some(handle) = option.handle { - scenario::publish_handle(handle, response.rect.center()); - } - if response.clicked() { - chosen = Some(option.value.to_owned()); - ui.close(); - } - } - if let Some(pending) = pending { - ui.label(pending); - } - }); - }) - .response; + if let Some(pending) = pending { + ui.label(pending); + } + }); + }); + let response = popup.response; + if popup.inner.is_some() && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + response.request_focus(); + } publish(ui, &response, egui::WidgetType::ComboBox); chosen } diff --git a/crates/ui-egui/src/ui_kit/gallery.rs b/crates/ui-egui/src/ui_kit/gallery.rs index 3bf12296c..1d0a28f29 100644 --- a/crates/ui-egui/src/ui_kit/gallery.rs +++ b/crates/ui-egui/src/ui_kit/gallery.rs @@ -538,25 +538,34 @@ const ELEMENTS: &[Element] = &[ ); settings_pointer_preview(ui, true, "Normal", true); }), - element!("preference_theme_rail", |ui, _| { - theme_rail( - ui, - |ui| { - for label in ["Light", "Dark", "System"] { - option_card( - ui, - label, - Some("Built in"), - label == "Light", - true, - PreferenceFigure::Theme { palette: Tokens::light().into(), system: label == "System" }, - ); - } - }, - |ui| { + element!("preference_theme_carousel", |ui, _| { + let light = ThemeSample::from_tokens(&Tokens::light()); + let dark = ThemeSample::from_tokens(&Tokens::dark()); + carousel(ui, "gallery_theme_carousel", 4, 88.0, 96.0, |ui, index| { + if index == 3 { theme_import_tile(ui, "Import…", "theme file"); - }, - ); + } else { + let label = ["Light", "Dark", "System"][index]; + picture_card( + ui, + &Card { + label, + sub: Some(if index == 2 { "Follows the OS" } else { "Built in" }), + selected: index == 0, + enabled: true, + options: None, + check: false, + aspect: 124.0 / 76.0, + figure: &|p, rect| match index { + 0 => paint_theme_thumbnail(p, rect, &light), + 1 => paint_theme_thumbnail(p, rect, &dark), + _ => paint_theme_system(p, rect, &light, &dark), + }, + }, + 88.0, + ); + } + }); }), element!("picture_card", |ui, _| { use super::preferences_figure_data as figures; @@ -732,7 +741,6 @@ const ELEMENTS: &[Element] = &[ element!("preference_option_cards", |ui, _| { ui.horizontal_wrapped(|ui| { for figure in [ - PreferenceFigure::Theme { palette: Tokens::light().into(), system: true }, PreferenceFigure::Pivot(2), PreferenceFigure::Quality(24), PreferenceFigure::Antialiasing(8), @@ -743,8 +751,22 @@ const ELEMENTS: &[Element] = &[ } }); }), + element!("settings_font_row", |ui, sample| { + settings_page(ui, |ui| { + settings_font_row(ui, "Font", |ui, part| { + if part == 0 { + named_control(ui, "Interface font", |ui| { + dropdown(ui, "gallery_preferences_font", &mut sample.selected, &["IBM Plex Sans (built in)", "Custom font"]); + }); + } else { + button(ui, "Choose font file…", Button::Normal); + button(ui, "Reset", Button::Ghost); + } + }); + font_specimen(ui, "The quick brown fox · 0123456789"); + }); + }), element!("preference_specimens", |ui, _| { - tab_accent_strip(ui); scale_specimen(ui, 1.1); status_palette_sample(ui, crate::theme::ColorVision::Deutan); colour_vision_sample(ui, &Tokens::get()); diff --git a/crates/ui-egui/src/ui_kit/layout_tests.rs b/crates/ui-egui/src/ui_kit/layout_tests.rs index eb0c99948..e239666a2 100644 --- a/crates/ui-egui/src/ui_kit/layout_tests.rs +++ b/crates/ui-egui/src/ui_kit/layout_tests.rs @@ -61,86 +61,116 @@ fn status_lines_wrap_at_form_width_and_leave_room_for_the_next_row() { } #[test] -fn theme_rail_cues_follow_hidden_content() { - use crate::ui_kit::preferences::theme_rail_cues; - assert_eq!(theme_rail_cues(0.0, 0.0), (false, false)); - assert_eq!(theme_rail_cues(0.0, 300.0), (false, true)); - assert_eq!(theme_rail_cues(150.0, 300.0), (true, true)); - assert_eq!(theme_rail_cues(300.0, 300.0), (true, false)); - assert_eq!(theme_rail_cues(0.25, 0.5), (false, false)); +fn carousel_window_clamps_offsets_and_keeps_a_card_on_narrow_pages() { + use crate::ui_kit::preferences_cards::carousel_window; + assert_eq!(carousel_window(0, 9, 280.0, 88.0, 8.0, 26.0), (0, 0)); + assert_eq!(carousel_window(6, 0, 280.0, 88.0, 8.0, 26.0), (0, 2)); + assert_eq!(carousel_window(6, 2, 280.0, 88.0, 8.0, 26.0), (2, 2)); + assert_eq!(carousel_window(6, 99, 280.0, 88.0, 8.0, 26.0), (4, 2)); + assert_eq!(carousel_window(6, 99, 100.0, 88.0, 8.0, 26.0), (5, 1)); } #[test] -fn theme_rail_arrows_scroll_one_card_and_hide_at_ends() { +fn theme_carousel_moves_one_card_and_disables_its_ends_without_selecting() { let ctx = crate::fonts::test_context(); - let t = Tokens::get(); - let width = t.form_label_width + t.space_24 + t.space_6; + let sample = ThemeSample::from_tokens(&Tokens::light()); let draw = |ui: &mut Ui| { - theme_rail( - ui, - |ui| { - for i in 0..3 { - let (rect, _) = ui.allocate_exact_size(egui::vec2(width, 80.0), egui::Sense::click()); - scenario::publish_target(&format!("test:theme:{i}"), rect); - } - }, - |_| {}, - ); + let bounds = ui.max_rect(); + carousel(ui, "test_themes", 3, 88.0, 96.0, |ui, index| { + let label = ["Light", "Dark", "System"][index]; + let response = picture_card( + ui, + &Card { + label, + sub: Some("Built in"), + selected: index == 0, + enabled: true, + options: (index == 2).then_some("Has options"), + check: false, + aspect: 124.0 / 76.0, + figure: &|p, r| paint_theme_thumbnail(p, r, &sample), + }, + 88.0, + ); + assert!(!response.clicked(), "scrolling must not select a card"); + assert!(bounds.contains_rect(response.rect)); + scenario::publish_target(&format!("test:theme:{index}"), response.rect); + }); }; for _ in 0..3 { frame(&ctx, vec![], draw); } - assert!(scenario::rect_of("prefs:theme_rail:Scroll left").is_none()); + let previous = format!("prefs:carousel:{}", crate::i18n::tr("prefs.carousel_previous")); + let next = format!("prefs:carousel:{}", crate::i18n::tr("prefs.carousel_next")); + let click = |handle: &str| { + let at = scenario::handle_at(handle).unwrap(); + frame(&ctx, pointer(at, true), draw); + frame(&ctx, pointer(at, false), draw); + frame(&ctx, vec![], draw); + }; let start = scenario::rect_of("test:theme:0").unwrap().left(); - let right = scenario::handle_at("prefs:theme_rail:Scroll right").unwrap(); - assert!((right.y - scenario::rect_of("test:theme:0").unwrap().center().y).abs() < 1.0); - frame(&ctx, pointer(right, true), draw); - frame(&ctx, pointer(right, false), draw); - frame(&ctx, vec![], draw); - let after = scenario::rect_of("test:theme:0").unwrap().left(); - assert!((start - after - width - t.space_8).abs() < 1.0); - assert!(scenario::rect_of("prefs:theme_rail:Scroll left").is_some()); - for _ in 0..4 { - if let Some(pos) = scenario::handle_at("prefs:theme_rail:Scroll right") { - frame(&ctx, pointer(pos, true), draw); - frame(&ctx, pointer(pos, false), draw); - frame(&ctx, vec![], draw); - } - } - assert!(scenario::rect_of("prefs:theme_rail:Scroll right").is_none()); - for _ in 0..4 { - if let Some(pos) = scenario::handle_at("prefs:theme_rail:Scroll left") { - frame(&ctx, pointer(pos, true), draw); - frame(&ctx, pointer(pos, false), draw); - frame(&ctx, vec![], draw); - } - } - assert!(scenario::rect_of("prefs:theme_rail:Scroll left").is_none()); + click(&previous); + assert_eq!(scenario::rect_of("test:theme:0").unwrap().left(), start, "previous is inert at the start"); + click(&next); + assert!(scenario::rect_of("test:theme:0").is_none()); + assert!((scenario::rect_of("test:theme:1").unwrap().left() - start).abs() < 1.0, "move exactly one item"); + assert!(scenario::rect_of("test:theme:2").is_some()); + click(&next); + assert!((scenario::rect_of("test:theme:1").unwrap().left() - start).abs() < 1.0, "next is inert at the end"); + click(&previous); + assert!(scenario::rect_of("test:theme:0").is_some()); + assert!(scenario::rect_of("test:theme:2").is_none()); } #[test] -fn theme_rail_chevrons_have_no_idle_box_and_show_hover_and_focus() { +fn carousel_arrows_expose_disabled_state_hover_and_keyboard_focus() { let ctx = crate::fonts::test_context(); - let t = Tokens::get(); - let rect = egui::Rect::from_min_size(egui::pos2(20.0, 20.0), egui::vec2(t.control_height, t.control_height)); + ctx.enable_accesskit(); let draw = |events| { - crate::test_support::frame(&ctx, egui::RawInput { events, focused: true, ..Default::default() }, |ui| { - crate::ui_kit::preferences::theme_rail_arrow(ui, rect, 1.0, "Scroll right"); - }) + scenario::clear_handles(); + crate::test_support::frame( + &ctx, + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(320.0, 400.0))), + events, + focused: true, + ..Default::default() + }, + |ui| { + ui.set_width(280.0); + scope(ui, |ui| { + carousel(ui, "keyboard_carousel", 3, 88.0, 96.0, |ui, i| { + let (r, _) = ui.allocate_exact_size(egui::vec2(88.0, 90.0), egui::Sense::hover()); + scenario::publish_rect(&format!("keyboard:item:{i}"), r); + }); + }); + }, + ) }; + let previous = crate::i18n::tr("prefs.carousel_previous"); + let next = crate::i18n::tr("prefs.carousel_next"); + draw(vec![]); let idle = draw(vec![]); - assert!(!idle.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Rect(_)))); - assert!(!idle.shapes.iter().any(|s| matches!(s.shape, egui::Shape::Circle(_))), "no backing until hovered"); - let hover = draw(vec![egui::Event::PointerMoved(rect.center())]); + let tree = idle.platform_output.accesskit_update.as_ref().unwrap(); + for (label, disabled) in [(previous, true), (next, false)] { + let nodes: Vec<_> = + tree.nodes.iter().filter(|(_, node)| node.role() == egui::accesskit::Role::Button && node.label() == Some(label)).collect(); + assert_eq!(nodes.len(), 1); + assert_eq!(nodes[0].1.is_disabled(), disabled); + } + let at = scenario::handle_at(&format!("prefs:carousel:{next}")).unwrap(); + let hover = draw(vec![egui::Event::PointerMoved(at)]); assert_eq!(hover.platform_output.cursor_icon, egui::CursorIcon::PointingHand); - assert!(hover.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Circle(c) if c.fill == t.hover && c.radius == rect.width() / 2.0))); - draw(pointer(rect.center(), true)); - draw(pointer(rect.center(), false)); - let focus = draw(vec![egui::Event::PointerMoved(egui::pos2(200.0, 200.0))]); + draw(vec![egui::Event::PointerMoved(egui::pos2(310.0, 390.0))]); + let focus = draw(key(egui::Key::Tab)); assert!( - !focus.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.stroke.color == t.form_primary)), - "a mouse click leaves no outline" + focus.shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Rect(r) if r.stroke.color == Tokens::get().form_primary)), + "keyboard focus uses the standard ring" ); + draw(key(egui::Key::Enter)); + draw(vec![]); + assert!(scenario::rect_of("keyboard:item:0").is_none(), "keyboard activates Next"); + assert!(scenario::rect_of("keyboard:item:2").is_some()); } #[test] diff --git a/crates/ui-egui/src/ui_kit/mod.rs b/crates/ui-egui/src/ui_kit/mod.rs index 06ea66cde..ca25d69da 100644 --- a/crates/ui-egui/src/ui_kit/mod.rs +++ b/crates/ui-egui/src/ui_kit/mod.rs @@ -93,6 +93,7 @@ pub(crate) use preferences::*; pub(crate) use preferences_assistant::*; #[allow(unused_imports, reason = "composed by the Preferences pages of #9875 to #9883")] pub(crate) use preferences_cards::*; +pub(crate) use preferences_figures::{ThemeSample, paint_theme_system, paint_theme_thumbnail}; pub(crate) use preferences_navigation::*; pub(crate) use preferences_small::*; pub(crate) use radial::{RADIAL_RADIUS, radial_menu}; @@ -137,3 +138,7 @@ pub(crate) fn fits_steadily(ui: &egui::Ui, key: impl std::hash::Hash + std::fmt: ui.data_mut(|data| data.insert_temp(id, fits)); fits } + +// Share the existing CPU rasteriser with page-level artwork regressions. +#[cfg(test)] +pub(crate) use checks::tests::raster as raster_test_shapes; diff --git a/crates/ui-egui/src/ui_kit/preferences.rs b/crates/ui-egui/src/ui_kit/preferences.rs index 8404ab02e..72f19999b 100644 --- a/crates/ui-egui/src/ui_kit/preferences.rs +++ b/crates/ui-egui/src/ui_kit/preferences.rs @@ -69,17 +69,6 @@ fn theme_option_metrics(ui: &Ui, option: &ThemeOptionRow<'_>, value: Option<&cra ThemeOptionMetrics { label, readout, reason, minimum: label + t.space_14 + control + reason } } -/// A quiet badge drawn within the existing theme card, without changing its hit target or size. -pub(crate) fn theme_options_badge(ui: &Ui, card: Rect, label: &str) { - let t = Tokens::get(); - let text = ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(t.font_micro), t.form_ink); - let size = vec2(text.size().x + t.space_8, t.space_16); - let rect = Rect::from_min_size(card.left_top() + vec2(t.space_6, t.space_6), size); - ui.painter().rect_filled(rect, t.radius_sm, t.dialog_body); - ui.painter().galley(rect.center() - text.size() / 2.0, text, t.form_ink); - scenario::publish_rect("prefs:theme_options_badge", rect); -} - /// Ordered two-column list, with composite children sharing their parent's cell and hit row. /// Returns Reset; edited values are returned through `values` for the caller's preference merge. pub(crate) fn theme_options_list( @@ -136,8 +125,15 @@ pub(crate) fn theme_options_list( .collect(); let plan = layout(&entries, dimension(ui.available_width()) - t.space_16); let mut reset = false; - let header = ui.horizontal(|ui| { + let header = ui.horizontal_wrapped(|ui| { super::text(ui, name, super::Text::Inline); + super::settings_inline_note( + ui, + &crate::i18n::format( + if options.len() == 1 { "prefs.appearance.option_count_one" } else { "prefs.appearance.option_count" }, + &[("count", &options.len().to_string())], + ), + ); if options.iter().any(|option| values.get(&option.definition.id).is_some_and(|v| *v != option.definition.default_value())) { let response = super::text_button(ui, crate::i18n::tr("prefs.theme_options_reset"), true); scenario::publish_target("prefs:theme_options_reset", response.rect); @@ -465,21 +461,6 @@ pub(crate) fn settings_card(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> e }) } -/// Only the four palette roles needed by a swatch, avoiding a copy of the full theme. -#[derive(Clone, Copy)] -pub(crate) struct ThemeSwatch { - background: Color32, - panel: Color32, - accent: Color32, - dim: Color32, - radius: u8, -} -impl From for ThemeSwatch { - fn from(t: Tokens) -> Self { - Self { background: t.viewport_top, panel: t.panel, accent: t.accent, dim: t.text_dim, radius: t.control_radius } - } -} - /// Controls and one explanatory specimen side by side, stacked on narrow viewports. pub(crate) fn settings_pair(ui: &mut Ui, controls: impl FnOnce(&mut Ui) -> R, preview: impl FnOnce(&mut Ui, R)) { if crate::prefs_search::suppress_chrome(ui) { @@ -507,116 +488,14 @@ pub(crate) fn settings_pair(ui: &mut Ui, controls: impl FnOnce(&mut Ui) -> R, } } -/// A horizontally scrollable, draggable tile rail with its import action pinned outside it. -/// The hidden scrollbar never reserves vertical space; a vertical wheel also moves the rail. -pub(crate) fn theme_rail(ui: &mut Ui, tiles: impl FnOnce(&mut Ui), import: impl FnOnce(&mut Ui)) { - if crate::prefs_search::suppress_chrome(ui) { - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing.x = Tokens::get().space_8; - tiles(ui); - }); - import(ui); - return; - } - let t = Tokens::get(); - let action_width = t.form_label_width + t.space_24 + t.space_6; - let rail_width = (dimension(ui.available_width()) - action_width - t.space_8).max(0.0); - ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = t.space_8; - ui.allocate_ui_with_layout(vec2(rail_width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| { - ui.style_mut().always_scroll_the_only_direction = true; - // This rail paints its own fully opaque, page-coloured edge cues. - ui.spacing_mut().scroll.fade.strength = 0.0; - let mut rail = egui::ScrollArea::horizontal() - .id_salt("settings_theme_rail") - .max_width(rail_width) - .auto_shrink([false, true]) - .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden) - .scroll_source(egui::scroll_area::ScrollSource { drag: egui::scroll_area::DragScroll::Always, ..Default::default() }) - .show(ui, |ui| { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = t.space_8; - tiles(ui); - }); - }); - let max_offset = (rail.content_size.x - rail.inner_rect.width()).max(0.0); - let (left, right) = theme_rail_cues(rail.state.offset.x, max_offset); - let arrow_size = t.control_height.min(rail.inner_rect.width() / 2.0); - for (visible, direction, label) in [(left, -1.0, "Scroll left"), (right, 1.0, "Scroll right")] { - if !visible || arrow_size <= 0.0 { - continue; - } - // The horizontal host starts with zero requested height; use the measured - // cards' height rather than the scroll area's initial viewport height. - let rail_rect = Rect::from_min_size(rail.inner_rect.min, vec2(rail.inner_rect.width(), rail.content_size.y)); - theme_rail_fade(ui, rail_rect, direction); - let center = pos2( - if direction < 0.0 { rail.inner_rect.left() + arrow_size / 2.0 } else { rail.inner_rect.right() - arrow_size / 2.0 }, - rail.inner_rect.top() + rail.content_size.y / 2.0, - ); - let rect = Rect::from_center_size(center, vec2(arrow_size, t.control_height)); - if theme_rail_arrow(ui, rect, direction, label).clicked() { - rail.state.offset.x = (rail.state.offset.x + direction * (action_width + t.space_8)).clamp(0.0, max_offset); - rail.state.store(ui.ctx(), rail.id); - ui.ctx().request_repaint(); - } - } - }); - ui.allocate_ui_with_layout(vec2(action_width, 0.0), egui::Layout::top_down(egui::Align::Min), import); - }); -} - -/// Ignore subpixel rounding at either end so cues do not flicker on a fully visible rail. -pub(super) fn theme_rail_cues(offset: f32, max_offset: f32) -> (bool, bool) { - (offset > 0.5, max_offset - offset > 0.5) -} - -/// Preferences pages inherit the Window card's opaque dialog_body surface. -/// Paint after the cards and before the arrows so the outer edge fully conceals content. -fn theme_rail_fade(ui: &Ui, rail: Rect, direction: f32) { - let t = Tokens::get(); - let width = (t.space_24 * 2.0 + t.space_8).min(rail.width() / 2.0); - let outer = if direction < 0.0 { rail.left() } else { rail.right() }; - let inner = outer - direction * width; - let mut mesh = egui::Mesh::default(); - for (x, color) in [(outer, t.dialog_body), (inner, Color32::TRANSPARENT)] { - mesh.colored_vertex(pos2(x, rail.top()), color); - mesh.colored_vertex(pos2(x, rail.bottom()), color); - } - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(2, 1, 3); - ui.painter().with_clip_rect(ui.clip_rect().intersect(rail)).add(mesh); -} - -pub(super) fn theme_rail_arrow(ui: &mut Ui, rect: Rect, direction: f32, label: &str) -> Response { - let t = Tokens::get(); - let response = ui.interact(rect, ui.make_persistent_id(("theme_rail_arrow", label)), Sense::click()); - if response.hovered() { - ui.painter().circle_filled(rect.center(), rect.width().min(rect.height()) / 2.0, t.hover); - } - let ink = if response.hovered() { t.form_ink } else { t.form_ink.gamma_multiply(0.65) }; - let icon = Rect::from_center_size(rect.center(), vec2(t.space_16, t.space_16)); - if direction < 0.0 { - crate::icons::paint_ink_mirrored(ui.painter(), icon, "chevron_right", ink); - } else { - crate::icons::paint_ink(ui.painter(), icon, "chevron_right", ink); - } - if response.has_focus() { - ui.painter().rect_stroke(rect, t.control_radius, Stroke::new(t.space_2, t.form_primary), egui::StrokeKind::Inside); - } - response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), crate::i18n::tr_label(label))); - scenario::publish_target(&format!("prefs:theme_rail:{label}"), rect); - response.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(crate::i18n::tr_label(label)) -} - -/// Dashed import tile matches the swatch tiles, while remaining permanently visible. +/// Dashed import tile, bounded by its carousel cell. pub(crate) fn theme_import_tile(ui: &mut Ui, label: &str, note: &str) -> Response { if crate::prefs_search::suppress_chrome(ui) && !crate::prefs_search::texts_hit(ui, &[label, note]) { return crate::prefs_search::hidden_response(ui); } let t = Tokens::get(); - let width = t.form_label_width + t.space_24 + t.space_6; - let height = t.control_height + t.space_6 * 2.0 + t.space_4 + t.space_16 * 2.0; + let width = t.space_24 * 3.0 + t.space_16; + let height = t.space_24 * 4.0; let (r, response) = ui.allocate_exact_size(vec2(width.min(dimension(ui.available_width())), height), Sense::click()); if response.hovered() { ui.painter().rect_filled(r, t.radius_lg, t.hover); @@ -668,7 +547,6 @@ pub(crate) fn settings_badge(ui: &mut Ui, text: &str, warning: bool) { #[derive(Clone, Copy)] pub(crate) enum PreferenceFigure { - Theme { palette: ThemeSwatch, system: bool }, Pivot(usize), Quality(usize), Antialiasing(u32), @@ -689,26 +567,16 @@ pub(crate) fn option_card(ui: &mut Ui, label: &str, note: Option<&str>, selected } } let t = Tokens::get(); - let theme = matches!(figure, PreferenceFigure::Theme { .. }); let width = match figure { - PreferenceFigure::Theme { .. } => t.form_label_width + t.space_24 + t.space_6, PreferenceFigure::Antialiasing(_) => t.space_24 * 3.0 + t.space_16, _ => t.form_label_width + t.space_24 * 2.0 + t.space_6, }; - let preview_height = if theme { - t.control_height - } else if matches!(figure, PreferenceFigure::Antialiasing(_)) { - t.space_24 * 3.0 - } else { - t.space_24 * 3.0 + t.space_3 - }; + let preview_height = if matches!(figure, PreferenceFigure::Antialiasing(_)) { t.space_24 * 3.0 } else { t.space_24 * 3.0 + t.space_3 }; let label_height = if matches!(figure, PreferenceFigure::ContactShading(_)) { t.space_16 * 2.0 } else { t.space_16 }; let height = preview_height + t.space_6 * 2.0 + t.space_4 + label_height + if note.is_some() { t.space_16 } else { 0.0 }; let enabled = enabled && ui.is_enabled(); - let (rect, response) = ui.allocate_exact_size( - vec2(if theme { width } else { width.min(dimension(ui.available_width())) }, height), - if enabled { Sense::click() } else { Sense::hover() }, - ); + let (rect, response) = + ui.allocate_exact_size(vec2(width.min(dimension(ui.available_width())), height), if enabled { Sense::click() } else { Sense::hover() }); let hover = enabled && response.hovered(); let ink = if !enabled { t.form_dim @@ -791,17 +659,9 @@ fn paint_preference_figure(p: &egui::Painter, rect: Rect, figure: PreferenceFigu let p = p.with_clip_rect(rect); let alpha = if enabled { 1.0 } else { 0.4 }; let accent = t.form_primary.gamma_multiply(alpha); - if let PreferenceFigure::Theme { palette, system } = figure { - theme_swatch(&p, rect, palette, false); - if system { - theme_swatch(&p, rect, Tokens::dark().into(), true); - } - return; - } p.rect_filled(rect, t.control_radius, t.viewport_top); t.container_rect(&p, rect, t.control_radius, egui::Color32::TRANSPARENT, t.dialog_rule); match figure { - PreferenceFigure::Theme { .. } => {} PreferenceFigure::Quality(sides) => { let n = sides.clamp(3, 96); let centre = rect.center(); @@ -870,60 +730,6 @@ pub(super) fn rounded_perimeter(r: Rect, radius: f32) -> Vec { .collect() } -fn clip_half_plane(vertices: Vec, side: impl Fn(Pos2) -> f32) -> Vec { - let Some(mut previous) = vertices.last().copied() else { return vertices }; - let mut clipped = Vec::with_capacity(vertices.len() + 2); - for current in vertices { - let a = side(previous); - let b = side(current); - if (a >= 0.0) != (b >= 0.0) { - clipped.push(previous + (current - previous) * (a / (a - b))); - } - if b >= 0.0 { - clipped.push(current); - } - previous = current; - } - clipped -} - -fn theme_swatch(p: &egui::Painter, r: Rect, c: ThemeSwatch, diagonal: bool) { - let boundary = rounded_perimeter(r, f32::from(c.radius)); - let fill = |mut vertices: Vec, color: Color32| { - if diagonal { - vertices = clip_half_plane(vertices, |v| (v.x - r.left()) / r.width() + (v.y - r.top()) / r.height() - 1.0); - } - for (index, &a) in boundary.iter().enumerate() { - let b = boundary.get(index + 1).copied().unwrap_or_else(|| boundary.first().copied().unwrap_or(a)); - vertices = clip_half_plane(vertices, |v| (b.x - a.x) * (v.y - a.y) - (b.y - a.y) * (v.x - a.x)); - if vertices.is_empty() { - break; - } - } - if vertices.len() >= 3 { - p.add(egui::Shape::convex_polygon(vertices, color, Stroke::NONE)); - } - }; - let rect = - |a: (f32, f32), b: (f32, f32), color| fill(vec![point(r, a.0, a.1), point(r, b.0, a.1), point(r, b.0, b.1), point(r, a.0, b.1)], color); - rect((0.0, 0.0), (1.0, 1.0), c.background); - rect((0.0, 0.0), (0.34, 1.0), c.panel); - rect((0.07, 0.29), (0.27, 0.40), c.dim); - rect((0.07, 0.54), (0.20, 0.65), c.dim); - let centre = point(r, 0.66, 0.5); - let radius = r.height() * 0.25; - fill( - (0..48) - .map(|i| { - let a = std::f32::consts::TAU * i as f32 / 48.0; - centre + vec2(a.cos(), a.sin()) * radius - }) - .collect(), - c.accent, - ); - rect((0.8, 0.39), (0.94, 0.61), c.panel); -} - #[derive(Clone, Copy)] pub(crate) struct LayoutPreview { pub compact: bool, @@ -937,25 +743,6 @@ pub(crate) fn layout_preview(ui: &mut Ui, state: LayoutPreview) { super::preferences_figures::paint_layout(ui, state); } -pub(crate) fn tab_accent_strip(ui: &mut Ui) { - if crate::prefs_search::suppress_chrome(ui) { - return; - } - let t = Tokens::get(); - super::text(ui, crate::i18n::tr("prefs.tab_accent_note"), super::Text::Hint("tab_accent")); - // Named as the ribbon names its tabs, so each reads as its tab does in every language. - let names = ["MODEL", "SURFACE", "MESH", "FORM", "SHEET METAL", "RENDER"]; - let (r, _) = ui.allocate_exact_size(vec2(dimension(ui.available_width()), t.space_24 + t.space_8), Sense::hover()); - let width = r.width() / names.len() as f32; - for (i, name) in names.iter().enumerate() { - let rect = Rect::from_min_size(r.min + vec2(i as f32 * width, 0.0), vec2((width - t.space_6).max(0.0), t.space_6)); - let accent = crate::theme::TabAccent::for_tab(&t, name); - ui.painter().rect_filled(rect, t.radius_sm, accent.color); - let label = Rect::from_min_size(pos2(rect.left(), rect.bottom() + t.space_4), vec2(rect.width(), t.space_16)); - centred_text(ui.painter(), label, &crate::workspace::tab_name(name), FontId::proportional(t.font_small), t.form_dim); - } -} - pub(crate) fn scale_specimen(ui: &mut Ui, scale: f32) { let t = Tokens::get(); let scale = if scale.is_finite() { scale.clamp(0.5, 2.5) / ui.ctx().zoom_factor().max(0.5) } else { 1.0 }; @@ -1010,6 +797,20 @@ pub(crate) fn scale_specimen(ui: &mut Ui, scale: f32) { /// Font picker and auxiliary actions share one line, with the specimen below. pub(crate) fn settings_font_row(ui: &mut Ui, label: &str, mut add: impl FnMut(&mut Ui, usize)) { let t = Tokens::get(); + if dimension(ui.available_width()) < t.form_label_width + t.space_24 * 14.0 { + super::settings_form(ui, t.form_label_width, |ui| { + let shown = super::row(ui, label, |ui| { + add(ui, 0); + ui.is_visible() + }); + if shown { + super::below_row_control(ui, label, ui.available_width(), |ui| { + ui.horizontal_wrapped(|ui| add(ui, 1)); + }); + } + }); + return; + } super::settings_form(ui, t.form_label_width, |ui| { super::row(ui, label, |ui| { let actions = t.space_24 * 8.0 + t.space_8; @@ -1083,6 +884,7 @@ pub(crate) fn status_palette_sample(ui: &mut Ui, mode: ColorVision) { let label = crate::i18n::tr(label); let galley = ui.painter().layout_no_wrap(label.to_owned(), crate::fonts::semibold(t.font_small), ink); let (r, _) = ui.allocate_exact_size(vec2(galley.size().x + t.space_24 + t.space_16, t.space_24), Sense::hover()); + scenario::publish_rect(&format!("prefs:status_sample:{label}"), r); ui.painter().rect_filled(r, t.radius_xl, fill); crate::icons::paint_ink( ui.painter(), @@ -1104,72 +906,20 @@ pub(crate) const COLOUR_VISION_SAMPLE: [&str; 6] = /// colours of `t` (the preference passes the mode being chosen, #7152). The six cells share one /// responsive, clipped area. pub(crate) fn colour_vision_sample(ui: &mut egui::Ui, t: &Tokens) { - let width = (dimension(ui.available_width()) / COLOUR_VISION_SAMPLE.len() as f32).min(t.space_24 * 3.0); - let line_width = t.space_4; - let (area, _) = ui.allocate_exact_size(egui::vec2(width * COLOUR_VISION_SAMPLE.len() as f32, t.space_24 * 2.0 + t.space_2), egui::Sense::hover()); + if crate::prefs_search::suppress_chrome(ui) { + return; + } + let count = COLOUR_VISION_SAMPLE.len() as f32; + let gap = t.space_8.min(dimension(ui.available_width()) / (count - 1.0)); + let width = ((dimension(ui.available_width()) - gap * (count - 1.0)) / count).min(t.space_24 * 3.0 + t.space_12); + let figure_height = t.space_24 + t.space_16 + t.space_4; + let (area, _) = ui.allocate_exact_size(vec2(width * count + gap * (count - 1.0), figure_height + t.space_3 + t.space_16), Sense::hover()); + scenario::publish_rect("prefs:colour_vision_samples", area); let p = ui.painter_at(area); - let line = |c| egui::Stroke::new(line_width, c); for (i, name) in COLOUR_VISION_SAMPLE.iter().enumerate() { - let cell = egui::Rect::from_min_size( - area.min + egui::vec2(width * i as f32, 0.0), - egui::vec2((width - t.space_8).max(0.0), t.control_height + t.space_4), - ); - let (a, b) = (cell.left_center() + egui::vec2(t.space_8, 0.0), cell.right_center() - egui::vec2(t.space_8, 0.0)); - match i { - 0 | 1 => { - p.rect_filled(cell, t.radius_sm, t.viewport_top); - p.line_segment([a, b], line(if i == 0 { t.sketch_locked } else { t.sketch_projected })); - } - 2 => { - // X along and Y up from one corner, as the view triad draws them. - p.rect_filled(cell, t.radius_sm, t.viewport_top); - let o = cell.left_bottom() + egui::vec2(t.space_12, -(t.space_4 + t.space_3)); - p.line_segment([o, egui::pos2(cell.right() - t.space_10, o.y)], line(t.axis_x)); - p.line_segment([o, egui::pos2(o.x, cell.top() + t.space_6)], line(t.axis_y)); - } - 3 => { - // Dashed, as the flat pattern draws them. - p.rect_filled(cell, t.radius_sm, t.viewport_top); - for (dy, c) in [(-(t.space_4 + t.space_3), t.bend_up), (t.space_4 + t.space_3, t.bend_down)] { - p.extend(egui::Shape::dashed_line( - &[a + egui::vec2(0.0, dy), b + egui::vec2(0.0, dy)], - line(c), - t.space_8, - t.space_3 + t.space_2, - )); - } - } - 4 => { - // The three bands of Draft Analysis; in a mode the negative one is striped. - let w = cell.width() / 3.0; - for (k, c) in t.analysis.draft.iter().enumerate() { - let band = egui::Rect::from_min_size(cell.min + egui::vec2(w * k as f32, 0.0), egui::vec2(w, cell.height())); - p.rect_filled(band, 0.0, crate::theme::srgb(*c)); - if k == 2 && t.analysis.hatch { - let stripes = p.with_clip_rect(band); - let dark = crate::theme::srgb(c.map(|x| x * 0.6)); - let mut x = band.left() - band.height(); - while x < band.right() { - stripes.line_segment( - [egui::pos2(x, band.bottom()), egui::pos2(x + band.height(), band.top())], - egui::Stroke::new(2.0, dark), - ); - x += t.space_6 + t.space_3; - } - } - } - } - _ => { - // A failed feature on the timeline. - p.rect( - cell.shrink2(egui::vec2(t.space_10, t.space_3)), - t.radius_sm, - t.timeline_item_error, - egui::Stroke::new(1.0, t.error), - egui::StrokeKind::Inside, - ); - } - } + let cell = egui::Rect::from_min_size(area.min + vec2((width + gap) * i as f32, 0.0), vec2(width, figure_height)); + scenario::publish_rect(&format!("prefs:colour_vision_sample:{i}"), cell); + super::preferences_figure_ops::paint_colour_vision(&p, cell, i, t); centred_text( &p, Rect::from_min_size(cell.left_bottom() + vec2(0.0, t.space_3), vec2(cell.width(), t.space_16)), diff --git a/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs b/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs index cd8aa00c8..94d73c869 100644 --- a/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs +++ b/crates/ui-egui/src/ui_kit/preferences_figure_ops.rs @@ -160,6 +160,8 @@ const MAX_POINTS: usize = 512; struct Ctx<'a> { t: &'a Tokens, sample: Option<&'a ThemeSample>, + /// Only the Appearance samples interpret the legacy SVG colour roles semantically. + colour_vision: Option, origin: Pos2, scale: f32, } @@ -167,7 +169,23 @@ struct Ctx<'a> { impl Ctx<'_> { fn ink(&self, ink: Ink, a: f32) -> Color32 { let t = self.t; - let c = match ink { + let semantic = match (self.colour_vision, ink) { + (Some(0), Ink::Cv0) => Some(t.sketch_locked), + (Some(1), Ink::Cv1) => Some(t.sketch_projected), + (Some(2), Ink::Cv2 | Ink::AxisX) => Some(t.axis_x), + (Some(2), Ink::Cv0 | Ink::AxisY) => Some(t.axis_y), + (Some(2), Ink::AxisZ) => Some(t.axis_z), + (Some(3), Ink::Cv1) => Some(t.bend_up), + (Some(3), Ink::Cv3) => Some(t.bend_down), + (Some(4), Ink::Cv3) => Some(crate::theme::srgb(t.analysis.draft[0])), + (Some(4), Ink::Cv1) => Some(crate::theme::srgb(t.analysis.draft[1])), + (Some(4), Ink::Cv4) => Some(crate::theme::srgb(t.analysis.draft[2])), + (Some(4), Ink::Black) => Some(crate::theme::srgb(t.analysis.draft[2].map(|c| c * 0.6))), + (Some(5), Ink::Cv2) => Some(t.error), + (Some(5), Ink::NoteFill) => Some(t.timeline_item_error), + _ => None, + }; + let c = semantic.unwrap_or_else(|| match ink { Ink::Ground => t.figure_ground, Ink::Line => t.figure_line, Ink::Top => t.figure_face_top, @@ -198,7 +216,7 @@ impl Ctx<'_> { Ink::Cv3 => t.bend_up, Ink::Cv4 => t.bend_down, Ink::Slot(n) => self.sample.and_then(|s| s.slots.get(n as usize).copied()).unwrap_or(Color32::TRANSPARENT), - }; + }); if a >= 1.0 { c } else { c.gamma_multiply(a.clamp(0.0, 1.0)) } } @@ -217,6 +235,33 @@ impl Ctx<'_> { /// Paints `figure` into `rect`, scaled to fit and centred, with `Tokens::get()` colours. pub(super) fn paint(p: &Painter, rect: Rect, figure: &Figure, sample: Option<&ThemeSample>, clip: Option<&[[f32; 2]]>) { + paint_with_tokens(p, rect, figure, sample, clip, &Tokens::get(), None); +} + +/// Reuse the six canonical figures with the semantic palette being previewed, without global state. +pub(super) fn paint_colour_vision(p: &Painter, rect: Rect, index: usize, t: &Tokens) { + use super::preferences_figure_data as figures; + let figure = match index { + 0 => &figures::COLOUR_VISION_FIXED, + 1 => &figures::COLOUR_VISION_PROJECTED, + 2 => &figures::COLOUR_VISION_AXES, + 3 => &figures::COLOUR_VISION_BENDS, + 4 => &figures::COLOUR_VISION_DRAFT, + 5 => &figures::COLOUR_VISION_FAILED, + _ => return, + }; + paint_with_tokens(p, rect, figure, None, None, t, Some(index)); +} + +fn paint_with_tokens( + p: &Painter, + rect: Rect, + figure: &Figure, + sample: Option<&ThemeSample>, + clip: Option<&[[f32; 2]]>, + t: &Tokens, + colour_vision: Option, +) { let size = rect.size(); if !rect.min.is_finite() || !size.is_finite() || size.x < 1.0 || size.y < 1.0 || size.x > MAX_SIDE || size.y > MAX_SIDE { return; @@ -227,8 +272,7 @@ pub(super) fn paint(p: &Painter, rect: Rect, figure: &Figure, sample: Option<&Th } let scale = (size.x / fw).min(size.y / fh); let fitted = Rect::from_center_size(rect.center(), vec2(fw * scale, fh * scale)); - let t = Tokens::get(); - let ctx = Ctx { t: &t, sample, origin: fitted.min, scale }; + let ctx = Ctx { t, sample, colour_vision, origin: fitted.min, scale }; let p = p.with_clip_rect(fitted.intersect(p.clip_rect())); let outer: Option> = clip.map(|c| c.iter().map(|&q| ctx.at(q)).collect()); // Nested clips are inside one another in every figure, so the innermost one is the clip. diff --git a/crates/ui-egui/tests/scenarios/colour_vision_setting.json b/crates/ui-egui/tests/scenarios/colour_vision_setting.json index b7c263fb2..7845d099f 100644 --- a/crates/ui-egui/tests/scenarios/colour_vision_setting.json +++ b/crates/ui-egui/tests/scenarios/colour_vision_setting.json @@ -7,7 +7,9 @@ {"call": "ui.scroll", "params": {"x": 1000, "y": 500, "delta": -5000}}, {"call": "ui.inspect", "params": {}}, {"expect": {"shown": "Color vision", "prefs": {"dialog": "Appearance"}, "same_width": "prefs:window"}}, - {"widget": "Deutan"}, + {"click": {"handle": "prefs:color_vision:protan"}}, + {"expect": {"prefs": {"color_vision": "protan"}}}, + {"click": {"handle": "prefs:color_vision:deutan"}}, {"expect": {"prefs": {"color_vision": "deutan"}, "same_width": "prefs:window"}}, {"widget": "Cancel"}, {"expect": {"prefs": {"dialog": null, "color_vision": "off"}}}, @@ -15,7 +17,7 @@ {"click": {"handle": "prefs:page:Appearance"}}, {"call": "ui.scroll", "params": {"x": 1000, "y": 500, "delta": -5000}}, {"call": "ui.inspect", "params": {}}, - {"widget": "Tritan"}, + {"click": {"handle": "prefs:color_vision:tritan"}}, {"widget": "OK"}, {"expect": {"prefs": {"dialog": null, "color_vision": "tritan"}}}, {"key": "Comma", "cmd": true}, diff --git a/crates/ui-egui/tests/scenarios/prefs_theme_files.json b/crates/ui-egui/tests/scenarios/prefs_theme_files.json index 76a5b1ae6..3cad8ec18 100644 --- a/crates/ui-egui/tests/scenarios/prefs_theme_files.json +++ b/crates/ui-egui/tests/scenarios/prefs_theme_files.json @@ -1,10 +1,12 @@ [ - {"note": "#2255: theme tiles offer the built-in themes; choosing one applies it immediately, and Cancel restores the previous theme."}, + {"note": "#2255: theme carousel offers the actual built-in themes; choosing one applies it immediately, and Cancel restores the previous theme."}, {"click": {"handle": "titlebar:preferences"}}, {"expect": {"prefs": {"dialog": "General", "theme": "dark", "dark": true}}}, {"click": {"handle": "prefs:page:Appearance"}}, + {"expect": {"shown_handles": ["prefs:theme:light"]}}, {"click": {"handle": "prefs:theme:light"}}, {"expect": {"prefs": {"theme": "light", "dark": false}, "shown_handles": ["prefs:theme"]}}, + {"expect": {"shown_handles": ["prefs:theme:gruvbox-dark"]}}, {"click": {"handle": "prefs:theme:gruvbox-dark"}}, {"expect": {"prefs": {"theme": "gruvbox-dark", "dark": true}}}, {"click": {"handle": "prefs:theme:light"}}, diff --git a/crates/ui-egui/tests/scenarios/prefs_viewport_theme.json b/crates/ui-egui/tests/scenarios/prefs_viewport_theme.json index 1e5ee20ce..86622ade6 100644 --- a/crates/ui-egui/tests/scenarios/prefs_viewport_theme.json +++ b/crates/ui-egui/tests/scenarios/prefs_viewport_theme.json @@ -1,13 +1,13 @@ [ - {"note": "#4146: under the theme tiles, Viewport draws the 3D view in the Light or Dark theme's colours whatever the window uses; it applies at once, and Cancel puts it back."}, + {"note": "#4146: under the theme carousel, 3D view colors draws the 3D view in the Light or Dark theme's colours whatever the window uses; it applies at once, and Cancel puts it back."}, {"click": {"handle": "titlebar:preferences"}}, {"click": {"handle": "prefs:page:Appearance"}}, {"expect": {"prefs": {"theme": "dark", "dark": true, "viewport_theme": "theme", "viewport_dark": true}}}, - {"widget": "Light", "near": "Viewport"}, + {"widget": "Light", "near": "3D view colors"}, {"expect": {"prefs": {"theme": "dark", "dark": true, "viewport_theme": "light", "viewport_dark": false}}}, - {"widget": "Dark", "near": "Viewport"}, + {"widget": "Dark", "near": "3D view colors"}, {"expect": {"prefs": {"viewport_theme": "dark", "viewport_dark": true}}}, - {"widget": "Light", "near": "Viewport"}, + {"widget": "Light", "near": "3D view colors"}, {"widget": "Cancel"}, {"expect": {"prefs": {"dialog": null, "theme": "dark", "viewport_theme": "theme", "viewport_dark": true}}} ]