Merge pull request #2959 from dotCooCoo/feat/about-licenses-tab

About: a Licenses tab shows the app's third-party license texts
This commit is contained in:
BFlat
2026-11-26 10:25:20 +07:00
committed by GitHub
5 changed files with 199 additions and 29 deletions
@@ -1,5 +1,5 @@
//! `AboutDialog`: Help > About in one window for every app, with the app's own data. Tabs About, Contributors and
//! Models, then the app's own tabs.
//! Models, then Licenses when the app gives license texts, then the app's own tabs.
mod contributors;
mod credits;
@@ -7,7 +7,7 @@ mod credits;
pub(crate) mod stories;
pub use contributors::{CommitShare, ContributorSort, NameMode};
pub use credits::{AboutImage, AboutInfo, AboutLink, Contributor, Credits, ModelCredit};
pub use credits::{AboutImage, AboutInfo, AboutLicense, AboutLink, Contributor, Credits, ModelCredit};
use crate::buttons::{Button, IconButton, Link};
use crate::choice::Segmented;
@@ -29,6 +29,7 @@ use crate::sections::{DialogRole, FooterButton};
use crate::style::TypeRole;
use crate::table::Table;
use crate::tabs::{Tab, TabKind, TabStrip};
use crate::text::SelectableText;
use contributors::{Writer, sorted_indices};
use craft_behavior::{ColumnKey, ColumnWidth, EditEvent, IconId, Mixed, SelectionChange, keyed};
use craft_theme::{Mode, Variant};
@@ -45,6 +46,9 @@ craft_ui::words! {
about_tab: "aboutDialog.tab" = "About";
contributors_tab: "aboutDialog.contributors" = "Contributors";
models_tab: "aboutDialog.models" = "Models";
licenses_tab: "aboutDialog.licenses" = "Licenses";
/// The name of the Licenses tab's picker, which lists the licenses by name.
license: "aboutDialog.license" = "License";
/// The footer button of the listed layout ([`AboutLayout::Listed`]).
close: "aboutDialog.close" = "Close";
version: template "aboutDialog.version" = "Version {version}";
@@ -107,7 +111,9 @@ pub enum AboutTab {
Contributors,
/// The credited AI models.
Models,
/// The app's own tab at this position in the app's tabs, shown after Models.
/// The app's third-party license texts, shown after Models when the app gives any.
Licenses,
/// The app's own tab at this position in the app's tabs, shown after Models and Licenses.
App(u8),
}
@@ -125,7 +131,7 @@ pub enum AboutLayout {
Listed,
}
/// A tab the app adds after Models: a name for the hosted dialog's `tab` field, a title and a body.
/// A tab the app adds after Models and Licenses: a name for the hosted dialog's `tab` field, a title and a body.
///
/// The body is `Send` because a [`HostedAbout`] lives on the dialog stack, which needs its dialogs `Send`.
pub struct AboutAppTab {
@@ -150,6 +156,8 @@ struct View {
descending: bool,
/// The contributors show as a table; the grab bag of name links otherwise.
table: bool,
/// The position of the license the Licenses tab shows.
license: usize,
}
/// The Models table's columns, the first of which holds the row label.
@@ -238,12 +246,15 @@ impl Outcome for AboutOutput {
/// header press sorts by its column, activating a row (Enter or a double click) reports the profile URL, and the
/// row's tooltip is the summary.
/// - **Models.** A table of the credited models with their commits, share of all commits and lines.
/// - **App tabs.** The app's own [`AboutAppTab`]s ([`app_tabs`](AboutDialog::app_tabs)) follow Models, each body in a
/// vertically scrolling stack.
/// - **Licenses.** Shown only when the app gives [`AboutLicense`]s ([`licenses`](AboutDialog::licenses)): a License
/// picker that lists them by name when there are several, then the picked license's full text, monospace and
/// selectable, in a vertically scrolling stack.
/// - **App tabs.** The app's own [`AboutAppTab`]s ([`app_tabs`](AboutDialog::app_tabs)) follow Models and Licenses,
/// each body in a vertically scrolling stack.
///
/// The name mode, the sort order and the view are kept in the dialog's container while it is open, and so is the tab
/// unless [`tab`](AboutDialog::tab) binds it. Links are reported
/// in [`AboutOutput::link`] and never opened from here. Enter and Escape close the dialog.
/// The name mode, the sort order, the view and the picked license are kept in the dialog's container while it is open,
/// and so is the tab unless [`tab`](AboutDialog::tab) binds it. Links are reported in [`AboutOutput::link`] and never
/// opened from here. Enter and Escape close the dialog.
#[must_use = "show the dialog with `show`"]
#[derive(crate::contract::Pattern, crate::contract::Props)]
pub struct AboutDialog<'a> {
@@ -255,7 +266,10 @@ pub struct AboutDialog<'a> {
/// Binds the shown tab to `tab`; the dialog opens on it.
#[prop]
tab: Option<Bind<'a, AboutTab>>,
/// The app's own tabs, shown after Models.
/// The third-party license texts the Licenses tab shows; without any the dialog has no Licenses tab.
#[prop]
licenses: Option<&'a [AboutLicense]>,
/// The app's own tabs, shown after Models and Licenses.
#[prop]
app_tabs: Option<&'a mut [AboutAppTab]>,
/// How the About tab lays out the info, and the footer button that goes with it.
@@ -266,12 +280,13 @@ pub struct AboutDialog<'a> {
impl<'a> AboutDialog<'a> {
/// The dialog over `info` and `credits`, opening on the About tab.
pub fn new(info: &'a AboutInfo, credits: &'a Credits) -> Self {
AboutDialog { info, credits, open: None, tab: None, app_tabs: None, layout: AboutLayout::default() }
AboutDialog { info, credits, open: None, tab: None, licenses: None, app_tabs: None, layout: AboutLayout::default() }
}
/// Shows the dialog.
pub fn show(self, ui: &mut Ui) -> AboutOutput {
let AboutDialog { info, credits, open, tab, mut app_tabs, layout } = self;
let AboutDialog { info, credits, open, tab, licenses, mut app_tabs, layout } = self;
let licenses = licenses.unwrap_or_default();
// The strip shows the titles while the body draws a tab, so it reads its own copy of them.
let app_titles: Vec<Label> = app_tabs.as_deref().unwrap_or_default().iter().map(|app| app.title.clone()).collect();
let env = Env::of(ui);
@@ -280,7 +295,7 @@ impl<'a> AboutDialog<'a> {
let dates = env.dates();
let writer = Writer { format: env.format(), dates: &dates, words: &words };
let title = Label::from(words.title.fill(&[("app", info.app_name.as_str())]));
let shown = Shown { words: &words, writer: &writer, info, credits, layout };
let shown = Shown { words: &words, writer: &writer, info, credits, licenses, layout };
let mut tab = tab;
let view = RefCell::new(View::default());
@@ -316,10 +331,11 @@ impl<'a> AboutDialog<'a> {
match (tab, app) {
(AboutTab::Contributors, _) => shown.contributors(ui, &view, &link),
(AboutTab::Models, _) => shown.models(ui),
(AboutTab::Licenses, _) if !shown.licenses.is_empty() => shown.licenses(ui, &view),
(AboutTab::App(_), Some(app)) => {
Stack::new().scroll(Scroll::vertical()).fill().show(ui, |ui, _| (app.body)(ui));
}
// An app tab past the given ones shows About.
// An app tab past the given ones, and Licenses without licenses, show About.
_ => shown.about(ui, &link),
}
});
@@ -343,11 +359,13 @@ struct Shown<'s> {
writer: &'s Writer<'s>,
info: &'s AboutInfo,
credits: &'s Credits,
licenses: &'s [AboutLicense],
layout: AboutLayout,
}
impl Shown<'_> {
/// The tab strip: the three built in, then one per app tab titled `app`. A pick of a tab is kept in `view`.
/// The tab strip: the three built in, Licenses when there are licenses, then one per app tab titled `app`. A pick
/// of a tab is kept in `view`.
fn tabs(&self, ui: &mut Ui, title: &Label, app: &[Label], view: &RefCell<View>) {
let words = self.words;
let mut tabs = vec![
@@ -355,6 +373,9 @@ impl Shown<'_> {
(AboutTab::Contributors, words.contributors_tab.clone()),
(AboutTab::Models, words.models_tab.clone()),
];
if !self.licenses.is_empty() {
tabs.push((AboutTab::Licenses, words.licenses_tab.clone()));
}
tabs.extend(app.iter().enumerate().filter_map(|(at, title)| u8::try_from(at).ok().map(|at| (AboutTab::App(at), title.clone()))));
let source = keyed(&tabs[..], |tab: &(AboutTab, Label)| tab.0).with_text(|tab| Cow::Borrowed(tab.1.as_str()));
let shown = view.borrow().tab;
@@ -587,6 +608,32 @@ impl Shown<'_> {
},
);
}
/// The Licenses tab: the License picker when there are several licenses, then the picked license's text.
fn licenses(&self, ui: &mut Ui, view: &RefCell<View>) {
let words = self.words;
let licenses = self.licenses;
let mut work = view.borrow().clone();
// A kept pick past the licenses given in this pass shows the first.
if work.license >= licenses.len() {
work.license = 0;
}
Stack::new().show(ui, |ui, _| {
if licenses.len() > 1 {
let entries: Vec<Entry<usize>> = licenses.iter().enumerate().map(|(at, license)| Entry::new(at, license.name.clone())).collect();
Row::new().show(ui, |ui, _| {
Text::new(words.license.clone()).show(ui);
Select::new(words.license.clone(), Bind::bound(&mut work.license), &entries).show(ui);
});
}
if let Some(license) = licenses.get(work.license) {
Stack::new().scroll(Scroll::vertical()).fill().show(ui, |ui, _| {
SelectableText::new(license.name.clone(), &license.text).multiline().mono().id_salt(("license", work.license)).show(ui);
});
}
});
*view.borrow_mut() = work;
}
}
/// An [`AboutDialog`] the [`DialogHost`](crate::dialog::DialogHost) owns, with the app's info and credits. A link the
@@ -604,6 +651,7 @@ pub struct HostedAbout {
tab: AboutTab,
link: Option<String>,
open: bool,
licenses: Vec<AboutLicense>,
app_tabs: Vec<AboutAppTab>,
layout: AboutLayout,
#[cfg(feature = "testing")]
@@ -620,6 +668,7 @@ impl HostedAbout {
tab: AboutTab::default(),
link: None,
open: true,
licenses: Vec::new(),
app_tabs: Vec::new(),
layout: AboutLayout::default(),
#[cfg(feature = "testing")]
@@ -627,7 +676,14 @@ impl HostedAbout {
}
}
/// Adds an app tab after Models.
/// The license texts of the Licenses tab ([`AboutDialog::licenses`]); without any the dialog has no Licenses tab.
#[must_use]
pub fn licenses(mut self, licenses: impl IntoIterator<Item = AboutLicense>) -> Self {
self.licenses = licenses.into_iter().collect();
self
}
/// Adds an app tab after Models and Licenses.
#[must_use]
pub fn app_tab(mut self, tab: AboutAppTab) -> Self {
self.app_tabs.push(tab);
@@ -658,28 +714,35 @@ impl HostedAbout {
const ABOUT_KEY: &str = "help.about";
/// The tabs' names in the hosted dialog's `tab` field.
const TAB_NAMES: [(AboutTab, &str); 3] = [(AboutTab::About, "about"), (AboutTab::Contributors, "contributors"), (AboutTab::Models, "models")];
const TAB_NAMES: [(AboutTab, &str); 4] =
[(AboutTab::About, "about"), (AboutTab::Contributors, "contributors"), (AboutTab::Models, "models"), (AboutTab::Licenses, "licenses")];
impl HostedAbout {
/// The name of `tab` in the dialog's `tab` field: the app tabs' names as well as the three built in. An app tab
/// past the given ones shows About, so it is named so.
/// The name of `tab` in the dialog's `tab` field: the app tabs' names as well as the ones built in. An app tab
/// past the given ones, and Licenses without licenses, show About, so they are named so.
fn tab_name(&self, tab: AboutTab) -> &str {
if let AboutTab::App(at) = tab
&& let Some(app) = self.app_tabs.get(usize::from(at))
{
return app.name;
}
TAB_NAMES.iter().find(|(known, _)| *known == tab).map_or("about", |(_, name)| *name)
TAB_NAMES.iter().find(|(known, _)| *known == tab && self.has(*known)).map_or("about", |(_, name)| *name)
}
/// The tab named `name` in the dialog's `tab` field; a name built in wins over an app tab's of the same name.
/// The tab named `name` in the dialog's `tab` field; a name built in wins over an app tab's of the same name while
/// the dialog shows that tab.
fn tab_named(&self, name: &str) -> Option<AboutTab> {
if let Some((tab, _)) = TAB_NAMES.iter().find(|(_, known)| *known == name) {
if let Some((tab, _)) = TAB_NAMES.iter().find(|(tab, known)| *known == name && self.has(*tab)) {
return Some(*tab);
}
let at = self.app_tabs.iter().position(|app| app.name == name)?;
u8::try_from(at).ok().map(AboutTab::App)
}
/// Whether the dialog shows the built-in `tab`: Licenses only with licenses, the others always.
fn has(&self, tab: AboutTab) -> bool {
tab != AboutTab::Licenses || !self.licenses.is_empty()
}
}
impl StackDialog for HostedAbout {
@@ -713,6 +776,7 @@ impl StackDialog for HostedAbout {
credits: &self.credits,
open: Some(Bind::bound(&mut self.open)),
tab: Some(Bind::bound(&mut self.tab)),
licenses: Some(&self.licenses[..]),
app_tabs: Some(&mut self.app_tabs[..]),
layout: self.layout,
}
@@ -1,5 +1,5 @@
//! The credits data: contributors, the credited AI models and the About tab's contents. The app bakes the tables at
//! build time and passes them in; nothing here carries interface text.
//! The credits data: contributors, the credited AI models, the About tab's contents and the third-party licenses. The
//! app bakes the tables at build time and passes them in; nothing here carries interface text.
use crate::runtime::env::Label;
use std::borrow::Cow;
@@ -151,6 +151,23 @@ impl AboutInfo {
}
}
/// A license on the Licenses tab: the name the tab lists it by and its full text.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct AboutLicense {
/// The name in the tab's license picker, such as "Apache License 2.0" or a bundled font's name.
pub name: Label,
/// The full text, shown as written in a monospace face.
pub text: Cow<'static, str>,
}
impl AboutLicense {
/// A license listed as `name` with its full `text`.
pub fn new(name: impl Into<Label>, text: impl Into<Cow<'static, str>>) -> Self {
AboutLicense { name: name.into(), text: text.into() }
}
}
/// One contributor, as the build script bakes them. A display or real name is shown only with recorded consent;
/// without one the `@login` stands in.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -1,6 +1,9 @@
//! Stories of `AboutDialog`: the About tab (centred and listed), the Contributors tab with a PR-only contributor, and an app tab.
//! Stories of `AboutDialog`: the About tab (centred and listed), the Contributors tab with a PR-only contributor, the
//! Licenses tab, and an app tab.
use super::{AboutAppTab, AboutDialog, AboutImage, AboutInfo, AboutLayout, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit};
use super::{
AboutAppTab, AboutDialog, AboutImage, AboutInfo, AboutLayout, AboutLicense, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit,
};
use crate::contract::Show as _;
use crate::dialog::stories::hosted;
use crate::display::Text;
@@ -104,6 +107,29 @@ fn about_dialog_icon_links(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
})
}
/// Two short license texts, standing in for the full texts an app bakes in.
const LICENSE_TEXTS: [(&str, &str); 2] = [
(
"MIT License",
"Permission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction.",
),
(
"SIL Open Font License 1.1",
"This Font Software is licensed under the SIL Open Font License, Version 1.1.\nThis license is copied below, and is also available with a FAQ.",
),
];
/// The dialog open on the Licenses tab, with two licenses (the License picker shows) or one (it does not).
#[story(AboutDialog<'static>, covers = [], drive = Drive::Never)]
fn about_dialog_licenses(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let several = *data.value("several_licenses", true);
hosted(ui, data, several, || {
let count = if several { LICENSE_TEXTS.len() } else { 1 };
let licenses = LICENSE_TEXTS.iter().take(count).map(|(name, text)| AboutLicense::new(*name, *text));
HostedAbout::new(info(true, false), CREDITS.clone()).licenses(licenses).tab(AboutTab::Licenses)
})
}
#[story(AboutDialog<'static>, covers = [], drive = Drive::Never)]
fn about_dialog_contributors(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let tab = *data.choice("tab", AboutTab::Contributors, &TABS);
@@ -69,8 +69,8 @@ pub use new_document::{
pub(crate) mod about;
pub use about::{
AboutAppTab, AboutDialog, AboutImage, AboutInfo, AboutLayout, AboutLink, AboutOutput, AboutTab, AboutWords, CommitShare, Contributor,
ContributorSort, Credits, HostedAbout, ModelCredit, NameMode,
AboutAppTab, AboutDialog, AboutImage, AboutInfo, AboutLayout, AboutLicense, AboutLink, AboutOutput, AboutTab, AboutWords, CommitShare,
Contributor, ContributorSort, Credits, HostedAbout, ModelCredit, NameMode,
};
mod color_choice;
@@ -4,7 +4,7 @@
use craft_ui::contract::{Bind, Role};
use craft_ui::dialog::{DialogHost, StackDialog as _};
use craft_ui::patterns::form_dialogs::{
AboutAppTab, AboutDialog, AboutInfo, AboutLayout, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit,
AboutAppTab, AboutDialog, AboutInfo, AboutLayout, AboutLicense, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit,
};
use craft_ui::testing::{Fixture, access, trial};
use egui::Vec2;
@@ -282,6 +282,69 @@ fn an_app_tab_shows_after_models_and_is_a_tab_field_value() {
assert!(refused.is_err(), "a name that is no tab's is refused");
}
/// The tab titles in the strip, in order.
fn tab_titles(fixture: &Fixture) -> Vec<String> {
fixture.by_role(Role::TAB).iter().filter_map(|tab| access::name(fixture.tree(), tab.node).map(str::to_owned)).collect()
}
/// Whether a painted run of text holds `text`.
fn painted(fixture: &Fixture, text: &str) -> bool {
fixture.texts().iter().any(|painted| painted.text.contains(text))
}
/// Guards the Licenses tab: it follows Models and comes before an app tab, it opens on the first license's text, and
/// the License picker shows the license picked in it in place of the first.
#[trial]
fn the_licenses_tab_follows_models_and_shows_the_picked_license() {
let licenses = [AboutLicense::new("MIT License", "Permission is hereby granted"), AboutLicense::new("Font License", "Reserved Font Name")];
let mut app = [AboutAppTab::new("languageData", "Languages", |_| {})];
let mut fixture = Fixture::new(move |ui| {
let _ = AboutDialog::new(&INFO, &CREDITS).tab(Bind::given(AboutTab::Licenses)).licenses(&licenses).app_tabs(&mut app).show(ui);
});
fixture.room(Vec2::new(1400.0, 1000.0)).idle(30);
assert_eq!(tab_titles(&fixture), ["About", "Contributors", "Models", "Licenses", "Languages"], "Licenses follows Models");
assert!(painted(&fixture, "Permission is hereby granted"), "the tab opens on the first license");
assert!(!painted(&fixture, "Reserved Font Name"), "one license shows at a time");
let picker =
fixture.by_role(Role::COMBO_BOX).into_iter().find(|target| fixture.tree().name_of(target.node) == Some("License")).expect("the picker");
fixture.click(&picker).idle(4);
let font = fixture.by_label("Font License").expect("the picker lists the second license");
fixture.click(&font).idle(10);
assert!(painted(&fixture, "Reserved Font Name"), "the picked license shows");
assert!(!painted(&fixture, "Permission is hereby granted"), "in place of the first");
}
/// Guards the Licenses tab's absence: without licenses the strip has no Licenses tab and the hosted dialog's `tab`
/// field refuses its name; with them `tab` takes the name, shows the text without a picker for one license, and lists
/// it back.
#[trial]
fn the_licenses_tab_shows_only_with_licenses_and_is_a_tab_field_value() {
let host = Rc::new(RefCell::new(DialogHost::new()));
let shown = Rc::clone(&host);
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
fixture.room(Vec2::new(1400.0, 1000.0));
let info = AboutInfo::new("PhotoCraft", "An image editor.", "1.0");
let id = host.borrow_mut().open(HostedAbout::new(info.clone(), CREDITS.clone()));
fixture.idle(10);
assert!(!tab_titles(&fixture).iter().any(|title| title == "Licenses"), "no Licenses tab without licenses");
let ctx = fixture.ctx().clone();
assert!(host.borrow_mut().set_json_field(&ctx, id, "tab", json!("licenses")).is_err(), "`tab` refuses Licenses without licenses");
host.borrow_mut().close_by_id(id);
fixture.idle(4);
let licensed = HostedAbout::new(info, CREDITS.clone()).licenses([AboutLicense::new("MIT License", "Permission is hereby granted")]);
let id = host.borrow_mut().open(licensed);
fixture.idle(10);
assert!(tab_titles(&fixture).iter().any(|title| title == "Licenses"), "the Licenses tab shows with licenses");
host.borrow_mut().set_json_field(&ctx, id, "tab", json!("licenses")).expect("`tab` takes the Licenses tab's name");
fixture.idle(4);
assert!(painted(&fixture, "Permission is hereby granted"), "setting `tab` shows the license");
assert!(fixture.by_role(Role::COMBO_BOX).is_empty(), "one license needs no picker");
let fields = host.borrow().get::<HostedAbout>().and_then(|about| about.json_fields());
assert_eq!(fields, Some(json!({ "tab": "licenses" })));
}
/// The contributors of the order trial: a capitalised login with a display name, an undated (pull request only)
/// contributor, and one with a real name.
static PEOPLE: LazyLock<Credits> = LazyLock::new(|| {