S015: Material You foundation: M3 schemes, Outfit, icons, springs, widgets, gallery

Fixes R1-01 (icon glyphs) and R1-02 (clock contrast).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-11 19:36:53 -06:00
commit 07b357deaf
20 changed files with 2292 additions and 308 deletions

View file

@ -1357,10 +1357,7 @@ impl App {
let site = win.tab().and_then(|t| t.theme_color);
let palette = theme::Palette::new(theme::seed(&settings, site, self.shared.system_accent), dark, &settings.theme.variant, settings.theme.contrast);
let ctx = &win.egui.egui_ctx;
// Pin egui's theme to ours so a system theme change can't swap in egui's default style.
ctx.set_theme(if dark { egui::Theme::Dark } else { egui::Theme::Light });
ctx.set_visuals(theme::visuals(&palette, theme::corner(&settings)));
ctx.all_styles_mut(|style| style.animation_time = theme::animation_time(&settings));
theme::apply(ctx, &palette, &settings);
if (settings.ui.scale - 1.0).abs() > 0.01 {
ctx.set_zoom_factor(settings.ui.scale.clamp(0.5, 3.0));
}

View file

@ -26,6 +26,8 @@ pub enum Page {
Welcome,
TaskManager,
DevTools,
/// Every widget and design token (not linked from the UI; for checking the design system).
Gallery,
/// Page source of the URL.
Source(String),
/// Network error page for a URL the browser itself couldn't open.
@ -51,6 +53,7 @@ impl Page {
"welcome" | "setup" => Page::Welcome,
"task-manager" | "tasks" => Page::TaskManager,
"devtools" => Page::DevTools,
"gallery" => Page::Gallery,
"source" => Page::Source(crate::util::percent_decode(&arg)),
_ => return None,
})
@ -73,6 +76,7 @@ impl Page {
Page::Welcome => "nacre://welcome".into(),
Page::TaskManager => "nacre://task-manager".into(),
Page::DevTools => "nacre://devtools".into(),
Page::Gallery => "nacre://gallery".into(),
Page::Source(url) => format!("nacre://source/{}", crate::util::encode_query(url)),
Page::Error(url, _) => url.clone(),
}
@ -93,6 +97,7 @@ impl Page {
Page::Welcome => "Welcome to Nacre".into(),
Page::TaskManager => "Task manager".into(),
Page::DevTools => "Developer tools".into(),
Page::Gallery => "Gallery".into(),
Page::Source(url) => format!("Source of {url}"),
Page::Error(_, _) => crate::resources::ERROR_TITLE.into(),
}

View file

@ -1,7 +1,11 @@
//! Colours and shapes for the interface, from the Appearance settings. Kept plain on purpose:
//! one accent colour drives a small set of roles; the designed look comes later.
//! The design tokens (docs/DESIGN.md "UI system"): Material You colour roles from a seed colour, shape, space, type
//! and motion. Everything the interface draws takes its colours, radii, sizes and springs from here.
use egui::{Color32, CornerRadius, Visuals};
use egui::{Color32, Context, CornerRadius, FontFamily, FontId, Id, Visuals};
use material_colors::color::Argb;
use material_colors::dynamic_color::{DynamicScheme, Variant};
use material_colors::hct::Hct;
use material_colors::palette::TonalPalette;
use crate::store::settings::{ColourFallback, ColourSource, Motion, Roundness, Settings, ThemeMode};
@ -44,49 +48,6 @@ pub fn to_hex(c: Color32) -> String {
format!("#{:02X}{:02X}{:02X}", c.r(), c.g(), c.b())
}
fn to_hsl(c: Color32) -> (f32, f32, f32) {
let (r, g, b) = (c.r() as f32 / 255.0, c.g() as f32 / 255.0, c.b() as f32 / 255.0);
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let l = (max + min) / 2.0;
if (max - min).abs() < 1e-6 {
return (0.0, 0.0, l);
}
let d = max - min;
let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) };
let h = if max == r { (g - b) / d + if g < b { 6.0 } else { 0.0 } } else if max == g { (b - r) / d + 2.0 } else { (r - g) / d + 4.0 };
(h * 60.0, s, l)
}
fn from_hsl(h: f32, s: f32, l: f32) -> Color32 {
let hue = |p: f32, q: f32, mut t: f32| {
if t < 0.0 {
t += 1.0;
}
if t > 1.0 {
t -= 1.0;
}
if t < 1.0 / 6.0 {
p + (q - p) * 6.0 * t
} else if t < 0.5 {
q
} else if t < 2.0 / 3.0 {
p + (q - p) * (2.0 / 3.0 - t) * 6.0
} else {
p
}
};
let (s, l) = (s.clamp(0.0, 1.0), l.clamp(0.0, 1.0));
if s == 0.0 {
let v = (l * 255.0) as u8;
return Color32::from_rgb(v, v, v);
}
let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s };
let p = 2.0 * l - q;
let h = h.rem_euclid(360.0) / 360.0;
Color32::from_rgb((hue(p, q, h + 1.0 / 3.0) * 255.0) as u8, (hue(p, q, h) * 255.0) as u8, (hue(p, q, h - 1.0 / 3.0) * 255.0) as u8)
}
/// The system accent colour: KDE's kdeglobals, else GNOME's accent-color setting.
pub fn system_accent() -> Option<Color32> {
#[cfg(unix)]
@ -151,75 +112,158 @@ pub fn system_dark(winit_theme: Option<winit::window::Theme>) -> bool {
}
}
/// The colour roles the interface uses.
// ---------------------------------------------------------------------------------------------------------------
// Colour
/// The colour roles of a Material 3 scheme. The first block holds the names the older UI code uses; they alias M3
/// roles (see `Palette::new`). New code uses the M3 names.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Palette {
pub dark: bool,
/// = primary.
pub accent: Color32,
/// = on_primary.
pub on_accent: Color32,
/// = secondary_container.
pub accent_soft: Color32,
/// = surface.
pub surface: Color32,
/// = surface_container_high.
pub surface_high: Color32,
/// = surface_container_lowest.
pub surface_low: Color32,
/// = on_surface.
pub text: Color32,
/// = on_surface_variant.
pub text_weak: Color32,
pub outline: Color32,
pub error: Color32,
/// Not an M3 role: an amber from a fixed hue, at the tones primary uses.
pub warning: Color32,
/// Not an M3 role: a green from a fixed hue, at the tones primary uses.
pub success: Color32,
pub primary: Color32,
pub on_primary: Color32,
pub primary_container: Color32,
pub on_primary_container: Color32,
pub inverse_primary: Color32,
pub secondary: Color32,
pub on_secondary: Color32,
pub secondary_container: Color32,
pub on_secondary_container: Color32,
pub tertiary: Color32,
pub on_tertiary: Color32,
pub tertiary_container: Color32,
pub on_tertiary_container: Color32,
pub on_error: Color32,
pub error_container: Color32,
pub on_error_container: Color32,
pub surface_dim: Color32,
pub surface_bright: Color32,
pub surface_container_lowest: Color32,
pub surface_container_low: Color32,
pub surface_container: Color32,
pub surface_container_high: Color32,
pub surface_container_highest: Color32,
pub on_surface: Color32,
pub on_surface_variant: Color32,
pub outline_variant: Color32,
pub inverse_surface: Color32,
pub inverse_on_surface: Color32,
pub scrim: Color32,
pub shadow: Color32,
}
fn argb(c: Color32) -> Argb {
Argb::new(255, c.r(), c.g(), c.b())
}
fn color(a: Argb) -> Color32 {
Color32::from_rgb(a.red, a.green, a.blue)
}
impl Palette {
/// The scheme for `seed`: `variant` is one of `VARIANTS`' keys, `contrast` runs from -1 (less) to 1 (more).
pub fn new(seed: Color32, dark: bool, variant: &str, contrast: f32) -> Palette {
let (h, s, _) = to_hsl(seed);
let s = match variant {
"vibrant" => (s * 1.25).min(1.0),
"expressive" => (s * 1.1).min(1.0),
"neutral" => s * 0.35,
"monochrome" => 0.0,
"fidelity" | "content" => s,
_ => s * 0.8,
let variant = match variant {
"vibrant" => Variant::Vibrant,
"expressive" => Variant::Expressive,
"neutral" => Variant::Neutral,
"monochrome" => Variant::Monochrome,
"fidelity" => Variant::Fidelity,
"content" => Variant::Content,
_ => Variant::TonalSpot,
};
let h2 = if variant == "expressive" { h + 60.0 } else { h };
let c = contrast.clamp(-1.0, 1.0) * 0.08;
let tint = if variant == "monochrome" { 0.0 } else { (s * 0.22).min(0.18) };
if dark {
Palette {
dark,
accent: from_hsl(h, s.max(0.3).min(0.8), 0.72 + c),
on_accent: from_hsl(h, 0.6, 0.18),
accent_soft: from_hsl(h2, s * 0.5, 0.28),
surface: from_hsl(h, tint, 0.075 - c * 0.5),
surface_high: from_hsl(h, tint, 0.14),
surface_low: from_hsl(h, tint, 0.05),
text: from_hsl(h, tint * 0.5, 0.92 + c),
text_weak: from_hsl(h, tint, 0.68 + c),
outline: from_hsl(h, tint, 0.32),
error: Color32::from_rgb(0xF2, 0xB8, 0xB5),
warning: Color32::from_rgb(0xFF, 0xCC, 0x80),
success: Color32::from_rgb(0xA5, 0xD6, 0xA7),
}
} else {
Palette {
dark,
accent: from_hsl(h, s.max(0.35).min(0.85), 0.40 - c),
on_accent: Color32::WHITE,
accent_soft: from_hsl(h2, s * 0.6, 0.88),
surface: from_hsl(h, tint, 0.975 + c * 0.2),
surface_high: from_hsl(h, tint, 0.92),
surface_low: from_hsl(h, tint, 0.995),
text: from_hsl(h, tint * 0.5, 0.10 - c),
text_weak: from_hsl(h, tint, 0.36 - c),
outline: from_hsl(h, tint, 0.78),
error: Color32::from_rgb(0xB3, 0x26, 0x1E),
warning: Color32::from_rgb(0x8B, 0x50, 0x00),
success: Color32::from_rgb(0x38, 0x6A, 0x20),
}
let s = DynamicScheme::by_variant(argb(seed), &variant, dark, Some(f64::from(contrast.clamp(-1.0, 1.0))));
// Status colours keep their own hue and follow primary's tones, so they sit with the scheme.
let tone = if dark { 80 } else { 40 };
let status = |hue: f64, chroma: f64| color(TonalPalette::of(hue, chroma).tone(tone));
Palette {
dark,
accent: color(s.primary()),
on_accent: color(s.on_primary()),
accent_soft: color(s.secondary_container()),
surface: color(s.surface()),
surface_high: color(s.surface_container_high()),
surface_low: color(s.surface_container_lowest()),
text: color(s.on_surface()),
text_weak: color(s.on_surface_variant()),
outline: color(s.outline()),
error: color(s.error()),
warning: status(75.0, 60.0),
success: status(140.0, 48.0),
primary: color(s.primary()),
on_primary: color(s.on_primary()),
primary_container: color(s.primary_container()),
on_primary_container: color(s.on_primary_container()),
inverse_primary: color(s.inverse_primary()),
secondary: color(s.secondary()),
on_secondary: color(s.on_secondary()),
secondary_container: color(s.secondary_container()),
on_secondary_container: color(s.on_secondary_container()),
tertiary: color(s.tertiary()),
on_tertiary: color(s.on_tertiary()),
tertiary_container: color(s.tertiary_container()),
on_tertiary_container: color(s.on_tertiary_container()),
on_error: color(s.on_error()),
error_container: color(s.error_container()),
on_error_container: color(s.on_error_container()),
surface_dim: color(s.surface_dim()),
surface_bright: color(s.surface_bright()),
surface_container_lowest: color(s.surface_container_lowest()),
surface_container_low: color(s.surface_container_low()),
surface_container: color(s.surface_container()),
surface_container_high: color(s.surface_container_high()),
surface_container_highest: color(s.surface_container_highest()),
on_surface: color(s.on_surface()),
on_surface_variant: color(s.on_surface_variant()),
outline_variant: color(s.outline_variant()),
inverse_surface: color(s.inverse_surface()),
inverse_on_surface: color(s.inverse_on_surface()),
scrim: color(s.scrim()),
shadow: color(s.shadow()),
}
}
}
/// Seed colour from the settings; `site` is the current page's colour when the source is "Website".
/// `over` laid on `base` at `amount` (0..1): state layers (hover, press) and tints, always opaque.
pub fn layer(base: Color32, over: Color32, amount: f32) -> Color32 {
let mix = |a: u8, b: u8| (f32::from(a) + (f32::from(b) - f32::from(a)) * amount.clamp(0.0, 1.0)).round() as u8;
Color32::from_rgb(mix(base.r(), over.r()), mix(base.g(), over.g()), mix(base.b(), over.b()))
}
/// State layer opacities (M3): the content colour laid over the container.
pub const HOVER: f32 = 0.08;
pub const FOCUS: f32 = 0.10;
pub const PRESS: f32 = 0.10;
pub const DRAG: f32 = 0.16;
/// Disabled controls: content and container opacity.
pub const DISABLED_CONTENT: f32 = 0.38;
pub const DISABLED_CONTAINER: f32 = 0.12;
/// Seed colour from the settings; `site` is the current page's colour when the source is "Website". Greys and
/// near-black or near-white site colours make poor seeds, so they fall back.
pub fn seed(settings: &Settings, site: Option<Color32>, system: Option<Color32>) -> Color32 {
let preset = parse_hex(&settings.theme.preset).unwrap_or(Color32::from_rgb(0x67, 0x50, 0xA4));
let fallback = || match settings.theme.fallback {
@ -227,13 +271,18 @@ pub fn seed(settings: &Settings, site: Option<Color32>, system: Option<Color32>)
ColourFallback::Palette => preset,
};
match settings.theme.source {
ColourSource::Website => site.filter(|c| { let (_, s, l) = to_hsl(*c); s > 0.15 && l > 0.1 && l < 0.9 }).unwrap_or_else(fallback),
ColourSource::Website => site.filter(|c| usable_seed(*c)).unwrap_or_else(fallback),
ColourSource::System => system.unwrap_or(preset),
ColourSource::Palette => preset,
ColourSource::Custom => parse_hex(&settings.theme.custom).unwrap_or(preset),
}
}
fn usable_seed(c: Color32) -> bool {
let hct = Hct::new(argb(c));
hct.get_chroma() >= 12.0 && (8.0..=95.0).contains(&hct.get_tone())
}
pub fn is_dark(settings: &Settings, system_is_dark: bool) -> bool {
match settings.theme.mode {
ThemeMode::System => system_is_dark,
@ -242,56 +291,295 @@ pub fn is_dark(settings: &Settings, system_is_dark: bool) -> bool {
}
}
pub fn corner(settings: &Settings) -> u8 {
// ---------------------------------------------------------------------------------------------------------------
// Shape and space
/// Corner radii (M3 shape scale) at the Default roundness. Read them through `radius`, which applies the
/// Roundness setting. `FULL` makes pills and circles.
pub const XS: f32 = 4.0;
pub const S: f32 = 8.0;
pub const M: f32 = 12.0;
pub const L: f32 = 16.0;
pub const XL: f32 = 28.0;
pub const FULL: f32 = 1000.0;
/// Spacing on a 4 px grid.
pub const GAP_XS: f32 = 4.0;
pub const GAP_S: f32 = 8.0;
pub const GAP_M: f32 = 12.0;
pub const GAP_L: f32 = 16.0;
pub const GAP_XL: f32 = 24.0;
/// Control heights: compact chrome controls, standard buttons and fields, list rows.
pub const CONTROL_SMALL: f32 = 32.0;
pub const CONTROL: f32 = 40.0;
pub const ROW: f32 = 56.0;
fn roundness_scale(settings: &Settings) -> f32 {
match settings.ui.roundness {
Roundness::Subtle => 4,
Roundness::Normal => 8,
Roundness::Round => 14,
Roundness::Subtle => 0.5,
Roundness::Normal => 1.0,
Roundness::Round => 1.4,
}
}
/// Seconds for UI animations (0 = off).
pub fn animation_time(settings: &Settings) -> f32 {
/// A radius token with the Roundness setting applied. `FULL` stays full.
pub fn radius(ctx: &Context, token: f32) -> f32 {
if token >= FULL { FULL } else { token * tokens(ctx).roundness }
}
/// egui's corner type, which holds whole points up to 255.
pub fn corner_radius(r: f32) -> CornerRadius {
CornerRadius::same(r.round().clamp(0.0, 255.0) as u8)
}
/// Corner radius of small controls (the egui default widgets), from the Roundness setting.
pub fn corner(settings: &Settings) -> u8 {
(S * roundness_scale(settings)).round() as u8
}
// ---------------------------------------------------------------------------------------------------------------
// Type
/// Type scale. Weight and colour carry hierarchy before size does.
pub const SMALL: f32 = 12.0;
pub const BODY: f32 = 14.0;
pub const TITLE: f32 = 18.0;
pub const HEADLINE: f32 = 24.0;
pub const DISPLAY: f32 = 64.0;
/// Outfit weights registered as font families (`ui::fonts`). Regular is egui's Proportional family.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Weight {
Thin,
Light,
Regular,
Medium,
SemiBold,
}
impl Weight {
pub const ALL: [Weight; 5] = [Weight::Thin, Weight::Light, Weight::Regular, Weight::Medium, Weight::SemiBold];
pub fn wght(self) -> f32 {
match self {
Weight::Thin => 200.0,
Weight::Light => 300.0,
Weight::Regular => 400.0,
Weight::Medium => 500.0,
Weight::SemiBold => 600.0,
}
}
pub fn family(self) -> FontFamily {
match self {
Weight::Regular => FontFamily::Proportional,
Weight::Thin => FontFamily::Name("outfit-thin".into()),
Weight::Light => FontFamily::Name("outfit-light".into()),
Weight::Medium => FontFamily::Name("outfit-medium".into()),
Weight::SemiBold => FontFamily::Name("outfit-semibold".into()),
}
}
}
pub fn font(size: f32, weight: Weight) -> FontId {
FontId::new(size, weight.family())
}
/// Material Symbols families: outlined (FILL 0) and filled (FILL 1, for selected states).
pub fn icon_font(size: f32, filled: bool) -> FontId {
FontId::new(size, FontFamily::Name(if filled { "icons-filled" } else { "icons" }.into()))
}
/// Icon sizes: in chrome and lists, and large (empty states, cards).
pub const ICON: f32 = 20.0;
pub const ICON_LARGE: f32 = 32.0;
// ---------------------------------------------------------------------------------------------------------------
// Motion
/// A spring: `stiffness` and `damping` ratio (1 = critically damped, no overshoot). Presets from M3 Expressive.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Spring {
pub stiffness: f32,
pub damping: f32,
}
/// Press and small controls.
pub const FAST: Spring = Spring { stiffness: 1400.0, damping: 0.62 };
/// Panels and movement.
pub const DEFAULT: Spring = Spring { stiffness: 700.0, damping: 0.68 };
/// Big transitions.
pub const SLOW: Spring = Spring { stiffness: 300.0, damping: 0.74 };
/// Colour, opacity and tints: never overshoots.
pub const EFFECT: Spring = Spring { stiffness: 900.0, damping: 1.0 };
/// Motion setting as a time factor: 1 = Normal, 0 = Off.
fn motion_scale(settings: &Settings) -> f32 {
match settings.ui.motion {
Motion::Off => 0.0,
Motion::Fast => 0.06,
Motion::Normal => 0.1,
Motion::Slow => 0.18,
Motion::Fast => 0.6,
Motion::Normal => 1.0,
Motion::Slow => 1.8,
}
}
/// egui visuals for a palette.
/// Seconds for egui's own animations (collapsing headers, scroll), 0 = off.
pub fn animation_time(settings: &Settings) -> f32 {
0.1 * motion_scale(settings)
}
#[derive(Clone, Copy, Debug)]
struct SpringState {
value: f32,
velocity: f32,
frame: u64,
}
/// A spring's current value, for tests.
#[cfg(test)]
pub fn spring_value(ctx: &Context, id: Id) -> Option<f32> {
ctx.data(|d| d.get_temp::<SpringState>(id)).map(|s| s.value)
}
/// Animates towards `target` with `spring` and returns this frame's value. The first call for an `id` starts at
/// the target. Retargeting mid-flight keeps the velocity, so motion never snaps. Repaints only while moving; with
/// Motion off it returns the target.
pub fn spring(ctx: &Context, id: Id, target: f32, spring: Spring) -> f32 {
let scale = tokens(ctx).motion;
let frame = ctx.cumulative_frame_nr();
let dt = ctx.input(|i| i.stable_dt).min(0.05);
let (value, moving) = ctx.data_mut(|d| {
let s = d.get_temp_mut_or_insert_with(id, || SpringState { value: target, velocity: 0.0, frame });
if scale <= 0.0 {
*s = SpringState { value: target, velocity: 0.0, frame };
} else if s.frame != frame {
s.frame = frame;
spring_step(s, target, spring, scale, dt);
}
(s.value, s.value != target)
});
if moving {
ctx.request_repaint();
}
value
}
/// A 0..1 value for an on/off state with the `EFFECT` spring: hover and selection tints, fades.
pub fn effect(ctx: &Context, id: Id, on: bool) -> f32 {
spring(ctx, id, if on { 1.0 } else { 0.0 }, EFFECT).clamp(0.0, 1.0)
}
/// Semi-implicit Euler in steps of at most 1/240 s. `scale` stretches time: the spring's stiffness drops with its
/// square, so Slow takes `scale` times as long with the same shape.
fn spring_step(s: &mut SpringState, target: f32, spring: Spring, scale: f32, dt: f32) {
let k = spring.stiffness / (scale * scale);
let c = 2.0 * spring.damping * k.sqrt();
let steps = (dt * 240.0).ceil().max(1.0);
let h = dt / steps;
for _ in 0..steps as u32 {
let a = -k * (s.value - target) - c * s.velocity;
s.velocity += a * h;
s.value += s.velocity * h;
}
if (s.value - target).abs() < 1e-3 && s.velocity.abs() < 1e-2 {
s.value = target;
s.velocity = 0.0;
}
}
// ---------------------------------------------------------------------------------------------------------------
// Applying the tokens
/// The tokens a window draws with, kept in its egui context so widgets can reach them from any `Ui`.
#[derive(Clone, Copy, Debug)]
pub struct Tokens {
pub palette: Palette,
/// Roundness setting as a factor on the radius tokens.
pub roundness: f32,
/// Motion setting as a time factor (0 = off).
pub motion: f32,
}
pub fn tokens(ctx: &Context) -> Tokens {
ctx.data(|d| d.get_temp::<Tokens>(Id::NULL)).unwrap_or_else(|| Tokens { palette: Palette::new(Color32::from_rgb(0x67, 0x50, 0xA4), true, "tonal_spot", 0.0), roundness: 1.0, motion: 1.0 })
}
/// Shortcut for the palette in widgets.
pub fn palette(ctx: &Context) -> Palette {
tokens(ctx).palette
}
/// Styles a window's egui context: tokens, visuals, text styles and spacing.
pub fn apply(ctx: &Context, palette: &Palette, settings: &Settings) {
ctx.data_mut(|d| d.insert_temp(Id::NULL, Tokens { palette: *palette, roundness: roundness_scale(settings), motion: motion_scale(settings) }));
// Pin egui's theme to ours so a system theme change can't swap in egui's default style.
ctx.set_theme(if palette.dark { egui::Theme::Dark } else { egui::Theme::Light });
ctx.set_visuals(visuals(palette, corner(settings)));
let time = animation_time(settings);
ctx.all_styles_mut(|style| {
use egui::TextStyle;
style.animation_time = time;
style.text_styles = [
(TextStyle::Small, FontId::proportional(SMALL)),
(TextStyle::Body, FontId::proportional(BODY)),
(TextStyle::Button, FontId::proportional(BODY)),
(TextStyle::Heading, font(HEADLINE, Weight::Medium)),
(TextStyle::Monospace, FontId::monospace(13.0)),
]
.into();
style.spacing.item_spacing = egui::vec2(GAP_S, 6.0);
style.spacing.button_padding = egui::vec2(GAP_M, GAP_XS);
style.spacing.interact_size.y = 24.0;
style.spacing.menu_margin = egui::Margin::same(GAP_S as i8);
});
}
/// egui visuals for a palette: egui's own widgets (plain buttons, fields, menus) in the scheme's roles.
pub fn visuals(p: &Palette, corner_radius: u8) -> Visuals {
let mut v = if p.dark { Visuals::dark() } else { Visuals::light() };
let r = CornerRadius::same(corner_radius);
let big = CornerRadius::same(corner_radius.saturating_mul(2));
v.panel_fill = p.surface;
v.window_fill = p.surface_high;
v.extreme_bg_color = p.surface_low;
v.faint_bg_color = p.surface_high;
v.override_text_color = Some(p.text);
v.hyperlink_color = p.accent;
v.selection.bg_fill = p.accent.gamma_multiply(0.45);
v.selection.stroke.color = p.accent;
v.window_corner_radius = r;
v.menu_corner_radius = r;
v.window_stroke.color = p.outline;
v.window_fill = p.surface_container;
v.extreme_bg_color = p.surface_container_highest;
v.text_edit_bg_color = Some(p.surface_container_highest);
v.faint_bg_color = p.surface_container_low;
v.code_bg_color = p.surface_container_high;
v.override_text_color = Some(p.on_surface);
v.weak_text_color = Some(p.on_surface_variant);
v.hyperlink_color = p.primary;
v.selection.bg_fill = layer(p.surface, p.primary, 0.35);
v.selection.stroke.color = p.primary;
v.window_corner_radius = big;
v.menu_corner_radius = big;
v.window_stroke.color = p.outline_variant;
v.window_shadow = egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if p.dark { 90 } else { 40 }) };
v.popup_shadow = egui::Shadow { offset: [0, 2], blur: 10, spread: 0, color: Color32::from_black_alpha(if p.dark { 80 } else { 32 }) };
v.error_fg_color = p.error;
v.warn_fg_color = p.warning;
for w in [&mut v.widgets.noninteractive, &mut v.widgets.inactive, &mut v.widgets.hovered, &mut v.widgets.active, &mut v.widgets.open] {
let base = p.surface_container_highest;
for (w, fill) in [
(&mut v.widgets.noninteractive, p.surface),
(&mut v.widgets.inactive, base),
(&mut v.widgets.hovered, layer(base, p.on_surface, HOVER)),
(&mut v.widgets.active, layer(base, p.on_surface, HOVER + PRESS)),
(&mut v.widgets.open, layer(base, p.on_surface, HOVER)),
] {
w.corner_radius = r;
w.bg_fill = fill;
w.weak_bg_fill = fill;
w.bg_stroke = egui::Stroke::NONE;
// Strong text is egui's active foreground: it must stay readable on the page (R1-02).
w.fg_stroke.color = p.on_surface;
w.expansion = 0.0;
}
v.widgets.noninteractive.bg_fill = p.surface;
v.widgets.noninteractive.bg_stroke.color = p.outline;
v.widgets.noninteractive.fg_stroke.color = p.text;
v.widgets.inactive.bg_fill = p.surface_high;
v.widgets.inactive.weak_bg_fill = p.surface_high;
v.widgets.inactive.fg_stroke.color = p.text;
v.widgets.hovered.bg_fill = p.accent_soft;
v.widgets.hovered.weak_bg_fill = p.accent_soft;
v.widgets.hovered.bg_stroke.color = p.accent;
v.widgets.active.bg_fill = p.accent;
v.widgets.active.weak_bg_fill = p.accent;
v.widgets.active.fg_stroke.color = p.on_accent;
v.widgets.noninteractive.bg_stroke = egui::Stroke::new(1.0, p.outline_variant);
v.widgets.noninteractive.fg_stroke.color = p.on_surface_variant;
v.widgets.inactive.fg_stroke.color = p.on_surface_variant;
v.widgets.hovered.bg_stroke = egui::Stroke::new(1.0, p.outline);
v.widgets.active.bg_stroke = egui::Stroke::new(1.0, p.primary);
v.widgets.open.bg_stroke = egui::Stroke::new(1.0, p.outline);
v
}
@ -315,9 +603,82 @@ mod tests {
assert_eq!(parse_hex("#6750A4"), Some(Color32::from_rgb(0x67, 0x50, 0xA4)));
assert_eq!(parse_css_color("rgb(10, 20, 30)"), Some(Color32::from_rgb(10, 20, 30)));
assert_eq!(parse_css_color("rgba(0, 0, 0, 0)"), None);
let c = Color32::from_rgb(200, 100, 50);
let (h, s, l) = to_hsl(c);
let back = from_hsl(h, s, l);
assert!((back.r() as i32 - 200).abs() <= 1 && (back.g() as i32 - 100).abs() <= 1);
assert_eq!(to_hex(Color32::from_rgb(200, 100, 50)), "#C86432");
}
fn hex(c: Color32) -> String {
to_hex(c)
}
/// Reference colours from Material Color Utilities' tonal spot tests (seed 0xff0000ff, standard contrast) and
/// Material Theme Builder (seed #6750A4).
#[test]
fn tonal_spot_reference_colours() {
let blue = Color32::from_rgb(0, 0, 255);
let light = Palette::new(blue, false, "tonal_spot", 0.0);
let dark = Palette::new(blue, true, "tonal_spot", 0.0);
assert_eq!(hex(light.primary), "#555992");
assert_eq!(hex(light.primary_container), "#E0E0FF");
assert_eq!(hex(dark.primary), "#BEC2FF");
let violet = parse_hex("#6750A4").unwrap();
assert_eq!(hex(Palette::new(violet, false, "tonal_spot", 0.0).primary), "#65558F");
assert_eq!(hex(Palette::new(violet, true, "tonal_spot", 0.0).primary), "#CFBDFE");
}
fn tone(c: Color32) -> f64 {
Hct::new(argb(c)).get_tone()
}
/// The scheme's tones follow the M3 spec for every preset seed: surface T98 / T6, primary T40 / T80, and text
/// at least 4.5:1 on every surface, in light and dark.
#[test]
fn scheme_tones_and_contrast() {
for preset in PRESETS {
let seed = parse_hex(preset).unwrap();
for dark in [false, true] {
let p = Palette::new(seed, dark, "tonal_spot", 0.0);
let (surface, primary) = if dark { (6.0, 80.0) } else { (98.0, 40.0) };
assert!((tone(p.surface) - surface).abs() < 1.0, "{preset} dark={dark} surface tone {}", tone(p.surface));
assert!((tone(p.primary) - primary).abs() < 1.0, "{preset} dark={dark} primary tone {}", tone(p.primary));
for (name, bg) in [("surface", p.surface), ("lowest", p.surface_container_lowest), ("highest", p.surface_container_highest)] {
for (text_name, fg) in [("on_surface", p.on_surface), ("on_surface_variant", p.on_surface_variant)] {
let ratio = material_colors::contrast::ratio_of_tones(tone(fg), tone(bg));
assert!(ratio >= 4.5, "{preset} dark={dark} {text_name} on {name}: {ratio:.2}");
}
}
let ratio = material_colors::contrast::ratio_of_tones(tone(p.on_primary), tone(p.primary));
assert!(ratio >= 4.5, "{preset} dark={dark} on_primary: {ratio:.2}");
}
}
}
/// Every variant builds, and grey site colours don't become seeds.
#[test]
fn variants_and_seeds() {
for (key, _) in VARIANTS {
let p = Palette::new(Color32::from_rgb(0x00, 0x6A, 0x6A), true, key, 0.0);
assert_ne!(p.primary, p.surface, "{key}");
}
assert!(!usable_seed(Color32::from_rgb(128, 128, 128)));
assert!(!usable_seed(Color32::WHITE));
assert!(usable_seed(Color32::from_rgb(0x0B, 0x57, 0xD0)));
}
#[test]
fn spring_settles_on_target() {
let mut s = SpringState { value: 0.0, velocity: 0.0, frame: 0 };
let mut peak: f32 = 0.0;
for _ in 0..120 {
spring_step(&mut s, 1.0, FAST, 1.0, 1.0 / 60.0);
peak = peak.max(s.value);
}
assert_eq!(s.value, 1.0);
assert!(peak > 1.0, "FAST overshoots a little");
let mut s = SpringState { value: 0.0, velocity: 0.0, frame: 0 };
for _ in 0..120 {
spring_step(&mut s, 1.0, EFFECT, 1.0, 1.0 / 60.0);
assert!(s.value <= 1.0, "EFFECT never overshoots");
}
assert_eq!(s.value, 1.0);
}
}

View file

@ -10,6 +10,7 @@ use crate::net::VpnStatus;
use crate::store::settings::{BookmarksBar, MediaButton};
use crate::tabs::Page;
use crate::util;
use crate::ui::icons;
#[derive(Clone, Debug, PartialEq)]
pub enum SuggestionKind {
@ -45,13 +46,13 @@ pub fn title_bar(root: &mut Ui, f: &mut Frame) {
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
// Same size for all three, flush right.
let size = Vec2::new(40.0, 26.0);
if ui.add_sized(size, egui::Button::new("✕").frame(false)).on_hover_text("Close").clicked() {
if ui.add_sized(size, egui::Button::new(icons::CLOSE).frame(false)).on_hover_text("Close").clicked() {
f.send(Command::WindowClose);
}
if ui.add_sized(size, egui::Button::new("🗖").frame(false)).on_hover_text("Maximize").clicked() {
if ui.add_sized(size, egui::Button::new(icons::CROP_SQUARE).frame(false)).on_hover_text("Maximize").clicked() {
f.send(Command::WindowMaximize);
}
if ui.add_sized(size, egui::Button::new("🗕").frame(false)).on_hover_text("Minimize").clicked() {
if ui.add_sized(size, egui::Button::new(icons::MINIMIZE).frame(false)).on_hover_text("Minimize").clicked() {
f.send(Command::WindowMinimize);
}
});
@ -83,7 +84,7 @@ pub fn tab_strip(root: &mut Ui, f: &mut Frame) {
}
});
});
if icon_button(ui, "➕", "New tab (Ctrl+T)").clicked() {
if icon_button(ui, icons::ADD, "New tab (Ctrl+T)").clicked() {
f.send(Command::NewTab);
}
});
@ -117,7 +118,7 @@ fn tab_button(ui: &mut Ui, f: &mut Frame, index: usize, width: f32) -> Option<us
} else if let Some(texture) = &tab.favicon {
ui.painter().image(texture.id(), icon_rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
} else {
let g = if tab.page.is_some() { "◆" } else { "●" };
let g = if tab.page.is_some() { icons::TAB } else { icons::PUBLIC };
ui.painter().text(icon_rect.center(), egui::Align2::CENTER_CENTER, g, egui::FontId::proportional(11.0), palette.text_weak);
}
x += 22.0;
@ -130,13 +131,13 @@ fn tab_button(ui: &mut Ui, f: &mut Frame, index: usize, width: f32) -> Option<us
if close.hovered() {
ui.painter().rect_filled(close_rect, 4.0, palette.outline);
}
ui.painter().text(close_rect.center(), egui::Align2::CENTER_CENTER, "✕", egui::FontId::proportional(11.0), palette.text);
ui.painter().text(close_rect.center(), egui::Align2::CENTER_CENTER, icons::CLOSE, crate::theme::icon_font(14.0, false), palette.text);
close_clicked = close.clicked();
let mut title_right = close_rect.left() - 4.0;
if tab.audible() || tab.muted {
let mute_rect = egui::Rect::from_center_size(egui::pos2(title_right - 9.0, center_y), Vec2::splat(18.0));
let mute = ui.interact(mute_rect, ui.id().with(("mute", tab_id)), Sense::click()).on_hover_text(if tab.muted { "Unmute tab" } else { "Mute tab" });
ui.painter().text(mute_rect.center(), egui::Align2::CENTER_CENTER, if tab.muted { "🔇" } else { "🔊" }, egui::FontId::proportional(12.0), palette.text);
ui.painter().text(mute_rect.center(), egui::Align2::CENTER_CENTER, if tab.muted { icons::VOLUME_OFF } else { icons::VOLUME_UP }, crate::theme::icon_font(14.0, false), palette.text);
mute_clicked = mute.clicked();
title_right = mute_rect.left() - 2.0;
}
@ -198,7 +199,7 @@ pub fn toolbar(root: &mut Ui, f: &mut Frame) {
}
if settings.toolbar_has("reload") {
if loading {
if icon_button(ui, "✕", "Stop").clicked() {
if icon_button(ui, icons::CLOSE, "Stop").clicked() {
f.send(Command::Stop);
}
} else if icon_button(ui, glyph("reload"), "Reload (Ctrl+R) · Shift-click: without cache").clicked() {
@ -212,7 +213,7 @@ pub fn toolbar(root: &mut Ui, f: &mut Frame) {
// Buttons on the right first, so the address bar can take what's left.
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = 2.0;
let menu = icon_button(ui, "☰", "Menu");
let menu = icon_button(ui, icons::MENU, "Menu");
if menu.clicked() {
f.ui.toggle(Flyout::Main, Some(menu.rect));
}
@ -226,7 +227,7 @@ pub fn toolbar(root: &mut Ui, f: &mut Frame) {
fn right_buttons(ui: &mut Ui, f: &mut Frame, settings: &crate::store::settings::Settings) {
let palette = f.palette();
if f.shared.profile_count() > 1 || f.incognito() {
let label = if f.incognito() { "🕶".to_owned() } else { f.shared.paths.profile.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default() };
let label = if f.incognito() { icons::DOMINO_MASK.to_owned() } else { f.shared.paths.profile.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default() };
let r = ui.add(egui::Button::new(label).min_size(Vec2::splat(28.0))).on_hover_text(format!("Profile: {}", f.shared.paths.profile));
if r.clicked() {
f.ui.toggle(Flyout::Profiles, Some(r.rect));
@ -262,7 +263,7 @@ fn right_buttons(ui: &mut Ui, f: &mut Frame, settings: &crate::store::settings::
if settings.toolbar_has("adblock") {
let blocked = f.tab().map(|t| t.blocked).unwrap_or(0);
let paused = f.tab().is_some_and(|t| settings.adblock_paused_on(&t.host()));
let label = if !settings.adblock.enabled || paused { RichText::new("🛡").weak() } else if blocked > 0 { RichText::new(format!("🛡{blocked}")) } else { RichText::new("🛡") };
let label = if !settings.adblock.enabled || paused { RichText::new(icons::SHIELD).weak() } else if blocked > 0 { RichText::new(format!("{}{blocked}", icons::SHIELD)) } else { RichText::new(icons::SHIELD) };
let r = ui.add(egui::Button::new(label.size(14.0)).min_size(Vec2::splat(28.0)).frame(false)).on_hover_text(format!("Ad blocker · {blocked} blocked on this page"));
if r.clicked() {
f.ui.toggle(Flyout::Shield, Some(r.rect));
@ -275,8 +276,8 @@ fn right_buttons(ui: &mut Ui, f: &mut Frame, settings: &crate::store::settings::
drop(downloads);
let label = match (running, progress) {
(0, _) => RichText::new(glyph("downloads")),
(_, Some(p)) => RichText::new(format!("⬇{:.0}%", p * 100.0)).color(palette.accent),
(n, None) => RichText::new(format!("⬇{n}")).color(palette.accent),
(_, Some(p)) => RichText::new(format!("{}{:.0}%", icons::DOWNLOAD, p * 100.0)).color(palette.accent),
(n, None) => RichText::new(format!("{}{n}", icons::DOWNLOAD)).color(palette.accent),
};
let r = ui.add(egui::Button::new(label.size(14.0)).min_size(Vec2::splat(28.0)).frame(false)).on_hover_text("Downloads (Ctrl+J)");
if r.clicked() {
@ -322,7 +323,7 @@ fn omnibox(ui: &mut Ui, f: &mut Frame) {
let bookmarked = is_web && f.shared.bookmarks.borrow().is_bookmarked(&tab.url);
let installable = is_web && shown.starts_with("http") && f.shared.apps.borrow().for_url(&url::Url::parse(&shown).unwrap_or_else(|_| url::Url::parse("about:blank").expect("valid"))).is_none();
// Site info button.
let lock = if !is_web { "◆" } else if secure { "🔒" } else if shown.starts_with("http://") { "⚠" } else { "ℹ" };
let lock = if !is_web { icons::TAB } else if secure { icons::LOCK } else if shown.starts_with("http://") { icons::WARNING } else { icons::INFO };
let r = ui.add(egui::Button::new(lock).frame(false).min_size(Vec2::splat(26.0))).on_hover_text(if secure { "Connection is secure" } else if is_web { "Connection is not secure" } else { "Nacre page" });
if r.clicked() && is_web {
f.ui.toggle(Flyout::SiteInfo, Some(r.rect));
@ -406,11 +407,11 @@ fn omnibox(ui: &mut Ui, f: &mut Frame) {
if (zoom - 1.0).abs() > 0.001 && ui.add(egui::Button::new(format!("{:.0}%", zoom * 100.0)).frame(false)).on_hover_text("Zoom · click to reset").clicked() {
f.send(Command::Zoom(0));
}
if installable && icon_button(ui, "⊕", "Install this site as an app").clicked() {
if installable && icon_button(ui, icons::INSTALL_DESKTOP, "Install this site as an app").clicked() {
f.send(Command::InstallApp);
}
if is_web {
let star = ui.add(egui::Button::new(RichText::new(if bookmarked { "★" } else { "☆" }).color(if bookmarked { palette.accent } else { palette.text })).frame(false).min_size(Vec2::splat(26.0))).on_hover_text("Bookmark this page (Ctrl+D)");
let star = ui.add(egui::Button::new(RichText::new(icons::STAR).font(crate::theme::icon_font(18.0, bookmarked)).color(if bookmarked { palette.accent } else { palette.text })).frame(false).min_size(Vec2::splat(26.0))).on_hover_text("Bookmark this page (Ctrl+D)");
if star.clicked() {
if bookmarked {
f.ui.toggle(Flyout::EditBookmark(f.tabs[*f.active].url.clone()), Some(star.rect));
@ -494,12 +495,12 @@ fn suggestion_popup(ui: &mut Ui, f: &mut Frame, below: egui::Rect) {
ui.set_width(below.width());
for (i, s) in items.iter().enumerate() {
let icon = match s.kind {
SuggestionKind::Search | SuggestionKind::SearchSuggestion => "🔍",
SuggestionKind::Url => "↗",
SuggestionKind::History => "🕘",
SuggestionKind::Bookmark => "★",
SuggestionKind::Tab(_) => "▭",
SuggestionKind::Page => "◆",
SuggestionKind::Search | SuggestionKind::SearchSuggestion => icons::SEARCH,
SuggestionKind::Url => icons::OPEN_IN_NEW,
SuggestionKind::History => icons::HISTORY,
SuggestionKind::Bookmark => icons::STAR,
SuggestionKind::Tab(_) => icons::TAB,
SuggestionKind::Page => icons::TAB,
};
let detail = if matches!(s.kind, SuggestionKind::History | SuggestionKind::Bookmark | SuggestionKind::Tab(_)) { format!(" {}", util::ellipsize(&s.url, 70)) } else { String::new() };
let text = format!("{icon} {}{detail}", util::ellipsize(if s.title.is_empty() { &s.url } else { &s.title }, 80));
@ -563,7 +564,7 @@ fn bookmark_item(ui: &mut Ui, f: &mut Frame, node: &crate::store::bookmarks::Nod
}
},
None => {
ui.menu_button(format!("📁 {}", util::ellipsize(&node.title, 20)), |ui| {
ui.menu_button(format!("{} {}", icons::FOLDER, util::ellipsize(&node.title, 20)), |ui| {
folder_menu(ui, f, node);
});
},
@ -583,7 +584,7 @@ fn folder_menu(ui: &mut Ui, f: &mut Frame, folder: &crate::store::bookmarks::Nod
}
},
None => {
ui.menu_button(format!("📁 {}", util::ellipsize(&child.title, 40)), |ui| folder_menu(ui, f, child));
ui.menu_button(format!("{} {}", icons::FOLDER, util::ellipsize(&child.title, 40)), |ui| folder_menu(ui, f, child));
},
}
}
@ -603,10 +604,10 @@ pub fn app_bar(root: &mut Ui, f: &mut Frame) {
egui::Panel::top("app-bar").exact_size(32.0).show(root, |ui| {
ui.horizontal_centered(|ui| {
let can_back = f.tab().is_some_and(|t| t.can_go_back());
if ui.add_enabled(can_back, egui::Button::new("⬅").frame(false)).clicked() {
if ui.add_enabled(can_back, egui::Button::new(icons::ARROW_BACK).frame(false)).clicked() {
f.send(Command::Back);
}
if icon_button(ui, "⟳", "Reload").clicked() {
if icon_button(ui, icons::REFRESH, "Reload").clicked() {
f.send(Command::Reload { hard: false });
}
let title = f.tab().map(|t| t.display_title()).unwrap_or_default();
@ -615,11 +616,11 @@ pub fn app_bar(root: &mut Ui, f: &mut Frame) {
ui.label(RichText::new(util::host_of_str(&url)).weak().small());
}
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let menu = icon_button(ui, "☰", "Menu");
let menu = icon_button(ui, icons::MENU, "Menu");
if menu.clicked() {
f.ui.toggle(Flyout::Main, Some(menu.rect));
}
if icon_button(ui, "↗", "Open in the browser").clicked()
if icon_button(ui, icons::OPEN_IN_NEW, "Open in the browser").clicked()
&& let Some(url) = f.tab().map(|t| t.url.clone())
{
f.send(Command::Open { url, how: Disposition::NewForegroundTab, from: None });
@ -655,19 +656,19 @@ pub fn pip_window(root: &mut Ui, f: &mut Frame) {
egui::Frame::popup(ui.style()).fill(Color32::from_black_alpha(170)).show(ui, |ui| {
ui.horizontal(|ui| {
let white = |t: &str| RichText::new(t).color(Color32::WHITE).size(16.0);
if ui.add(egui::Button::new(white("⏪")).frame(false)).on_hover_text("Back 10 seconds").clicked() {
if ui.add(egui::Button::new(white(icons::FAST_REWIND)).frame(false)).on_hover_text("Back 10 seconds").clicked() {
f.send(Command::PipAct { action: "skip".into(), value: -10.0 });
}
if ui.add(egui::Button::new(white("⏯")).frame(false)).on_hover_text("Play or pause").clicked() {
if ui.add(egui::Button::new(white(icons::PLAY_PAUSE)).frame(false)).on_hover_text("Play or pause").clicked() {
f.send(Command::PipAct { action: "toggle".into(), value: 0.0 });
}
if ui.add(egui::Button::new(white("⏩")).frame(false)).on_hover_text("Forward 10 seconds").clicked() {
if ui.add(egui::Button::new(white(icons::FAST_FORWARD)).frame(false)).on_hover_text("Forward 10 seconds").clicked() {
f.send(Command::PipAct { action: "skip".into(), value: 10.0 });
}
if ui.add(egui::Button::new(white("🔇")).frame(false)).on_hover_text("Mute").clicked() {
if ui.add(egui::Button::new(white(icons::VOLUME_OFF)).frame(false)).on_hover_text("Mute").clicked() {
f.send(Command::PipAct { action: "mute".into(), value: 0.0 });
}
if ui.add(egui::Button::new(white("⤶")).frame(false)).on_hover_text("Back to the tab").clicked() {
if ui.add(egui::Button::new(white(icons::PIP_EXIT)).frame(false)).on_hover_text("Back to the tab").clicked() {
f.send(Command::ExitPip);
}
});

View file

@ -7,6 +7,7 @@ use super::Frame;
use crate::actions::{Command, DialogResult, PromptAnswer};
use crate::tabs::{Dialog, Prompt};
use crate::util;
use crate::ui::icons;
pub fn prompt_bars(root: &mut Ui, f: &mut Frame) {
let Some(tab) = f.tab() else { return };
@ -42,7 +43,7 @@ pub fn prompt_bars(root: &mut Ui, f: &mut Frame) {
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let mut answer = None;
if ui.small_button("✕").on_hover_text("Not now").clicked() {
if ui.small_button(icons::CLOSE).on_hover_text("Not now").clicked() {
answer = Some(PromptAnswer::Dismiss);
}
match kind {
@ -117,17 +118,17 @@ pub fn find_bar(root: &mut Ui, f: &mut Frame) {
}
let label = if find.text.is_empty() { String::new() } else if find.count == 0 { "No matches".into() } else { format!("{} of {}", find.index, find.count) };
ui.label(RichText::new(label).weak());
if ui.small_button("⬆").on_hover_text("Previous (Shift+Enter)").clicked() {
if ui.small_button(icons::ARROW_UPWARD).on_hover_text("Previous (Shift+Enter)").clicked() {
f.send(Command::Find { text: find.text.clone(), forward: false, case: find.case_sensitive });
}
if ui.small_button("⬇").on_hover_text("Next (Enter)").clicked() {
if ui.small_button(icons::ARROW_DOWNWARD).on_hover_text("Next (Enter)").clicked() {
f.send(Command::Find { text: find.text.clone(), forward: true, case: find.case_sensitive });
}
if ui.checkbox(&mut find.case_sensitive, "Match case").changed() {
f.send(Command::Find { text: find.text.clone(), forward: true, case: find.case_sensitive });
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.small_button("✕").clicked() {
if ui.small_button(icons::CLOSE).clicked() {
f.send(Command::FindClose);
}
});
@ -340,7 +341,7 @@ pub fn page_dialogs(ctx: &egui::Context, f: &mut Frame) {
}
for (id, user) in items {
let label = if user.is_empty() { "(no user name)".to_owned() } else { user.clone() };
if ui.button(format!("🔑 {label}")).clicked() {
if ui.button(format!("{} {label}", icons::KEY)).clicked() {
extra.push(Command::FillLogin { tab: tab_id, id: *id });
}
}
@ -374,13 +375,13 @@ pub fn page_dialogs(ctx: &egui::Context, f: &mut Frame) {
if kind == "card" {
for c in &vault.contents.cards {
let label = if c.nickname.is_empty() { c.masked() } else { format!("{} {}", c.nickname, c.masked()) };
if ui.button(format!("💳 {label}")).clicked() {
if ui.button(format!("{} {label}", icons::CREDIT_CARD)).clicked() {
extra.push(Command::FillCard { tab: tab_id, id: c.id });
}
}
} else {
for a in &vault.contents.addresses {
if ui.button(format!("🏠 {}, {}", a.name, a.street)).clicked() {
if ui.button(format!("{} {}, {}", icons::HOME, a.name, a.street)).clicked() {
extra.push(Command::FillAddress { tab: tab_id, id: a.id });
}
}

285
src/ui/icons.rs Normal file
View file

@ -0,0 +1,285 @@
//! Material Symbols Outlined code points (Apache 2.0), from tools/icons.txt. Generated by tools/icons.py:
//! edit the list and run the tool, don't edit this file.
pub const ARROW_BACK: &str = "\u{e5c4}";
pub const ARROW_FORWARD: &str = "\u{e5c8}";
pub const ARROW_UPWARD: &str = "\u{e5d8}";
pub const ARROW_DOWNWARD: &str = "\u{e5db}";
pub const REFRESH: &str = "\u{e5d5}";
pub const CLOSE: &str = "\u{e5cd}";
pub const HOME: &str = "\u{e9b2}";
pub const ADD: &str = "\u{e145}";
pub const REMOVE: &str = "\u{e15b}";
pub const CHECK: &str = "\u{e5ca}";
pub const CHEVRON_LEFT: &str = "\u{e5cb}";
pub const CHEVRON_RIGHT: &str = "\u{e5cc}";
pub const EXPAND_MORE: &str = "\u{e5cf}";
pub const EXPAND_LESS: &str = "\u{e5ce}";
pub const MORE_VERT: &str = "\u{e5d4}";
pub const MORE_HORIZ: &str = "\u{e5d3}";
pub const MENU: &str = "\u{e5d2}";
pub const OPEN_IN_NEW: &str = "\u{e89e}";
pub const UNDO: &str = "\u{e166}";
pub const FULLSCREEN: &str = "\u{e5d0}";
pub const FULLSCREEN_EXIT: &str = "\u{e5d1}";
pub const MINIMIZE: &str = "\u{e931}";
pub const CROP_SQUARE: &str = "\u{e3c6}";
pub const SELECT_WINDOW: &str = "\u{e6fa}";
pub const TAB: &str = "\u{e8d8}";
pub const TAB_GROUP: &str = "\u{f743}";
pub const DRAG_INDICATOR: &str = "\u{e945}";
pub const DRAG_PAN: &str = "\u{f71e}";
pub const SIDE_NAVIGATION: &str = "\u{e9e2}";
pub const SEARCH: &str = "\u{e8b6}";
pub const STAR: &str = "\u{f09a}";
pub const BOOKMARK: &str = "\u{e8e7}";
pub const BOOKMARK_ADD: &str = "\u{e598}";
pub const BOOKMARKS: &str = "\u{e98b}";
pub const HISTORY: &str = "\u{e8b3}";
pub const DOWNLOAD: &str = "\u{f090}";
pub const UPLOAD: &str = "\u{f09b}";
pub const FOLDER: &str = "\u{e2c7}";
pub const FOLDER_OPEN: &str = "\u{e2c8}";
pub const DELETE: &str = "\u{e92e}";
pub const SETTINGS: &str = "\u{e8b8}";
pub const SHIELD: &str = "\u{e9e0}";
pub const KEY: &str = "\u{e73c}";
pub const PASSWORD: &str = "\u{f042}";
pub const CREDIT_CARD: &str = "\u{e8a1}";
pub const QR_CODE_2: &str = "\u{e00a}";
pub const APPS: &str = "\u{e5c3}";
pub const GRID_VIEW: &str = "\u{e9b0}";
pub const CODE: &str = "\u{e86f}";
pub const BUG_REPORT: &str = "\u{e868}";
pub const MUSIC_NOTE: &str = "\u{e405}";
pub const LANGUAGE: &str = "\u{e894}";
pub const VPN_LOCK: &str = "\u{e62f}";
pub const SCREENSHOT_MONITOR: &str = "\u{ec08}";
pub const PICTURE_IN_PICTURE_ALT: &str = "\u{e911}";
pub const PIP_EXIT: &str = "\u{f70d}";
pub const INSTALL_DESKTOP: &str = "\u{eb71}";
pub const ZOOM_IN: &str = "\u{e8ff}";
pub const ZOOM_OUT: &str = "\u{e900}";
pub const SHARE: &str = "\u{e80d}";
pub const CHROME_READER_MODE: &str = "\u{e86d}";
pub const DOMINO_MASK: &str = "\u{f5e4}";
pub const EXTENSION: &str = "\u{e87b}";
pub const TRANSLATE: &str = "\u{e8e2}";
pub const PUBLIC: &str = "\u{e80b}";
pub const TRAVEL_EXPLORE: &str = "\u{e2db}";
pub const COOKIE: &str = "\u{eaac}";
pub const BLOCK: &str = "\u{f08c}";
pub const FILTER_LIST: &str = "\u{e152}";
pub const SYNC: &str = "\u{e627}";
pub const LINK: &str = "\u{e250}";
pub const CONTENT_COPY: &str = "\u{e14d}";
pub const EDIT: &str = "\u{f097}";
pub const PUSH_PIN: &str = "\u{f10d}";
pub const PRINT: &str = "\u{e8ad}";
pub const INFO: &str = "\u{e88e}";
pub const WARNING: &str = "\u{f083}";
pub const ERROR: &str = "\u{f8b6}";
pub const HELP: &str = "\u{e8fd}";
pub const LOCK: &str = "\u{e899}";
pub const LOCK_OPEN: &str = "\u{e898}";
pub const VISIBILITY: &str = "\u{e8f4}";
pub const VISIBILITY_OFF: &str = "\u{e8f5}";
pub const CHECK_CIRCLE: &str = "\u{f0be}";
pub const RADIO_BUTTON_UNCHECKED: &str = "\u{e836}";
pub const CIRCLE: &str = "\u{ef4a}";
pub const PROGRESS_ACTIVITY: &str = "\u{e9d0}";
pub const NOTIFICATIONS: &str = "\u{e7f5}";
pub const MIC: &str = "\u{e31d}";
pub const VIDEOCAM: &str = "\u{e04b}";
pub const PIN_DROP: &str = "\u{e55e}";
pub const BLUETOOTH: &str = "\u{e1a7}";
pub const SPORTS_ESPORTS: &str = "\u{ea28}";
pub const SPEED: &str = "\u{e9e4}";
pub const STORAGE: &str = "\u{e1db}";
pub const DEVICES: &str = "\u{e326}";
pub const DNS: &str = "\u{e875}";
pub const VERIFIED_USER: &str = "\u{f013}";
pub const PERSON: &str = "\u{f0d3}";
pub const ACCOUNT_CIRCLE: &str = "\u{f20b}";
pub const GROUP: &str = "\u{ea21}";
pub const LOGOUT: &str = "\u{e9ba}";
pub const SCHEDULE: &str = "\u{efd6}";
pub const TIMER: &str = "\u{e425}";
pub const PLAY_ARROW: &str = "\u{e037}";
pub const PAUSE: &str = "\u{e034}";
pub const PLAY_PAUSE: &str = "\u{f137}";
pub const STOP: &str = "\u{e047}";
pub const SKIP_PREVIOUS: &str = "\u{e045}";
pub const SKIP_NEXT: &str = "\u{e044}";
pub const FAST_REWIND: &str = "\u{e020}";
pub const FAST_FORWARD: &str = "\u{e01f}";
pub const SHUFFLE: &str = "\u{e043}";
pub const REPEAT: &str = "\u{e040}";
pub const VOLUME_UP: &str = "\u{e050}";
pub const VOLUME_DOWN: &str = "\u{e04d}";
pub const VOLUME_OFF: &str = "\u{e04f}";
pub const GRAPHIC_EQ: &str = "\u{e1b8}";
pub const IMAGE: &str = "\u{e3f4}";
pub const PALETTE: &str = "\u{e40a}";
pub const DARK_MODE: &str = "\u{e51c}";
pub const LIGHT_MODE: &str = "\u{e518}";
pub const CONTRAST: &str = "\u{eb37}";
pub const TUNE: &str = "\u{e429}";
pub const SHAPES: &str = "\u{e602}";
pub const WAVES: &str = "\u{e176}";
pub const BUBBLE_CHART: &str = "\u{e6dd}";
pub const SCATTER_PLOT: &str = "\u{e268}";
pub const BLUR_ON: &str = "\u{e3a5}";
pub const TEXTURE: &str = "\u{e421}";
pub const SUNNY: &str = "\u{e81a}";
pub const BEDTIME: &str = "\u{f159}";
pub const PARTLY_CLOUDY_DAY: &str = "\u{f172}";
pub const PARTLY_CLOUDY_NIGHT: &str = "\u{f174}";
pub const CLOUD: &str = "\u{f15c}";
pub const RAINY: &str = "\u{f176}";
pub const WEATHER_SNOWY: &str = "\u{e2cd}";
pub const THUNDERSTORM: &str = "\u{ebdb}";
pub const FOGGY: &str = "\u{e818}";
/// Every icon with its name, for the gallery.
pub const ALL: &[(&str, &str)] = &[
("arrow_back", ARROW_BACK),
("arrow_forward", ARROW_FORWARD),
("arrow_upward", ARROW_UPWARD),
("arrow_downward", ARROW_DOWNWARD),
("refresh", REFRESH),
("close", CLOSE),
("home", HOME),
("add", ADD),
("remove", REMOVE),
("check", CHECK),
("chevron_left", CHEVRON_LEFT),
("chevron_right", CHEVRON_RIGHT),
("expand_more", EXPAND_MORE),
("expand_less", EXPAND_LESS),
("more_vert", MORE_VERT),
("more_horiz", MORE_HORIZ),
("menu", MENU),
("open_in_new", OPEN_IN_NEW),
("undo", UNDO),
("fullscreen", FULLSCREEN),
("fullscreen_exit", FULLSCREEN_EXIT),
("minimize", MINIMIZE),
("crop_square", CROP_SQUARE),
("select_window", SELECT_WINDOW),
("tab", TAB),
("tab_group", TAB_GROUP),
("drag_indicator", DRAG_INDICATOR),
("drag_pan", DRAG_PAN),
("side_navigation", SIDE_NAVIGATION),
("search", SEARCH),
("star", STAR),
("bookmark", BOOKMARK),
("bookmark_add", BOOKMARK_ADD),
("bookmarks", BOOKMARKS),
("history", HISTORY),
("download", DOWNLOAD),
("upload", UPLOAD),
("folder", FOLDER),
("folder_open", FOLDER_OPEN),
("delete", DELETE),
("settings", SETTINGS),
("shield", SHIELD),
("key", KEY),
("password", PASSWORD),
("credit_card", CREDIT_CARD),
("qr_code_2", QR_CODE_2),
("apps", APPS),
("grid_view", GRID_VIEW),
("code", CODE),
("bug_report", BUG_REPORT),
("music_note", MUSIC_NOTE),
("language", LANGUAGE),
("vpn_lock", VPN_LOCK),
("screenshot_monitor", SCREENSHOT_MONITOR),
("picture_in_picture_alt", PICTURE_IN_PICTURE_ALT),
("pip_exit", PIP_EXIT),
("install_desktop", INSTALL_DESKTOP),
("zoom_in", ZOOM_IN),
("zoom_out", ZOOM_OUT),
("share", SHARE),
("chrome_reader_mode", CHROME_READER_MODE),
("domino_mask", DOMINO_MASK),
("extension", EXTENSION),
("translate", TRANSLATE),
("public", PUBLIC),
("travel_explore", TRAVEL_EXPLORE),
("cookie", COOKIE),
("block", BLOCK),
("filter_list", FILTER_LIST),
("sync", SYNC),
("link", LINK),
("content_copy", CONTENT_COPY),
("edit", EDIT),
("push_pin", PUSH_PIN),
("print", PRINT),
("info", INFO),
("warning", WARNING),
("error", ERROR),
("help", HELP),
("lock", LOCK),
("lock_open", LOCK_OPEN),
("visibility", VISIBILITY),
("visibility_off", VISIBILITY_OFF),
("check_circle", CHECK_CIRCLE),
("radio_button_unchecked", RADIO_BUTTON_UNCHECKED),
("circle", CIRCLE),
("progress_activity", PROGRESS_ACTIVITY),
("notifications", NOTIFICATIONS),
("mic", MIC),
("videocam", VIDEOCAM),
("pin_drop", PIN_DROP),
("bluetooth", BLUETOOTH),
("sports_esports", SPORTS_ESPORTS),
("speed", SPEED),
("storage", STORAGE),
("devices", DEVICES),
("dns", DNS),
("verified_user", VERIFIED_USER),
("person", PERSON),
("account_circle", ACCOUNT_CIRCLE),
("group", GROUP),
("logout", LOGOUT),
("schedule", SCHEDULE),
("timer", TIMER),
("play_arrow", PLAY_ARROW),
("pause", PAUSE),
("play_pause", PLAY_PAUSE),
("stop", STOP),
("skip_previous", SKIP_PREVIOUS),
("skip_next", SKIP_NEXT),
("fast_rewind", FAST_REWIND),
("fast_forward", FAST_FORWARD),
("shuffle", SHUFFLE),
("repeat", REPEAT),
("volume_up", VOLUME_UP),
("volume_down", VOLUME_DOWN),
("volume_off", VOLUME_OFF),
("graphic_eq", GRAPHIC_EQ),
("image", IMAGE),
("palette", PALETTE),
("dark_mode", DARK_MODE),
("light_mode", LIGHT_MODE),
("contrast", CONTRAST),
("tune", TUNE),
("shapes", SHAPES),
("waves", WAVES),
("bubble_chart", BUBBLE_CHART),
("scatter_plot", SCATTER_PLOT),
("blur_on", BLUR_ON),
("texture", TEXTURE),
("sunny", SUNNY),
("bedtime", BEDTIME),
("partly_cloudy_day", PARTLY_CLOUDY_DAY),
("partly_cloudy_night", PARTLY_CLOUDY_NIGHT),
("cloud", CLOUD),
("rainy", RAINY),
("weather_snowy", WEATHER_SNOWY),
("thunderstorm", THUNDERSTORM),
("foggy", FOGGY),
];

View file

@ -11,6 +11,7 @@ use crate::store::downloads::State as DlState;
use crate::store::settings::{VpnProvider, Visualizer};
use crate::tabs::Page;
use crate::util;
use crate::ui::icons;
/// A right-click menu on a page: Servo's own items plus Nacre's.
pub struct PageMenu {
@ -254,7 +255,7 @@ fn main_menu(ui: &mut Ui, f: &mut Frame) {
if ui.button("+").clicked() {
run = Some(Command::Zoom(1));
}
if ui.button("⛶").on_hover_text("Full screen (F11)").clicked() {
if ui.button(icons::FULLSCREEN).on_hover_text("Full screen (F11)").clicked() {
run = Some(Command::Action(Action::Fullscreen));
}
});
@ -308,7 +309,7 @@ fn downloads(ui: &mut Ui, f: &mut Frame) {
f.send(Command::ShowPage(Page::Downloads));
f.ui.flyout = None;
}
if ui.small_button("📂").on_hover_text("Open the downloads folder").clicked() {
if ui.small_button(icons::FOLDER_OPEN).on_hover_text("Open the downloads folder").clicked() {
f.send(Command::Download(DownloadOp::OpenFolder));
}
});
@ -376,34 +377,34 @@ pub fn download_row(ui: &mut Ui, f: &mut Frame, d: &crate::store::downloads::Dow
});
match d.state {
DlState::Running => {
if ui.small_button("⏸").on_hover_text("Pause").clicked() {
if ui.small_button(icons::PAUSE).on_hover_text("Pause").clicked() {
f.send(Command::Download(DownloadOp::Pause(d.id)));
}
if ui.small_button("✕").on_hover_text("Cancel").clicked() {
if ui.small_button(icons::CLOSE).on_hover_text("Cancel").clicked() {
f.send(Command::Download(DownloadOp::Cancel(d.id)));
}
},
DlState::Paused => {
if ui.small_button("▶").on_hover_text("Resume").clicked() {
if ui.small_button(icons::PLAY_ARROW).on_hover_text("Resume").clicked() {
f.send(Command::Download(DownloadOp::Resume(d.id)));
}
if ui.small_button("✕").on_hover_text("Cancel").clicked() {
if ui.small_button(icons::CLOSE).on_hover_text("Cancel").clicked() {
f.send(Command::Download(DownloadOp::Cancel(d.id)));
}
},
DlState::Failed => {
if ui.small_button("⟳").on_hover_text("Try again").clicked() {
if ui.small_button(icons::REFRESH).on_hover_text("Try again").clicked() {
f.send(Command::Download(DownloadOp::Retry(d.id)));
}
},
DlState::Done => {
if ui.small_button("📂").on_hover_text("Show in folder").clicked() {
if ui.small_button(icons::FOLDER_OPEN).on_hover_text("Show in folder").clicked() {
f.send(Command::Download(DownloadOp::ShowInFolder(d.id)));
}
},
_ => {},
}
if !d.active() && ui.small_button("🗑").on_hover_text("Remove from the list").clicked() {
if !d.active() && ui.small_button(icons::DELETE).on_hover_text("Remove from the list").clicked() {
f.send(Command::Download(DownloadOp::Remove(d.id)));
}
});
@ -563,19 +564,19 @@ fn media(ui: &mut Ui, f: &mut Frame) {
}
ui.horizontal(|ui| {
let big = |t: &str| RichText::new(t).size(18.0);
if ui.button(big("⏮")).on_hover_text("Previous").clicked() {
if ui.button(big(icons::SKIP_PREVIOUS)).on_hover_text("Previous").clicked() {
f.send(Command::Media { tab: now.tab, action: "prev".into(), value: 0.0 });
}
if ui.button(big(if state.paused { "▶" } else { "⏸" })).clicked() {
if ui.button(big(if state.paused { icons::PLAY_ARROW } else { icons::PAUSE })).clicked() {
f.send(Command::Media { tab: now.tab, action: "toggle".into(), value: 0.0 });
}
if ui.button(big("⏭")).on_hover_text("Next").clicked() {
if ui.button(big(icons::SKIP_NEXT)).on_hover_text("Next").clicked() {
f.send(Command::Media { tab: now.tab, action: "next".into(), value: 0.0 });
}
if ui.button(big(if now.muted { "🔇" } else { "🔊" })).on_hover_text("Mute tab").clicked() {
if ui.button(big(if now.muted { icons::VOLUME_OFF } else { icons::VOLUME_UP })).on_hover_text("Mute tab").clicked() {
f.send(Command::MuteTab(now.tab));
}
if state.is_video && ui.button(big("⧉")).on_hover_text("Picture in picture").clicked() {
if state.is_video && ui.button(big(icons::PICTURE_IN_PICTURE_ALT)).on_hover_text("Picture in picture").clicked() {
if let Some(i) = f.tabs.iter().position(|t| t.id == now.tab) {
f.send(Command::SelectTab(i));
}
@ -603,7 +604,7 @@ fn site_info(ui: &mut Ui, f: &mut Frame) {
let url = tab.url.clone();
let secure = url.starts_with("https://");
ui.label(RichText::new(&host).strong());
ui.label(if secure { "🔒 The connection is secure" } else { "⚠ The connection is not secure: others on the network can see and change this page" });
ui.label(if secure { format!("{} The connection is secure", icons::LOCK) } else { format!("{} The connection is not secure: others on the network can see and change this page", icons::WARNING) });
ui.separator();
ui.label(RichText::new("Permissions").strong());
let decisions = f.shared.permissions.borrow().for_host(&host);

View file

@ -4,7 +4,9 @@
pub mod chrome;
pub mod dialogs;
pub mod icons;
pub mod menus;
pub mod paint;
pub mod pages;
pub mod widgets;
@ -38,6 +40,33 @@ pub enum Flyout {
Apps,
}
static OUTFIT: &[u8] = include_bytes!("../../assets/fonts/Outfit[wght].ttf");
static SYMBOLS: &[u8] = include_bytes!("../../assets/fonts/MaterialSymbolsOutlined-Nacre.ttf");
/// The interface fonts: Outfit at each `theme::Weight` (one variable font), Material Symbols for `icons`, then
/// egui's own fonts for scripts Outfit lacks (Cyrillic, Greek). Set once per window.
pub fn fonts() -> egui::FontDefinitions {
use egui::{FontData, FontFamily, FontTweak};
use std::sync::Arc;
let mut fonts = egui::FontDefinitions::default();
let fallback: Vec<String> = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
let variable = |bytes: &'static [u8], coords: &[(&str, f32)]| Arc::new(FontData::from_static(bytes).tweak(FontTweak { coords: egui::epaint::text::VariationCoords::new(coords.iter().copied()), ..Default::default() }));
for weight in crate::theme::Weight::ALL {
let name = format!("outfit-{}", weight.wght());
fonts.font_data.insert(name.clone(), variable(OUTFIT, &[("wght", weight.wght())]));
let family = [name, "symbols".to_owned()].into_iter().chain(fallback.iter().cloned()).collect();
fonts.families.insert(weight.family(), family);
}
fonts.font_data.insert("symbols".to_owned(), variable(SYMBOLS, &[("FILL", 0.0)]));
fonts.font_data.insert("symbols-filled".to_owned(), variable(SYMBOLS, &[("FILL", 1.0)]));
fonts.families.insert(FontFamily::Name("icons".into()), vec!["symbols".to_owned()]);
fonts.families.insert(FontFamily::Name("icons-filled".into()), vec!["symbols-filled".to_owned()]);
if let Some(mono) = fonts.families.get_mut(&FontFamily::Monospace) {
mono.push("symbols".to_owned());
}
fonts
}
#[derive(Default)]
pub struct WindowUi {
pub palette: Option<Palette>,
@ -252,7 +281,7 @@ fn toasts(ctx: &egui::Context, f: &mut Frame) {
t.until = std::time::Instant::now();
}
}
if ui.small_button("✕").clicked()
if ui.small_button(icons::CLOSE).clicked()
&& let Some(t) = f.shared.toasts.borrow_mut().get_mut(i)
{
t.until = std::time::Instant::now();

View file

@ -8,6 +8,7 @@ use super::super::Frame;
use crate::actions::Command;
use crate::store::scripts::{self, Kind};
use crate::util;
use crate::ui::icons;
const NEW_SCRIPT: &str = "// ==UserScript==\n// @name My script\n// @match https://example.com/*\n// @run-at document-end\n// ==/UserScript==\n\n";
@ -101,7 +102,7 @@ pub fn draw(ui: &mut Ui, f: &mut Frame) {
f.send(Command::ReloadScripts);
}
ui.vertical(|ui| {
ui.label(RichText::new(format!("{} {}", if item.kind == Kind::Script { "📜" } else { "🎨" }, header.name)).strong());
ui.label(RichText::new(format!("{} {}", if item.kind == Kind::Script { icons::CODE } else { icons::PALETTE }, header.name)).strong());
let mut detail = header.matches.join(", ");
if !header.version.is_empty() {
detail = format!("v{} · {detail}", header.version);

View file

@ -9,6 +9,7 @@ use super::super::Frame;
use crate::actions::{Command, Disposition};
use crate::store::bookmarks::{Node, BAR};
use crate::util;
use crate::ui::icons;
pub fn draw(ui: &mut Ui, f: &mut Frame) {
page_column(ui, "bookmarks", 900.0, |ui| {
@ -45,7 +46,7 @@ pub fn draw(ui: &mut Ui, f: &mut Frame) {
let current = f.ui.pages.bookmarks_folder.unwrap_or(BAR);
ui.horizontal_wrapped(|ui| {
for (id, name) in &folders {
if ui.selectable_label(current == *id, format!("📁 {name}")).clicked() {
if ui.selectable_label(current == *id, format!("{} {name}", icons::FOLDER)).clicked() {
f.ui.pages.bookmarks_folder = Some(*id);
}
}
@ -143,7 +144,7 @@ fn bookmark_row(ui: &mut Ui, f: &mut Frame, node: &Node, parent: u64, index: usi
ui.label(RichText::new(util::host_of_str(url)).weak().small());
},
None => {
if ui.link(format!("📁 {}", node.title)).clicked() {
if ui.link(format!("{} {}", icons::FOLDER, node.title)).clicked() {
f.ui.pages.bookmarks_folder = Some(node.id);
}
ui.label(RichText::new(format!("{} items", node.children.len())).weak().small());
@ -164,10 +165,10 @@ fn bookmark_row(ui: &mut Ui, f: &mut Frame, node: &Node, parent: u64, index: usi
}
}
});
if index + 1 < count && ui.small_button("⬇").clicked() {
if index + 1 < count && ui.small_button(icons::ARROW_DOWNWARD).clicked() {
f.shared.bookmarks.borrow_mut().move_to(node.id, parent, Some(index + 1));
}
if index > 0 && ui.small_button("⬆").clicked() {
if index > 0 && ui.small_button(icons::ARROW_UPWARD).clicked() {
f.shared.bookmarks.borrow_mut().move_to(node.id, parent, Some(index - 1));
}
});

View file

@ -6,6 +6,7 @@ use super::super::menus::download_row;
use super::super::widgets::page_column;
use super::super::Frame;
use crate::actions::{Command, DownloadOp};
use crate::ui::icons;
pub fn draw(ui: &mut Ui, f: &mut Frame) {
page_column(ui, "downloads", 860.0, |ui| {
@ -15,7 +16,7 @@ pub fn draw(ui: &mut Ui, f: &mut Frame) {
if ui.button("Clear finished").clicked() {
f.send(Command::Download(DownloadOp::ClearFinished));
}
if ui.button("📂 Open folder").clicked() {
if ui.button(format!("{} Open folder", icons::FOLDER_OPEN)).clicked() {
f.send(Command::Download(DownloadOp::OpenFolder));
}
if ui.button("Settings").clicked() {

233
src/ui/pages/gallery.rs Normal file
View file

@ -0,0 +1,233 @@
//! nacre://gallery: every design token and widget in the current scheme, for checking the design system by eye
//! (tests/smoke/gallery.txt shoots it in light and dark). Not linked from the interface.
use egui::{Align2, Color32, Id, RichText, Sense, Ui, pos2, vec2};
use crate::theme::{self, Palette, Weight};
use crate::ui::{icons, paint, widgets};
use widgets::ButtonKind;
#[derive(Clone, Copy, PartialEq)]
enum Pick {
Few,
Some,
Lots,
}
#[derive(Clone)]
struct State {
switches: [bool; 2],
pick: Pick,
units: u8,
text: String,
toggle: bool,
moved: bool,
waving: bool,
}
impl Default for State {
fn default() -> Self {
State { switches: [true, false], pick: Pick::Some, units: 0, text: String::new(), toggle: true, moved: false, waving: false }
}
}
pub fn draw(ui: &mut Ui) {
let id = Id::new("gallery-state");
let mut state = ui.data_mut(|d| d.get_temp::<State>(id)).unwrap_or_default();
let p = theme::palette(ui.ctx());
widgets::page_column(ui, "gallery", 920.0, |ui| {
ui.label(RichText::new("Gallery").font(theme::font(theme::HEADLINE, Weight::Medium)));
ui.label(RichText::new("Design tokens and widgets in the current scheme. See docs/DESIGN.md, UI system.").color(p.on_surface_variant));
heading(ui, "Colour roles");
colours(ui, &p);
heading(ui, "Type");
ui.label(RichText::new("12:45:30").font(theme::font(theme::DISPLAY, Weight::Thin)).color(p.primary));
ui.label(RichText::new("Headline, medium").font(theme::font(theme::HEADLINE, Weight::Medium)));
ui.label(RichText::new("Title, medium").font(theme::font(theme::TITLE, Weight::Medium)));
ui.label(RichText::new("Body text in Outfit. Ünïcödé, Кириллица, Ελληνικά fall back to egui's font.").font(theme::font(theme::BODY, Weight::Regular)));
ui.label(RichText::new("Small text for descriptions and hints").font(theme::font(theme::SMALL, Weight::Regular)).color(p.on_surface_variant));
ui.horizontal(|ui| {
for w in Weight::ALL {
ui.label(RichText::new(format!("{w:?} {}", w.wght())).font(theme::font(theme::TITLE, w)));
}
});
heading(ui, "Shape");
ui.horizontal(|ui| {
for (name, r) in [("XS", theme::XS), ("S", theme::S), ("M", theme::M), ("L", theme::L), ("XL", theme::XL), ("FULL", theme::FULL)] {
let (rect, _) = ui.allocate_exact_size(vec2(96.0, 64.0), Sense::hover());
let radius = theme::radius(ui.ctx(), r).min(rect.height() / 2.0);
ui.painter().rect_filled(rect, theme::corner_radius(radius), p.secondary_container);
ui.painter().text(rect.center(), Align2::CENTER_CENTER, name, theme::font(theme::SMALL, Weight::Medium), p.on_secondary_container);
}
});
heading(ui, "Buttons");
ui.horizontal(|ui| {
for (kind, label) in [(ButtonKind::Filled, "Filled"), (ButtonKind::Tonal, "Tonal"), (ButtonKind::Outlined, "Outlined"), (ButtonKind::Text, "Text")] {
widgets::button(ui, kind, None, label);
}
});
ui.horizontal(|ui| {
widgets::button(ui, ButtonKind::Filled, Some(icons::DOWNLOAD), "Download");
widgets::button(ui, ButtonKind::Tonal, Some(icons::FOLDER_OPEN), "Open folder");
widgets::button(ui, ButtonKind::Outlined, Some(icons::SHARE), "Share");
widgets::button(ui, ButtonKind::Text, Some(icons::ADD), "Add shortcut");
});
ui.add_enabled_ui(false, |ui| {
ui.horizontal(|ui| {
for kind in [ButtonKind::Filled, ButtonKind::Tonal, ButtonKind::Outlined, ButtonKind::Text] {
widgets::button(ui, kind, None, "Disabled");
}
});
});
ui.horizontal(|ui| {
for key in ["back", "forward", "reload", "home", "bookmarks", "downloads", "history", "adblock", "settings"] {
widgets::icon_button(ui, widgets::glyph(key), key);
}
if widgets::icon_toggle(ui, icons::STAR, "Selected toggle", state.toggle).clicked() {
state.toggle = !state.toggle;
}
ui.add_enabled_ui(false, |ui| widgets::icon_button(ui, icons::DELETE, "Disabled"));
});
heading(ui, "Switches and segmented buttons");
ui.horizontal(|ui| {
widgets::switch(ui, &mut state.switches[0]);
widgets::switch(ui, &mut state.switches[1]);
ui.add_enabled_ui(false, |ui| {
let (mut on, mut off) = (true, false);
widgets::switch(ui, &mut on);
widgets::switch(ui, &mut off);
});
});
ui.add_space(theme::GAP_S);
widgets::segmented(ui, &mut state.pick, &[(Pick::Few, "Few"), (Pick::Some, "Some"), (Pick::Lots, "Lots")]);
ui.add_space(theme::GAP_S);
widgets::segmented(ui, &mut state.units, &[(0, "Auto"), (1, "°C"), (2, "°F")]);
heading(ui, "Field");
widgets::text_field(ui, &mut state.text, "Search or type a URL", 420.0);
widgets::section(ui, "Card with rows");
widgets::card(ui, |ui| {
widgets::switch_row(ui, "Block ads", "Uses the filter lists below", &mut state.switches[0]);
widgets::switch_row(ui, "Send Do Not Track", "", &mut state.switches[1]);
widgets::row(ui, "Amount", "How many shapes drift behind the page", |ui| widgets::segmented(ui, &mut state.pick, &[(Pick::Few, "Few"), (Pick::Some, "Some"), (Pick::Lots, "Lots")]));
widgets::link_row(ui, "Filter lists", "3 of 9 on");
widgets::link_row(ui, "Site settings", "Location, camera, microphone and other permissions");
});
heading(ui, "Motion");
ui.horizontal(|ui| {
if widgets::button(ui, ButtonKind::Tonal, Some(icons::ARROW_FORWARD), "Move").clicked() {
state.moved = !state.moved;
}
ui.label(RichText::new("Fast, default and slow springs").color(p.on_surface_variant));
});
for (i, (name, spring)) in [("Fast", theme::FAST), ("Default", theme::DEFAULT), ("Slow", theme::SLOW), ("Effect", theme::EFFECT)].into_iter().enumerate() {
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width().min(560.0), 28.0), Sense::hover());
let t = theme::spring(ui.ctx(), Id::new(("gallery-spring", i)), if state.moved { 1.0 } else { 0.0 }, spring);
ui.painter().rect_filled(rect, theme::corner_radius(14.0), p.surface_container);
let x = egui::lerp((rect.left() + 40.0)..=(rect.right() - 40.0), t);
ui.painter().rect_filled(egui::Rect::from_center_size(pos2(x, rect.center().y), vec2(64.0, 20.0)), theme::corner_radius(10.0), p.primary);
ui.painter().text(pos2(x, rect.center().y), Align2::CENTER_CENTER, name, theme::font(theme::SMALL, Weight::Medium), p.on_primary);
ui.add_space(theme::GAP_XS);
}
heading(ui, "Expressive shapes");
ui.horizontal(|ui| {
widgets::switch(ui, &mut state.waving);
ui.label("Animate the wave");
});
let phase = if state.waving {
ui.ctx().request_repaint();
(ui.input(|i| i.time) * 4.0) as f32
} else {
0.0
};
let amplitude = theme::spring(ui.ctx(), Id::new("gallery-wave"), if state.waving { 3.0 } else { 0.0 }, theme::DEFAULT);
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width().min(560.0), 24.0), Sense::hover());
paint::wavy_progress(ui.painter(), rect, 0.6, amplitude.max(if state.waving { 0.0 } else { 3.0 }), phase, &p);
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width().min(560.0), 24.0), Sense::hover());
paint::wavy_progress(ui.painter(), rect, 0.3, 0.0, 0.0, &p);
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width().min(560.0), 24.0), Sense::hover());
paint::wavy_line(ui.painter(), rect.left(), rect.right(), rect.center().y, 4.0, 24.0, phase, egui::Stroke::new(2.0, p.tertiary));
ui.add_space(theme::GAP_M);
ui.horizontal(|ui| {
let (rect, _) = ui.allocate_exact_size(vec2(140.0, 140.0), Sense::hover());
let spin = if state.waving { phase * 0.1 } else { 0.0 };
paint::cookie(ui.painter(), rect.center(), 64.0, 9, spin, p.primary_container, egui::Stroke::NONE);
widgets::icon(ui, rect.center(), icons::MUSIC_NOTE, theme::ICON_LARGE, true, p.on_primary_container);
let (rect, _) = ui.allocate_exact_size(vec2(140.0, 140.0), Sense::hover());
paint::cookie(ui.painter(), rect.center(), 64.0, 12, 0.0, p.tertiary_container, egui::Stroke::new(2.0, p.tertiary));
let (rect, _) = ui.allocate_exact_size(vec2(200.0, 140.0), Sense::hover());
let card = rect.shrink(16.0);
let radius = theme::radius(ui.ctx(), theme::L);
paint::shadow(ui.painter(), card, radius, p.dark);
ui.painter().rect_filled(card, theme::corner_radius(radius), p.surface_container_high);
ui.painter().text(card.center(), Align2::CENTER_CENTER, "Floating surface", theme::font(theme::BODY, Weight::Medium), p.on_surface);
});
heading(ui, "Icons");
let columns = ((ui.available_width() / 112.0).floor() as usize).max(1);
egui::Grid::new("gallery-icons").spacing(vec2(theme::GAP_XS, theme::GAP_XS)).show(ui, |ui| {
for (i, (name, glyph)) in icons::ALL.iter().enumerate() {
let (rect, _) = ui.allocate_exact_size(vec2(108.0, 52.0), Sense::hover());
widgets::icon(ui, pos2(rect.center().x, rect.top() + 16.0), glyph, theme::ICON, false, p.on_surface);
let name = crate::util::ellipsize(name, 16);
ui.painter().text(pos2(rect.center().x, rect.bottom() - 10.0), Align2::CENTER_CENTER, name, theme::font(10.0, Weight::Regular), p.on_surface_variant);
if (i + 1) % columns == 0 {
ui.end_row();
}
}
});
});
ui.data_mut(|d| d.insert_temp(id, state));
}
fn heading(ui: &mut Ui, text: &str) {
ui.add_space(theme::GAP_XL);
ui.label(RichText::new(text).font(theme::font(theme::TITLE, Weight::Medium)));
ui.add_space(theme::GAP_S);
}
fn colours(ui: &mut Ui, p: &Palette) {
let pairs: [(&str, Color32, Color32); 21] = [
("primary", p.primary, p.on_primary),
("primary container", p.primary_container, p.on_primary_container),
("secondary", p.secondary, p.on_secondary),
("secondary container", p.secondary_container, p.on_secondary_container),
("tertiary", p.tertiary, p.on_tertiary),
("tertiary container", p.tertiary_container, p.on_tertiary_container),
("error", p.error, p.on_error),
("error container", p.error_container, p.on_error_container),
("surface dim", p.surface_dim, p.on_surface),
("surface", p.surface, p.on_surface),
("surface bright", p.surface_bright, p.on_surface),
("inverse surface", p.inverse_surface, p.inverse_on_surface),
("container lowest", p.surface_container_lowest, p.on_surface),
("container low", p.surface_container_low, p.on_surface),
("container", p.surface_container, p.on_surface),
("container high", p.surface_container_high, p.on_surface),
("container highest", p.surface_container_highest, p.on_surface_variant),
("outline", p.outline, p.surface),
("outline variant", p.outline_variant, p.on_surface),
("warning", p.warning, p.surface),
("success", p.success, p.surface),
];
let columns = ((ui.available_width() / 180.0).floor() as usize).max(1);
egui::Grid::new("gallery-colours").spacing(vec2(theme::GAP_S, theme::GAP_S)).show(ui, |ui| {
for (i, (name, fill, on)) in pairs.iter().enumerate() {
let (rect, _) = ui.allocate_exact_size(vec2(172.0, 56.0), Sense::hover());
ui.painter().rect_filled(rect, theme::corner_radius(theme::radius(ui.ctx(), theme::M)), *fill);
ui.painter().text(rect.left_top() + vec2(12.0, 10.0), Align2::LEFT_TOP, *name, theme::font(theme::SMALL, Weight::Medium), *on);
ui.painter().text(rect.left_bottom() + vec2(12.0, -10.0), Align2::LEFT_BOTTOM, theme::to_hex(*fill), theme::font(theme::SMALL, Weight::Regular), *on);
if (i + 1) % columns == 0 {
ui.end_row();
}
}
});
}

View file

@ -7,6 +7,7 @@ use super::super::Frame;
use crate::actions::{Command, Disposition};
use crate::tabs::Page;
use crate::util;
use crate::ui::icons;
pub fn draw(ui: &mut Ui, f: &mut Frame) {
page_column(ui, "history", 860.0, |ui| {
@ -51,7 +52,7 @@ pub fn draw(ui: &mut Ui, f: &mut Frame) {
}
ui.label(RichText::new(util::host_of_str(&visit.url)).weak().small());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.menu_button("⋮", |ui| {
ui.menu_button(icons::MORE_VERT, |ui| {
if ui.button("Open in new tab").clicked() {
f.send(Command::Open { url: visit.url.clone(), how: Disposition::NewBackgroundTab, from: None });
ui.close();

View file

@ -10,6 +10,7 @@ use crate::store::permissions::{Decision, Kind};
use crate::store::settings::{ColourSource, DohProvider, ThemeMode};
use crate::tabs::Page;
use crate::util;
use crate::ui::icons;
pub fn site_settings(ui: &mut Ui, f: &mut Frame, host: &str) {
page_column(ui, "site-settings", 860.0, |ui| {
@ -26,8 +27,8 @@ pub fn site_settings(ui: &mut Ui, f: &mut Frame, host: &str) {
ui.label(RichText::new("No sites yet.").weak());
}
for h in hosts.iter().filter(|h| q.is_empty() || h.contains(&q)) {
let summary: Vec<String> = all.iter().filter(|(x, ..)| x == h).map(|(_, k, d)| format!("{} {}", k.label(), if *d == Decision::Allow { "✓" } else { "✕" })).collect();
if row(ui, h, &summary.join(" · "), |ui| ui.button("›").clicked()) {
let summary: Vec<String> = all.iter().filter(|(x, ..)| x == h).map(|(_, k, d)| format!("{} {}", k.label(), if *d == Decision::Allow { icons::CHECK } else { icons::CLOSE })).collect();
if row(ui, h, &summary.join(" · "), |ui| ui.button(icons::CHEVRON_RIGHT).clicked()) {
f.send(Command::ShowPage(Page::SiteSettings(h.clone())));
}
}

View file

@ -4,6 +4,7 @@ pub mod apps;
pub mod bookmarks;
pub mod devtools;
pub mod downloads;
pub mod gallery;
pub mod history;
pub mod misc;
pub mod newtab;
@ -75,6 +76,7 @@ pub fn draw(ui: &mut Ui, f: &mut Frame, page: &Page) {
Page::Welcome => misc::welcome(ui, f),
Page::TaskManager => misc::task_manager(ui, f),
Page::DevTools => devtools::draw(ui, f),
Page::Gallery => gallery::draw(ui),
Page::Source(url) => misc::source(ui, f, url),
Page::Error(url, why) => misc::error(ui, f, url, why),
}

View file

@ -6,6 +6,7 @@ use egui::{RichText, Ui, Vec2};
use super::super::Frame;
use crate::actions::{Command, Disposition};
use crate::util;
use crate::ui::icons;
pub fn draw(ui: &mut Ui, f: &mut Frame) {
let ntp = f.shared.settings.borrow().ntp.clone();
@ -48,7 +49,7 @@ pub fn draw(ui: &mut Ui, f: &mut Frame) {
let (hour, suffix) = if ntp.clock24 { (t.hour, "") } else { (if t.hour % 12 == 0 { 12 } else { t.hour % 12 }, if t.hour < 12 { " AM" } else { " PM" }) };
let text = if ntp.seconds { format!("{hour}:{:02}:{:02}{suffix}", t.minute, t.second) } else { format!("{hour}:{:02}{suffix}", t.minute) };
ui.vertical_centered(|ui| {
ui.label(RichText::new(text).size(64.0).strong());
ui.label(RichText::new(text).font(crate::theme::font(crate::theme::DISPLAY, crate::theme::Weight::Thin)).color(palette.primary));
ui.label(RichText::new(util::format_day_heading(now)).weak());
});
ui.ctx().request_repaint_after(std::time::Duration::from_secs(if ntp.seconds { 1 } else { 15 }));
@ -93,7 +94,7 @@ pub fn draw(ui: &mut Ui, f: &mut Frame) {
f.send(Command::Open { url: url.clone(), how: Disposition::NewBackgroundTab, from: None });
}
}
if ui.add(egui::Button::new("➕\nAdd").min_size(Vec2::new(90.0, 64.0))).on_hover_text("Edit shortcuts in settings").clicked() {
if ui.add(egui::Button::new(format!("{}\nAdd", icons::ADD)).min_size(Vec2::new(90.0, 64.0))).on_hover_text("Edit shortcuts in settings").clicked() {
f.send(Command::ShowPage(crate::tabs::Page::Settings("newtab".into())));
}
});
@ -103,19 +104,19 @@ pub fn draw(ui: &mut Ui, f: &mut Frame) {
if let Some(now) = now {
super::super::widgets::card(ui, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new("♫").size(22.0).color(palette.accent));
ui.label(RichText::new(icons::MUSIC_NOTE).size(22.0).color(palette.accent));
ui.vertical(|ui| {
ui.label(RichText::new(util::ellipsize(if now.state.title.is_empty() { &now.title } else { &now.state.title }, 60)).strong());
ui.label(RichText::new(if now.state.artist.is_empty() { now.host.clone() } else { now.state.artist.clone() }).weak());
});
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("⏭").clicked() {
if ui.button(icons::SKIP_NEXT).clicked() {
f.send(Command::Media { tab: now.tab, action: "next".into(), value: 0.0 });
}
if ui.button(if now.state.paused { "▶" } else { "⏸" }).clicked() {
if ui.button(if now.state.paused { icons::PLAY_ARROW } else { icons::PAUSE }).clicked() {
f.send(Command::Media { tab: now.tab, action: "toggle".into(), value: 0.0 });
}
if ui.button("⏮").clicked() {
if ui.button(icons::SKIP_PREVIOUS).clicked() {
f.send(Command::Media { tab: now.tab, action: "prev".into(), value: 0.0 });
}
});
@ -162,7 +163,7 @@ pub fn draw(ui: &mut Ui, f: &mut Frame) {
f.shared.reading.borrow_mut().set_read(&item.url, true);
f.send(Command::Navigate(item.url.clone()));
}
if ui.small_button("✓").on_hover_text("Mark as read").clicked() {
if ui.small_button(icons::CHECK).on_hover_text("Mark as read").clicked() {
f.shared.reading.borrow_mut().set_read(&item.url, true);
}
});
@ -204,13 +205,13 @@ fn initial(title: &str) -> String {
/// WMO weather codes (Open-Meteo).
fn weather_glyph(code: u32) -> &'static str {
match code {
0 => "☀",
1..=3 => "⛅",
45 | 48 => "🌫",
51..=67 | 80..=82 => "🌧",
71..=77 | 85 | 86 => "🌨",
95..=99 => "⛈",
_ => "☁",
0 => icons::SUNNY,
1..=3 => icons::PARTLY_CLOUDY_DAY,
45 | 48 => icons::FOGGY,
51..=67 | 80..=82 => icons::RAINY,
71..=77 | 85 | 86 => icons::WEATHER_SNOWY,
95..=99 => icons::THUNDERSTORM,
_ => icons::CLOUD,
}
}

View file

@ -12,6 +12,7 @@ use crate::keys::{Action, Shortcut};
use crate::store::settings::*;
use crate::tabs::Page;
use crate::util;
use crate::ui::icons;
const SECTIONS: &[(&str, &str)] = &[
("general", "General"),
@ -67,7 +68,7 @@ pub fn draw(ui: &mut Ui, f: &mut Frame, requested: &str) {
}
if let Some((_, label)) = SUBPAGES.iter().find(|(k, _)| *k == f.ui.pages.settings_section) {
ui.separator();
ui.label(RichText::new(format!("› {label}")).strong());
ui.label(RichText::new(format!("{} {label}", icons::CHEVRON_RIGHT)).strong());
}
});
let section = f.ui.pages.settings_section.clone();
@ -157,25 +158,25 @@ fn general(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
row(ui, "On startup", "", |ui| segmented(ui, &mut s.startup.mode, StartupMode::ALL));
row(ui, "Home page", "Used by the Home button and the Home startup option", |ui| ui.add(egui::TextEdit::singleline(&mut s.startup.home_url).desired_width(240.0)));
let engine = s.search_engine_name();
if row(ui, "Search engine", "Used in the address bar and on the new tab page", |ui| ui.button(format!("🔍 {engine}")).clicked()) {
if row(ui, "Search engine", "Used in the address bar and on the new tab page", |ui| ui.button(format!("{} {engine}", icons::SEARCH)).clicked()) {
open(f, "search");
}
let profiles = f.shared.paths.profile_list().profiles.len();
if row(ui, "Profiles", &format!("Using {} · {profiles} profile{}", f.shared.paths.profile, if profiles == 1 { "" } else { "s" }), |ui| ui.button("›").clicked()) {
if row(ui, "Profiles", &format!("Using {} · {profiles} profile{}", f.shared.paths.profile, if profiles == 1 { "" } else { "s" }), |ui| ui.button(icons::CHEVRON_RIGHT).clicked()) {
open(f, "profiles");
}
let langs = if s.spell.langs.is_empty() { crate::spell::system_language() } else { s.spell.langs.join(", ") };
if row(ui, "Spell check", &if s.spell.enabled { langs } else { "Off".into() }, |ui| ui.button("›").clicked()) {
if row(ui, "Spell check", &if s.spell.enabled { langs } else { "Off".into() }, |ui| ui.button(icons::CHEVRON_RIGHT).clicked()) {
open(f, "spell");
}
let custom = s.keys.len();
if row(ui, "Keyboard shortcuts", &if custom == 0 { "Default keys".to_owned() } else { format!("{custom} changed") }, |ui| ui.button("›").clicked()) {
if row(ui, "Keyboard shortcuts", &if custom == 0 { "Default keys".to_owned() } else { format!("{custom} changed") }, |ui| ui.button(icons::CHEVRON_RIGHT).clicked()) {
open(f, "keys");
}
if row(ui, "Import from another browser", "Bookmarks, history and settings from Chrome, Firefox, Edge, Brave…", |ui| ui.button("›").clicked()) {
if row(ui, "Import from another browser", "Bookmarks, history and settings from Chrome, Firefox, Edge, Brave…", |ui| ui.button(icons::CHEVRON_RIGHT).clicked()) {
open(f, "import");
}
if row(ui, "New tab page", &format!("{} shortcuts on the new tab page", s.ntp.shortcuts.len()), |ui| ui.button("›").clicked()) {
if row(ui, "New tab page", &format!("{} shortcuts on the new tab page", s.ntp.shortcuts.len()), |ui| ui.button(icons::CHEVRON_RIGHT).clicked()) {
open(f, "newtab");
}
switch_row(ui, "Custom title bar", "Frameless window with Nacre's own controls (restart to apply)", &mut s.ui.custom_title_bar);
@ -379,7 +380,7 @@ fn privacy(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
}
});
}
if row(ui, "Site settings", "Location, camera, microphone, notifications, pop-ups and other permissions", |ui| ui.button("›").clicked()) {
if row(ui, "Site settings", "Location, camera, microphone, notifications, pop-ups and other permissions", |ui| ui.button(icons::CHEVRON_RIGHT).clicked()) {
open(f, "permissions");
}
if row(ui, "Delete browsing data", "History, cookies, cache and more", |ui| ui.button("Delete…").clicked()) {
@ -431,7 +432,7 @@ fn adblock(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
f.send(Command::UpdateFilterLists);
}
let on = s.adblock.lists.len();
if row(ui, "Filter lists", &format!("{on} of {} on", crate::adblock::LISTS.len()), |ui| ui.button("›").clicked()) {
if row(ui, "Filter lists", &format!("{on} of {} on", crate::adblock::LISTS.len()), |ui| ui.button(icons::CHEVRON_RIGHT).clicked()) {
open(f, "lists");
}
switch_row(ui, "Hide ad leftovers", "Cosmetic (##) rules from the lists", &mut s.adblock.cosmetic);
@ -519,7 +520,7 @@ fn downloads(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
section(ui, "Downloads");
card(ui, |ui| {
let dir = s.downloads.dir.display().to_string();
if row(ui, "Save to", &dir, |ui| ui.button("📂 Change").clicked())
if row(ui, "Save to", &dir, |ui| ui.button(format!("{} Change", icons::FOLDER_OPEN)).clicked())
&& let Some(path) = rfd::FileDialog::new().set_directory(&s.downloads.dir).pick_folder()
{
s.downloads.dir = path;
@ -527,7 +528,7 @@ fn downloads(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
switch_row(ui, "Ask where to save each file", "", &mut s.downloads.ask);
switch_row(ui, "Show downloads when they start", "", &mut s.downloads.auto_open);
let using = if s.downloads.manager == "builtin" { "Nacre".to_owned() } else { crate::net::dlm::by_key(&s.downloads.manager).map(|m| m.name.to_owned()).unwrap_or_default() };
if row(ui, "Download managers", &format!("New downloads go to {using}"), |ui| ui.button("›").clicked()) {
if row(ui, "Download managers", &format!("New downloads go to {using}"), |ui| ui.button(icons::CHEVRON_RIGHT).clicked()) {
open(f, "managers");
}
});
@ -601,7 +602,7 @@ fn media(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
row(ui, "Visualizer", cava, |ui| segmented(ui, &mut s.media.visualizer, Visualizer::ALL));
switch_row(ui, "Spin artwork while playing", "", &mut s.media.spin);
let status = if s.rpc.enabled { f.shared.presence_status.borrow().clone() } else { "Off".into() };
if row(ui, "Discord Rich Presence", &status, |ui| ui.button("›").clicked()) {
if row(ui, "Discord Rich Presence", &status, |ui| ui.button(icons::CHEVRON_RIGHT).clicked()) {
open(f, "discord");
}
row(ui, "Protected content (Widevine)", "Netflix, Hulu, Spotify and other DRM video can't play: the Servo engine has no DRM support", |ui| ui.add_enabled(false, egui::Button::new("Not available")));
@ -682,7 +683,7 @@ fn about(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
row(ui, "Colour", &format!("{} · {}", crate::theme::to_hex(accent), if dark { "dark" } else { "light" }), |_| ());
let p = &f.shared.paths;
row(ui, "Profile", &format!("{}\n{}\n{}", p.config.display(), p.data.display(), p.cache.display()), |ui| {
if ui.button("📂").on_hover_text("Open the data folder").clicked() {
if ui.button(icons::FOLDER_OPEN).on_hover_text("Open the data folder").clicked() {
util::open_external(&p.data.to_string_lossy());
}
});
@ -904,10 +905,10 @@ fn newtab(ui: &mut Ui, f: &mut Frame, s: &mut Settings) {
switch(ui, on);
ui.label(element_label(name));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if i + 1 < len && ui.small_button("⬇").clicked() {
if i + 1 < len && ui.small_button(icons::ARROW_DOWNWARD).clicked() {
swap = Some((i, i + 1));
}
if i > 0 && ui.small_button("⬆").clicked() {
if i > 0 && ui.small_button(icons::ARROW_UPWARD).clicked() {
swap = Some((i, i - 1));
}
});

115
src/ui/paint.rs Normal file
View file

@ -0,0 +1,115 @@
//! Drawing helpers for the Material 3 Expressive shapes: the scalloped "cookie", wavy lines and wavy progress.
//! Each call builds one point list and hands it to the painter; nothing is kept between frames.
use std::f32::consts::TAU;
use egui::{Color32, Mesh, Painter, Pos2, Rect, Shape, Stroke, TextureId, pos2, vec2};
use crate::theme::Palette;
/// Points around a cookie: a circle of `radius` with `lobes` rounded scallops cut `depth` (0..1 of the radius)
/// deep, turned by `rotation` radians.
pub fn cookie_points(center: Pos2, radius: f32, lobes: u32, depth: f32, rotation: f32) -> Vec<Pos2> {
let count = (lobes * 16).clamp(48, 192);
(0..count)
.map(|i| {
let a = i as f32 / count as f32 * TAU;
let r = radius * (1.0 - depth * (1.0 - (lobes as f32 * (a - rotation)).cos()) / 2.0);
center + vec2(a.cos(), a.sin()) * r
})
.collect()
}
/// A filled cookie with an optional outline. The fill is a fan from the centre (cookies are star-shaped around it,
/// which egui's convex fill can't assume); a hairline in the fill colour smooths its edge.
pub fn cookie(painter: &Painter, center: Pos2, radius: f32, lobes: u32, rotation: f32, fill: Color32, stroke: Stroke) {
let points = cookie_points(center, radius, lobes, COOKIE_DEPTH, rotation);
painter.add(fan(&points, center, fill, None, radius));
let edge = if stroke.width > 0.0 { stroke } else { Stroke::new(1.0, fill) };
painter.add(Shape::closed_line(points, edge));
}
/// An image (album art, a site icon) cut to a cookie.
pub fn cookie_image(painter: &Painter, texture: TextureId, center: Pos2, radius: f32, lobes: u32, rotation: f32) {
let points = cookie_points(center, radius, lobes, COOKIE_DEPTH, rotation);
painter.add(fan(&points, center, Color32::WHITE, Some(texture), radius));
}
/// Scallop depth of the cookie (M3 "cookie" shapes are shallow).
pub const COOKIE_DEPTH: f32 = 0.1;
fn fan(points: &[Pos2], center: Pos2, color: Color32, texture: Option<TextureId>, radius: f32) -> Mesh {
let mut mesh = texture.map(Mesh::with_texture).unwrap_or_default();
// Without a texture the vertices keep egui's white-pixel UV; with one, the image maps onto the circle.
let uv = |p: Pos2| pos2(0.5 + (p.x - center.x) / (2.0 * radius), 0.5 + (p.y - center.y) / (2.0 * radius));
for (i, p) in std::iter::once(&center).chain(points).enumerate() {
mesh.colored_vertex(*p, color);
if texture.is_some() {
mesh.vertices[i].uv = uv(*p);
}
}
for i in 0..points.len() {
let next = (i + 1) % points.len();
mesh.add_triangle(0, i as u32 + 1, next as u32 + 1);
}
mesh
}
/// A sine line from `x0` to `x1` around `y`, with round ends. `phase` (radians) moves the wave; an amplitude of 0
/// draws a straight line, so animating the amplitude flattens it smoothly.
pub fn wavy_line(painter: &Painter, x0: f32, x1: f32, y: f32, amplitude: f32, wavelength: f32, phase: f32, stroke: Stroke) {
if x1 <= x0 {
return;
}
let wave = |x: f32| y + amplitude * ((x - x0) / wavelength * TAU + phase).sin();
let steps = ((x1 - x0) / 2.0).ceil().max(1.0) as usize;
let points: Vec<Pos2> = (0..=steps).map(|i| {
let x = x0 + (x1 - x0) * i as f32 / steps as f32;
pos2(x, wave(x))
}).collect();
let ends = [points[0], points[steps]];
painter.add(Shape::line(points, stroke));
for p in ends {
painter.circle_filled(p, stroke.width / 2.0, stroke.color);
}
}
/// Wavy progress (M3 Expressive, linear): the done part as a wave in primary, a gap, the rest as a flat track,
/// and a stop dot at the end. `fraction` is 0..1, `amplitude` in points (0 = flat, e.g. when paused).
pub fn wavy_progress(painter: &Painter, rect: Rect, fraction: f32, amplitude: f32, phase: f32, p: &Palette) {
const THICK: f32 = 4.0;
const GAP: f32 = 4.0;
let y = rect.center().y;
let (left, right) = (rect.left() + THICK / 2.0, rect.right() - THICK / 2.0);
let split = left + (right - left) * fraction.clamp(0.0, 1.0);
wavy_line(painter, left, split, y, amplitude, 40.0, phase, Stroke::new(THICK, p.primary));
let track_start = if fraction > 0.0 { split + GAP + THICK } else { left };
if track_start < right {
painter.line_segment([pos2(track_start, y), pos2(right, y)], Stroke::new(THICK, p.secondary_container));
painter.circle_filled(pos2(track_start, y), THICK / 2.0, p.secondary_container);
painter.circle_filled(pos2(right, y), THICK / 2.0, p.secondary_container);
painter.circle_filled(pos2(right, y), THICK / 2.0 - 0.5, p.primary);
}
}
/// The soft shadow under a floating surface (menus, dialogs, cards that lift). egui blurs it in the tessellator.
pub fn shadow(painter: &Painter, rect: Rect, radius: f32, dark: bool) {
let shadow = egui::Shadow { offset: [0, 3], blur: 14, spread: 0, color: Color32::from_black_alpha(if dark { 110 } else { 46 }) };
painter.add(shadow.as_shape(rect, crate::theme::corner_radius(radius)));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cookie_stays_between_inner_and_outer_radius() {
let c = pos2(10.0, 10.0);
let points = cookie_points(c, 50.0, 9, COOKIE_DEPTH, 0.3);
assert!(points.len() >= 48);
for p in &points {
let r = (*p - c).length();
assert!((45.0 - 1e-3..=50.0 + 1e-3).contains(&r), "radius {r}");
}
}
}

View file

@ -1,64 +1,262 @@
//! Small building blocks used across the interface.
//! Small building blocks used across the interface, drawn from the theme tokens (docs/DESIGN.md "UI system").
//! Every control answers hover (a state layer), press (a squeeze), keyboard focus (a ring) and disabled.
use egui::{Response, RichText, Sense, Ui, Vec2};
use egui::{Align2, Color32, CornerRadius, Id, Rect, Response, RichText, Sense, Shape, Stroke, StrokeKind, Ui, Vec2, pos2, vec2};
/// A square button with a glyph and a tooltip.
use super::icons;
use crate::theme::{self, Palette, Weight};
/// How a control looks while the pointer and keyboard work on it, each 0..1 and animated.
struct Interaction {
hover: f32,
press: f32,
focus: bool,
enabled: bool,
}
fn interaction(ui: &Ui, response: &Response) -> Interaction {
let ctx = ui.ctx();
let enabled = response.enabled();
let hover = theme::effect(ctx, response.id.with("hover"), enabled && response.hovered());
let press = theme::spring(ctx, response.id.with("press"), if enabled && response.is_pointer_button_down_on() { 1.0 } else { 0.0 }, theme::FAST);
Interaction { hover, press, focus: response.has_focus(), enabled }
}
impl Interaction {
/// The state layer: the content colour over the container.
fn layer(&self, container: Color32, content: Color32) -> Color32 {
theme::layer(container, content, self.amount())
}
/// State layer opacity.
fn amount(&self) -> f32 {
theme::HOVER * self.hover + theme::PRESS * self.press.clamp(0.0, 1.0)
}
}
fn focus_ring(ui: &Ui, rect: Rect, radius: f32, p: &Palette) {
ui.painter().rect_stroke(rect.expand(2.0), theme::corner_radius(radius + 2.0), Stroke::new(2.0, p.secondary), StrokeKind::Outside);
}
fn disabled(c: Color32, enabled: bool, amount: f32) -> Color32 {
if enabled { c } else { c.gamma_multiply(amount) }
}
/// Is `text` a Material Symbols code point (`icons::*`)?
fn is_icon(text: &str) -> bool {
text.chars().next().is_some_and(|c| ('\u{e000}'..='\u{f8ff}').contains(&c)) && text.chars().count() == 1
}
/// Draws an icon from `icons` (or any short text glyph) centred on `center`.
pub fn icon(ui: &Ui, center: egui::Pos2, glyph: &str, size: f32, filled: bool, color: Color32) {
let font = if is_icon(glyph) { theme::icon_font(size, filled) } else { theme::font(size * 0.8, Weight::Regular) };
ui.painter().text(center, Align2::CENTER_CENTER, glyph, font, color);
}
/// A round icon button with a tooltip. `glyph` is one of `icons::*`.
pub fn icon_button(ui: &mut Ui, glyph: &str, tooltip: &str) -> Response {
let button = egui::Button::new(RichText::new(glyph).size(15.0)).min_size(Vec2::new(28.0, 28.0)).frame(false);
ui.add(button).on_hover_text(tooltip)
icon_control(ui, glyph, tooltip, false)
}
/// Like `icon_button` but shows as pressed when `on`.
/// Like `icon_button` but shows as selected (tonal fill, filled icon) when `on`.
pub fn icon_toggle(ui: &mut Ui, glyph: &str, tooltip: &str, on: bool) -> Response {
let button = egui::Button::new(RichText::new(glyph).size(15.0)).min_size(Vec2::new(28.0, 28.0)).selected(on).frame(on);
ui.add(button).on_hover_text(tooltip)
icon_control(ui, glyph, tooltip, on)
}
/// An on/off switch. Returns true when it changed.
fn icon_control(ui: &mut Ui, glyph: &str, tooltip: &str, on: bool) -> Response {
let p = theme::palette(ui.ctx());
let size = theme::CONTROL_SMALL;
let (rect, response) = ui.allocate_exact_size(Vec2::splat(size), Sense::click());
if ui.is_rect_visible(rect) {
let s = interaction(ui, &response);
let selected = theme::effect(ui.ctx(), response.id.with("on"), on);
let content = theme::layer(p.on_surface_variant, p.on_secondary_container, selected);
// Press squashes the circle towards a squircle.
let radius = theme::corner_radius(size / 2.0 * (1.0 - 0.45 * s.press.clamp(0.0, 1.2)));
if selected > 0.0 {
ui.painter().rect_filled(rect, radius, p.secondary_container.gamma_multiply(selected));
}
let state = s.amount();
if state > 0.0 {
ui.painter().rect_filled(rect, radius, content.gamma_multiply(state));
}
icon(ui, rect.center(), glyph, theme::ICON, on, disabled(content, s.enabled, theme::DISABLED_CONTENT));
if s.focus {
focus_ring(ui, rect, size / 2.0, &p);
}
}
response.on_hover_text(tooltip)
}
/// An on/off switch (M3): the handle travels, grows and shows a check when on, with a halo on hover.
/// Returns true when it changed.
pub fn switch(ui: &mut Ui, on: &mut bool) -> bool {
let size = Vec2::new(36.0, 20.0);
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
let p = theme::palette(ui.ctx());
let (rect, mut response) = ui.allocate_exact_size(vec2(52.0, 32.0), Sense::click());
if response.clicked() {
*on = !*on;
response.mark_changed();
}
let t = ui.ctx().animate_bool_responsive(response.id, *on);
let visuals = ui.style().interact_selectable(&response, *on);
let radius = rect.height() / 2.0;
let fill = if *on { ui.visuals().selection.stroke.color } else { ui.visuals().widgets.inactive.bg_fill };
ui.painter().rect(rect, radius, fill, visuals.bg_stroke, egui::StrokeKind::Inside);
let x = egui::lerp((rect.left() + radius)..=(rect.right() - radius), t);
let knob = if *on { ui.visuals().panel_fill } else { ui.visuals().widgets.inactive.fg_stroke.color };
ui.painter().circle_filled(egui::pos2(x, rect.center().y), radius * 0.72, knob);
response.clicked()
if ui.is_rect_visible(rect) {
let s = interaction(ui, &response);
let ctx = ui.ctx();
let t = theme::effect(ctx, response.id.with("on"), *on);
let travel = theme::spring(ctx, response.id.with("x"), if *on { 1.0 } else { 0.0 }, theme::FAST);
let track = theme::layer(p.surface_container_highest, p.primary, t);
let outline = theme::layer(p.outline, p.primary, t);
let painter = ui.painter();
painter.rect(rect, CornerRadius::same(16), disabled(track, s.enabled, theme::DISABLED_CONTAINER), Stroke::new(2.0, disabled(outline, s.enabled, theme::DISABLED_CONTAINER)), StrokeKind::Inside);
let x = egui::lerp((rect.left() + 16.0)..=(rect.right() - 16.0), travel);
let center = pos2(x, rect.center().y);
let halo = theme::layer(p.on_surface, p.primary, t);
if s.amount() > 0.0 {
painter.circle_filled(center, 20.0, halo.gamma_multiply(s.amount()));
}
let handle = 8.0 + 4.0 * t + 2.0 * s.press.clamp(0.0, 1.2);
let fill = theme::layer(p.outline, p.on_primary, t);
let fill = if s.hover > 0.0 { theme::layer(fill, theme::layer(p.on_surface_variant, p.primary_container, t), s.hover) } else { fill };
painter.circle_filled(center, handle, disabled(fill, s.enabled, theme::DISABLED_CONTENT));
if t > 0.01 {
icon(ui, center, icons::CHECK, 16.0 * t, false, p.on_primary_container.gamma_multiply(t));
}
if s.focus {
focus_ring(ui, rect, 16.0, &p);
}
}
response.changed()
}
/// A row of buttons choosing one of `options`. Returns true when it changed.
/// A row of connected buttons choosing one of `options` (M3 segmented buttons): the selected one gets a tonal fill
/// and a check mark. Returns true when it changed.
pub fn segmented<T: Copy + PartialEq>(ui: &mut Ui, value: &mut T, options: &[(T, &str)]) -> bool {
let p = theme::palette(ui.ctx());
let font = theme::font(theme::BODY, Weight::Medium);
let check = 18.0 + theme::GAP_XS;
let widest = options.iter().map(|(_, label)| ui.painter().layout_no_wrap((*label).to_owned(), font.clone(), p.on_surface).size().x).fold(0.0, f32::max);
let segment = vec2((widest + check + 2.0 * theme::GAP_M).max(64.0), theme::CONTROL);
let total = vec2(segment.x * options.len() as f32, segment.y);
let (rect, _) = ui.allocate_exact_size(total, Sense::hover());
let id = ui.id().with("segmented").with(rect.min.x as i32).with(rect.min.y as i32);
let mut changed = false;
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 2.0;
for (option, label) in options {
let selected = *value == *option;
let text = if selected { format!("✓ {label}") } else { (*label).to_owned() };
if ui.add(egui::Button::new(text).selected(selected)).clicked() && !selected {
*value = *option;
changed = true;
}
let last = options.len().saturating_sub(1);
for (i, (option, label)) in options.iter().enumerate() {
let r = Rect::from_min_size(pos2(rect.left() + segment.x * i as f32, rect.top()), segment);
let response = ui.interact(r, id.with(i), Sense::click());
let selected = *value == *option;
if response.clicked() && !selected {
*value = *option;
changed = true;
}
});
if !ui.is_rect_visible(r) {
continue;
}
let s = interaction(ui, &response);
let t = theme::effect(ui.ctx(), response.id.with("on"), *value == *option);
let full = (segment.y / 2.0) as u8;
let corners = CornerRadius { nw: if i == 0 { full } else { 0 }, sw: if i == 0 { full } else { 0 }, ne: if i == last { full } else { 0 }, se: if i == last { full } else { 0 } };
let container = theme::layer(p.surface, p.secondary_container, t);
let content = theme::layer(p.on_surface, p.on_secondary_container, t);
let fill = s.layer(container, content);
if t > 0.0 || s.hover + s.press > 0.0 {
ui.painter().rect_filled(r, corners, fill);
}
let galley = ui.painter().layout_no_wrap((*label).to_owned(), font.clone(), content);
// The check slides in from nothing, pushing the label right by its width.
let shift = check * t;
let x = r.center().x - (galley.size().x + shift) / 2.0;
if t > 0.01 {
icon(ui, pos2(x + 9.0 * t, r.center().y), icons::CHECK, 18.0 * t, false, content);
}
ui.painter().galley(pos2(x + shift, r.center().y - galley.size().y / 2.0), galley, disabled(content, s.enabled, theme::DISABLED_CONTENT));
if i > 0 {
ui.painter().vline(r.left(), r.y_range(), Stroke::new(1.0, p.outline));
}
if s.focus {
focus_ring(ui, r, segment.y / 2.0, &p);
}
}
ui.painter().rect_stroke(rect, CornerRadius::same((segment.y / 2.0) as u8), Stroke::new(1.0, p.outline), StrokeKind::Inside);
changed
}
/// Button emphasis, highest first.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ButtonKind {
Filled,
Tonal,
Outlined,
Text,
}
/// A pill button with an optional leading icon. Press morphs the pill to a rounded rectangle.
pub fn button(ui: &mut Ui, kind: ButtonKind, icon_glyph: Option<&str>, label: &str) -> Response {
let p = theme::palette(ui.ctx());
let font = theme::font(theme::BODY, Weight::Medium);
let galley = ui.painter().layout_no_wrap(label.to_owned(), font, Color32::PLACEHOLDER);
let pad = if kind == ButtonKind::Text { theme::GAP_M } else { theme::GAP_XL };
let lead = if icon_glyph.is_some() { 18.0 + theme::GAP_S } else { 0.0 };
let left = if icon_glyph.is_some() { theme::GAP_L } else { pad };
let size = vec2(left + lead + galley.size().x + pad, theme::CONTROL);
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
if ui.is_rect_visible(rect) {
let s = interaction(ui, &response);
let (container, content) = match kind {
ButtonKind::Filled => (p.primary, p.on_primary),
ButtonKind::Tonal => (p.secondary_container, p.on_secondary_container),
ButtonKind::Outlined | ButtonKind::Text => (Color32::TRANSPARENT, p.primary),
};
let content = if s.enabled { content } else { p.on_surface.gamma_multiply(theme::DISABLED_CONTENT) };
let radius = egui::lerp((rect.height() / 2.0)..=theme::radius(ui.ctx(), theme::S), s.press.clamp(0.0, 1.0));
let r = theme::corner_radius(radius);
let fill = if !s.enabled {
if container == Color32::TRANSPARENT { Color32::TRANSPARENT } else { p.on_surface.gamma_multiply(theme::DISABLED_CONTAINER) }
} else if container == Color32::TRANSPARENT {
content.gamma_multiply(s.amount())
} else {
s.layer(container, content)
};
ui.painter().rect_filled(rect, r, fill);
if kind == ButtonKind::Outlined {
let line = if s.enabled { p.outline_variant } else { p.on_surface.gamma_multiply(theme::DISABLED_CONTAINER) };
ui.painter().rect_stroke(rect, r, Stroke::new(1.0, line), StrokeKind::Inside);
}
let mut x = rect.left() + left;
if let Some(glyph) = icon_glyph {
icon(ui, pos2(x + 9.0, rect.center().y), glyph, 18.0, false, content);
x += lead;
}
ui.painter().galley_with_override_text_color(pos2(x, rect.center().y - galley.size().y / 2.0), galley, content);
if s.focus {
focus_ring(ui, rect, rect.height() / 2.0, &p);
}
}
response
}
/// The rows of a card: each row after the first draws a hairline above itself.
fn first_row_id(ui: &Ui) -> Id {
ui.id().with("first-row")
}
/// A setting: title and description on the left, the control on the right.
pub fn row<R>(ui: &mut Ui, title: &str, description: &str, control: impl FnOnce(&mut Ui) -> R) -> R {
row_frame(ui, title, description, None, control).0
}
fn row_frame<R>(ui: &mut Ui, title: &str, description: &str, click: Option<Id>, control: impl FnOnce(&mut Ui) -> R) -> (R, Option<Response>) {
let p = theme::palette(ui.ctx());
let first = ui.data_mut(|d| d.remove_temp::<bool>(first_row_id(ui))).unwrap_or(false);
let background = ui.painter().add(Shape::Noop);
let mut result = None;
egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| {
let inner = egui::Frame::NONE.inner_margin(egui::Margin::symmetric(theme::GAP_L as i8, theme::GAP_M as i8)).show(ui, |ui| {
ui.set_min_height(theme::ROW - 2.0 * theme::GAP_M);
ui.horizontal(|ui| {
ui.vertical(|ui| {
ui.set_max_width((ui.available_width() - 260.0).max(200.0));
ui.label(RichText::new(title).strong());
ui.add_space((theme::ROW - 2.0 * theme::GAP_M - if description.is_empty() { 20.0 } else { 36.0 }).max(0.0) / 2.0);
ui.label(RichText::new(title).font(theme::font(theme::BODY, Weight::Regular)).color(p.on_surface));
if !description.is_empty() {
ui.label(RichText::new(description).small().weak());
ui.label(RichText::new(description).font(theme::font(theme::SMALL, Weight::Regular)).color(p.on_surface_variant));
}
});
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
@ -66,8 +264,21 @@ pub fn row<R>(ui: &mut Ui, title: &str, description: &str, control: impl FnOnce(
});
});
});
ui.separator();
result.expect("control ran")
let rect = inner.response.rect;
if !first {
ui.painter().hline(rect.x_range().shrink(theme::GAP_L), rect.top(), Stroke::new(1.0, p.outline_variant));
}
let response = click.map(|id| {
let response = ui.interact(rect, id, Sense::click());
let s = interaction(ui, &response);
let tint = p.on_surface.gamma_multiply(s.amount());
ui.painter().set(background, Shape::rect_filled(rect, theme::corner_radius(theme::radius(ui.ctx(), theme::XS)), tint));
if s.focus {
focus_ring(ui, rect.shrink(2.0), theme::radius(ui.ctx(), theme::XS), &p);
}
response
});
(result.expect("control ran"), response)
}
/// A switch row. Returns true when it changed.
@ -75,21 +286,43 @@ pub fn switch_row(ui: &mut Ui, title: &str, description: &str, on: &mut bool) ->
row(ui, title, description, |ui| switch(ui, on))
}
/// A row that opens something: title, description, and an arrow.
/// A row that opens something: the whole row is the button, with a chevron at the end.
pub fn link_row(ui: &mut Ui, title: &str, description: &str) -> bool {
row(ui, title, description, |ui| ui.button("›").clicked())
let p = theme::palette(ui.ctx());
let id = ui.id().with("link-row").with(title);
let (_, response) = row_frame(ui, title, description, Some(id), |ui| {
let (rect, _) = ui.allocate_exact_size(Vec2::splat(24.0), Sense::hover());
icon(ui, rect.center(), icons::CHEVRON_RIGHT, theme::ICON, false, p.on_surface_variant);
});
response.is_some_and(|r| r.clicked())
}
/// A group title above a card, in the accent colour, lined up with the rows' text.
pub fn section(ui: &mut Ui, title: &str) {
ui.add_space(14.0);
ui.label(RichText::new(title).size(20.0).strong());
ui.add_space(4.0);
let p = theme::palette(ui.ctx());
ui.add_space(theme::GAP_XL);
ui.horizontal(|ui| {
ui.add_space(theme::GAP_L);
ui.label(RichText::new(title).font(theme::font(theme::BODY, Weight::Medium)).color(p.primary));
});
ui.add_space(theme::GAP_XS);
}
/// A card that groups rows.
/// A card that groups rows: a large rounded surface a step above the page.
pub fn card<R>(ui: &mut Ui, contents: impl FnOnce(&mut Ui) -> R) -> R {
let fill = ui.visuals().faint_bg_color;
egui::Frame::NONE.fill(fill).corner_radius(ui.visuals().window_corner_radius).inner_margin(egui::Margin::same(4)).show(ui, contents).inner
let p = theme::palette(ui.ctx());
let radius = theme::corner_radius(theme::radius(ui.ctx(), theme::L));
egui::Frame::NONE
.fill(p.surface_container)
.corner_radius(radius)
.inner_margin(egui::Margin::symmetric(0, theme::GAP_XS as i8))
.show(ui, |ui| {
ui.data_mut(|d| d.insert_temp(first_row_id(ui), true));
let r = contents(ui);
ui.data_mut(|d| d.remove_temp::<bool>(first_row_id(ui)));
r
})
.inner
}
/// Centered page column of at most `width` points, scrolling.
@ -117,7 +350,7 @@ pub fn page_column<R>(ui: &mut Ui, id: &str, width: f32, contents: impl FnOnce(&
/// A text field with a hint; returns its response.
pub fn text_field(ui: &mut Ui, text: &mut String, hint: &str, width: f32) -> Response {
ui.add(egui::TextEdit::singleline(text).hint_text(hint).desired_width(width))
ui.add(egui::TextEdit::singleline(text).hint_text(hint).desired_width(width).margin(vec2(theme::GAP_M, theme::GAP_S)))
}
/// A number field limited to `range`. Returns true when it changed.
@ -125,30 +358,117 @@ pub fn number(ui: &mut Ui, value: &mut u32, range: std::ops::RangeInclusive<u32>
ui.add(egui::DragValue::new(value).range(range).suffix(suffix)).changed()
}
/// Glyph for a toolbar button key.
/// Icon for a toolbar button key.
pub fn glyph(key: &str) -> &'static str {
match key {
"back" => "⬅",
"forward" => "➡",
"reload" => "⟳",
"home" => "🏠",
"incognito" => "🕶",
"passwords" => "🔑",
"history" => "🕘",
"downloads" => "⬇",
"bookmarks" => "★",
"qr" => "▦",
"devtools" => "🛠",
"adblock" => "🛡",
"media" => "♫",
"vpn" => "🌐",
"apps" => "▤",
"screenshot" => "📷",
"pip" => "⧉",
"zoom" => "🔍",
"share" => "⤴",
"reader" => "📖",
"settings" => "⚙",
_ => "•",
"back" => icons::ARROW_BACK,
"forward" => icons::ARROW_FORWARD,
"reload" => icons::REFRESH,
"home" => icons::HOME,
"incognito" => icons::DOMINO_MASK,
"passwords" => icons::KEY,
"history" => icons::HISTORY,
"downloads" => icons::DOWNLOAD,
"bookmarks" => icons::STAR,
"qr" => icons::QR_CODE_2,
"devtools" => icons::CODE,
"adblock" => icons::SHIELD,
"media" => icons::MUSIC_NOTE,
"vpn" => icons::VPN_LOCK,
"apps" => icons::APPS,
"screenshot" => icons::SCREENSHOT_MONITOR,
"pip" => icons::PICTURE_IN_PICTURE_ALT,
"zoom" => icons::ZOOM_IN,
"share" => icons::SHARE,
"reader" => icons::CHROME_READER_MODE,
"settings" => icons::SETTINGS,
_ => icons::CIRCLE,
}
}
#[cfg(test)]
mod tests {
use super::*;
use egui::{Event, Key, Modifiers, PointerButton, RawInput};
/// Runs one frame of `body` at `time` with `events`, returning the rect the body drew in.
fn frame(ctx: &egui::Context, time: f64, events: Vec<Event>, body: &mut dyn FnMut(&mut Ui)) -> Rect {
let mut rect = Rect::NOTHING;
let input = RawInput { time: Some(time), events, screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() };
let _ = ctx.run_ui(input, |ui| rect = ui.horizontal(|ui| body(ui)).response.rect);
rect
}
fn click_at(pos: egui::Pos2) -> Vec<Vec<Event>> {
let button = |pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
vec![vec![Event::PointerMoved(pos)], vec![button(true)], vec![button(false)], vec![]]
}
#[test]
fn switch_toggles_by_pointer_and_keyboard() {
let ctx = egui::Context::default();
let mut on = false;
let mut changes = 0;
let mut draw = |ui: &mut Ui| {
if switch(ui, &mut on) {
changes += 1;
}
};
let rect = frame(&ctx, 0.0, vec![], &mut draw);
for (i, events) in click_at(rect.center()).into_iter().enumerate() {
frame(&ctx, 0.02 * (i + 1) as f64, events, &mut draw);
}
drop(draw);
assert!(on, "a click turns it on");
assert_eq!(changes, 1);
let key = |key, pressed| Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE };
let mut draw = |ui: &mut Ui| {
switch(ui, &mut on);
};
// Move the pointer away, then Tab to focus the switch and Space to toggle it.
for (i, events) in [vec![Event::PointerGone], vec![key(Key::Tab, true), key(Key::Tab, false)], vec![key(Key::Space, true), key(Key::Space, false)], vec![]].into_iter().enumerate() {
frame(&ctx, 1.0 + 0.02 * i as f64, events, &mut draw);
}
drop(draw);
assert!(!on, "Space on the focused switch turns it off");
}
#[test]
fn segmented_picks_the_clicked_option() {
let ctx = egui::Context::default();
let mut value = 0;
let mut draw = |ui: &mut Ui| {
segmented(ui, &mut value, &[(0, "Few"), (1, "Some"), (2, "Lots")]);
};
let rect = frame(&ctx, 0.0, vec![], &mut draw);
let third = egui::pos2(rect.left() + rect.width() * 5.0 / 6.0, rect.center().y);
for (i, events) in click_at(third).into_iter().enumerate() {
frame(&ctx, 0.02 * (i + 1) as f64, events, &mut draw);
}
drop(draw);
assert_eq!(value, 2);
}
/// Hover fades in with the effect spring and a press squeezes, both settling back once the pointer leaves.
#[test]
fn hover_and_press_animate_and_settle() {
let ctx = egui::Context::default();
let id = std::cell::Cell::new(Id::NULL);
let mut draw = |ui: &mut Ui| id.set(button(ui, ButtonKind::Tonal, None, "Save").id);
let rect = frame(&ctx, 0.0, vec![], &mut draw);
let id = id.get();
let hover = |ctx: &egui::Context| theme::spring_value(ctx, id.with("hover")).unwrap_or(0.0);
frame(&ctx, 0.016, vec![Event::PointerMoved(rect.center())], &mut draw);
frame(&ctx, 0.032, vec![], &mut draw);
let early = hover(&ctx);
for i in 3..40 {
frame(&ctx, 0.016 * i as f64, vec![], &mut draw);
}
assert!(early > 0.0 && early < 1.0, "hover eases in, got {early}");
assert_eq!(hover(&ctx), 1.0);
for i in 40..90 {
frame(&ctx, 0.016 * i as f64, if i == 40 { vec![Event::PointerGone] } else { vec![] }, &mut draw);
}
assert_eq!(hover(&ctx), 0.0);
}
}

View file

@ -100,6 +100,7 @@ impl BrowserWindow {
let rendering = Rc::new(rendering);
let _ = rendering.make_current();
let egui = egui_glow::EguiGlow::new(event_loop, rendering.glow_gl_api(), None, Some(window.scale_factor() as f32), true);
egui.egui_ctx.set_fonts(crate::ui::fonts());
let page_context = Rc::new(rendering.offscreen_context(size));
let id = window.id();
Ok(BrowserWindow {