PhotoCraft: An open-source, photo editor written by scratch in pure Rust
About window: fixed table headers, aligned columns, fitted tabs (#2000)
Dan Hiorns9966b534cd1b
diff --git a/crates/ui-egui/src/credits.rs b/crates/ui-egui/src/credits.rsindex 43151478c..d9762533a 100644--- a/crates/ui-egui/src/credits.rs+++ b/crates/ui-egui/src/credits.rs@@ -105,6 +105,27 @@ impl SortKey {pub fn default_ascending(self) -> bool {matches!(self, SortKey::Name | SortKey::FirstCommit | SortKey::LastCommit)}++ /// Counts line up on the right of their column; names and dates read from the left.+ fn numeric(self) -> bool {+ !self.default_ascending()+ }++ /// The table cell for `c` (the name column shows `c.name(..)` as a link instead).+ fn cell(self, c: &Contributor) -> String {+ match self {+ SortKey::Name => c.login.to_string(),+ SortKey::Prs => group(c.prs),+ SortKey::Commits => group(c.commits),+ SortKey::LinesAdded => group(c.lines_added),+ SortKey::LinesDeleted => group(c.lines_deleted),+ SortKey::LinesDelta => signed(c.lines_delta()),+ SortKey::BinaryAdded => group(c.binary_added),+ SortKey::BinaryDeleted => group(c.binary_deleted),+ SortKey::FirstCommit => day(c.first_commit).to_string(),+ SortKey::LastCommit => day(c.last_commit).to_string(),+ }+ }}impl Contributor {@@ -212,8 +233,25 @@ impl Default for View {}}+/// Height of the Contributors list (grab bag or table, header included), the same on both views so+/// switching between them doesn't resize the window. The Models table is as tall as its rows, up+/// to this.+const LIST_HEIGHT: f32 = 340.0;+const TABLE_HEADER_H: f32 = 24.0;+const TABLE_ROW_H: f32 = 22.0;+/// Room for the sort arrow in every header, so the columns don't move when the sort does.+const SORT_ARROW_W: f32 = 12.0;+/// Padding inside each cell, on each side.+const CELL_PAD: f32 = 6.0;+const NAME_MIN_W: f32 = 110.0;+/// About ▸ Contributors: a name toggle, a sort, and the list as a grab bag or a table.pub fn contributors_ui(ui: &mut egui::Ui) {+ contributors_in(ui, CONTRIBUTORS, TOTAL_COMMITS);+}++/// [`contributors_ui`] over a given list (tests pass their own).+fn contributors_in(ui: &mut egui::Ui, contributors: &[Contributor], total_commits: u64) {let id = egui::Id::new("credits_view");let mut v = ui.data_mut(|d| d.get_temp::<View>(id)).unwrap_or_default();ui.horizontal_wrapped(|ui| {@@ -244,86 +282,254 @@ pub fn contributors_ui(ui: &mut egui::Ui) {v.table = true;}});- let list = sorted(CONTRIBUTORS, v.names, v.key, v.ascending);+ let list = sorted(contributors, v.names, v.key, v.ascending);let counts = crate::i18n::fmt(tl!("Contributors: {contributors} · Commits: {commits}"),- &[("contributors", &group(list.len() as u64)), ("commits", &group(TOTAL_COMMITS))],+ &[("contributors", &group(list.len() as u64)), ("commits", &group(total_commits))],);ui.label(RichText::new(counts).small().weak());ui.separator();- egui::ScrollArea::both().auto_shrink([false, false]).max_height(340.0).show(ui, |ui| {- if list.is_empty() {- ui.label(tl!("No contributor data was built into this copy."));- } else if v.table {- table(ui, &list, &mut v);- } else {+ let height = LIST_HEIGHT;+ if list.is_empty() {+ ui.label(tl!("No contributor data was built into this copy."));+ } else if v.table {+ table(ui, &list, &mut v, height);+ } else {+ egui::ScrollArea::vertical().id_salt("credits_bag").auto_shrink([false, false]).max_height(height).show(ui, |ui| {+ // Spacing alone separates the names: a "·" between them started some lines.+ ui.spacing_mut().item_spacing = egui::vec2(14.0, 8.0);+ // Each name is one unit: otherwise egui flows a link that doesn't fit onto the next+ // line as wrapped text, at the font's line height instead of the row spacing.+ ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);+ // horizontal_wrapped gives its first row the interact height; text rows are shorter,+ // so the first gap came out wider than the rest.+ ui.spacing_mut().interact_size.y = 0.0;ui.horizontal_wrapped(|ui| {- for (i, c) in list.iter().enumerate() {- if i > 0 {- ui.label(RichText::new("·").weak());- }- ui.hyperlink_to(c.name(v.names), format!("https://github.com/{}", c.login)).on_hover_text(c.summary());+ for c in &list {+ link(ui, c, v.names);}});+ });+ }+ ui.data_mut(|d| d.insert_temp(id, v));+}++/// Height of a table showing all `rows` (header included), up to [`LIST_HEIGHT`].+fn table_height(ui: &egui::Ui, rows: usize) -> f32 {+ // Each row, and the header, is followed by the row gap.+ let gap = ui.spacing().item_spacing.y;+ let body = rows as f32 * (TABLE_ROW_H + gap) + gap;+ (TABLE_HEADER_H + body).min(LIST_HEIGHT)+}++fn link(ui: &mut egui::Ui, c: &Contributor, names: NameMode) -> egui::Response {+ ui.hyperlink_to(c.name(names), format!("https://github.com/{}", c.login)).on_hover_text(c.summary())+}++fn text_width(ui: &egui::Ui, text: &str, font: &egui::FontId) -> f32 {+ ui.fonts_mut(|f| f.layout_no_wrap(text.to_string(), font.clone(), egui::Color32::WHITE).size().x)+}++/// A column's width: its widest cell, or its header plus the sort arrow's room, so no column+/// changes width when the sort or the rows change.+fn column_width<'a>(ui: &egui::Ui, header: &str, cells: impl Iterator<Item = &'a str>) -> f32 {+ let body = egui::TextStyle::Body.resolve(ui.style());+ let widest = cells.map(|c| text_width(ui, c, &body)).fold(0.0, f32::max);+ let head = text_width(ui, header, &crate::theme::semibold(body.size)) + SORT_ARROW_W;+ (widest.max(head) + 2.0 * CELL_PAD).ceil()+}++/// A credits table: columns of `widths`, the `None` one taking what the others leave (at least+/// `flex_min`). The header stays put while the rows scroll, within `height` (header included). Too+/// narrow for every column (a long translation), it scrolls sideways rather than clip one.+fn credits_table(+ ui: &mut egui::Ui,+ id: &str,+ widths: &[Option<f32>],+ flex_min: f32,+ height: f32,+ header: impl FnOnce(egui_extras::TableRow<'_, '_>),+ body: impl FnOnce(egui_extras::TableBody<'_>),+) {+ // The rows' scroll bar sits beside the columns: leave it room, or it pushes the table past the+ // window and a sideways scroll bar appears under it.+ let fixed: f32 = widths.iter().flatten().sum::<f32>() + ui.spacing().scroll.allocated_width();+ // The table puts a row gap under its header.+ let body_h = (height - TABLE_HEADER_H - ui.spacing().item_spacing.y).max(TABLE_ROW_H);+ egui::ScrollArea::horizontal().id_salt((id, "h")).auto_shrink([false, true]).show(ui, |ui| {+ let flex = (ui.available_width() - fixed).max(flex_min);+ // No gaps between cells: their padding spaces them, and the header rule runs unbroken.+ ui.spacing_mut().item_spacing.x = 0.0;+ let mut b = egui_extras::TableBuilder::new(ui)+ .id_salt(id)+ .striped(true)+ .resizable(false)+ .auto_shrink([false, false])+ .min_scrolled_height(body_h)+ .max_scroll_height(body_h)+ .cell_layout(egui::Layout::left_to_right(egui::Align::Center));+ for w in widths {+ b = b.column(match w {+ Some(w) => egui_extras::Column::exact(*w),+ None => egui_extras::Column::exact(flex).clip(true),+ });}+ b.header(TABLE_HEADER_H, header).body(body);});- ui.data_mut(|d| d.insert_temp(id, v));}-fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View) {- egui::Grid::new("credits_table").striped(true).num_columns(SortKey::ALL.len()).show(ui, |ui| {- for k in SortKey::ALL {- let arrow = if v.key == k { if v.ascending { " ▲" } else { " ▼" } } else { "" };- if ui.button(RichText::new(format!("{}{arrow}", k.label().1)).strong()).on_hover_text(k.label().0).clicked() {- if v.key == k {- v.ascending = !v.ascending;- } else {- v.key = k;- v.ascending = k.default_ascending();- }+/// The Contributors table; clicking a header sorts by it (again reverses it).+fn table(ui: &mut egui::Ui, list: &[&Contributor], v: &mut View, height: f32) {+ let t = crate::theme::Tokens::get(ui.ctx());+ let names = v.names;+ let widths: Vec<Option<f32>> = SortKey::ALL+ .iter()+ .map(|&k| {+ let cells: Vec<String> = list.iter().map(|c| k.cell(c)).collect();+ (k != SortKey::Name).then(|| column_width(ui, k.label().1, cells.iter().map(String::as_str)))+ })+ .collect();+ credits_table(+ ui,+ "credits_table",+ &widths,+ NAME_MIN_W,+ height,+ |mut header| {+ for k in SortKey::ALL {+ header.col(|ui| {+ let sort = (v.key == k).then_some(v.ascending);+ let (long, short) = k.label();+ if header_cell(ui, &t, short, k.numeric(), Some(sort)).on_hover_text(long).clicked() {+ if v.key == k {+ v.ascending = !v.ascending;+ } else {+ v.key = k;+ v.ascending = k.default_ascending();+ }+ }+ });}- }- ui.end_row();- for c in list {- ui.hyperlink_to(c.name(v.names), format!("https://github.com/{}", c.login)).on_hover_text(c.summary());- ui.label(group(c.prs));- ui.label(group(c.commits));- ui.label(group(c.lines_added));- ui.label(group(c.lines_deleted));- ui.label(signed(c.lines_delta()));- ui.label(group(c.binary_added));- ui.label(group(c.binary_deleted));- ui.label(day(c.first_commit));- ui.label(day(c.last_commit));- ui.end_row();- }+ },+ |body| {+ body.rows(TABLE_ROW_H, list.len(), |mut row| {+ let Some(c) = list.get(row.index()) else { return };+ row.col(|ui| {+ ui.add_space(CELL_PAD);+ link(ui, c, names);+ });+ for k in SortKey::ALL.into_iter().skip(1) {+ row.col(|ui| cell(ui, k.numeric(), &k.cell(c)));+ }+ });+ },+ );+}++fn cell(ui: &mut egui::Ui, numeric: bool, text: &str) {+ let layout = if numeric { egui::Layout::right_to_left(egui::Align::Center) } else { egui::Layout::left_to_right(egui::Align::Center) };+ ui.with_layout(layout, |ui| {+ ui.add_space(CELL_PAD);+ ui.add(egui::Label::new(text).selectable(false));});}+/// One header: its label (on the right over counts, like their numbers) under a rule. A sortable+/// one (`sort` is `Some`) is a button, with the arrow on the label's inner side when it's the sort+/// (`Some(Some(ascending))`), in room every header keeps.+fn header_cell(ui: &mut egui::Ui, t: &crate::theme::Tokens, label: &str, numeric: bool, sort: Option<Option<bool>>) -> egui::Response {+ let rect = ui.max_rect();+ let resp = ui.allocate_rect(rect, if sort.is_some() { egui::Sense::click() } else { egui::Sense::hover() });+ let kind = if sort.is_some() { egui::WidgetType::Button } else { egui::WidgetType::Label };+ resp.widget_info(|| egui::WidgetInfo::labeled(kind, true, label));+ let resp = if sort.is_some() { resp.on_hover_cursor(egui::CursorIcon::PointingHand) } else { resp };+ let current = sort.flatten();+ let color = if sort.is_none() || current.is_some() || resp.hovered() { t.text } else { t.text_dim };+ let size = egui::TextStyle::Body.resolve(ui.style()).size;+ let galley = ui.painter().layout_no_wrap(label.to_string(), crate::theme::semibold(size), color);+ let inner = rect.shrink2(egui::vec2(CELL_PAD, 0.0));+ let y = rect.center().y - galley.size().y / 2.0;+ let (text_x, arrow_x) = if numeric {+ let x = inner.right() - galley.size().x;+ (x, x - SORT_ARROW_W / 2.0)+ } else {+ (inner.left(), inner.left() + galley.size().x + SORT_ARROW_W / 2.0)+ };+ ui.painter().galley(egui::pos2(text_x, y), galley, color);+ if let Some(ascending) = current {+ let (c, h) = (egui::pos2(arrow_x, rect.center().y), 3.0);+ let pts = if ascending {+ vec![c + egui::vec2(-h, h * 0.6), c + egui::vec2(h, h * 0.6), c + egui::vec2(0.0, -h * 0.9)]+ } else {+ vec![c + egui::vec2(-h, -h * 0.6), c + egui::vec2(h, -h * 0.6), c + egui::vec2(0.0, h * 0.9)]+ };+ ui.painter().add(egui::Shape::convex_polygon(pts, t.accent, egui::Stroke::NONE));+ }+ let line = egui::Rect::from_min_max(egui::pos2(rect.left(), rect.bottom() - 1.0), rect.max);+ ui.painter().rect_filled(line, 0.0, t.separator);+ resp+}+/// About ▸ Models: AI models credited in Co-Authored-By trailers.pub fn models_ui(ui: &mut egui::Ui) {- if MODELS.is_empty() {+ models_in(ui, MODELS, TOTAL_COMMITS);+}++/// Share of all commits, whole percent; a model with any commits never reads "0%".+fn percent(commits: u64, total: u64) -> String {+ let p = 100.0 * commits as f64 / total.max(1) as f64;+ if commits > 0 && p < 0.5 { "<1%".into() } else { format!("{:.0}%", p.min(100.0)) }+}++/// The Models table's cells for `m`, column by column; counts are the last three.+fn model_cells(m: &Model, total: u64) -> [String; 6] {+ [+ m.company.to_string(),+ m.model.to_string(),+ m.version.to_string(),+ group(m.commits),+ percent(m.commits, total),+ format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted)),+ ]+}++/// [`models_ui`] over a given list (tests pass their own).+fn models_in(ui: &mut egui::Ui, models: &[Model], total_commits: u64) {+ if models.is_empty() {ui.label(tl!("No model credits were built into this copy."));return;}- let assisted: u64 = MODELS.iter().map(|m| m.commits).max().unwrap_or(0).max(1);- egui::ScrollArea::both().auto_shrink([false, false]).max_height(340.0).show(ui, |ui| {- egui::Grid::new("credits_models").striped(true).num_columns(6).show(ui, |ui| {- for h in [tl!("Company"), tl!("Model"), tl!("Version"), tl!("Commits"), tl!("% of all commits"), tl!("Lines +/−")] {- ui.label(RichText::new(h).strong());- }- ui.end_row();- for m in MODELS {- ui.label(m.company);- ui.label(m.model);- ui.label(m.version);- ui.label(group(m.commits));- ui.label(format!("{:.0}%", 100.0 * m.commits as f64 / TOTAL_COMMITS.max(assisted) as f64));- ui.label(format!("+{} / −{}", group(m.lines_added), group(m.lines_deleted)));- ui.end_row();+ let t = crate::theme::Tokens::get(ui.ctx());+ // Counted against every commit, or the busiest model's if the total somehow trails it.+ let total = total_commits.max(models.iter().map(|m| m.commits).max().unwrap_or(0));+ let heads = [tl!("Company"), tl!("Model"), tl!("Version"), tl!("Commits"), tl!("% of all commits"), tl!("Lines +/−")];+ let rows: Vec<[String; 6]> = models.iter().map(|m| model_cells(m, total)).collect();+ // The model name takes the spare width.+ let widths: Vec<Option<f32>> =+ (0..heads.len()).map(|i| (i != 1).then(|| column_width(ui, heads[i], rows.iter().filter_map(|r| r.get(i)).map(String::as_str)))).collect();+ let numeric = |i: usize| i >= 3;+ credits_table(+ ui,+ "credits_models",+ &widths,+ NAME_MIN_W,+ table_height(ui, rows.len()),+ |mut header| {+ for (i, h) in heads.iter().enumerate() {+ header.col(|ui| {+ header_cell(ui, &t, h, numeric(i), None);+ });}- });- });+ },+ |body| {+ body.rows(TABLE_ROW_H, rows.len(), |mut row| {+ let Some(cells) = rows.get(row.index()) else { return };+ for (i, text) in cells.iter().enumerate() {+ row.col(|ui| cell(ui, numeric(i), text));+ }+ });+ },+ );}#[cfg(test)]@@ -396,3 +602,7 @@ mod tests {assert_eq!(day(""), "—");}}++#[cfg(test)]+#[path = "credits_tests.rs"]+mod ui_tests;diff --git a/crates/ui-egui/src/credits_tests.rs b/crates/ui-egui/src/credits_tests.rsnew file mode 100644index 000000000..b3cb5a46e--- /dev/null+++ b/crates/ui-egui/src/credits_tests.rs@@ -0,0 +1,244 @@+//! The Contributors tab as drawn: the table's header stays put while its rows scroll, its columns+//! keep their places whatever the sort, counts line up on the right, and every column fits the+//! About window; the grab bag's rows are evenly spaced.++use egui::{Rect, accesskit::Role, vec2};+use egui_kittest::Harness;+use egui_kittest::kittest::{NodeT, Queryable};++use super::*;++/// The About window's width (`dialogs.rs` gives its tabs 700 pt).+const WIDTH: f32 = 700.0;++fn leak(s: String) -> &'static str {+ Box::leak(s.into_boxed_str())+}++/// `n` contributors with distinct, realistic-sized counts (six-digit line counts, a long login).+fn people(n: u64) -> Vec<Contributor> {+ (0..n)+ .map(|i| Contributor {+ login: if i == 0 { "nullpointerexception" } else { leak(format!("user{i:02}")) },+ display_name: None,+ real_name: None,+ prs: 100 + i,+ commits: 1000 + i,+ lines_added: 277_000 + i,+ lines_deleted: 22_000 + i,+ binary_added: 30 + i,+ binary_deleted: i,+ first_commit: leak(format!("2026-09-{:02}T00:00:00Z", 1 + i % 28)),+ last_commit: "2026-10-07T00:00:00Z",+ })+ .collect()+}++fn harness(list: Vec<Contributor>, table: bool) -> Harness<'static> {+ let mut h = Harness::builder().with_size(vec2(WIDTH + 20.0, 520.0)).build_ui(move |ui| {+ if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("semibold".into()))) {+ return;+ }+ let id = egui::Id::new("credits_view");+ if ui.data(|d| d.get_temp::<View>(id)).is_none() {+ ui.data_mut(|d| d.insert_temp(id, View { table, ..View::default() }));+ }+ ui.set_width(WIDTH);+ contributors_in(ui, &list, 1);+ });+ crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);+ h.run_steps(4);+ h+}++fn header(h: &Harness<'_>, k: SortKey) -> Rect {+ let label = k.label().1;+ // The old table put the sort arrow in the label ("First ▲").+ let named = |l: &str| l == label || l.strip_prefix(label).is_some_and(|rest| rest.trim().chars().all(|c| "▲▼".contains(c)));+ h.query_all_by_role(Role::Button)+ .find(|n| n.accesskit_node().label().is_some_and(|l| named(&l)))+ .map(|n| n.rect())+ .unwrap_or_else(|| panic!("no {label} header"))+}++fn headers(h: &Harness<'_>) -> Vec<Rect> {+ SortKey::ALL.iter().map(|&k| header(h, k)).collect()+}++fn text_rect(h: &Harness<'_>, text: &str) -> Option<Rect> {+ h.query_all_by_label(text).next().map(|n| n.rect())+}++fn view(h: &Harness<'_>) -> View {+ h.ctx.data(|d| d.get_temp::<View>(egui::Id::new("credits_view"))).unwrap_or_default()+}++#[test]+fn the_table_header_stays_put_while_the_rows_scroll() {+ let mut h = harness(people(60), true);+ let before = headers(&h);+ let first = text_rect(&h, "@user01").expect("the second row is shown");+ let over = first.center();+ h.event(egui::Event::PointerMoved(over));+ for _ in 0..6 {+ h.event(egui::Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta: vec2(0.0, -200.0),+ modifiers: egui::Modifiers::NONE,+ phase: egui::TouchPhase::Move,+ });+ h.run_steps(2);+ }+ h.run_steps(4);+ assert_eq!(headers(&h), before, "the header moved with the rows");+ let moved = text_rect(&h, "@user01").map(|r| r.top());+ assert!(moved.is_none_or(|y| y < first.top() - 100.0), "the rows didn't scroll: {moved:?} vs {}", first.top());+}++#[test]+fn clicking_a_header_sorts_by_it_and_no_column_moves() {+ let mut h = harness(people(12), true);+ let before = headers(&h);+ assert_eq!((view(&h).key, view(&h).ascending), (SortKey::FirstCommit, true));+ for (k, ascending) in [(SortKey::Commits, false), (SortKey::Commits, true), (SortKey::Name, true), (SortKey::LastCommit, true)] {+ let at = header(&h, k).center();+ h.query_all_by_role(Role::Button).find(|n| n.rect().contains(at)).expect("the header").click();+ h.run_steps(3);+ assert_eq!((view(&h).key, view(&h).ascending), (k, ascending));+ assert_eq!(headers(&h), before, "sorting by {k:?} moved the columns");+ }+}++#[test]+fn counts_line_up_on_the_right_and_names_and_dates_on_the_left() {+ let h = harness(people(8), true);+ let (commits, first) = (header(&h, SortKey::Commits), header(&h, SortKey::FirstCommit));+ let cells = |col: Rect| -> Vec<Rect> {+ h.query_all_by_role(Role::Label)+ .map(|n| n.rect())+ .filter(|r| r.top() > col.bottom() && r.center().x > col.left() && r.center().x < col.right())+ .collect()+ };+ let nums = cells(commits);+ assert!(nums.len() >= 8, "{} commit cells", nums.len());+ assert!(nums.iter().all(|r| (r.right() - nums[0].right()).abs() < 0.5), "commit counts don't share a right edge: {nums:?}");+ let dates = cells(first);+ assert!(dates.len() >= 8, "{} date cells", dates.len());+ assert!(dates.iter().all(|r| (r.left() - dates[0].left()).abs() < 0.5), "dates don't share a left edge: {dates:?}");+ assert!(nums[0].right() <= commits.right() && dates[0].left() >= first.left());+}++#[test]+fn every_column_fits_the_about_window() {+ let h = harness(people(8), true);+ let hs = headers(&h);+ let (left, right) = (hs[0].left(), hs.last().map_or(0.0, |r| r.right()));+ assert!(right - left <= WIDTH + 0.5, "the table is {} pt wide in a {WIDTH} pt window", right - left);+ // The longest value of each column is shown whole, inside its column.+ for (k, col) in SortKey::ALL.iter().zip(&hs).skip(1) {+ let widest = people(8).iter().map(|c| k.cell(c)).max_by_key(|s| s.len()).unwrap_or_default();+ let r = text_rect(&h, &widest).unwrap_or_else(|| panic!("{k:?}: no {widest} cell"));+ assert!(r.left() >= col.left() && r.right() <= col.right(), "{k:?}: {widest} at {r:?} spills out of {col:?}");+ }+}++#[test]+fn the_grab_bag_rows_are_evenly_spaced() {+ let h = harness(people(60), false);+ let links = || h.query_all(egui_kittest::kittest::by().predicate(|n| n.label().is_some_and(|l| l.starts_with('@'))));+ let mut tops: Vec<f32> = links().map(|n| n.rect().top()).collect();+ tops.sort_by(f32::total_cmp);+ tops.dedup_by(|a, b| (*a - *b).abs() < 0.5);+ assert!(tops.len() >= 3, "{} rows", tops.len());+ let gaps: Vec<f32> = tops.windows(2).map(|w| w[1] - w[0]).collect();+ assert!(gaps.iter().all(|g| (g - gaps[0]).abs() < 0.5), "uneven rows: {gaps:?}");+ // And spaced apart: more than the text's own line height.+ let line = links().next().map_or(0.0, |n| n.rect().height());+ assert!(gaps[0] > line + 4.0, "rows {} pt apart for {line} pt links", gaps[0]);+}++fn model(company: &'static str, name: &'static str, commits: u64) -> Model {+ Model { company, model: name, version: "1.0", commits, lines_added: 150_000 + commits, lines_deleted: 20_000 }+}++#[test]+fn a_model_with_commits_never_reads_zero_percent() {+ assert_eq!(percent(228, 482), "47%");+ assert_eq!(percent(2, 482), "<1%");+ assert_eq!(percent(0, 482), "0%");+ assert_eq!(percent(5, 0), "100%"); // a total that trails the model's own count+ assert_eq!(percent(3, 1), "100%");+}++#[test]+fn the_models_table_lines_counts_up_on_the_right_under_a_rule_of_headers() {+ let models: Vec<Model> = (0..8).map(|i| model("Anthropic", leak(format!("Model {i}")), [228, 45, 6, 2, 2, 1, 1, 1][i])).collect();+ let mut h = Harness::builder().with_size(vec2(WIDTH + 20.0, 520.0)).build_ui(move |ui| {+ if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("semibold".into()))) {+ return;+ }+ ui.set_width(WIDTH);+ models_in(ui, &models, 482);+ });+ crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);+ h.run_steps(4);+ let head = |l: &str| h.query_all_by_label(l).next().map(|n| n.rect()).unwrap_or_else(|| panic!("no {l} header"));+ let (commits, lines) = (head("Commits"), head("Lines +/−"));+ assert!(lines.right() - head("Company").left() <= WIDTH + 0.5, "the table is wider than the window");+ let column = |col: Rect| -> Vec<Rect> {+ h.query_all_by_role(Role::Label)+ .map(|n| n.rect())+ .filter(|r| r.top() > col.bottom() && r.center().x > col.left() && r.center().x < col.right())+ .collect()+ };+ for (name, col) in [("Commits", commits), ("Lines", lines)] {+ let cells = column(col);+ assert_eq!(cells.len(), 8, "{name}: {} cells", cells.len());+ assert!(cells.iter().all(|r| (r.right() - cells[0].right()).abs() < 0.5), "{name} isn't right-aligned: {cells:?}");+ }+ assert!(h.query_all_by_label("<1%").count() == 5, "small shares read <1%");+}++/// The About window on `tab` (and the Contributors table when `table`): the top of its title and of+/// its OK button, and the bottom of the lowest thing between them.+fn about_window(tab: &str, table: bool) -> (f32, f32, f32) {+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| {+ crate::PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());+ crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default())+ });+ let mut fields = serde_json::Map::new();+ fields.insert("tab".into(), serde_json::json!(tab));+ h.state_mut().ui.open_dialog(crate::state::DialogKind::About, fields);+ h.ctx.data_mut(|d| d.insert_temp(egui::Id::new("credits_view"), View { table, ..View::default() }));+ h.run_steps(6);+ let ok = h.query_all_by_role(Role::Button).find(|n| n.accesskit_node().label().as_deref() == Some("OK")).map(|n| n.rect()).expect("the OK button");+ // The dialog's contents: everything between its title and the OK button.+ let title = h.query_all_by_label("About PhotoCraft").map(|n| n.rect()).find(|r| r.top() < ok.top()).expect("the dialog title");+ let lowest = h+ .query_all(egui_kittest::kittest::by().predicate(|n| n.bounding_box().is_some()))+ .map(|n| n.rect())+ .filter(|r| r.top() > title.bottom() && r.bottom() < ok.top() && r.left() >= title.left() - 1.0 && r.right() <= ok.right() + 1.0 && r.height() < 100.0)+ .map(|r| r.bottom())+ .fold(f32::MIN, f32::max);+ (title.top(), ok.top(), lowest)+}++#[test]+fn about_and_models_end_where_their_content_does() {+ for tab in ["about", "models"] {+ let (_, ok, lowest) = about_window(tab, false);+ assert!(lowest > f32::MIN, "{tab}: nothing above OK");+ assert!(ok - lowest < 40.0, "{tab}: {} pt of blank space above OK", ok - lowest);+ }+}++#[test]+fn switching_the_contributors_view_keeps_the_window_size() {+ // A new window is placed by its first frame, so compare the height, title to OK.+ let height = |table| {+ let (title, ok, _) = about_window("contributors", table);+ ok - title+ };+ let (bag, table) = (height(false), height(true));+ assert!((bag - table).abs() < 0.5, "{bag} pt tall on the grab bag, {table} pt on the table");+}diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex 9b7fae60f..97b2651fa 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -178,22 +178,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {fields.insert("tab".into(), json!(chosen));}ui.add_space(8.0);- match chosen {- "contributors" => crate::credits::contributors_ui(ui),- "models" => crate::credits::models_ui(ui),- _ => {- ui.label(tl!("PhotoCraft — an open-source, native image editor written in Rust."));- ui.label(crate::i18n::fmt(tl!("Version {version}"), &[("version", &photocraft_engine::build_info::long_version())]));- ui.add_space(12.0);- ui.vertical_centered(|ui| {- crate::links::discord_button(app, ui, 220.0);- ui.add_space(8.0);- crate::links::link_row(app, ui);- });- ui.add_space(10.0);- ui.weak("egui · wgpu · photocraft-engine");- }- }+ about_tab_body(app, ui, chosen);}DialogKind::Command if crate::fill_ui::owns(&fields) => crate::fill_ui::body(app, ui, &mut fields),DialogKind::Command if crate::stroke_ui::owns(&fields) => crate::stroke_ui::body(ui, &mut fields),@@ -331,6 +316,26 @@ fn about_tab(fields: &serde_json::Map<String, Value>) -> &'static str {ABOUT_TABS.iter().copied().find(|t| *t == want).unwrap_or("about")}+/// One About tab's contents: the credits lists, or the product blurb and links.+fn about_tab_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, tab: &str) {+ match tab {+ "contributors" => crate::credits::contributors_ui(ui),+ "models" => crate::credits::models_ui(ui),+ _ => {+ ui.label(tl!("PhotoCraft — an open-source, native image editor written in Rust."));+ ui.label(crate::i18n::fmt(tl!("Version {version}"), &[("version", &photocraft_engine::build_info::long_version())]));+ ui.add_space(12.0);+ ui.vertical_centered(|ui| {+ crate::links::discord_button(app, ui, 220.0);+ ui.add_space(8.0);+ crate::links::link_row(app, ui);+ });+ ui.add_space(10.0);+ ui.weak("egui · wgpu · photocraft-engine");+ }+ }+}+/// The dialog title as shown: [`title`] in the UI language.fn display_title(d: &Dialog) -> String {match d.kind {