use crate::error::{GuiError, GuiResult};
use crate::theme::{Theme, ThemeMode};
use crate::widgets::Color;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IconRole {
New,
Open,
Save,
Close,
Delete,
Copy,
Paste,
Undo,
Redo,
Refresh,
Search,
Preferences,
Home,
Folder,
File,
Information,
Warning,
Error,
Question,
Help,
Play,
Stop,
NavigateBack,
NavigateForward,
NavigateUp,
Application,
FormatBold,
FormatItalic,
FormatStrikethrough,
FormatCode,
FormatHeading,
ListBulleted,
ListNumbered,
ListTask,
Quote,
InsertLink,
InsertImage,
InsertTable,
InsertRule,
ThemeToggle,
}
impl IconRole {
pub const ALL: [IconRole; 40] = [
IconRole::New,
IconRole::Open,
IconRole::Save,
IconRole::Close,
IconRole::Delete,
IconRole::Copy,
IconRole::Paste,
IconRole::Undo,
IconRole::Redo,
IconRole::Refresh,
IconRole::Search,
IconRole::Preferences,
IconRole::Home,
IconRole::Folder,
IconRole::File,
IconRole::Information,
IconRole::Warning,
IconRole::Error,
IconRole::Question,
IconRole::Help,
IconRole::Play,
IconRole::Stop,
IconRole::NavigateBack,
IconRole::NavigateForward,
IconRole::NavigateUp,
IconRole::Application,
IconRole::FormatBold,
IconRole::FormatItalic,
IconRole::FormatStrikethrough,
IconRole::FormatCode,
IconRole::FormatHeading,
IconRole::ListBulleted,
IconRole::ListNumbered,
IconRole::ListTask,
IconRole::Quote,
IconRole::InsertLink,
IconRole::InsertImage,
IconRole::InsertTable,
IconRole::InsertRule,
IconRole::ThemeToggle,
];
pub fn as_str(self) -> &'static str {
match self {
Self::New => "new",
Self::Open => "open",
Self::Save => "save",
Self::Close => "close",
Self::Delete => "delete",
Self::Copy => "copy",
Self::Paste => "paste",
Self::Undo => "undo",
Self::Redo => "redo",
Self::Refresh => "refresh",
Self::Search => "search",
Self::Preferences => "preferences",
Self::Home => "home",
Self::Folder => "folder",
Self::File => "file",
Self::Information => "information",
Self::Warning => "warning",
Self::Error => "error",
Self::Question => "question",
Self::Help => "help",
Self::Play => "play",
Self::Stop => "stop",
Self::NavigateBack => "navigate-back",
Self::NavigateForward => "navigate-forward",
Self::NavigateUp => "navigate-up",
Self::Application => "application",
Self::FormatBold => "format-bold",
Self::FormatItalic => "format-italic",
Self::FormatStrikethrough => "format-strikethrough",
Self::FormatCode => "format-code",
Self::FormatHeading => "format-heading",
Self::ListBulleted => "list-bulleted",
Self::ListNumbered => "list-numbered",
Self::ListTask => "list-task",
Self::Quote => "quote",
Self::InsertLink => "insert-link",
Self::InsertImage => "insert-image",
Self::InsertTable => "insert-table",
Self::InsertRule => "insert-rule",
Self::ThemeToggle => "theme-toggle",
}
}
pub fn xdg_name(self) -> &'static str {
match self {
Self::New => "document-new",
Self::Open => "document-open",
Self::Save => "document-save",
Self::Close => "window-close",
Self::Delete => "edit-delete",
Self::Copy => "edit-copy",
Self::Paste => "edit-paste",
Self::Undo => "edit-undo",
Self::Redo => "edit-redo",
Self::Refresh => "view-refresh",
Self::Search => "edit-find",
Self::Preferences => "preferences-system",
Self::Home => "go-home",
Self::Folder => "folder",
Self::File => "text-x-generic",
Self::Information => "dialog-information",
Self::Warning => "dialog-warning",
Self::Error => "dialog-error",
Self::Question => "dialog-question",
Self::Help => "help-browser",
Self::Play => "media-playback-start",
Self::Stop => "media-playback-stop",
Self::NavigateBack => "go-previous",
Self::NavigateForward => "go-next",
Self::NavigateUp => "go-up",
Self::Application => "application-x-executable",
Self::FormatBold => "format-text-bold",
Self::FormatItalic => "format-text-italic",
Self::FormatStrikethrough => "format-text-strikethrough",
Self::FormatCode => "format-text-code",
Self::FormatHeading => "format-text-heading",
Self::ListBulleted => "format-list-unordered",
Self::ListNumbered => "format-list-ordered",
Self::ListTask => "format-list-checkbox",
Self::Quote => "format-text-blockquote",
Self::InsertLink => "insert-link",
Self::InsertImage => "insert-image",
Self::InsertTable => "insert-table",
Self::InsertRule => "insert-horizontal-rule",
Self::ThemeToggle => "night-light",
}
}
pub fn sf_symbol_name(self) -> Option<&'static str> {
match self {
Self::New => Some("doc.badge.plus"),
Self::Open => Some("folder"),
Self::Save => Some("square.and.arrow.down"),
Self::Close => Some("xmark"),
Self::Delete => Some("trash"),
Self::Copy => Some("doc.on.doc"),
Self::Paste => Some("doc.on.clipboard"),
Self::Undo => Some("arrow.uturn.backward"),
Self::Redo => Some("arrow.uturn.forward"),
Self::Refresh => Some("arrow.clockwise"),
Self::Search => Some("magnifyingglass"),
Self::Preferences => Some("gearshape"),
Self::Home => Some("house"),
Self::Folder => Some("folder"),
Self::File => Some("doc"),
Self::Information => Some("info.circle"),
Self::Warning => Some("exclamationmark.triangle"),
Self::Error => Some("xmark.octagon"),
Self::Question => Some("questionmark.circle"),
Self::Help => Some("questionmark.circle"),
Self::Play => Some("play.fill"),
Self::Stop => Some("stop.fill"),
Self::NavigateBack => Some("chevron.backward"),
Self::NavigateForward => Some("chevron.forward"),
Self::NavigateUp => Some("arrow.up"),
Self::Application => Some("app"),
Self::FormatBold => Some("bold"),
Self::FormatItalic => Some("italic"),
Self::FormatStrikethrough => Some("strikethrough"),
Self::FormatCode => Some("chevron.left.forwardslash.chevron.right"),
Self::FormatHeading => Some("textformat.size"),
Self::ListBulleted => Some("list.bullet"),
Self::ListNumbered => Some("list.number"),
Self::ListTask => Some("checklist"),
Self::Quote => Some("quote.opening"),
Self::InsertLink => Some("link"),
Self::InsertImage => Some("photo"),
Self::InsertTable => Some("tablecells"),
Self::InsertRule => Some("minus"),
Self::ThemeToggle => Some("circle.lefthalf.filled"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IconSize {
Small,
Large,
}
impl IconSize {
pub const ALL: [IconSize; 2] = [IconSize::Small, IconSize::Large];
pub fn pixels(self) -> u32 {
match self {
Self::Small => 16,
Self::Large => 32,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Small => "small",
Self::Large => "large",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IconSource {
Portable,
Native,
}
impl IconSource {
pub fn as_str(self) -> &'static str {
match self {
Self::Portable => "portable",
Self::Native => "native",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ArtCapabilities {
pub native_icons: bool,
pub dpi_variants: bool,
pub theme_aware: bool,
}
impl ArtCapabilities {
pub const fn none() -> Self {
Self {
native_icons: false,
dpi_variants: false,
theme_aware: false,
}
}
pub const fn native(dpi_variants: bool, theme_aware: bool) -> Self {
Self {
native_icons: true,
dpi_variants,
theme_aware,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StockIcon {
pub role: IconRole,
pub size: IconSize,
pub mode: ThemeMode,
pub scale: u32,
pub source: IconSource,
pub width: u32,
pub height: u32,
pub pixels: Vec<u8>,
}
impl StockIcon {
pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
if x >= self.width || y >= self.height {
return None;
}
let offset = ((y * self.width + x) * 4) as usize;
Some([
self.pixels[offset],
self.pixels[offset + 1],
self.pixels[offset + 2],
self.pixels[offset + 3],
])
}
pub fn has_visible_pixels(&self) -> bool {
self.pixels.as_chunks::<4>().0.iter().any(|px| px[3] != 0)
}
pub fn to_bmp(&self, background: Color) -> Vec<u8> {
let width = self.width as usize;
let height = self.height as usize;
let row_stride = (width * 3 + 3) & !3;
let pixel_bytes = row_stride * height;
let mut out = Vec::with_capacity(54 + pixel_bytes);
let file_size = (54 + pixel_bytes) as u32;
out.extend_from_slice(b"BM");
out.extend_from_slice(&file_size.to_le_bytes());
out.extend_from_slice(&[0, 0, 0, 0]); out.extend_from_slice(&54u32.to_le_bytes());
out.extend_from_slice(&40u32.to_le_bytes()); out.extend_from_slice(&(width as i32).to_le_bytes());
out.extend_from_slice(&(height as i32).to_le_bytes());
out.extend_from_slice(&1u16.to_le_bytes()); out.extend_from_slice(&24u16.to_le_bytes()); out.extend_from_slice(&0u32.to_le_bytes()); out.extend_from_slice(&(pixel_bytes as u32).to_le_bytes());
out.extend_from_slice(&2835i32.to_le_bytes()); out.extend_from_slice(&2835i32.to_le_bytes());
out.extend_from_slice(&0u32.to_le_bytes()); out.extend_from_slice(&0u32.to_le_bytes());
for y in (0..height).rev() {
let row_start = out.len();
for x in 0..width {
let [r, g, b, a] = self.pixel(x as u32, y as u32).expect("in bounds");
let alpha = a as u32;
let blend = |channel: u8, bg: u8| -> u8 {
(((channel as u32 * alpha) + (bg as u32 * (255 - alpha)) + 127) / 255) as u8
};
out.push(blend(b, background.b));
out.push(blend(g, background.g));
out.push(blend(r, background.r));
}
out.resize(row_start + row_stride, 0);
}
out
}
}
pub fn unsupported_native_icon(role: IconRole, size: IconSize, detail: &str) -> GuiError {
GuiError::UnsupportedCapability(format!(
"native stock icon ({} / {}): {}",
role.as_str(),
size.as_str(),
detail
))
}
pub fn resample_rgba(
source: &[u8],
source_width: u32,
source_height: u32,
target_width: u32,
target_height: u32,
) -> GuiResult<(u32, u32, Vec<u8>)> {
if source_width == 0
|| source_height == 0
|| target_width == 0
|| target_height == 0
|| source.len() != (source_width * source_height * 4) as usize
{
return Err(GuiError::Backend(
"icon resample received a mismatched raster".to_owned(),
));
}
let mut out = vec![0u8; (target_width * target_height * 4) as usize];
for ty in 0..target_height {
let y0 = (ty * source_height) / target_height;
let y1 = (((ty + 1) * source_height) / target_height)
.max(y0 + 1)
.min(source_height);
for tx in 0..target_width {
let x0 = (tx * source_width) / target_width;
let x1 = (((tx + 1) * source_width) / target_width)
.max(x0 + 1)
.min(source_width);
let mut sums = [0.0f32; 4];
let mut count = 0.0f32;
for sy in y0..y1 {
for sx in x0..x1 {
let offset = ((sy * source_width + sx) * 4) as usize;
let alpha = source[offset + 3] as f32 / 255.0;
sums[0] += source[offset] as f32 * alpha;
sums[1] += source[offset + 1] as f32 * alpha;
sums[2] += source[offset + 2] as f32 * alpha;
sums[3] += alpha;
count += 1.0;
}
}
let offset = ((ty * target_width + tx) * 4) as usize;
let average_alpha = sums[3] / count;
if sums[3] > 0.0 {
out[offset] = (sums[0] / sums[3] + 0.5) as u8;
out[offset + 1] = (sums[1] / sums[3] + 0.5) as u8;
out[offset + 2] = (sums[2] / sums[3] + 0.5) as u8;
}
out[offset + 3] = (average_alpha * 255.0 + 0.5) as u8;
}
}
Ok((target_width, target_height, out))
}
pub fn resample_rgba_centered(
source: &[u8],
source_width: u32,
source_height: u32,
edge: u32,
) -> GuiResult<(u32, u32, Vec<u8>)> {
if source_width == 0 || source_height == 0 || edge == 0 {
return Err(GuiError::Backend(
"icon resample received an empty raster".to_owned(),
));
}
if source_width == edge && source_height == edge {
if source.len() != (edge * edge * 4) as usize {
return Err(GuiError::Backend(
"icon resample received a mismatched raster".to_owned(),
));
}
return Ok((edge, edge, source.to_vec()));
}
let scale = (edge as f32 / source_width as f32).min(edge as f32 / source_height as f32);
let target_width = ((source_width as f32 * scale).round() as u32).clamp(1, edge);
let target_height = ((source_height as f32 * scale).round() as u32).clamp(1, edge);
let (_, _, scaled) = resample_rgba(
source,
source_width,
source_height,
target_width,
target_height,
)?;
let mut out = vec![0u8; (edge * edge * 4) as usize];
let x_offset = (edge - target_width) / 2;
let y_offset = (edge - target_height) / 2;
for y in 0..target_height {
for x in 0..target_width {
let source_offset = ((y * target_width + x) * 4) as usize;
let target_offset = (((y + y_offset) * edge + x + x_offset) * 4) as usize;
out[target_offset..target_offset + 4]
.copy_from_slice(&scaled[source_offset..source_offset + 4]);
}
}
Ok((edge, edge, out))
}
pub fn render_stock_icon(role: IconRole, size: IconSize, mode: ThemeMode, scale: u32) -> StockIcon {
let scale = scale.clamp(1, 4);
render_stock_icon_at_extent(role, size, mode, scale, size.pixels() * scale)
}
pub fn stock_icon_edge_for_scale(size: IconSize, scale: f64) -> u32 {
let base = size.pixels();
let scale = if scale.is_finite() { scale } else { 1.0 };
((f64::from(base) * scale).round() as u32).clamp(base, base * 4)
}
pub fn render_stock_icon_for_scale(
role: IconRole,
size: IconSize,
mode: ThemeMode,
scale: f64,
) -> StockIcon {
let extent = stock_icon_edge_for_scale(size, scale);
let whole = ((f64::from(extent) / f64::from(size.pixels())).round() as u32).clamp(1, 4);
render_stock_icon_at_extent(role, size, mode, whole, extent)
}
fn render_stock_icon_at_extent(
role: IconRole,
size: IconSize,
mode: ThemeMode,
scale: u32,
extent: u32,
) -> StockIcon {
let pixel_scale = extent as f32 / size.pixels() as f32;
let theme = Theme::for_mode(mode);
let shapes = glyph(role);
let mut pixels = vec![0u8; (extent * extent * 4) as usize];
let samples = (SUPERSAMPLE * SUPERSAMPLE) as f32;
let mut top_counts = vec![0u32; shapes.len()];
for py in 0..extent {
for px in 0..extent {
top_counts.iter_mut().for_each(|count| *count = 0);
for sy in 0..SUPERSAMPLE {
for sx in 0..SUPERSAMPLE {
let logical_x =
(px as f32 + (sx as f32 + 0.5) / SUPERSAMPLE as f32) / pixel_scale;
let logical_y =
(py as f32 + (sy as f32 + 0.5) / SUPERSAMPLE as f32) / pixel_scale;
let mut top = None;
for (index, (shape, _)) in shapes.iter().enumerate() {
if covers(shape, logical_x, logical_y) {
top = Some(index);
}
}
if let Some(index) = top {
top_counts[index] += 1;
}
}
}
let mut out = [0.0f32; 4];
for (index, (_, ink)) in shapes.iter().enumerate() {
let coverage = top_counts[index] as f32 / samples;
if coverage > 0.0 {
let color = ink_color(*ink, &theme);
out = blend(out, color, coverage);
}
}
let offset = ((py * extent + px) * 4) as usize;
for (channel, value) in out.iter().enumerate() {
pixels[offset + channel] = (value * 255.0 + 0.5) as u8;
}
}
}
StockIcon {
role,
size,
mode,
scale,
source: IconSource::Portable,
width: extent,
height: extent,
pixels,
}
}
const SUPERSAMPLE: u32 = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Ink {
Text,
Accent,
Warning,
Error,
Surface,
}
fn ink_color(ink: Ink, theme: &Theme) -> Color {
match ink {
Ink::Text => theme.colors.text,
Ink::Accent => theme.colors.accent,
Ink::Warning => theme.colors.warning,
Ink::Error => theme.colors.error,
Ink::Surface => theme.colors.surface,
}
}
#[derive(Debug, Clone, PartialEq)]
enum Shape {
Rect {
x: f32,
y: f32,
w: f32,
h: f32,
},
RoundRect {
x: f32,
y: f32,
w: f32,
h: f32,
r: f32,
},
Frame {
x: f32,
y: f32,
w: f32,
h: f32,
t: f32,
},
Circle {
cx: f32,
cy: f32,
r: f32,
},
Ring {
cx: f32,
cy: f32,
r: f32,
t: f32,
},
RingSeg {
cx: f32,
cy: f32,
r: f32,
t: f32,
a0: f32,
a1: f32,
},
Segment {
x0: f32,
y0: f32,
x1: f32,
y1: f32,
t: f32,
},
Polygon(Vec<(f32, f32)>),
}
fn covers(shape: &Shape, px: f32, py: f32) -> bool {
match shape {
Shape::Rect { x, y, w, h } => px >= *x && px <= x + w && py >= *y && py <= y + h,
Shape::RoundRect { x, y, w, h, r } => {
let inner_x = px.clamp(x + r, x + w - r);
let inner_y = py.clamp(y + r, y + h - r);
let dx = px - inner_x;
let dy = py - inner_y;
dx * dx + dy * dy <= r * r
}
Shape::Frame { x, y, w, h, t } => {
px >= *x
&& px <= x + w
&& py >= *y
&& py <= y + h
&& !(px >= x + t && px <= x + w - t && py >= y + t && py <= y + h - t)
}
Shape::Circle { cx, cy, r } => {
let dx = px - cx;
let dy = py - cy;
dx * dx + dy * dy <= r * r
}
Shape::Ring { cx, cy, r, t } => {
let dx = px - cx;
let dy = py - cy;
let distance = (dx * dx + dy * dy).sqrt();
(distance - r).abs() <= t / 2.0
}
Shape::RingSeg {
cx,
cy,
r,
t,
a0,
a1,
} => {
let dx = px - cx;
let dy = py - cy;
let distance = (dx * dx + dy * dy).sqrt();
if (distance - r).abs() > t / 2.0 {
return false;
}
let mut angle = dy.atan2(dx).to_degrees();
if angle < 0.0 {
angle += 360.0;
}
let mut end = *a1;
if end <= *a0 {
end += 360.0;
}
if angle < *a0 {
angle += 360.0;
}
angle >= *a0 && angle <= end
}
Shape::Segment { x0, y0, x1, y1, t } => {
let vx = x1 - x0;
let vy = y1 - y0;
let length_sq = vx * vx + vy * vy;
let projection = if length_sq == 0.0 {
0.0
} else {
(((px - x0) * vx + (py - y0) * vy) / length_sq).clamp(0.0, 1.0)
};
let dx = px - (x0 + projection * vx);
let dy = py - (y0 + projection * vy);
dx * dx + dy * dy <= (t / 2.0) * (t / 2.0)
}
Shape::Polygon(points) => {
let mut inside = false;
let mut j = points.len() - 1;
for i in 0..points.len() {
let (xi, yi) = points[i];
let (xj, yj) = points[j];
if (yi > py) != (yj > py) && px < (xj - xi) * (py - yi) / (yj - yi) + xi {
inside = !inside;
}
j = i;
}
inside
}
}
}
fn blend(dst: [f32; 4], src: Color, coverage: f32) -> [f32; 4] {
let src_rgb = [
src.r as f32 / 255.0,
src.g as f32 / 255.0,
src.b as f32 / 255.0,
];
let out_alpha = coverage + dst[3] * (1.0 - coverage);
if out_alpha <= 0.0 {
return [0.0, 0.0, 0.0, 0.0];
}
let mut out = [0.0f32; 4];
for channel in 0..3 {
out[channel] =
(src_rgb[channel] * coverage + dst[channel] * dst[3] * (1.0 - coverage)) / out_alpha;
}
out[3] = out_alpha;
out
}
fn glyph(role: IconRole) -> Vec<(Shape, Ink)> {
use Ink::{Accent, Error, Surface, Text, Warning};
let seg = |x0: f32, y0: f32, x1: f32, y1: f32, t: f32| Shape::Segment { x0, y0, x1, y1, t };
let rect = |x: f32, y: f32, w: f32, h: f32| Shape::Rect { x, y, w, h };
let frame = |x: f32, y: f32, w: f32, h: f32, t: f32| Shape::Frame { x, y, w, h, t };
let circle = |cx: f32, cy: f32, r: f32| Shape::Circle { cx, cy, r };
let round = |x: f32, y: f32, w: f32, h: f32, r: f32| Shape::RoundRect { x, y, w, h, r };
match role {
IconRole::New => vec![
(frame(3.5, 1.5, 8.0, 13.0, 1.4), Text),
(seg(10.5, 9.5, 10.5, 15.5, 1.6), Accent),
(seg(7.5, 12.5, 13.5, 12.5, 1.6), Accent),
],
IconRole::Open => vec![
(
Shape::Polygon(vec![
(1.5, 3.5),
(6.2, 3.5),
(7.4, 5.6),
(14.5, 5.6),
(14.5, 13.5),
(1.5, 13.5),
]),
Accent,
),
(
Shape::Polygon(vec![(1.5, 7.0), (15.2, 7.0), (12.8, 14.0), (1.5, 14.0)]),
Text,
),
],
IconRole::Save => vec![
(round(2.5, 1.5, 11.0, 13.0, 1.4), Accent),
(rect(5.5, 1.5, 5.0, 4.0), Surface),
(frame(5.0, 9.0, 6.0, 5.5, 1.2), Surface),
],
IconRole::Close => vec![
(seg(3.5, 3.5, 12.5, 12.5, 1.8), Error),
(seg(12.5, 3.5, 3.5, 12.5, 1.8), Error),
],
IconRole::Delete => vec![
(seg(3.0, 4.2, 13.0, 4.2, 1.5), Error),
(seg(6.4, 2.4, 9.6, 2.4, 1.5), Error),
(
Shape::Polygon(vec![(4.4, 5.2), (11.6, 5.2), (10.6, 14.0), (5.4, 14.0)]),
Error,
),
(seg(6.9, 7.0, 6.9, 12.2, 1.1), Surface),
(seg(9.1, 7.0, 9.1, 12.2, 1.1), Surface),
],
IconRole::Copy => vec![
(frame(2.2, 2.2, 7.6, 7.6, 1.4), Text),
(frame(6.2, 6.2, 7.6, 7.6, 1.4), Accent),
],
IconRole::Paste => vec![
(frame(4.0, 2.8, 8.0, 11.2, 1.4), Text),
(rect(6.2, 1.4, 3.6, 2.6), Accent),
],
IconRole::Undo => vec![
(seg(12.5, 4.5, 12.5, 8.5, 1.6), Accent),
(seg(12.5, 8.5, 5.5, 8.5, 1.6), Accent),
(
Shape::Polygon(vec![(2.0, 8.5), (6.5, 6.3), (6.5, 10.7)]),
Accent,
),
],
IconRole::Redo => vec![
(seg(3.5, 4.5, 3.5, 8.5, 1.6), Accent),
(seg(3.5, 8.5, 10.5, 8.5, 1.6), Accent),
(
Shape::Polygon(vec![(14.0, 8.5), (9.5, 6.3), (9.5, 10.7)]),
Accent,
),
],
IconRole::Refresh => vec![
(
Shape::RingSeg {
cx: 8.0,
cy: 8.0,
r: 5.0,
t: 1.6,
a0: 40.0,
a1: 330.0,
},
Accent,
),
(
Shape::Polygon(vec![(10.6, 11.0), (14.2, 9.4), (13.0, 13.4)]),
Accent,
),
],
IconRole::Search => vec![
(
Shape::Ring {
cx: 6.6,
cy: 6.6,
r: 4.0,
t: 1.6,
},
Accent,
),
(seg(9.6, 9.6, 14.0, 14.0, 2.0), Text),
],
IconRole::Preferences => {
let mut shapes = vec![
(circle(8.0, 8.0, 4.6), Accent),
(circle(8.0, 8.0, 1.9), Surface),
];
for step in 0..6 {
let angle = (30.0 + 60.0 * step as f32).to_radians();
let (sin, cos) = angle.sin_cos();
shapes.push((
seg(
8.0 + 4.6 * cos,
8.0 + 4.6 * sin,
8.0 + 6.6 * cos,
8.0 + 6.6 * sin,
2.0,
),
Accent,
));
}
shapes
}
IconRole::Home => vec![
(
Shape::Polygon(vec![(8.0, 1.8), (14.6, 7.6), (1.4, 7.6)]),
Accent,
),
(rect(3.6, 7.6, 8.8, 6.8), Text),
(rect(6.6, 10.4, 2.8, 4.0), Surface),
],
IconRole::Folder => vec![(
Shape::Polygon(vec![
(1.5, 3.6),
(6.2, 3.6),
(7.4, 5.7),
(14.5, 5.7),
(14.5, 13.6),
(1.5, 13.6),
]),
Accent,
)],
IconRole::File => vec![
(frame(3.6, 1.5, 8.8, 13.0, 1.4), Text),
(
Shape::Polygon(vec![(9.0, 1.5), (12.4, 5.0), (9.0, 5.0)]),
Text,
),
],
IconRole::Information => vec![
(circle(8.0, 8.0, 6.0), Accent),
(rect(7.1, 7.0, 1.8, 4.6), Surface),
(rect(7.1, 4.4, 1.8, 1.6), Surface),
],
IconRole::Warning => vec![
(
Shape::Polygon(vec![(8.0, 1.4), (15.0, 14.0), (1.0, 14.0)]),
Warning,
),
(rect(7.2, 5.8, 1.6, 4.6), Surface),
(rect(7.2, 11.4, 1.6, 1.6), Surface),
],
IconRole::Error => vec![
(circle(8.0, 8.0, 6.0), Error),
(seg(5.6, 5.6, 10.4, 10.4, 1.6), Surface),
(seg(10.4, 5.6, 5.6, 10.4, 1.6), Surface),
],
IconRole::Question => vec![
(circle(8.0, 8.0, 6.0), Accent),
(
Shape::RingSeg {
cx: 8.0,
cy: 6.8,
r: 2.4,
t: 1.6,
a0: 180.0,
a1: 350.0,
},
Surface,
),
(seg(8.0, 8.9, 8.0, 10.8, 1.6), Surface),
(circle(8.0, 12.6, 0.9), Surface),
],
IconRole::Help => {
let mut shapes = vec![
(
Shape::Ring {
cx: 8.0,
cy: 8.0,
r: 5.2,
t: 1.8,
},
Accent,
),
(circle(8.0, 8.0, 2.6), Surface),
(
Shape::Ring {
cx: 8.0,
cy: 8.0,
r: 2.0,
t: 1.4,
},
Accent,
),
];
for step in 0..4 {
let angle = (45.0 + 90.0 * step as f32).to_radians();
let (sin, cos) = angle.sin_cos();
shapes.push((
seg(
8.0 + 2.6 * cos,
8.0 + 2.6 * sin,
8.0 + 4.8 * cos,
8.0 + 4.8 * sin,
1.6,
),
Accent,
));
}
shapes
}
IconRole::Play => vec![(
Shape::Polygon(vec![(4.6, 2.6), (13.4, 8.0), (4.6, 13.4)]),
Accent,
)],
IconRole::Stop => vec![(round(3.4, 3.4, 9.2, 9.2, 1.2), Error)],
IconRole::NavigateBack => vec![
(seg(13.6, 8.0, 4.0, 8.0, 1.8), Accent),
(
Shape::Polygon(vec![(7.6, 4.4), (7.6, 11.6), (2.4, 8.0)]),
Accent,
),
],
IconRole::NavigateForward => vec![
(seg(2.4, 8.0, 12.0, 8.0, 1.8), Accent),
(
Shape::Polygon(vec![(8.4, 4.4), (8.4, 11.6), (13.6, 8.0)]),
Accent,
),
],
IconRole::NavigateUp => vec![
(seg(8.0, 13.6, 8.0, 4.0, 1.8), Accent),
(
Shape::Polygon(vec![(4.4, 7.6), (11.6, 7.6), (8.0, 2.4)]),
Accent,
),
],
IconRole::Application => vec![
(round(2.0, 2.6, 12.0, 10.8, 1.4), Accent),
(seg(2.0, 5.4, 14.0, 5.4, 0.9), Surface),
(circle(4.0, 4.0, 0.7), Surface),
(circle(6.0, 4.0, 0.7), Surface),
],
IconRole::FormatBold => vec![
(round(3.0, 2.0, 3.5, 12.0, 1.0), Text),
(round(3.5, 2.0, 8.0, 6.4, 2.2), Text),
(round(5.8, 3.8, 4.0, 2.8, 1.0), Surface),
(round(3.5, 7.6, 9.2, 6.4, 2.2), Text),
(round(5.8, 9.4, 5.0, 2.8, 1.0), Surface),
],
IconRole::FormatItalic => vec![
(seg(5.5, 2.5, 12.0, 2.5, 2.0), Text),
(seg(4.0, 13.5, 10.5, 13.5, 2.0), Text),
(seg(9.5, 2.5, 6.5, 13.5, 2.2), Text),
],
IconRole::FormatStrikethrough => vec![
(seg(11.0, 3.5, 6.5, 3.5, 1.8), Text),
(seg(5.5, 4.5, 5.5, 7.0, 1.8), Text),
(seg(5.5, 7.0, 10.5, 9.0, 1.8), Text),
(seg(10.5, 9.0, 10.5, 11.5, 1.8), Text),
(seg(10.5, 12.5, 5.0, 12.5, 1.8), Text),
(seg(2.5, 8.0, 13.5, 8.0, 2.0), Accent),
],
IconRole::FormatCode => vec![
(seg(5.5, 4.5, 2.5, 8.0, 1.6), Text),
(seg(2.5, 8.0, 5.5, 11.5, 1.6), Text),
(seg(9.0, 3.5, 7.0, 12.5, 1.6), Accent),
(seg(10.5, 4.5, 13.5, 8.0, 1.6), Text),
(seg(13.5, 8.0, 10.5, 11.5, 1.6), Text),
],
IconRole::FormatHeading => vec![
(seg(2.8, 3.0, 2.8, 13.0, 1.8), Text),
(seg(8.2, 3.0, 8.2, 13.0, 1.8), Text),
(seg(2.8, 8.0, 8.2, 8.0, 1.8), Text),
(seg(11.2, 6.8, 12.8, 5.2, 1.4), Accent),
(seg(12.8, 5.2, 12.8, 13.0, 1.6), Accent),
(seg(11.2, 13.0, 14.4, 13.0, 1.4), Accent),
],
IconRole::ListBulleted => vec![
(circle(3.5, 4.2, 1.3), Accent),
(seg(6.8, 4.2, 14.0, 4.2, 1.6), Text),
(circle(3.5, 8.0, 1.3), Accent),
(seg(6.8, 8.0, 14.0, 8.0, 1.6), Text),
(circle(3.5, 11.8, 1.3), Accent),
(seg(6.8, 11.8, 14.0, 11.8, 1.6), Text),
],
IconRole::ListNumbered => vec![
(seg(2.4, 4.2, 3.6, 3.0, 1.2), Accent),
(seg(3.6, 3.0, 3.6, 6.8, 1.4), Accent),
(seg(6.8, 4.8, 14.0, 4.8, 1.6), Text),
(seg(2.0, 9.6, 4.8, 9.6, 1.2), Accent),
(seg(4.8, 9.6, 2.0, 12.8, 1.2), Accent),
(seg(2.0, 12.8, 5.0, 12.8, 1.2), Accent),
(seg(6.8, 11.2, 14.0, 11.2, 1.6), Text),
],
IconRole::ListTask => vec![
(frame(2.0, 2.5, 5.0, 5.0, 1.1), Accent),
(seg(2.8, 5.0, 4.0, 6.2, 1.1), Accent),
(seg(4.0, 6.2, 6.5, 3.2, 1.1), Accent),
(seg(8.5, 5.0, 14.0, 5.0, 1.6), Text),
(frame(2.0, 9.5, 5.0, 5.0, 1.1), Accent),
(seg(8.5, 12.0, 14.0, 12.0, 1.6), Text),
],
IconRole::Quote => vec![
(rect(2.2, 2.5, 2.0, 11.0), Accent),
(seg(6.0, 4.5, 13.8, 4.5, 1.5), Text),
(seg(6.0, 8.0, 13.8, 8.0, 1.5), Text),
(seg(6.0, 11.5, 11.0, 11.5, 1.5), Text),
],
IconRole::InsertLink => vec![
(seg(3.5, 12.5, 6.5, 9.5, 1.8), Accent),
(seg(3.5, 12.5, 6.5, 14.5, 1.6), Accent),
(seg(6.5, 14.5, 8.5, 12.5, 1.6), Accent),
(seg(9.5, 6.5, 12.5, 3.5, 1.8), Accent),
(seg(9.5, 3.5, 12.5, 3.5, 1.6), Accent),
(seg(7.5, 5.5, 9.5, 3.5, 1.6), Accent),
(seg(5.5, 10.5, 10.5, 5.5, 2.0), Text),
],
IconRole::InsertImage => vec![
(frame(2.0, 2.5, 12.0, 11.0, 1.4), Text),
(circle(5.2, 5.6, 1.3), Accent),
(
Shape::Polygon(vec![
(3.4, 12.0),
(7.0, 7.6),
(9.8, 10.8),
(11.8, 8.8),
(12.6, 12.0),
]),
Accent,
),
],
IconRole::InsertTable => vec![
(frame(2.0, 2.5, 12.0, 11.0, 1.4), Text),
(rect(2.0, 2.5, 12.0, 3.5), Accent),
(seg(2.0, 6.0, 14.0, 6.0, 1.4), Text),
(seg(2.0, 9.5, 14.0, 9.5, 1.2), Text),
(seg(8.0, 2.5, 8.0, 13.5, 1.4), Text),
(seg(8.0, 2.5, 8.0, 6.0, 1.2), Surface),
],
IconRole::InsertRule => vec![
(seg(2.0, 8.0, 14.0, 8.0, 2.0), Accent),
(seg(4.0, 4.0, 12.0, 4.0, 1.0), Text),
(seg(4.0, 12.0, 12.0, 12.0, 1.0), Text),
],
IconRole::ThemeToggle => vec![
(
Shape::Ring {
cx: 8.0,
cy: 8.0,
r: 5.2,
t: 1.6,
},
Accent,
),
(seg(8.0, 2.8, 8.0, 13.2, 1.4), Accent),
(
Shape::Polygon(vec![
(8.0, 2.8),
(6.0, 3.2),
(4.4, 4.6),
(3.3, 6.2),
(3.0, 8.0),
(3.3, 9.8),
(4.4, 11.4),
(6.0, 12.8),
(8.0, 13.2),
]),
Accent,
),
],
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fractional_scale_icons_render_at_the_scaled_edge() {
let icon =
render_stock_icon_for_scale(IconRole::Save, IconSize::Small, ThemeMode::Light, 1.5);
assert_eq!((icon.width, icon.height), (24, 24));
assert_eq!(icon.pixels.len(), 24 * 24 * 4);
assert!(icon.has_visible_pixels());
assert_eq!(stock_icon_edge_for_scale(IconSize::Small, 1.25), 20);
assert_eq!(
stock_icon_edge_for_scale(IconSize::Small, 0.5),
16,
"never below 1x"
);
assert_eq!(
stock_icon_edge_for_scale(IconSize::Small, 9.0),
64,
"never above 4x"
);
assert_eq!(stock_icon_edge_for_scale(IconSize::Small, f64::NAN), 16);
for whole in 1..=4u32 {
let integer =
render_stock_icon(IconRole::Save, IconSize::Small, ThemeMode::Dark, whole);
let fractional = render_stock_icon_for_scale(
IconRole::Save,
IconSize::Small,
ThemeMode::Dark,
f64::from(whole),
);
assert_eq!(integer, fractional, "scale {whole}");
}
}
fn has_color_near(icon: &StockIcon, color: Color, tolerance: i32) -> bool {
icon.pixels.as_chunks::<4>().0.iter().any(|px| {
px[3] > 200
&& (px[0] as i32 - color.r as i32).abs() <= tolerance
&& (px[1] as i32 - color.g as i32).abs() <= tolerance
&& (px[2] as i32 - color.b as i32).abs() <= tolerance
})
}
fn alpha_channel(icon: &StockIcon) -> Vec<u8> {
icon.pixels
.as_chunks::<4>()
.0
.iter()
.map(|px| px[3])
.collect()
}
#[test]
fn every_role_resolves_every_size_and_mode() {
assert_eq!(IconRole::ALL.len(), 40);
for role in IconRole::ALL {
for size in IconSize::ALL {
for mode in [ThemeMode::Light, ThemeMode::Dark] {
let icon = render_stock_icon(role, size, mode, 1);
assert_eq!(icon.width, size.pixels(), "{role:?}/{size:?}");
assert_eq!(icon.height, size.pixels(), "{role:?}/{size:?}");
assert_eq!(icon.pixels.len(), (icon.width * icon.height * 4) as usize);
assert!(
icon.has_visible_pixels(),
"{role:?}/{size:?}/{mode:?} rendered empty"
);
}
}
}
}
#[test]
fn dpi_scale_multiplies_the_raster_and_is_deterministic() {
let first = render_stock_icon(IconRole::Warning, IconSize::Small, ThemeMode::Light, 2);
let second = render_stock_icon(IconRole::Warning, IconSize::Small, ThemeMode::Light, 2);
assert_eq!(first.width, 32);
assert_eq!(first.height, 32);
assert_eq!(first, second, "renderer must be deterministic");
let large = render_stock_icon(IconRole::Warning, IconSize::Large, ThemeMode::Light, 1);
assert_eq!(large.width, 32);
assert_ne!(
first, large,
"Small@2x and Large@1x are different DPI variants even at equal raster size"
);
let clamped = render_stock_icon(IconRole::Warning, IconSize::Small, ThemeMode::Light, 0);
assert_eq!(clamped.scale, 1);
assert_eq!(clamped.width, 16);
let capped = render_stock_icon(IconRole::Warning, IconSize::Small, ThemeMode::Light, 9);
assert_eq!(capped.scale, 4);
assert_eq!(capped.width, 64);
}
#[test]
fn theme_mode_changes_ink_but_not_geometry() {
let light = render_stock_icon(IconRole::Error, IconSize::Large, ThemeMode::Light, 1);
let dark = render_stock_icon(IconRole::Error, IconSize::Large, ThemeMode::Dark, 1);
assert_eq!(light.width, dark.width);
assert_eq!(
alpha_channel(&light),
alpha_channel(&dark),
"theme must not change glyph coverage"
);
assert_ne!(light.pixels, dark.pixels, "theme must change the palette");
let theme_light = Theme::light();
let theme_dark = Theme::dark();
assert!(has_color_near(&light, theme_light.colors.error, 8));
assert!(has_color_near(&dark, theme_dark.colors.error, 8));
}
#[test]
fn severity_and_action_roles_use_their_theme_tokens() {
let theme = Theme::light();
let warning = render_stock_icon(IconRole::Warning, IconSize::Large, ThemeMode::Light, 1);
let information =
render_stock_icon(IconRole::Information, IconSize::Large, ThemeMode::Light, 1);
let play = render_stock_icon(IconRole::Play, IconSize::Large, ThemeMode::Light, 1);
assert!(has_color_near(&warning, theme.colors.warning, 8));
assert!(has_color_near(&information, theme.colors.accent, 8));
assert!(has_color_near(&play, theme.colors.accent, 8));
}
#[test]
fn size_mode_and_role_identifiers_are_stable_and_unique() {
let mut role_ids: Vec<&str> = IconRole::ALL.iter().map(|role| role.as_str()).collect();
role_ids.sort_unstable();
role_ids.dedup();
assert_eq!(
role_ids.len(),
IconRole::ALL.len(),
"role identifiers must be unique"
);
assert!(role_ids.iter().all(|value| !value.is_empty()));
let mut xdg: Vec<&str> = IconRole::ALL.iter().map(|role| role.xdg_name()).collect();
let before = xdg.len();
xdg.sort_unstable();
xdg.dedup();
assert_eq!(xdg.len(), before, "xdg icon names must be unique");
assert!(xdg.iter().all(|value| !value.is_empty()));
assert_eq!(IconSize::Small.pixels(), 16);
assert_eq!(IconSize::Large.pixels(), 32);
assert_eq!(IconSize::Small.as_str(), "small");
assert_eq!(IconSize::Large.as_str(), "large");
assert_eq!(IconSource::Portable.as_str(), "portable");
assert_eq!(IconSource::Native.as_str(), "native");
}
#[test]
fn capability_constructors_report_expected_flags() {
assert_eq!(ArtCapabilities::none(), ArtCapabilities::default());
assert!(!ArtCapabilities::none().native_icons);
let native = ArtCapabilities::native(true, false);
assert!(native.native_icons);
assert!(native.dpi_variants);
assert!(!native.theme_aware);
}
#[test]
fn resamplers_preserve_alpha_and_aspect() {
let pixel = |buffer: &[u8], x: usize, y: usize, width: usize| -> [u8; 4] {
let offset = (y * width + x) * 4;
[
buffer[offset],
buffer[offset + 1],
buffer[offset + 2],
buffer[offset + 3],
]
};
let mut source = vec![0u8; 2 * 2 * 4];
source[0..4].copy_from_slice(&[255, 0, 0, 255]);
let (width, height, scaled) = resample_rgba(&source, 2, 2, 4, 4).expect("resample");
assert_eq!((width, height), (4, 4));
assert_eq!(scaled.len(), 4 * 4 * 4);
assert_eq!(pixel(&scaled, 0, 0, 4), [255, 0, 0, 255]);
assert_eq!(pixel(&scaled, 3, 3, 4)[3], 0);
let mut wide = vec![0u8; 4 * 2 * 4];
for index in 0..8 {
wide[index * 4] = 10;
wide[index * 4 + 1] = 200;
wide[index * 4 + 2] = 30;
wide[index * 4 + 3] = 255;
}
let (width, height, centered) = resample_rgba_centered(&wide, 4, 2, 8).expect("center");
assert_eq!((width, height), (8, 8));
assert_eq!(centered.len(), 8 * 8 * 4);
assert_eq!(pixel(¢ered, 0, 0, 8)[3], 0);
assert_eq!(pixel(¢ered, 4, 4, 8)[3], 255);
assert_eq!(pixel(¢ered, 7, 7, 8)[3], 0);
assert!(resample_rgba(&source, 2, 2, 4, 4).is_ok());
assert!(matches!(
resample_rgba(&source, 3, 3, 4, 4),
Err(GuiError::Backend(_))
));
}
#[test]
fn bmp_export_has_a_valid_header_and_composites_alpha() {
let icon = render_stock_icon(IconRole::Folder, IconSize::Small, ThemeMode::Light, 1);
let background = Color::rgb(0x10, 0x20, 0x30);
let bmp = icon.to_bmp(background);
assert_eq!(&bmp[0..2], b"BM");
let declared_size = u32::from_le_bytes([bmp[2], bmp[3], bmp[4], bmp[5]]);
assert_eq!(declared_size as usize, bmp.len());
let offset = u32::from_le_bytes([bmp[10], bmp[11], bmp[12], bmp[13]]);
assert_eq!(offset, 54);
let header_size = u32::from_le_bytes([bmp[14], bmp[15], bmp[16], bmp[17]]);
assert_eq!(header_size, 40);
let width = i32::from_le_bytes([bmp[18], bmp[19], bmp[20], bmp[21]]);
let height = i32::from_le_bytes([bmp[22], bmp[23], bmp[24], bmp[25]]);
assert_eq!((width, height), (16, 16));
let bits = u16::from_le_bytes([bmp[28], bmp[29]]);
assert_eq!(bits, 24);
let row_stride = (16 * 3 + 3) & !3;
assert_eq!(bmp.len(), 54 + row_stride * 16);
let corner_row_start = 54 + row_stride * 15;
let (b, g, r) = (
bmp[corner_row_start],
bmp[corner_row_start + 1],
bmp[corner_row_start + 2],
);
assert_eq!((r, g, b), (background.r, background.g, background.b));
let opaque = (0..16u32)
.flat_map(|y| (0..16u32).map(move |x| (x, y)))
.find(|(x, y)| icon.pixel(*x, *y).map(|px| px[3] > 200).unwrap_or(false));
assert!(opaque.is_some(), "folder glyph should have opaque pixels");
assert!(bmp.len() > 54);
}
#[test]
fn sf_symbols_cover_all_portable_roles() {
for role in IconRole::ALL {
let symbol = role.sf_symbol_name();
assert!(symbol.is_some(), "{role:?} must have an SF Symbol mapping");
assert!(
!symbol.unwrap().is_empty(),
"{role:?} SF Symbol name cannot be empty"
);
}
}
#[test]
fn formatting_roles_resolve_and_render_crisply() {
let formatting_roles = [
IconRole::FormatBold,
IconRole::FormatItalic,
IconRole::FormatStrikethrough,
IconRole::FormatCode,
IconRole::FormatHeading,
IconRole::ListBulleted,
IconRole::ListNumbered,
IconRole::ListTask,
IconRole::Quote,
IconRole::InsertLink,
IconRole::InsertImage,
IconRole::InsertTable,
IconRole::InsertRule,
IconRole::ThemeToggle,
];
assert_eq!(formatting_roles.len(), 14);
for role in formatting_roles {
assert!(
role.as_str().starts_with("format-")
|| role.as_str().starts_with("list-")
|| role.as_str().starts_with("insert-")
|| role.as_str() == "quote"
|| role.as_str() == "theme-toggle",
"unexpected as_str: {}",
role.as_str()
);
assert!(
!role.xdg_name().is_empty(),
"xdg_name cannot be empty for {role:?}"
);
assert!(
role.sf_symbol_name().is_some(),
"sf_symbol_name cannot be None for {role:?}"
);
for size in IconSize::ALL {
for mode in [ThemeMode::Light, ThemeMode::Dark] {
let icon = render_stock_icon(role, size, mode, 1);
assert_eq!(icon.width, size.pixels());
assert_eq!(icon.height, size.pixels());
assert!(
icon.has_visible_pixels(),
"formatting role {role:?} ({size:?}, {mode:?}) rendered empty"
);
}
}
}
}
}