widgets-w1: net change of 2 commits

- widgets-w1: written by an agent
- widgets-w1: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor committed 2026-11-27 03:23:17 +00:00
1 parent 6934082b3d
commit a4adbb46e4
7 files changed
+438 -106

No files matched your search

+16 -1
View File
@@ -199,7 +199,22 @@ impl Preflight<'_> {
/// The root `<svg>`'s element children in document order (text and comments skipped): `class` attribute, byte
/// span, and `shared` for `defs` and `style`.
pub fn top_level_parts(&self) -> Vec<TopLevelPart<'_>> {
todo!("wg.F13")
self.xml
.root_element()
.children()
.filter(roxmltree::Node::is_element)
.map(|part| TopLevelPart {
class: part.attribute("class"),
span: part.range(),
shared: matches!(part.tag_name().name(), "defs" | "style"),
descendant_classes: part
.descendants()
.filter(|node| *node != part && node.is_element())
.filter(|node| !node.ancestors().any(|ancestor| ancestor.is_element() && matches!(ancestor.tag_name().name(), "defs" | "style")))
.filter_map(|node| node.attribute("class"))
.collect(),
})
.collect()
}
/// The deepest stack of open source elements, before references are followed; a
+30 -40
View File
@@ -338,10 +338,9 @@ impl SvgIcon {
(px, stroke_px)
}
/// The icon's ink layer in white for a square of `side` points at `ppp`, its alpha from the drawing.
/// The icon's silhouette in white for a square of `side` points at `ppp`, its alpha from the drawing.
pub(crate) fn mask(&self, side: f32, ppp: f32) -> egui::ColorImage {
// P3(widgets-w1): wg.F17
self.layer(side, ppp, svg_set::Layer::Run { run: 0, class: svg_set::Class::Ink })
self.layer(side, ppp, svg_set::Layer::Silhouette)
}
/// The icon's `layer` for a square of `side` points at `ppp`.
@@ -353,13 +352,12 @@ impl SvgIcon {
/// Paints every layer of the icon in `color` centred in `square`, on whole pixels: a one-ink silhouette (a
/// cursor's icon).
pub(crate) fn paint(&self, painter: &Painter, square: Rect, color: Color32) {
self.paint_layers(painter, square, LayerInks::single(color));
self.paint_layers(painter, square, LayerInks::Single(color));
}
/// Paints the icon centred in `square`, on whole pixels, each layer in its ink of `inks`. A catalog icon has only
/// the ink layer; an app icon also paints its accent and fixed parts over it. A layer with no part is not painted.
/// An app icon with a fill (`AppIcons::with_fills`) paints it under every layer, in the fill's own colour whatever
/// the inks.
/// Paints the icon centred in `square`, on whole pixels. Layered app icons paint consecutive colour runs in
/// document order; single-ink and catalog icons paint one silhouette. Empty runs paint no quad.
/// An app icon's fill (`AppIcons::with_fills`) paints underneath in its own colour whatever the inks.
pub(crate) fn paint_layers(&self, painter: &Painter, square: Rect, inks: LayerInks) {
let ctx = painter.ctx();
let ppp = ctx.pixels_per_point();
@@ -375,36 +373,31 @@ impl SvgIcon {
let tint = Color32::from_rgba_unmultiplied(r, g, b, a);
crate::runtime::egui::textures::paint(painter, texture, rect, uv, tint, egui::CornerRadius::ZERO);
}
// P3(widgets-w1): wg.F18
let (ink, accent, fixed) = match inks {
LayerInks::Single(color) => (color, color, Some(color)),
LayerInks::Layered { ink, accent } => (ink, accent, None),
};
// P3(widgets-w1): wg.F17
let fixed = match fixed {
Some(color) => (svg_set::Layer::Silhouette, color),
// design: allow[raw-colour/const](a fixed layer keeps the colours it is drawn in: a white tint leaves them unchanged)
None => (svg_set::Layer::Run { run: 2, class: svg_set::Class::Fixed }, Color32::WHITE),
};
// P3(widgets-w1): wg.F17
let layers = [
(svg_set::Layer::Run { run: 0, class: svg_set::Class::Ink }, ink),
(svg_set::Layer::Run { run: 1, class: svg_set::Class::Accent }, accent),
fixed,
];
let count = if matches!(self.entry, svg_set::Entry::Catalog(_)) { 1 } else { layers.len() };
for (layer, color) in layers.into_iter().take(count) {
// Each layer is its own texture, so a disabled icon's one-ink fixed layer and the enabled one as drawn
// are both kept.
let paint = |layer, color| {
let key = (self.entry, self.set, px, stroke_px, self.mirrored, layer);
let drawn = || {
let image = self.layer(square.width(), ppp, layer);
(!image.pixels.iter().all(|pixel| pixel.a() == 0)).then_some(image)
};
let Some(texture) = TextureCache::texture_if(ctx, key, drawn) else {
continue;
return;
};
crate::runtime::egui::textures::paint(painter, texture, rect, uv, color, egui::CornerRadius::ZERO);
};
match inks {
LayerInks::Single(color) => paint(svg_set::Layer::Silhouette, color),
LayerInks::Layered { ink, .. } if matches!(self.entry, svg_set::Entry::Catalog(_)) => paint(svg_set::Layer::Silhouette, ink),
LayerInks::Layered { ink, accent } => {
for &(run, class) in svg_set::runs_of(self.entry).iter() {
let color = match class {
svg_set::Class::Ink => ink,
svg_set::Class::Accent => accent,
// design: allow[raw-colour/const](a white tint preserves a fixed run's own colours)
svg_set::Class::Fixed => Color32::WHITE,
};
paint(svg_set::Layer::Run { run, class }, color);
}
}
}
}
}
@@ -415,29 +408,26 @@ pub(crate) enum LayerInks {
/// Every part paints in one ink.
Single(Color32),
/// Ink and accent parts take their own inks; fixed parts paint as drawn.
Layered { ink: Color32, accent: Color32 },
Layered {
/// The ink of unclassed parts.
ink: Color32,
/// The ink of accent parts.
accent: Color32,
},
}
impl LayerInks {
/// Every layer in `color`.
pub(crate) fn single(color: Color32) -> Self {
// P3(widgets-w1): wg.F18
LayerInks::Single(color)
}
/// The inks of an icon painted in `color`: the accent parts in `colors.accent.solid` and the fixed parts as drawn,
/// except that with `single_ink` (a disabled component) every layer paints in `color`, and with `on_dark` (a strong
/// fill or scrim, where the accent colour would vanish) the accent parts paint in `color` and the fixed parts stay
/// as drawn.
pub(crate) fn of(tokens: &UiTokens, color: Color32, single_ink: bool, on_dark: bool) -> Self {
if on_dark && !single_ink {
// P3(widgets-w1): wg.F18
return LayerInks::Layered { ink: color, accent: color };
}
if single_ink {
return LayerInks::single(color);
return LayerInks::Single(color);
}
// P3(widgets-w1): wg.F18
LayerInks::Layered { ink: color, accent: crate::style::rgba_color(tokens.color.accent.solid) }
}
}
+85 -23
View File
@@ -12,6 +12,8 @@ include!(concat!(env!("OUT_DIR"), "/icons.rs"));
/// Unclassed parts take the ink, `accent` parts take the accent ink, and `fixed` parts keep their colours, in document
/// order; `on` and `off` parts paint only in the enabled and disabled look, respectively.
/// Each non-shared root child has one inherited colour class; differing nested colour classes are refused.
/// A root child's `accent` or `fixed` chooses its colour; otherwise it takes Ink. Descendants may inherit or repeat
/// that colour, and `on`/`off` affect visibility only. Shared `defs` and `style` do not consume run positions.
/// Visibility wrappers sit inside colour wrappers, and differing fill and stroke colours use consecutive parts,
/// fill first. Adjacent equal-colour runs retain source order; disabled icons form one silhouette.
#[derive(Clone, Copy, Debug)]
@@ -44,6 +46,8 @@ impl AppIcons {
///
/// Registering the same set again is a no-op; a name the built-in catalog or an earlier app set has is refused with a
/// log line.
/// Icons follow [`AppIcons`]'s homogeneous root-part convention and paint adjacent equal-colour runs in document
/// order. Invalid documents are logged and refused individually, so valid siblings remain available.
pub fn register_app_icons(set: &'static AppIcons) {
let mut guard = APPS.write().unwrap_or_else(PoisonError::into_inner);
let registry = &mut *guard;
@@ -52,7 +56,9 @@ pub fn register_app_icons(set: &'static AppIcons) {
}
let set_at = registry.sets.len();
registry.sets.push(set);
for (icon, (name, _)) in set.icons.iter().enumerate() {
registry.runs.push(Vec::with_capacity(set.icons.len()));
for (icon, (name, svg)) in set.icons.iter().enumerate() {
registry.runs[set_at].push(IconRuns::default());
if find(name).is_some() {
log::warn!("app icon set {:?}: icon {name:?} is refused, the built-in catalog has it", set.name);
continue;
@@ -62,7 +68,13 @@ pub fn register_app_icons(set: &'static AppIcons) {
let earlier = registry.sets[registry.index[at].1].name;
log::warn!("app icon set {:?}: icon {name:?} is refused, set {earlier:?} has it", set.name);
}
Err(at) => registry.index.insert(at, (name, set_at, icon)),
Err(at) => match icon_runs(svg) {
Ok(runs) => {
registry.runs[set_at][icon] = runs;
registry.index.insert(at, (name, set_at, icon));
}
Err(reason) => log::warn!("app icon set {:?}: icon {name:?} is refused: {reason}", set.name),
},
}
}
}
@@ -71,10 +83,27 @@ pub fn register_app_icons(set: &'static AppIcons) {
struct Registry {
sets: Vec<&'static AppIcons>,
index: Vec<(&'static str, usize, usize)>,
runs: Vec<Vec<IconRuns>>,
}
#[derive(Default)]
struct IconRuns {
documents: Vec<Arc<[u8]>>,
order: Arc<[(u16, Class)]>,
}
fn icon_runs(svg: &[u8]) -> Result<IconRuns, String> {
let documents = svg_tree::classified_runs(svg)?;
let mut order = Vec::with_capacity(documents.len());
for (run, (class, _)) in documents.iter().enumerate() {
let run = u16::try_from(run).map_err(|e| e.to_string())?;
order.push((run, *class));
}
Ok(IconRuns { documents: documents.into_iter().map(|(_, document)| Arc::from(document.into_bytes())).collect(), order: Arc::from(order) })
}
/// Process-wide like the generated catalog: it is the icon catalog, not pass state.
static APPS: RwLock<Registry> = RwLock::new(Registry { sets: Vec::new(), index: Vec::new() });
static APPS: RwLock<Registry> = RwLock::new(Registry { sets: Vec::new(), index: Vec::new(), runs: Vec::new() });
/// An icon the lookup found: a catalog position or an app set's icon.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -157,11 +186,35 @@ pub(crate) enum Class {
Fixed,
}
impl Class {
/// The colour chosen by a root part; an unclassed part takes the icon's ink.
pub(crate) fn root(classes: Option<&str>) -> Result<Self, String> {
Ok(Self::of(classes)?.unwrap_or(Self::Ink))
}
/// The explicit colour class, refusing ambiguous parts; visibility classes do not choose an ink.
pub(crate) fn of(classes: Option<&str>) -> Result<Option<Self>, String> {
let mut color = None;
for class in classes.unwrap_or_default().split_ascii_whitespace() {
let next = match class {
"accent" => Self::Accent,
"fixed" => Self::Fixed,
_ => continue,
};
if color.is_some_and(|known| known != next) {
return Err("an icon part declares differing colour classes".to_owned());
}
color = Some(next);
}
Ok(color)
}
}
/// The paint order of an icon's runs, split once at registration.
#[allow(dead_code)] // P3(widgets-w1): wg.F15
pub(crate) fn runs_of(entry: Entry) -> Arc<[(u16, Class)]> {
let _ = entry;
todo!("wg.F15")
let Entry::App { set, icon } = entry else { return Arc::from([]) };
let registry = APPS.read().unwrap_or_else(PoisonError::into_inner);
Arc::clone(&registry.runs[set][icon].order)
}
/// One run under its class sheet, or the whole icon as one silhouette.
@@ -181,31 +234,40 @@ pub(crate) enum Layer {
impl Layer {
/// The style sheet that hides every part outside the layer; the SVG engine applies it, so the class is matched
/// by its own selectors.
fn style_sheet(self) -> &'static str {
// P3(widgets-w1): wg.F17
if let Layer::Run { run, .. } = self {
let _ = run;
}
match self {
Layer::Run { class: Class::Ink, .. } => ".accent, .accent *, .fixed, .fixed * { visibility: hidden }",
Layer::Run { class: Class::Accent, .. } => "* { visibility: hidden } .accent, .accent * { visibility: visible }",
Layer::Run { class: Class::Fixed, .. } | Layer::Silhouette => "* { visibility: hidden } .fixed, .fixed * { visibility: visible }",
}
fn style_sheet(self) -> Option<&'static str> {
Some(match self {
Layer::Run { class: Class::Ink, .. } => ".accent, .accent *, .fixed, .fixed *, .off, .off * { visibility: hidden }",
Layer::Run { class: Class::Accent, .. } => {
"* { visibility: hidden } .accent, .accent * { visibility: visible } .off, .off * { visibility: hidden }"
}
Layer::Run { class: Class::Fixed, .. } => {
"* { visibility: hidden } .fixed, .fixed * { visibility: visible } .off, .off * { visibility: hidden }"
}
Layer::Silhouette => ".on, .on * { visibility: hidden }",
})
}
}
/// The `layer` of `entry` at `px` x `px` physical pixels, in white or, for a [`Class::Fixed`] run, as drawn. A catalog entry
/// has only an ink layer, drawn as [`rasterise`]; its other layers are transparent. An app entry is drawn with its
/// has only a silhouette, drawn as [`rasterise`]; its run layers are transparent. An app entry is drawn with its
/// set's stroke width, the layer's parts only.
pub(crate) fn rasterise_entry(entry: Entry, set: IconSet, px: u32, stroke_px: f32, mirrored: bool, layer: Layer) -> ColorImage {
match (entry, layer) {
// P3(widgets-w1): wg.F17
(Entry::Catalog(index), Layer::Run { class: Class::Ink, .. }) => rasterise(index, set, px, stroke_px, mirrored),
(Entry::Catalog(index), Layer::Silhouette) => rasterise(index, set, px, stroke_px, mirrored),
(Entry::Catalog(_), _) => ColorImage::filled([px as usize; 2], Color32::TRANSPARENT),
(Entry::App { set: s, icon }, layer) => {
let (name, svg, own) = app_icon(s, icon);
let drawn = draw(svg, Some(layer.style_sheet()), own, px, stroke_px, mirrored);
// P3(widgets-w1): wg.F17
let run = match layer {
Layer::Run { run, .. } => {
let registry = APPS.read().unwrap_or_else(PoisonError::into_inner);
registry.runs[s][icon].documents.get(usize::from(run)).cloned()
}
Layer::Silhouette => None,
};
let drawn = match (&run, layer) {
(None, Layer::Run { .. }) => Err("unknown icon run".to_owned()),
_ => draw(run.as_deref().unwrap_or(svg), layer.style_sheet(), own, px, stroke_px, mirrored),
};
image(drawn, px, matches!(layer, Layer::Run { class: Class::Fixed, .. }), || format!("app icon {name}"))
}
}
@@ -245,8 +307,8 @@ fn draw(svg: &[u8], style_sheet: Option<&str>, own: Option<f32>, px: u32, stroke
if let Some(own) = own {
// Every `stroke-width` scales by the same factor, so a set's thinner details stay thinner.
let units = stroke_px * view.width() / px as f32;
let text = std::str::from_utf8(svg).map_err(|e| e.to_string())?;
tree = svg_tree::parse_styled(scale_stroke_widths(text, units / own).as_bytes(), style_sheet)?;
let text = svg_tree::icon_text(svg)?;
tree = svg_tree::parse_styled(scale_stroke_widths(&text, units / own).as_bytes(), style_sheet)?;
}
let (sx, sy) = (px as f32 / view.width(), px as f32 / view.height());
let transform =
+75 -7
View File
@@ -2,13 +2,83 @@
//! user's disk, so parsing is bounded: no gzip, no DTD (entity expansion), a node limit, a nesting limit, and no
//! `<image>` loaded, which keeps a document from making the renderer read another file or nest an SVG.
use craft_svg::tree::{self, Limits, usvg};
use super::svg_set::Class;
use craft_svg::{
svgz,
tree::{self, Limits, usvg},
};
/// Admission checks shared by parsing and text rewriting; compressed icons never reach the decoder.
fn admit_icon(svg: &[u8]) -> Result<(), String> {
if svg.starts_with(&GZIP_MAGIC) {
return Err("compressed SVG".to_owned());
}
let limit = icon_limits().bytes;
if svg.len() > limit {
return Err(svgz::Error::TooLarge(limit).to_string());
}
Ok(())
}
/// Bounded, checked UTF-8 text for rewriting without retaining an obsolete encoding declaration.
pub(crate) fn icon_text(svg: &[u8]) -> Result<String, String> {
let limits = icon_limits();
admit_icon(svg)?;
let text = svgz::decode(svg).map_err(|e| e.to_string())?;
if text.len() > limits.bytes {
return Err(svgz::Error::TooLarge(limits.bytes).to_string());
}
tree::preflight(&text, &limits).map_err(|e| e.to_string())?;
let text = if text.strip_prefix("<?xml").is_some_and(|rest| rest.starts_with(char::is_whitespace)) {
let end = text.find("?>").ok_or_else(|| "unterminated XML declaration".to_owned())?;
&text[end + 2..]
} else {
&text
};
Ok(text.to_owned())
}
/// Splits consecutive non-shared top-level parts of equal class into complete SVG documents.
#[allow(dead_code)] // P3(widgets-w1): wg.F14
pub(crate) fn split_runs(svg: &[u8]) -> Result<Vec<String>, String> {
let _ = svg;
todo!("wg.F14")
Ok(classified_runs(svg)?.into_iter().map(|(_, document)| document).collect())
}
/// Splits complete run documents while retaining the class chosen during grouping.
pub(super) fn classified_runs(svg: &[u8]) -> Result<Vec<(Class, String)>, String> {
let text = icon_text(svg)?;
let checked = tree::preflight(&text, &icon_limits()).map_err(|e| e.to_string())?;
let parts = checked.top_level_parts();
let mut runs: Vec<(Class, Vec<std::ops::Range<usize>>)> = Vec::new();
for part in parts.iter().filter(|part| !part.shared) {
let class = Class::root(part.class)?;
for descendant in &part.descendant_classes {
if Class::of(Some(descendant))?.is_some_and(|nested| nested != class) {
return Err("an icon root part contains differing colour classes".to_owned());
}
}
if let Some((_, spans)) = runs.last_mut().filter(|(last, _)| *last == class) {
spans.push(part.span.clone());
} else {
runs.push((class, vec![part.span.clone()]));
}
}
// Registration refuses rendering errors too, including invalid SVG roots with no parts.
parse_styled(text.as_bytes(), None)?;
let (Some(first), Some(last)) = (parts.first(), parts.last()) else { return Ok(Vec::new()) };
let mut documents = Vec::with_capacity(runs.len());
for (class, spans) in runs {
let mut document = text[..first.span.start].to_owned();
for part in parts.iter().filter(|part| part.shared) {
document.push_str(&text[part.span.clone()]);
}
for span in spans {
document.push_str(&text[span]);
}
document.push_str(&text[last.span.end..]);
parse_styled(document.as_bytes(), None)?;
documents.push((class, document));
}
Ok(documents)
}
/// Elements and text nodes an icon SVG may have; a glyph has a handful.
@@ -45,9 +115,7 @@ pub fn parse(svg: &[u8]) -> Result<usvg::Tree, String> {
/// parser, so a layer by class is read by the SVG engine's own selectors.
#[doc(hidden)]
pub fn parse_styled(svg: &[u8], style_sheet: Option<&str>) -> Result<usvg::Tree, String> {
if svg.starts_with(&GZIP_MAGIC) {
return Err("compressed SVG".to_owned());
}
admit_icon(svg)?;
let options = usvg::Options {
image_href_resolver: usvg::ImageHrefResolver { resolve_data: Box::new(|_, _, _| None), resolve_string: Box::new(|_, _| None) },
style_sheet: style_sheet.map(str::to_owned),
+164 -16
View File
@@ -1,7 +1,9 @@
//! Trials of the icon lookup: the app icon registry (the catalog wins a clashing name, the first set keeps a name two
//! sets share), the set a theme's icon pack picks, and an app icon's layers by class.
//! sets share), the set a theme's icon pack picks, and app icons' ordered colour runs and disabled silhouettes.
use crate::primitives::{AppIcons, DataMode, Draw, DrawEnv, IconSpec, Layer, Mirror, PaintRecord, SvgIcon, icon_names, register_app_icons};
use crate::primitives::{
AppIcons, Class, DataMode, Draw, DrawEnv, FlagMark, IconSpec, Layer, Mirror, PaintRecord, SvgIcon, icon_names, register_app_icons,
};
use crate::style::{Ink, StyleColor, UiTokens, ink_color, rgba_color};
use crate::testing::{Frames, style, trial};
use craft_behavior::IconId;
@@ -131,8 +133,7 @@ fn an_accent_part_on_a_dark_surface_paints_in_the_icons_ink() {
}
let record = RefCell::new(PaintRecord::default());
let shapes = frames.frame_shapes(|ui| {
// P3(widgets-w1): cv.F5
let env = DrawEnv { tokens: &tokens, direction: Direction::Ltr, ink: surface, mark: crate::primitives::FlagMark::default() };
let env = DrawEnv { tokens: &tokens, direction: Direction::Ltr, ink: surface, mark: FlagMark::default() };
Draw::new(ui.painter(), &record, env).icon(rect, &spec);
});
textured(&shapes).into_iter().map(|(_, tint)| tint).collect::<Vec<_>>()
@@ -157,8 +158,7 @@ fn an_accent_part_paints_in_the_accent_ink_a_fixed_part_as_drawn_and_both_take_t
let spec = IconSpec::svg(IconId::from(std::borrow::Cow::Borrowed(name))).color(StyleColor(color));
let record = RefCell::new(PaintRecord::default());
let shapes = frames.frame_shapes(|ui| {
// P3(widgets-w1): cv.F5
let env = DrawEnv { tokens: &tokens, direction: Direction::Ltr, ink: Ink::OnPanel, mark: crate::primitives::FlagMark::default() };
let env = DrawEnv { tokens: &tokens, direction: Direction::Ltr, ink: Ink::OnPanel, mark: FlagMark::default() };
Draw::new(ui.painter(), &record, env).data(mode).icon(rect, &spec);
});
textured(&shapes)
@@ -177,26 +177,24 @@ fn an_accent_part_paints_in_the_accent_ink_a_fixed_part_as_drawn_and_both_take_t
assert_eq!(fixed_tint, Color32::WHITE, "the fixed parts keep the colours they are drawn in");
assert!(ink_layer != accent_layer && accent_layer != fixed_layer && ink_layer != fixed_layer, "each layer is its own texture");
assert_eq!(disabled.len(), 3, "a disabled app icon paints the same three layers, got {disabled:?}");
let [(off_ink, a), (off_accent, b), (off_fixed, c)] = disabled[..] else { return };
assert_eq!([a, b, c], [ink; 3], "every layer takes the one ink when the component is disabled");
assert_eq!((off_ink, off_accent), (ink_layer, accent_layer), "the ink and accent layers are the same drawings, tinted");
assert_ne!(off_fixed, fixed_layer, "a disabled fixed part is drawn as a silhouette, not in its own colours");
assert_eq!(disabled.len(), 1, "a disabled app icon paints one silhouette, got {disabled:?}");
let [(silhouette, tint)] = disabled[..] else { return };
assert_eq!(tint, ink, "the silhouette takes the component's one ink");
assert!(enabled.iter().all(|(texture, _)| *texture != silhouette), "the silhouette has its own texture");
let tints: Vec<Color32> = enabled_in_the_disabled_colour.iter().map(|(_, tint)| *tint).collect();
// design: allow[raw-colour/const](a fixed layer keeps the colours it is drawn in: the trial expects the white tint that leaves them unchanged)
assert_eq!(tints, [off, rgba_color(tokens.color.accent.solid), Color32::WHITE], "an enabled icon in the disabled colour keeps its layers");
// What each layer holds: the class split is the SVG engine's, so a sheet it ignored would give every layer the whole drawing.
// Each run must retain its own geometry, and the fixed run must keep its drawn colour.
let layered = icon(LAYERED_NAME);
assert!(layered.is_some(), "the layered icon resolves");
let Some(layered) = layered else { return };
let (body, nib, cap) = ((9, 12), (16, 12), (3, 12));
// P3(widgets-w1): wg.F17
let [plain, accent, fixed] = [
Layer::Run { run: 0, class: crate::primitives::Class::Ink },
Layer::Run { run: 1, class: crate::primitives::Class::Accent },
Layer::Run { run: 2, class: crate::primitives::Class::Fixed },
Layer::Run { run: 0, class: Class::Ink },
Layer::Run { run: 1, class: Class::Accent },
Layer::Run { run: 2, class: Class::Fixed },
]
.map(|layer| layered.layer(24.0, 1.0, layer));
assert!(texel(&plain, body.0, body.1).a() > 0 && texel(&plain, nib.0, nib.1).a() == 0, "the ink layer holds the plain body only");
@@ -204,11 +202,161 @@ fn an_accent_part_paints_in_the_accent_ink_a_fixed_part_as_drawn_and_both_take_t
let red = texel(&fixed, cap.0, cap.1);
assert!(red.a() > 0 && red.r() > red.g() && red.r() > red.b(), "the fixed layer holds the cap in its own colour: {red:?}");
assert!(texel(&fixed, body.0, body.1).a() == 0 && texel(&plain, cap.0, cap.1).a() == 0, "the cap is in no other layer");
let silhouette = layered.layer(24.0, 1.0, Layer::Silhouette);
for (x, y) in [body, nib, cap] {
assert!(texel(&silhouette, x, y).a() > 0, "the disabled silhouette holds every part");
}
// An icon with no classed part paints its ink layer alone.
assert_eq!(paint(PLAIN_NAME, DataMode::Full, ink).len(), 1, "a layer with no part paints no quad");
}
#[trial]
fn an_app_icons_parts_paint_in_document_order_and_on_and_off_parts_only_in_their_look() {
// Original SVG fixtures isolate ordering, visibility and encoding without external artwork.
const ORDERED_NAME: &str = concat!("zz_w1_", "ordered");
const FEATURES_NAME: &str = concat!("zz_w1_", "features");
// Shared nodes consume no run: the two ink bars must stay on opposite sides of the fixed square.
const ORDERED: &[u8] = br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<defs><clipPath id="body"><rect width="24" height="24"/></clipPath></defs>
<g clip-path="url(#body)"><defs><path class="accent" id="unused" d="M1 1 H2"/></defs><rect x="2" y="8" width="20" height="8"/></g>
<style>.unused { fill: none }</style>
<g class="fixed"><rect x="6" y="6" width="12" height="12" fill="#d02020"/><g class="on"><g class="fixed"><circle cx="3" cy="21" r="2"/></g></g><g class="off"><circle cx="21" cy="21" r="2"/></g></g>
<g><rect x="2" y="10" width="20" height="2"/></g>
<g class="on"><circle cx="3" cy="3" r="2"/></g>
<g class="off"><circle cx="21" cy="3" r="2"/></g>
</svg>"##;
// Each feature has its own region, so losing one cannot be masked by another primitive.
const FEATURES: &[u8] = br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M2 3 H4" fill="none" stroke="black" stroke-width="2" stroke-linecap="round"/>
<path d="M8 5 V2 H12" fill="none" stroke="black" stroke-width="4" stroke-linejoin="round"/>
<path d="M15 3 H23" fill="none" stroke="black" stroke-width="2" stroke-dasharray="2 2"/>
<rect x="2" y="8" width="4" height="4" fill-opacity="0.4"/>
<path d="M8 12 A3 3 0 0 1 14 12 Z"/>
<path d="M17 12 C17 6 23 6 23 12 Z"/>
<rect x="2" y="17" width="6" height="2" transform="rotate(90 5 18)"/>
<rect x="10" y="16" width="6" height="6" rx="3"/>
</svg>"##;
static SET: AppIcons = AppIcons::new("w1-order", None, &[(ORDERED_NAME, ORDERED), (FEATURES_NAME, FEATURES)]);
register_app_icons(&SET);
let tokens = style::tokens(Mode::Light, Contrast::Standard);
let ink = ink_color(&tokens, Ink::OnPanel);
let mut frames = Frames::new();
frames.record_paint();
let uploads = RefCell::new(Vec::new());
let mut paint = |name: &'static str, mode| {
let spec = IconSpec::svg(IconId::from(std::borrow::Cow::Borrowed(name))).color(StyleColor(ink));
let record = RefCell::new(PaintRecord::default());
frames.frame(Vec::new(), |ui| {
let env = DrawEnv { tokens: &tokens, direction: Direction::Ltr, ink: Ink::OnPanel, mark: FlagMark::default() };
Draw::new(ui.painter(), &record, env).data(mode).icon(Rect::from_min_size(pos2(10.0, 10.0), vec2(24.0, 24.0)), &spec);
});
let Some(output) = frames.take_paint() else { return Vec::new() };
let shapes = output.shapes.iter().map(|clipped| clipped.shape.clone()).collect::<Vec<_>>();
let quads = textured(&shapes);
for (texture, _) in &quads {
if let Some(deltas) = output.textures_delta.set.get(texture) {
for delta in deltas {
let egui::ImageData::Color(image) = &delta.image;
uploads.borrow_mut().push((*texture, std::sync::Arc::clone(image)));
}
}
}
output.drop_without_applying_deltas();
quads
};
let enabled = paint(ORDERED_NAME, DataMode::Full);
// design: allow[raw-colour/const](a white tint preserves the fixed square's colour)
assert_eq!(enabled.iter().map(|(_, tint)| *tint).collect::<Vec<_>>(), [ink, Color32::WHITE, ink]);
let disabled = paint(ORDERED_NAME, DataMode::Dimmed);
assert_eq!(disabled.len(), 1);
assert!(enabled.iter().all(|(texture, _)| *texture != disabled[0].0));
let ordered = icon(ORDERED_NAME);
assert!(ordered.is_some(), "the ordered icon must register");
let Some(ordered) = ordered else { return };
let runs = [Class::Ink, Class::Fixed, Class::Ink]
.into_iter()
.enumerate()
.map(|(run, class)| ordered.layer(24.0, 1.0, Layer::Run { run: run as u16, class }))
.collect::<Vec<_>>();
for ((texture, _), expected) in enabled.iter().zip(&runs) {
assert!(uploads.borrow().iter().any(|(id, image)| id == texture && image.as_ref() == expected), "the painted textures follow document order");
}
assert!(texel(&runs[0], 3, 14).a() > 0 && texel(&runs[0], 3, 3).a() == 0);
assert!(texel(&runs[1], 12, 14).r() > texel(&runs[1], 12, 14).g());
assert!(texel(&runs[2], 12, 10).a() > 0 && texel(&runs[2], 12, 14).a() == 0);
assert!(runs.iter().any(|run| texel(run, 3, 3).a() > 0), "the enabled look holds the on group");
assert!(runs.iter().all(|run| texel(run, 21, 3).a() == 0), "no enabled texture holds the off group");
let silhouette = ordered.layer(24.0, 1.0, Layer::Silhouette);
assert!(texel(&silhouette, 3, 3).a() == 0 && texel(&silhouette, 21, 3).a() > 0);
assert!(runs.iter().any(|run| texel(run, 3, 21).a() > 0), "fixed parts inherit their colour inside visibility wrappers");
assert!(runs.iter().all(|run| texel(run, 21, 21).a() == 0), "the fixed class cannot reveal an off group");
assert!(texel(&silhouette, 3, 21).a() == 0 && texel(&silhouette, 21, 21).a() > 0);
assert_eq!(paint(FEATURES_NAME, DataMode::Full).len(), 1);
assert_eq!(paint(FEATURES_NAME, DataMode::Dimmed).len(), 1);
let features = icon(FEATURES_NAME);
assert!(features.is_some(), "the feature icon must register");
let Some(features) = features else { return };
let silhouette = features.layer(24.0, 1.0, Layer::Silhouette);
assert_eq!(features.layer(24.0, 1.0, Layer::Run { run: 0, class: Class::Ink }), silhouette, "every feature survives splitting");
assert!(texel(&silhouette, 1, 3).a() > texel(&silhouette, 0, 3).a(), "round caps extend the segment");
assert!(texel(&silhouette, 7, 1).a() > texel(&silhouette, 6, 0).a(), "round joins trim the outer corner");
assert!(texel(&silhouette, 15, 3).a() > texel(&silhouette, 18, 3).a(), "dashes leave gaps");
assert!(texel(&silhouette, 3, 9).a() > 0 && texel(&silhouette, 3, 9).a() < texel(&silhouette, 13, 19).a(), "fill opacity survives splitting");
for (x, y) in [(11, 10), (20, 10), (5, 16), (13, 19)] {
assert!(texel(&silhouette, x, y).a() > 0, "arcs, cubics, rotation and rounded rectangles retain their regions");
}
assert!(texel(&silhouette, 2, 18).a() == 0, "rotation moves the horizontal rectangle");
assert!(texel(&silhouette, 10, 16).a() < texel(&silhouette, 13, 19).a(), "rounded rectangles trim the corner");
// Encoding conversion must serve both split documents and the stroke-scaled original silhouette.
const UTF16_NAME: &str = concat!("zz_w1_", "utf16");
const LATIN1_NAME: &str = concat!("zz_w1_", "latin1");
const MIXED_NAME: &str = concat!("zz_w1_", "mixed");
const NESTED_NAME: &str = concat!("zz_w1_", "nested");
const BROKEN_NAME: &str = concat!("zz_w1_", "broken");
const ENCODING_NAME: &str = concat!("zz_w1_", "encoding");
const GZIP_NAME: &str = concat!("zz_w1_", "gzip");
const LARGE_NAME: &str = concat!("zz_w1_", "large");
const MIXED: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><g><rect width="24" height="24"/><g class="fixed"><circle cx="12" cy="12" r="4"/></g><path d="M2 12 H22"/></g></svg>"#;
const NESTED: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><g class="accent"><g class="fixed"><circle cx="12" cy="12" r="4"/></g></g></svg>"#;
let utf16 = "<?xml version='1.0' encoding='UTF-16'?><svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><title>caf\u{e9}</title><path d='M4 12 H20' fill='none' stroke='black' stroke-width=\"2\"/></svg>";
let utf16: &'static [u8] =
Box::leak([0xff, 0xfe].into_iter().chain(utf16.encode_utf16().flat_map(u16::to_le_bytes)).collect::<Vec<_>>().into_boxed_slice());
const LATIN1: &[u8] = b"<?xml version='1.0' encoding='ISO-8859-1'?><svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><title>caf\xe9</title><path d='M4 12 H20' fill='none' stroke='black' stroke-width=\"2\"/></svg>";
let mut large = b"<?xml version='1.0' encoding='ISO-8859-1'?><svg><title>".to_vec();
large.extend(std::iter::repeat_n(0xe9, (1 << 19) + 1));
large.extend_from_slice(b"</title></svg>");
let icons = Box::leak(
vec![
(UTF16_NAME, utf16),
(LATIN1_NAME, LATIN1),
(MIXED_NAME, MIXED),
(NESTED_NAME, NESTED),
(BROKEN_NAME, b"<svg><g>".as_slice()),
(ENCODING_NAME, b"<svg>\xff</svg>".as_slice()),
(GZIP_NAME, b"\x1f\x8b".as_slice()),
(LARGE_NAME, Box::leak(large.into_boxed_slice())),
]
.into_boxed_slice(),
);
let encoded = Box::leak(Box::new(AppIcons::new("w1-encodings", Some(2.0), icons)));
register_app_icons(encoded);
for refused in [MIXED_NAME, NESTED_NAME, BROKEN_NAME, ENCODING_NAME, GZIP_NAME, LARGE_NAME] {
assert!(icon(refused).is_none(), "an invalid sibling must not enter the name index");
}
for name in [UTF16_NAME, LATIN1_NAME] {
assert_eq!(paint(name, DataMode::Full).len(), 1, "a valid encoded sibling paints through Draw");
assert_eq!(paint(name, DataMode::Dimmed).len(), 1, "stroke scaling accepts the encoded silhouette");
let encoded = icon(name);
assert!(encoded.is_some(), "a valid encoded sibling must register");
let Some(encoded) = encoded else { return };
assert!(encoded.layer(24.0, 1.0, Layer::Silhouette).pixels.iter().any(|pixel| pixel.a() > 0));
}
assert_eq!(mask(UTF16_NAME), mask(LATIN1_NAME), "encodings preserve the same geometry");
}
/// The tints of the textured shapes `name` paints under the tint `color`, first to last.
fn painted(name: &'static str, color: Color32) -> Vec<Color32> {
let Some(svg) = icon(name) else { return Vec::new() };
@@ -132,13 +132,12 @@ impl<'a, T: Value + 'static> SplitButton<'a, T> {
}
fn with_menu(menu: SplitMenu<'a, T>) -> Self {
// P3(widgets-w1): wg.F1
SplitButton {
common: Common::new(),
menu,
arrow_label: None,
icon: None,
icon_only: Default::default(),
icon_only: false,
arrangement: Arrangement::default(),
chosen: None,
}
@@ -148,7 +147,7 @@ impl<'a, T: Value + 'static> SplitButton<'a, T> {
fn spec<'s>(&'s self, label: &'s str, chevron: &'s IconSpec<'s>) -> FaceSpec<'s> {
FaceSpec {
arrangement: self.arrangement,
label,
label: if self.icon_only { "" } else { label },
role: None,
lead: self.icon.as_ref(),
picture: None,
@@ -176,6 +175,10 @@ impl<T: Value + 'static> Component for SplitButton<'_, T> {
type Style = SplitButtonStyle;
type Output = SplitOutput<T>;
fn shows_label(&self) -> bool {
!self.icon_only
}
fn default_variant(env: &crate::runtime::env::Env) -> Option<Variant> {
super::push_default(env)
}
+62 -16
View File
@@ -5,9 +5,9 @@ use super::{
SplitButton, SplitMenu, ToggleButton,
};
use crate::contract::{Bind, BodyCx, Entry, LeastWidth, PopupKind, Props as _, Show as _, ShowContainer as _, Sizing, Trigger, Validity};
use crate::display::{Picture, Shade, Text};
use crate::display::{Picture, PictureSize, Shade, Text};
use crate::layout_components::{Grid, Row, Stack};
use crate::list::ThumbAspect;
use crate::list::{ThumbAspect, ThumbSize};
use crate::menu::{Menu, MenuItem};
use crate::primitives::{AppIcons, HAlign, IconMark, IconSpec, register_app_icons};
use crate::runtime::commands::EditCommands;
@@ -224,9 +224,21 @@ fn icon_button_bar_mark(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
shown.into()
}
/// A pen drawn in the icon ink, with its tip line in the accent ink (`class="accent"`) and a cap dot in its own colour
/// (`class="fixed"`).
const TWO_INK_PEN: &[u8] = br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M5 15 L14 6 L18 10 L9 19 L5 19 Z" fill="black"/><rect class="accent" x="3" y="21" width="18" height="2" fill="black"/><circle class="fixed" cx="18" cy="5" r="2" fill="#d04848"/></svg>"##;
/// Playing and paused controls keep their scrim and white ink legible over a photograph.
#[story(IconButton<'static>, covers = [], drive = Drive::Never, title = "Over a picture")]
fn icon_button_over_picture(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let image = || sample_picture(3, [256, 128]);
let photo = Picture::new("", 3, &image).aspect(ThumbAspect::new(2, 1)).extent(PictureSize::Thumb(ThumbSize::Large)).show(ui);
Row::new()
.show_at(ui, photo.rect, |ui, _| {
IconButton::new(IconId::new("pause")).label("Pause").variant(IconButton::OVER_PICTURE).id_salt("playing").show(ui);
IconButton::new(IconId::new("play")).label("Play").variant(IconButton::OVER_PICTURE).id_salt("paused").show(ui);
})
.into()
}
/// The cap's ink stroke overlaps its fixed colour; a disc and ring distinguish enabled and disabled looks.
const TWO_INK_PEN: &[u8] = br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M5 15 L14 6 L18 10 L9 19 L5 19 Z" fill="black"/><rect class="accent" x="3" y="21" width="18" height="2" fill="black"/><circle class="fixed" cx="18" cy="5" r="2" fill="#d04848"/><path d="M16 5 H20" fill="none" stroke="black"/><g class="on"><circle cx="3" cy="5" r="2" fill="black"/></g><g class="off"><circle cx="8" cy="5" r="2" fill="none" stroke="black"/></g></svg>"##;
/// The pen's name in [`STORY_ICONS`]; the icon-id scan reads only catalog ids written as literals, so the story names
/// its app icon through this constant.
@@ -235,9 +247,8 @@ const TWO_INK_PEN_NAME: &str = "story_two_ink_pen";
/// The stories' own app icon set, under a name no other story or app uses.
static STORY_ICONS: AppIcons = AppIcons::new("ui-widgets-stories", None, &[(TWO_INK_PEN_NAME, TWO_INK_PEN)]);
/// An app icon in two inks and a fixed colour, enabled and then disabled: a disabled button takes the disabled ink in
/// every layer.
#[story(IconButton<'static>, covers = [], drive = Drive::Never, title = "Two-ink icon")]
/// Enabled runs preserve overlapping ink and fixed colour; disabled parts share one silhouette.
#[story(IconButton<'static>, covers = [], drive = Drive::Never, title = "Two-look icon")]
fn icon_button_two_ink(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
// A second registration of the same set is a no-op, so the story registers it on every run.
register_app_icons(&STORY_ICONS);
@@ -321,14 +332,18 @@ fn button_in_side_menu(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
overrides.values.set(ControlPlace::SideMenu);
},
|ui| {
for (name, icon) in [("Home", IconId::new("home")), ("Open", IconId::new("open")), ("Save", IconId::new("save"))] {
Button::new(name)
.icon(icon)
.variant(Variant::GHOST)
.sizing(Sizing::FillWidth)
.align(HAlign::Start)
.selected(name == "Open")
.show(ui);
for enabled in [true, false] {
for (name, icon) in [("Home", IconId::new("home")), ("Open", IconId::new("open")), ("Save", IconId::new("save"))] {
Button::new(name)
.icon(icon)
.variant(Variant::GHOST)
.sizing(Sizing::FillWidth)
.align(HAlign::Start)
.selected(name == "Open")
.enabled(enabled)
.id_salt((name, enabled))
.show(ui);
}
}
},
);
@@ -384,6 +399,30 @@ fn toggle_button_on(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
shown.into()
}
/// The story remembers the last activation's count so the readout survives settling passes.
#[story(ToggleButton<'static>, covers = [], drive = Drive::Custom(double_click_toggle), title = "Double click")]
fn toggle_button_double_click(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let shown = ToggleButton::new("Snap to grid", data.bind("double_click", false)).show(ui);
let clicks = data.value("clicks", 0);
if shown.clicks != 0 {
*clicks = shown.clicks;
}
let words = match *clicks {
0 => "No click",
1 => "Single click",
2 => "Double click",
_ => "Multiple clicks",
};
StoryOutput::from(shown).readout(words)
}
fn double_click_toggle(fixture: &mut Fixture) {
if let Some(toggle) = fixture.by_label("Snap to grid") {
fixture.click(&toggle);
fixture.click(&toggle);
}
}
#[story(ToggleButton<'static>, covers = [Default])]
fn toggle_button(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let size = *data.choice("size", ControlSize::Md, &SIZES);
@@ -484,6 +523,13 @@ fn split_button(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
SplitButton::new("Trace", &entries).icon(IconId::new("image")).arrow_label("Tracing presets").show(ui).into()
}
/// The main part keeps its name as its tooltip while the arrow names its own options.
#[story(SplitButton<'static, u8>, covers = [], drive = Drive::Never, title = "Icon only")]
fn split_button_icon_only(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
let entries = presets();
SplitButton::new("Bullets", &entries).icon(IconId::new("list")).icon_only().arrow_label("Bullets options").show(ui).into()
}
fn open_menu(fixture: &mut Fixture) {
fixture.key(Key::Tab, Modifiers::NONE);
fixture.key(Key::ArrowDown, Modifiers::ALT);