diff --git a/Cargo.lock b/Cargo.lock index cff5ae6a9b2..22589d9adab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3997,6 +3997,7 @@ dependencies = [ "serde", "serde_json", "toml", + "unicode-segmentation", "web-time", ] diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 8e7b77f42f3..40c4dce3267 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -20,6 +20,8 @@ lightcraft-develop = { workspace = true } lightcraft-pipeline = { workspace = true } lightcraft-catalog = { workspace = true } web-time = { workspace = true } +# file names are shortened between letters, not inside one (readout::elide_middle); the engine has it already +unicode-segmentation = "1.13" lightcraft-engine = { workspace = true } lightcraft-slideshow = { workspace = true } lightcraft-preview = { workspace = true } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 79390f13647..129d4c44e64 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -169,7 +169,7 @@ "{stage}… {:.0}%": "{stage}… {:.0}%", "{verb} {n} Photo{}": "{verb}: {n} Foto{}", "{weekday}, {day}": "{weekday}, {day}.", - "{weekday}, {day} {month} {year}": "{weekday}, {day}.{month:02}.{year}", + "{weekday}, {day} {month} {year}": "{weekday}, {day:02}.{month:02}.{year}", "{what} merge added": "{what}-Zusammenfügung hinzugefügt", "{what} merge failed: {e}": "{what}-Zusammenfügung fehlgeschlagen: {e}", "{year}": "{year}", diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 64628822031..27ed495cbcb 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -611,7 +611,7 @@ fn whats_new_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { let l = line.trim_end(); if let Some(h) = l.strip_prefix("### ") { ui.add_space(6.0); - ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(12.5)).color(t.text)); + ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.body_strong()).color(t.text)); } else if let Some(h) = l.strip_prefix("## ") { ui.add_space(8.0); ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(14.0)).color(t.text)); @@ -696,7 +696,7 @@ fn all_metadata_body(ui: &mut egui::Ui, t: &Tokens, dlg: &mut Dialog) { } for (g, list) in &groups { ui.add_space(6.0); - ui.label(egui::RichText::new(g).font(t.semibold(12.5)).color(t.text)); + ui.label(egui::RichText::new(g).font(t.body_strong()).color(t.text)); egui::Grid::new(format!("meta-{g}")).num_columns(2).spacing([16.0, 3.0]).striped(true).show(ui, |ui| { for (n, v) in list { ui.label(egui::RichText::new(n).color(t.text_dim)); @@ -740,7 +740,7 @@ fn smart_rules_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: .color(t.text_dim), ); } else { - ui.label(egui::RichText::new(crate::i18n::tr("Fix the marked rules to save this album.")).color(t.caution)); + ui.label(egui::RichText::new(crate::i18n::tr("Fix the marked rules to save this album.")).color(t.text_caution())); } } @@ -952,7 +952,7 @@ fn rename_person_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, co *confirm = true; } if let Some(why) = plan.block { - ui.label(egui::RichText::new(crate::i18n::tr(why)).color(t.caution)); + ui.label(egui::RichText::new(crate::i18n::tr(why)).color(t.text_caution())); } else { ui.label( egui::RichText::new(crate::i18n::tr_format!( @@ -969,7 +969,7 @@ fn rename_person_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, co "“{to}” is already a person. Combining them makes one person; Undo separates them again.", to = to.trim() )) - .color(t.caution), + .color(t.text_caution()), ); let r = ui.checkbox(merge, crate::i18n::tr("Combine with the existing person")); crate::widgets::register(ui, "check:personMerge", r.rect); @@ -1473,7 +1473,9 @@ fn export_apple_photos_rows(ui: &mut egui::Ui, t: &Tokens, opts: &mut ExportOpti ) }); ui.label( - egui::RichText::new(crate::i18n::tr("The first time, macOS asks whether LightCraft may control Photos.")).size(11.0).color(t.text_dim), + egui::RichText::new(crate::i18n::tr("The first time, macOS asks whether LightCraft may control Photos.")) + .font(t.caption()) + .color(t.text_dim), ); } } @@ -1728,7 +1730,7 @@ fn about_body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, dlg: &mut 1 => crate::credits::contributors_ui(app, ui), 2 => crate::credits::models_ui(ui), _ => { - ui.label(egui::RichText::new("LightCraft").font(t.semibold(20.0)).color(t.text)); + ui.label(egui::RichText::new("LightCraft").font(t.display_strong()).color(t.text)); ui.label(crate::i18n::tr_format!("Version {} — a clean-room, pure-Rust photo library and raw developer.", env!("CARGO_PKG_VERSION"))); ui.label(crate::i18n::tr_format!( "MIT OR Apache-2.0. Fonts: {} (OFL). Icons: original.", diff --git a/crates/ui-egui/src/dialogs/faces.rs b/crates/ui-egui/src/dialogs/faces.rs index 1811ec0a947..3052091d9b7 100644 --- a/crates/ui-egui/src/dialogs/faces.rs +++ b/crates/ui-egui/src/dialogs/faces.rs @@ -154,7 +154,7 @@ pub fn setup_banner(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 6)).show(ui, |ui| { ui.horizontal_wrapped(|ui| { - ui.label(RichText::new(message).font(t.font(12.5)).color(t.text_dim)); + ui.label(RichText::new(message).font(t.label()).color(t.text_dim)); let r = ui.button(button); register(ui, "faces:setup", r.rect); if r.clicked() { @@ -299,7 +299,7 @@ pub fn settings_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { }); // what is wrong with the user's own catalog (catalog.json in the models folder), if anything for e in list["catalog"]["errors"].as_array().into_iter().flatten().filter_map(Value::as_str).take(3) { - ui.add(egui::Label::new(RichText::new(format!("catalog.json: {e}")).font(t.font(11.5)).color(t.caution)).wrap()); + ui.add(egui::Label::new(RichText::new(format!("catalog.json: {e}")).font(t.caption()).color(t.text_caution())).wrap()); } if let Some(d) = all.iter().find(|m| m["role"] == "detector") { ui.add_space(4.0); @@ -335,15 +335,15 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, ui.label(RichText::new(size).color(t.text_dim)); } if selected { - ui.label(RichText::new(crate::i18n::tr("in use")).color(t.accent)); + ui.label(RichText::new(crate::i18n::tr("in use")).color(t.text_link())); } else if installed { ui.label(RichText::new(crate::i18n::tr("installed")).color(t.text_dim)); } }); - ui.label(RichText::new(licence_line(m)).font(t.font(11.5)).color(if m["licence"]["commercial"] == "yes" { + ui.label(RichText::new(licence_line(m)).font(t.caption()).color(if m["licence"]["commercial"] == "yes" { t.text_dim } else { - t.caution + t.text_caution() })); // how fast it is, as times faster than a ResNet-100 model (milliseconds would depend on the computer), // with whether it passed its test when it has been installed @@ -356,7 +356,7 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, None => (speed.map(str::to_string), true), }; if let Some(line) = line { - ui.label(RichText::new(line).font(t.font(11.5)).color(if ok { t.text_dim } else { t.caution })); + ui.label(RichText::new(line).font(t.caption()).color(if ok { t.text_dim } else { t.text_caution() })); } match (dl_state, dl) { (Some("running"), Some(d)) => { @@ -375,12 +375,12 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, (Some("done"), _) => { ui.horizontal(|ui| { crate::progress::spinner(ui, 12.0); - ui.label(RichText::new(crate::i18n::tr("Downloaded and checked. Installing…")).font(t.font(11.5)).color(t.text_dim)); + ui.label(RichText::new(crate::i18n::tr("Downloaded and checked. Installing…")).font(t.caption()).color(t.text_dim)); }); } (Some("failed"), Some(d)) => { let why = sentence(d["error"].as_str().unwrap_or("The download failed")); - ui.add(egui::Label::new(RichText::new(why).font(t.font(11.5)).color(t.caution)).wrap()); + ui.add(egui::Label::new(RichText::new(why).font(t.caption()).color(t.text_caution())).wrap()); } _ => {} } @@ -450,7 +450,7 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info let kind = info["kind"].as_str().unwrap_or("unsupported"); let file = info["fileName"].as_str().unwrap_or(""); if kind == "unsupported" { - ui.label(RichText::new(crate::i18n::tr("This file cannot be used yet")).font(t.semibold(13.5)).color(t.caution)); + ui.label(RichText::new(crate::i18n::tr("This file cannot be used yet")).font(t.body_strong()).color(t.text_caution())); ui.add( egui::Label::new( RichText::new(sentence(info["reason"].as_str().unwrap_or("It is not a face recognition model LightCraft understands"))) @@ -485,7 +485,7 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info ); } let commercial = m["licence"]["commercial"].as_str().unwrap_or("unknown"); - ui.label(RichText::new(licence_line(m)).font(t.semibold(12.5)).color(if commercial == "yes" { t.text } else { t.caution })); + ui.label(RichText::new(licence_line(m)).font(t.body_strong()).color(if commercial == "yes" { t.text } else { t.text_caution() })); let notice = m["licence"]["notice"].as_str().unwrap_or(""); if !notice.is_empty() { ui.add(egui::Label::new(RichText::new(notice).color(t.text_label)).wrap()); @@ -517,7 +517,7 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info } else { "The model is kept on this computer only. LightCraft never uploads or shares it." }; - ui.label(RichText::new(closing).font(t.font(11.5)).color(t.text_dim)); + ui.label(RichText::new(closing).font(t.caption()).color(t.text_dim)); } /// Pressing Download: the model's terms first, in the same dialog as a model file. Accepting them starts the download; @@ -683,7 +683,7 @@ pub fn name_editor( } } if let Some(label) = setup.short() { - let b = ui.add(egui::Button::new(RichText::new(label).font(t.font(12.0)).color(t.accent)).frame(false)); + let b = ui.add(egui::Button::new(RichText::new(label).font(t.font(12.0)).color(t.text_link())).frame(false)); register(ui, "faces:setup", b.rect); if b.clicked() { outcome = Editor::Setup; diff --git a/crates/ui-egui/src/dialogs/import/body.rs b/crates/ui-egui/src/dialogs/import/body.rs index 8f82ae51dd7..46c0481ec6c 100644 --- a/crates/ui-egui/src/dialogs/import/body.rs +++ b/crates/ui-egui/src/dialogs/import/body.rs @@ -166,7 +166,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { } _ => "Add in place: the library references the files where they are; nothing is copied or moved.", })) - .color(if d.copy && d.move_files { t.caution } else { t.text_dim }) + .color(if d.copy && d.move_files { t.text_caution() } else { t.text_dim }) .small(), ); register(ui, "label:importModeHelp", r.rect); @@ -224,7 +224,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDialog) { let t = Tokens::get(ui.ctx()); match lightcraft_engine::rename::folder_template_error(&d.folder_template) { Some(e) => { - ui.label(egui::RichText::new(e).color(t.caution)); + ui.label(egui::RichText::new(e).color(t.text_caution())); } None => unknown_tags_warning(ui, &d.folder_template), } @@ -437,8 +437,9 @@ fn candidate_cell(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &mut ImportDial p.rect_filled(br, 3.0, Color32::from_rgba_unmultiplied(170, 60, 50, 220)); p.galley(br.min + vec2(4.0, 2.0), g, Color32::WHITE); } - let name = if c.name.chars().count() > 18 { format!("{}…", c.name.chars().take(17).collect::()) } else { c.name.clone() }; - p.text(pos2(rect.left() + 2.0, img.bottom() + 9.0), Align2::LEFT_CENTER, name, t.font(10.5), if ok { t.text_label } else { t.text_dim }); + // (shortened in the middle to the cell's width: the end of a name is the number of the frame) + let name = crate::readout::elide_middle(&c.name, rect.width() - 4.0, |s| p.layout_no_wrap(s.to_string(), t.caption(), t.text_label).size().x); + p.text(pos2(rect.left() + 2.0, img.bottom() + 9.0), Align2::LEFT_CENTER, name, t.caption(), if ok { t.text_label } else { t.text_dim }); let tip = format!( "{}\n{} × {} · {} · {:.1} MB{}", c.path, diff --git a/crates/ui-egui/src/dialogs/import/tags.rs b/crates/ui-egui/src/dialogs/import/tags.rs index 1ae10ca0212..0c78cba9e9f 100644 --- a/crates/ui-egui/src/dialogs/import/tags.rs +++ b/crates/ui-egui/src/dialogs/import/tags.rs @@ -3,7 +3,7 @@ use super::{Tokens, register}; /// Reserve the actual translated tag button width beside a template field. pub(crate) fn tag_field_width(ui: &egui::Ui) -> f32 { let t = Tokens::get(ui.ctx()); - let galley = ui.painter().layout_no_wrap(crate::i18n::tr("Tags").to_string(), t.semibold(11.5), t.text); + let galley = ui.painter().layout_no_wrap(crate::i18n::tr("Tags").to_string(), t.caption_strong(), t.text); (ui.available_width() - (galley.size().x + 18.0).max(37.0) - ui.spacing().item_spacing.x).max(80.0) } @@ -32,7 +32,7 @@ pub(crate) fn unknown_tags_warning(ui: &mut egui::Ui, template: &str) { if unknown.len() == 1 { "s" } else { "" }, s = s ); - ui.label(egui::RichText::new(text).color(Tokens::get(ui.ctx()).caution)); + ui.label(egui::RichText::new(text).color(Tokens::get(ui.ctx()).text_caution())); } } diff --git a/crates/ui-egui/src/dialogs/keymap.rs b/crates/ui-egui/src/dialogs/keymap.rs index 3ebe2505705..e99513e9f58 100644 --- a/crates/ui-egui/src/dialogs/keymap.rs +++ b/crates/ui-egui/src/dialogs/keymap.rs @@ -43,7 +43,7 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { d.insert_temp(search_id, search.clone()); d.insert_temp(all_id, show_all); }); - ui.label(RichText::new(crate::i18n::tr("Click a shortcut, then press the new keys (Esc cancels).")).size(11.0).color(t.text_dim)); + ui.label(RichText::new(crate::i18n::tr("Click a shortcut, then press the new keys (Esc cancels).")).font(t.caption()).color(t.text_dim)); ui.add_space(4.0); let needle = search.trim().to_lowercase(); @@ -129,7 +129,7 @@ fn row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, b: &Bindable, sc: apply(app, ui.ctx(), serde_json::json!({"id": b.id, "reset": true})); } }); - ui.label(RichText::new(b.id).size(10.5).color(t.text_dim)); + ui.label(RichText::new(b.id).font(t.caption()).color(t.text_dim)); ui.end_row(); } @@ -177,7 +177,7 @@ fn fixed_keys(app: &LightcraftApp, ui: &mut egui::Ui, t: &Tokens, mac: bool, nee return; } ui.add_space(8.0); - ui.label(RichText::new(crate::i18n::tr("Fixed keys")).font(t.semibold(12.5)).color(t.text)); + ui.label(RichText::new(crate::i18n::tr("Fixed keys")).font(t.body_strong()).color(t.text)); // keys saved for commands this build knows: an entry for an unknown command takes no key let taken: Vec<_> = shortcuts::saved_keys(&app.ui.settings.keymap).map(|(_, k)| k).collect(); egui::Grid::new("shortcuts-fixed").striped(true).num_columns(2).spacing([12.0, 4.0]).show(ui, |ui| { diff --git a/crates/ui-egui/src/dialogs/print_view.rs b/crates/ui-egui/src/dialogs/print_view.rs index c9af1d776d6..209c7b040e2 100644 --- a/crates/ui-egui/src/dialogs/print_view.rs +++ b/crates/ui-egui/src/dialogs/print_view.rs @@ -612,7 +612,7 @@ fn preview(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, s let painter = ui.painter_at(area); painter.rect_filled(area, 4.0, t.canvas); let Ok((pw, ph)) = st.layout.page_size() else { - painter.text(area.center(), Align2::CENTER_CENTER, crate::i18n::tr("This page setup is not valid"), t.font(13.0), t.caution); + painter.text(area.center(), Align2::CENTER_CENTER, crate::i18n::tr("This page setup is not valid"), t.font(13.0), t.text_caution()); return; }; let g = &st.guides; @@ -692,7 +692,7 @@ fn preview(app: &mut LightcraftApp, ui: &mut Ui, t: &Tokens, pu: &mut PrintUi, s if package { ui.label(egui::RichText::new(format!("{} {}", st.layout.cells.len(), crate::i18n::tr("cells"))).color(t.text_dim)); if st.layout.has_overlaps() { - ui.label(egui::RichText::new(crate::i18n::tr("cells overlap")).color(t.caution)); + ui.label(egui::RichText::new(crate::i18n::tr("cells overlap")).color(t.text_caution())); } } }); diff --git a/crates/ui-egui/src/dialogs/rules_editor.rs b/crates/ui-egui/src/dialogs/rules_editor.rs index 67f5e4bb496..685439ffda4 100644 --- a/crates/ui-egui/src/dialogs/rules_editor.rs +++ b/crates/ui-egui/src/dialogs/rules_editor.rs @@ -296,7 +296,7 @@ fn small_button_width(ui: &egui::Ui, text: &str) -> f32 { fn problem_note(ui: &mut egui::Ui, problem: Option<&Problem>, salt: &str) { let Some(p) = problem else { return }; let t = Tokens::get(ui.ctx()); - let r = ui.label(RichText::new(format!("⚠ {}", crate::i18n::problem_text(p))).color(t.caution).small()); + let r = ui.label(RichText::new(format!("⚠ {}", crate::i18n::problem_text(p))).color(t.text_caution()).small()); register(ui, format!("ruleProblem:{salt}"), r.rect); } diff --git a/crates/ui-egui/src/dialogs/settings/appearance.rs b/crates/ui-egui/src/dialogs/settings/appearance.rs index f714a97e62f..c0dc722dd9a 100644 --- a/crates/ui-egui/src/dialogs/settings/appearance.rs +++ b/crates/ui-egui/src/dialogs/settings/appearance.rs @@ -60,7 +60,7 @@ fn theme_card(ui: &mut egui::Ui, t: &Tokens, card: ThemeCar ui.horizontal(|ui| { ui.label(RichText::new(crate::i18n::tr(title)).font(t.semibold(12.0)).color(t.text)); if active { - ui.label(RichText::new(crate::i18n::tr("In Use")).size(11.0).color(t.accent)); + ui.label(RichText::new(crate::i18n::tr("In Use")).font(t.caption()).color(t.text_link())); } }); let shown = options.iter().find(|(v, _)| v == value).or(options.first()).map(|(_, k)| *k).unwrap_or_default(); diff --git a/crates/ui-egui/src/dialogs/settings/display.rs b/crates/ui-egui/src/dialogs/settings/display.rs index a5b1974d21c..369c6eef3f2 100644 --- a/crates/ui-egui/src/dialogs/settings/display.rs +++ b/crates/ui-egui/src/dialogs/settings/display.rs @@ -41,13 +41,13 @@ pub(super) fn display_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens } }); if let Some(e) = &app.display_error { - ui.label(RichText::new(e).size(11.0).color(t.reject)); + ui.label(RichText::new(e).font(t.caption()).color(t.text_error())); } if let Some(d) = ¤t { let info = d.describe(); if !screen { row(ui, t, crate::i18n::tr("File"), |ui| { - path_label(ui, "settingsDisplayFile", &d.path, egui::FontId::proportional(11.0), t.text_dim, 0.0); + path_label(ui, "settingsDisplayFile", &d.path, t.caption(), t.text_dim, 0.0); }); } row(ui, t, crate::i18n::tr("Type"), |ui| { @@ -61,7 +61,7 @@ pub(super) fn display_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens let p = &info["primaries"]; let xy = |(k, l): (&str, &str)| format!("{l} {:.3}, {:.3}", p[k][0].as_f64().unwrap_or(0.0), p[k][1].as_f64().unwrap_or(0.0)); let text = [("red", "R"), ("green", "G"), ("blue", "B")].map(xy).join(" "); - ui.label(RichText::new(text).size(11.0).color(t.text_dim)); + ui.label(RichText::new(text).font(t.caption()).color(t.text_dim)); }); } hint( diff --git a/crates/ui-egui/src/dialogs/settings/performance.rs b/crates/ui-egui/src/dialogs/settings/performance.rs index e65402c200f..d65631dc0b5 100644 --- a/crates/ui-egui/src/dialogs/settings/performance.rs +++ b/crates/ui-egui/src/dialogs/settings/performance.rs @@ -20,7 +20,7 @@ pub(super) fn performance_tab(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &To // One line, the whole text on hover: the reason can be a long driver message (no adapter // among the backends …), and the GPU state is process-wide, so it may change between frames; // a hint that wrapped would move every control below it under the pointer. - ui.add(egui::Label::new(RichText::new(crate::i18n::tr(&status)).size(11.0).color(t.text_dim)).truncate()).on_hover_text(&status); + ui.add(egui::Label::new(RichText::new(crate::i18n::tr(&status)).font(t.caption()).color(t.text_dim)).truncate()).on_hover_text(&status); row(ui, t, crate::i18n::tr("Preview size"), |ui| { let opts: Vec<(u32, String)> = PREVIEW_LIMITS.iter().map(|e| (*e, if *e == 0 { crate::i18n::tr("Automatic").to_string() } else { format!("{e} px") })).collect(); @@ -107,7 +107,7 @@ fn smart_previews(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { "settingsSmartFolder", &path, egui::TextStyle::Body.resolve(ui.style()), - if available { t.text } else { t.reject }, + if available { t.text } else { t.text_error() }, if custom { 0.0 } else { label_width(ui, "(library default)", egui::TextStyle::Body) }, ); if !custom { diff --git a/crates/ui-egui/src/dialogs/settings/slide_layout.rs b/crates/ui-egui/src/dialogs/settings/slide_layout.rs index 2fc55abdae9..a3e5dba5586 100644 --- a/crates/ui-egui/src/dialogs/settings/slide_layout.rs +++ b/crates/ui-egui/src/dialogs/settings/slide_layout.rs @@ -196,7 +196,7 @@ pub fn preview(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, max_h: f3 if !tpl.description.is_empty() { said = format!("{said}\n{}", tpl.description); } - let galley = ui.painter().layout(said, t.font(11.0), Color32::WHITE, (room.width() - 8.0).max(1.0)); + let galley = ui.painter().layout(said, t.caption(), Color32::WHITE, (room.width() - 8.0).max(1.0)); let band = Rect::from_min_size( pos2(room.left(), (room.bottom() - galley.size().y - 6.0).max(room.top())), vec2(room.width(), galley.size().y + 6.0), diff --git a/crates/ui-egui/src/dialogs/settings/slide_overlays.rs b/crates/ui-egui/src/dialogs/settings/slide_overlays.rs index fe72ed6a6a0..66096e0d51e 100644 --- a/crates/ui-egui/src/dialogs/settings/slide_overlays.rs +++ b/crates/ui-egui/src/dialogs/settings/slide_overlays.rs @@ -293,6 +293,6 @@ pub fn sections(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { hint(ui, t, "The export watermark, drawn on the photo and sized relative to it."); } for warning in app.session.slide_overlays.warnings() { - ui.label(RichText::new(warning).size(11.0).color(t.caution)); + ui.label(RichText::new(warning).font(t.caption()).color(t.text_caution())); } } diff --git a/crates/ui-egui/src/dialogs/settings/slide_templates.rs b/crates/ui-egui/src/dialogs/settings/slide_templates.rs index d32cb05524a..14ba8606279 100644 --- a/crates/ui-egui/src/dialogs/settings/slide_templates.rs +++ b/crates/ui-egui/src/dialogs/settings/slide_templates.rs @@ -116,7 +116,7 @@ fn template_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, tpl: &Te } if pending(&ctx) == Some(Pending::Delete(tpl.id.clone())) { ui.horizontal(|ui| { - ui.label(RichText::new(crate::i18n::tr_format!("Delete “{name}”?", name = name)).color(t.caution)); + ui.label(RichText::new(crate::i18n::tr_format!("Delete “{name}”?", name = name)).color(t.text_caution())); if crate::widgets::text_button(ui, "slideshowTemplateDeleteConfirm", "Delete", false).clicked() { set_pending(&ctx, None); act(app, &ctx, "slideshow.templates.delete", json!({"id": tpl.id}), |_| String::new()); @@ -194,7 +194,7 @@ fn menu(app: &mut LightcraftApp, ui: &mut egui::Ui, tpl: &Template, name: &str) /// A group heading inside the browser. fn group(ui: &mut egui::Ui, t: &Tokens, text: &str) { ui.add_space(2.0); - ui.label(RichText::new(crate::i18n::tr(text)).size(11.0).color(t.text_dim)); + ui.label(RichText::new(crate::i18n::tr(text)).font(t.caption()).color(t.text_dim)); } /// The Templates section. @@ -265,10 +265,10 @@ pub fn section(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { } // files that couldn't be read for p in listing.problems.iter().take(4) { - ui.label(RichText::new(crate::i18n::tr_format!("Skipped {problem}", problem = p)).size(11.0).color(t.caution)); + ui.label(RichText::new(crate::i18n::tr_format!("Skipped {problem}", problem = p)).font(t.caption()).color(t.text_caution())); } if listing.problems.len() > 4 { let more = listing.problems.len() - 4; - ui.label(RichText::new(crate::i18n::tr_format!("…and {more} more", more = more)).size(11.0).color(t.caution)); + ui.label(RichText::new(crate::i18n::tr_format!("…and {more} more", more = more)).font(t.caption()).color(t.text_caution())); } } diff --git a/crates/ui-egui/src/dialogs/settings/slide_titles.rs b/crates/ui-egui/src/dialogs/settings/slide_titles.rs index 79d0dfd3f4a..150cc1fd88a 100644 --- a/crates/ui-egui/src/dialogs/settings/slide_titles.rs +++ b/crates/ui-egui/src/dialogs/settings/slide_titles.rs @@ -163,6 +163,6 @@ pub fn sections(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) { ); let warnings = s.warnings(&app.session.slide_overlays); for w in warnings { - ui.label(egui::RichText::new(w).size(11.0).color(t.caution)); + ui.label(egui::RichText::new(w).font(t.caption()).color(t.text_caution())); } } diff --git a/crates/ui-egui/src/dialogs/settings/widgets.rs b/crates/ui-egui/src/dialogs/settings/widgets.rs index 7607b125168..2d7159c73f8 100644 --- a/crates/ui-egui/src/dialogs/settings/widgets.rs +++ b/crates/ui-egui/src/dialogs/settings/widgets.rs @@ -51,7 +51,7 @@ pub(super) fn button_width(ui: &egui::Ui, text: &str) -> f32 { pub(crate) fn heading(ui: &mut egui::Ui, t: &Tokens, text: &str) { ui.add_space(4.0); - ui.label(RichText::new(crate::i18n::tr(text)).font(t.semibold(12.5)).color(t.text)); + ui.label(RichText::new(crate::i18n::tr(text)).font(t.body_strong()).color(t.text)); } pub(crate) fn row(ui: &mut egui::Ui, t: &Tokens, label: &str, add: impl FnOnce(&mut egui::Ui) -> R) -> R { @@ -74,7 +74,7 @@ pub(crate) fn row(ui: &mut egui::Ui, t: &Tokens, label: &str, add: impl FnOnc } pub(crate) fn hint(ui: &mut egui::Ui, t: &Tokens, text: &str) { - ui.label(RichText::new(crate::i18n::tr(text)).size(11.0).color(t.text_dim)); + ui.label(RichText::new(crate::i18n::tr(text)).font(t.caption()).color(t.text_dim)); } /// A checkbox addressable as `check:{id}`; true when toggled. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9db7035c1d0..c1050a05e96 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -73,6 +73,7 @@ pub use widgets::text_field; mod app; mod caches; mod clock; +mod readout; mod services; #[cfg(test)] diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index ed9c45fb5d8..e5ab4b1cdc3 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -31,7 +31,7 @@ pub mod strip; pub mod topbar; pub mod unnamed; -use egui::{Align2, Rect, pos2, vec2}; +use egui::{Rect, pos2, vec2}; use crate::LightcraftApp; pub use crate::dialogs; @@ -100,7 +100,7 @@ pub fn toast(app: &mut LightcraftApp, ctx: &egui::Context) { let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("toast"))); // long messages (a save warning, the web build's notices) wrap within the canvas let wrap = (canvas.width() - 80.0).clamp(200.0, 720.0); - let (background, foreground) = label.map(crate::theme::label_toast_colors).unwrap_or((egui::Color32::from_black_alpha(200), t.text)); + let (background, foreground) = label.map(crate::theme::label_toast_colors).unwrap_or((Tokens::photo_shade(), Tokens::on_photo())); let foreground = foreground.gamma_multiply(fade); let galley = painter.layout(text, t.font(14.0), foreground, wrap); let size = vec2(galley.size().x + 40.0, (galley.size().y + 22.0).max(40.0)); @@ -116,8 +116,20 @@ pub fn toast(app: &mut LightcraftApp, ctx: &egui::Context) { pub fn empty_message(ui: &egui::Ui, rect: Rect, title: &str, body: &str) { let t = Tokens::get(ui.ctx()); let p = ui.painter(); - p.text(rect.center() - vec2(0.0, 12.0), Align2::CENTER_CENTER, crate::i18n::tr(title), t.semibold(18.0), t.text_label); - p.text(rect.center() + vec2(0.0, 14.0), Align2::CENTER_CENTER, crate::i18n::tr(body), t.font(13.0), t.text_dim); + // Both wrap inside the view (a sentence used to run out of a narrow one), centred line by + // line, the two as one block about the middle. + let wrap = (rect.width() - 48.0).max(80.0); + let centred = |text: &str, font: egui::FontId, color: egui::Color32| { + let mut job = egui::text::LayoutJob::simple(text.to_string(), font, color, wrap); + job.halign = egui::Align::Center; + p.layout_job(job) + }; + let title = centred(crate::i18n::tr(title), t.display_strong(), t.text_label); + let body = centred(crate::i18n::tr(body), t.body(), t.text_dim); + let top = rect.center().y - (title.size().y + 6.0 + body.size().y) / 2.0; + let below = top + title.size().y + 6.0; + p.galley(pos2(rect.center().x, top), title, t.text_label); + p.galley(pos2(rect.center().x, below), body, t.text_dim); } /// A button under an empty state's message: the command it runs, its label, and the id it is diff --git a/crates/ui-egui/src/panels/activity.rs b/crates/ui-egui/src/panels/activity.rs index dffdd1c4d33..0f1e16f3f49 100644 --- a/crates/ui-egui/src/panels/activity.rs +++ b/crates/ui-egui/src/panels/activity.rs @@ -95,7 +95,7 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { if hidden > 0 || (app.activity_expanded && tasks.len() > MAX_ROWS) { ui.add_space(4.0); let text = if hidden > 0 { tr_format!("+{n} more", n = hidden) } else { tr("Show less").to_string() }; - let r = ui.add(egui::Label::new(RichText::new(text).font(t.font(11.0)).color(t.accent)).sense(Sense::click())); + let r = ui.add(egui::Label::new(RichText::new(text).font(t.font(11.0)).color(t.text_link())).sense(Sense::click())); register(ui, "activity:more", r.rect); toggle = r.clicked(); } @@ -126,7 +126,7 @@ fn row(ui: &mut egui::Ui, t: &Tokens, task: &TaskInfo, width: f32) -> bool { ui.allocate_ui_with_layout(vec2(label_w, 18.0), Layout::left_to_right(Align::Center), |ui| { // the whole width, so the cross lands at the right edge however short the name ui.set_width(label_w); - ui.add(egui::Label::new(RichText::new(tr(&task.label)).font(t.font(12.5)).color(t.text)).truncate()); + ui.add(egui::Label::new(RichText::new(tr(&task.label)).font(t.body()).color(t.text)).truncate()); }); if cross { let (rect, resp) = ui.allocate_exact_size(vec2(CROSS, CROSS), Sense::click()); diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index 9b9a2367340..beb8129293e 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -340,7 +340,7 @@ fn photo_tile(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, slot: Slo x += g.size().x + 10.0; } let name = photo.copy_name.as_ref().map(|c| format!("{} ({c})", photo.file_name)).unwrap_or(photo.file_name.clone()); - let g = pt.layout_no_wrap(name, t.font(11.5), t.text_dim); + let g = pt.layout_no_wrap(name, t.caption(), t.text_dim); let name_w = g.size().x; if x + name_w + 110.0 < cap.right() { pt.galley(pos2(x, cap.center().y - g.size().y / 2.0), g, t.text_dim); diff --git a/crates/ui-egui/src/panels/denoise.rs b/crates/ui-egui/src/panels/denoise.rs index b72df10b2e8..cd61bae8662 100644 --- a/crates/ui-egui/src/panels/denoise.rs +++ b/crates/ui-egui/src/panels/denoise.rs @@ -176,7 +176,7 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, am let state = app.session.denoise_photo_state(id); let pad = egui::Margin { left: 24, right: 22, top: 0, bottom: 6 }; let note = |ui: &mut egui::Ui, text: &str, color: egui::Color32| { - ui.add(egui::Label::new(RichText::new(crate::i18n::tr(text)).size(11.0).color(color)).wrap()); + ui.add(egui::Label::new(RichText::new(crate::i18n::tr(text)).font(t.caption()).color(color)).wrap()); }; match state { PhotoState::NotApplicable | PhotoState::Ready => {} @@ -232,7 +232,7 @@ pub fn detail_status(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, am } PhotoState::Failed { why, unsupported } => { egui::Frame::NONE.inner_margin(pad).show(ui, |ui| { - let color = if unsupported { t.text_dim } else { t.caution }; + let color = if unsupported { t.text_dim } else { t.text_caution() }; note(ui, &sentence(&why), color); if !unsupported { let r = ui.small_button(crate::i18n::tr("Try again")); @@ -468,22 +468,22 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, ui.label(RichText::new(size).color(t.text_dim)); } if selected { - ui.label(RichText::new(tr("in use")).color(t.accent)); + ui.label(RichText::new(tr("in use")).color(t.text_link())); } else if installed { ui.label(RichText::new(tr("installed")).color(t.text_dim)); } }); - ui.label(RichText::new(licence_line(m)).font(t.font(11.5)).color(if m["licence"]["commercial"] == "yes" { + ui.label(RichText::new(licence_line(m)).font(t.caption()).color(if m["licence"]["commercial"] == "yes" { t.text_dim } else { - t.caution + t.text_caution() })); match m["accepted"]["selfTest"].as_object() { Some(test) if test.get("ok").and_then(Value::as_bool) == Some(true) => { - ui.label(RichText::new(tr("Tested and works on this computer")).font(t.font(11.5)).color(t.text_dim)); + ui.label(RichText::new(tr("Tested and works on this computer")).font(t.caption()).color(t.text_dim)); } Some(_) => { - ui.label(RichText::new(tr("Failed its last test")).font(t.font(11.5)).color(t.caution)); + ui.label(RichText::new(tr("Failed its last test")).font(t.caption()).color(t.text_caution())); } None => {} } @@ -504,12 +504,12 @@ fn model_row(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, m: &Value, (Some("done" | "installing"), _) => { ui.horizontal(|ui| { crate::progress::spinner(ui, 12.0); - ui.label(RichText::new(tr("Downloaded and checked. Installing…")).font(t.font(11.5)).color(t.text_dim)); + ui.label(RichText::new(tr("Downloaded and checked. Installing…")).font(t.caption()).color(t.text_dim)); }); } (Some("failed"), Some(d)) => { let why = sentence(d["error"].as_str().unwrap_or("The download failed")); - ui.add(egui::Label::new(RichText::new(why).font(t.font(11.5)).color(t.caution)).wrap()); + ui.add(egui::Label::new(RichText::new(why).font(t.caption()).color(t.text_caution())).wrap()); } _ => {} } @@ -697,7 +697,7 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info let kind = info["kind"].as_str().unwrap_or("unsupported"); let file = info["fileName"].as_str().unwrap_or(""); if kind == "unsupported" { - ui.label(RichText::new(tr("This file cannot be used yet")).font(t.semibold(13.5)).color(t.caution)); + ui.label(RichText::new(tr("This file cannot be used yet")).font(t.body_strong()).color(t.text_caution())); ui.add( egui::Label::new( RichText::new(sentence(tr(info["reason"].as_str().unwrap_or("It is not a denoise model LightCraft understands")))) @@ -733,7 +733,7 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info ); } let commercial = m["licence"]["commercial"].as_str().unwrap_or("unknown"); - ui.label(RichText::new(licence_line(m)).font(t.semibold(12.5)).color(if commercial == "yes" { t.text } else { t.caution })); + ui.label(RichText::new(licence_line(m)).font(t.body_strong()).color(if commercial == "yes" { t.text } else { t.text_caution() })); let notice = m["licence"]["notice"].as_str().unwrap_or(""); if !notice.is_empty() { ui.add(egui::Label::new(RichText::new(notice).color(t.text_label)).wrap()); @@ -763,5 +763,5 @@ pub fn model_dialog(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, info } else { "The model is kept on this computer only. LightCraft never uploads or shares it." }; - ui.label(RichText::new(tr(closing)).font(t.font(11.5)).color(t.text_dim)); + ui.label(RichText::new(tr(closing)).font(t.caption()).color(t.text_dim)); } diff --git a/crates/ui-egui/src/panels/detail.rs b/crates/ui-egui/src/panels/detail.rs index 2b58595d2a1..0c6a3f7d10d 100644 --- a/crates/ui-egui/src/panels/detail.rs +++ b/crates/ui-egui/src/panels/detail.rs @@ -293,7 +293,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { shown = draw(Slot::Before, img_rect, canvas); // on the photo itself, so it gets the hover label's dark pill to stay readable over light // pictures; painted after the window renders below, which would cover it zoomed in - let g = p.layout_no_wrap(crate::i18n::tr("Before").to_string(), t.font(12.0), Color32::WHITE); + let g = p.layout_no_wrap(crate::i18n::tr("Before").to_string(), t.label(), Tokens::on_photo()); before_badge = Some((label_badge_rect(img_rect, canvas, g.size(), badge_top_inset), g)); } else if let Some((_key, label)) = &hover_key && let Some(tex) = app.renderer.textures.get(&Slot::Hover).filter(|t| t.photo == id) @@ -582,7 +582,7 @@ fn status_pill( fn proof_surround(app: &LightcraftApp, p: &egui::Painter, t: &Tokens, canvas: Rect) { p.rect_filled(canvas, 0.0, Color32::from_gray(238)); let label = crate::i18n::tr_format!("Proof Preview · {}", app.ui.proof.space.label()); - p.text(pos2(canvas.right() - 16.0, canvas.top() + 14.0), Align2::RIGHT_CENTER, label, t.font(12.5), Color32::from_gray(60)); + p.text(pos2(canvas.right() - 16.0, canvas.top() + 14.0), Align2::RIGHT_CENTER, label, t.label(), Color32::from_gray(60)); } /// Request the window renders, remember which sides have one, and release the slot of a side without. @@ -795,15 +795,15 @@ fn draw_slot(app: &LightcraftApp, p: &egui::Painter, id: PhotoId, ppp: f32, slot fn draw_hover(p: &egui::Painter, t: &Tokens, tex: &crate::render::Tex, label: &str, [img_rect, canvas]: [Rect; 2], badge_top_inset: f32) { let hover_rect = fit_texture_rect(img_rect, tex.size); p.image(tex.tex.id(), hover_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - let g = p.layout_no_wrap(label.to_string(), t.font(12.0), Color32::WHITE); + let g = p.layout_no_wrap(label.to_string(), t.label(), Tokens::on_photo()); let bg = label_badge_rect(hover_rect, canvas, g.size(), badge_top_inset); paint_badge(p, bg, g); } /// A label on a dark pill. fn paint_badge(p: &egui::Painter, bg: Rect, g: std::sync::Arc) { - p.rect_filled(bg, 4.0, Color32::from_black_alpha(160)); - p.galley(bg.min + vec2(8.0, 4.0), g, Color32::WHITE); + p.rect_filled(bg, 4.0, Tokens::photo_shade()); + p.galley(bg.min + vec2(8.0, 4.0), g, Tokens::on_photo()); } /// No photo is active: the empty-library message if the library is empty, else "No photo selected". @@ -1212,14 +1212,17 @@ mod tests { #[test] fn film_labels_cut_on_characters_not_bytes() { - // the name from #266: byte 13 falls inside '限' - assert_eq!(film_label("202407層三限定訂閱圖(4)"), "202407層三限定訂閱圖…"); - assert_eq!(film_label("写真"), "写真"); + // (a character is a unit wide here; the cell has room for 14) + let label = |name: &str| film_label(name, 14.0, |s| s.chars().count() as f32); + // the name from #266: no cut falls inside a character + assert_eq!(label("202407層三限定訂閱圖(4)"), "202407…定訂閱圖(4)"); + assert_eq!(label("写真"), "写真"); // exactly 14 characters (42 bytes) is shown whole - assert_eq!(film_label("一二三四五六七八九十一二三四"), "一二三四五六七八九十一二三四"); - assert_eq!(film_label("IMG_20240712_153012"), "IMG_20240712_…"); - assert_eq!(film_label("DSC_0001"), "DSC_0001"); - assert_eq!(film_label(""), ""); + assert_eq!(label("一二三四五六七八九十一二三四"), "一二三四五六七八九十一二三四"); + // the number of the frame stays + assert_eq!(label("IMG_20240712_153012"), "IMG_20…_153012"); + assert_eq!(label("DSC_0001"), "DSC_0001"); + assert_eq!(label(""), ""); } /// With the photo flipped, the crop box's corners reach the screen mirrored; the dimming diff --git a/crates/ui-egui/src/panels/detail/crop.rs b/crates/ui-egui/src/panels/detail/crop.rs index f88b23fdd85..100cd3f71c5 100644 --- a/crates/ui-egui/src/panels/detail/crop.rs +++ b/crates/ui-egui/src/panels/detail/crop.rs @@ -304,7 +304,7 @@ pub(super) fn rotate_cursor_turn(pts: &[Pos2], q: Pos2, inside: bool) -> f32 { fn angle_readout(ui: &egui::Ui, at: Pos2, angle: f64, bounds: Rect) { let t = Tokens::get(ui.ctx()); let p = top_painter(ui, "crop-angle-readout"); - let galley = p.layout_no_wrap(crop_angle_label(angle), t.font(12.5), Color32::WHITE); + let galley = p.layout_no_wrap(crop_angle_label(angle), t.body(), Color32::WHITE); let rect = readout_rect(at, galley.size() + vec2(12.0, 6.0), bounds); p.rect_filled(rect, 4.0, Color32::from_black_alpha(170)); p.galley(rect.min + vec2(6.0, 3.0), galley, Color32::WHITE); diff --git a/crates/ui-egui/src/panels/detail/filmstrip.rs b/crates/ui-egui/src/panels/detail/filmstrip.rs index 4a0de28cf24..e2732d3889f 100644 --- a/crates/ui-egui/src/panels/detail/filmstrip.rs +++ b/crates/ui-egui/src/panels/detail/filmstrip.rs @@ -44,10 +44,11 @@ pub(super) fn navigator(app: &mut LightcraftApp, ui: &mut egui::Ui, canvas: Rect // ------------------------------------------------------------------------ filmstrip -/// A filmstrip cell's file-name label: names longer than 14 characters are cut to 13 and an -/// ellipsis. Counts characters, not bytes, so a CJK name is never cut inside a character (#266). -pub(super) fn film_label(name: &str) -> String { - if name.chars().nth(14).is_some() { format!("{}…", name.chars().take(13).collect::()) } else { name.to_string() } +/// A file name over a filmstrip cell, in the room left of the format: shortened in the middle +/// when it is too long, so that the number at its end stays ("IMG_20…_153012"). It lost its end +/// after 13 characters, however wide they were. +pub(super) fn film_label(name: &str, room: f32, width: impl Fn(&str) -> f32) -> String { + crate::readout::elide_middle(name, room, width) } /// Draw the horizontal filmstrip in `r`: selectable thumbnail cells with names and format when @@ -65,7 +66,7 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { let ppp = ui.ctx().pixels_per_point(); if ids.is_empty() { let why = if app.session.filter != Default::default() { "No photos match the filters (View → Clear Filters)" } else { "No photos" }; - ui.painter().text(r.center(), Align2::CENTER_CENTER, why, t.font(12.5), t.text_dim); + ui.painter().text(r.center(), Align2::CENTER_CENTER, why, t.label(), t.text_dim); return; } let mut child = ui.new_child(egui::UiBuilder::new().max_rect(r.shrink2(vec2(0.0, 4.0)))); @@ -108,12 +109,19 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { } else { t.canvas }; - p.rect_filled(cr, 0.0, crate::theme::label_background(base, label, selected)); + let fill = crate::theme::label_background(base, label, selected); + p.rect_filled(cr, 0.0, fill); + // (a selected cell is lighter than the canvas the dim text is made for, or darker, and + // a colour label tints any cell; under the pointer the fill is see-through, and what + // the text is on is that fill over the strip) + let dim = t.legible(t.text_dim, t.canvas.blend(fill), 4.5); let names = app.ui.settings.film_names; if let Some(ph) = app.session.catalog.photo(*id).filter(|_| names) { let name = ph.file_name.rsplit_once('.').map(|(n, _)| n).unwrap_or(&ph.file_name); - p.text(pos2(cr.left() + 8.0, cr.top() + 10.0), Align2::LEFT_CENTER, film_label(name), t.font(10.0), t.text_dim); - p.text(pos2(cr.right() - 8.0, cr.top() + 10.0), Align2::RIGHT_CENTER, &ph.format, t.semibold(8.5), t.text_dim); + let format = p.text(pos2(cr.right() - 8.0, cr.top() + 10.0), Align2::RIGHT_CENTER, &ph.format, t.micro_strong(), dim); + let room = format.left() - 6.0 - (cr.left() + 8.0); + let shown = film_label(name, room, |s| p.layout_no_wrap(s.to_string(), t.micro(), dim).size().x); + p.text(pos2(cr.left() + 8.0, cr.top() + 10.0), Align2::LEFT_CENTER, shown, t.micro(), dim); } let img_area = Rect::from_min_max(cr.min + vec2(10.0, 22.0), cr.max - vec2(10.0, 8.0)); crate::panels::grid::request_thumb(app, *id, (256.0 * ppp.min(2.0) / 2.0) as usize * 2, 8); @@ -137,13 +145,13 @@ pub(crate) fn filmstrip(app: &mut LightcraftApp, ui: &mut egui::Ui, r: Rect) { if app.ui.settings.film_badges && let Some(ph) = app.session.catalog.photo(*id) { - film_badges(p, &t, fr, ph); + film_badges(p, fr, ph); } if let Some(st) = app.session.catalog.stack_of(*id) { let collapsed = st.collapsed; let text = if collapsed { st.photos.len().to_string() } else { format!("{}/{}", st.position(*id).unwrap_or(0) + 1, st.photos.len()) }; - let g = p.layout_no_wrap(text, t.semibold(9.5), Color32::WHITE); + let g = p.layout_no_wrap(text, t.micro_strong(), Color32::WHITE); let br = Rect::from_min_size(fr.min + vec2(3.0, 3.0), vec2(g.size().x + 22.0, 15.0)); // like the grid's badge: a click expands / collapses the stack let badge = ui.interact(br, egui::Id::unique(("film-stack-badge", id.0)), Sense::click()).on_hover_text(if collapsed { @@ -204,24 +212,42 @@ pub(crate) fn film_spoken(file_name: &str, failed: bool) -> String { } /// Rating, flag and edited badges along a filmstrip thumbnail's bottom edge (Settings → Interface). -fn film_badges(p: &egui::Painter, t: &Tokens, fr: Rect, ph: &lightcraft_catalog::Photo) { +fn film_badges(p: &egui::Painter, fr: Rect, ph: &lightcraft_catalog::Photo) { use crate::icons::{Icon, paint}; use lightcraft_catalog::Flag; - let edited = ph.is_edited(); - if ph.rating == 0 && ph.flag == Flag::None && !edited { + if ph.rating == 0 && ph.flag == Flag::None && !ph.is_edited() { return; } let bar = Rect::from_min_max(pos2(fr.left(), fr.bottom() - 15.0), fr.right_bottom()); - p.rect_filled(bar, 0.0, Color32::from_black_alpha(130)); + // (a picture has no theme: its marks are in one light ink on a shade as wide as they are, + // not in the theme's star and label colours, which are dark in the light themes) + let ink = Tokens::on_photo(); + let clipped = p.with_clip_rect(bar.intersect(p.clip_rect())); + let p = &clipped; + let shade = |from: f32, to: f32| { + if to > from { + p.rect_filled(Rect::from_min_max(pos2(from, bar.top() + 1.0), pos2(to, bar.bottom() - 1.0)), 3.0, Tokens::photo_shade()); + } + }; + let flag_w = if ph.flag == Flag::None { 0.0 } else { 12.0 }; + // (on a narrow thumbnail the stars close up, so that the flag after them is still inside the bar it is clipped to) + let crate::widgets::FilmMarks { pitch, edited } = crate::widgets::film_marks(bar.width(), ph.rating as usize, flag_w, ph.is_edited()); + let marks_w = ph.rating as f32 * pitch + flag_w; + if marks_w > 0.0 { + shade(bar.left() + 1.0, (bar.left() + 5.0 + marks_w).min(bar.right())); + } + if edited { + shade((bar.right() - 16.0).max(bar.left()), bar.right() - 1.0); + } let y = bar.center().y; let mut x = bar.left() + 3.0; - x += crate::rating::paint_rating(p, pos2(x, y), ph.rating, crate::rating::RatingSize::Small, t.star) + 2.0; + x += crate::rating::paint_rating_spaced(p, pos2(x, y), ph.rating, crate::rating::RatingSize::Small, pitch, ink) + 2.0; match ph.flag { - Flag::Pick => paint(p, Rect::from_min_size(pos2(x, y - 5.0), vec2(10.0, 10.0)), Icon::FlagPickFilled, t.pick), - Flag::Reject => paint(p, Rect::from_min_size(pos2(x, y - 5.0), vec2(10.0, 10.0)), Icon::FlagReject, t.reject), + Flag::Pick => paint(p, Rect::from_min_size(pos2(x, y - 5.0), vec2(10.0, 10.0)), Icon::FlagPickFilled, ink), + Flag::Reject => paint(p, Rect::from_min_size(pos2(x, y - 5.0), vec2(10.0, 10.0)), Icon::FlagReject, Tokens::on_photo_reject()), Flag::None => {} } if edited { - paint(p, Rect::from_min_size(pos2(bar.right() - 13.0, y - 5.0), vec2(10.0, 10.0)), Icon::Sliders, t.text_label); + paint(p, Rect::from_min_size(pos2(bar.right() - 13.0, y - 5.0), vec2(10.0, 10.0)), Icon::Sliders, ink); } } diff --git a/crates/ui-egui/src/panels/detail/info.rs b/crates/ui-egui/src/panels/detail/info.rs index da5ae1bed66..bb571a720cf 100644 --- a/crates/ui-egui/src/panels/detail/info.rs +++ b/crates/ui-egui/src/panels/detail/info.rs @@ -228,20 +228,8 @@ fn info_line(field: crate::state::LoupeInfoField, photo: &lightcraft_catalog::Ph F::CaptureDate => pretty_date(photo.captured.as_deref().unwrap_or(&photo.imported)), F::Dimensions => format!("{} × {}", photo.width, photo.height), F::Exposure => { - let mut exp = Vec::new(); - if !m.shutter.is_empty() { - exp.push(format!("{} s", m.shutter)); - } - if let Some(a) = m.aperture { - exp.push(format!("f/{a:.1}")); - } - if let Some(i) = m.iso { - exp.push(format!("ISO {i}")); - } - if let Some(f) = m.focal_mm { - exp.push(format!("{f:.0} mm")); - } - if exp.is_empty() { "No exposure information".into() } else { exp.join(" ") } + let exp = crate::readout::exposure(m); + if exp.is_empty() { "No exposure information".into() } else { exp.join(" · ") } } F::Camera => m.camera.clone(), F::Lens => m.lens.clone(), diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index fb47fc148a1..71909a0230f 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -67,8 +67,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let (hr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 40.0), Sense::hover()); ui.painter().text(pos2(hr.left() + 24.0, hr.bottom() - 10.0), Align2::LEFT_CENTER, crate::i18n::tr("Edit"), t.semibold(15.0), t.text); egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 8, bottom: 14 }).show(ui, |ui| { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 8.0; + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(8.0, 6.0); if text_button(ui, "auto", crate::i18n::tr("Auto"), false).clicked() { let _ = app.run("develop.auto", json!({})); app.toast(ui.ctx(), crate::i18n::tr("Auto settings applied")); @@ -84,8 +84,15 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { { let _ = app.run("develop.hdr", json!({"enabled": !d.hdr.enabled})); } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if text_button(ui, "reset", crate::i18n::tr("Reset"), false) + // (Reset at the right of the row when it has room there, else on a row of its own: in + // German it is "Zurücksetzen" and lay over HDR) + let reset = crate::i18n::tr("Reset"); + if ui.available_size_before_wrap().x < crate::widgets::text_button_width(ui, reset) { + ui.end_row(); + } + // (a layout of the width left on this row, 24 pt tall: after `end_row`, the new row) + ui.allocate_ui_with_layout(vec2(ui.available_size_before_wrap().x, 24.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { + if text_button(ui, "reset", reset, false) .on_hover_text(reset_tip(&app.ui.settings.keymap, ui.ctx().os() == egui::os::OperatingSystem::Mac)) .clicked() { @@ -110,7 +117,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if app.session.auto_sync && n > 1 { egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 0, bottom: 10 }).show(ui, |ui| { ui.horizontal(|ui| { - ui.label(egui::RichText::new(crate::i18n::tr_format!("Auto Sync: edits apply to {n} photos", n = n)).color(t.accent).size(12.0)); + ui.label( + egui::RichText::new(crate::i18n::tr_format!("Auto Sync: edits apply to {n} photos", n = n)).color(t.text_link()).font(t.label()), + ); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if text_button(ui, "autoSyncOff", crate::i18n::tr("Turn Off"), false).clicked() { let _ = app.run("develop.autoSync", json!({"on": false})); @@ -128,7 +137,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { // a long name is cut short before Browse Profiles: a wider row would widen the whole panel's // content, and the sliders below would run past its edge let max = ui.available_width() - 28.0 - ui.spacing().item_spacing.x; - let r = crate::widgets::dropdown_within(ui, "profile", crate::i18n::profile_label(&d.profile.id, name), t.font(15.0), t.text_label, max); + let r = crate::widgets::dropdown_within(ui, "profile", crate::i18n::profile_label(&d.profile.id, name), t.body(), t.text_label, max); let below = r.rect.bottom(); egui::Popup::menu(&r).show(|ui| profile_menu(app, ui, &d, below)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -198,7 +207,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 2, bottom: 2 }).show(ui, |ui| { ui.horizontal(|ui| { ui.label(egui::RichText::new(crate::i18n::tr("White Balance")).font(t.font(13.0)).color(t.text_dim)); - let r = crate::widgets::dropdown(ui, "wbMode", crate::i18n::tr(d.wb.mode.label()), t.font(14.0), t.text_label); + let r = crate::widgets::dropdown(ui, "wbMode", crate::i18n::tr(d.wb.mode.label()), t.body(), t.text_label); egui::Popup::menu(&r).show(|ui| { for m in WbMode::ALL { if m == WbMode::Custom { @@ -337,7 +346,9 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { } if lp && !has_lens { ui.label( - egui::RichText::new(crate::i18n::tr("No lens data embedded in this file.")).size(11.0).color(Tokens::get(ui.ctx()).text_dim), + egui::RichText::new(crate::i18n::tr("No lens data embedded in this file.")) + .font(t.caption()) + .color(Tokens::get(ui.ctx()).text_dim), ); } }); diff --git a/crates/ui-egui/src/panels/edit/histogram.rs b/crates/ui-egui/src/panels/edit/histogram.rs index 085fbda5d12..4222316b110 100644 --- a/crates/ui-egui/src/panels/edit/histogram.rs +++ b/crates/ui-egui/src/panels/edit/histogram.rs @@ -86,8 +86,8 @@ pub(super) fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) bar(a + 1.0, z - 1.0, Color32::from_rgb(c[0], c[1], c[2])); } let y = plot.bottom() + 18.0; - p.text(pos2((plot.left() + x0) / 2.0, y), Align2::CENTER_CENTER, crate::i18n::tr("SDR"), t.font(12.5), t.text_label); - p.text(pos2((x0 + plot.right()) / 2.0, y), Align2::CENTER_CENTER, crate::i18n::tr("HDR"), t.font(12.5), t.text_label); + p.text(pos2((plot.left() + x0) / 2.0, y), Align2::CENTER_CENTER, crate::i18n::tr("SDR"), t.body(), t.text_label); + p.text(pos2((x0 + plot.right()) / 2.0, y), Align2::CENTER_CENTER, crate::i18n::tr("HDR"), t.body(), t.text_label); let info = Rect::from_center_size(pos2(plot.right() - 16.0, y), vec2(14.0, 14.0)); paint(p, info, Icon::Info, t.text_label); ui.interact(info, egui::Id::unique("hdrHistogramInfo"), Sense::hover()).on_hover_text(crate::i18n::tr( @@ -214,21 +214,10 @@ pub(super) fn histogram(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) p.text(pos2(r.left() + r.width() / 2.0, r.bottom() - 13.0), Align2::CENTER_CENTER, text, t.font(12.5), t.text_label); } else if let Some(ph) = app.session.catalog.photo(id) { let m = &ph.meta; - let parts: Vec = [ - m.iso.map(|i| format!("ISO {i}")), - m.focal_mm.map(|f| format!("{f:.0}mm")), - m.aperture.map(|a| format!("f/{a:.1}")), - if m.shutter.is_empty() { None } else { Some(m.shutter.clone()) }, - ] - .into_iter() - .flatten() - .collect(); - - if !parts.is_empty() { - let text = parts.join(" · "); + if let Some(text) = crate::readout::exposure_line(m) { let y = r.bottom() - 13.0; let x = r.left() + r.width() / 2.0; - p.text(pos2(x, y), Align2::CENTER_CENTER, text, t.font(12.5), t.text_label); + p.text(pos2(x, y), Align2::CENTER_CENTER, text, t.body(), t.text_label); } } } diff --git a/crates/ui-egui/src/panels/edit/mixer.rs b/crates/ui-egui/src/panels/edit/mixer.rs index 0bddba375d8..5b91a0ccad7 100644 --- a/crates/ui-egui/src/panels/edit/mixer.rs +++ b/crates/ui-egui/src/panels/edit/mixer.rs @@ -119,7 +119,7 @@ pub(super) fn point_color(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &Develo }); if n == 0 { egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 2, bottom: 8 }).show(ui, |ui| { - ui.label(egui::RichText::new(crate::i18n::tr("Pick a colour on the photo with the eyedropper.")).size(12.0).color(t.text_dim)); + ui.label(egui::RichText::new(crate::i18n::tr("Pick a colour on the photo with the eyedropper.")).font(t.label()).color(t.text_dim)); }); return; } diff --git a/crates/ui-egui/src/panels/edit/sliders.rs b/crates/ui-egui/src/panels/edit/sliders.rs index 00adb9928a7..e77f02c5843 100644 --- a/crates/ui-egui/src/panels/edit/sliders.rs +++ b/crates/ui-egui/src/panels/edit/sliders.rs @@ -89,7 +89,7 @@ fn profile_menu_rows(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSett } }; let heading = |ui: &mut egui::Ui, s: &str| { - ui.label(egui::RichText::new(crate::i18n::tr(s)).font(t.semibold(11.5)).color(t.text_dim)); + ui.label(egui::RichText::new(crate::i18n::tr(s)).font(t.caption_strong()).color(t.text_dim)); }; for (title, key, ids) in [("Favorites", "fav", app.session.profile_favorites.clone()), ("Recent", "recent", app.session.profile_recent.clone())] { let list: Vec<_> = ids.iter().filter_map(|id| app.session.profile_info(id).map(|(name, _)| (id.as_str(), name))).collect(); @@ -237,7 +237,7 @@ pub(super) fn hdr_row(app: &mut LightcraftApp, ui: &mut egui::Ui, d: &DevelopSet pub(super) fn quick_develop(app: &mut LightcraftApp, ui: &mut egui::Ui, n: usize) { let t = Tokens::get(ui.ctx()); egui::Frame::NONE.inner_margin(egui::Margin { left: 24, right: 22, top: 0, bottom: 10 }).show(ui, |ui| { - ui.label(egui::RichText::new(crate::i18n::tr_format!("Quick Develop · {n} photos", n = n)).color(t.text_label).size(12.5)); + ui.label(egui::RichText::new(crate::i18n::tr_format!("Quick Develop · {n} photos", n = n)).color(t.text_label).font(t.body())); ui.add_space(4.0); let rows: [(&str, &str, f64, f64); 9] = [ ("Exposure", "light.exposure", 1.0 / 3.0, 1.0), @@ -252,7 +252,7 @@ pub(super) fn quick_develop(app: &mut LightcraftApp, ui: &mut egui::Ui, n: usize ]; egui::Grid::new("quick-develop").num_columns(5).spacing([4.0, 3.0]).show(ui, |ui| { for (label, ctl, small, big) in rows { - ui.label(egui::RichText::new(crate::i18n::tr(label)).size(11.5).color(t.text_dim)); + ui.label(egui::RichText::new(crate::i18n::tr(label)).font(t.caption()).color(t.text_dim)); // Keep the existing automation ids while drawing all step arrows as vectors. for (txt, icon, d) in [ ("◀◀", Icon::ChevronDoubleLeft, -big), diff --git a/crates/ui-egui/src/panels/filterbar.rs b/crates/ui-egui/src/panels/filterbar.rs index 8b34fbaf950..1f563e3e7eb 100644 --- a/crates/ui-egui/src/panels/filterbar.rs +++ b/crates/ui-egui/src/panels/filterbar.rs @@ -14,6 +14,8 @@ use crate::widgets::register; pub const HEIGHT: f32 = 40.0; /// Bar width (points) below which the controls take two rows. const WIDE: f32 = 1240.0; +/// Between two controls of a row. +const GAP: f32 = 4.0; /// Colour-label swatches (UI colours, our own choice). pub use crate::theme::label_color; @@ -62,7 +64,7 @@ fn picker(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, current: &str, a ui, &format!("filter-{id}"), if active && matches!(id, "camera" | "lens" | "keyword") { current } else { crate::i18n::tr(current) }, - t.font(12.5), + t.label(), if active { t.text } else { t.text_label }, ); if active { @@ -95,9 +97,30 @@ fn picker(app: &mut LightcraftApp, ui: &mut egui::Ui, id: &str, current: &str, a pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - // one row when there is room, else the metadata pickers and actions go to a second row - let two_rows = ui.available_width() < WIDE; - let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), if two_rows { 2.0 * HEIGHT - 8.0 } else { HEIGHT }), Sense::hover()); + // How wide the three parts of the bar were when last drawn (rating, flag and label; type and + // edited; the metadata pickers and the buttons): their words are longer in some languages, + // and what a row holds follows what fits, not a width that suits English. + let widths_id = egui::Id::unique("filterbar:widths"); + let seen: [f32; 3] = ui.data(|d| d.get_temp(widths_id)).unwrap_or([0.0; 3]); + let room = ui.available_width() - 32.0; + // One row when there is room, else the metadata pickers and actions go to a second row. Type + // and edited go down with them when they would run off the first, and stand on a row of + // their own between the two when they fit on neither. + // (Each part is measured from where it begins, so it measures the same on whichever row it + // stands, and parts that share a row have a gap between them: what fits is then a matter of + // the widths alone, and the bar comes to rest. Measured with the gap before it, a part was + // four points wider when it followed another, and in that band the bar changed its mind + // every frame.) + let [first, second, third] = seen; + let two_rows = ui.available_width() < WIDE || first + GAP + second + GAP + third > room; + let (second_row, third_row) = match (two_rows, first + GAP + second <= room, second + GAP + third <= room) { + (false, _, _) => (0, 0), + (true, true, _) => (0, 1), + (true, false, true) => (1, 1), + (true, false, false) => (1, 2), + }; + let rows = third_row as f32 + 1.0; + let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), rows * (HEIGHT - 8.0) + 8.0), Sense::hover()); ui.painter().rect_filled(bar, 0.0, t.chrome); ui.painter().line_segment([bar.left_bottom(), bar.right_bottom()], Stroke::new(1.0, t.divider)); register(ui, "filterbar", bar); @@ -105,12 +128,12 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { let row = |ui: &mut egui::Ui, i: f32| { let r = Rect::from_min_size(bar.min + vec2(16.0, 4.0 + i * (HEIGHT - 8.0)), vec2(bar.width() - 32.0, HEIGHT - 8.0)); let mut c = ui.new_child(egui::UiBuilder::new().max_rect(r).layout(egui::Layout::left_to_right(egui::Align::Center))); - c.spacing_mut().item_spacing.x = 4.0; + c.spacing_mut().item_spacing.x = GAP; c }; - let mut row1 = row(ui, 0.0); - let mut row2 = row(ui, 1.0); - let ui = &mut row1; + let mut rows = [row(ui, 0.0), row(ui, 1.0), row(ui, 2.0)]; + let [ui, ..] = &mut rows; + let began = ui.cursor().left(); // rating: operator + stars caption(ui, "Rating"); @@ -180,8 +203,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { } } ui.add_space(14.0); + let first_w = ui.min_rect().right() - began; // kind + edited + let Some(ui) = rows.get_mut(second_row) else { return }; + let began = ui.cursor().left(); let kind_label = match f.kind { None => "All types", Some(MediaKind::Image) => "Photos", @@ -233,8 +259,11 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { .collect(), ); + let second_w = ui.min_rect().right() - began; + // metadata pickers - let ui: &mut egui::Ui = if two_rows { &mut row2 } else { &mut row1 }; + let Some(ui) = rows.get_mut(third_row) else { return }; + let began = ui.cursor().left(); let values = app.caches.filter_values(&app.session.catalog); let (cameras, lenses, keywords) = (values.cameras.clone(), values.lenses.clone(), values.keywords.clone()); for (id, key, all_label, current, values) in [ @@ -252,20 +281,26 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) { // save / clear ui.add_space(14.0); let filtering = app.session.filter != Default::default(); - let save = ui.add_enabled(filtering, egui::Button::new(egui::RichText::new(crate::i18n::tr("Save as Smart Album…")).font(t.font(12.5)))); + let save = ui.add_enabled(filtering, egui::Button::new(egui::RichText::new(crate::i18n::tr("Save as Smart Album…")).font(t.label()))); register(ui, "button:filterSave", save.rect); if save.clicked() { let _ = app.run("dialog.newSmartAlbum", json!({})); } - let clear = ui.add_enabled(filtering, egui::Button::new(egui::RichText::new(crate::i18n::tr("Clear")).font(t.font(12.5)))); + let clear = ui.add_enabled(filtering, egui::Button::new(egui::RichText::new(crate::i18n::tr("Clear")).font(t.label()))); register(ui, "button:filterClear", clear.rect); if clear.clicked() { app.ui.search.clear(); let _ = app.run("library.clearFilter", json!({})); } // filter presets: apply one, save the current filter, delete - let presets = crate::widgets::dropdown(ui, "filterPresets", crate::i18n::tr("Presets"), t.font(12.5), t.text); + let presets = crate::widgets::dropdown(ui, "filterPresets", crate::i18n::tr("Presets"), t.label(), t.text); register(ui, "button:filterPresets", presets.rect); + let now = [first_w, second_w, ui.min_rect().right() - began]; + // (a number that is none would never equal itself: it is not kept, nor asked about again) + if now.iter().all(|w| w.is_finite()) && now.iter().zip(seen).any(|(now, seen)| (now - seen).abs() > 0.5) { + ui.data_mut(|d| d.insert_temp(widths_id, now)); + ui.ctx().request_repaint(); + } egui::Popup::menu(&presets).show(|ui| { let names: Vec = app.session.filter_presets.iter().map(|f| f.name.clone()).collect(); for n in &names { diff --git a/crates/ui-egui/src/panels/grid.rs b/crates/ui-egui/src/panels/grid.rs index 5064b8d401c..0d649ddc89a 100644 --- a/crates/ui-egui/src/panels/grid.rs +++ b/crates/ui-egui/src/panels/grid.rs @@ -301,13 +301,13 @@ fn show_inner(app: &mut LightcraftApp, ui: &mut egui::Ui) { let (hr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::hover()); ui.painter().rect_filled(hr, 0.0, t.canvas); let full = crate::i18n::source_title(&app.session); - let count_w = ui.painter().layout_no_wrap(cnt.clone(), t.font(12.5), t.text_dim).size().x; + let count_w = ui.painter().layout_no_wrap(cnt.clone(), t.label(), t.text_dim).size().x; // the title gives way to the count: a long album or folder name is trimmed, in full on hover let room = (hr.width() - 20.0 - count_w - 36.0).max(0.0); - let font = t.semibold(17.0); + let font = t.display_strong(); let title = crate::widgets::elide_head(&full, room, |s| ui.painter().layout_no_wrap(s.to_string(), font.clone(), t.text).size().x); let title_rect = ui.painter().text(pos2(hr.left() + 20.0, hr.center().y), Align2::LEFT_CENTER, &title, font, t.text); - let count_rect = ui.painter().text(pos2(hr.right() - 20.0, hr.center().y), Align2::RIGHT_CENTER, cnt, t.font(12.5), t.text_dim); + let count_rect = ui.painter().text(pos2(hr.right() - 20.0, hr.center().y), Align2::RIGHT_CENTER, cnt, t.label(), t.text_dim); crate::widgets::register(ui, "grid:title", title_rect); crate::widgets::register(ui, "grid:count", count_rect); if title != full { @@ -674,7 +674,7 @@ fn group_header(app: &mut LightcraftApp, ui: &mut egui::Ui, run: &DateRun, ids: pos2(x + gw + 10.0, r.center().y), Align2::LEFT_CENTER, crate::i18n::tr_format!("· {n} photo{}", if n == 1 { "" } else { "s" }, n = n), - t.font(12.5), + t.label(), t.text_dim, ); if resp.clicked() { @@ -783,7 +783,7 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square }; paint_cell_thumbnail(app, p, &t, id, img_rect, ThumbFlags { square, selected, active, onscreen, ppp }); // labels and badges - paint_cell_caption(app, p, &t, &photo, r, square); + paint_cell_caption(app, p, &t, &photo, r, CaptionFlags { square, selected }); paint_cell_badges(app, p, &t, &photo, img_rect, BadgeFlags { square, selected, hovered: resp.hovered() }); if let Some(name) = &photo.copy_name { paint_copy_tag(p, &t, name, img_rect, square); @@ -791,9 +791,6 @@ fn cell(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId, r: Rect, square if let Some(why) = &photo.preview_only { paint_preview_pill(ui, p, &t, id, why, img_rect); } - if photo.flag == Flag::Reject { - p.rect_filled(img_rect, 0.0, Color32::from_black_alpha(110)); - } cell_interaction(app, ui, &resp, id, &photo); } @@ -845,38 +842,41 @@ fn paint_cell_thumbnail(app: &mut LightcraftApp, p: &egui::Painter, t: &Tokens, } } -fn paint_cell_caption(app: &LightcraftApp, p: &egui::Painter, t: &Tokens, photo: &lightcraft_catalog::Photo, r: Rect, square: bool) { +fn paint_cell_caption(app: &LightcraftApp, p: &egui::Painter, t: &Tokens, photo: &lightcraft_catalog::Photo, r: Rect, flags: CaptionFlags) { + let CaptionFlags { square, selected } = flags; if square && app.ui.show_filenames { let m = &photo.meta; let name = match app.ui.grid_info.as_str() { - "exposure" => { - let parts: Vec = [ - // whole seconds read "8 s"; fractions as written ("1/250") - (!m.shutter.is_empty()) - .then(|| if m.shutter.contains('/') || m.shutter.ends_with('s') { m.shutter.clone() } else { format!("{} s", m.shutter) }), - m.aperture.map(|a| format!("f/{a:.1}").replace(".0", "")), - m.iso.map(|i| format!("ISO {i}")), - m.focal_mm.map(|f| format!("{f:.0} mm")), - ] - .into_iter() - .flatten() - .collect(); - if parts.is_empty() { "—".to_string() } else { parts.join(" · ") } - } + "exposure" => crate::readout::exposure_line(m).unwrap_or_else(|| "—".to_string()), "date" => photo.captured.as_deref().map(crate::i18n::display_time).unwrap_or_else(|| crate::i18n::tr("No date").into()), _ => photo.file_name.rsplit_once('.').map(|(n, _)| n.to_string()).unwrap_or(photo.file_name.clone()), }; - p.text(pos2(r.left() + 8.0, r.top() + 12.0), Align2::LEFT_CENTER, name, t.font(10.5), t.text_dim); let fmt = photo.format.clone(); - let g = p.layout_no_wrap(fmt, t.semibold(9.0), t.text_label); + // (the format's chip is dark in every theme, so its letters are light in every theme: in + // the light themes they were the label colour, dark on dark) + let chip = Color32::from_gray(26); + let ink = t.ink_on(chip); + let g = p.layout_no_wrap(fmt, t.micro_strong(), ink); let br = Rect::from_min_size(pos2(r.right() - g.size().x - 14.0, r.top() + 5.0), g.size() + vec2(8.0, 3.0)); - p.rect_filled(br, 2.0, Color32::from_gray(26)); - p.galley(br.min + vec2(4.0, 1.5), g, t.text_label); + // (a chosen cell is lighter than the cell the dim text is made for, or darker, and a + // colour label tints either: the line is made legible on the cell as it is) + let base = if selected { t.cell_selected } else { t.cell }; + let dim = t.legible(t.text_dim, crate::theme::label_background(base, photo.label, selected), 4.5); + // (the line ends before the format: it used to run on under it) + let line = crate::widgets::one_line(p, &name, t.caption(), dim, br.left() - 6.0 - (r.left() + 8.0)); + p.galley(pos2(r.left() + 8.0, r.top() + 12.0 - line.size().y / 2.0), line, dim); + p.rect_filled(br, 2.0, chip); + p.galley(br.min + vec2(4.0, 1.5), g, ink); } } fn paint_cell_badges(app: &LightcraftApp, p: &egui::Painter, t: &Tokens, photo: &lightcraft_catalog::Photo, img_rect: Rect, flags: BadgeFlags) { let BadgeFlags { square, selected, hovered } = flags; + // (a rejected photo is dimmed under its marks, not over them: over them it took the flag's + // red down with the photo, to under 3:1 on the shade) + if photo.flag == Flag::Reject { + p.rect_filled(img_rect, 0.0, Color32::from_black_alpha(110)); + } let show_badges = match app.ui.settings.grid_badges { crate::state::GridBadges::Auto => hovered || selected || photo.rating > 0 || photo.flag != Flag::None || photo.label.is_some(), crate::state::GridBadges::Always => true, @@ -890,22 +890,53 @@ fn paint_cell_badges(app: &LightcraftApp, p: &egui::Painter, t: &Tokens, photo: } if show_badges { let bar = badge_bar; + // A picture has no theme: its marks are in one light ink on a shade, not in the theme's + // star and label colours (dark in the light themes). Each group of marks has a shade as + // wide as it is, so that a rated photo keeps its lower edge; shade and marks end where + // the photo ends (on a narrow one they ran on over the gap to the next). Under the + // pointer and on a chosen photo the band along the lower edge is there as it was: it is + // what says "this one", and in the light themes the outline of a chosen photo alone + // hardly shows. + let ink = Tokens::on_photo(); + let flag_w = if photo.flag == Flag::None { 0.0 } else { 18.0 }; + // (on a narrow photo the stars close up, so that the flag after them is still inside the bar it is clipped to, + // and clear of the shade under the marks at the right, 6 points beyond it; where they cannot close up enough, + // the marks at the right give way) + let fit = crate::widgets::badge_marks(bar.width(), photo.rating as usize, flag_w, photo.is_edited(), photo.label.is_some()); + let pitch = fit.pitch; + let right_w = if fit.edited { 20.0 } else { 0.0 } + if fit.label { 20.0 } else { 0.0 }; + let marks_w = photo.rating as f32 * pitch; + let clipped = p.with_clip_rect(bar.intersect(p.clip_rect())); + let p = &clipped; if (hovered || selected) && (square || photo.label.is_none()) { p.rect_filled(bar, 0.0, Color32::from_black_alpha(120)); } + let shade = |from: f32, to: f32| { + if to > from { + p.rect_filled(Rect::from_min_max(pos2(from, bar.top() + 3.0), pos2(to, bar.bottom() - 3.0)), 4.0, Tokens::photo_shade()); + } + }; + if marks_w + flag_w > 0.0 { + shade(bar.left() + 3.0, (bar.left() + 9.0 + marks_w + flag_w).min(bar.right())); + } + if right_w > 0.0 { + shade((bar.right() - right_w - 6.0).max(bar.left()), bar.right() - 3.0); + } let mut x = bar.left() + 6.0; - x += crate::rating::paint_rating(p, pos2(x, bar.center().y), photo.rating, crate::rating::RatingSize::Medium, t.star) + 4.0; + x += crate::rating::paint_rating_spaced(p, pos2(x, bar.center().y), photo.rating, crate::rating::RatingSize::Medium, pitch, ink) + 4.0; match photo.flag { - Flag::Pick => paint(p, Rect::from_min_size(pos2(x, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::FlagPickFilled, t.pick), - Flag::Reject => paint(p, Rect::from_min_size(pos2(x, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::FlagReject, t.reject), + Flag::Pick => paint(p, Rect::from_min_size(pos2(x, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::FlagPickFilled, ink), + Flag::Reject => { + paint(p, Rect::from_min_size(pos2(x, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::FlagReject, Tokens::on_photo_reject()) + } Flag::None => {} } let mut right = bar.right(); - if photo.is_edited() { - paint(p, Rect::from_min_size(pos2(right - 20.0, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::Sliders, t.text_label); + if fit.edited { + paint(p, Rect::from_min_size(pos2(right - 20.0, bar.center().y - 7.0), vec2(14.0, 14.0)), Icon::Sliders, ink); right -= 20.0; } - if let Some(l) = photo.label { + if let (Some(l), true) = (photo.label, fit.label) { p.circle(pos2(right - 12.0, bar.center().y), 5.0, label_color(l), Stroke::new(1.0, Color32::from_black_alpha(120))); } } @@ -913,7 +944,7 @@ fn paint_cell_badges(app: &LightcraftApp, p: &egui::Painter, t: &Tokens, photo: fn paint_copy_tag(p: &egui::Painter, t: &Tokens, name: &str, img_rect: Rect, square: bool) { // virtual copy: a folded-corner tag at the top right - let g = p.layout_no_wrap(name.to_string(), t.semibold(10.5), Color32::WHITE); + let g = p.layout_no_wrap(name.to_string(), t.micro_strong(), Color32::WHITE); let tr = if square { img_rect.right_top() + vec2(-6.0, 6.0) } else { img_rect.right_top() + vec2(-5.0, 5.0) }; let br = Rect::from_min_max(pos2(tr.x - g.size().x - 26.0, tr.y), pos2(tr.x, tr.y + 20.0)); p.rect_filled(br, 10.0, Color32::from_black_alpha(165)); @@ -932,7 +963,7 @@ fn paint_copy_tag(p: &egui::Painter, t: &Tokens, name: &str, img_rect: Rect, squ fn paint_preview_pill(ui: &egui::Ui, p: &egui::Painter, t: &Tokens, id: PhotoId, why: &str, img_rect: Rect) { // a raw shown from its embedded JPEG: a small amber "Preview" pill at the image's bottom // left, above the badge bar (always shown: it changes what editing does) - let g = p.layout_no_wrap(crate::i18n::tr("Preview").into(), t.semibold(9.5), Color32::WHITE); + let g = p.layout_no_wrap(crate::i18n::tr("Preview").into(), t.micro_strong(), Color32::WHITE); let at = pos2(img_rect.left() + 6.0, img_rect.bottom() - 30.0 - 16.0); let br = Rect::from_min_size(at, vec2(g.size().x + 24.0, 16.0)); p.rect_filled(br, 8.0, Color32::from_black_alpha(170)); @@ -989,6 +1020,12 @@ struct ThumbFlags { ppp: f32, } +/// What [`paint_cell_caption`] needs to know about the cell. +struct CaptionFlags { + square: bool, + selected: bool, +} + struct BadgeFlags { square: bool, selected: bool, @@ -1006,12 +1043,12 @@ fn folder_header(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_engi ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 8.0; let count_w = - ui.painter().layout_no_wrap(cnt.to_owned(), t.font(12.5), t.text_dim).size().x.ceil().min((ui.available_width() * 0.45).floor()); + ui.painter().layout_no_wrap(cnt.to_owned(), t.label(), t.text_dim).size().x.ceil().min((ui.available_width() * 0.45).floor()); let path_w = (ui.available_width() - count_w - 8.0).max(0.0).floor(); ui.allocate_ui_with_layout(vec2(path_w, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { folder_breadcrumbs(app, ui, &b.path); }); - let count = ui.add_sized(vec2(count_w, 24.0), egui::Label::new(egui::RichText::new(cnt).size(12.5).color(t.text_dim)).truncate()); + let count = ui.add_sized(vec2(count_w, 24.0), egui::Label::new(egui::RichText::new(cnt).font(t.label()).color(t.text_dim)).truncate()); register(ui, "grid:count", count.rect); count.on_hover_text(cnt); }); @@ -1028,7 +1065,7 @@ fn folder_header(app: &mut LightcraftApp, ui: &mut egui::Ui, b: &lightcraft_engi if local_n > 0 { let label = crate::i18n::tr_format!("Add {local_n} to My Photos", local_n = local_n); let button = - ui.add(egui::Button::new(egui::RichText::new(label).font(t.semibold(11.5)).color(t.text)).wrap().min_size(vec2(37.0, 24.0))); + ui.add(egui::Button::new(egui::RichText::new(label).font(t.caption_strong()).color(t.text)).wrap().min_size(vec2(37.0, 24.0))); register(ui, "button:addToLibrary", button.rect); if button.clicked() { let local: Vec = ids.iter().filter(|id| app.session.catalog.photo(**id).is_some_and(|p| p.local)).map(|id| id.0).collect(); @@ -1090,7 +1127,7 @@ fn folder_breadcrumbs(app: &mut LightcraftApp, ui: &mut egui::Ui, path: &str) { let last = remaining == 1; // Share the bounded row among the remaining crumbs, leaving room for every separator. let width = ((ui.available_width() - separator_w * (remaining - 1) as f32) / remaining as f32).max(0.0).floor(); - let text = egui::RichText::new(*part).size(13.0).color(if last { t.text } else { t.text_label }); + let text = egui::RichText::new(*part).font(t.body()).color(if last { t.text } else { t.text_label }); let r = ui.add_sized(vec2(width, 24.0), egui::Label::new(if last { text.strong() } else { text }).truncate().sense(Sense::click())); register(ui, format!("crumb:{i}"), r.rect); if !last { diff --git a/crates/ui-egui/src/panels/histogram.rs b/crates/ui-egui/src/panels/histogram.rs index 3f26b46bded..130f39cf472 100644 --- a/crates/ui-egui/src/panels/histogram.rs +++ b/crates/ui-egui/src/panels/histogram.rs @@ -349,10 +349,10 @@ mod tests { dragging, }; assert_eq!(active("light.exposure", 0.45, false).readout().as_deref(), Some("Exposure: +0.45 EV")); - assert_eq!(active("light.exposure", -2.0, true).readout().as_deref(), Some("Exposure: -2.00 EV")); + assert_eq!(active("light.exposure", -2.0, true).readout().as_deref(), Some("Exposure: −2.00 EV")); assert_eq!(active("light.shadows", 25.0, true).readout().as_deref(), Some("Shadows: +25")); assert_eq!(active("light.blacks", 0.0, false).readout().as_deref(), Some("Blacks: 0")); - assert_eq!(active("light.highlights", -100.0, false).readout().as_deref(), Some("Highlights: -100")); + assert_eq!(active("light.highlights", -100.0, false).readout().as_deref(), Some("Highlights: −100")); assert_eq!(active("light.whites", 13.0, false).readout().as_deref(), Some("Whites: +13")); } diff --git a/crates/ui-egui/src/panels/keywording.rs b/crates/ui-egui/src/panels/keywording.rs index 4861d4c6fa7..3e32f0e5521 100644 --- a/crates/ui-egui/src/panels/keywording.rs +++ b/crates/ui-egui/src/panels/keywording.rs @@ -176,7 +176,7 @@ pub fn scope(app: &mut LightcraftApp, ui: &mut egui::Ui, selection: &[PhotoId]) } let t = Tokens::get(ui.ctx()); let said = crate::i18n::tr_format!("Keywords of {n} selected photos", n = photos); - let r = ui.label(egui::RichText::new(said).size(11.5).color(t.text_label)); + let r = ui.label(egui::RichText::new(said).font(t.caption()).color(t.text_label)); register(ui, "keywordScope", r.rect); ui.add_space(4.0); } diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index 92498eb0233..857845e9239 100644 --- a/crates/ui-egui/src/panels/left/albums.rs +++ b/crates/ui-egui/src/panels/left/albums.rs @@ -343,7 +343,7 @@ pub(super) fn top_level_drop_target(app: &mut LightcraftApp, ui: &mut egui::Ui, ui.painter().rect_stroke(header.shrink2(vec2(8.0, 3.0)), 4.0, stroke, egui::StrokeKind::Inside); // right-aligned, left of the + button let edge = header.right().min(ui.clip_rect().right()); - ui.painter().text(pos2(edge - 56.0, header.center().y), Align2::RIGHT_CENTER, crate::i18n::tr("Top Level"), t.font(12.5), t.text_dim); + ui.painter().text(pos2(edge - 56.0, header.center().y), Align2::RIGHT_CENTER, crate::i18n::tr("Top Level"), t.label(), t.text_dim); if over && ui.input(|i| i.pointer.primary_released()) { drop_album(app, ui, dragged, None); } diff --git a/crates/ui-egui/src/panels/left/rows.rs b/crates/ui-egui/src/panels/left/rows.rs index ac364aa3658..817cdb3381d 100644 --- a/crates/ui-egui/src/panels/left/rows.rs +++ b/crates/ui-egui/src/panels/left/rows.rs @@ -169,11 +169,11 @@ fn draw_row(app: &mut LightcraftApp, ui: &mut egui::Ui, row: Row) -> egui::Respo icon, if selected { t.text } else { t.icon }, ); - let font = t.font(13.5); + let font = t.body(); let color = if selected { t.text } else { t.text_label }; // a count of nothing is there, but fainter: the rows that hold photos stand out let count_color = |n: usize| if n == 0 { t.text_dim.gamma_multiply(0.55) } else { t.text_dim }; - let count_galley = count.filter(|_| app.ui.show_counts).map(|n| ui.painter().layout_no_wrap(n.to_string(), t.font(12.5), count_color(n))); + let count_galley = count.filter(|_| app.ui.show_counts).map(|n| crate::readout::figures(ui.painter(), &n.to_string(), t.label(), count_color(n))); let label_left = r.left() + 42.0 + indent; let count_left = count_galley.as_ref().map_or(edge - 18.0, |g| edge - 18.0 - g.size().x); // a label's dot sits just before the count @@ -214,8 +214,8 @@ pub(super) fn out_of_sight(app: &LightcraftApp, ui: &mut egui::Ui, id: &str, lab let indent = drawn_indent(ui, indent); let t = Tokens::get(ui.ctx()); let painter = ui.painter(); - let name_w = painter.layout_no_wrap(label.to_string(), t.font(13.5), t.text_label).size().x; - let count_w = count.filter(|_| app.ui.show_counts).map(|n| painter.layout_no_wrap(n.to_string(), t.font(12.5), t.text_dim).size().x); + let name_w = painter.layout_no_wrap(label.to_string(), t.body(), t.text_label).size().x; + let count_w = count.filter(|_| app.ui.show_counts).map(|n| crate::readout::figures(painter, &n.to_string(), t.label(), t.text_dim).size().x); note_width(ui, row_need(indent, name_w, if mark { MARK_W } else { 0.0 }, count_w)); true } diff --git a/crates/ui-egui/src/panels/left/sections.rs b/crates/ui-egui/src/panels/left/sections.rs index 5597904a889..9333bf7123b 100644 --- a/crates/ui-egui/src/panels/left/sections.rs +++ b/crates/ui-egui/src/panels/left/sections.rs @@ -89,7 +89,7 @@ fn empty_hint(ui: &mut egui::Ui, section: SidebarSection) { let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); register(ui, format!("sidebarEmpty:{}", section.id()), r); let text = crate::i18n::tr(section.empty_hint()); - let galley = ui.painter().layout_no_wrap(text.to_string(), t.font(12.5), t.text_dim); + let galley = ui.painter().layout_no_wrap(text.to_string(), t.label(), t.text_dim); note_width(ui, 42.0 + galley.size().x + 18.0); ui.painter().galley(pos2(r.left() + 42.0, r.center().y - galley.size().y / 2.0), galley, t.text_dim); } @@ -219,14 +219,14 @@ fn section_header(app: &mut LightcraftApp, ui: &mut egui::Ui, section: SidebarSe register(ui, format!("{widget}Chevron:{id}"), Rect::from_center_size(c, vec2(16.0, 16.0))); let col = if hovered { t.text } else { t.text_dim }; paint(ui.painter(), Rect::from_center_size(c, vec2(16.0, 16.0)), if open { Icon::ChevronDown } else { Icon::ChevronRight }, col); - ui.painter().text(pos2(r.left() + 18.0, r.center().y), Align2::LEFT_CENTER, title, t.semibold(13.5), t.text_label); + ui.painter().text(pos2(r.left() + 18.0, r.center().y), Align2::LEFT_CENTER, title, t.title_strong(), t.text_label); let button = header_button(section); // (an album being dragged puts "Top Level" in the Albums header) let room = !(section == SidebarSection::Albums && app.ui.dragging_album.is_some()); if !open && rows > 0 && app.ui.show_counts && room { // folded: how much is in there (left of the header's own button) let right = edge - 18.0 - if button.is_some() { HEADER_BUTTON + 4.0 } else { 0.0 }; - let count = ui.painter().text(pos2(right, r.center().y), Align2::RIGHT_CENTER, rows.to_string(), t.font(12.5), t.text_dim); + let count = ui.painter().text(pos2(right, r.center().y), Align2::RIGHT_CENTER, rows.to_string(), t.label(), t.text_dim); register(ui, format!("{widget}Count:{id}"), count); } if section == SidebarSection::Albums { diff --git a/crates/ui-egui/src/panels/library_problem.rs b/crates/ui-egui/src/panels/library_problem.rs index 544e29449aa..861ad6263cf 100644 --- a/crates/ui-egui/src/panels/library_problem.rs +++ b/crates/ui-egui/src/panels/library_problem.rs @@ -1032,9 +1032,9 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) { ui.label(RichText::new(crate::i18n::tr("LightCraft couldn't find where to keep your library.")).color(t.text)); } else { ui.label(RichText::new(crate::i18n::tr("LightCraft couldn't open the library at")).color(t.text_label)); - ui.label(RichText::new(&problem.path).font(t.semibold(12.5)).color(t.text)); + ui.label(RichText::new(&problem.path).font(t.body_strong()).color(t.text)); } - ui.add(egui::Label::new(RichText::new(&problem.error).color(t.caution)).wrap()); + ui.add(egui::Label::new(RichText::new(&problem.error).color(t.text_caution())).wrap()); ui.label( RichText::new( "Your photos and edits in it are untouched. You can try again (e.g. after closing another program that has it open \ @@ -1161,7 +1161,7 @@ fn show_chooser(app: &mut LightcraftApp, ctx: &egui::Context, problem: &LibraryP } }); if !problem.error.is_empty() { - ui.add(egui::Label::new(RichText::new(&problem.error).color(t.caution)).wrap()); + ui.add(egui::Label::new(RichText::new(&problem.error).color(t.text_caution())).wrap()); } let selected = chooser.selected.and_then(|i| chooser.libraries.get(i)); let mut button = |ui: &mut egui::Ui, id: &str, label: &str, enabled: bool, c: Choice| { @@ -1231,7 +1231,7 @@ fn recent_row(ui: &mut egui::Ui, t: &Tokens, i: usize, library: &RecentLibrary, }); ui.add(egui::Label::new(RichText::new(parent).size(11.0).color(dim)).truncate().selectable(false)); if let Some(why) = &library.unavailable { - ui.add(egui::Label::new(RichText::new(why).size(11.0).color(t.caution)).wrap().selectable(false)); + ui.add(egui::Label::new(RichText::new(why).size(11.0).color(t.text_caution())).wrap().selectable(false)); } else if library.checking { let text = if library.slow { crate::i18n::tr("Not answering yet: the drive may be asleep or offline") } else { crate::i18n::tr("Checking…") }; @@ -1260,6 +1260,10 @@ pub fn banner(app: &mut LightcraftApp, ui: &mut egui::Ui) { } let t = Tokens::get(ui.ctx()); let mut reopen = false; + // what is written on the caution colour is black or white, whichever stands out more; the button's veil goes the + // other way, so that it never takes the ink's contrast down + let ink = t.ink_on(t.caution); + let veil = if ink == egui::Color32::WHITE { egui::Color32::from_black_alpha(40) } else { egui::Color32::from_white_alpha(40) }; egui::Panel::top("library-problem-banner") .exact_size(30.0) .frame(egui::Frame::NONE.fill(t.caution).inner_margin(egui::Margin::symmetric(12, 0))) @@ -1267,13 +1271,11 @@ pub fn banner(app: &mut LightcraftApp, ui: &mut egui::Ui) { ui.horizontal_centered(|ui| { let r = ui.label( RichText::new(crate::i18n::tr("Temporary session — your library isn't open, and nothing you do here is saved.")) - .font(t.semibold(12.5)) - .color(t.canvas), + .font(t.body_strong()) + .color(ink), ); register(ui, "indicator:temporarySession", r.rect); - let b = ui.add( - egui::Button::new(RichText::new(crate::i18n::tr("Open Library…")).color(t.canvas)).fill(egui::Color32::from_black_alpha(40)), - ); + let b = ui.add(egui::Button::new(RichText::new(crate::i18n::tr("Open Library…")).color(ink)).fill(veil)); register(ui, "button:libraryReopen", b.rect); reopen = b.clicked(); }); diff --git a/crates/ui-egui/src/panels/mask_effects.rs b/crates/ui-egui/src/panels/mask_effects.rs index d1c4fe1f498..c828ed04129 100644 --- a/crates/ui-egui/src/panels/mask_effects.rs +++ b/crates/ui-egui/src/panels/mask_effects.rs @@ -447,7 +447,7 @@ pub fn save_body( ui.label( egui::RichText::new(crate::i18n::tr("Highlighted: sliders this mask changes. Sliders left out stay as they are when the preset is applied.")) .color(t.text_dim) - .size(11.0), + .font(t.caption()), ); let r = ui.checkbox(amount, crate::i18n::tr("Include Amount")); register(ui, "check:effectAmount", r.rect); @@ -575,7 +575,7 @@ pub fn manage_body( if !e.extra.is_empty() { info += &crate::i18n::tr_format!(" · kept, not applied: {}", e.extra.keys().cloned().collect::>().join(", ")); } - ui.add(egui::Label::new(egui::RichText::new(info).color(t.text_dim).size(11.0)).truncate()); + ui.add(egui::Label::new(egui::RichText::new(info).color(t.text_dim).font(t.caption())).truncate()); }); } } @@ -679,7 +679,7 @@ pub fn manage_body( } }); if mask.is_none() { - ui.label(egui::RichText::new(crate::i18n::tr("Select a mask to apply or update presets.")).color(t.text_dim).size(11.0)); + ui.label(egui::RichText::new(crate::i18n::tr("Select a mask to apply or update presets.")).color(t.text_dim).font(t.caption())); } } diff --git a/crates/ui-egui/src/panels/masking.rs b/crates/ui-egui/src/panels/masking.rs index ce28482c464..e1906ca85f9 100644 --- a/crates/ui-egui/src/panels/masking.rs +++ b/crates/ui-egui/src/panels/masking.rs @@ -9,7 +9,7 @@ use super::edit::apply_slider_out; use super::right::header; use crate::LightcraftApp; use crate::icons::{Icon, paint}; -use crate::theme::Tokens; +use crate::theme::{TextSize, Tokens}; use crate::widgets::{divider, icon_button, one_line, register, slider, text_button}; const fn spec(id: &'static str, label: &'static str, min: f64, max: f64, step: f64, decimals: u8, track: Track) -> ControlSpec { @@ -66,7 +66,7 @@ const TILE_PAD: f32 = 3.0; /// Columns, tile width and label size of the Create New Mask grid in `width`, `label(size)` being /// the widest label at a font size: four tiles of up to 52 pt (at least 48), else three, else two — -/// the first that fits the labels at 10.5 pt, or at 9.5 pt before a column is dropped. A tile grows +/// the first that fits the labels at caption size, or at micro size before a column is dropped. A tile grows /// past 52 pt for a long (translated) label. In a panel too narrow even for that, two tiles whose /// labels are cut short. fn tile_layout(width: f32, label: impl Fn(f32) -> f32) -> (usize, f32, f32) { @@ -76,14 +76,14 @@ fn tile_layout(width: f32, label: impl Fn(f32) -> f32) -> (usize, f32, f32) { if n == 4 && w < 48.0 { continue; } - for size in [10.5, 9.5] { + for size in [TextSize::Caption.points(), TextSize::Micro.points()] { let need = (label(size) + 2.0 * TILE_PAD).ceil(); if need <= w { return (n, w.min(TILE.max(need)), size); } } } - (2, room(2).max(24.0), 9.5) + (2, room(2).max(24.0), TextSize::Micro.points()) } pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { @@ -253,7 +253,8 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let icon = m.components.first().map(|c| kind_label(&c.shape).1).unwrap_or(Icon::Mask); paint(ui.painter(), Rect::from_min_size(r.min + vec2(8.0, 7.0), vec2(16.0, 16.0)), icon, t.text_label); // a long name is cut short (with …) before the eye, the full name on hover - let color = if m.visible { t.text } else { t.text_disabled }; + // (a hidden mask's name is still read: dimmer, not the colour of what cannot be used) + let color = if m.visible { t.text } else { t.text_dim }; let g = one_line(ui.painter(), &m.name, t.font(13.0), color, r.width() - 32.0 - 32.0); let elided = g.elided; let at = pos2(r.left() + 32.0, r.center().y - g.size().y / 2.0); @@ -459,7 +460,7 @@ fn overlay_options(app: &mut LightcraftApp, ui: &mut egui::Ui) { let view = MaskView::parse(&app.ui.mask_overlay_mode).unwrap_or_default(); ui.horizontal(|ui| { ui.label(egui::RichText::new(crate::i18n::tr("Overlay")).color(t.text_dim)); - let r = crate::widgets::dropdown(ui, "maskOverlayMode", menu_label(view.label()), t.font(12.5), t.text_label); + let r = crate::widgets::dropdown(ui, "maskOverlayMode", menu_label(view.label()), t.body(), t.text_label); egui::Popup::menu(&r).show(|ui| { for v in MaskView::ALL { if ui.selectable_label(v == view, menu_label(v.label())).clicked() { @@ -518,7 +519,7 @@ fn range_controls(app: &mut LightcraftApp, ui: &mut egui::Ui, comp: usize, shape }; match shape { MaskShape::LuminanceRange { lo, hi, lo_feather, hi_feather } => { - ui.label(egui::RichText::new(crate::i18n::tr("Select Luminance Range")).color(t.text_dim).size(11.5)); + ui.label(egui::RichText::new(crate::i18n::tr("Select Luminance Range")).color(t.text_dim).font(t.caption())); let (lo, hi) = (*lo, *hi); let w = ui.available_width().min(240.0); let (rect, resp) = ui.allocate_exact_size(vec2(w, 18.0), Sense::click_and_drag()); @@ -626,14 +627,14 @@ fn range_controls(app: &mut LightcraftApp, ui: &mut egui::Ui, comp: usize, shape } app.run("mask.update", json!({"component": comp, "shape": s})) }); - ui.label(egui::RichText::new(crate::i18n::tr("− harder border · + softer border")).color(t.text_dim).size(11.0)); + ui.label(egui::RichText::new(crate::i18n::tr("− harder border · + softer border")).color(t.text_dim).font(t.caption())); } MaskShape::ColorRange { samples, refine } => { ui.horizontal(|ui| { ui.label( egui::RichText::new(crate::i18n::tr_format!("{} sample{}", samples.len(), if samples.len() == 1 { "" } else { "s" })) .color(t.text_dim) - .size(11.5), + .font(t.caption()), ); let picking = app.ui.tool == "colorRange"; if text_button(ui, &format!("colorPick{comp}"), crate::i18n::tr("Pick"), picking) @@ -949,16 +950,16 @@ mod tests { /// room by dropping a column rather than drawing it past its tile. #[test] fn tile_labels_get_the_room_they_need() { - let short = |size: f32| size * 4.0; // "Luminance"-ish: 42 pt at 10.5 - let long = |size: f32| size * 5.6; // "Background"/"Hintergrund": 59 pt at 10.5, 53 at 9.5 - assert_eq!(tile_layout(224.0, short), (4, 51.0, 10.5)); + let short = |size: f32| size * 4.0; // "Luminance"-ish: 44 pt at 11 + let long = |size: f32| size * 5.6; // "Background"/"Hintergrund": 62 pt at 11, 56 at 10 + assert_eq!(tile_layout(224.0, short), (4, 51.0, 11.0)); // too wide for four at either size: three tiles, wider than 52 so the label fits let (n, w, size) = tile_layout(224.0, long); - assert_eq!((n, size), (3, 10.5)); - assert!(w >= long(10.5) + 2.0 * TILE_PAD && w <= (224.0 - 2.0 * TILE_GAP) / 3.0, "{w}"); - // a smaller label keeps a column: 9.5 pt fits where 10.5 doesn't - let mid = |size: f32| size * 4.6; // 48.3 at 10.5, 43.7 at 9.5 - assert_eq!(tile_layout(224.0, mid), (4, 51.0, 9.5)); + assert_eq!((n, size), (3, 11.0)); + assert!(w >= long(11.0) + 2.0 * TILE_PAD && w <= (224.0 - 2.0 * TILE_GAP) / 3.0, "{w}"); + // a smaller label keeps a column: 10 pt fits where 11 doesn't + let mid = |size: f32| size * 4.4; // 48.4 at 11, 44 at 10 + assert_eq!(tile_layout(224.0, mid), (4, 51.0, 10.0)); // a wide panel: tiles stay 52 pt (or as wide as the label) assert_eq!(tile_layout(474.0, short).0, 4); assert_eq!(tile_layout(474.0, short).1, TILE); diff --git a/crates/ui-egui/src/panels/people.rs b/crates/ui-egui/src/panels/people.rs index 73d19cbaa95..138ac17626a 100644 --- a/crates/ui-egui/src/panels/people.rs +++ b/crates/ui-egui/src/panels/people.rs @@ -169,7 +169,7 @@ fn card(app: &mut LightcraftApp, ui: &mut egui::Ui, person: &Person, r: Rect, ed } // how many photos they are in, on the picture let count = if person.count > 999 { "999+".to_string() } else { person.count.to_string() }; - let g = p.layout_no_wrap(count, t.font(11.5), Color32::WHITE); + let g = p.layout_no_wrap(count, t.caption(), Color32::WHITE); let pill = Rect::from_min_size(pos2(face.right() - g.size().x - 14.0, face.bottom() - g.size().y - 11.0), g.size() + vec2(10.0, 6.0)); p.rect_filled(pill, 4.0, Color32::from_black_alpha(175)); p.galley(pill.min + vec2(5.0, 3.0), g, Color32::WHITE); diff --git a/crates/ui-egui/src/panels/presets.rs b/crates/ui-egui/src/panels/presets.rs index 6d35a50274c..08bc3d8550d 100644 --- a/crates/ui-egui/src/panels/presets.rs +++ b/crates/ui-egui/src/panels/presets.rs @@ -401,7 +401,7 @@ pub fn picker_rows(ui: &mut egui::Ui, salt: &str, presets: &PresetList, selected let size = vec2(ui.available_width(), row_h); match row { PickRow::Header(g) => { - ui.add_sized(size, egui::Label::new(egui::RichText::new(g).size(10.5).weak())); + ui.add_sized(size, egui::Label::new(egui::RichText::new(g).font(Tokens::get(ui.ctx()).caption()).weak())); } PickRow::Preset(i) => { let Some(p) = presets.get(*i) else { continue }; diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs index ec178223d53..8663f7a13db 100644 --- a/crates/ui-egui/src/panels/right.rs +++ b/crates/ui-egui/src/panels/right.rs @@ -149,8 +149,8 @@ pub fn fold_title(app: &mut LightcraftApp, ui: &egui::Ui, id: &str, r: Rect, res pub fn label_row(ui: &mut egui::Ui, label: &str, value: &str) { let t = Tokens::get(ui.ctx()); let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::hover()); - ui.painter().text(pos2(r.left() + 24.0, r.center().y), Align2::LEFT_CENTER, crate::i18n::tr(label), t.font(12.5), t.text_dim); - ui.painter().text(pos2(r.left() + 110.0, r.center().y), Align2::LEFT_CENTER, value, t.font(12.5), t.text_label); + ui.painter().text(pos2(r.left() + 24.0, r.center().y), Align2::LEFT_CENTER, crate::i18n::tr(label), t.body(), t.text_dim); + ui.painter().text(pos2(r.left() + 110.0, r.center().y), Align2::LEFT_CENTER, value, t.body(), t.text_label); } fn padded(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui)) { diff --git a/crates/ui-egui/src/panels/right/crop.rs b/crates/ui-egui/src/panels/right/crop.rs index 0b71fffe8ac..6cc8f62920c 100644 --- a/crates/ui-egui/src/panels/right/crop.rs +++ b/crates/ui-egui/src/panels/right/crop.rs @@ -80,7 +80,7 @@ pub(super) fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { ui.label(crate::i18n::tr("Aspect Ratio")); let cur = aspect_label(app.crop_tool_aspect(), original); let t = Tokens::get(ui.ctx()); - let r = crate::widgets::dropdown(ui, "cropAspect", crate::i18n::tr(&cur), t.font(12.5), t.text); + let r = crate::widgets::dropdown(ui, "cropAspect", crate::i18n::tr(&cur), t.body(), t.text); egui::Popup::menu(&r).show(|ui| { for (label, a) in ASPECT_PRESETS { @@ -255,7 +255,7 @@ pub(super) fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { "{} of 4 guides — drag along lines that should be vertical or horizontal.", d.geometry.guides.len() )) - .size(11.0) + .font(Tokens::get(ui.ctx()).caption()) .color(Tokens::get(ui.ctx()).text_dim), ); } diff --git a/crates/ui-egui/src/panels/right/history.rs b/crates/ui-egui/src/panels/right/history.rs index d434075adc5..22485b291f3 100644 --- a/crates/ui-egui/src/panels/right/history.rs +++ b/crates/ui-egui/src/panels/right/history.rs @@ -155,7 +155,7 @@ pub(super) fn activity(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) pos2(r.left() + 24.0, r.center().y), Align2::LEFT_CENTER, crate::i18n::history_label(&h.label, &app.session.presets), - t.font(12.5), + t.body(), text, ); if resp.clicked() { diff --git a/crates/ui-egui/src/panels/right/info.rs b/crates/ui-egui/src/panels/right/info.rs index 5810a0f2721..c88f3be9bb8 100644 --- a/crates/ui-egui/src/panels/right/info.rs +++ b/crates/ui-egui/src/panels/right/info.rs @@ -85,7 +85,7 @@ pub(super) fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { meta_field(app, ui, label, key, value, lines, mixed.contains(&key), &targets); } // file: name (rename), path (reveal), capture time (edit) - let small = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(crate::i18n::tr(text)).size(11.5).color(t.text_dim)); + let small = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(crate::i18n::tr(text)).font(t.caption()).color(t.text_dim)); small(ui, "File Name"); ui.allocate_ui_with_layout(vec2(ui.available_width(), 22.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { if crate::widgets::icon_button(ui, "infoRename", Icon::Pencil, vec2(20.0, 20.0), false, true, "Rename…").clicked() { @@ -102,7 +102,7 @@ pub(super) fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { lightcraft_catalog::Source::File { path } => path.clone(), lightcraft_catalog::Source::Demo { .. } => crate::i18n::tr("Generated demo photo").into(), }; - ui.add(egui::Label::new(egui::RichText::new(path).size(12.0).color(t.text_label)).truncate()); + ui.add(egui::Label::new(egui::RichText::new(path).font(t.label()).color(t.text_label)).truncate()); if crate::menus::ui_enabled(app, "app.showInFinder") { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if crate::widgets::icon_button(ui, "infoReveal", Icon::Folder, vec2(20.0, 20.0), false, true, crate::menus::reveal_label()) @@ -121,7 +121,7 @@ pub(super) fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { } let cap = p.captured.as_deref().map(crate::i18n::display_time).unwrap_or_else(|| "—".into()); ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - ui.add(egui::Label::new(egui::RichText::new(cap).size(12.5).color(t.text)).truncate()); + ui.add(egui::Label::new(egui::RichText::new(cap).font(t.body()).color(t.text)).truncate()); }); }); ui.add_space(6.0); @@ -137,7 +137,7 @@ pub(super) fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let gps_mixed = mixed.contains(&"gps"); let gps = if gps_mixed { String::new() } else { m.gps.map(|(la, lo)| format!("{la:.6}, {lo:.6}")).unwrap_or_default() }; let gid = egui::Id::unique("info-gps"); - ui.label(egui::RichText::new("GPS").size(11.5).color(t.text_dim)); + ui.label(egui::RichText::new("GPS").font(t.caption()).color(t.text_dim)); let mut edit: FieldEdit = ui.data(|d| d.get_temp(gid)).unwrap_or_else(|| FieldEdit::new(&gps, gps_mixed, &targets)); let hint = crate::i18n::tr(if gps_mixed { MIXED } else { "latitude, longitude" }); let r = crate::text_field::TextField::singleline("field:gps", &mut edit.text).hint(hint).label("GPS").width(f32::INFINITY).show(ui); @@ -159,7 +159,7 @@ pub(super) fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if let Some((la, lo)) = m.gps.filter(|_| !gps_mixed) { let pretty = format!("{:.5}° {}, {:.5}° {}", la.abs(), if la >= 0.0 { "N" } else { "S" }, lo.abs(), if lo >= 0.0 { "E" } else { "W" }); ui.horizontal(|ui| { - ui.label(egui::RichText::new(pretty).size(11.0).color(t.text_dim)); + ui.label(egui::RichText::new(pretty).font(t.caption()).color(t.text_dim)); if text_button(ui, "showOnMap", crate::i18n::tr("Show on Map"), false) .on_hover_text(crate::i18n::tr("Open the place in OpenStreetMap")) .clicked() @@ -210,7 +210,7 @@ pub(super) fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { _ => "Smart preview available", }; ui.add_space(6.0); - ui.label(egui::RichText::new(crate::i18n::tr(text)).color(if online { t.text_dim } else { t.accent })); + ui.label(egui::RichText::new(crate::i18n::tr(text)).color(if online { t.text_dim } else { t.text_link() })); } } ui.add_space(10.0); @@ -230,7 +230,7 @@ fn camera_card(ui: &mut egui::Ui, p: &lightcraft_catalog::Photo) { let m = &p.meta; egui::Frame::NONE.fill(t.canvas).corner_radius(6.0).inner_margin(egui::Margin::symmetric(12, 10)).show(ui, |ui| { ui.set_width(ui.available_width()); - let dim = |s: &str| egui::RichText::new(s.to_string()).size(12.0).color(t.text_label); + let dim = |s: &str| egui::RichText::new(s.to_string()).font(t.label()).color(t.text_label); if !m.camera.is_empty() { ui.label(dim(&m.camera)); } @@ -241,14 +241,14 @@ fn camera_card(ui: &mut egui::Ui, p: &lightcraft_catalog::Photo) { ui.label(dim(&format!("{} × {} · {}", p.width, p.height, human_size(p.file_size)))); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { egui::Frame::NONE.fill(t.chrome).corner_radius(3.0).inner_margin(egui::Margin::symmetric(5, 1)).show(ui, |ui| { - ui.label(egui::RichText::new(p.format.to_uppercase()).size(10.5).color(t.text_label)); + ui.label(egui::RichText::new(p.format.to_uppercase()).font(t.caption()).extra_letter_spacing(0.5).color(t.text_label)); }); }); }); let rows = [ - ("Focal length", m.focal_mm.map(|f| format!("{f:.1} mm").replace(".0 mm", " mm"))), - ("Shutter speed", (!m.shutter.is_empty()).then(|| crate::i18n::tr_format!("{} sec", m.shutter))), - ("Aperture", m.aperture.map(|f| format!("f / {f:.1}").replace(".0", ""))), + ("Focal length", m.focal_mm.and_then(crate::readout::focal)), + ("Shutter speed", crate::readout::shutter(&m.shutter)), + ("Aperture", m.aperture.and_then(crate::readout::aperture)), ("ISO", m.iso.map(|i| i.to_string())), ]; if rows.iter().any(|r| r.1.is_some()) { @@ -268,7 +268,7 @@ fn camera_card(ui: &mut egui::Ui, p: &lightcraft_catalog::Photo) { let r = ui.horizontal_wrapped(|ui| { ui.label(dim(crate::i18n::tr("Focus"))); ui.add_space(12.0); - ui.label(egui::RichText::new(text).size(12.0).color(t.text)); + ui.label(egui::RichText::new(text).font(t.label()).color(t.text)); }); register(ui, "info:focus", r.response.rect); } @@ -400,7 +400,7 @@ pub(crate) fn mixed_meta(catalog: &lightcraft_catalog::Catalog, ids: &[PhotoId], /// are selected (`view.infoSelectedPhotos`). fn metadata_for(app: &mut LightcraftApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(crate::i18n::tr("Show Metadata For")).size(11.5).color(t.text_dim)); + ui.label(egui::RichText::new(crate::i18n::tr("Show Metadata For")).font(t.caption()).color(t.text_dim)); ui.horizontal_wrapped(|ui| { let on = app.ui.settings.info_selected_photos; for (id, label, selected) in [("infoFor-target", "Target Photo", false), ("infoFor-selected", "Selected Photos", true)] { @@ -417,7 +417,7 @@ fn metadata_for(app: &mut LightcraftApp, ui: &mut egui::Ui) { /// picked goes to the photos `targets`. fn copyright_status(app: &mut LightcraftApp, ui: &mut egui::Ui, current: lightcraft_catalog::CopyrightStatus, mixed: bool, targets: &[PhotoId]) { let t = Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(crate::i18n::tr("Copyright Status")).size(11.5).color(t.text_dim)); + ui.label(egui::RichText::new(crate::i18n::tr("Copyright Status")).font(t.caption()).color(t.text_dim)); let shown = crate::i18n::tr(if mixed { MIXED } else { current.label() }); let r = crate::widgets::combo_box("info-copyright-status").selected_text(shown).show_ui(ui, |ui| { for st in lightcraft_catalog::CopyrightStatus::ALL { @@ -440,7 +440,7 @@ fn copyright_status(app: &mut LightcraftApp, ui: &mut egui::Ui, current: lightcr #[allow(clippy::too_many_arguments)] fn meta_field(app: &mut LightcraftApp, ui: &mut egui::Ui, label: &str, key: &str, value: &str, lines: usize, mixed: bool, targets: &[PhotoId]) { let t = Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(crate::i18n::tr(label)).size(11.5).color(t.text_dim)); + ui.label(egui::RichText::new(crate::i18n::tr(label)).font(t.caption()).color(t.text_dim)); let id = egui::Id::unique(("info-field", key)); let value = if mixed { "" } else { value }; let mut edit: FieldEdit = ui.data(|d| d.get_temp(id)).unwrap_or_else(|| FieldEdit::new(value, mixed, targets)); diff --git a/crates/ui-egui/src/panels/right/keywords.rs b/crates/ui-egui/src/panels/right/keywords.rs index b6598476ac7..0852c237e52 100644 --- a/crates/ui-egui/src/panels/right/keywords.rs +++ b/crates/ui-egui/src/panels/right/keywords.rs @@ -310,7 +310,9 @@ fn keyword_set(app: &mut LightcraftApp, ui: &mut egui::Ui) { let r = ui .add_sized( [bw, 22.0], - egui::Button::new(egui::RichText::new(short).size(11.5).color(if on { t.text } else { t.text_label })).selected(on).truncate(), + egui::Button::new(egui::RichText::new(short).font(t.label()).color(if on { t.text } else { t.text_label })) + .selected(on) + .truncate(), ) .on_hover_text(format!("{} — ⌥{}", k.replace('|', " › "), i + 1)); register(ui, format!("kwSet:{}", i + 1), r.rect); diff --git a/crates/ui-egui/src/panels/second.rs b/crates/ui-egui/src/panels/second.rs index cbdaa2d7388..63e4409341b 100644 --- a/crates/ui-egui/src/panels/second.rs +++ b/crates/ui-egui/src/panels/second.rs @@ -37,7 +37,7 @@ fn body(app: &mut LightcraftApp, ui: &mut egui::Ui) { area.center(), egui::Align2::CENTER_CENTER, crate::i18n::tr("No photo selected"), - egui::FontId::proportional(14.0), + crate::theme::Tokens::get(ui.ctx()).title(), Color32::GRAY, ); return; diff --git a/crates/ui-egui/src/panels/topbar.rs b/crates/ui-egui/src/panels/topbar.rs index 5e3fea8a11c..e6c6426c5ab 100644 --- a/crates/ui-egui/src/panels/topbar.rs +++ b/crates/ui-egui/src/panels/topbar.rs @@ -101,7 +101,7 @@ fn search_field(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, sr: Rect ui.new_child(egui::UiBuilder::new().max_rect(sr.shrink2(vec2(10.0, 4.0))).layout(egui::Layout::left_to_right(egui::Align::Center))); let empty = app.ui.search.is_empty(); if empty && !focused { - let g = child.painter().layout_no_wrap(crate::i18n::tr("Search Photos").into(), t.font(13.5), t.text_dim); + let g = child.painter().layout_no_wrap(crate::i18n::tr("Search Photos").into(), t.body(), t.text_dim); let w = g.size().x + 24.0; let x0 = sr.center().x - w / 2.0; paint(child.painter(), Rect::from_min_size(pos2(x0, sr.center().y - 8.0), vec2(16.0, 16.0)), Icon::Search, t.text_dim); @@ -111,7 +111,7 @@ fn search_field(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, sr: Rect .label(crate::i18n::tr("Search Photos")) .frame(false) .width(sr.width() - 20.0) - .font(t.font(13.5)) + .font(t.body()) .text_color(t.text) .show(&mut child) .response; @@ -146,7 +146,7 @@ fn filter_button(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, sr: Rec if active > 0 { let c = fr.right_top() + vec2(-3.0, 8.0); ui.painter().circle_filled(c, 7.0, t.accent); - ui.painter().text(c, Align2::CENTER_CENTER, active.to_string(), t.semibold(9.5), t.canvas); + ui.painter().text(c, Align2::CENTER_CENTER, active.to_string(), t.micro_strong(), t.ink_on(t.accent)); } let fresp = fresp.on_hover_text(if active > 0 { crate::i18n::tr_format!("Filter bar — {active} active filter{}", if active == 1 { "" } else { "s" }, active = active) @@ -195,7 +195,7 @@ fn right_icons(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens, full: Rec if warn { let c = r.right_top() + vec2(-5.0, 6.0); ui.painter().circle_filled(c, 6.0, t.reject); - ui.painter().text(c, Align2::CENTER_CENTER, "!", t.semibold(9.5), t.canvas); + ui.painter().text(c, Align2::CENTER_CENTER, "!", t.micro_strong(), t.ink_on(t.reject)); register(ui, "indicator:unsaved", r); } // a refusal says why (Import while a Lightroom catalog is coming in) diff --git a/crates/ui-egui/src/panels/unnamed.rs b/crates/ui-egui/src/panels/unnamed.rs index 7f42437b2ef..e337416ba33 100644 --- a/crates/ui-egui/src/panels/unnamed.rs +++ b/crates/ui-egui/src/panels/unnamed.rs @@ -258,8 +258,8 @@ pub fn tile(app: &mut LightcraftApp, ui: &mut egui::Ui, list: &Unnamed, i: usize } if let Some(name) = &f.suggestion { p.rect_filled(strip, 0.0, Color32::from_black_alpha(165)); - let label = super::people::fit(p, name, t.font(11.5), r.width() - 18.0); - p.text(pos2(r.left() + 5.0, strip.center().y), Align2::LEFT_CENTER, format!("{label}?"), t.font(11.5), Color32::from_gray(225)); + let label = super::people::fit(p, name, t.caption(), r.width() - 18.0); + p.text(pos2(r.left() + 5.0, strip.center().y), Align2::LEFT_CENTER, format!("{label}?"), t.caption(), Color32::from_gray(225)); } if let (Some(a), Some(who)) = (&accept, &f.suggestion) && a.clone().on_hover_text(format!("Name this face {who}")).clicked() diff --git a/crates/ui-egui/src/readout.rs b/crates/ui-egui/src/readout.rs new file mode 100644 index 00000000000..4c9bb8d4eb2 --- /dev/null +++ b/crates/ui-egui/src/readout.rs @@ -0,0 +1,289 @@ +//! How the interface writes what it reads off a photo or a control: one way to say an exposure, +//! a minus that is a minus, figures that stand in columns, and a file name shortened in the +//! middle so that its number stays. +//! +//! Before: one exposure read "f / 2.8", "f/11.0" and "f/11" with "35 mm" and "35mm", "1/250 sec", +//! "1/250 s" and "1/250" in four places, in three orders; a negative value had a hyphen; +//! Inter's figures are of unequal width, so a value changed its left edge while it was dragged +//! and counts did not line up; and a long file name on the filmstrip lost its end, where the +//! number of the frame is. + +use std::sync::Arc; + +use egui::{Color32, FontId}; +use lightcraft_catalog::Meta; + +/// The sign of a negative number. +pub(crate) const MINUS: char = '\u{2212}'; + +/// An aperture: "f/2.8", "f/11". Nothing for a number that is none. +pub(crate) fn aperture(f: f32) -> Option { + if !f.is_finite() || f <= 0.0 { + return None; + } + let tenths = (f64::from(f) * 10.0).round(); + Some(if tenths % 10.0 == 0.0 { format!("f/{:.0}", tenths / 10.0) } else { format!("f/{:.1}", tenths / 10.0) }) +} + +/// A focal length: "35 mm", "16.5 mm". +pub(crate) fn focal(mm: f32) -> Option { + if !mm.is_finite() || mm <= 0.0 { + return None; + } + let tenths = (f64::from(mm) * 10.0).round(); + Some(if tenths % 10.0 == 0.0 { format!("{:.0} mm", tenths / 10.0) } else { format!("{:.1} mm", tenths / 10.0) }) +} + +/// A shutter speed as the catalog holds it ("1/250", "8"), with its unit in the language of the +/// interface: "1/250 sec". One that names its unit already ("30s") stays as it is. +pub(crate) fn shutter(held: &str) -> Option { + let held = held.trim(); + if held.is_empty() { + return None; + } + Some(if held.ends_with(|c: char| c.is_alphabetic()) { held.to_string() } else { crate::i18n::tr_format!("{} sec", held) }) +} + +/// A sensitivity: "ISO 100". +pub(crate) fn iso(iso: u32) -> String { + format!("ISO {iso}") +} + +/// What a photo was taken with, in the order a photographer says it: shutter speed, aperture, +/// sensitivity, focal length. Only what the photo has. +pub(crate) fn exposure(m: &Meta) -> Vec { + [shutter(&m.shutter), m.aperture.and_then(aperture), m.iso.map(iso), m.focal_mm.and_then(focal)].into_iter().flatten().collect() +} + +/// [`exposure`] on one line ("1/250 sec · f/2.8 · ISO 100 · 35 mm"), or nothing. +pub(crate) fn exposure_line(m: &Meta) -> Option { + Some(exposure(m)).filter(|parts| !parts.is_empty()).map(|parts| parts.join(" · ")) +} + +/// A number as written by `format!`, with a minus for its hyphen ("−1.25"). +pub(crate) fn signed(written: &str) -> String { + match written.strip_prefix('-') { + Some(rest) => format!("{MINUS}{rest}"), + None => written.to_string(), + } +} + +/// The widths of the characters of `text` in `font`, and of the font's widest figure. +fn widths(painter: &egui::Painter, text: &str, font: &FontId) -> (Vec<(char, f32)>, f32) { + painter.ctx().fonts_mut(|fonts| { + let cell = ('0'..='9').map(|c| fonts.glyph_width(font, c)).fold(0.0, f32::max); + (text.chars().map(|c| (c, fonts.glyph_width(font, c))).collect(), cell) + }) +} + +/// The room a figure lacks to fill a cell as wide as the widest figure (none for other characters). +fn room(c: char, width: f32, cell: f32) -> f32 { + if c.is_ascii_digit() && width.is_finite() { (cell - width).max(0.0) } else { 0.0 } +} + +/// `text` on one line with every figure in a cell as wide as the widest figure of the font, so +/// that numbers stand in columns and a changing value keeps its place. (The font's own figures +/// are of unequal width, and egui cannot ask it for its tabular ones.) The text of the galley is +/// `text` unchanged. +/// +/// A figure stands at the end of its cell, so the galley is as wide as its cells: for a count, +/// which is figures only. A number with a sign is [`value`]'s. +pub(crate) fn figures(painter: &egui::Painter, text: &str, font: FontId, color: Color32) -> Arc { + let (widths, cell) = widths(painter, text, &font); + let mut job = egui::text::LayoutJob::default(); + job.wrap.max_width = f32::INFINITY; + let mut buffer = [0u8; 4]; + for (c, width) in widths { + job.append(c.encode_utf8(&mut buffer), room(c, width, cell), egui::TextFormat { font_id: font.clone(), color, ..Default::default() }); + } + painter.layout_job(job) +} + +/// A value ("−1.25", "+100") painted to end at `right_center`, each figure in the middle of a +/// cell as wide as the widest figure: the value begins and ends where any other of as many +/// figures does, and a narrow 1 does not stand off from its sign. Returns where it is. +pub(crate) fn value(painter: &egui::Painter, right_center: egui::Pos2, text: &str, font: FontId, color: Color32) -> egui::Rect { + let (widths, cell) = widths(painter, text, &font); + let mut job = egui::text::LayoutJob::default(); + job.wrap.max_width = f32::INFINITY; + let mut buffer = [0u8; 4]; + // (half a figure's room before it and half after; what is after is given as room before + // the next character, and after the last by where the galley is put) + let mut after = 0.0; + for (c, width) in widths { + let half = room(c, width, cell) / 2.0; + job.append(c.encode_utf8(&mut buffer), after + half, egui::TextFormat { font_id: font.clone(), color, ..Default::default() }); + after = half; + } + let galley = painter.layout_job(job); + let size = galley.size() + egui::vec2(after, 0.0); + let rect = egui::Rect::from_min_size(egui::pos2(right_center.x - size.x, right_center.y - size.y / 2.0), size); + painter.galley(rect.min, galley, color); + rect +} + +/// `text` shortened in the middle to fit `max` (as `width` measures it): the start and the end +/// stay, the end a character longer when they cannot be equal ("IMG_20…_153012"), for the end +/// of a file name is the number of the frame. Cuts fall between letters as a reader sees them (a +/// letter keeps its combining marks: an accent written apart, an Arabic vowel sign); what cannot +/// fit at all is "…". +pub(crate) fn elide_middle(text: &str, max: f32, width: impl Fn(&str) -> f32) -> String { + if width(text) <= max { + return text.to_string(); + } + let chars: Vec<&str> = unicode_segmentation::UnicodeSegmentation::graphemes(text, true).collect(); + let kept = |keep: usize| { + let tail = keep.div_ceil(2); + let head = keep - tail; + let mut out: String = chars.iter().take(head).copied().collect(); + out.push('…'); + out.extend(chars.iter().skip(chars.len().saturating_sub(tail)).copied()); + out + }; + // the most characters that fit (fewer never measure wider than more, near enough: the + // result is measured again below) + let (mut fits, mut too_many) = (0usize, chars.len()); + while fits + 1 < too_many { + let middle = fits + (too_many - fits) / 2; + if width(&kept(middle)) <= max { + fits = middle; + } else { + too_many = middle; + } + } + (0..=fits).rev().map(kept).find(|out| width(out) <= max).unwrap_or_else(|| "…".to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_exposure_is_said_one_way() { + crate::i18n::set_language(crate::i18n::Locale::En); + // Given what four photos were taken with + assert_eq!(aperture(2.8).as_deref(), Some("f/2.8")); + assert_eq!(aperture(11.0).as_deref(), Some("f/11")); + assert_eq!(aperture(10.04).as_deref(), Some("f/10")); + assert_eq!(aperture(1.4).as_deref(), Some("f/1.4")); + assert_eq!(focal(35.0).as_deref(), Some("35 mm")); + assert_eq!(focal(16.5).as_deref(), Some("16.5 mm")); + assert_eq!(focal(100.0).as_deref(), Some("100 mm")); + assert_eq!(shutter("1/250").as_deref(), Some("1/250 sec")); + assert_eq!(shutter("8").as_deref(), Some("8 sec")); + assert_eq!(shutter("30s").as_deref(), Some("30s")); + assert_eq!(iso(100), "ISO 100"); + // Then a photo's line gives them in a photographer's order, and leaves out what it lacks + let m = Meta { shutter: "1/250".into(), aperture: Some(2.8), iso: Some(100), focal_mm: Some(35.0), ..Default::default() }; + assert_eq!(exposure_line(&m).as_deref(), Some("1/250 sec · f/2.8 · ISO 100 · 35 mm")); + let m = Meta { aperture: Some(11.0), ..Default::default() }; + assert_eq!(exposure_line(&m).as_deref(), Some("f/11")); + assert_eq!(exposure_line(&Meta::default()), None); + } + + #[test] + fn a_number_that_is_none_says_nothing() { + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0, -2.8] { + assert_eq!(aperture(bad), None, "{bad}"); + assert_eq!(focal(bad), None, "{bad}"); + } + assert_eq!(shutter(""), None); + assert_eq!(shutter(" "), None); + // (a number too large to be a lens is still written, not a crash) + assert_eq!(focal(f32::MAX).map(|s| s.ends_with(" mm")), Some(true)); + } + + #[test] + fn a_negative_number_has_a_minus() { + assert_eq!(signed("-1.25"), "−1.25"); + assert_eq!(signed("+35"), "+35"); + assert_eq!(signed("0"), "0"); + assert_eq!(signed("-"), "−"); + assert_eq!(signed(""), ""); + // (only the sign: a range keeps its hyphen) + assert_eq!(signed("16-35"), "16-35"); + } + + #[test] + fn figures_stand_in_cells_of_one_width() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut output = ctx.run_ui(Default::default(), |ui| { + let t = crate::theme::Tokens::for_kind(crate::theme::ThemeKind::Charcoal); + let wide = |s: &str| figures(ui.painter(), s, t.body(), Color32::WHITE).size().x; + let plain = |s: &str| ui.painter().layout_no_wrap(s.to_string(), t.body(), Color32::WHITE).size().x; + // Given numbers of as many figures, the narrowest and the widest + // Then they are as wide as one another, which as the font draws them they are not + assert!((plain("111") - plain("444")).abs() > 2.0, "the font's own figures differ: {} and {}", plain("111"), plain("444")); + // (to a tenth of a point: a glyph is placed on a whole pixel) + assert!((wide("111") - wide("444")).abs() < 0.1, "{} and {}", wide("111"), wide("444")); + assert!((wide("+100") - wide("+111")).abs() < 0.1); + // (beside a point the font moves a figure a little, as it does a letter) + assert!((wide("−1.25") - wide("−4.04")).abs() < 1.0, "{} and {}", wide("−1.25"), wide("−4.04")); + assert!((plain("−1.11") - plain("−4.44")).abs() > 4.0); + // And what is not a figure is as the font has it, and the text is unchanged + assert!((wide("ISO") - plain("ISO")).abs() < 0.1); + assert_eq!(figures(ui.painter(), "−1.25", t.body(), Color32::WHITE).job.text, "−1.25"); + assert_eq!(figures(ui.painter(), "", t.body(), Color32::WHITE).size().x, 0.0); + // And a value with a sign ends where it is told to and begins where any other of as + // many figures does, its 1 no farther from the sign than half its room + let at = egui::pos2(300.0, 40.0); + let (narrow, wide) = + (value(ui.painter(), at, "−1.11", t.body(), Color32::WHITE), value(ui.painter(), at, "−4.44", t.body(), Color32::WHITE)); + assert_eq!((narrow.right(), wide.right()), (300.0, 300.0)); + assert!((narrow.left() - wide.left()).abs() < 1.0, "{narrow:?} {wide:?}"); + assert_eq!(value(ui.painter(), at, "", t.body(), Color32::WHITE).width(), 0.0); + }); + // (nothing is painted: the font atlas made for the measuring is not uploaded anywhere) + output.textures_delta.clear(); + } + + #[test] + fn a_long_name_loses_its_middle_and_keeps_its_number() { + // (a character is a unit wide here) + let width = |s: &str| s.chars().count() as f32; + assert_eq!(elide_middle("DSC_0001", 14.0, width), "DSC_0001"); + assert_eq!(elide_middle("IMG_20240712_153012", 14.0, width), "IMG_20…_153012"); + assert_eq!(elide_middle("IMG_20240712_153012", 5.0, width), "IM…12"); + assert_eq!(elide_middle("IMG_20240712_153012", 2.0, width), "…2"); + assert_eq!(elide_middle("IMG_20240712_153012", 1.0, width), "…"); + assert_eq!(elide_middle("IMG_20240712_153012", 0.0, width), "…"); + assert_eq!(elide_middle("IMG_20240712_153012", f32::NAN, width), "…"); + assert_eq!(elide_middle("", 0.0, width), ""); + // the name from #266: cuts fall on characters, not bytes + assert_eq!(elide_middle("202407層三限定訂閱圖(4)", 9.0, width), "2024…圖(4)"); + // a very long name is not measured once a character + let long = "x".repeat(100_000); + let measured = std::cell::Cell::new(0usize); + let counting = |s: &str| { + measured.set(measured.get() + 1); + s.chars().count() as f32 + }; + assert_eq!(elide_middle(&long, 9.0, counting).chars().count(), 9); + assert!(measured.get() < 40, "{} measurements", measured.get()); + } + + /// Scenario: a name written with combining marks (an accented name as macOS stores it, a vowelled + /// Arabic one) is cut between letters, never between a letter and its mark: no mark is left on the "…". + #[test] + fn a_cut_never_parts_a_letter_from_its_mark() { + // (a letter with its mark is a unit wide here, as it is drawn) + let width = |s: &str| s.chars().filter(|c| !('\u{300}'..='\u{36f}').contains(c) && !('\u{64b}'..='\u{652}').contains(c)).count() as f32; + // Given "été" eight times over, each é an e and a combining acute + let accented = "e\u{301}te\u{301}".repeat(8); + // and a vowelled Arabic word, each letter with its haraka + let vowelled = "\u{643}\u{64e}\u{62a}\u{64e}\u{628}\u{64e}".repeat(6); + for name in [accented.as_str(), vowelled.as_str()] { + for max in 2..12 { + // When it is shortened to any width + let short = elide_middle(name, max as f32, width); + // Then what follows the "…" starts with a letter, and both parts are parts of the name + let (head, tail) = short.split_once('…').expect("shortened"); + let first = tail.chars().next(); + assert!(first.is_none_or(|c| width(&c.to_string()) > 0.0), "{max}: a mark on the ellipsis in {short:?}"); + assert!(name.starts_with(head) && name.ends_with(tail), "{max}: {short:?}"); + assert!(width(&short) <= max as f32, "{max}: {short:?}"); + } + } + } +} diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 3a102a29a90..adaba89452a 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -77,6 +77,13 @@ mod tallies; mod temp_slider; mod titlebar; mod tool_overlay; +mod type_contrast; +mod type_fit; +mod type_on_photo; +mod type_polish; +mod type_readout; +mod type_roles; +mod type_scale; mod unsaved; mod view_cost; mod wb_selector; diff --git a/crates/ui-egui/src/tests/crop_rotate.rs b/crates/ui-egui/src/tests/crop_rotate.rs index 7cab2f08532..7bcd66bd992 100644 --- a/crates/ui-egui/src/tests/crop_rotate.rs +++ b/crates/ui-egui/src/tests/crop_rotate.rs @@ -123,7 +123,7 @@ fn the_angle_reads_like_the_straighten_value() { use crate::panels::detail::crop_angle_label; assert_eq!(crop_angle_label(0.0), "0.00°", "as the Angle field shows it at rest"); assert_eq!(crop_angle_label(2.5), "+2.50°"); - assert_eq!(crop_angle_label(-12.254), "-12.25°"); + assert_eq!(crop_angle_label(-12.254), "−12.25°", "with a minus, as a slider's value has"); assert_eq!(crop_angle_label(-0.001), "0.00°", "no minus zero, and every zero the same"); } diff --git a/crates/ui-egui/src/tests/dialog_fit.rs b/crates/ui-egui/src/tests/dialog_fit.rs index e2e9dd4bf2b..b4b421e5e4e 100644 --- a/crates/ui-egui/src/tests/dialog_fit.rs +++ b/crates/ui-egui/src/tests/dialog_fit.rs @@ -94,12 +94,14 @@ fn export_dialog_is_unchanged_in_a_tall_window() { assert_fits(&h, "Export at 1600×1000"); let dialog = rect(&h, "dialog:window"); // (846 tall as before #781: the whole dialog, nothing scrolled away, plus the Export to row - // since #956; 615 wide since the format row gained JPEG XL, #780. On macOS the dialog has one + // since #956. On macOS the dialog has one // more row, "Add to Apple Photos" (#236), so it is 30 taller there. 8 more since its footer's // buttons are the button component's medium size, 30 points, as the welcome's and every dialog's) let height = if cfg!(target_os = "macos") { 916.0 } else { 886.0 }; assert!((dialog.height() - height).abs() <= 1.0, "{dialog:?}"); - assert!((dialog.width() - 615.2).abs() <= 1.0, "{dialog:?}"); + // (602 wide: 615 when the format row gained JPEG XL, #780, and 13 less since its choices are set at + // caption size, 11 pt where they were 11.5) + assert!((dialog.width() - 602.0).abs() <= 1.0, "{dialog:?}"); } // Scenario: other long dialogs fit a short window too, with their buttons on screen diff --git a/crates/ui-egui/src/tests/type_contrast.rs b/crates/ui-egui/src/tests/type_contrast.rs new file mode 100644 index 00000000000..d7c5aa0ad85 --- /dev/null +++ b/crates/ui-egui/src/tests/type_contrast.rs @@ -0,0 +1,383 @@ +//! What the interface writes can be read in every theme: text stands 4.5:1 against what it is +//! drawn on (3:1 at display size), on the panels, the grid, a photo being edited, Settings and the +//! dialogs. Left out: what is disabled, and text over a picture (its own scrim is another test). +//! +//! Before: the dim text of captions, counts and explanations was 4.20:1 on a panel in Charcoal and +//! 3.3 to 4.3:1 in the light themes, a link in the accent colour 2.56:1 in Charcoal, a caution +//! 3.09:1 in Silver, and anything `.weak()` under 4.1:1 in every theme. + +use std::collections::BTreeMap; +use std::time::Duration; + +use egui::{Color32, Rect}; +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::panels::library_problem::LibraryProblem; +use crate::panels::settings::TABS; +use crate::theme::{TextSize, ThemeKind, Tokens}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo(kind: ThemeKind) -> Headless { + let services = Services { png: None, write_shared: Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1280.0, 900.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + run(&mut h, "view.theme", json!({"theme": kind.id()})); + h +} + +fn run(h: &mut Headless, command: &str, params: Value) { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + rest(h); +} + +fn set(h: &mut Headless, what: Value) { + let r = h.request("ui.set", what, T); + assert_eq!(r["ok"], true, "ui.set: {r}"); + rest(h); +} + +/// Everything drawn and at rest, the pointer over nothing, and no toast: a toast (the one a label +/// gives, say) fades out by the clock, so how much of it is left depends on how fast the frames +/// run, and it is not what is being read. +fn rest(h: &mut Headless) { + h.settle(T); + h.app.ui.toast = None; + h.request("ui.move", json!({"x": 2.0, "y": 2.0}), T); + for _ in 0..3 { + h.step(); + } +} + +/// WCAG contrast of two opaque colours. +fn contrast(a: Color32, b: Color32) -> f32 { + let lum = |c: Color32| { + let lin = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * lin(c.r()) + 0.7152 * lin(c.g()) + 0.0722 * lin(c.b()) + }; + let (a, b) = (lum(a), lum(b)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) +} + +/// `over` drawn on `under`. +fn blend(over: Color32, under: Color32) -> Color32 { + let a = f32::from(over.a()) / 255.0; + // (premultiplied: the colour's channels already carry its alpha) + let mix = |o: u8, u: u8| (f32::from(o) + f32::from(u) * (1.0 - a)).round().clamp(0.0, 255.0) as u8; + Color32::from_rgb(mix(over.r(), under.r()), mix(over.g(), under.g()), mix(over.b(), under.b())) +} + +/// The colour most of `rect` is, and the share of its pixels that are it (one pixel a point). +fn ground(image: &egui::ColorImage, rect: Rect) -> Option<(Color32, f32)> { + let [w, h] = image.size; + let (x0, x1) = (rect.left().floor().max(0.0) as usize, (rect.right().ceil().max(0.0) as usize).min(w)); + let (y0, y1) = (rect.top().floor().max(0.0) as usize, (rect.bottom().ceil().max(0.0) as usize).min(h)); + let mut seen: BTreeMap<[u8; 4], usize> = BTreeMap::new(); + for y in y0..y1 { + for x in x0..x1 { + *seen.entry(image.pixels[y * w + x].to_array()).or_default() += 1; + } + } + let all: usize = seen.values().sum(); + let (most, n) = seen.into_iter().max_by_key(|(_, n)| *n)?; + Some((Color32::from_rgba_premultiplied(most[0], most[1], most[2], most[3]), n as f32 / all as f32)) +} + +/// Whether any pixel of `rect` is nearly `colour`, and nearer it than the ground it would be on +/// (text under a light header is not "inked" by the header's being nearly white). +fn inked(image: &egui::ColorImage, rect: Rect, colour: Color32, ground: Color32) -> bool { + let [w, h] = image.size; + let (x0, x1) = (rect.left().floor().max(0.0) as usize, (rect.right().ceil().max(0.0) as usize).min(w)); + let (y0, y1) = (rect.top().floor().max(0.0) as usize, (rect.bottom().ceil().max(0.0) as usize).min(h)); + let far = |p: Color32, from: Color32| p.r().abs_diff(from.r()).max(p.g().abs_diff(from.g())).max(p.b().abs_diff(from.b())); + (y0..y1).any(|y| (x0..x1).any(|x| image.pixels.get(y * w + x).is_some_and(|p| far(*p, colour) <= 20 && far(*p, colour) < far(*p, ground)))) +} + +/// The text on screen that cannot be read: what it says, its colour, what it is on and how far +/// apart the two stand. +fn unreadable(h: &Headless, t: &Tokens, within: Option) -> Vec { + let image = h.paint(); + let mut out = BTreeMap::new(); + fn texts(shape: &egui::Shape, clip: Rect, out: &mut Vec<(egui::epaint::TextShape, Rect)>) { + match shape { + egui::Shape::Text(text) => out.push((text.clone(), clip)), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| texts(s, clip, out)), + _ => {} + } + } + let mut drawn = Vec::new(); + h.view.shapes.iter().for_each(|s| texts(&s.shape, s.clip_rect, &mut drawn)); + for (text, clip) in drawn { + let said = text.galley.job.text.trim(); + // (a disabled control is drawn fainter as a whole; nothing to read in an empty string) + if said.is_empty() || text.opacity_factor < 1.0 { + continue; + } + let rect = text.visual_bounding_rect().intersect(clip); + // (what lies under a dialog's shade is not what is being read) + if within.is_some_and(|within| !within.contains_rect(rect)) { + continue; + } + // (a row cut by the edge of what scrolls: too little of it is left to say what it is on) + let whole = text.visual_bounding_rect(); + if rect.width() < 2.0 || rect.height() < 2.0 || rect.area() < 0.6 * whole.area() { + continue; + } + // (a little around the letters: a dash's own rectangle is mostly dash) + let Some((on, share)) = ground(&image, rect.expand(2.0)) else { continue }; + // (over a picture no colour is most of the rectangle) + if share < 0.3 { + continue; + } + let large = text.galley.job.sections.iter().all(|s| s.format.font_id.size >= TextSize::Display.points()); + for section in &text.galley.job.sections { + let own = Some(section.format.color).filter(|c| *c != Color32::PLACEHOLDER); + let colour = text.override_text_color.or(own).unwrap_or(text.fallback_color); + // (a count of nothing is fainter on purpose: the rows that hold photos stand out) + if colour == t.text_disabled || colour.a() == 0 || colour == t.text_dim.gamma_multiply(0.55) { + continue; + } + let shown = blend(colour, on); + // (text under a window is drawn and then covered: none of its colour is left) + if !inked(&image, rect, shown, on) { + continue; + } + let stands = contrast(shown, on); + if stands < if large { 3.0 } else { 4.5 } { + let what: String = said.chars().take(28).collect(); + out.entry((shown.to_array(), on.to_array())) + .or_insert_with(|| format!("{what:?} {:?} on {:?}: {stands:.2}", shown.to_array(), on.to_array())); + } + } + } + out.into_values().collect() +} + +fn assert_readable(h: &Headless, kind: ThemeKind, screen: &str, bad: &mut Vec) { + let t = Tokens::for_kind(kind); + // (with a dialog open, the dialog is what is read) + let dialog = h.app.widgets.iter().find(|(w, _)| w == "dialog:window").map(|(_, r)| *r); + assert_eq!(dialog.is_some(), h.app.ui.dialog.is_some(), "{screen}: a dialog and its window go together"); + bad.extend(unreadable(h, &t, dialog).into_iter().map(|line| format!("{kind:?}, {screen}: {line}"))); +} + +fn report(bad: Vec) { + assert!(bad.is_empty(), "{} kinds of text cannot be read:\n{}", bad.len(), bad.join("\n")); +} + +#[test] +fn the_library_can_be_read_in_every_theme() { + let mut bad = Vec::new(); + for kind in ThemeKind::ALL { + // Given the demo library in the grid in a theme, with the sidebar and each right panel + let mut h = demo(kind); + run(&mut h, "view.photoGrid", json!({})); + run(&mut h, "library.select", json!({"ids": [1]})); + for right in ["info", "keywords", "edit", "versions", "activity"] { + // When the panel is shown + set(&mut h, json!({"leftPanel": true, "right": right, "thumbSize": 200})); + // Then its text stands out from what it is on + assert_readable(&h, kind, &format!("grid with {right}"), &mut bad); + } + // And with a filter on (its count is written on a circle of the accent in the top bar), + // in square cells, each with its name and format over it, one of them the chosen one + run(&mut h, "library.filter", json!({"rating": 1})); + run(&mut h, "view.squareGrid", json!({})); + // (two of them with a colour label, which tints the cell: the chosen one and another) + let shown: Vec = h.app.session.visible_cloned().iter().take(3).map(|id| id.0).collect(); + let [chosen, other, ..] = shown[..] else { panic!("{kind:?}: two photos pass the filter") }; + run(&mut h, "photo.label", json!({"ids": [chosen], "label": "red"})); + run(&mut h, "photo.label", json!({"ids": [other], "label": "yellow"})); + run(&mut h, "library.select", json!({"ids": [chosen]})); + for id in [chosen, other] { + assert!(h.app.widgets.iter().any(|(w, _)| *w == format!("thumb:{id}")), "{kind:?}: photo {id} is on screen"); + } + assert!(h.painted_text().iter().any(|t| t == "JPEG"), "{kind:?}: the cells say their format"); + assert_readable(&h, kind, "square grid, filtered", &mut bad); + } + report(bad); +} + +#[test] +fn a_photo_being_edited_can_be_read_in_every_theme() { + let mut bad = Vec::new(); + for kind in ThemeKind::ALL { + // Given a photo opened by itself in a theme, the filmstrip under it + let mut h = demo(kind); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + for right in ["edit", "info", "masking", "crop", "remove", "profiles"] { + // When each tool panel is shown + set(&mut h, json!({"leftPanel": false, "right": right, "openSections": ["light", "color", "effects", "detail"]})); + // Then its text stands out from what it is on + assert_readable(&h, kind, &format!("detail with {right}"), &mut bad); + } + } + report(bad); +} + +#[test] +fn the_names_over_the_filmstrip_can_be_read_on_any_cell_in_every_theme() { + /// The filmstrip's cells that are wholly on screen, by photo. + fn cells(h: &Headless) -> Vec<(u64, Rect)> { + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let cell = |(w, r): &(String, Rect)| Some((w.strip_prefix("film:")?.parse().ok()?, *r)); + h.app.widgets.iter().filter_map(cell).filter(|(_, r)| screen.contains_rect(*r)).collect() + } + const LABELS: [&str; 5] = ["red", "yellow", "green", "blue", "purple"]; + let mut bad = Vec::new(); + for kind in ThemeKind::ALL { + // Given a photo opened by itself in a theme, and on the filmstrip under it a photo with + // each colour label, which tints its cell, and one with none + let mut h = demo(kind); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "info"})); + let others: Vec = cells(&h).iter().map(|(id, _)| *id).filter(|id| *id != 1).take(LABELS.len() + 1).collect(); + let [labelled @ .., plain] = &others[..] else { panic!("{kind:?}: other photos are on the filmstrip") }; + assert_eq!(labelled.len(), LABELS.len(), "{kind:?}: a photo for each label and one more are on the filmstrip"); + for (id, label) in labelled.iter().zip(LABELS) { + run(&mut h, "photo.label", json!({"ids": [id], "label": label})); + } + assert!(h.painted_text().iter().any(|t| t == "JPEG"), "{kind:?}: the cells say their format"); + // Then at rest the names stand out from their cells + assert_readable(&h, kind, "filmstrip at rest", &mut bad); + for (id, label) in labelled.iter().zip(LABELS).chain([(plain, "no label")]) { + // When the pointer is on a cell that is not the chosen one (its fill is see-through) + let cell = cells(&h).iter().find(|(c, _)| c == id).map(|(_, r)| *r); + let Some(cell) = cell else { panic!("{kind:?}: photo {id} is on the filmstrip") }; + h.request("ui.move", json!({"x": cell.center().x, "y": cell.top() + 10.0}), T); + for _ in 0..3 { + h.step(); + } + // Then its name and format stand out from the cell as it is painted + assert_readable(&h, kind, &format!("filmstrip, pointer on a cell with {label}"), &mut bad); + } + for (id, label) in labelled.iter().zip(LABELS) { + // And when a labelled photo is the chosen one + run(&mut h, "library.select", json!({"ids": [id]})); + assert_readable(&h, kind, &format!("filmstrip, the photo with {label} chosen"), &mut bad); + } + } + report(bad); +} + +#[test] +fn settings_and_the_dialogs_can_be_read_in_every_theme() { + let mut bad = Vec::new(); + for kind in ThemeKind::ALL { + let mut h = demo(kind); + // Given each tab of Settings in a theme + for (tab, _) in TABS { + run(&mut h, "app.settings", json!({"tab": tab})); + assert_readable(&h, kind, &format!("Settings ▸ {tab}"), &mut bad); + } + h.request("ui.dialog.cancel", json!({}), T); + // And the dialogs a person meets most + for command in ["dialog.export", "app.shortcuts", "app.about"] { + run(&mut h, command, json!({})); + assert_readable(&h, kind, command, &mut bad); + h.request("ui.dialog.cancel", json!({}), T); + h.step(); + } + } + report(bad); +} + +#[test] +fn the_colours_that_say_something_stand_out_from_every_surface_in_every_theme() { + for kind in ThemeKind::ALL { + let t = Tokens::for_kind(kind); + // Given the surfaces text is written on at rest + for on in [t.chrome, t.canvas, t.grid_bg, t.cell, t.inset, t.field, t.button] { + // When dim text, a link, a caution or an error is written on one + for (what, colour) in [("dim", t.text_dim), ("link", t.text_link()), ("caution", t.text_caution()), ("error", t.text_error())] { + // Then it stands 4.5:1 + assert!(contrast(colour, on) >= 4.5, "{kind:?}: {what} {colour:?} on {on:?} is {:.2}", contrast(colour, on)); + } + } + // And dim text is still dimmer than a label, which is dimmer than what is written + let (dim, label, text) = (contrast(t.text_dim, t.chrome), contrast(t.text_label, t.chrome), contrast(t.text, t.chrome)); + assert!(dim + 1.0 < label && label < text, "{kind:?}: dim {dim:.2}, label {label:.2}, text {text:.2}"); + // And what is chosen keeps its label readable on the accent mixed in behind it + assert!(contrast(t.text_label, t.selection_fill()) >= 4.5, "{kind:?}: a chosen chip"); + assert_ne!(t.selection_fill(), t.chrome, "{kind:?}: what is chosen is marked"); + // And a count or a mark on a filled circle is in the ink that stands out from the fill + for fill in [t.accent, t.reject, t.caution] { + let ink = t.ink_on(fill); + assert!(contrast(ink, fill) >= 4.5, "{kind:?}: {ink:?} on {fill:?} is {:.2}", contrast(ink, fill)); + } + } + // And black or white is chosen by which is farther, also where neither is far + let t = Tokens::for_kind(ThemeKind::Charcoal); + assert_eq!(t.ink_on(Color32::BLACK), Color32::WHITE); + assert_eq!(t.ink_on(Color32::WHITE), Color32::BLACK); + assert_eq!(t.ink_on(Color32::from_gray(118)), Color32::BLACK); +} + +#[test] +fn the_warnings_of_the_slideshow_overlays_can_be_read_in_every_theme() { + let mut bad = Vec::new(); + for kind in ThemeKind::ALL { + let mut h = demo(kind); + // Given a text overlay with a tag that is no token, which the overlays page warns about + run(&mut h, "slideshow.overlays", json!({"addText": {"text": "{notatoken}"}})); + assert!(!h.app.session.slide_overlays.warnings().is_empty(), "{kind:?}: the overlay is warned about"); + // When Settings ▸ Slideshow shows it + run(&mut h, "app.settings", json!({"tab": "slideshow"})); + // (it ends the overlays section, below the fold: the page is scrolled to it) + // (with the pointer over the page, not over the pinned preview or a list that scrolls on its own) + h.request("ui.hoverWidget", json!({"id": "settings:pageRoom"}), T); + for _ in 0..40 { + if h.painted_text().iter().any(|t| t.contains("isn't a token")) { + break; + } + h.request("ui.scroll", json!({"dx": 0.0, "dy": -150.0}), T); + h.settle(T); + } + // (and a little further, so that the line is whole and not cut by the edge of what scrolls) + h.request("ui.scroll", json!({"dx": 0.0, "dy": -120.0}), T); + h.settle(T); + assert!(h.painted_text().iter().any(|t| t.contains("isn't a token")), "{kind:?}: the warning is on the page"); + // Then it stands 4.5:1 from the panel + assert_readable(&h, kind, "Settings ▸ slideshow, an overlay warning", &mut bad); + } + report(bad); +} + +#[test] +fn the_unknown_tag_warning_of_a_template_can_be_read_in_every_theme() { + let mut bad = Vec::new(); + for kind in ThemeKind::ALL { + let mut h = demo(kind); + // Given photos chosen, and the Rename dialog open with a template that has a tag that is no token + run(&mut h, "library.select", json!({"ids": [1, 2]})); + run(&mut h, "dialog.rename", json!({"template": "{notatoken}-{seq:3}"})); + assert!(h.painted_text().iter().any(|t| t.contains("as typed")), "{kind:?}: the template is warned about"); + // Then the warning stands 4.5:1 from the dialog + assert_readable(&h, kind, "Rename, an unknown tag", &mut bad); + } + report(bad); +} + +#[test] +fn the_temporary_session_banner_can_be_read_in_every_theme() { + let mut bad = Vec::new(); + for kind in ThemeKind::ALL { + // Given a session that is temporary (the library did not open), in a theme + let mut h = demo(kind); + h.app.library_problem = Some(LibraryProblem { dismissed: true, ..LibraryProblem::new("/no/such/library", "a test error") }); + rest(&mut h); + assert!(h.app.widgets.iter().any(|(w, _)| w == "indicator:temporarySession"), "{kind:?}: the banner is shown"); + // Then its words and its button stand 4.5:1 from the caution colour it is filled with + assert_readable(&h, kind, "the temporary-session banner", &mut bad); + } + report(bad); +} diff --git a/crates/ui-egui/src/tests/type_fit.rs b/crates/ui-egui/src/tests/type_fit.rs new file mode 100644 index 00000000000..4ecbc8813c9 --- /dev/null +++ b/crates/ui-egui/src/tests/type_fit.rs @@ -0,0 +1,220 @@ +//! Words that are longer in another language keep to their place: a button does not lie over +//! its neighbour, a choice's name stays inside the choice, a row of the filter bar ends inside +//! the bar, and a value begins after its label. +//! +//! Before, in German: Reset ("Zurücksetzen") lay over HDR in the head of the Edit panel, "Mit +//! Hilfslinien" ran out of its third of the Upright choices, and the filter bar's first row ran +//! off the grid at "Bearbeitet oder nicht". (The card of Info already gives a long label its +//! room, "Velocidade do obturador" among them: its scenario keeps it so.) + +use std::time::Duration; + +use egui::Rect; +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo(language: &str) -> Headless { + let services = Services { png: None, write_shared: Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1600.0, 1000.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + run(&mut h, language, json!({})); + run(&mut h, "library.select", json!({"ids": [1]})); + h +} + +fn run(h: &mut Headless, command: &str, params: Value) { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + rest(h); +} + +fn set(h: &mut Headless, what: Value) { + let r = h.request("ui.set", what, T); + assert_eq!(r["ok"], true, "ui.set: {r}"); + rest(h); +} + +fn rest(h: &mut Headless) { + h.settle(T); + h.request("ui.move", json!({"x": 2.0, "y": 2.0}), T); + // (a layout that follows what it measured the frame before has come to rest) + for _ in 0..5 { + h.step(); + } +} + +fn rect(h: &Headless, id: &str) -> Rect { + h.app.widgets.iter().find(|(w, _)| w == id).map(|(_, r)| *r).unwrap_or_else(|| panic!("no widget {id}")) +} + +fn widgets(h: &Headless, prefix: &str) -> Vec<(String, Rect)> { + h.app.widgets.iter().filter(|(w, _)| w.starts_with(prefix)).cloned().collect() +} + +/// Every piece of text drawn, with where it is. +fn texts(h: &Headless) -> Vec<(String, Rect)> { + h.view + .painted_shapes() + .iter() + .filter_map(|shape| match shape { + egui::Shape::Text(text) => Some((text.galley.job.text.clone(), text.visual_bounding_rect())), + _ => None, + }) + .collect() +} + +#[test] +fn the_buttons_at_the_head_of_edit_do_not_lie_over_one_another() { + for language in ["app.language.english", "app.language.german", "app.language.russian", "app.language.french"] { + // Given a photo being edited in a language + let mut h = demo(language); + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "edit", "openSections": ["light"]})); + // When the head of the Edit panel is drawn + let buttons: Vec<(&str, Rect)> = ["auto", "bw", "hdr", "reset"].into_iter().map(|id| (id, rect(&h, &format!("button:{id}")))).collect(); + // Then no button touches another + for (i, (a, ra)) in buttons.iter().enumerate() { + for (b, rb) in buttons.iter().skip(i + 1) { + assert!(!ra.expand(1.0).intersects(*rb), "{language}: {a} {ra:?} lies over {b} {rb:?}"); + } + } + } +} + +/// Reset used to be drawn in a right-to-left layout of the head's single row, and lay over HDR in +/// German. Now the head wraps: Reset goes on the row of the others where it has room (English), +/// on a row of its own where it has not (German), and at the right of the head either way. +#[test] +fn reset_is_on_the_row_of_the_others_when_it_has_room_and_below_them_when_it_has_not() { + for (language, own_row) in [("app.language.english", false), ("app.language.german", true)] { + // Given a photo being edited in a language + let mut h = demo(language); + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "edit", "openSections": ["light"]})); + // When the head of the Edit panel is drawn + let hdr = rect(&h, "button:hdr"); + let reset = rect(&h, "button:reset"); + // Then Reset is below the others only where it has no room beside them + if own_row { + assert!(reset.top() >= hdr.bottom(), "{language}: reset {reset:?} is not below hdr {hdr:?}"); + } else { + assert!((reset.center().y - hdr.center().y).abs() < 4.0, "{language}: reset {reset:?} is not on the row of hdr {hdr:?}"); + assert!(reset.left() >= hdr.right(), "{language}: reset {reset:?} lies over hdr {hdr:?}"); + } + // And at the right of the head either way + assert!(reset.right() > hdr.right(), "{language}: reset {reset:?} is not at the right of hdr {hdr:?}"); + } +} + +#[test] +fn the_name_of_a_choice_stays_inside_the_choice() { + for language in ["app.language.english", "app.language.german", "app.language.russian", "app.language.french", "app.language.spanish"] { + // Given the Crop panel in a language, with its rows of choices + let mut h = demo(language); + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "crop"})); + let drawn = texts(&h); + let mut choices = widgets(&h, "button:cropOverlay-"); + choices.extend(widgets(&h, "button:upright-")); + assert!(choices.len() >= 10, "{language}: the overlay and upright choices are on screen ({})", choices.len()); + // Then each choice's name lies inside it, with a little room at each side + for (id, choice) in choices { + let name = drawn.iter().find(|(_, at)| choice.contains(at.center())).unwrap_or_else(|| panic!("{language}: {id} has no name")); + assert!( + choice.shrink2(egui::vec2(2.0, 0.0)).contains_rect(name.1), + "{language}: {:?} at {:?} runs out of {id} {choice:?}", + name.0, + name.1 + ); + } + } +} + +#[test] +fn a_row_of_the_filter_bar_ends_inside_the_bar() { + for language in ["app.language.english", "app.language.german", "app.language.russian", "app.language.french"] { + // Given the grid with both side panels and the filter bar, in a language + let mut h = demo(language); + run(&mut h, "view.photoGrid", json!({})); + set(&mut h, json!({"leftPanel": true, "right": "info", "thumbSize": 200, "filterBar": true})); + let bar = rect(&h, "filterbar"); + // When its controls are drawn + let mut controls = widgets(&h, "dropdown:filter-"); + controls.extend(["button:filterSave", "button:filterClear", "button:filterPresets"].into_iter().map(|id| (id.to_string(), rect(&h, id)))); + assert!(controls.len() >= 8, "{language}: {}", controls.len()); + // Then every one of them lies in the bar + for (id, control) in controls { + assert!(bar.contains_rect(control), "{language}: {id} {control:?} runs out of the bar {bar:?}"); + } + } +} + +#[test] +fn a_value_on_the_card_of_info_begins_after_its_label() { + for language in ["app.language.english", "app.language.german", "app.language.portuguese", "app.language.spanish", "app.language.french"] { + // Given the Info panel of a photo in a language + let mut h = demo(language); + run(&mut h, "view.photoGrid", json!({})); + set(&mut h, json!({"leftPanel": true, "right": "info", "thumbSize": 200})); + let drawn = texts(&h); + let meta = h.app.session.catalog.photo(lightcraft_catalog::PhotoId(1)).map(|p| p.meta.clone()).expect("photo 1"); + let mut begins = Vec::new(); + for (label, value) in [ + ("Focal length", meta.focal_mm.and_then(crate::readout::focal)), + ("Shutter speed", crate::readout::shutter(&meta.shutter)), + ("Aperture", meta.aperture.and_then(crate::readout::aperture)), + ] { + let (label, value) = (crate::i18n::tr(label).to_string(), value.expect("the demo photo has it")); + let at = |said: &str| { + drawn.iter().find(|(text, _)| text == said).map(|(_, at)| *at).unwrap_or_else(|| panic!("{language}: {said:?} is not drawn")) + }; + let (label_at, value_at) = (at(&label), at(&value)); + // Then the value begins at least a gap after its label ends + assert!(value_at.left() >= label_at.right() + 8.0, "{language}: {label:?} {label_at:?} and {value:?} {value_at:?}"); + begins.push(value_at.left()); + } + // And the values stand under one another + assert!(begins.iter().all(|x| (x - begins[0]).abs() < 1.0), "{language}: {begins:?}"); + } +} + +#[test] +fn the_filter_bar_comes_to_rest_at_every_width() { + for language in ["app.language.english", "app.language.german", "app.language.french"] { + // Given the grid and the filter bar in a language, and what the bar's three parts measure + let mut h = demo(language); + run(&mut h, "view.photoGrid", json!({})); + set(&mut h, json!({"leftPanel": true, "right": "info", "thumbSize": 200, "filterBar": true})); + let parts: [f32; 3] = h.view.ctx.data(|d| d.get_temp(egui::Id::unique("filterbar:widths"))).expect("the bar has measured its parts"); + assert!(parts.iter().all(|w| *w > 40.0), "{language}: {parts:?}"); + let gap = 4.0; + // When the window is as wide as leaves the bar a point or two more or less than each of + // the widths at which what a row holds changes + for edge in [parts[0] + parts[1] + parts[2] + 2.0 * gap, parts[0] + parts[1] + gap, parts[1] + parts[2] + gap] { + for tenth in -40..=40 { + let room = edge + tenth as f32 / 10.0; + h.size.x += room - (rect(&h, "filterbar").width() - 32.0); + let mut heights = Vec::new(); + for _ in 0..12 { + h.step(); + heights.push(rect(&h, "filterbar").height()); + } + assert!(((rect(&h, "filterbar").width() - 32.0) - room).abs() < 0.05, "{language}: the bar has the room asked for"); + // Then within a few frames the bar is one height and stays it: it used to change + // every frame in a band four points wide, and the grid under it jumped + let rest: Vec = heights.iter().skip(6).copied().collect(); + assert!(rest.iter().all(|height| *height == rest[0]), "{language}: at {room} pt of room the bar is {heights:?} high frame by frame"); + // And nothing in it runs out of it + let bar = rect(&h, "filterbar"); + for (id, control) in widgets(&h, "dropdown:filter-") { + assert!(control.right() <= bar.right() + 0.5, "{language}: at {room} pt {id} {control:?} runs out of {bar:?}"); + } + } + } + } +} diff --git a/crates/ui-egui/src/tests/type_on_photo.rs b/crates/ui-egui/src/tests/type_on_photo.rs new file mode 100644 index 00000000000..700d3ec5b86 --- /dev/null +++ b/crates/ui-egui/src/tests/type_on_photo.rs @@ -0,0 +1,390 @@ +//! What is written or marked over a picture is in one light ink on a dark shade of its own, in +//! every theme: the ratings and flags on a thumbnail, the toast, the name of a side in Before and +//! After. A picture has no theme, so the colours of a theme's text do not belong on it. +//! +//! Before: in the light themes a thumbnail's stars were dark grey (the theme's star colour) on the +//! photo or on a dark bar, and the toast wrote the theme's near-black text on a black shade; in +//! the dark themes a rated thumbnail's stars lay on the bare photo and went out on a bright one. + +use std::time::Duration; + +use egui::{Color32, Rect}; +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::theme::{ThemeKind, Tokens}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo(kind: ThemeKind) -> Headless { + let services = Services { png: None, write_shared: Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1600.0, 1000.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + run(&mut h, "view.theme", json!({"theme": kind.id()})); + h +} + +fn run(h: &mut Headless, command: &str, params: Value) { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + rest(h); +} + +/// Everything drawn and at rest, the pointer over nothing. +fn rest(h: &mut Headless) { + h.settle(T); + h.request("ui.move", json!({"x": 2.0, "y": 2.0}), T); + for _ in 0..3 { + h.step(); + } +} + +/// WCAG contrast of two opaque colours. +fn contrast(a: Color32, b: Color32) -> f32 { + let lum = |c: Color32| { + let lin = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * lin(c.r()) + 0.7152 * lin(c.g()) + 0.0722 * lin(c.b()) + }; + let (a, b) = (lum(a), lum(b)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) +} + +fn pixels(image: &egui::ColorImage, rect: Rect) -> Vec { + let [w, h] = image.size; + let (x0, x1) = (rect.left().floor().max(0.0) as usize, (rect.right().ceil().max(0.0) as usize).min(w)); + let (y0, y1) = (rect.top().floor().max(0.0) as usize, (rect.bottom().ceil().max(0.0) as usize).min(h)); + (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).map(|(x, y)| image.pixels[y * w + x]).collect() +} + +/// The colours a drawn shape is filled and outlined in (text aside). +fn colours(shape: &egui::Shape) -> Vec { + match shape { + egui::Shape::Path(path) => match &path.stroke.color { + egui::epaint::ColorMode::Solid(stroke) => vec![path.fill, *stroke], + egui::epaint::ColorMode::UV(_) => vec![path.fill], + }, + egui::Shape::LineSegment { stroke, .. } => vec![stroke.color], + egui::Shape::Circle(circle) => vec![circle.fill, circle.stroke.color], + egui::Shape::Ellipse(ellipse) => vec![ellipse.fill, ellipse.stroke.color], + egui::Shape::Rect(rect) => vec![rect.fill, rect.stroke.color], + _ => Vec::new(), + } +} + +/// A rated photo's cell that is on screen and not the chosen one: `prefix` is `thumb` or `film`. +fn rated_cell(h: &Headless, prefix: &str, chosen: u64) -> (Rect, u8) { + let screen = Rect::from_min_size(egui::Pos2::ZERO, h.size); + h.app + .widgets + .iter() + .filter_map(|(id, r)| Some((id.strip_prefix(prefix)?.strip_prefix(':')?.parse::().ok()?, *r))) + .filter(|(id, r)| *id != chosen && screen.contains_rect(*r)) + .find_map(|(id, r)| { + let photo = h.app.session.catalog.photo(lightcraft_catalog::PhotoId(id))?; + (photo.rating >= 2 && photo.label.is_none()).then_some((r, photo.rating)) + }) + .unwrap_or_else(|| panic!("no rated {prefix} on screen")) +} + +/// In the strip along the bottom of `cell`: marks are drawn in the ink for pictures, each on a +/// rectangle of the shade, and the shade is under them in the picture that results. +fn assert_marked(h: &Headless, cell: Rect, rating: u8, what: &str) { + let (ink, shade) = (Tokens::on_photo(), Tokens::photo_shade()); + let strip = Rect::from_min_max(egui::pos2(cell.left(), cell.bottom() - 30.0), cell.right_bottom()); + let shapes = h.view.painted_shapes(); + let within: Vec<&egui::Shape> = shapes.iter().filter(|s| strip.contains_rect(s.visual_bounding_rect())).collect(); + // (a star is one shape or a few; there are at least as many in the ink as stars) + let marks: Vec = + within.iter().filter(|s| !matches!(s, egui::Shape::Rect(_)) && colours(s).contains(&ink)).map(|s| s.visual_bounding_rect()).collect(); + assert!(marks.len() >= usize::from(rating), "{what}: {} marks in the ink {ink:?} for {rating} stars", marks.len()); + // (the shade may be wider than the cell: a photo cut to its cell brings its strip along) + let shades: Vec = + shapes.iter().filter(|s| matches!(s, egui::Shape::Rect(r) if r.fill == shade)).map(|s| s.visual_bounding_rect()).collect(); + for mark in &marks { + assert!(shades.iter().any(|shade| shade.expand(1.0).contains_rect(*mark)), "{what}: the mark at {mark:?} has no shade under it ({shades:?})"); + } + // And in the picture: the shade beside the marks is dark enough for the ink to stand 3:1 + let image = h.paint(); + let [w, height] = image.size; + let mut stands = Vec::new(); + for shade in shades.iter().filter(|shade| marks.iter().any(|mark| shade.expand(1.0).contains_rect(*mark))) { + let inside = shade.shrink(1.0).intersect(cell); + for y in inside.top().ceil().max(0.0) as usize..(inside.bottom().floor().max(0.0) as usize).min(height) { + for x in inside.left().ceil().max(0.0) as usize..(inside.right().floor().max(0.0) as usize).min(w) { + let here = egui::pos2(x as f32 + 0.5, y as f32 + 0.5); + if !marks.iter().any(|mark| mark.expand(1.5).contains(here)) { + stands.push(contrast(ink, image.pixels[y * w + x])); + } + } + } + } + stands.sort_by(f32::total_cmp); + // (a tenth in: a mark's soft edge may reach a pixel past its rectangle) + let ground = stands.get(stands.len() / 10).copied().unwrap_or(1.0); + assert!(stands.len() >= 12 && ground >= 3.0, "{what}: the ink stands {ground:.2} against its shade ({} pixels of it)", stands.len()); +} + +/// The first text shape that says `part`: its colour and where it is. +fn text(h: &Headless, part: &str) -> (Color32, Rect) { + h.view + .painted_shapes() + .iter() + .find_map(|shape| match shape { + egui::Shape::Text(text) if text.galley.job.text.contains(part) => { + let own = text.galley.job.sections.first().map(|s| s.format.color).filter(|c| *c != Color32::PLACEHOLDER); + Some((text.override_text_color.or(own).unwrap_or(text.fallback_color), text.visual_bounding_rect())) + } + _ => None, + }) + .unwrap_or_else(|| panic!("no text with {part:?} is drawn")) +} + +/// The colour most of `rect` is. +fn ground(image: &egui::ColorImage, rect: Rect) -> Color32 { + let mut seen = std::collections::BTreeMap::new(); + for p in pixels(image, rect) { + *seen.entry(p.to_array()).or_insert(0usize) += 1; + } + let most = seen.into_iter().max_by_key(|(_, n)| *n).map(|(c, _)| c).unwrap_or([0; 4]); + Color32::from_rgb(most[0], most[1], most[2]) +} + +#[test] +fn the_marks_on_a_thumbnail_stand_out_from_the_photo_in_every_theme() { + for kind in ThemeKind::ALL { + // Given the grid in a theme, and a rated photo that is neither chosen nor under the pointer + let mut h = demo(kind); + run(&mut h, "view.photoGrid", json!({})); + run(&mut h, "library.select", json!({"ids": [2]})); + let r = h.request("ui.set", json!({"leftPanel": true, "right": "info", "thumbSize": 200}), T); + assert_eq!(r["ok"], true, "{r}"); + rest(&mut h); + // When it is drawn + let (thumb, rating) = rated_cell(&h, "thumb", 2); + // Then its stars are in the ink for pictures, on a shade that lets them stand 3:1 + assert_marked(&h, thumb, rating, &format!("{kind:?}: the stars on a thumbnail")); + } +} + +#[test] +fn the_marks_on_a_filmstrip_cell_stand_out_in_every_theme() { + for kind in ThemeKind::ALL { + // Given a photo opened by itself in a theme, the filmstrip under it + let mut h = demo(kind); + run(&mut h, "library.select", json!({"ids": [2]})); + run(&mut h, "view.detail", json!({})); + // When a rated photo's cell is drawn + let (cell, rating) = rated_cell(&h, "film", 2); + // Then its stars are in the ink for pictures on their shade + assert_marked(&h, cell, rating, &format!("{kind:?}: the stars on a filmstrip cell")); + } +} + +#[test] +fn a_toast_can_be_read_in_every_theme() { + for kind in ThemeKind::ALL { + // Given a photo opened by itself in a theme + let mut h = demo(kind); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + // When something is said in a toast + let now = h.app.tick_now(); + h.app.ui.toast = Some(("Rated 3 stars".into(), now + 60.0, None)); + h.step(); + h.step(); + // Then it is written in the ink for pictures and stands 4.5:1 against its shade + let (colour, at) = text(&h, "Rated 3 stars"); + assert_eq!(colour, Tokens::on_photo(), "{kind:?}"); + let on = ground(&h.paint(), at.expand(6.0)); + assert!(contrast(colour, on) >= 4.5, "{kind:?}: {colour:?} on {on:?} is {:.2}", contrast(colour, on)); + } +} + +#[test] +fn before_is_named_on_a_shade_of_its_own_in_every_theme() { + for kind in ThemeKind::ALL { + // Given a photo opened by itself in a theme + let mut h = demo(kind); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + // When the photo is shown as it was before its edits + run(&mut h, "view.showOriginal", json!({})); + // Then "Before" is written over the picture in the ink for pictures, on a shade + let (colour, at) = text(&h, "Before"); + assert_eq!(colour, Tokens::on_photo(), "{kind:?}"); + let on = ground(&h.paint(), at.expand(3.0)); + assert!(contrast(colour, on) >= 4.5, "{kind:?}: {colour:?} on {on:?} is {:.2}", contrast(colour, on)); + } +} + +#[test] +fn the_ink_for_pictures_stands_out_from_its_shade_over_any_picture() { + // Given the shade laid over the brightest and the darkest a picture can be + let (ink, shade) = (Tokens::on_photo(), Tokens::photo_shade()); + let a = f32::from(shade.a()) / 255.0; + for under in [Color32::WHITE, Color32::BLACK, Color32::from_rgb(255, 230, 40)] { + let mix = |u: u8| (f32::from(u) * (1.0 - a)).round() as u8; + let on = Color32::from_rgb(mix(under.r()), mix(under.g()), mix(under.b())); + // Then the ink stands 4.5:1 on it + assert!(contrast(ink, on) >= 4.5, "{ink:?} over {under:?}: {:.2}", contrast(ink, on)); + } +} + +#[test] +fn a_rejection_over_a_picture_is_a_red_that_stands_out_from_its_shade() { + // Given the red a rejected photo's flag is drawn in over a picture + let (red, shade) = (Tokens::on_photo_reject(), Tokens::photo_shade()); + let a = f32::from(shade.a()) / 255.0; + // When the shade lies over the brightest a picture can be, and over the darkest + for under in [Color32::WHITE, Color32::BLACK] { + let mix = |u: u8| (f32::from(u) * (1.0 - a)).round() as u8; + let on = Color32::from_rgb(mix(under.r()), mix(under.g()), mix(under.b())); + // Then the flag stands 3:1, as a mark must + assert!(contrast(red, on) >= 3.0, "{red:?} over {under:?}: {:.2}", contrast(red, on)); + } + // And it is drawn in that red in every theme, on a shade (the theme's own red is for panels) + for kind in ThemeKind::ALL { + let mut h = demo(kind); + run(&mut h, "view.photoGrid", json!({})); + let rejected = h + .app + .session + .catalog + .photos() + .find(|p| p.flag == lightcraft_catalog::Flag::Reject) + .map(|p| p.id.0) + .expect("the demo has a rejected photo"); + run(&mut h, "library.select", json!({"ids": [rejected]})); + run(&mut h, "view.detail", json!({})); + let cell = h.app.widgets.iter().find(|(w, _)| *w == format!("film:{rejected}")).map(|(_, r)| *r).expect("its filmstrip cell"); + let shapes = h.view.painted_shapes(); + let flags: Vec = shapes + .iter() + .filter(|s| colours(s).contains(&red) && cell.intersects(s.visual_bounding_rect())) + .map(|s| s.visual_bounding_rect()) + .collect(); + assert!(!flags.is_empty(), "{kind:?}: the flag is in {red:?}"); + let shades: Vec = + shapes.iter().filter(|s| matches!(s, egui::Shape::Rect(r) if r.fill == shade)).map(|s| s.visual_bounding_rect()).collect(); + for flag in flags { + assert!(shades.iter().any(|shade| shade.expand(1.0).contains_rect(flag)), "{kind:?}: the flag at {flag:?} has no shade ({shades:?})"); + } + } +} + +#[test] +fn the_marks_of_a_narrow_thumbnail_stay_on_the_thumbnail() { + // Given the grid with thumbnails so small that a portrait one is narrower than its marks + let mut h = demo(ThemeKind::Charcoal); + run(&mut h, "view.photoGrid", json!({})); + let r = h.request("ui.set", json!({"leftPanel": true, "right": "info", "thumbSize": 60}), T); + assert_eq!(r["ok"], true, "{r}"); + rest(&mut h); + let cells: Vec = h.app.widgets.iter().filter(|(w, _)| w.starts_with("thumb:")).map(|(_, r)| *r).collect(); + assert!(cells.len() >= 8 && cells.iter().any(|c| c.width() < 60.0), "narrow thumbnails are on screen"); + // When their marks are drawn + fn marks(shape: &egui::Shape, clip: Rect, out: &mut Vec<(Rect, Rect)>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| marks(s, clip, out)), + other if colours(other).contains(&Tokens::on_photo()) && !matches!(other, egui::Shape::Rect(_)) => { + out.push((other.visual_bounding_rect(), clip)) + } + _ => {} + } + } + let mut drawn = Vec::new(); + h.view.shapes.iter().for_each(|s| marks(&s.shape, s.clip_rect, &mut drawn)); + assert!(drawn.len() >= 8, "marks are drawn ({})", drawn.len()); + // Then what shows of each lies on its own thumbnail: none reaches over the gap to the next + for (mark, clip) in drawn { + let shown = mark.intersect(clip); + if shown.width() <= 0.0 || shown.height() <= 0.0 { + continue; + } + assert!(cells.iter().any(|cell| cell.expand(0.5).contains_rect(shown)), "the mark at {shown:?} is on no thumbnail"); + } +} + +#[test] +fn a_photo_chosen_or_under_the_pointer_keeps_the_band_along_its_lower_edge() { + for kind in ThemeKind::ALL { + // Given the grid in a theme, and a photo with no rating, flag, label or edit + let mut h = demo(kind); + run(&mut h, "view.photoGrid", json!({})); + let r = h.request("ui.set", json!({"leftPanel": true, "right": "info", "thumbSize": 200}), T); + assert_eq!(r["ok"], true, "{r}"); + rest(&mut h); + let screen = Rect::from_min_size(egui::Pos2::ZERO, h.size); + let plain = h + .app + .widgets + .iter() + .filter_map(|(id, r)| Some((id.strip_prefix("thumb:")?.parse::().ok()?, *r))) + .filter(|(_, r)| screen.contains_rect(*r)) + .find(|(id, _)| { + h.app + .session + .catalog + .photo(lightcraft_catalog::PhotoId(*id)) + .is_some_and(|p| p.rating == 0 && p.flag == lightcraft_catalog::Flag::None && p.label.is_none() && !p.is_edited()) + }) + .map(|(id, _)| id) + .expect("a plain photo is on screen"); + let band = |h: &Headless| { + let cell = h.app.widgets.iter().find(|(w, _)| *w == format!("thumb:{plain}")).map(|(_, r)| *r).expect("its thumbnail"); + let strip = Rect::from_min_max(egui::pos2(cell.left(), cell.bottom() - 24.0), cell.right_bottom()); + h.view.painted_shapes().iter().any(|s| matches!(s, egui::Shape::Rect(r) if r.fill == Color32::from_black_alpha(120) && (r.rect.width() - strip.width()).abs() < 1.0 && strip.expand(1.0).contains_rect(r.rect))) + }; + // When it is not chosen, it has no band; when it is chosen, it has one the width of the + // photo: in the light themes its outline alone is 1.1 to 2.1:1 against the grid + run(&mut h, "library.select", json!({"ids": []})); + assert!(!band(&h), "{kind:?}: a photo that is not chosen has no band"); + // When the pointer is on it, it has the band (nothing else says the pointer is there) + let cell = h.app.widgets.iter().find(|(w, _)| *w == format!("thumb:{plain}")).map(|(_, r)| *r).expect("its thumbnail"); + h.request("ui.move", json!({"x": cell.center().x, "y": cell.center().y}), T); + for _ in 0..3 { + h.step(); + } + assert!(band(&h), "{kind:?}: the photo under the pointer has its band"); + rest(&mut h); + assert!(!band(&h), "{kind:?}: the band goes when the pointer does"); + run(&mut h, "library.select", json!({"ids": [plain]})); + assert!(band(&h), "{kind:?}: the chosen photo has its band"); + } +} + +#[test] +fn a_rejected_photos_flag_is_not_dimmed_with_the_photo() { + for kind in ThemeKind::ALL { + // Given the grid in a theme, with a rejected photo (which is drawn dimmed) + let mut h = demo(kind); + run(&mut h, "view.photoGrid", json!({})); + let r = h.request("ui.set", json!({"leftPanel": false, "right": "none", "thumbSize": 110}), T); + assert_eq!(r["ok"], true, "{r}"); + run(&mut h, "library.select", json!({"ids": []})); + let screen = Rect::from_min_size(egui::Pos2::ZERO, h.size); + let cell = h + .app + .widgets + .iter() + .filter_map(|(id, r)| Some((id.strip_prefix("thumb:")?.parse::().ok()?, *r))) + .filter(|(_, r)| screen.contains_rect(*r)) + .find(|(id, _)| h.app.session.catalog.photo(lightcraft_catalog::PhotoId(*id)).is_some_and(|p| p.flag == lightcraft_catalog::Flag::Reject)) + .map(|(_, r)| r) + .expect("a rejected photo is on screen"); + // When it is painted + let image = h.paint(); + let strip = Rect::from_min_max(egui::pos2(cell.left(), cell.bottom() - 24.0), cell.right_bottom()); + // Then its flag is in the red for pictures as that red is: the dimming lies under the + // marks, not over them + let red = Tokens::on_photo_reject(); + let all = pixels(&image, strip); + let flag = all.iter().filter(|p| p.r().abs_diff(red.r()).max(p.g().abs_diff(red.g())).max(p.b().abs_diff(red.b())) <= 24).count(); + assert!(flag >= 6, "{kind:?}: {flag} pixels of the flag's red {red:?} along the lower edge"); + } +} diff --git a/crates/ui-egui/src/tests/type_polish.rs b/crates/ui-egui/src/tests/type_polish.rs new file mode 100644 index 00000000000..8fc94cb5041 --- /dev/null +++ b/crates/ui-egui/src/tests/type_polish.rs @@ -0,0 +1,164 @@ +//! Smaller matters of how the interface writes: emphasis that shows, a value no larger than the +//! header over it, a format in capitals with room between its letters, what an empty view says +//! kept inside the view, and a German date with both its numbers in two figures. + +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::theme::{TextSize, ThemeKind, Tokens}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo(size: [f32; 2]) -> Headless { + let services = Services { png: None, write_shared: Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), size, 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + h +} + +fn run(h: &mut Headless, command: &str, params: Value) { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + rest(h); +} + +fn set(h: &mut Headless, what: Value) { + let r = h.request("ui.set", what, T); + assert_eq!(r["ok"], true, "ui.set: {r}"); + rest(h); +} + +fn rest(h: &mut Headless) { + h.settle(T); + for _ in 0..3 { + h.step(); + } +} + +/// The text shapes whose text has `part`. +fn drawn(h: &Headless, part: &str) -> Vec { + h.view + .painted_shapes() + .into_iter() + .filter_map(|shape| match shape { + egui::Shape::Text(text) if text.galley.job.text.contains(part) => Some(text), + _ => None, + }) + .collect() +} + +#[test] +fn emphasis_is_the_colour_of_what_is_written_in_every_theme() { + for kind in ThemeKind::ALL { + // Given a theme applied + let ctx = egui::Context::default(); + crate::theme::apply_kind(&ctx, kind); + let (t, visuals) = (Tokens::for_kind(kind), ctx.global_style().visuals.clone()); + // Then text marked strong is in the text colour, which stands out from a label's, and + // text marked weak is the dim text + assert_eq!(visuals.strong_text_color(), t.text, "{kind:?}"); + assert_ne!(visuals.strong_text_color(), visuals.text_color(), "{kind:?}: strong is told from plain"); + assert_eq!(visuals.weak_text_color(), t.text_dim, "{kind:?}"); + // And a label marked strong is drawn in it (the theme's one colour for all text does not + // take it back) + let mut output = ctx.run_ui(Default::default(), |ui| { + ui.label(egui::RichText::new("marked").strong()); + ui.label("plain"); + }); + let colour = |said: &str| { + output.shapes.iter().find_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.job.text == said => { + let own = text.galley.job.sections.first().map(|s| s.format.color).filter(|c| *c != egui::Color32::PLACEHOLDER); + Some(text.override_text_color.or(own).unwrap_or(text.fallback_color)) + } + _ => None, + }) + }; + assert_eq!((colour("marked"), colour("plain")), (Some(t.text), Some(t.text_label)), "{kind:?}"); + output.textures_delta.clear(); + } +} + +#[test] +fn a_value_in_edit_is_no_larger_than_the_header_of_its_section() { + // Given a photo being edited, the Light and Color sections open + let mut h = demo([1600.0, 1000.0]); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "edit", "openSections": ["light", "color"]})); + let size = |part: &str| { + let shapes = drawn(&h, part); + let shape = shapes.iter().find(|s| s.galley.job.text == part).unwrap_or_else(|| panic!("{part:?} is not drawn")); + shape.galley.job.sections.first().map(|s| s.format.font_id.size).unwrap_or(0.0) + }; + // Then the profile and the white balance are written at the size of a control's value, under + // headers a step larger + assert_eq!(size("Light"), TextSize::Title.points()); + assert_eq!(size("As Shot"), TextSize::Body.points()); + // (the profile of a demo photo is Color, which is also the name of a section) + let mut colors: Vec = drawn(&h, "Color") + .iter() + .filter(|s| s.galley.job.text == "Color") + .filter_map(|s| s.galley.job.sections.first().map(|s| s.format.font_id.size)) + .collect(); + colors.sort_by(f32::total_cmp); + assert_eq!(colors, [TextSize::Body.points(), TextSize::Title.points()], "the profile's value and the section's header"); +} + +#[test] +fn a_format_in_capitals_has_room_between_its_letters() { + // Given the Info panel of a photo + let mut h = demo([1600.0, 1000.0]); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.photoGrid", json!({})); + set(&mut h, json!({"leftPanel": true, "right": "info", "thumbSize": 200})); + // Then the format on its card, written in capitals, is spaced a little + let chips: Vec = drawn(&h, "JPEG").iter().filter_map(|s| s.galley.job.sections.first().map(|s| s.format.extra_letter_spacing)).collect(); + assert!(chips.iter().any(|spacing| *spacing >= 0.4), "{chips:?}"); +} + +#[test] +fn what_an_empty_view_says_stays_inside_the_view() { + // Given a narrow view with nothing to show and much to say + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply_kind(&ctx, ThemeKind::Charcoal); + let view = egui::Rect::from_min_size(egui::pos2(120.0, 60.0), egui::vec2(300.0, 400.0)); + let body = "Right-click a photo ▸ Set as Reference Photo, then View → Reference View (Shift+R)"; + // When it says what to do + let mut output = ctx.run_ui(Default::default(), |ui| crate::panels::empty_message(ui, view, "No reference photo", body)); + let said: Vec = output + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) => Some(text.clone()), + _ => None, + }) + .collect(); + output.textures_delta.clear(); + // Then the title and the sentence are inside the view, the sentence on more than one line, + // and the title above it + assert_eq!(said.len(), 2, "a title and a sentence"); + for text in &said { + let at = text.visual_bounding_rect(); + assert!(view.contains_rect(at), "{:?} at {at:?} runs out of {view:?}", text.galley.job.text); + } + assert!(said[1].galley.rows.len() >= 2, "the sentence is wrapped"); + assert!(said[0].visual_bounding_rect().bottom() <= said[1].visual_bounding_rect().top()); + // And both are centred in it + for text in &said { + assert!((text.visual_bounding_rect().center().x - view.center().x).abs() < 3.0, "{:?}", text.visual_bounding_rect()); + } +} + +#[test] +fn a_german_date_has_its_day_in_two_figures_as_its_month_is() { + crate::i18n::set_language(crate::i18n::Locale::De); + assert_eq!(crate::i18n::date_group_label("2026-09-04", false), "Freitag, 04.09.2026"); + assert_eq!(crate::i18n::date_group_label("2026-09-20", false), "Sonntag, 20.09.2026"); + crate::i18n::set_language(crate::i18n::Locale::En); +} diff --git a/crates/ui-egui/src/tests/type_readout.rs b/crates/ui-egui/src/tests/type_readout.rs new file mode 100644 index 00000000000..206106d2bde --- /dev/null +++ b/crates/ui-egui/src/tests/type_readout.rs @@ -0,0 +1,211 @@ +//! What is read off a photo or a control is written one way: an exposure in the same words +//! wherever it is shown, a negative value with a minus, values in a column of figures. +//! (The parts are tested in `readout.rs`; here, what a person sees.) + +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo() -> Headless { + let services = Services { png: None, write_shared: Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1600.0, 1000.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + h +} + +fn run(h: &mut Headless, command: &str, params: Value) { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + rest(h); +} + +fn set(h: &mut Headless, what: Value) { + let r = h.request("ui.set", what, T); + assert_eq!(r["ok"], true, "ui.set: {r}"); + rest(h); +} + +fn rest(h: &mut Headless) { + h.settle(T); + for _ in 0..3 { + h.step(); + } +} + +/// Where the text that is exactly `said` was drawn. +fn drawn(h: &Headless, said: &str) -> egui::Rect { + h.view + .painted_shapes() + .iter() + .find_map(|shape| match shape { + egui::Shape::Text(text) if text.galley.job.text == said => Some(text.visual_bounding_rect()), + _ => None, + }) + .unwrap_or_else(|| { + panic!( + "{said:?} is not drawn; drawn: {:?}", + h.painted_text().iter().filter(|t| t.chars().any(|c| c.is_ascii_digit())).collect::>() + ) + }) +} + +#[test] +fn a_photos_exposure_reads_the_same_wherever_it_is_shown() { + // Given a photo of the demo library and what it was taken with + let mut h = demo(); + run(&mut h, "library.select", json!({"ids": [1]})); + let meta = h.app.session.catalog.photo(lightcraft_catalog::PhotoId(1)).map(|p| p.meta.clone()).expect("photo 1"); + let parts = crate::readout::exposure(&meta); + let line = parts.join(" · "); + assert_eq!(parts.len(), 4, "the demo photo has all four: {line}"); + assert!(line.contains(" sec · f/") && line.contains(" · ISO ") && line.ends_with(" mm"), "{line}"); + let said = |h: &Headless, what: &str| h.painted_text().iter().any(|t| t == what); + // When it is shown in the Info panel, each part is on its row as the line has it + run(&mut h, "view.photoGrid", json!({})); + set(&mut h, json!({"leftPanel": true, "right": "info", "thumbSize": 200})); + for part in parts.iter().filter(|part| !part.starts_with("ISO")) { + assert!(said(&h, part), "Info says {part:?}: {:?}", h.painted_text()); + } + // And over a square cell of the grid, the line + run(&mut h, "view.squareGrid", json!({})); + run(&mut h, "view.gridInfo", json!({"info": "exposure"})); + set(&mut h, json!({"thumbSize": 320})); + let lines: Vec = h.app.session.catalog.photos().filter_map(|p| crate::readout::exposure_line(&p.meta)).collect(); + let over_cells: Vec = h.painted_text().into_iter().filter(|t| t.contains(" · ISO ")).collect(); + assert!(over_cells.len() >= 3, "cells say what their photos were taken with: {over_cells:?}"); + for over in &over_cells { + assert!(lines.contains(over), "the grid says {over:?}, which is no photo's line"); + } + run(&mut h, "view.squareGrid", json!({})); + // And under the histogram of the Edit panel, the line + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "edit", "openSections": ["light"]})); + assert!(said(&h, &line), "the histogram says {line:?}"); + // And in the overlay on the photo, the line + run(&mut h, "view.infoOverlay", json!({})); + if !said(&h, &line) { + run(&mut h, "view.infoOverlay", json!({})); + } + assert!(said(&h, &line), "the overlay says {line:?}"); + // Then nowhere on these screens is an aperture spaced out or a focal length run together + for text in h.painted_text() { + assert!(!text.contains("f / "), "{text:?}"); + assert!(!text.as_bytes().windows(3).any(|w| w[0].is_ascii_digit() && &w[1..] == b"mm"), "{text:?}"); + } +} + +#[test] +fn a_negative_value_has_a_minus_and_is_typed_with_either_sign() { + // Given a photo being edited + let mut h = demo(); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "edit", "openSections": ["light"]})); + // When its exposure is taken down + run(&mut h, "develop.set", json!({"values": {"light.exposure": -1.25}})); + // Then the value is written with a minus, not a hyphen + let texts = h.painted_text(); + assert!(texts.iter().any(|t| t == "−1.25"), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "-1.25")); + // And what is typed into the value is read with the minus it was shown with, or a hyphen + let exposure = lightcraft_develop::controls::find("light.exposure").expect("the exposure control"); + assert_eq!(crate::widgets::typed_value(exposure, "−1.25"), Some(-1.25)); + assert_eq!(crate::widgets::typed_value(exposure, "-1.25"), Some(-1.25)); + assert_eq!(crate::widgets::typed_value(exposure, "−"), None); +} + +/// Scenario: a value is typed with the digits an Arabic or Persian keyboard gives. +#[test] +fn a_value_is_typed_in_arabic_or_persian_digits() { + // Given the exposure, contrast and temperature controls + let exposure = lightcraft_develop::controls::find("light.exposure").expect("the exposure control"); + let contrast = lightcraft_develop::controls::find("light.contrast").expect("the contrast control"); + let temp = lightcraft_develop::controls::find("wb.temp").expect("the temperature control"); + // When a value is typed in Arabic-Indic digits, with the Arabic decimal sign or a point + // Then it is the number those digits write + assert_eq!(crate::widgets::typed_value(exposure, "١٫٢٥"), Some(1.25)); + assert_eq!(crate::widgets::typed_value(exposure, "١.٢٥"), Some(1.25)); + assert_eq!(crate::widgets::typed_value(exposure, "-٠٫٥"), Some(-0.5)); + assert_eq!(crate::widgets::typed_value(exposure, "−٠٫٥"), Some(-0.5), "with the minus a value is shown with"); + // And with the Arabic percent sign, or a unit, after it + assert_eq!(crate::widgets::typed_value(contrast, "٢٠٪"), Some(20.0)); + assert_eq!(crate::widgets::typed_value(temp, "٥٦٠٠ K"), Some(5600.0)); + // And in the Persian forms of the digits, or the two kinds together + assert_eq!(crate::widgets::typed_value(exposure, "۱٫۲۵"), Some(1.25)); + assert_eq!(crate::widgets::typed_value(contrast, "۲0"), Some(20.0)); + // And with the direction marks a keyboard or a paste can put around a number + assert_eq!(crate::widgets::typed_value(contrast, "\u{200f}٢٠\u{200e}"), Some(20.0)); + assert_eq!(crate::widgets::typed_value(contrast, "\u{61c}-٢٠"), Some(-20.0)); + // (a number pasted from an app that wraps it in an isolate or an embedding) + assert_eq!(crate::widgets::typed_value(contrast, "\u{2068}٢٠\u{2069}"), Some(20.0)); + assert_eq!(crate::widgets::typed_value(contrast, "\u{202a}20\u{202c}"), Some(20.0)); + // And with the Arabic comma for the decimal sign, as a comma is one + assert_eq!(crate::widgets::typed_value(exposure, "١،٥"), Some(1.5)); + // And an angle with its degree sign, whatever follows the sign + assert_eq!(crate::widgets::typed_value(contrast, "٥°\u{200e}"), Some(5.0)); + assert_eq!(crate::widgets::typed_value(contrast, "5 °"), Some(5.0)); + // But what is not a number stays one: the slider keeps its value + for bad in ["٫", "١٫٢٫٣", "٪", "١٬٢٠٠", "٢٠ك"] { + assert_eq!(crate::widgets::typed_value(contrast, bad), None, "{bad:?}"); + } +} + +#[test] +fn the_values_of_sliders_stand_in_one_column() { + // Given a photo being edited + let mut h = demo(); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + set(&mut h, json!({"leftPanel": false, "right": "edit", "openSections": ["light"]})); + // When two sliders hold numbers of as many figures, narrow ones and wide ones + run(&mut h, "develop.set", json!({"values": {"light.contrast": 11, "light.highlights": 44}})); + // Then the two values begin at the same place, and end within half the room a 1 leaves in + // its cell (as the font draws them, "+11" is six points narrower than "+44") + let (narrow, wide) = (drawn(&h, "+11"), drawn(&h, "+44")); + assert!((narrow.left() - wide.left()).abs() < 1.0, "{narrow:?} {wide:?}"); + assert!((narrow.right() - wide.right()).abs() < 2.5, "{narrow:?} {wide:?}"); +} + +#[test] +fn the_counts_of_the_sidebar_are_set_in_figures_of_one_width() { + // Given the library with its sidebar and the counts beside its rows + let mut h = demo(); + run(&mut h, "view.photoGrid", json!({})); + set(&mut h, json!({"leftPanel": true, "right": "info", "thumbSize": 200})); + let left = h.app.widgets.iter().find(|(w, _)| w == "thumb:1").map_or(480.0, |(_, r)| r.left()); + // When the count of all photos is drawn (two figures) + let all = h.app.session.catalog.photos().count().to_string(); + let counts: Vec = h + .view + .painted_shapes() + .into_iter() + .filter_map(|shape| match shape { + egui::Shape::Text(text) if text.galley.job.text == all && text.pos.x < left => Some(text), + _ => None, + }) + .collect(); + // Then on the row of All Photos a figure narrower than the widest is given the room it + // lacks before it (the font's own "2" is narrower than its "4"; rows drawn by other code, + // such as By Date, are not this change's) + let room = |count: &egui::epaint::TextShape| count.galley.job.sections.first().map_or(0.0, |s| s.leading_space); + assert!(all.starts_with('2'), "the demo has twenty-odd photos ({all})"); + assert!(counts.iter().any(|count| room(count) > 0.1), "no count of {all} in the sidebar is set in cells ({} counts)", counts.len()); +} + +#[test] +fn a_value_opens_for_typing_with_a_hyphen_a_keyboard_has() { + // Given a negative and a positive value as a slider shows them + let exposure = lightcraft_develop::controls::find("light.exposure").expect("the exposure control"); + assert_eq!(crate::widgets::shown_value(exposure, -1.25), "−1.25"); + // When the value is opened to be typed over + // Then the draft has the keyboard's hyphen (what is copied from it pastes anywhere) and no plus + assert_eq!(crate::widgets::draft_value(exposure, -1.25), "-1.25"); + assert_eq!(crate::widgets::draft_value(exposure, 0.5), "0.50"); + assert_eq!(crate::widgets::typed_value(exposure, &crate::widgets::draft_value(exposure, -1.25)), Some(-1.25)); +} diff --git a/crates/ui-egui/src/tests/type_roles.rs b/crates/ui-egui/src/tests/type_roles.rs new file mode 100644 index 00000000000..17b46eb9eb9 --- /dev/null +++ b/crates/ui-egui/src/tests/type_roles.rs @@ -0,0 +1,68 @@ +//! The type roles (`theme::TextSize` and `Tokens::caption()`, `Tokens::body_strong()` and the +//! like): seven sizes, each with a job, in a regular and a semibold face. This is the model; the +//! panels move over to it as their text is touched. + +use egui::FontFamily; + +use crate::theme::{FONT_SEMIBOLD, TextSize, ThemeKind, Tokens}; + +fn tokens() -> Tokens { + Tokens::for_kind(ThemeKind::Charcoal) +} + +#[test] +fn the_sizes_are_those_of_the_scale_smallest_first() { + // Given the seven roles + let points: Vec = TextSize::ALL.iter().map(|size| size.points()).collect(); + // Then their sizes are 10, 11, 12, 13, 14, 15 and 18 pt, each larger than the one before + assert_eq!(points, [10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 18.0]); +} + +#[test] +fn the_sizes_of_the_scale_are_a_point_or_more_apart() { + // Two sizes closer than a point cannot be told apart, so they would not carry different jobs + for pair in TextSize::ALL.windows(2) { + assert!(pair[1].points() - pair[0].points() >= 1.0, "{pair:?}"); + } +} + +#[test] +fn each_role_gives_its_size_in_both_faces() { + let t = tokens(); + // Given each role's regular and semibold font + let roles = [ + (TextSize::Micro, t.micro(), t.micro_strong()), + (TextSize::Caption, t.caption(), t.caption_strong()), + (TextSize::Label, t.label(), t.label_strong()), + (TextSize::Body, t.body(), t.body_strong()), + (TextSize::Title, t.title(), t.title_strong()), + (TextSize::PanelTitle, t.panel_title(), t.panel_title_strong()), + (TextSize::Display, t.display(), t.display_strong()), + ]; + assert_eq!(roles.len(), TextSize::ALL.len()); + for (size, regular, strong) in roles { + // Then both are the role's size, the regular in the proportional family and the strong in the semibold + assert_eq!((regular.size, strong.size), (size.points(), size.points()), "{size:?}"); + assert_eq!(regular.family, FontFamily::Proportional, "{size:?}"); + assert_eq!(strong.family, FontFamily::Name(FONT_SEMIBOLD.into()), "{size:?}"); + // And asking the theme by role is the same font + assert_eq!((t.regular(size), t.strong(size)), (regular, strong), "{size:?}"); + } +} + +#[test] +fn the_text_styles_a_control_takes_are_roles() { + // Given the theme applied to a context + let t = tokens(); + let ctx = egui::Context::default(); + crate::theme::apply_kind(&ctx, ThemeKind::Charcoal); + // When a label, a button, small text and a window's title take their style's font + let style = ctx.global_style(); + let font = |s: egui::TextStyle| style.text_styles.get(&s).cloned(); + // Then each is a named size, in the regular face + assert_eq!(font(egui::TextStyle::Body), Some(t.body())); + assert_eq!(font(egui::TextStyle::Button), Some(t.body())); + assert_eq!(font(egui::TextStyle::Small), Some(t.caption())); + // And a window's title is the panel's name, in semibold + assert_eq!(font(egui::TextStyle::Heading), Some(t.panel_title_strong())); +} diff --git a/crates/ui-egui/src/tests/type_scale.rs b/crates/ui-egui/src/tests/type_scale.rs new file mode 100644 index 00000000000..c05dd7fd759 --- /dev/null +++ b/crates/ui-egui/src/tests/type_scale.rs @@ -0,0 +1,172 @@ +//! Text is set in seven sizes, one per job (`theme::TextSize`), so that two sizes on a screen are +//! always told apart and the same job is the same size on every panel. +//! +//! Before: 17 sizes from 8.5 to 20 pt, 102 of 237 uses on half points. A slider's name (12.5) stood +//! by a checkbox's (13), a caption was 11 in Settings and 11.5 in Info, and panel titles came in +//! 13.5, 14, 15 and 17. + +use std::collections::BTreeMap; +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::headless::Headless; +use crate::panels::settings::TABS; +use crate::theme::{TextSize, ThemeKind, Tokens}; +use crate::{LightcraftApp, Services}; + +const T: Duration = Duration::from_secs(20); + +fn demo() -> Headless { + let services = Services { png: None, write_shared: Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; + let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1600.0, 1000.0], 1.0); + // let the first renders finish (a render still running at exit can crash in GPU teardown) + h.settle(T); + h +} + +fn run(h: &mut Headless, command: &str, params: Value) { + let r = h.request("engine.execute", json!({"command": command, "params": params}), T); + assert_eq!(r["ok"], true, "{command}: {r}"); + h.settle(T); + h.step(); + h.step(); +} + +fn set(h: &mut Headless, what: Value) { + let r = h.request("ui.set", what, T); + assert_eq!(r["ok"], true, "ui.set: {r}"); + h.settle(T); + h.step(); + h.step(); +} + +/// The sizes of the text the last frame drew that are not on the scale, each with a piece of +/// text drawn in it (hundredths of a point, so that they sort). +fn off_scale(h: &Headless) -> BTreeMap { + let mut out = BTreeMap::new(); + for shape in h.view.painted_shapes() { + let egui::Shape::Text(text) = shape else { continue }; + for section in &text.galley.job.sections { + let size = section.format.font_id.size; + if !TextSize::ALL.iter().any(|role| (role.points() - size).abs() < 0.01) { + out.entry((size * 100.0).round() as u32).or_insert_with(|| text.galley.job.text.chars().take(40).collect()); + } + } + } + out +} + +fn assert_on_scale(h: &Headless, screen: &str) { + let off = off_scale(h); + assert!(off.is_empty(), "{screen}: text drawn off the scale (size × 100, a sample): {off:?}"); +} + +#[test] +fn the_library_draws_its_text_on_the_scale() { + // Given the demo library in the grid, with the sidebar and each right panel in turn + let mut h = demo(); + run(&mut h, "view.photoGrid", json!({})); + run(&mut h, "library.select", json!({"ids": [1]})); + for right in ["info", "keywords", "edit", "versions", "activity"] { + // When the panel is shown + set(&mut h, json!({"leftPanel": true, "right": right, "thumbSize": 200})); + // Then every piece of text on screen is one of the seven sizes + assert_on_scale(&h, &format!("grid with {right}")); + } +} + +#[test] +fn a_photo_being_edited_draws_its_text_on_the_scale() { + // Given a photo opened by itself with the Edit panel's sections open and the filmstrip under it + let mut h = demo(); + run(&mut h, "library.select", json!({"ids": [1]})); + run(&mut h, "view.detail", json!({})); + for right in ["edit", "info", "masking", "crop", "remove", "profiles"] { + // When each tool panel is shown + set(&mut h, json!({"leftPanel": false, "right": right, "openSections": ["light", "color", "effects", "detail"]})); + // Then every piece of text on screen is one of the seven sizes + assert_on_scale(&h, &format!("detail with {right}")); + } +} + +#[test] +fn settings_and_the_dialogs_draw_their_text_on_the_scale() { + let mut h = demo(); + // Given each tab of Settings + for (tab, _) in TABS { + // When it is shown + run(&mut h, "app.settings", json!({"tab": tab})); + // Then its title, tabs, headings, rows and explanations are on the scale + assert_on_scale(&h, &format!("Settings ▸ {tab}")); + } + h.request("ui.dialog.cancel", json!({}), T); + // And given the dialogs a person meets most + for command in ["dialog.export", "app.shortcuts", "app.about"] { + // When one is open + run(&mut h, command, json!({})); + // Then so is everything in it + assert_on_scale(&h, command); + h.request("ui.dialog.cancel", json!({}), T); + h.step(); + } +} + +#[test] +fn a_size_asked_for_by_number_is_given_on_the_scale() { + let t = Tokens::for_kind(ThemeKind::Charcoal); + let on_scale = |points: f32| TextSize::ALL.iter().any(|size| size.points() == points); + // Given any number of points, also none at all + for asked in (0..=120).map(|quarter| quarter as f32 * 0.25).chain([f32::NAN, f32::INFINITY, -4.0]) { + // When either face is asked for at it + let (regular, strong) = (t.font(asked), t.semibold(asked)); + // Then the font is one of the seven sizes + assert!(on_scale(regular.size) && on_scale(strong.size), "{asked} gave {} and {}", regular.size, strong.size); + } + // And a size between two goes to the one nearer a control's, one below the smallest to the smallest + for (asked, given) in [(8.5, 10.0), (10.5, 11.0), (11.5, 12.0), (12.5, 13.0), (13.5, 13.0), (16.0, 15.0), (17.0, 18.0), (20.0, 18.0)] { + assert_eq!(TextSize::nearest(asked).points(), given, "{asked}"); + } + // And what is past either end is the end, however far + for (asked, given) in [(1e9, 18.0), (f32::MAX, 18.0), (f32::INFINITY, 18.0), (-1e9, 10.0), (f32::NEG_INFINITY, 10.0), (0.0, 10.0)] { + assert_eq!(TextSize::nearest(asked).points(), given, "{asked}"); + } + assert_eq!(TextSize::nearest(f32::NAN), TextSize::Body); + // And a size of the scale is itself + for size in TextSize::ALL { + assert_eq!(TextSize::nearest(size.points()), size); + } +} + +#[test] +fn the_line_over_a_square_cell_ends_before_the_format() { + // Given the square grid with small cells, and each thing a cell can say over its photo + // (one language: the language is the whole process's, and other tests read English) + for language in ["English"] { + let mut h = demo(); + run(&mut h, "view.photoGrid", json!({})); + run(&mut h, "view.squareGrid", json!({})); + for info in ["exposure", "date", "filename"] { + run(&mut h, "view.gridInfo", json!({"info": info})); + set(&mut h, json!({"thumbSize": 110})); + // When the cells are drawn + let texts: Vec<(String, egui::Rect)> = h + .view + .painted_shapes() + .iter() + .filter_map(|shape| match shape { + egui::Shape::Text(text) => Some((text.galley.job.text.clone(), text.visual_bounding_rect())), + _ => None, + }) + .collect(); + let formats: Vec<&(String, egui::Rect)> = texts.iter().filter(|(said, _)| said == "JPEG").collect(); + assert!(formats.len() >= 4, "{language} {info}: cells with their format are on screen ({})", formats.len()); + // Then no line runs under a format: it is cut short before it + for (_, format) in formats { + let room = format.expand2(egui::vec2(3.0, 0.0)); + let under: Vec<&String> = texts.iter().filter(|(said, at)| said != "JPEG" && at.intersects(room)).map(|(said, _)| said).collect(); + assert!(under.is_empty(), "{language} {info}: {under:?} runs under the format at {format:?}"); + } + } + } +} diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index e55008efdb0..a1785deb090 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -10,6 +10,66 @@ use std::sync::Arc; use egui::{Color32, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Stroke, Visuals}; pub const FONT_SEMIBOLD: &str = "semibold"; + +/// The sizes text is set in, one per job. The steps are a point or more, so two sizes on a screen +/// are told apart; a panel names the size its text has (`t.caption()`, `t.body_strong()`, …) +/// instead of writing a number. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextSize { + /// A badge or a pill on a thumbnail or an icon. + Micro, + /// An explanation, the caption over a field, a line of status; in semibold, a small button or + /// a choice. + Caption, + /// What stands by something larger: a count, the title of a tab, a control of the filter bar. + Label, + /// Controls, rows, values and menus. + Body, + /// The header of a section in a panel. + Title, + /// The name of a panel or of a window. + PanelTitle, + /// The title over the photos, and what an empty screen says. + Display, +} + +impl TextSize { + /// Smallest first. + pub const ALL: [TextSize; 7] = + [TextSize::Micro, TextSize::Caption, TextSize::Label, TextSize::Body, TextSize::Title, TextSize::PanelTitle, TextSize::Display]; + + /// The size in points. + pub const fn points(self) -> f32 { + match self { + TextSize::Micro => 10.0, + TextSize::Caption => 11.0, + TextSize::Label => 12.0, + TextSize::Body => 13.0, + TextSize::Title => 14.0, + TextSize::PanelTitle => 15.0, + TextSize::Display => 18.0, + } + } + + /// The size nearest a number of points; of two equally near, the one nearer [`TextSize::Body`] + /// (12.5 is 13 and so is 13.5). Anything past the ends is the end: a huge number or infinity + /// the largest, a negative one the smallest. Not a number: the size of a control. + pub fn nearest(points: f32) -> TextSize { + // (far from the scale every size is as near as the next in an f32) + let points = points.clamp(0.0, 1000.0); + let body = TextSize::Body.points(); + let mut best = TextSize::Body; + let mut least = f32::INFINITY; + for size in TextSize::ALL { + let off = (size.points() - points).abs(); + if off < least || (off == least && (size.points() - body).abs() < (best.points() - body).abs()) { + (best, least) = (size, off); + } + } + best + } +} + const WEB_CHINESE_FONT: &str = "web Noto Sans CJK SC"; /// Shared colour-label palette for badges, thumbnail surrounds and feedback. @@ -168,7 +228,7 @@ impl Tokens { pub fn for_kind(kind: ThemeKind) -> Tokens { let rgb = |v: u32| Color32::from_rgb((v >> 16) as u8, (v >> 8) as u8, v as u8); let base = Tokens::default(); - match kind { + let t = match kind { ThemeKind::Charcoal => base, ThemeKind::Midnight => Tokens { chrome: rgb(0x1e1e1e), @@ -250,17 +310,170 @@ impl Tokens { caution: rgb(0xb0761a), ..base }, + }; + // The dim text of captions, counts and explanations is read like any other: it stands + // 4.5:1 against every surface it is written on (as observed it was 4.20:1 on a panel in + // Charcoal, and 3.3 to 4.3:1 on the light themes' surfaces). + Tokens { text_dim: t.on_surfaces(t.text_dim), ..t } + } + + /// The surfaces text is written on at rest: panels, the canvas, the grid and its cells, + /// insets, text boxes and buttons. (A hovered, pressed or selected surface is passing or + /// marked otherwise: text there is made legible against it where it is drawn.) + fn surfaces(&self) -> [Color32; 7] { + [self.chrome, self.canvas, self.grid_bg, self.cell, self.inset, self.field, self.button] + } + + /// `color`, brought as far toward the text colour as it takes to stand 4.5:1 against every + /// surface of [`Self::surfaces`]: a colour that says something as text. + fn on_surfaces(&self, color: Color32) -> Color32 { + self.surfaces().into_iter().fold(color, |c, on| self.legible(c, on, 4.5)) + } + + /// What is written or marked over a picture: a picture has no theme, so this is the same + /// light ink in every theme, on [`Self::photo_shade`]. + pub const fn on_photo() -> Color32 { + Color32::from_rgb(0xf2, 0xf2, 0xf2) + } + + /// The flag of a rejected photo over a picture: a red light enough to stand 3:1 on the shade + /// whatever is under it (a theme's own red is made for its panels: 2.3 to 3:1 here). + pub const fn on_photo_reject() -> Color32 { + Color32::from_rgb(0xff, 0x6b, 0x6b) + } + + /// The shade under what is written or marked over a picture. + /// (Black at 200 of 255: over white it is a grey the ink stands about 10.6:1 against, and + /// [`Self::on_photo_reject`] 4:1.) + pub fn photo_shade() -> Color32 { + Color32::from_black_alpha(200) + } + + /// The accent as text: a link, "in use", what Auto Sync is doing. (The accent itself is + /// for fills and outlines: as text it is 2.56:1 on a panel in Charcoal.) + pub fn text_link(&self) -> Color32 { + self.on_surfaces(self.accent) + } + + /// The caution colour as text. (3.09:1 on a panel in Silver as it is.) + pub fn text_caution(&self) -> Color32 { + self.on_surfaces(self.caution) + } + + /// The colour of a rejection or an error as text. + pub fn text_error(&self) -> Color32 { + self.on_surfaces(self.reject) + } + + /// What is written on a filled mark (a count on the accent, "!" on the error colour): black + /// or white, whichever stands out more. + pub fn ink_on(&self, fill: Color32) -> Color32 { + let white = self.legible(Color32::WHITE, fill, 4.5) == Color32::WHITE; + let black = self.legible(Color32::BLACK, fill, 4.5) == Color32::BLACK; + match (white, black) { + (true, false) => Color32::WHITE, + (false, true) => Color32::BLACK, + // both stand 4.5:1 or neither does: the farther from the fill + _ if Self::lightness(fill) < 0.18 => Color32::WHITE, + _ => Color32::BLACK, } } + /// Relative luminance (WCAG), 0 black to 1 white. + fn lightness(c: Color32) -> f32 { + let linear = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * linear(c.r()) + 0.7152 * linear(c.g()) + 0.0722 * linear(c.b()) + } + + /// The fill behind what is chosen (a chosen chip): the accent mixed into the + /// panel as strongly as leaves the label colour 4.5:1 on it. + pub fn selection_fill(&self) -> Color32 { + const STEPS: u8 = 12; + (0..=STEPS) + .rev() + .map(|step| self.chrome.lerp_to_gamma(self.accent, 0.6 * f32::from(step) / f32::from(STEPS))) + .find(|fill| self.legible(self.text_label, *fill, 4.5) == self.text_label) + .unwrap_or(self.chrome) + } + pub fn get(ctx: &egui::Context) -> Tokens { ctx.data(|d| d.get_temp::(egui::Id::NULL)).unwrap_or_default() } + /// The regular face at the size of the scale nearest `size` ([`TextSize::nearest`]): text + /// asked for by a number is on the scale too. New code names the size (`t.body()`, …). pub fn font(&self, size: f32) -> FontId { - FontId::proportional(size) + self.regular(TextSize::nearest(size)) } + /// The semibold face at the size of the scale nearest `size`. pub fn semibold(&self, size: f32) -> FontId { - FontId::new(size, FontFamily::Name(FONT_SEMIBOLD.into())) + self.strong(TextSize::nearest(size)) + } + /// The regular face at a size of the scale. + pub fn regular(&self, size: TextSize) -> FontId { + FontId::proportional(size.points()) + } + /// The semibold face at a size of the scale. + pub fn strong(&self, size: TextSize) -> FontId { + FontId::new(size.points(), FontFamily::Name(FONT_SEMIBOLD.into())) + } + /// Micro: a badge or a pill on a thumbnail or an icon. + pub fn micro(&self) -> FontId { + self.regular(TextSize::Micro) + } + /// [`Self::micro`] in semibold. + pub fn micro_strong(&self) -> FontId { + self.strong(TextSize::Micro) + } + /// Caption: an explanation, the caption over a field, a line of status; in semibold, a small button. + pub fn caption(&self) -> FontId { + self.regular(TextSize::Caption) + } + /// [`Self::caption`] in semibold. + pub fn caption_strong(&self) -> FontId { + self.strong(TextSize::Caption) + } + /// Label: what stands by something larger: a count, the title of a tab. + pub fn label(&self) -> FontId { + self.regular(TextSize::Label) + } + /// [`Self::label`] in semibold. + pub fn label_strong(&self) -> FontId { + self.strong(TextSize::Label) + } + /// Body: controls, rows, values and menus. + pub fn body(&self) -> FontId { + self.regular(TextSize::Body) + } + /// [`Self::body`] in semibold. + pub fn body_strong(&self) -> FontId { + self.strong(TextSize::Body) + } + /// Title: the header of a section in a panel (set strong; plain is for a value at its size). + pub fn title(&self) -> FontId { + self.regular(TextSize::Title) + } + /// [`Self::title`] in semibold. + pub fn title_strong(&self) -> FontId { + self.strong(TextSize::Title) + } + /// PanelTitle: the name of a panel or of a window (set strong). + pub fn panel_title(&self) -> FontId { + self.regular(TextSize::PanelTitle) + } + /// [`Self::panel_title`] in semibold. + pub fn panel_title_strong(&self) -> FontId { + self.strong(TextSize::PanelTitle) + } + /// Display: the title over the photos, and what an empty screen says (set strong). + pub fn display(&self) -> FontId { + self.regular(TextSize::Display) + } + /// [`Self::display`] in semibold. + pub fn display_strong(&self) -> FontId { + self.strong(TextSize::Display) } } @@ -389,6 +602,32 @@ fn theme_id() -> egui::Id { egui::Id::unique("lightcraft-theme") } +impl Tokens { + /// `color` as it is where it stands `ratio`:1 or more against `on`, as WCAG measures it (4.5 + /// for text, 3 for a line or a mark that says where something is); else moved toward the text + /// colour, which stands furthest from every surface, in small steps until it does, and the + /// text colour itself when nothing on the way does (or `ratio` is no number). + /// + /// For text and marks drawn in a token chosen for its hue or its quietness (the dim text, the + /// accent, the caution and reject colours, a border) on a surface where a theme's value for it + /// is too close to read: the token keeps its value for everything else that uses it. + pub fn legible(&self, color: Color32, on: Color32, ratio: f32) -> Color32 { + fn luminance(c: Color32) -> f32 { + let linear = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * linear(c.r()) + 0.7152 * linear(c.g()) + 0.0722 * linear(c.b()) + } + let stands = |c: Color32| { + let (a, b) = (luminance(c), luminance(on)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) >= ratio + }; + const STEPS: u8 = 32; + (0..STEPS).map(|step| color.lerp_to_gamma(self.text, f32::from(step) / f32::from(STEPS))).find(|c| stands(*c)).unwrap_or(self.text) + } +} + /// The theme `ctx` is styled with (none before the first [`apply_kind`]). pub fn current(ctx: &egui::Context) -> Option { ctx.data(|d| d.get_temp::(theme_id())) @@ -426,9 +665,12 @@ pub fn apply_kind(ctx: &egui::Context, kind: ThemeKind) { v.window_stroke = Stroke::new(1.0, t.button_border); v.window_corner_radius = CornerRadius::same(6); v.menu_corner_radius = CornerRadius::same(6); - v.selection.bg_fill = t.accent.gamma_multiply(0.6); + v.selection.bg_fill = t.selection_fill(); v.selection.stroke = Stroke::new(1.0, t.accent); v.override_text_color = Some(t.text_label); + // (egui's own: the label colour at 60 %, under 4.1:1 in every theme, and a bright blue) + v.weak_text_color = Some(t.text_dim); + v.hyperlink_color = t.text_link(); let (popup, window) = if dark { (140, 160) } else { (50, 60) }; v.popup_shadow = egui::epaint::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(popup) }; v.window_shadow = egui::epaint::Shadow { offset: [0, 8], blur: 30, spread: 0, color: Color32::from_black_alpha(window) }; @@ -438,6 +680,9 @@ pub fn apply_kind(ctx: &egui::Context, kind: ThemeKind) { CornerRadius::same(4), Stroke::new(1.0, t.text_label), ); + // (what is marked strong is in the text colour: egui takes it from here, and as the label + // colour it was no different from plain text; so are the icons of a control being pressed) + w.active.fg_stroke = Stroke::new(1.0, t.text); w.noninteractive.bg_stroke = Stroke::new(1.0, t.divider); w.inactive.bg_stroke = Stroke::new(1.0, t.button_border); ctx.set_visuals_of(egui::Theme::Dark, v.clone()); @@ -447,10 +692,10 @@ pub fn apply_kind(ctx: &egui::Context, kind: ThemeKind) { s.spacing.item_spacing = egui::vec2(6.0, 4.0); s.spacing.button_padding = egui::vec2(8.0, 3.0); s.spacing.interact_size.y = 22.0; - s.text_styles.insert(egui::TextStyle::Body, FontId::proportional(13.0)); - s.text_styles.insert(egui::TextStyle::Button, FontId::proportional(13.0)); - s.text_styles.insert(egui::TextStyle::Small, FontId::proportional(11.0)); - s.text_styles.insert(egui::TextStyle::Heading, FontId::new(16.0, FontFamily::Name(FONT_SEMIBOLD.into()))); + s.text_styles.insert(egui::TextStyle::Body, t.body()); + s.text_styles.insert(egui::TextStyle::Button, t.body()); + s.text_styles.insert(egui::TextStyle::Small, t.caption()); + s.text_styles.insert(egui::TextStyle::Heading, t.panel_title_strong()); s.animation_time = 0.08; }); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 89185d9918a..6e6d305dad9 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -225,10 +225,10 @@ pub fn preview_only_notice(ui: &mut Ui, key: &str, reason: &str) -> bool { ui.horizontal(|ui| { let (ir, _) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::hover()); paint(ui.painter(), ir, Icon::Info, t.caution); - ui.label(egui::RichText::new(crate::i18n::tr("Preview only")).font(t.semibold(12.5)).color(t.text)); + ui.label(egui::RichText::new(crate::i18n::tr("Preview only")).font(t.body_strong()).color(t.text)); }); ui.add_space(2.0); - ui.label(egui::RichText::new(preview_only_explanation(reason)).size(11.5).color(t.text_label)); + ui.label(egui::RichText::new(preview_only_explanation(reason)).font(t.caption()).color(t.text_label)); ui.add_space(6.0); reload = text_button(ui, &format!("reloadPreviewOnly:{key}"), "Reload from Disk", false).clicked(); }) @@ -317,11 +317,29 @@ pub struct SliderOut { } /// What a value typed into a slider asks for (issue #322): a number such as `0.5`, `+12`, `-1,5` -/// (comma or point) or `5600 K`, on the control's steps and clamped to its range. `None` when it -/// isn't a finite number, so the slider keeps its value. +/// (comma or point), `5600 K` or `5°`, on the control's steps and clamped to its range. The digits may +/// be the Arabic-Indic or Persian ones (`١٫٥`, `۲۰٪`), as an Arabic or Persian keyboard gives +/// them. `None` when it isn't a finite number, so the slider keeps its value. pub fn typed_value(spec: &ControlSpec, text: &str) -> Option { - let t = text.trim().replace(',', "."); - let t = t.trim_end_matches(|c: char| c == '%' || c == 'K' || c == 'k' || c.is_whitespace()); + let t: String = text + .chars() + // (the marks a keyboard or a paste puts around a number to say which way it reads: the + // direction marks, and the embeddings and isolates an app wraps a number in) + .filter(|c| !matches!(c, '\u{200e}' | '\u{200f}' | '\u{61c}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')) + .map(|c| match c { + // (Arabic-Indic digits, and their Persian forms) + '\u{660}'..='\u{669}' => char::from_digit(c as u32 - 0x660, 10).unwrap_or(c), + '\u{6f0}'..='\u{6f9}' => char::from_digit(c as u32 - 0x6f0, 10).unwrap_or(c), + // (a decimal comma, the Arabic comma, or the Arabic decimal sign) + ',' | '\u{60c}' | '\u{66b}' => '.', + '\u{66a}' => '%', + // (a minus as the value is shown with, or the hyphen of a keyboard) + crate::readout::MINUS => '-', + c => c, + }) + .collect(); + let t = t.trim(); + let t = t.trim_end_matches(|c: char| c == '%' || c == '°' || c == 'K' || c == 'k' || c.is_whitespace()); let v: f64 = t.parse().ok().filter(|v: &f64| v.is_finite())?; let step = spec.step.max(1e-9); Some(((v / step).round() * step).clamp(spec.min, spec.max)) @@ -330,7 +348,7 @@ pub fn typed_value(spec: &ControlSpec, text: &str) -> Option { /// A slider's value as shown next to its label. pub(crate) fn shown_value(spec: &ControlSpec, v: f64) -> String { let shown = if spec.id == "wb.temp" { format!("{v:.0}") } else { spec.format(v).replace("+0.00", "0").replace("-0.00", "0") }; - if shown == "+0" || shown == "-0" { "0".to_string() } else { shown } + if shown == "+0" || shown == "-0" { "0".to_string() } else { crate::readout::signed(&shown) } } /// Pointer travel (points, sideways from the press) that turns a press on a slider's value into a @@ -385,6 +403,12 @@ fn update_wheel_arming(ui: &mut Ui, id: egui::Id, resp: &egui::Response, row: Re /// The radius of a slider's hollow ring thumb. const THUMB_RING: f32 = 7.0; +/// A slider's value as the text its field opens with: no plus, and the hyphen of a keyboard +/// for the minus it is shown with, so that what is copied from the field pastes anywhere. +pub(crate) fn draft_value(spec: &ControlSpec, v: f64) -> String { + shown_value(spec, v).trim_start_matches('+').replace(crate::readout::MINUS, "-") +} + /// A Lightroom slider row (label + value above a track with a hollow ring thumb). /// Double-click the label or thumb to reset (hovering either says so). Shift-drag = fine adjustment. /// Scroll sideways over it to nudge it. Click the value to type one: Return or clicking away applies it, @@ -456,10 +480,10 @@ pub fn slider(ui: &mut Ui, spec: &ControlSpec, value: f64, enabled: bool, label_ let hovered = resp.hovered() || resp.dragged(); let text_c = if enabled { t.text_label } else { t.text_disabled }; let p = ui.painter(); - p.text(label_rect.left_center(), Align2::LEFT_CENTER, crate::i18n::tr(label_override.unwrap_or(spec.label)), t.font(12.5), text_c); + p.text(label_rect.left_center(), Align2::LEFT_CENTER, crate::i18n::tr(label_override.unwrap_or(spec.label)), t.body(), text_c); if typing.is_none() { - p.text(label_rect.right_center(), Align2::RIGHT_CENTER, shown_value(spec, v), t.font(12.5), text_c); - // the scrub pointer, as over Lightroom's values: a drag here changes the value + // (in a column of figures: the value keeps its place while it changes) + crate::readout::value(p, label_rect.right_center(), &shown_value(spec, v), t.body(), text_c); if enabled && (value_resp.hovered() || scrub.is_some()) { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); } @@ -595,7 +619,7 @@ fn update_typing_gesture(ui: &mut Ui, g: &SliderLayout, value_resp: &Response, t let value_pressed = value_resp.is_pointer_button_down_on() && ui.input(|i| i.pointer.button_pressed(egui::PointerButton::Primary)); // Focus on the owned primary press before fast typing; retain the readout's click activation. if g.enabled && typing.is_none() && (value_resp.clicked() || value_pressed) { - *typing = Some((shown_value(g.spec, g.value).trim_start_matches('+').to_string(), 0, value_pressed)); + *typing = Some((draft_value(g.spec, g.value), 0, value_pressed)); } let value_released = ui.input(|i| i.pointer.button_released(egui::PointerButton::Primary)); // A release over the value keeps the field the press opened, however long the button was held @@ -646,7 +670,7 @@ fn edit_value(ui: &mut Ui, t: &Tokens, g: &SliderLayout, draft: Draft, out: &mut let mut child = ui.new_child(egui::UiBuilder::new().max_rect(g.value_rect).layout(egui::Layout::right_to_left(egui::Align::Center))); // the old value is selected when the field takes the focus, so typing replaces it let field = crate::text_field::TextField::singleline(&format!("sliderField:{}", g.spec.id), &mut text) - .font(t.font(12.5)) + .font(t.body()) .horizontal_align(egui::Align::RIGHT) .width(g.value_rect.width()) .margin(egui::Margin::ZERO) @@ -886,13 +910,24 @@ pub fn flyout_row(ui: &mut Ui, id: &str, title: &str, icon: Icon, open: bool) -> resp } +/// How wide a [`text_button`] is, for the width of its label. +fn text_button_size(label_w: f32) -> f32 { + (label_w + 18.0).max(37.0) +} + +/// How wide a [`text_button`] with this label is: for a row that has to know whether one fits. +pub fn text_button_width(ui: &Ui, label: &str) -> f32 { + let t = Tokens::get(ui.ctx()); + text_button_size(ui.painter().layout_no_wrap(crate::i18n::tr(label).to_string(), t.caption_strong(), t.text).size().x) +} + /// A small bordered text button (Auto, B&W, HDR…). pub fn text_button(ui: &mut Ui, id: &str, label: &str, active: bool) -> Response { let label = if id.starts_with("labelSet-") { label } else { crate::i18n::tr(label) }; let t = Tokens::get(ui.ctx()); - let font = t.semibold(11.5); + let font = t.caption_strong(); let galley = ui.painter().layout_no_wrap(label.to_string(), font, t.text); - let size = vec2((galley.size().x + 18.0).max(37.0), 24.0); + let size = vec2(text_button_size(galley.size().x), 24.0); let (r, resp) = ui.allocate_exact_size(size, Sense::click()); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, active, label)); register(ui, format!("button:{id}"), r); @@ -909,14 +944,25 @@ pub fn text_button(ui: &mut Ui, id: &str, label: &str, active: bool) -> Response resp } -/// A segmented control: `labels` share the available width equally, `per_row` per row. Each segment is -/// addressable as `button:{id}-{key}` (keys parallel to labels). Returns the clicked index. +/// Room left and right of a segment's name. +const SEGMENT_PAD: f32 = 5.0; + +/// A segmented control: `labels` share the available width equally, at most `per_row` to a row (fewer where +/// the longest name would not fit its share; a name is cut only where one to a row is too narrow). Each +/// segment is addressable as `button:{id}-{key}` (keys parallel to labels). Returns the clicked index. pub fn segmented(ui: &mut Ui, id: &str, items: &[(&str, &str)], active: Option, per_row: usize) -> Option { let t = Tokens::get(ui.ctx()); - let per_row = per_row.max(1); let gap = 4.0; let w = ui.available_width(); - let seg_w = ((w - gap * (per_row as f32 - 1.0)) / per_row as f32).max(24.0); + let width_of = |per_row: usize| ((w - gap * (per_row as f32 - 1.0)) / per_row as f32).max(24.0); + // `per_row` to a row, or fewer where the longest name (a translation) would not fit its + // share of the width: "Mit Hilfslinien" ran out of a third of the panel + let widest = items + .iter() + .map(|(label, _)| ui.painter().layout_no_wrap(crate::i18n::tr(label).to_string(), t.caption_strong(), t.text).size().x) + .fold(0.0, f32::max); + let per_row = (1..=per_row.max(1)).rev().find(|n| width_of(*n) >= widest + 2.0 * SEGMENT_PAD).unwrap_or(1); + let seg_w = width_of(per_row); let mut clicked = None; for (row_i, row) in items.chunks(per_row).enumerate() { ui.horizontal(|ui| { @@ -936,7 +982,9 @@ pub fn segmented(ui: &mut Ui, id: &str, items: &[(&str, &str)], active: Option= 3.0); + } + assert_eq!(star_pitch(400.0, stars, flag_w, full), full, "a wide bar keeps the spacing"); + assert_eq!(star_pitch(10.0, 0, flag_w, full), full, "no stars, nothing to close up"); + assert_eq!(star_pitch(1.0, stars, flag_w, full), 3.0, "never closer than 3 pt"); + } + + /// Given a square cell narrow enough that the stars and flag at the left and the marks at the right cannot all fit, + /// When the badge bar is laid out, + /// Then no mark at the left reaches the shade under the marks at the right, whatever the width and the marks. + #[test] + fn the_marks_of_a_narrow_badge_bar_never_lie_on_each_other() { + for width in (30..=200).map(|w| w as f32) { + for stars in 0..=5_usize { + for flag_w in [0.0_f32, 18.0] { + for (edited, label) in [(false, false), (true, false), (false, true), (true, true)] { + let marks = badge_marks(width, stars, flag_w, edited, label); + let at = format!("width {width}, {stars} stars, flag {flag_w}, edited {edited}, label {label}: {marks:?}"); + assert!(marks.pitch >= 3.0 && marks.pitch <= 13.0, "{at}"); + assert!((!marks.edited || edited) && (!marks.label || label), "{at}: only marks that were asked for"); + let left_end = 9.0 + stars as f32 * marks.pitch + flag_w; + let right_w = if marks.edited { 20.0 } else { 0.0 } + if marks.label { 20.0 } else { 0.0 }; + // (with no mark at the left there is nothing to keep apart) + if right_w > 0.0 && (stars > 0 || flag_w > 0.0) { + assert!(left_end <= width - right_w - 6.0, "{at}: the left marks end at {left_end}"); + } + } + } + } + } + // a wide bar keeps every mark it was given + assert_eq!(badge_marks(400.0, 5, 18.0, true, true), BadgeMarks { pitch: 13.0, edited: true, label: true }); + // a narrow bar gives up the label's dot before the "edited" mark, which has no other sign + let marks = badge_marks(80.0, 5, 18.0, true, true); + assert!(marks.edited && !marks.label, "{marks:?}"); + // a bar with nothing at the left keeps the marks at the right that fit in it (the label's dot sat + // 2 points outside a 30 point bar, clipped away) + assert_eq!(badge_marks(40.0, 0, 0.0, true, true), BadgeMarks { pitch: 13.0, edited: true, label: true }); + assert_eq!(badge_marks(30.0, 0, 0.0, true, true), BadgeMarks { pitch: 13.0, edited: true, label: false }); + assert_eq!(badge_marks(30.0, 0, 0.0, false, true), BadgeMarks { pitch: 13.0, edited: false, label: true }); + } + + /// Given a filmstrip cell narrow enough that its stars, flag and "edited" mark cannot all fit, + /// When its badge bar is laid out, + /// Then the stars and the flag end before the "edited" mark, or the mark is left out. + #[test] + fn the_marks_of_a_narrow_filmstrip_cell_never_lie_on_each_other() { + for width in (20..=120).map(|w| w as f32) { + for stars in 0..=5_usize { + for flag_w in [0.0_f32, 12.0] { + let marks = film_marks(width, stars, flag_w, true); + let at = format!("width {width}, {stars} stars, flag {flag_w}: {marks:?}"); + assert!(marks.pitch >= 3.0 && marks.pitch <= 9.0, "{at}"); + let left_end = 3.0 + stars as f32 * marks.pitch + flag_w; + if marks.edited && (stars > 0 || flag_w > 0.0) { + assert!(left_end <= width - 16.0, "{at}: the left marks end at {left_end}"); + } + } + } + } + // a wide cell keeps every mark, and so does a narrow one with no stars and no flag + assert_eq!(film_marks(200.0, 5, 12.0, true), FilmMarks { pitch: 9.0, edited: true }); + assert!(film_marks(30.0, 0, 0.0, true).edited); + // a cell with room for the stars but not for the "edited" mark beside them gives up the mark, not the flag + let marks = film_marks(37.0, 5, 12.0, true); + assert!(!marks.edited && marks.pitch >= 3.0, "{marks:?}"); + assert!(3.0 + 5.0 * marks.pitch + 12.0 <= 37.0 - 3.0 || marks.pitch == 3.0, "{marks:?}"); + } + #[test] fn nudges_are_a_sensible_step() { let spec = |id, min, max, step| ControlSpec { @@ -1182,6 +1310,73 @@ pub(crate) fn one_line(painter: &egui::Painter, text: &str, font: egui::FontId, painter.layout_job(job) } +/// How far apart the `stars` of a rating on a photo are set, in a bar with `room` for the stars and the flag after +/// them (`flag_w`, 0 for no flag): `full` where all fit, closer where the photo is narrow (its marks are clipped to +/// it, and the flag is the last mark: it was the first to go). The star drawn is one less than the pitch, as at `full`. +pub(crate) fn star_pitch(room: f32, stars: usize, flag_w: f32, full: f32) -> f32 { + if stars == 0 { + return full; + } + ((room - flag_w) / stars as f32).clamp(3.0, full) +} + +/// How the stars of a filmstrip cell are spaced, and whether its "edited" mark is drawn ([`film_marks`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct FilmMarks { + /// [`star_pitch`] of the stars. + pub pitch: f32, + /// Whether the "edited" mark at the right is drawn. + pub edited: bool, +} + +/// What a filmstrip cell's badge bar `bar_w` wide holds: the stars (closed up as far as [`star_pitch`] lets them) and the +/// flag (`flag_w`) from the left, the "edited" mark (16 wide with its shade) at the right. Where the stars and the flag still +/// would end under that shade, the mark goes and they have the whole bar. +pub(crate) fn film_marks(bar_w: f32, stars: usize, flag_w: f32, edited: bool) -> FilmMarks { + let pitch_with = |edited: bool| star_pitch(bar_w - 6.0 - if edited { 16.0 } else { 0.0 }, stars, flag_w, 9.0); + let pitch = pitch_with(edited); + if edited && (stars > 0 || flag_w > 0.0) && 3.0 + stars as f32 * pitch + flag_w > bar_w - 16.0 { + return FilmMarks { pitch: pitch_with(false), edited: false }; + } + FilmMarks { pitch, edited } +} + +/// Which marks a thumbnail's badge bar has room for, and how its stars are spaced ([`badge_marks`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct BadgeMarks { + /// [`star_pitch`] of the stars. + pub pitch: f32, + /// Whether the "edited" mark at the right is drawn. + pub edited: bool, + /// Whether the color label's dot at the right is drawn. + pub label: bool, +} + +/// What a badge bar `bar_w` wide holds: the stars and the flag (`flag_w`) from the left, and at the right the "edited" +/// mark (20 wide) and the label's dot (20 wide), a 6 point gap between the two groups. The stars close up as far as +/// [`star_pitch`] lets them; when they and the flag still do not fit beside the marks at the right, those marks go, the +/// label's dot first (a labeled cell is tinted by its label as well, and the "edited" mark has no other sign), so that no +/// mark lies on another. With nothing at the left there is nothing to keep apart: the marks at the right need only be in the bar. +pub(crate) fn badge_marks(bar_w: f32, stars: usize, flag_w: f32, edited: bool, label: bool) -> BadgeMarks { + let right = |edited: bool, label: bool| { + let w = if edited { 20.0 } else { 0.0 } + if label { 20.0 } else { 0.0 }; + (w, if w > 0.0 { 6.0 } else { 0.0 }) + }; + // (with nothing at the left there is nothing to keep apart, but the marks at the right must still be in the bar) + let fits = |room: f32, w: f32| if stars == 0 && flag_w == 0.0 { w <= bar_w } else { stars as f32 * 3.0 + flag_w <= room }; + let layout = |edited: bool, label: bool| { + let (w, gap) = right(edited, label); + let room = bar_w - 9.0 - w - gap; + (BadgeMarks { pitch: star_pitch(room, stars, flag_w, 13.0), edited, label }, fits(room, w)) + }; + // (the last resort, no marks at the right, is what a bar too narrow for anything is left with) + [(edited, label), (edited, false)] + .into_iter() + .map(|(edited, label)| layout(edited, label)) + .find_map(|(marks, fits)| fits.then_some(marks)) + .unwrap_or_else(|| layout(false, false).0) +} + /// `text` shortened to fit `max` (as `width` measures it): leading folders drop first /// (`Users/me/Pictures/Lightroom` → `…/Pictures/Lightroom`) so the end of a path, which says the /// most, stays; a single name still too long loses its end (`2024-06-12 Tri…`: folders tend to diff --git a/crates/ui-egui/src/widgets/rating.rs b/crates/ui-egui/src/widgets/rating.rs index 8b1183eb632..a06ff798e91 100644 --- a/crates/ui-egui/src/widgets/rating.rs +++ b/crates/ui-egui/src/widgets/rating.rs @@ -1,11 +1,11 @@ //! One star rating for the whole interface: the clickable row of five stars ([`Rating`]) and the -//! painter-only helpers for stars drawn onto photos and captions ([`paint_rating`], [`paint_star`]). +//! painter-only helpers for stars drawn onto photos and captions ([`paint_rating_spaced`], [`paint_star`]). //! It replaces `widgets::stars` and the private star-painting loops of the grid badge, the film //! badges, the compare caption and the filter bar. //! //! ```ignore //! if let Some(r) = Rating::new("bottom", photo.rating).show(ui) { … } -//! paint_rating(ui.painter(), pos, 3, RatingSize::Small, color); +//! paint_rating_spaced(ui.painter(), pos, 3, RatingSize::Small, RatingSize::Small.step(), color); //! ``` //! //! Hovering a star previews the rating a click would set; clicking the current rating clears it. @@ -42,7 +42,7 @@ impl RatingSize { } } - /// Distance from one painted star to the next in [`paint_rating`]. + /// Distance from one painted star to the next in [`paint_rating_spaced`]. pub fn step(self) -> f32 { match self { Self::Small => 9.0, @@ -63,15 +63,17 @@ pub fn paint_star(painter: &Painter, rect: Rect, filled: bool, color: Color32) { } /// Paint `rating` filled stars in a row, the first one's left edge at `pos.x` and its vertical centre -/// at `pos.y`. Returns the width the row takes (0 for no stars), so the caller can lay out what follows. -pub fn paint_rating(painter: &Painter, pos: Pos2, rating: u8, size: RatingSize, color: Color32) -> f32 { +/// at `pos.y`, `pitch` apart (`size.step()` for the whole row). On a photo too narrow for the whole row +/// each star is as much smaller than `size.icon()` as the pitch is closer than the step, and never less +/// than 1. Returns the width the row takes (0 for no stars), so the caller can lay out what follows. +pub fn paint_rating_spaced(painter: &Painter, pos: Pos2, rating: u8, size: RatingSize, pitch: f32, color: Color32) -> f32 { let n = rating.min(STARS); - let side = size.icon(); + let side = (size.icon() - (size.step() - pitch).max(0.0)).max(1.0); for i in 0..n { - let left = pos.x + f32::from(i) * size.step(); + let left = pos.x + f32::from(i) * pitch; paint_star(painter, Rect::from_min_size(pos2(left, pos.y - side / 2.0), vec2(side, side)), true, color); } - f32::from(n) * size.step() + f32::from(n) * pitch } /// What the stars show once hovering is taken into account: the hovered star's rating previews over diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c25920034..5e5dc87e0bf 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -104,6 +104,87 @@ ## 2026-10-21 +### Text sizes +- Text is set in seven sizes, each with a job: 10 pt for a badge on a thumbnail, 11 for an explanation, the + caption over a field or on a small button or choice, 12 for a count or the title of a tab, 13 for controls, rows + and values, 14 for the header of a section, 15 for the name of a panel or a window, 18 for the title over the + photos. There were seventeen, from 8.5 to 20 pt and often half a point apart: a slider's name was 12.5 pt beside a + checkbox's 13, a caption 11 pt in Settings and 11.5 in Info. +- A size between two went to the one its job has: a slider's name and value 12.5 to 13 pt, a count 12.5 to 12, + an explanation or the caption over a field 11.5 to 11, a row of the sidebar and the search box 13.5 to 13, a + window's title 16 to 15 (the size of a panel's name), the title over the photos 17 to 18. +- The smallest text is 10 pt: the format on a filmstrip cell was 8.5, the count on the filter button 9.5. +- For those who write code: name the size (`t.caption()`, `t.body_strong()`, … in `theme.rs`); a number asked of + the theme (`t.font(12.5)`) is drawn at the nearest size. + +### Text that can be read +- The dim text of captions, counts, file names and explanations stands 4.5:1 against every panel, the grid, a + cell, a text box and a button, in all four themes. It was 4.20:1 on a panel in Charcoal, 3.3 to 4.4:1 on the + surfaces of Silver and Paper. It stays dimmer than a label. +- So do a placeholder in a text box and anything else written faintly (they were the label colour at 60 %, under + 4.1:1 on a panel in every theme), a link (the accent as text was 2.56:1 on a panel in Charcoal, and links in About a bright blue + at 2.4 to 2.8:1 in the light themes), and a caution or an error written as text (3.09:1 in Silver). +- A chosen chip keeps its label 4.5:1 on the accent behind it; the count on the filter button and the "!" on the + cloud button (while changes can't be saved) are in black or white, whichever stands out from the circle; the name + on a selected filmstrip cell or square grid cell, or one tinted by a colour label, is made readable on that cell, + and the format over a square cell is light on its dark chip in the light themes too; a hidden mask's name is dim, + not the colour of what cannot be used. +- Left as it was: a count of nothing in the sidebar ("0") is fainter than the other counts on purpose. + +### Marks and words over a picture +- What is written or marked over a photo on a thumbnail or a filmstrip cell, in a toast and in "Before" is in one + light ink on a dark shade of its own, the same in every theme: a picture has no theme. In Silver and Paper the stars, the pick flag and the "edited" mark on a thumbnail or a + filmstrip cell were the theme's dark greys on a dark bar, and next to invisible; the toast wrote the theme's + near-black text on its black shade. +- The marks on a thumbnail or filmstrip cell (rating stars and the pick or reject flag, and the "edited" mark and + colour label at the other side) are each on a small shade, only as wide as they are, wherever they show: before, + they lay on the bare photo and went out on a bright one. Which thumbnails show marks is as it was (a rated, flagged + or labelled one, or one under the pointer or chosen). The band along the lower edge of a photo under the pointer or + a chosen one is as it was; the dark bar across a marked filmstrip cell is gone, its marks being on their shades. On + a thumbnail or a filmstrip cell narrower than its marks they end where the photo ends, and the stars close up and + get smaller to leave room for the flag, and an "edited" mark or a label's dot with no room left beside them is not drawn. +- The flag of a rejected photo on a thumbnail or a filmstrip cell is a lighter red, which stands out from its shade in every theme, and + a rejected thumbnail is dimmed under its marks, not over them. +- "Before", over a photo shown as it was before its edits, and the label of a hover preview are on a darker shade. +- Left as they were: the virtual-copy tag, "Preview" and a stack's count, which were white on dark pills of their + own already. + +### Numbers +- What a photo was taken with reads the same wherever it is shown: "1/250 sec · f/2.8 · ISO 100 · 35 mm" under the + histogram, over a square cell of the grid and in the info overlay, and the same words on the rows of Info. One + photo used to read "f / 2.8", "f/11.0" and "f/11", "35 mm" and "35mm", "1/250 sec", "1/250 s" and "1/250", in + three different orders. +- A slider's negative value has a minus (−1.25), not a hyphen; either can be typed, and the field a slider's value opens + in for typing has the hyphen, so that what is copied from it pastes anywhere. +- A value can be typed in the digits an Arabic or Persian keyboard gives (١٫٥, ۲۰٪), with the Arabic decimal + sign, comma or percent sign; they used to be no number, and the slider kept its value. +- A slider's value stands in a column of figures: it begins and ends where any other value of as many figures does, + and no longer shifts while it is dragged. The counts on the rows of the left sidebar's lists (My Photos, Albums, + Folders) are set in the same figures. +- A long file name on the filmstrip or in the Import grid is shortened in the middle to the room it has, so the + number of the frame stays (`IMG_20…_153012` where it was `IMG_20240712_…`). + +### Longer words keep to their place +- Edit: Reset goes to a row of its own under Auto, B&W and HDR when it has no room beside them. In German + ("Zurücksetzen") it lay over HDR. +- A row of choices (the crop overlays, Upright, the vignette styles, the two tabs of Versions) puts fewer to a row + when the longest name would not fit its share of the width: "Mit Hilfslinien" ran out of a third of the panel, + "Goldfarben" out of a quarter. +- The filter bar puts on each row what fits there, by what its words measure: Type and Edited go down to the second + row, or to one of their own, where they ran off the edge of the grid (the long German name of the Edited filter, + with both side panels open), and the bar grows by a row. In English each row holds what it did down to a grid about + 720 pt wide; narrower than that, Type and Edited go to the second row, and below about 680 pt to a row of their + own. A part that is wider than the whole bar still runs off it (German under about 645 pt). + +### Small things in how the interface writes +- Text marked for emphasis is in the full text colour; it was the label colour, the same as the text around it. +- Edit: the profile and the white balance are written at the size of any control's value (13 pt). They were 15 + and 14 pt, larger than and as large as the 14 pt headers of the sections they stand in. +- The format on the card of Info, in capitals, has a little room between its letters. +- What an empty view says (no photo selected, nothing to compare, no reference photo) is wrapped inside the view + and centred; a long sentence ran out of a narrow one. +- German: the day of a date has two figures as its month does ("Freitag, 04.09.2026", not "4.09.2026"). + ### Settings window - Settings is one size on every tab and stays where it is as you go through them; before, each tab made its own size and the tabs moved under the pointer. The tabs stay in place while a long page scrolls (in a very short