diff --git a/crates/theme/src/format/mod.rs b/crates/theme/src/format/mod.rs index 8bd3c70cc..66c2e06b4 100644 --- a/crates/theme/src/format/mod.rs +++ b/crates/theme/src/format/mod.rs @@ -41,6 +41,8 @@ const OFFSET: &str = "a number"; const KNOB: &str = "\"round\" or \"tab\""; /// What `shape.wells` takes. const WELLS: &str = "\"square\" or \"round\""; +/// What `icon_pack` takes. +const ICON_PACK: &str = "an icon pack id: 2 to 64 of a-z, 0-9, '.', '_' or '-', starting with a-z or 0-9"; const EDGE: &str = "\"flat\" or {\"bevel\": {\"width\": n}} with n above 0"; /// A parsed theme file: the theme and the JSON it came from, so that [`fn@write`] keeps unknown keys. diff --git a/crates/theme/src/format/parse.rs b/crates/theme/src/format/parse.rs index 3ec6c270c..bc9c3d0bf 100644 --- a/crates/theme/src/format/parse.rs +++ b/crates/theme/src/format/parse.rs @@ -4,14 +4,14 @@ use std::collections::BTreeMap; use serde_json::{Map, Value}; -use super::{EDGE, ErrorKind, FormatError, FormatErrors, KNOB, LENGTH, MAX_THEME_BYTES, OFFSET, SCHEMA, SCHEMA_VERSION, ThemeFile, WELLS}; +use super::{EDGE, ErrorKind, FormatError, FormatErrors, ICON_PACK, KNOB, LENGTH, MAX_THEME_BYTES, OFFSET, SCHEMA, SCHEMA_VERSION, ThemeFile, WELLS}; use crate::color::Rgba; use crate::scale::Radius; use crate::theme::{ AppOverrides, ContrastIntent, EdgeSeed, ModePins, ModeSeeds, Pins, RadiusOffset, SeedOverrides, Seeds, ShapeSeed, ThemeDef, Variants, }; use crate::tokens::{ColorToken, KnobShape, RadiusSet, Status, WellShape}; -use crate::{AppId, ThemeId}; +use crate::{AppId, IconPackId, ThemeId}; /// Parses and validates a theme file. Unknown keys are allowed anywhere except in colour maps, and /// kept for [`write`](super::write). Every field error is reported, not @@ -148,6 +148,7 @@ impl Parser { self.choice(raw, "variants", Variants::Both, &[("both", Variants::Both), ("light", Variants::LightOnly), ("dark", Variants::DarkOnly)]); let contrast_intent = self.choice(raw, "contrast_intent", ContrastIntent::Standard, &[("standard", ContrastIntent::Standard), ("low", ContrastIntent::Low)]); + let icon_pack = self.icon_pack(raw); let seeds = self.seeds(raw); let shape = self.shape(raw); let pins = self.mode_pins(raw, variants, true); @@ -169,6 +170,7 @@ impl Parser { pins: pins?, high_contrast: high_contrast?, contrast_intent, + icon_pack, apps: apps?, }) } @@ -191,6 +193,19 @@ impl Parser { } } + /// The pack id under `icon_pack`: `None` when absent or null. Only the form is checked; a pack that is not + /// installed draws the default icons. + fn icon_pack(&mut self, raw: &Map) -> Option { + self.at("icon_pack", |p| match raw.get("icon_pack") { + None | Some(Value::Null) => None, + Some(Value::String(s)) => IconPackId::parse(s).map_err(|_| p.fail(ErrorKind::BadValue { expected: ICON_PACK })).ok(), + Some(_) => { + p.fail(ErrorKind::WrongType { expected: "a string" }); + None + } + }) + } + fn seeds(&mut self, raw: &Map) -> Option { let seeds = self.required_object(raw, "seeds")?; self.at("seeds", |p| p.seed_values(seeds)) diff --git a/crates/theme/src/format/write.rs b/crates/theme/src/format/write.rs index c30bf6c3d..020185614 100644 --- a/crates/theme/src/format/write.rs +++ b/crates/theme/src/format/write.rs @@ -8,8 +8,22 @@ use crate::theme::{AppOverrides, ContrastIntent, EdgeSeed, ModePins, ModeSeeds, use crate::tokens::{KnobShape, WellShape}; /// Top-level keys in the order a file lists them; other keys follow, sorted. -const TOP_ORDER: [&str; 13] = - ["schema", "schema_version", "id", "name", "version", "variants", "contrast_intent", "seeds", "shape", "light", "dark", "high_contrast", "apps"]; +const TOP_ORDER: [&str; 14] = [ + "schema", + "schema_version", + "id", + "name", + "version", + "variants", + "contrast_intent", + "icon_pack", + "seeds", + "shape", + "light", + "dark", + "high_contrast", + "apps", +]; /// The file as pretty-printed JSON ending in a newline. Known values come from `file.theme`; /// unknown keys come from the file that was parsed. Keys are sorted below the top level. Fails @@ -41,6 +55,14 @@ fn update(raw: &mut Map, t: &ThemeDef) { ContrastIntent::Low => "low", }; raw.insert("contrast_intent".to_owned(), intent.into()); + match &t.icon_pack { + None => { + raw.remove("icon_pack"); + } + Some(pack) => { + raw.insert("icon_pack".to_owned(), pack.as_str().into()); + } + } with_object(raw, "seeds", |seeds| { seeds.insert("neutral".to_owned(), t.seeds.neutral.to_hex().into()); diff --git a/crates/theme/src/format_tests.rs b/crates/theme/src/format_tests.rs index 3bed95586..427b43e9e 100644 --- a/crates/theme/src/format_tests.rs +++ b/crates/theme/src/format_tests.rs @@ -14,7 +14,7 @@ fn full() -> Value { "schema": "craft-design-theme", "schema_version": 1, "x_top": { "list": [1, 2, { "k": null }] }, "id": "test.full", "name": "Full", "version": 3, - "variants": "both", "contrast_intent": "low", + "variants": "both", "contrast_intent": "low", "icon_pack": "craft.tabler", "seeds": { "neutral": "#535353", "accent": "#78ADF6", "x_seed": "kept", "status": { "good": "#85DC6A", "warn": "#E8B046", "bad": "#FF8080", "info": "#78ADF6", "x_status": 1 } @@ -55,6 +55,7 @@ fn round_trip_keeps_values_and_unknown_keys() { let t = &file.theme; assert_eq!((t.id.as_str(), t.name.as_str(), t.version), ("test.full", "Full", 3)); assert_eq!((t.variants, t.contrast_intent), (Variants::Both, ContrastIntent::Low)); + assert_eq!(t.icon_pack.as_ref().map(IconPackId::as_str), Some("craft.tabler")); assert_eq!(t.seeds.accent, hex("#78adf6")); let shape = t.shape.unwrap(); assert_eq!(shape.radius.unwrap().button, 999.0); @@ -82,6 +83,7 @@ fn round_trip_keeps_values_and_unknown_keys() { ("/apps/photocraft/high_contrast/dark/text.normal", &json!("#ffffff")), ("/apps/x_app_entry", &orig["apps"]["x_app_entry"]), ("/version", &json!(3)), + ("/icon_pack", &json!("craft.tabler")), ("/shape/knob", &json!("tab")), ("/shape/wells", &json!("round")), ("/shape/radius/button", &json!("full")), @@ -95,6 +97,33 @@ fn round_trip_keeps_values_and_unknown_keys() { assert_eq!(format::write(&again).unwrap(), text, "writing is stable"); } +/// A pack set on a file without one is written; clearing it removes the key and keeps the file's unknown keys; a +/// value that is not a well-formed pack id is an error at its key. +#[test] +fn the_icon_pack_is_added_cleared_and_checked() { + let mut v = full(); + v.as_object_mut().unwrap().remove("icon_pack"); + let mut file = parse_value(&v).unwrap(); + assert_eq!(file.theme.icon_pack, None); + file.theme.icon_pack = Some(IconPackId::parse("user.rounded").unwrap()); + let added: Value = serde_json::from_str(&format::write(&file).unwrap()).unwrap(); + assert_eq!(added.pointer("/icon_pack"), Some(&json!("user.rounded"))); + + let mut file = parse_value(&full()).unwrap(); + file.theme.icon_pack = None; + let cleared: Value = serde_json::from_str(&format::write(&file).unwrap()).unwrap(); + assert_eq!(cleared.pointer("/icon_pack"), None); + assert_eq!(cleared.pointer("/x_top"), full().pointer("/x_top"), "unknown keys stay"); + + for bad in [json!(3), json!("Bad Pack"), json!("x")] { + let mut v = full(); + v["icon_pack"] = bad.clone(); + let e = errors(&v); + assert_eq!(e.len(), 1, "{bad}: {e:?}"); + assert!(e[0].starts_with("icon_pack: "), "{bad}: {e:?}"); + } +} + /// A theme file with the given light-mode pins. fn with_light(pins: Value) -> Value { let mut v = full(); diff --git a/crates/theme/src/id.rs b/crates/theme/src/id.rs index d3e20dfc2..7c3c842eb 100644 --- a/crates/theme/src/id.rs +++ b/crates/theme/src/id.rs @@ -52,6 +52,63 @@ fn check_form(s: &str) -> Result<(), IdError> { Ok(()) } +/// The form, then the rules for ids users create, which become file names: no reserved `craft.` prefix and no Windows +/// device name as the first dot-separated part. +fn check_user(s: &str) -> Result<(), IdError> { + check_form(s)?; + let first = s.split('.').next().unwrap_or_default(); + if s.starts_with(RESERVED_PREFIX) { + Err(IdError::Reserved) + } else if DEVICE_NAMES.iter().any(|d| first.eq_ignore_ascii_case(d)) { + Err(IdError::DeviceName) + } else { + Ok(()) + } +} + +/// The id of an icon pack a theme names: the same form as a [`ThemeId`]. `craft.` ids are the built-in sets +/// (`craft.lucide`, `craft.phosphor`, `craft.carbon`, `craft.tabler`); other ids name packs in the suite library. +#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct IconPackId(Arc); + +impl IconPackId { + /// Checks the form only, as a theme file does: a well-formed id that names no installed pack draws the default + /// icons. + pub fn parse(s: &str) -> Result { + check_form(s)?; + Ok(IconPackId(Arc::from(s))) + } + + /// [`IconPackId::parse`], refusing the reserved `craft.` prefix and Windows device names: for packs users create + /// or import, whose ids become file names. + pub fn parse_user(s: &str) -> Result { + check_user(s)?; + Ok(IconPackId(Arc::from(s))) + } + + /// The id as text. + pub fn as_str(&self) -> &str { + &self.0 + } + + /// True for the built-in sets' `craft.` ids. + pub fn is_builtin(&self) -> bool { + self.0.starts_with(RESERVED_PREFIX) + } +} + +impl fmt::Debug for IconPackId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&*self.0, f) + } +} + +impl fmt::Display for IconPackId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + /// An app's stable identity, the key of a theme's per-app overrides: the same form as a /// [`ThemeId`], `[a-z0-9][a-z0-9._-]{1,63}`, without the reserved prefix or device-name rules. #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] @@ -92,15 +149,8 @@ impl ThemeId { /// [`ThemeId::parse`], refusing the reserved `craft.` prefix and Windows device names: for /// themes users create or import, whose ids become file names. pub fn parse_user(s: &str) -> Result { - let id = Self::parse(s)?; - let first = id.0.split('.').next().unwrap_or_default(); - if id.is_builtin() { - Err(IdError::Reserved) - } else if DEVICE_NAMES.iter().any(|d| first.eq_ignore_ascii_case(d)) { - Err(IdError::DeviceName) - } else { - Ok(id) - } + check_user(s)?; + Ok(ThemeId(Arc::from(s))) } /// For the crate's own constants, which are valid by construction (a test checks each). diff --git a/crates/theme/src/lib.rs b/crates/theme/src/lib.rs index 2c9705afa..57e85bce2 100644 --- a/crates/theme/src/lib.rs +++ b/crates/theme/src/lib.rs @@ -76,7 +76,7 @@ pub use color_model::{ pub use contrast::{contrast_ratio, ensure_contrast, relative_luminance, text_contrast_min}; pub use derive::{Anchoring, ContrastCheck, PassMove, Ramps, over}; pub use explain::{ColorOrigin, Explained, PairReport, SizeLayer, SizeOrigin, explain, explain_sized}; -pub use id::{APP_DEFAULT, AppId, IdError, RESERVED_PREFIX, SUITE_DEFAULT, ThemeId}; +pub use id::{APP_DEFAULT, AppId, IconPackId, IdError, RESERVED_PREFIX, SUITE_DEFAULT, ThemeId}; pub use identify::{Identify, identifiable_outline, visible_hover}; pub use parts::{ BadgeColors, BadgeStyle, BadgeTone, BorderColors, ButtonColors, ButtonVariant, BySize, CheckOffColors, CheckOnColors, CheckSwitchColors, diff --git a/crates/theme/src/semantic_tests.rs b/crates/theme/src/semantic_tests.rs index 5d6c10204..8fcf41812 100644 --- a/crates/theme/src/semantic_tests.rs +++ b/crates/theme/src/semantic_tests.rs @@ -26,6 +26,7 @@ fn theme(id: &str, neutral: &str, accent: &str, status: [&str; 4]) -> ThemeDef { pins: ModePins::default(), high_contrast: ModePins::default(), contrast_intent: ContrastIntent::Standard, + icon_pack: None, apps: BTreeMap::new(), } } diff --git a/crates/theme/src/theme.rs b/crates/theme/src/theme.rs index dddb91609..ecc907a1f 100644 --- a/crates/theme/src/theme.rs +++ b/crates/theme/src/theme.rs @@ -5,7 +5,7 @@ use std::collections::BTreeMap; use super::color::Rgba; use super::ramp::Mode; use super::tokens::{ColorToken, ColorTokens, Edge, KnobShape, RadiusSet, Status, WellShape}; -use crate::{AppId, ThemeId}; +use crate::{AppId, IconPackId, ThemeId}; /// A theme: seeds to derive from, values that override the derivation, and an optional shape. #[derive(Clone, Debug, PartialEq)] @@ -31,6 +31,9 @@ pub struct ThemeDef { pub high_contrast: ModePins, /// Whether the theme is meant to have low contrast. pub contrast_intent: ContrastIntent, + /// The icon pack the theme draws its icons from; `None` draws the suite's default set. Icons the pack lacks fall + /// back to the default drawings. + pub icon_pack: Option, /// Per-app overrides, applied over the theme's own values when resolving for that app. pub apps: BTreeMap, } diff --git a/crates/ui-contract/src/contract/ghost.rs b/crates/ui-contract/src/contract/ghost.rs index 7a30d1267..263cff9a5 100644 --- a/crates/ui-contract/src/contract/ghost.rs +++ b/crates/ui-contract/src/contract/ghost.rs @@ -5,7 +5,7 @@ use crate::primitives::pointer_art::{self as pointers, Art}; -use crate::primitives::{Draw, DrawEnv, IconSet, Mirror, PaintRecord, PaintShape, RuleKind, SvgIcon, TextRun, outline}; +use crate::primitives::{Draw, DrawEnv, Mirror, PaintRecord, PaintShape, RuleKind, SvgIcon, TextRun, outline}; use crate::runtime::drag::{self, DragPreview, DropMark}; use crate::runtime::egui::areas; use crate::runtime::env::Env; @@ -89,7 +89,7 @@ fn pointer_art(env: &Env, cursor: &craft_behavior::PaintedCursor, closed: bool, PaintedCursor::Zoom { out, .. } => pointers::zoom(&pen, *out), PaintedCursor::Tool { icon, hotspot, badge, .. } => { let side = env.tokens.size.icon.md; - let icon = SvgIcon::of(&env.tokens, env.direction, side, icon, IconSet::default(), Mirror::Auto); + let icon = SvgIcon::of(&env.tokens, env.direction, side, icon, Mirror::Auto); pointers::tool(&pen, icon, *hotspot, *badge, side); } PaintedCursor::Badged { badge, .. } => pointers::badge_beside(&pen, *badge), @@ -103,7 +103,7 @@ fn pointer_art(env: &Env, cursor: &craft_behavior::PaintedCursor, closed: bool, PaintedCursor::PointerTool { pointer, icon, .. } => { // The arrow's icon sits under its body, so it takes the larger size to show past the arrow. let side = if *pointer == PointerGlyph::Arrow { env.tokens.size.icon.md } else { env.tokens.size.icon.sm }; - let icon = SvgIcon::of(&env.tokens, env.direction, side, icon, IconSet::default(), Mirror::Auto); + let icon = SvgIcon::of(&env.tokens, env.direction, side, icon, Mirror::Auto); pointers::pointer_tool(&pen, *pointer, icon, side, edge, ink); } // `Hidden` has no marks. diff --git a/crates/ui-contract/src/primitives/icon.rs b/crates/ui-contract/src/primitives/icon.rs index 017b30e68..758cd0744 100644 --- a/crates/ui-contract/src/primitives/icon.rs +++ b/crates/ui-contract/src/primitives/icon.rs @@ -1,11 +1,11 @@ -//! `IconSpec`: an icon to paint, and the SVG set it can name. +//! `IconSpec`: an icon to paint, and the icon sets a theme's icon pack picks among. use super::svg_set; use super::textures::TextureCache; use crate::style::{DataColor, Ink, StyleColor, UiTokens, ink_color}; use craft_behavior::IconId; use craft_i18n::Direction; -use craft_theme::Srgba; +use craft_theme::{IconPackId, Srgba}; use egui::emath::GuiRounding as _; use egui::{Color32, Painter, Rect, pos2, vec2}; @@ -95,8 +95,6 @@ pub struct IconSpec<'a> { pub color: Option, /// Mirroring under right-to-left. pub mirror: Mirror, - /// The set an SVG icon is drawn from. - pub set: IconSet, /// A dot of a colour from data at the icon's bottom-trailing corner; see [`badge`](Self::badge). pub badge: Option, } @@ -104,30 +102,23 @@ pub struct IconSpec<'a> { impl<'a> IconSpec<'a> { /// An icon of the SVG set or a tool icon, in the panel ink. pub fn svg(id: IconId) -> Self { - IconSpec { source: IconSource::Svg(id), ink: Ink::OnPanel, color: None, mirror: Mirror::Auto, set: IconSet::default(), badge: None } + IconSpec { source: IconSource::Svg(id), ink: Ink::OnPanel, color: None, mirror: Mirror::Auto, badge: None } } /// An icon whose glyph is the mark of the cursor `badge` (the plus or minus drawn at the cursor), painted by the /// one cursor-badge painter. pub fn mark(badge: craft_behavior::CursorBadge) -> IconSpec<'a> { - IconSpec { source: IconSource::Mark(badge), ink: Ink::OnPanel, color: None, mirror: Mirror::Auto, set: IconSet::default(), badge: None } + IconSpec { source: IconSource::Mark(badge), ink: Ink::OnPanel, color: None, mirror: Mirror::Auto, badge: None } } /// An icon of `glyph` in the panel ink. pub fn glyph(glyph: &'a dyn Glyph) -> Self { - IconSpec { source: IconSource::Glyph(glyph), ink: Ink::OnPanel, color: None, mirror: Mirror::Auto, set: IconSet::default(), badge: None } + IconSpec { source: IconSource::Glyph(glyph), ink: Ink::OnPanel, color: None, mirror: Mirror::Auto, badge: None } } /// A swatch of `color`, painted as [`Draw::swatch_well`](super::Draw::swatch_well) paints a well. pub fn swatch(color: Srgba) -> Self { - IconSpec { - source: IconSource::Swatch(Some(color)), - ink: Ink::OnPanel, - color: None, - mirror: Mirror::Never, - set: IconSet::default(), - badge: None, - } + IconSpec { source: IconSource::Swatch(Some(color)), ink: Ink::OnPanel, color: None, mirror: Mirror::Never, badge: None } } /// The empty swatch of a colour the theme decides (a "Default" pasteboard colour): it keeps a swatch's place, so @@ -140,13 +131,13 @@ impl<'a> IconSpec<'a> { /// none. A blank name shows an empty box. pub fn initial(name: &str) -> Self { let letter = name.trim_start().chars().next().map_or(' ', |first| first.to_uppercase().next().unwrap_or(first)); - IconSpec { source: IconSource::Initial(letter), ink: Ink::OnPanel, color: None, mirror: Mirror::Never, set: IconSet::default(), badge: None } + IconSpec { source: IconSource::Initial(letter), ink: Ink::OnPanel, color: None, mirror: Mirror::Never, badge: None } } /// A filled circle in the panel ink, or in the colour [`color`](Self::color) or [`data_color`](Self::data_color) /// sets (a status dot, a person's dot). pub fn disc() -> Self { - IconSpec { source: IconSource::Disc, ink: Ink::OnPanel, color: None, mirror: Mirror::Never, set: IconSet::default(), badge: None } + IconSpec { source: IconSource::Disc, ink: Ink::OnPanel, color: None, mirror: Mirror::Never, badge: None } } /// Sets the ink. @@ -175,12 +166,6 @@ impl<'a> IconSpec<'a> { self } - /// Sets the set an SVG icon is drawn from. - pub fn set(mut self, set: IconSet) -> Self { - self.set = set; - self - } - /// Adds a dot of `color` at the bottom-trailing corner of an SVG or glyph icon, ringed in the icon's colour: the /// tone a point picker sets. The dot is a data colour (`Draw::data_fill`); the ring follows the icon's colour. pub fn badge(mut self, color: DataColor) -> Self { @@ -227,7 +212,7 @@ pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, } IconSource::Glyph(glyph) => glyph.paint(painter, tokens, square, color, rtl && glyph.directional() && spec.mirror == Mirror::Auto), IconSource::Svg(id) => { - if let Some(icon) = SvgIcon::of(tokens, direction, side, id, spec.set, spec.mirror) { + if let Some(icon) = SvgIcon::of(tokens, direction, side, id, spec.mirror) { icon.paint(painter, square, color); } } @@ -235,15 +220,34 @@ pub(crate) fn paint(painter: &Painter, tokens: &UiTokens, direction: Direction, } } -/// Logs an icon name the catalog and the app sets lack, once per name: the lookup repeats on every repaint. -fn report_unresolved(name: &str) { +/// Runs `log` the first time `key` is seen: lookups repeat on every repaint and every resolve. +fn log_once(key: String, log: impl FnOnce()) { static REPORTED: std::sync::Mutex>> = std::sync::Mutex::new(None); let mut reported = REPORTED.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if reported.get_or_insert_with(Default::default).insert(name.to_owned()) { - log::error!("icon {name:?} is not in the catalog"); + if reported.get_or_insert_with(Default::default).insert(key) { + log(); } } +impl IconSet { + /// The built-in set a theme's `icon_pack` names: `craft.` and the set's [`id`](IconSet::id), such as + /// `craft.tabler`; `None` for any other id. + pub fn of_pack(id: &IconPackId) -> Option { + let name = id.as_str().strip_prefix(craft_theme::RESERVED_PREFIX)?; + IconSet::ALL.into_iter().find(|set| set.id() == name) + } +} + +/// The set SVG icons draw from under a theme that names `pack`: the default set when it names none, and, with a log +/// line the first time, when it names one that is not installed. +pub(crate) fn theme_icons(pack: Option<&IconPackId>) -> IconSet { + let Some(pack) = pack else { return IconSet::default() }; + IconSet::of_pack(pack).unwrap_or_else(|| { + log_once(format!("pack:{pack}"), || log::warn!("icon pack {pack:?} is not installed; the default icons are drawn")); + IconSet::default() + }) +} + /// A catalog or app icon as it is drawn: its entry and set, whether it is mirrored, and its stroke width in points. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct SvgIcon { @@ -254,15 +258,16 @@ pub(crate) struct SvgIcon { } impl SvgIcon { - /// The icon `id` of `set` at `side` points under `direction` and `mirror`; `None`, with a log line the first time, for a name the - /// catalog and the registered app sets lack. - pub(crate) fn of(tokens: &UiTokens, direction: Direction, side: f32, id: &IconId, set: IconSet, mirror: Mirror) -> Option { + /// The icon `id` in the set `tokens`' theme draws, at `side` points under `direction` and `mirror`; `None`, with a + /// log line the first time, for a name the catalog and the registered app sets lack. + pub(crate) fn of(tokens: &UiTokens, direction: Direction, side: f32, id: &IconId, mirror: Mirror) -> Option { let Some(entry) = svg_set::lookup(id.name()) else { - report_unresolved(id.name()); + let name = id.name(); + log_once(format!("icon:{name}"), || log::error!("icon {name:?} is not in the catalog")); return None; }; let mirrored = direction == Direction::Rtl && svg_set::directional(entry) && mirror == Mirror::Auto; - Some(SvgIcon { entry, set, mirrored, stroke: stroke(tokens, side) }) + Some(SvgIcon { entry, set: tokens.icons(), mirrored, stroke: stroke(tokens, side) }) } /// The image's side in pixels and its stroke in 64ths of a pixel for a square of `side` points at `ppp`: the diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index d302024b4..f04bca2fc 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -36,8 +36,8 @@ pub use draw::{Dashes, DataStrokeWidth, DataWidth, Draw, PaintShape, StrokeColor pub use faces::FacesCx; pub use focus_ring::{FocusKind, FocusRing}; pub use handle::{Handle, HandleShape}; -pub(crate) use icon::SvgIcon; pub use icon::{Glyph, IconSet, IconSource, IconSpec, Mirror, has_icon, icon_names}; +pub(crate) use icon::{SvgIcon, theme_icons}; pub use ime_surface::ImeSurface; pub use kit::{ Checker, CheckerArea, GridAxis, GridInk, GridLines, GridLook, GridStroke, MAX_LINES, Tick, TickEdge, TickRank, dashed, drop_mark, ellipse, diff --git a/crates/ui-contract/src/runtime/env/tokens.rs b/crates/ui-contract/src/runtime/env/tokens.rs index 1c9f71ac1..dcd7ce5f0 100644 --- a/crates/ui-contract/src/runtime/env/tokens.rs +++ b/crates/ui-contract/src/runtime/env/tokens.rs @@ -3,7 +3,7 @@ use super::root::{ResolvedRoot, RootEnv}; use crate::runtime::pass_state; use crate::style::UiTokens; -use craft_theme::{AppSizes, Appearance, Contrast, Mode, SUITE_DEFAULT, Size, TextSize, ThemeDef, ThemeId, builtins, resolve_sized}; +use craft_theme::{AppSizes, Appearance, Contrast, Mode, SUITE_DEFAULT, Size, TextSize, ThemeDef, ThemeId, builtins}; use egui::Context; use std::sync::Arc; @@ -82,11 +82,11 @@ fn resolve_inputs(inputs: &TokenInputs) -> Arc { Appearance { mode: inputs.mode, contrast: inputs.contrast, size: inputs.density, text_size: inputs.text_size, reduced_motion: false }; let themes = builtins(); if let Some(def) = &inputs.theme_def { - return Arc::new(UiTokens::new(Arc::new(resolve_sized(def, appearance, None, &inputs.sizes).tokens), inputs.contrast, inputs.density)); + return Arc::new(UiTokens::of_theme(def, appearance, &inputs.sizes)); } let theme: &ThemeDef = [inputs.theme.as_str(), SUITE_DEFAULT].into_iter().find_map(|id| themes.iter().find(|theme| theme.id.as_str() == id)).unwrap_or(&themes[0]); - Arc::new(UiTokens::new(Arc::new(resolve_sized(theme, appearance, None, &inputs.sizes).tokens), inputs.contrast, inputs.density)) + Arc::new(UiTokens::of_theme(theme, appearance, &inputs.sizes)) } /// What the resolved root tokens depend on. The sizes are compared by identity, as `set_input` does. diff --git a/crates/ui-contract/src/style/tokens.rs b/crates/ui-contract/src/style/tokens.rs index d17bd5507..d4616867f 100644 --- a/crates/ui-contract/src/style/tokens.rs +++ b/crates/ui-contract/src/style/tokens.rs @@ -1,7 +1,8 @@ //! `UiTokens`: the runtime's egui-ready view of one resolved token set. use crate::fonts::{SEMIBOLD, StackFacts}; -use craft_theme::{Contrast, GroupValues, Size, Tokens, TypeRole}; +use crate::primitives::{IconSet, theme_icons}; +use craft_theme::{AppSizes, Appearance, Contrast, GroupValues, Size, ThemeDef, Tokens, TypeRole, resolve_sized}; use egui::{CornerRadius, FontFamily, FontId}; use std::hash::{Hash, Hasher}; use std::ops::Deref; @@ -10,7 +11,7 @@ use std::sync::Arc; /// One resolved token set with the theme's token-group values and a key of their content. Each theme scope /// (mode, contrast, theme, density, text size) resolves its own; equal sets share a key, so the caches keyed by /// it hold one entry per distinct set however often a set is rebuilt. The set remembers the contrast and density it -/// was resolved under, and the key covers both. It derefs to the craft-theme tokens, which +/// was resolved under and the icon set its theme draws, and the key covers them. It derefs to the craft-theme tokens, which /// only `style` reads. #[derive(Clone, Debug)] pub struct UiTokens { @@ -18,14 +19,31 @@ pub struct UiTokens { groups: Arc, contrast: Contrast, density: Size, + icons: IconSet, key: u64, } impl UiTokens { - /// A token set resolved under `contrast` and `density`, with no theme values for token groups. + /// A token set resolved under `contrast` and `density`, with no theme values for token groups, drawing the default + /// icon set. pub fn new(tokens: Arc, contrast: Contrast, density: Size) -> Self { + Self::with_icons(tokens, contrast, density, IconSet::default()) + } + + /// The tokens `theme` resolves to under `appearance` and `sizes`, drawing the icon pack the theme names. + pub fn of_theme(theme: &ThemeDef, appearance: Appearance, sizes: &AppSizes) -> Self { + let tokens = Arc::new(resolve_sized(theme, appearance, None, sizes).tokens); + Self::with_icons(tokens, appearance.contrast, appearance.size, theme_icons(theme.icon_pack.as_ref())) + } + + fn with_icons(tokens: Arc, contrast: Contrast, density: Size, icons: IconSet) -> Self { let groups = Arc::new(GroupValues::new()); - UiTokens { key: content_key(&tokens, &groups, contrast, density), tokens, groups, contrast, density } + UiTokens { key: content_key(&tokens, &groups, contrast, density, icons), tokens, groups, contrast, density, icons } + } + + /// The icon set SVG icons are drawn from. + pub(crate) fn icons(&self) -> IconSet { + self.icons } /// The contrast setting the set was resolved under. @@ -94,11 +112,12 @@ impl UiTokens { } /// The key of a token set: the hash of its resolved values, which are all `f32` and so have no `Hash`. -fn content_key(tokens: &Tokens, groups: &GroupValues, contrast: Contrast, density: Size) -> u64 { +fn content_key(tokens: &Tokens, groups: &GroupValues, contrast: Contrast, density: Size, icons: IconSet) -> u64 { let mut hasher = std::collections::hash_map::DefaultHasher::new(); format!("{tokens:?}{groups:?}").hash(&mut hasher); contrast.hash(&mut hasher); density.hash(&mut hasher); + icons.hash(&mut hasher); hasher.finish() } diff --git a/crates/ui-contract/src/testing/icon_trials.rs b/crates/ui-contract/src/testing/icon_trials.rs index b6e620d16..db89c9f64 100644 --- a/crates/ui-contract/src/testing/icon_trials.rs +++ b/crates/ui-contract/src/testing/icon_trials.rs @@ -1,10 +1,12 @@ -//! Trials of the app icon registry: the catalog wins a clashing name, the first set keeps a name two sets share. +//! Trials of the icon lookup: the app icon registry (the catalog wins a clashing name, the first set keeps a name two +//! sets share) and the set a theme's icon pack picks. -use crate::primitives::{AppIcons, IconSet, Mirror, SvgIcon, icon_names, register_app_icons}; +use crate::primitives::{AppIcons, Mirror, SvgIcon, icon_names, register_app_icons}; +use crate::style::UiTokens; use crate::testing::{style, trial}; use craft_behavior::IconId; use craft_i18n::Direction; -use craft_theme::{Contrast, Mode}; +use craft_theme::{AppSizes, Appearance, Contrast, IconPackId, Mode, Size, TextSize, builtins}; use egui::ColorImage; // Built from parts so the workspace scan of icon-id literals does not read them. @@ -20,7 +22,7 @@ static SECOND_SET: AppIcons = AppIcons { name: "t10-second", stroke_width: None, fn icon(name: &'static str) -> Option { let tokens = style::tokens(Mode::Light, Contrast::Standard); - SvgIcon::of(&tokens, Direction::Ltr, 24.0, &IconId::from(std::borrow::Cow::Borrowed(name)), IconSet::default(), Mirror::Auto) + SvgIcon::of(&tokens, Direction::Ltr, 24.0, &IconId::from(std::borrow::Cow::Borrowed(name)), Mirror::Auto) } fn mask(name: &'static str) -> Option { @@ -57,3 +59,25 @@ fn an_app_icon_set_resolves_after_the_catalog_and_the_first_set_keeps_a_shared_n assert_eq!((mask(FIRST_NAME), mask(SECOND_NAME), mask(CATALOG_NAME)), (first, second, close)); assert_eq!(icon_names().len(), catalog); } + +/// The mask of `name` under the first built-in theme with its icon pack set to `pack`. +fn mask_under_pack(pack: Option<&str>, name: &'static str) -> Option { + let mut theme = builtins()[0].clone(); + let pack = pack.map(IconPackId::parse).transpose(); + assert!(pack.is_ok(), "{pack:?}"); + theme.icon_pack = pack.unwrap_or_default(); + let appearance = + Appearance { mode: Mode::Dark, contrast: Contrast::Standard, size: Size::Compact, text_size: TextSize::Small, reduced_motion: false }; + let tokens = UiTokens::of_theme(&theme, appearance, &AppSizes::default()); + SvgIcon::of(&tokens, Direction::Ltr, 24.0, &IconId::from(std::borrow::Cow::Borrowed(name)), Mirror::Auto).map(|icon| icon.mask(24.0, 1.0)) +} + +#[trial] +fn a_theme_icon_pack_picks_the_set_and_an_unknown_pack_draws_the_default() { + let default = mask_under_pack(None, CATALOG_NAME); + assert!(default.is_some()); + // Carbon's close is a fill drawing; Lucide's and Tabler's are the same two strokes. + assert_ne!(mask_under_pack(Some("craft.carbon"), CATALOG_NAME), default, "a built-in pack draws its own icon"); + assert_eq!(mask_under_pack(Some("craft.lucide"), CATALOG_NAME), default, "the default set by name draws the default"); + assert_eq!(mask_under_pack(Some("user.missing"), CATALOG_NAME), default, "a pack that is not installed draws the default"); +} diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 81b919de2..334dc2ab6 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -492,7 +492,7 @@ The Text size setting scales the roles only (0.83x, 1x, 1.17x, 1.33x), rounded t ### 5.3 Iconography -- **Sets.** Phosphor is the base set. The gallery's active set defaults to Lucide. A theme may supply an icon pack that replaces the base icons it covers; missing icons fall back to the base set. +- **Sets.** Phosphor is the base set: it draws every icon. The suite's default set is Lucide, which falls back to Phosphor. A theme picks its set with `icon_pack` ([suite-themes.md](suite-themes.md)): a built-in set (`craft.lucide`, `craft.phosphor`, `craft.carbon`, `craft.tabler`) or a pack in the suite library that replaces the icons it covers. Missing icons fall back to the base set, a library pack's to the default set. The resolved tokens carry the set, so every icon drawn under a theme, a theme scope included, follows it. - **Strokes.** 1.25 pt at the small size, 1.5 pt at medium and large. ### 5.4 Dimensions diff --git a/docs/suite-themes.md b/docs/suite-themes.md index b0cb6bdba..2b9f3d4e5 100644 --- a/docs/suite-themes.md +++ b/docs/suite-themes.md @@ -37,6 +37,7 @@ the app's pins (`apps.`), then the theme's high-contrast pins, then the app' "id": "user.navy", "name": "Navy", "version": 1, "variants": "both", "contrast_intent": "standard", + "icon_pack": "craft.carbon", "seeds": { "neutral": "#535353", "accent": "#78ADF6", "status": { "good": "#85DC6A", "warn": "#E8B046", "bad": "#FF8080", "info": "#78ADF6" } }, "shape": null, @@ -55,6 +56,7 @@ the app's pins (`apps.`), then the theme's high-contrast pins, then the app' | `version` | no | the author's revision, default 1 | | `variants` | no | `"both"` (default), `"light"` or `"dark"` | | `contrast_intent` | no | `"standard"` (default) or `"low"`: the theme is meant to be soft, and pickers label it "Low contrast" | +| `icon_pack` | no | the id of the icon pack the theme draws its icons from (same form as `id`); absent or `null` draws the suite's default set (Lucide). `craft.lucide`, `craft.phosphor`, `craft.carbon` and `craft.tabler` are the built-in sets, which fall back to Phosphor for icons they lack; other ids name packs in the suite library. A pack that is not installed draws the default icons; it is not a file error | | `seeds` | yes | `neutral`, `accent` and `status.good/warn/bad/info`, all required | | `shape` | no | `null`, or `{ "radius": { control, popup, window, panel, button, pill? }, "radius_offset": { control?, popup?, window? }, "edge": "flat" or {"bevel": {"width": 1}}, "knob": "round" or "tab", "wells": "square" or "round" }`; `knob` is the shape of a value track's thumb (default `"round"`; Classic's `"tab"` is an upright tab); `wells` is the shape of a colour well that stands on its own, SwatchPair's (default `"square"`; Adwaita, Breeze and Soft are `"round"`); a radius is a number or `"full"`; `radius` needs the first five keys when present and fixes the radii at every Size; `radius_offset` (numbers, negative allowed, missing keys 0) is added to the control, popup and window radii in force, so the theme keeps its own shape at every Size (Soft: control +1, popup +2, window +2, which makes 7/10/14 at Comfortable and 4/6/8 at Compact); a "full" radius and `panel`, `button` and `pill` are not offset, and a sum below 0 is 0; `pill` (switch, slider, progress and badge shapes, clamped to half the part's height) defaults to `"full"`, and Classic sets it to 0 | | `light`, `dark` | no | colour pins: dotted token path to `#RRGGBB`, `#RRGGBBAA` or a reference `"{token.path}"` (see References); surfaces (`surface.*` except `surface.scrim`) must be opaque. A `seeds` key holds that mode's seed overrides: `neutral`, `accent` and `status.good/warn/bad/info`, each optional; a field it names replaces the theme's `seeds` value in that mode and the rest fall through |