Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! Native palette (defaults match Discord's dark theme) and font setup.
use eframe::egui::{self, Color32, FontData, FontDefinitions, FontFamily, Rounding, Stroke, Visuals};
use rencord::theme::Palette;
#[derive(Clone, Debug)]
pub struct Theme {
pub bg_primary: Color32,
pub bg_secondary: Color32,
pub bg_secondary_alt: Color32,
pub bg_tertiary: Color32,
pub bg_floating: Color32,
pub bg_hover: Color32,
pub bg_selected: Color32,
pub bg_message_hover: Color32,
pub bg_mentioned: Color32,
pub input_bg: Color32,
pub text_normal: Color32,
pub text_muted: Color32,
pub header_primary: Color32,
pub header_secondary: Color32,
pub interactive_normal: Color32,
pub interactive_hover: Color32,
pub interactive_active: Color32,
pub interactive_muted: Color32,
pub text_link: Color32,
pub accent: Color32,
pub danger: Color32,
/// Channel names (Discord's --channels-default).
pub channel_default: Color32,
/// Hairline borders (--border-subtle).
pub border_subtle: Color32,
/// Popouts / floating user panel (--background-surface-high).
pub surface_high: Color32,
/// Discord's positive notice bar: background and text
/// (--notice-background-positive / --notice-text-positive).
pub notice_positive: (Color32, Color32),
/// Nitro client theme gradient (None: plain theme).
pub gradient: Option<Gradient>,
/// A client theme's text tint: the colour and how far text is mixed
/// toward it (None: plain theme).
pub text_mix: Option<(Color32, f32)>,
/// What Discord lays over the gradient for each surface.
pub overlays: Overlays,
/// Discord's light theme (light Nitro presets).
pub light: bool,
/// Code-block highlighting colours (Discord's --text-code-*).
pub syntax: Syntax,
/// Button colours that differ by theme (Discord's --control-*).
pub controls: Controls,
}
/// The theme's share of Discord's button tokens (--control-secondary-* and
/// --control-critical-secondary-*); the solid brand and red buttons are the
/// same in every theme.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Controls {
/// The grey fill while hovered and while pressed (it's `overlay(0.12)` at rest).
pub hover: Color32,
pub active: Color32,
/// The grey buttons' hairline edge.
pub border: Color32,
/// The red label of a grey "critical" button (Disable Account).
pub critical_text: Color32,
}
/// Discord's code-block colours (its highlight.js theme, --text-code-*).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Syntax {
pub code: Color32,
pub keyword: Color32,
pub r#type: Color32,
pub title: Color32,
pub attribute: Color32,
pub decorator: Color32,
pub number: Color32,
pub string: Color32,
pub builtin: Color32,
pub comment: Color32,
pub addition: Color32,
pub deletion: Color32,
}
impl Syntax {
/// Discord's values for each base theme ("dark" = Discord's Darker,
/// "ash" = Dark, "onyx" = Midnight).
fn for_theme(name: &str) -> Self {
let s = |v: [u32; 12]| Syntax {
code: hex(v[0]),
keyword: hex(v[1]),
r#type: hex(v[2]),
title: hex(v[3]),
attribute: hex(v[4]),
decorator: hex(v[5]),
number: hex(v[6]),
string: hex(v[7]),
builtin: hex(v[8]),
comment: hex(v[9]),
addition: hex(v[10]),
deletion: hex(v[11]),
};
match name {
"ash" => s([0xfdfdff, 0xfecac9, 0xfec5f1, 0xc9d4ff, 0xbcd8ff, 0xfecf83, 0xfbcdb7, 0xade3bd, 0xfecf83, 0xc2c2c9, 0xb0e5c0, 0xfecac9]),
"onyx" => s([0xd3d4d9, 0xfa9694, 0xff84df, 0x9aacfe, 0x82b4f6, 0xe4a65d, 0xe8a17c, 0x7fc094, 0xe4a65d, 0xa0a1a9, 0x82c296, 0xfa9694]),
"light" => s([0x282630, 0x7b1926, 0x711a5e, 0x303783, 0x0d3e7f, 0x63330f, 0x6d2a10, 0x0b4a2a, 0x63330f, 0x4d4c57, 0x0a4427, 0x731623]),
_ => s([0xe8e8ec, 0xffadaa, 0xffa5e9, 0xb1c0ff, 0x9dc6fa, 0xf6b463, 0xf2b696, 0x93d0a6, 0xf6b463, 0xaeaeb6, 0x98d4aa, 0xffadaa]),
}
}
}
/// A CSS `linear-gradient(angle, color stop, …)` over the whole window, the
/// way Discord paints a Nitro client theme (`fixed 0 0 / cover`).
#[derive(Clone, Debug, PartialEq)]
pub struct Gradient {
/// (colour, position 0–1), in order.
pub stops: Vec<(Color32, f32)>,
/// CSS degrees: 0 = towards the top, 90 = towards the right.
pub angle: f32,
}
impl Gradient {
/// Colours spread evenly (a custom theme's colour list).
pub fn even(colors: &[Color32], angle: f32) -> Self {
let n = colors.len().max(2) - 1;
let mut stops: Vec<(Color32, f32)> = colors.iter().enumerate().map(|(i, c)| (*c, i as f32 / n as f32)).collect();
if stops.len() == 1 {
stops.push((stops[0].0, 1.0));
}
Self { stops, angle }
}
/// The colour at `p` with the gradient laid over `area` (CSS maths:
/// the gradient line runs through the centre, long enough that the
/// corners get the end colours; colours mix in sRGB).
pub fn color_at(&self, p: egui::Pos2, area: egui::Rect) -> Color32 {
let Some(first) = self.stops.first() else { return Color32::BLACK };
let a = self.angle.to_radians();
let dir = egui::vec2(a.sin(), -a.cos());
let len = (area.width() * a.sin()).abs() + (area.height() * a.cos()).abs();
let t = 0.5 + (p - area.center()).dot(dir) / len.max(1.0);
if t <= first.1 {
return first.0;
}
for w in self.stops.windows(2) {
let ((c0, p0), (c1, p1)) = (w[0], w[1]);
if t <= p1 {
let f = if p1 > p0 { (t - p0) / (p1 - p0) } else { 1.0 };
return c0.lerp_to_gamma(c1, f.clamp(0.0, 1.0));
}
}
self.stops.last().map_or(first.0, |s| s.0)
}
}
/// Discord's overlays on a gradient theme: a colour (black in dark themes,
/// white in light ones) at a strength per surface.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Overlays {
pub color: Color32,
/// App frame: server list, channel list, title bar.
pub frame: f32,
/// Chat and member list.
pub chat: f32,
/// Floating user panel, composer (--background-gradient-highest).
pub panel: f32,
}
impl Overlays {
/// A custom client theme (Discord's `.custom-client-theme` maths, with
/// m = (30 + 0.7 × (100 − base mix)) / 100).
fn custom(base_mix: f32, light: bool) -> Self {
let m = (30.0 + 0.7 * (100.0 - base_mix)) / 100.0;
if light {
Self { color: Color32::WHITE, frame: 0.325 + m * 0.5 * 0.65, chat: 0.85 * (0.6 + m * 0.4), panel: 0.95 * (0.8 + m * 0.2) }
} else {
Self { color: Color32::BLACK, frame: 0.42 + m * 0.4 * 0.7, chat: 0.48 + m * 0.4 * 0.8, panel: 0.39 + m * 0.4 * 0.65 }
}
}
/// A Nitro preset (Discord's plain `.custom-theme-background` values).
fn preset(light: bool) -> Self {
if light {
Self { color: Color32::WHITE, frame: 0.65, chat: 0.85, panel: 0.95 }
} else {
Self { color: Color32::BLACK, frame: 0.7, chat: 0.8, panel: 0.65 }
}
}
}
impl Default for Overlays {
fn default() -> Self {
Self::preset(false)
}
}
/// One of Discord's Nitro "Color" themes (Settings → Appearance).
pub struct GradientPreset {
/// Discord's preset id (what the account's settings store).
pub id: u32,
pub name: &'static str,
pub light: bool,
pub angle: f32,
/// (0xRRGGBB, stop %).
pub stops: &'static [(u32, f32)],
}
impl GradientPreset {
pub fn gradient(&self) -> Gradient {
Gradient { stops: self.stops.iter().map(|&(c, p)| (hex(c), p / 100.0)).collect(), angle: self.angle }
}
}
/// Discord's gradient presets, in the order its picker shows them (colours,
/// stops and angles from Discord's own table).
pub const GRADIENT_PRESETS: &[GradientPreset] = &[
GradientPreset { id: 0, name: "Mint Apple", light: true, angle: 180.0, stops: &[(0x56b69f, 6.15), (0x63bc61, 48.7), (0x9eca67, 93.07)] },
GradientPreset { id: 1, name: "Citrus Sherbert", light: true, angle: 180.0, stops: &[(0xf3b336, 31.1), (0xee8558, 67.09)] },
GradientPreset { id: 2, name: "Retro Raincloud", light: true, angle: 148.0, stops: &[(0x3a7ca1, 5.64), (0x7f7eb9, 26.38), (0x7f7eb9, 49.92), (0x3a7ca1, 73.12)] },
GradientPreset { id: 3, name: "Hanami", light: true, angle: 38.0, stops: &[(0xefaab3, 3.56), (0xefd696, 35.49), (0xa6daa2, 68.78)] },
GradientPreset { id: 4, name: "Sunrise", light: true, angle: 154.0, stops: &[(0x9f4175, 8.62), (0xc49064, 48.07), (0xa6953d, 76.04)] },
GradientPreset { id: 5, name: "Cotton Candy", light: true, angle: 180.0, stops: &[(0xf4abb8, 8.5), (0xb1c2fc, 94.28)] },
GradientPreset { id: 6, name: "LoFi Vibes", light: true, angle: 179.0, stops: &[(0xa4c0f7, 7.08), (0xa9e4e8, 34.94), (0xb0e2b8, 65.12), (0xcfdfa2, 96.23)] },
GradientPreset { id: 7, name: "Desert Khaki", light: true, angle: 38.0, stops: &[(0xe7dbd0, 12.92), (0xdfd0b2, 32.92), (0xe0d6a3, 52.11)] },
GradientPreset { id: 8, name: "Sunset", light: false, angle: 141.0, stops: &[(0x48288c, 27.57), (0xdb7f4b, 71.25)] },
GradientPreset { id: 9, name: "Chroma Glow", light: false, angle: 128.0, stops: &[(0x0eb5bf, 3.94), (0x4c0ce0, 26.1), (0xa308a7, 39.82), (0x9a53ff, 56.89), (0x218be0, 76.45)] },
GradientPreset { id: 10, name: "Forest", light: false, angle: 162.0, stops: &[(0x142215, 11.2), (0x2d4d39, 29.93), (0x454c32, 48.64), (0x5a7c58, 67.85), (0xa98e4b, 83.54)] },
GradientPreset { id: 11, name: "Crimson Moon", light: false, angle: 64.0, stops: &[(0x950909, 16.17), (0x000000, 72.0)] },
GradientPreset { id: 12, name: "Midnight Blurple", light: false, angle: 48.0, stops: &[(0x5348ca, 11.21), (0x140730, 61.92)] },
GradientPreset { id: 13, name: "Mars", light: false, angle: 170.0, stops: &[(0x895240, 14.61), (0x8f4343, 74.62)] },
GradientPreset { id: 14, name: "Dusk", light: false, angle: 180.0, stops: &[(0x665069, 12.84), (0x91a3d1, 85.99)] },
GradientPreset { id: 15, name: "Under the Sea", light: false, angle: 179.0, stops: &[(0x647962, 1.91), (0x588575, 48.99), (0x6a8482, 96.35)] },
GradientPreset { id: 17, name: "Retro Storm", light: false, angle: 148.0, stops: &[(0x3a7ca1, 5.64), (0x58579a, 26.38), (0x58579a, 49.92), (0x3a7ca1, 73.12)] },
GradientPreset { id: 18, name: "Neon Nights", light: false, angle: 180.0, stops: &[(0x01a89e, 0.0), (0x7d60ba, 50.0), (0xb43898, 100.0)] },
GradientPreset { id: 20, name: "Strawberry Lemonade", light: false, angle: 161.0, stops: &[(0xaf1a6c, 18.79), (0xc26b20, 49.76), (0xe7a525, 80.72)] },
GradientPreset { id: 21, name: "Aurora", light: false, angle: 239.0, stops: &[(0x062053, 10.39), (0x191fbb, 26.87), (0x13929a, 48.31), (0x218573, 64.98), (0x051a81, 92.5)] },
GradientPreset { id: 19, name: "Sepia", light: false, angle: 69.0, stops: &[(0x857664, 14.14), (0x5b4421, 60.35)] },
GradientPreset { id: 22, name: "Blurple Twilight", light: false, angle: 47.0, stops: &[(0x2c3fe7, 11.18), (0x261d83, 64.54)] },
GradientPreset { id: 16, name: "Memory Lane", light: true, angle: 180.0, stops: &[(0x7289da, 4.0), (0x4e5d94, 96.0)] },
GradientPreset { id: 23, name: "Hexagon", light: false, angle: 135.0, stops: &[(0x4645ff, 0.0), (0xaf01f3, 33.33), (0xff6698, 66.67), (0xf89a03, 100.0)] },
];
pub fn gradient_preset(id: u32) -> Option<&'static GradientPreset> {
GRADIENT_PRESETS.iter().find(|p| p.id == id)
}
/// Hue (degrees), saturation and lightness of a colour (0–1).
fn hsl_of(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, min) = (r.max(g).max(b), r.min(g).min(b));
let l = (max + min) / 2.0;
let d = max - min;
if d <= f32::EPSILON {
return (0.0, 0.0, l);
}
let s = if l > 0.5 { d / (2.0 - max - min) } else { d / (max + min) };
(hue_of(c), s, l)
}
/// Relative luminance (chroma.js `luminance()`).
fn luminance(c: Color32) -> f32 {
let lin = |v: u8| {
let v = v as f32 / 255.0;
if v <= 0.03928 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
};
0.2126 * lin(c.r()) + 0.7152 * lin(c.g()) + 0.0722 * lin(c.b())
}
/// Hue (degrees) of a colour.
fn hue_of(c: Color32) -> 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, min) = (r.max(g).max(b), r.min(g).min(b));
let d = max - min;
if d <= f32::EPSILON {
return 0.0;
}
let h = if max == r {
((g - b) / d).rem_euclid(6.0)
} else if max == g {
(b - r) / d + 2.0
} else {
(r - g) / d + 4.0
};
h * 60.0
}
fn hsl(h: f32, s: f32, l: f32) -> Color32 {
let f = |n: f32| {
let k = (n + h / 30.0) % 12.0;
let a = s * l.min(1.0 - l);
let v = l - a * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0);
(v.clamp(0.0, 1.0) * 255.0).round() as u8
};
Color32::from_rgb(f(0.0), f(8.0), f(4.0))
}
/// "#0016ff" → colour.
pub fn parse_hex(s: &str) -> Option<Color32> {
let v = u32::from_str_radix(s.trim_start_matches('#'), 16).ok()?;
Some(hex(v))
}
const fn hex(rgb: u32) -> Color32 {
Color32::from_rgb((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8)
}
/// CSS `rgba()` blended the way a browser does it: premultiplied in sRGB
/// (gamma) space. egui's `from_rgba_unmultiplied` premultiplies in linear
/// space, which makes Discord's translucent overlays come out far too bright;
/// so does `Color32::from_white_alpha` (a button's 8 % white edge turned into
/// a white outline). Use this for every translucent colour.
pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color32 {
let m = |c: u8| ((c as u16 * a as u16 + 127) / 255) as u8;
Color32::from_rgba_premultiplied(m(r), m(g), m(b), a)
}
/// Discord's translucent "mod" overlay: hsl(240 4% 60.784%) at `a`.
fn modc(a: f32) -> Color32 {
rgba(151, 151, 159, (a * 255.0).round() as u8)
}
/// Discord's dark themes. Values are Discord's own design tokens (taken from
/// its web client CSS): "ash" = .theme-dark, "dark" = .theme-darker,
/// "onyx" = .theme-midnight.
pub const PRESETS: &[(&str, &str)] = &[("dark", "Dark"), ("ash", "Ash"), ("onyx", "Onyx")];
struct Tokens {
lowest: u32,
lower: u32,
low: u32,
surface_high: u32,
surface_higher: u32,
chat_input: u32,
text_default: u32,
text_muted: u32,
text_strong: u32,
channels: u32,
interactive: u32,
link: u32,
mod_normal: f32,
mod_strong: f32,
notice_bg: u32,
notice_text: u32,
control_border: f32,
critical_text: u32,
}
fn tokens(name: &str) -> Tokens {
match name {
// Discord's .theme-light (used by the light Nitro presets).
"light" => Tokens {
lowest: 0xf3f3f4, lower: 0xfbfbfb, low: 0xfbfbfb, surface_high: 0xffffff, surface_higher: 0xffffff,
chat_input: 0xf7f7f8, text_default: 0x2e2e34, text_muted: 0x6d6f78, text_strong: 0x28282d,
channels: 0x666872, interactive: 0x595a63, link: 0x006dd4, mod_normal: 0.16, mod_strong: 0.24, notice_bg: 0xc8ffd8, notice_text: 0x00461f,
control_border: 0.2, critical_text: 0xb92733,
},
"ash" => Tokens {
lowest: 0x2c2d32, lower: 0x323339, low: 0x36373e, surface_high: 0x393a41, surface_higher: 0x3c3d45,
chat_input: 0x393a41, text_default: 0xf3f3f4, text_muted: 0xabacb2, text_strong: 0xffffff,
channels: 0x999aa1, interactive: 0xc5c6ca, link: 0x76aff6, mod_normal: 0.16, mod_strong: 0.2, notice_bg: 0x00431e, notice_text: 0xc1fcd1,
control_border: 0.04, critical_text: 0xffa09b,
},
"onyx" => Tokens {
lowest: 0x000000, lower: 0x000000, low: 0x000000, surface_high: 0x0a0a0c, surface_higher: 0x121214,
chat_input: 0x101013, text_default: 0xd4d5d8, text_muted: 0x81828a, text_strong: 0xdcdcdf,
channels: 0x7a7b83, interactive: 0x96979e, link: 0x2781e7, mod_normal: 0.2, mod_strong: 0.24, notice_bg: 0x001002, notice_text: 0x7ecb94,
control_border: 0.16, critical_text: 0xeb5f5e,
},
_ => Tokens {
lowest: 0x121214, lower: 0x1a1a1e, low: 0x202024, surface_high: 0x242429, surface_higher: 0x28282d,
chat_input: 0x222327, text_default: 0xefeff1, text_muted: 0x96979e, text_strong: 0xfbfbfb,
channels: 0x81828a, interactive: 0xabacb2, link: 0x4d96ee, mod_normal: 0.16, mod_strong: 0.2, notice_bg: 0x002b0e, notice_text: 0x99e0ad,
control_border: 0.04, critical_text: 0xf87e7a,
},
}
}
impl Default for Theme {
fn default() -> Self {
Self::preset("dark")
}
}
impl Theme {
pub fn preset(name: &str) -> Self {
let k = tokens(name);
Self {
bg_primary: hex(k.lower),
bg_secondary: hex(k.lowest),
bg_secondary_alt: hex(k.low),
bg_tertiary: hex(k.lowest),
bg_floating: hex(k.surface_higher),
bg_hover: modc(0.12),
bg_selected: modc(k.mod_normal),
bg_message_hover: modc(0.06),
bg_mentioned: rgba(240, 177, 50, 26),
input_bg: hex(k.chat_input),
text_normal: hex(k.text_default),
text_muted: hex(k.text_muted),
header_primary: hex(k.text_strong),
header_secondary: hex(k.interactive),
interactive_normal: hex(k.interactive),
interactive_hover: hex(k.text_strong),
interactive_active: hex(k.text_strong),
interactive_muted: modc(k.mod_strong + 0.15),
text_link: hex(k.link),
accent: hex(0x5865f2),
danger: hex(0xf23f43),
channel_default: hex(k.channels),
border_subtle: modc(0.12),
surface_high: hex(k.surface_high),
notice_positive: (hex(k.notice_bg), hex(k.notice_text)),
gradient: None,
text_mix: None,
overlays: Overlays::default(),
light: name == "light",
syntax: Syntax::for_theme(name),
controls: Controls { hover: modc(k.mod_normal), active: modc(k.mod_strong), border: modc(k.control_border), critical_text: hex(k.critical_text) },
}
}
/// Discord's scrollbar thumb (--scrollbar-auto-thumb: hsl(234 4.7% 42%),
/// mixed toward a client theme's base like the surfaces are).
pub fn scrollbar_thumb(&self) -> Color32 {
let thumb = hex(0x66676f);
match self.gradient {
Some(_) => thumb.lerp_to_gamma(self.bg_tertiary, 0.4),
None => thumb,
}
}
/// A whole page's / panel's background: the colour, or nothing under a
/// client theme (the gradient behind shows through, as in Discord).
pub fn page(&self, c: Color32) -> Color32 {
if self.gradient.is_some() {
Color32::TRANSPARENT
} else {
c
}
}
/// Every surface mixed toward `base` and text toward `text`, like
/// Discord's `color-mix(in oklab, token 100%, base N%)` (normalised N/(100+N)).
fn mixed(mut self, base: Color32, text: Color32, base_mix: f32, text_mix: f32) -> Self {
let surf = |c: Color32| c.lerp_to_gamma(base, base_mix / (100.0 + base_mix));
let txt = |c: Color32| c.lerp_to_gamma(text, text_mix / (100.0 + text_mix));
self.bg_primary = surf(self.bg_primary);
self.bg_secondary = surf(self.bg_secondary);
self.bg_secondary_alt = surf(self.bg_secondary_alt);
self.bg_tertiary = surf(self.bg_tertiary);
self.bg_floating = surf(self.bg_floating);
self.input_bg = surf(self.input_bg);
self.surface_high = surf(self.surface_high);
self.text_normal = txt(self.text_normal);
self.text_muted = txt(self.text_muted);
self.header_primary = txt(self.header_primary);
self.header_secondary = txt(self.header_secondary);
self.interactive_normal = txt(self.interactive_normal);
self.channel_default = txt(self.channel_default);
self.text_mix = Some((text, text_mix / (100.0 + text_mix)));
self
}
/// A text or icon colour of Discord's (a status green, a warning yellow)
/// tinted the way a client theme tints its text.
pub fn tint_text(&self, c: Color32) -> Color32 {
match self.text_mix {
Some((to, k)) => c.lerp_to_gamma(to, k),
None => c,
}
}
/// Accessibility → Saturation: the interface's colours pulled toward
/// grey (`amount` 1 = as they are, 0 = no colour). Pictures, role colours
/// and other people's content are left alone, as in Discord.
pub fn saturated(mut self, amount: f32) -> Self {
let k = amount.clamp(0.0, 1.0);
let f = |c: &mut Color32| {
let [r, g, b, a] = c.to_srgba_unmultiplied();
let grey = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
let mix = |v: u8| (grey + (v as f32 - grey) * k).round() as u8;
*c = Color32::from_rgba_unmultiplied(mix(r), mix(g), mix(b), a);
};
for c in [
&mut self.bg_primary,
&mut self.bg_secondary,
&mut self.bg_secondary_alt,
&mut self.bg_tertiary,
&mut self.bg_floating,
&mut self.bg_hover,
&mut self.bg_selected,
&mut self.bg_message_hover,
&mut self.bg_mentioned,
&mut self.input_bg,
&mut self.text_normal,
&mut self.text_muted,
&mut self.header_primary,
&mut self.header_secondary,
&mut self.interactive_normal,
&mut self.interactive_hover,
&mut self.interactive_active,
&mut self.interactive_muted,
&mut self.text_link,
&mut self.accent,
&mut self.danger,
&mut self.channel_default,
&mut self.border_subtle,
&mut self.surface_high,
] {
f(c);
}
self
}
/// Accessibility → High Contrast: text and icons at full strength, and
/// borders you can see.
pub fn high_contrast(mut self) -> Self {
let (strong, soft, border) = if self.light {
(Color32::BLACK, Color32::from_rgb(38, 40, 46), rgba(0, 0, 0, 120))
} else {
(Color32::WHITE, Color32::from_rgb(226, 228, 232), rgba(255, 255, 255, 110))
};
self.text_normal = strong;
self.header_primary = strong;
self.interactive_hover = strong;
self.interactive_active = strong;
self.text_muted = soft;
self.header_secondary = soft;
self.interactive_normal = soft;
self.channel_default = soft;
self.border_subtle = border;
self
}
/// Your own Nitro client theme (Discord's custom gradient): its colours
/// spread evenly at `angle`, surfaces mixed toward its darkest colour at
/// 5 % lightness (60 + 0.4 × (100 − base mix) %), text 30 % toward it
/// nearly white. Discord's `custom-client-theme` maths.
pub fn with_client_theme(self, colors: &[Color32], angle: f32, base_mix: f32) -> Self {
if colors.is_empty() {
return self;
}
let darkest = *colors.iter().min_by(|a, b| luminance(**a).total_cmp(&luminance(**b))).unwrap_or(&colors[0]);
let lightest = *colors.iter().max_by(|a, b| luminance(**a).total_cmp(&luminance(**b))).unwrap_or(&colors[0]);
let h = 100.0 - base_mix;
let light = self.light;
let mut t = if light {
let (lh, _, _) = hsl_of(lightest);
let (_, ls, _) = hsl_of(lightest);
self.mixed(hsl(lh, 1.0, 0.9), hsl(lh, ls, 0.05 * h / 100.0), 30.0 - 0.2 * base_mix, 40.0)
} else {
let (dh, ds, _) = hsl_of(darkest);
self.mixed(hsl(dh, 1.0, 0.05), hsl(dh, ds, (100.0 - 0.1 * h) / 100.0), 60.0 + 0.4 * h, 30.0)
};
t.gradient = Some(Gradient::even(colors, angle));
t.overlays = Overlays::custom(base_mix, light);
t
}
/// One of Discord's Nitro presets: its gradient, surfaces 50 % toward the
/// darker end colour (5 % lightness; the lighter one at 90 % in a light
/// preset), text 38 % toward the other end, very light (dark) and a
/// little softer for blues. Discord's preset maths.
pub fn with_preset(self, p: &GradientPreset) -> Self {
let first = hex(p.stops.first().map_or(0, |s| s.0));
let last = hex(p.stops.last().map_or(0, |s| s.0));
let (lighter, mut darker) = if luminance(first) > luminance(last) { (first, last) } else { (last, first) };
// (Discord: a darker end with hue 0 — grey, black or pure red — gives
// way to the lighter one.)
if hue_of(darker) == 0.0 {
darker = lighter;
}
let light = self.light;
let text_src = if light { darker } else { lighter };
let th = hue_of(text_src);
let blue = (200.0..=300.0).contains(&th);
let text = hsl(th, 1.0, if light { if blue { 0.25 } else { 0.15 } } else if blue { 0.8 } else { 0.95 });
let base = if light { hsl(hue_of(lighter), 1.0, 0.9) } else { hsl(hue_of(darker), 1.0, 0.05) };
let mut t = self.mixed(base, text, 50.0, 38.0);
t.gradient = Some(p.gradient());
t.overlays = Overlays::preset(light);
t
}
/// `base` preset with every slot the translated palette provides replaced.
pub fn from_palette(base: &str, p: &Palette) -> Self {
let mut t = Self::preset(base);
let get = |slot: &str| p.get(slot).map(|[r, g, b, a]| rgba(r, g, b, a));
// Surfaces must be opaque: there's nothing behind the window to blend with.
let opaque = |slot: &str| p.get(slot).map(|[r, g, b, _]| Color32::from_rgb(r, g, b));
macro_rules! set {
(opaque: $($f:ident),*) => { $( if let Some(c) = opaque(stringify!($f)) { t.$f = c; } )* };
($($f:ident),*) => { $( if let Some(c) = get(stringify!($f)) { t.$f = c; } )* };
}
set!(opaque: bg_primary, bg_secondary, bg_secondary_alt, bg_tertiary, bg_floating, input_bg);
set!(
bg_hover, bg_selected, bg_message_hover, bg_mentioned, text_normal, text_muted,
header_primary, header_secondary, interactive_normal, interactive_hover,
interactive_active, interactive_muted, text_link, accent, danger
);
t
}
pub fn apply(&self, ctx: &egui::Context) {
let mut v = if self.light { Visuals::light() } else { Visuals::dark() };
v.override_text_color = Some(self.text_normal);
v.panel_fill = self.bg_primary;
// Popups (tooltips, drop-downs) as Discord draws its tooltips (read
// 2026-11-22): surface-high, a 1 px border-subtle, 8 px corners,
// 8 x 12 px padding and a 0 12 24 rgba(0,0,0,.24) shadow.
v.window_fill = self.surface_high;
v.window_stroke = Stroke::new(1.0_f32, self.border_subtle);
v.window_rounding = Rounding::same(8.0);
v.menu_rounding = Rounding::same(8.0);
v.popup_shadow = egui::epaint::Shadow { offset: egui::vec2(0.0, 12.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(61) };
v.extreme_bg_color = self.bg_tertiary;
v.faint_bg_color = self.bg_secondary_alt;
v.code_bg_color = self.bg_secondary_alt;
v.hyperlink_color = self.text_link;
v.selection.bg_fill = self.accent.gamma_multiply(0.7);
v.selection.stroke = Stroke::new(1.0_f32,self.header_primary);
v.widgets.noninteractive.bg_fill = self.bg_secondary;
v.widgets.noninteractive.weak_bg_fill = self.bg_secondary;
v.widgets.noninteractive.bg_stroke = Stroke::new(1.0_f32, self.border_subtle);
v.widgets.noninteractive.fg_stroke = Stroke::new(1.0_f32,self.text_normal);
v.widgets.inactive.bg_fill = self.input_bg;
v.widgets.inactive.weak_bg_fill = self.input_bg;
v.widgets.inactive.fg_stroke = Stroke::new(1.0_f32,self.interactive_normal);
v.widgets.hovered.bg_fill = self.bg_selected;
v.widgets.hovered.weak_bg_fill = self.bg_selected;
v.widgets.hovered.fg_stroke = Stroke::new(1.5_f32,self.interactive_hover);
v.widgets.hovered.bg_stroke = Stroke::NONE;
v.widgets.active.bg_fill = self.accent;
v.widgets.active.weak_bg_fill = self.accent;
v.widgets.active.fg_stroke = Stroke::new(1.5_f32,self.header_primary);
v.widgets.open.weak_bg_fill = self.bg_secondary_alt;
// No spinner over pictures while they load (avatars, emoji, attachments): Discord
// shows a blurred preview or nothing, never a circle.
v.image_loading_spinners = false;
ctx.set_visuals(v);
ctx.style_mut(|s| s.spacing.menu_margin = egui::Margin::symmetric(12.0, 8.0));
}
}
/// A system font file, memory-mapped: the ~20 MB of fonts (Yu Gothic alone
/// is 11 MB) then live in file-backed pages that are only read in when a
/// glyph needs them, instead of being copied into the heap. Fonts are
/// installed once per run, so the mapping is leaked on purpose.
fn font_file(path: impl AsRef<std::path::Path>) -> Option<FontData> {
let file = std::fs::File::open(path).ok()?;
// SAFETY: Windows' own font files aren't modified while they're in use;
// the mapping is never unmapped (egui keeps the bytes for the whole run).
let map = unsafe { memmap2::Mmap::map(&file) }.ok()?;
let bytes: &'static [u8] = Box::leak(Box::new(map));
Some(FontData::from_static(bytes))
}
/// Windows' font folder, `%SystemRoot%\Fonts` (Windows needn't be on C:).
fn windows_fonts() -> std::path::PathBuf {
std::env::var_os("SystemRoot").map_or_else(|| "C:\\Windows".into(), std::path::PathBuf::from).join("Fonts")
}
/// rrsans (gg sans) compiled into the exe (build.rs sets `rustcord_gg_sans` when
/// the files are in `apps/rustcord/fonts/rrsans`): regular, semibold (RustCord's
/// "bold": Discord's weight for names and headings) and mono.
#[cfg(rustcord_gg_sans)]
const EMBEDDED_GG_SANS: Option<(&[u8], &[u8], &[u8])> = Some((
include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/rrsans/rrsans.ttf")),
include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/rrsans/rrsanssemibold.ttf")),
include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/rrsans/rrsansmono.ttf")),
));
#[cfg(not(rustcord_gg_sans))]
const EMBEDDED_GG_SANS: Option<(&[u8], &[u8], &[u8])> = None;
/// rrsans Medium (weight 500): Discord's weight for channel names, the user
/// panel's name and most UI labels.
#[cfg(rustcord_gg_sans)]
const EMBEDDED_GG_SANS_MEDIUM: Option<&[u8]> = Some(include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/rrsans/rrsansmedium.ttf")));
#[cfg(not(rustcord_gg_sans))]
const EMBEDDED_GG_SANS_MEDIUM: Option<&[u8]> = None;
/// rrsans Bold (700: Discord's weight for **bold** and headings in messages),
/// Italic and Bold Italic (real italic faces, as Discord's `em` uses).
#[cfg(rustcord_gg_sans)]
const EMBEDDED_GG_SANS_STYLES: Option<(&[u8], &[u8], &[u8])> = Some((
include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/rrsans/rrsansbold.ttf")),
include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/rrsans/rrsansitalic.ttf")),
include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/rrsans/rrsansbolditalic.ttf")),
));
#[cfg(not(rustcord_gg_sans))]
const EMBEDDED_GG_SANS_STYLES: Option<(&[u8], &[u8], &[u8])> = None;
/// gg sans files on this PC, which win over the built-in copy: installed for
/// the user or for everyone, or dropped into RustCord's `fonts` folder
/// (`%APPDATA%\RustCord\RustCord\config\fonts`).
/// Returns (regular, heavy) font files; heavy prefers Semibold (Discord's
/// weight for names and headers), then Bold, then Medium.
fn find_gg_sans() -> (Option<std::path::PathBuf>, Option<std::path::PathBuf>) {
let mut dirs: Vec<std::path::PathBuf> = Vec::new();
if let Some(d) = directories::ProjectDirs::from("dev", "RustCord", "RustCord") {
dirs.push(d.config_dir().join("fonts"));
}
if let Some(local) = std::env::var_os("LOCALAPPDATA") {
dirs.push(std::path::PathBuf::from(local).join("Microsoft\\Windows\\Fonts"));
}
if cfg!(windows) {
dirs.push(windows_fonts());
}
let (mut regular, mut heavy): (Option<(u8, std::path::PathBuf)>, Option<(u8, std::path::PathBuf)>) = (None, None);
for dir in dirs {
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for e in entries.flatten() {
let path = e.path();
let ext = path.extension().and_then(|x| x.to_str()).map(str::to_ascii_lowercase);
if !matches!(ext.as_deref(), Some("ttf" | "otf")) {
continue;
}
let stem: String = path.file_stem().and_then(|s| s.to_str()).unwrap_or("").to_ascii_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect();
let Some(weight) = stem.strip_prefix("ggsans").or_else(|| stem.strip_prefix("rrsans")) else { continue };
if weight.contains("italic") || weight.contains("mono") {
continue;
}
// Lower rank wins.
let heavy_rank = if weight.contains("semibold") {
Some(0)
} else if weight.contains("bold") && !weight.contains("extra") {
Some(1)
} else if weight.contains("medium") {
Some(2)
} else {
None
};
match heavy_rank {
Some(rank) => {
if heavy.as_ref().is_none_or(|(r, _)| rank < *r) {
heavy = Some((rank, path));
}
}
None if weight.is_empty() || weight.contains("normal") || weight.contains("regular") || weight.contains("book") => {
if regular.is_none() {
regular = Some((0, path));
}
}
None => {}
}
}
}
(regular.map(|(_, p)| p), heavy.map(|(_, p)| p))
}
include!(concat!(env!("OUT_DIR"), "/dns_fonts.rs"));
/// Display-name font ids that have a font registered (see `install_fonts`).
static DNS_IDS: std::sync::OnceLock<Vec<u32>> = std::sync::OnceLock::new();
/// The egui family for a Discord display-name font id, if RustCord has it.
pub fn dns_family(font_id: u32) -> Option<FontFamily> {
DNS_IDS.get()?.contains(&font_id).then(|| FontFamily::Name(format!("dns-{font_id}").into()))
}
/// Discord's letter spacing for each display-name font, in em.
pub fn dns_letter_spacing(font_id: u32) -> f32 {
match font_id {
3 => 0.04,
6 | 10 => 0.01,
7 | 8 => 0.02,
12 | 14 => 0.03,
_ => 0.0,
}
}
/// Antialias text the way Windows is set to, as Discord's own app (Chromium)
/// does: with ClearType on, glyphs are drawn per LCD subpixel in the screen's
/// colour order, which makes them crisper than grayscale antialiasing.
/// `RUSTCORD_TEXT_AA=gray|rgb|bgr` overrides the setting.
fn use_system_text_antialiasing() {
let from_env = match std::env::var("RUSTCORD_TEXT_AA").ok().as_deref() {
Some("gray") => Some(0),
Some("rgb") => Some(1),
Some("bgr") => Some(2),
_ => None,
};
let mode = from_env.unwrap_or_else(system_text_antialiasing);
log::info!("fonts: {} antialiasing", ["grayscale", "LCD (RGB)", "LCD (BGR)"][mode as usize]);
eframe::egui_glow::painter::TEXT_LCD.store(mode, std::sync::atomic::Ordering::Relaxed);
}
/// 0: grayscale, 1: ClearType on an RGB screen, 2: on a BGR screen.
#[cfg(windows)]
fn system_text_antialiasing() -> u8 {
use windows_sys::Win32::UI::WindowsAndMessaging::{
SystemParametersInfoW, FE_FONTSMOOTHINGCLEARTYPE, FE_FONTSMOOTHINGORIENTATIONBGR, SPI_GETFONTSMOOTHING,
SPI_GETFONTSMOOTHINGORIENTATION, SPI_GETFONTSMOOTHINGTYPE,
};
let get = |what| {
let mut value: u32 = 0;
// SAFETY: each of these settings writes one 32-bit value to the pointer.
let ok = unsafe { SystemParametersInfoW(what, 0, (&mut value as *mut u32).cast(), 0) };
(ok != 0).then_some(value)
};
if get(SPI_GETFONTSMOOTHING) == Some(0) || get(SPI_GETFONTSMOOTHINGTYPE) != Some(FE_FONTSMOOTHINGCLEARTYPE) {
return 0;
}
if get(SPI_GETFONTSMOOTHINGORIENTATION) == Some(FE_FONTSMOOTHINGORIENTATIONBGR) {
2
} else {
1
}
}
#[cfg(not(windows))]
fn system_text_antialiasing() -> u8 {
0
}
/// Scroll as far per mouse-wheel notch as Chromium, and so Discord, does.
/// egui's own 40 points felt stiff next to it (#51).
pub fn use_system_scroll_speed(ctx: &egui::Context) {
let per_notch = wheel_points_per_notch();
log::info!("scrolling: {per_notch:.0} px per wheel notch");
ctx.options_mut(|o| o.line_scroll_speed = per_notch);
}
/// Windows: the "lines to scroll" mouse setting × 100/3 px (100 px with the
/// default 3 lines), as Chromium's wheel events count it.
#[cfg(windows)]
fn wheel_points_per_notch() -> f32 {
use windows_sys::Win32::UI::WindowsAndMessaging::{SystemParametersInfoW, SPI_GETWHEELSCROLLLINES};
// "One screen at a time" (WHEEL_PAGESCROLL, UINT_MAX): the default is used then.
const WHEEL_PAGESCROLL: u32 = u32::MAX;
let mut lines: u32 = 0;
// SAFETY: SPI_GETWHEELSCROLLLINES writes one 32-bit value to the pointer.
let ok = unsafe { SystemParametersInfoW(SPI_GETWHEELSCROLLLINES, 0, (&mut lines as *mut u32).cast(), 0) };
if ok == 0 || lines == 0 || lines == WHEEL_PAGESCROLL {
lines = 3;
}
lines.min(100) as f32 * 100.0 / 3.0
}
/// Linux: Chromium's fixed 53 px per notch (touchpads send exact distances).
#[cfg(all(unix, not(target_os = "macos")))]
fn wheel_points_per_notch() -> f32 {
53.0
}
/// macOS: Chromium's 40 px per notch of a mouse without precise scrolling.
#[cfg(target_os = "macos")]
fn wheel_points_per_notch() -> f32 {
40.0
}
/// Prefer the system UI font where available, and add symbol/emoji
/// fallbacks so more of Discord's text renders.
pub fn install_fonts(ctx: &egui::Context) {
use_system_text_antialiasing();
let mut fonts = FontDefinitions::default();
let (gg_regular, gg_heavy) = find_gg_sans();
// (On Windows, files in its font folder.)
let candidates: &[(&str, &str, bool)] = if cfg!(windows) {
&[
("segoe-ui", "segoeui.ttf", true),
("segoe-symbol", "seguisym.ttf", false),
("segoe-emoji", "seguiemj.ttf", false),
// Other scripts and the decorative characters servers put in
// channel and server names (・ ┃ ꒰ ୨ ᐢ ꕤ ༺ 𓍯 etc.); without these
// they show as boxes. The files are mapped, not read: only the
// pages a lookup touches are loaded, and those stay Windows' file
// cache rather than RustCord's own memory (a font's hinter is only
// made once it draws a glyph). Yu Gothic covers Japanese and most
// Chinese characters; the fonts after Malgun (Korean) are asked,
// in this order, for whatever the ones before them lack.
("yu-gothic", "YuGothR.ttc", false),
("malgun", "malgun.ttf", false),
// Yi (꒰ ꒱ ꒷) and ﹏.
("microsoft-yi-baiti", "msyi.ttf", false),
// Canadian syllabics (ᐢ ᐟ ᘏ) and Cherokee.
("gadugi", "gadugi.ttf", false),
// Vai (ꕤ ꔫ), N'Ko, Ethiopic, Tifinagh.
("ebrima", "ebrima.ttf", false),
// Historic scripts (𓍯 𐭩), the Bamum supplement (𖦹), Syriac marks.
("segoe-ui-historic", "seguihis.ttf", false),
// Indian scripts beyond the digits Segoe UI has (ৎ ൃ): Nirmala UI,
// a .ttf on Windows 10 and in a collection on Windows 11.
("nirmala-ttf", "Nirmala.ttf", false),
("nirmala", "Nirmala.ttc", false),
// Tibetan (༄ ༺ ༻), Tai Le (ᥴ), Mongolian (ᡣ).
("himalaya", "himalaya.ttf", false),
("tai-le", "taile.ttf", false),
("mongolian-baiti", "monbaiti.ttf", false),
// Thai (none of the above has it): Leelawadee UI, which Chrome
// picks for Thai on Windows.
("leelawadee-ui", "LeelawUI.ttf", false),
// Windows 11's catch-all for the rest (𐙚 ᭡ ꪆ ᰔ ᯓ 𖹭); Windows 10 lacks it.
("sans-serif-collection", "SansSerifCollection.ttf", false),
]
} else if cfg!(target_os = "linux") {
// Symbols and other scripts, where each distribution keeps them
// (Debian/Ubuntu, Arch, Fedora); the ones not installed are skipped.
&[
("dejavu-sans", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", false),
("dejavu-sans-arch", "/usr/share/fonts/TTF/DejaVuSans.ttf", false),
("dejavu-sans-fedora", "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf", false),
("noto-cjk", "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", false),
("noto-cjk-arch", "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc", false),
("noto-cjk-fedora", "/usr/share/fonts/google-noto-sans-cjk-fonts/NotoSansCJK-Regular.ttc", false),
// Thai.
("noto-thai", "/usr/share/fonts/truetype/noto/NotoSansThai-Regular.ttf", false),
("noto-thai-arch", "/usr/share/fonts/noto/NotoSansThai-Regular.ttf", false),
("noto-thai-fedora", "/usr/share/fonts/google-noto/NotoSansThai-Regular.ttf", false),
// (Fedora installs the variable font by default.)
("noto-thai-fedora-vf", "/usr/share/fonts/google-noto-vf/NotoSansThai[wght].ttf", false),
// Bengali.
("noto-bengali", "/usr/share/fonts/truetype/noto/NotoSansBengali-Regular.ttf", false),
("noto-bengali-arch", "/usr/share/fonts/noto/NotoSansBengali-Regular.ttf", false),
("noto-bengali-fedora", "/usr/share/fonts/google-noto/NotoSansBengali-Regular.ttf", false),
("noto-bengali-fedora-vf", "/usr/share/fonts/google-noto-vf/NotoSansBengali[wght].ttf", false),
]
} else if cfg!(target_os = "macos") {
// Symbols, Chinese and Japanese (Hiragino Sans GB has kana too) and
// Korean, from the fonts every Mac has.
&[
("apple-symbols", "/System/Library/Fonts/Apple Symbols.ttf", false),
("hiragino-sans-gb", "/System/Library/Fonts/Hiragino Sans GB.ttc", false),
("apple-sd-gothic-neo", "/System/Library/Fonts/AppleSDGothicNeo.ttc", false),
// Thai.
("thonburi", "/System/Library/Fonts/Thonburi.ttc", false),
]
} else {
&[]
};
let mut primary_pos = 0;
// gg sans first (files on this PC, else the built-in copy); Segoe UI fills
// in anything it lacks (other scripts, symbols).
let gg_file = gg_regular.as_ref().and_then(font_file);
let gg = match (gg_file, EMBEDDED_GG_SANS) {
(Some(data), _) => {
log::info!("fonts: using gg sans from {}", gg_regular.as_ref().map(|p| p.display().to_string()).unwrap_or_default());
Some(data)
}
(None, Some((regular, _, _))) => {
log::info!("fonts: using the built-in rrsans");
Some(FontData::from_static(regular))
}
(None, None) => None,
};
if let Some(data) = gg {
fonts.font_data.insert("gg-sans".into(), data);
fonts.families.entry(FontFamily::Proportional).or_default().insert(0, "gg-sans".into());
primary_pos = 1;
}
// Hebrew and Arabic come from Arial, as in Chrome with Discord's font list
// ("gg sans", "Noto Sans", "Helvetica Neue", Helvetica, Arial): gg sans
// has neither, and on Windows Arial is the first of the rest that does.
#[cfg(windows)]
if let Some(data) = font_file(windows_fonts().join("arial.ttf")) {
fonts.font_data.insert(ARIAL_RTL.into(), data.only(hebrew_or_arabic));
fonts.families.entry(FontFamily::Proportional).or_default().insert(primary_pos, ARIAL_RTL.into());
fonts.families.entry(FontFamily::Monospace).or_default().push(ARIAL_RTL.into());
primary_pos += 1;
}
// Code blocks and `inline code` in gg sans mono, like Discord.
if let Some((_, _, mono)) = EMBEDDED_GG_SANS {
fonts.font_data.insert("gg-sans-mono".into(), FontData::from_static(mono));
fonts.families.entry(FontFamily::Monospace).or_default().insert(0, "gg-sans-mono".into());
}
for (name, path, primary) in candidates {
let file = if cfg!(windows) { windows_fonts().join(path) } else { std::path::PathBuf::from(path) };
let Some(data) = font_file(file) else { continue };
fonts.font_data.insert(name.to_string(), data);
let family = fonts.families.entry(FontFamily::Proportional).or_default();
if *primary {
family.insert(primary_pos, name.to_string());
primary_pos += 1;
} else {
family.push(name.to_string());
}
fonts
.families
.entry(FontFamily::Monospace)
.or_default()
.push(name.to_string());
}
// A real bold face for **bold**, names and headings. Always defined (it
// falls back to the regular fonts) because egui panics on unknown families.
let mut bold = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
if cfg!(windows) {
if let Some(data) = font_file(windows_fonts().join("segoeuib.ttf")) {
fonts.font_data.insert("segoe-ui-bold".into(), data);
bold.insert(0, "segoe-ui-bold".into());
}
// Thai in bold; otherwise the regular Leelawadee UI is found first.
if let Some(data) = font_file(windows_fonts().join("LeelaUIb.ttf")) {
fonts.font_data.insert("leelawadee-ui-bold".into(), data.only(thai));
bold.insert(0, "leelawadee-ui-bold".into());
}
if let Some(data) = font_file(windows_fonts().join("arialbd.ttf")) {
fonts.font_data.insert("arial-rtl-bold".into(), data.only(hebrew_or_arabic));
bold.insert(0, "arial-rtl-bold".into());
}
}
let heavy = gg_heavy.as_ref().and_then(font_file).or_else(|| EMBEDDED_GG_SANS.map(|(_, semibold, _)| FontData::from_static(semibold)));
if let Some(data) = heavy {
fonts.font_data.insert("gg-sans-heavy".into(), data);
bold.insert(0, "gg-sans-heavy".into());
}
fonts.families.insert(FontFamily::Name(BOLD.into()), bold);
// Medium (500); the regular fonts stand in without it.
let mut medium = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
if let Some(bytes) = EMBEDDED_GG_SANS_MEDIUM {
fonts.font_data.insert("gg-sans-medium".into(), FontData::from_static(bytes));
medium.insert(0, "gg-sans-medium".into());
}
fonts.families.insert(FontFamily::Name(MEDIUM.into()), medium);
// Message markup: Bold (700), Italic and Bold Italic. Always defined;
// without the files they fall back to semibold / the regular fonts.
let regular = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
let heavy = fonts.families.get(&FontFamily::Name(BOLD.into())).cloned().unwrap_or_default();
let (mut strong, mut italic, mut strong_italic) = (heavy.clone(), regular, heavy);
if let Some((bold, ital, bold_ital)) = EMBEDDED_GG_SANS_STYLES {
for (key, bytes, family) in [("gg-sans-bold", bold, &mut strong), ("gg-sans-italic", ital, &mut italic), ("gg-sans-bold-italic", bold_ital, &mut strong_italic)] {
fonts.font_data.insert(key.into(), FontData::from_static(bytes));
family.insert(0, key.into());
}
}
fonts.families.insert(FontFamily::Name(STRONG.into()), strong.clone());
fonts.families.insert(FontFamily::Name(ITALIC.into()), italic);
fonts.families.insert(FontFamily::Name(STRONG_ITALIC.into()), strong_italic.clone());
// Discord's display face for badge names ("ABC Ginto Discord Nord": Bold,
// Bold Italic and Black Italic), falling back to gg sans in the same style.
for (key, bytes, fallback) in
[(GINTO_BOLD, GINTO_NORD_700, &strong), (GINTO_BOLD_ITALIC, GINTO_NORD_700I, &strong_italic), (GINTO_BLACK_ITALIC, GINTO_NORD_900I, &strong_italic)]
{
fonts.font_data.insert(key.into(), FontData::from_static(bytes));
let mut family = vec![key.to_string()];
family.extend(fallback.iter().cloned());
fonts.families.insert(FontFamily::Name(key.into()), family);
}
// Nitro display-name fonts: a family per Discord font id, falling back to
// the UI fonts for characters the display font lacks.
let fallback = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
let mut ids = Vec::new();
for (id, bytes) in DNS_FONTS {
let key = format!("dns-{id}");
fonts.font_data.insert(key.clone(), FontData::from_static(bytes));
let mut family = vec![key.clone()];
family.extend(fallback.iter().cloned());
fonts.families.insert(FontFamily::Name(key.as_str().into()), family);
ids.push(*id);
}
let _ = DNS_IDS.set(ids);
// Discord's own icons first (built from its SVGs into a font, at the Segoe
// code points RustCord uses plus a few new ones); anything they don't
// cover falls back to Windows' Segoe Fluent Icons, then MDL2 (elsewhere,
// to Discord's nearest icons).
fonts.font_data.insert("discord-icons".into(), FontData::from_static(DISCORD_ICONS));
let mut icons = vec!["discord-icons".to_string()];
#[cfg(not(windows))]
{
fonts.font_data.insert("discord-icons-fallback".into(), FontData::from_static(DISCORD_ICONS_FALLBACK));
icons.push("discord-icons-fallback".into());
}
#[cfg(windows)]
for file in ["SegoeIcons.ttf", "segmdl2.ttf"] {
if let Some(data) = font_file(windows_fonts().join(file)) {
fonts.font_data.insert(file.into(), data);
icons.push(file.to_string());
}
}
icons.extend(fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default());
fonts.families.insert(FontFamily::Name(ICONS.into()), icons);
ctx.set_fonts(fonts);
}
/// Arial, for Hebrew and Arabic only (see `install_fonts`).
#[cfg(windows)]
const ARIAL_RTL: &str = "arial-rtl";
/// Thai letters, vowels, tone marks and digits.
fn thai(c: char) -> bool {
matches!(c as u32, 0x0E00..=0x0E7F)
}
/// Hebrew and Arabic letters, marks, digits and presentation forms.
fn hebrew_or_arabic(c: char) -> bool {
matches!(c as u32, 0x0590..=0x06FF | 0x0750..=0x077F | 0x08A0..=0x08FF | 0xFB1D..=0xFDFF | 0xFE70..=0xFEFE)
}
pub const BOLD: &str = "bold";
pub const MEDIUM: &str = "medium";
pub const STRONG: &str = "strong";
pub const ITALIC: &str = "italic";
pub const STRONG_ITALIC: &str = "strong-italic";
/// "ABC Ginto Discord Nord" Bold / Bold Italic / Black Italic (badge names).
/// Discord ships no upright Black: its upright heavy capitals are the Bold
/// face.
pub const GINTO_BOLD: &str = "ginto-700";
pub const GINTO_BOLD_ITALIC: &str = "ginto-700i";
pub const GINTO_BLACK_ITALIC: &str = "ginto-900i";
const GINTO_NORD_700: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/ginto/ginto-nord-700.ttf"));
const GINTO_NORD_700I: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/ginto/ginto-nord-700-italic.ttf"));
const GINTO_NORD_900I: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/ginto/ginto-nord-900-italic.ttf"));
/// The family for message markup: regular, **bold** (gg sans 700), *italic*
/// (a real italic face) or both.
pub fn markup_family(bold: bool, italic: bool) -> FontFamily {
match (bold, italic) {
(false, false) => FontFamily::Proportional,
(true, false) => FontFamily::Name(STRONG.into()),
(false, true) => FontFamily::Name(ITALIC.into()),
(true, true) => FontFamily::Name(STRONG_ITALIC.into()),
}
}
pub const ICONS: &str = "icons";
/// gg sans Medium at `size` (Discord's font-weight 500).
pub fn medium(size: f32) -> egui::FontId {
egui::FontId::new(size, FontFamily::Name(MEDIUM.into()))
}
/// Discord's icons (its 24×24 SVGs, as a font).
const DISCORD_ICONS: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/discord-icons.ttf"));
/// Off Windows: Discord's icons at the Segoe code points that Windows' own
/// icon font draws there.
#[cfg(not(windows))]
const DISCORD_ICONS_FALLBACK: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/discord-icons-fallback.ttf"));
pub fn icon_font(size: f32) -> egui::FontId {
egui::FontId::new(size, FontFamily::Name(ICONS.into()))
}
/// Icon code points: Segoe Fluent Icons ones (most drawn with Discord's own
/// icon from `fonts/discord-icons.ttf`), plus Discord-only icons in U+F1001…
pub mod icon {
pub const HASH: &str = "\u{F1001}";
pub const ANNOUNCEMENT: &str = "\u{F1002}";
pub const FORUM: &str = "\u{F1003}";
pub const STAGE: &str = "\u{F1004}";
pub const THREAD: &str = "\u{F1005}";
/// Discord's header "Threads" button (spools of thread).
pub const THREADS: &str = "\u{F1018}";
pub const GIFT: &str = "\u{F1008}";
pub const GIF: &str = "\u{F1009}";
pub const STICKER: &str = "\u{F100A}";
pub const BOOST: &str = "\u{F100B}";
pub const FRIENDS: &str = "\u{F100C}";
pub const USER_PLUS: &str = "\u{F100E}";
/// A handset with sound waves (Discord's "Start Voice Call").
pub const PHONE_CALL: &str = "\u{F1015}";
/// People with a plus (Discord's "Add to DM"; the button isn't built yet).
#[allow(dead_code)]
pub const GROUP_PLUS: &str = "\u{F1016}";
/// A filled person in a circle (Discord's "Show User Profile").
pub const USER_CIRCLE: &str = "\u{F1017}";
/// Discord's BadgeIcon (a rosette), OrbsIcon, UserCircleIcon (filled) and
/// ChevronSmallRightIcon.
pub const BADGE: &str = "\u{F1019}";
pub const ORBS: &str = "\u{F101A}";
pub const USER_CIRCLE_FILLED: &str = "\u{F101B}";
pub const CHEVRON_SMALL_RIGHT: &str = "\u{F101C}";
/// CircleInformationIcon, ArrowSmallLeft/Right, EyeSlashIcon.
pub const CIRCLE_INFO: &str = "\u{F101D}";
pub const ARROW_LEFT: &str = "\u{F101E}";
pub const ARROW_RIGHT: &str = "\u{F101F}";
pub const EYE_SLASH: &str = "\u{F1020}";
/// GameControllerIcon, LightningIcon, FireIcon and the "New Player" sprout
/// (Discord's recent-activity cards).
pub const GAME_CONTROLLER: &str = "\u{F1021}";
pub const BOLT: &str = "\u{F1022}";
pub const FLAME: &str = "\u{F1023}";
pub const SPROUT: &str = "\u{F1024}";
/// MusicIcon, TvIcon and AppsIcon (what someone is doing, in the member
/// and DM lists) and StickerSmallIcon (a sticker's tooltip).
pub const MUSIC: &str = "\u{F1025}";
pub const TV: &str = "\u{F1026}";
pub const APPS: &str = "\u{F1027}";
pub const STICKER_SMALL: &str = "\u{F1028}";
/// CrownIcon: the group owner in a group DM's member list.
pub const CROWN: &str = "\u{F1029}";
pub const INVITE: &str = "\u{E8FA}";
pub const MIC_OFF: &str = "\u{F781}";
pub const DEAFENED: &str = "\u{F100F}";
pub const VOICE: &str = "\u{F1010}";
/// LockIcon (Nitro-locked emoji in the picker).
pub const LOCK: &str = "\u{E72E}";
pub const TEXT_LOCK: &str = "\u{F1011}";
pub const VOICE_LOCK: &str = "\u{F1012}";
pub const ANNOUNCEMENT_LOCK: &str = "\u{F1013}";
pub const FORUM_LOCK: &str = "\u{F1014}";
pub const BELL_SLASH: &str = "\u{E7ED}";
pub const BELL: &str = "\u{EA8F}";
pub const CALENDAR: &str = "\u{E787}";
pub const LEAVE: &str = "\u{E7E8}";
pub const EDIT: &str = "\u{E70F}";
pub const REPLY: &str = "\u{E7A7}";
pub const FORWARD: &str = "\u{E7A6}";
pub const COPY: &str = "\u{E8C8}";
pub const PIN: &str = "\u{E718}";
pub const UNPIN: &str = "\u{E77A}";
pub const UNREAD: &str = "\u{F1006}";
pub const LINK: &str = "\u{E71B}";
pub const DOWNLOAD: &str = "\u{E896}";
pub const OPEN_EXTERNAL: &str = "\u{E8A7}";
pub const SPEAK: &str = "\u{E767}";
pub const DELETE: &str = "\u{E74D}";
pub const ID: &str = "\u{E8EC}";
pub const EMOJI: &str = "\u{E76E}";
pub const CHEVRON: &str = "\u{E76C}";
pub const ADD: &str = "\u{E710}";
pub const MORE: &str = "\u{E712}";
pub const PLUGIN: &str = "\u{EA86}";
pub const MESSAGE: &str = "\u{E8BD}";
pub const FILE: &str = "\u{E8A5}";
pub const AUDIO: &str = "\u{E8D6}";
pub const FOLDER: &str = "\u{E8B7}";
pub const PEOPLE: &str = "\u{E716}";
pub const SETTINGS: &str = "\u{E713}";
pub const CHECK: &str = "\u{E73E}";
pub const CLOSE: &str = "\u{E711}";
pub const MAIL: &str = "\u{F1006}";
pub const SHIELD: &str = "\u{EA18}";
pub const BACK: &str = "\u{E72B}";
pub const FORWARD_NAV: &str = "\u{E72A}";
pub const INBOX: &str = "\u{E715}";
pub const HELP: &str = "\u{E897}";
pub const GAME: &str = "\u{E7FC}";
pub const PROFILE: &str = "\u{E77B}";
pub const SEARCH: &str = "\u{E721}";
pub const MIC: &str = "\u{E720}";
pub const HEADPHONES: &str = "\u{E7F6}";
pub const CHEVRON_DOWN: &str = "\u{E70D}";
/// Filled star (Discord's Favourites).
pub const STAR: &str = "\u{E735}";
pub const NITRO: &str = "\u{E945}";
pub const SHOP: &str = "\u{E7BF}";
pub const QUESTS: &str = "\u{F1007}";
pub const PLAY: &str = "\u{E768}";
pub const PAUSE: &str = "\u{E769}";
pub const MUTE: &str = "\u{E74F}";
}
/// `RichText` in the bold family.
/// Discord's translucent "mod" overlay, rgba(151,151,159,`a`), blended the
/// way a browser does (see [`rgba`]).
pub fn overlay(a: f32) -> Color32 {
modc(a.clamp(0.0, 1.0))
}
pub fn bold(text: impl Into<String>) -> egui::RichText {
egui::RichText::new(text).family(FontFamily::Name(BOLD.into()))
}
/// Discord's default-avatar palette, picked from the name.
pub fn color_for(name: &str) -> Color32 {
const COLORS: [Color32; 6] = [
hex(0x5865f2),
hex(0x757e8a),
hex(0x3ba55c),
hex(0xfaa61a),
hex(0xed4245),
hex(0xeb459f),
];
let h = name.bytes().fold(0u32, |a, b| a.wrapping_mul(31).wrapping_add(b as u32));
COLORS[(h % 6) as usize]
}
#[cfg(test)]
mod tests {
use eframe::egui::epaint::text::{FontData, FontDefinitions, LayoutJob, LayoutSection, TextFormat};
use eframe::egui::epaint::Fonts;
use eframe::egui::{FontFamily, FontId};
/// The decorative characters servers put in their names (issue #3) have a
/// font: Yi, Canadian syllabics, Vai, Tibetan, Bengali, historic scripts,
/// and Windows 11's catch-all for the rest.
#[cfg(windows)]
#[test]
fn decorative_characters_have_a_font() {
let ctx = eframe::egui::Context::default();
super::install_fonts(&ctx);
let _ = ctx.run(Default::default(), |_| {});
let mut chars = String::from("꒰꒱꒷୨୧⊹⋆⟡ᐢᐟᘏꕤꔫ༄༺༻ৎ𓍯𐭩﹏・┃");
if super::windows_fonts().join("SansSerifCollection.ttf").exists() {
chars.push_str("𐙚᭡ꪆᰔᯓ");
}
let missing: String = chars.chars().filter(|c| !ctx.fonts(|f| f.has_glyph(&FontId::proportional(16.0), *c))).collect();
assert!(missing.is_empty(), "no font for {missing}");
}
/// Hinting makes letters a whole number of pixels tall, as Chrome draws
/// Discord's text: the x-height at 16 px is 8 px (7.52 px unhinted).
/// `-- --nocapture` prints the glyphs for comparing with Chrome's.
#[test]
fn hinted_letters_fill_whole_pixels() {
use eframe::egui::epaint::text::hinted::Hinted;
let Ok(bytes) = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/rrsans/rrsans.ttf")) else { return };
let data: &'static [u8] = Box::leak(bytes.into_boxed_slice());
let hinted = Hinted::new(data, 0, 16.0).expect("gg sans carries hinting");
for ch in ['H', 'o', 'l', 'e', 'x'] {
let r = hinted.raster(hinted.glyph_id(ch).unwrap(), 1.0).unwrap();
println!("{ch}: {}x{} at ({}, {})", r.width, r.height, r.min_x, r.min_y);
for y in 0..r.height {
let row: String = (0..r.width).map(|x| format!("{:3} ", (r.coverage[y * r.width + x] * 100.0).round() as i32)).collect();
println!(" {row}");
}
}
let x = hinted.raster(hinted.glyph_id('x').unwrap(), 1.0).unwrap();
assert_eq!((x.min_y, x.height), (-8, 8));
for mode in 0..7u8 {
let Some(h) = Hinted::with_mode(data, 0, 16.0, mode) else { continue };
for ch in ['o', 'H'] {
let r = h.raster(h.glyph_id(ch).unwrap(), 1.0).unwrap();
let row = |y: usize| -> String { (0..r.width).map(|x| format!("{:3} ", (r.coverage[y * r.width + x] * 100.0).round() as i32)).collect() };
println!("mode {mode} {ch}: {}x{} at ({}, {}) | {} | {} | {}", r.width, r.height, r.min_x, r.min_y, row(0), row(1), row(5));
}
}
}
/// A glyph drawn a quarter, half or three quarters of a pixel to the
/// right (subpixel positioning) has the same amount of ink as the
/// unshifted one. The "Y" and "V" at 12.5 px used to come out as a filled
/// box with the letter cut out when shifted by 0.75 px: their left edge
/// then sits exactly on a pixel border.
#[test]
fn shifted_glyphs_keep_their_ink() {
let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/fonts/rrsans");
for file in ["rrsans.ttf", "rrsansmedium.ttf", "rrsanssemibold.ttf"] {
// The fonts aren't in every checkout.
let Ok(bytes) = std::fs::read(format!("{dir}/{file}")) else { continue };
let mut defs = FontDefinitions::default();
defs.font_data.insert("gg".into(), FontData::from_owned(bytes).into());
defs.families.entry(FontFamily::Proportional).or_default().insert(0, "gg".into());
let fonts = Fonts::new(1.0, 8192, defs);
let ink = |c: char, size: f32, shift: f32| -> f32 {
let text = c.to_string();
let job = LayoutJob {
sections: vec![LayoutSection {
leading_space: shift,
byte_range: 0..text.len(),
format: TextFormat { font_id: FontId::proportional(size), ..Default::default() },
}],
text,
..Default::default()
};
let galley = fonts.layout_job(job);
let uv = galley.rows[0].glyphs[0].uv_rect;
let image = fonts.image();
let mut sum = 0.0;
for y in uv.min[1]..uv.max[1] {
for x in uv.min[0]..uv.max[0] {
// (The atlas keeps opacity: back to coverage.)
let opacity = image.pixels[y as usize * image.size[0] + x as usize];
sum += (opacity as f32 / 255.0).powf(1.0 / eframe::egui::epaint::FontImage::GAMMA);
}
}
sum
};
for size in [10.0, 11.0, 12.0, 12.5, 13.0, 14.0, 15.0, 16.0, 20.0, 24.0] {
for c in ('A'..='Z').chain('a'..='z').chain('0'..='9') {
let base = ink(c, size, 0.0);
for shift in [0.25, 0.5, 0.75] {
let shifted = ink(c, size, shift);
assert!(
(shifted - base).abs() <= base * 0.1 + 0.5,
"{file}: {c:?} at {size} px shifted {shift} px has ink {shifted}, unshifted {base}"
);
}
}
}
}
}
/// A right-to-left word inside left-to-right text runs right to left,
/// and the cursor goes on the side of a character it starts on. (egui's
/// own fonts have no Hebrew: its letters are replacement boxes, which is
/// enough for their order.)
#[test]
fn right_to_left_text_is_reordered() {
let fonts = Fonts::new(1.0, 1024, FontDefinitions::default());
let text = "ab \u{5d0}\u{5d1}\u{5d2} cd";
let galley = fonts.layout_job(LayoutJob::single_section(text.into(), TextFormat::default()));
let row = &galley.rows[0];
assert_eq!(row.text(), text);
let x: Vec<f32> = row.glyphs.iter().map(|g| g.pos.x).collect();
assert!(x[0] < x[1] && x[1] < x[2] && x[2] < x[5] && x[5] < x[4] && x[4] < x[3] && x[3] < x[6], "{x:?}");
assert!(row.glyphs[3].is_rtl() && !row.glyphs[0].is_rtl() && !row.glyphs[6].is_rtl());
assert_eq!(row.x_offset(3), row.glyphs[3].max_x());
// A right-to-left letter's right half is before it, its left half after.
assert_eq!(row.char_at(row.glyphs[3].max_x() - 0.5), 3);
assert_eq!(row.char_at(row.glyphs[3].pos.x + 0.5), 4);
assert_eq!(row.char_at(row.glyphs[5].pos.x + 0.5), 6);
// Left-to-right text keeps its order and level.
let galley = fonts.layout_job(LayoutJob::single_section("Hello, world".into(), TextFormat::default()));
assert!(galley.rows[0].glyphs.iter().all(|g| g.bidi_level == 0));
assert!(galley.rows[0].glyphs.windows(2).all(|w| w[0].pos.x < w[1].pos.x));
}
/// Arabic letters join (issue #13: a word came out as separate letters):
/// shaped, from Arial as in Chrome, and laid out right to left.
#[cfg(windows)]
#[test]
fn arabic_letters_join() {
let ctx = eframe::egui::Context::default();
super::install_fonts(&ctx);
let _ = ctx.run(Default::default(), |_| {});
let format = TextFormat { font_id: FontId::proportional(16.0), ..Default::default() };
let layout = |text: &str| ctx.fonts(|f| f.layout_job(LayoutJob::single_section(text.into(), format.clone())));
let word = "\u{633}\u{644}\u{627}\u{645}"; // salam
let galley = layout(word);
let row = &galley.rows[0];
assert_eq!(row.text(), word);
assert!(row.glyphs.iter().all(|g| g.is_rtl()));
// The first letter is the rightmost.
let lefts: Vec<f32> = row.glyphs.iter().filter(|g| 0.0 < g.advance_width).map(|g| g.pos.x).collect();
assert!(lefts.windows(2).all(|w| w[0] > w[1]), "{lefts:?}");
// Joined letters take other forms, so other widths, than alone.
let alone: f32 = word.chars().map(|c| layout(&c.to_string()).rows[0].glyphs[0].advance_width).sum();
let joined: f32 = row.glyphs.iter().map(|g| g.advance_width).sum();
assert!((joined - alone).abs() > 1.0, "joined {joined}, alone {alone}");
// As wide as Chrome draws it with Discord's font list (measured on
// Discord web: 30.188 px).
let galley = layout("\u{645}\u{631}\u{62d}\u{628}\u{627}");
assert!((galley.rows[0].rect.width() - 30.188).abs() < 0.6, "{}", galley.rows[0].rect.width());
}
/// Bengali and the other scripts of South and South-East Asia are shaped
/// (PR #11): a conjunct, or a consonant with its vowel sign, is one
/// picture while each character keeps a glyph of its own (for the cursor
/// and copying), and words are as wide as Chrome draws them in the same
/// font (measured on Discord web, 2026-12-04).
#[cfg(windows)]
#[test]
fn brahmic_letters_are_shaped() {
let ctx = eframe::egui::Context::default();
super::install_fonts(&ctx);
let _ = ctx.run(Default::default(), |_| {});
let format = TextFormat { font_id: FontId::proportional(16.0), ..Default::default() };
let layout = |text: &str| ctx.fonts(|f| f.layout_job(LayoutJob::single_section(text.into(), format.clone())));
// "ki" (the vowel sign goes before the consonant) and "ksha" (a conjunct).
for (text, chars) in [("\u{995}\u{9bf}", 2), ("\u{995}\u{9cd}\u{9b7}", 3)] {
let galley = layout(text);
let glyphs = &galley.rows[0].glyphs;
assert_eq!(glyphs.len(), chars, "{text}: a glyph per character");
assert_eq!(glyphs.iter().filter(|g| !g.uv_rect.is_nothing()).count(), 1, "{text}: one picture");
}
for (text, chrome) in [
// Bengali and Tamil: Nirmala UI, in Chrome with Discord's font list too.
("\u{9ac}\u{9be}\u{982}\u{9b2}\u{9be}", 36.766),
("\u{9af}\u{9be}\u{99a}\u{9cd}\u{99b}\u{9c7}", 37.922),
("\u{9ae}\u{9c2}\u{9b2}\u{9cd}\u{9af}\u{9be}\u{9af}\u{9bc}\u{9a8}", 53.75),
("\u{ba4}\u{bae}\u{bbf}\u{bb4}\u{bcd}", 47.5),
// Hindi in Nirmala UI. (Discord web draws Devanagari in its own
// Noto Sans instead, 26.766 px wide.)
("\u{939}\u{93f}\u{928}\u{94d}\u{926}\u{940}", 32.594),
] {
let width = layout(text).rows[0].rect.width();
// (Within a pixel: a row ends at the whole pixel its last letter
// is drawn from, plus that letter's width.)
assert!((width - chrome).abs() < 1.0, "{text}: {width} px (Chrome {chrome})");
}
}
/// Arabic, Latin, Hebrew and digits in one line land where Chrome puts
/// them (Discord web's message font, measured 2026-12-03: the left edge
/// of each character below).
#[cfg(windows)]
#[test]
fn mixed_directions_match_chrome() {
let ctx = eframe::egui::Context::default();
super::install_fonts(&ctx);
let _ = ctx.run(Default::default(), |_| {});
let format = TextFormat { font_id: FontId::proportional(16.0), ..Default::default() };
let text = "\u{645}\u{631}\u{62d}\u{628}\u{627} \u{628}\u{627}\u{644}\u{639}\u{627}\u{644}\u{645}\u{60c} \u{643}\u{64a}\u{641} \u{62d}\u{627}\u{644}\u{643}\u{61f} \u{2014} Hello \u{5e9}\u{5dc}\u{5d5}\u{5dd} \u{5e2}\u{5d5}\u{5dc}\u{5dd} 123";
let galley = ctx.fonts(|f| f.layout_job(LayoutJob::single_section(text.into(), format)));
let row = &galley.rows[0];
let left = |c: char| {
let i = text.chars().position(|x| x == c).unwrap();
row.glyphs[i].pos.x
};
for (c, chrome) in [('\u{61f}', 0.0), ('\u{645}', 122.7), ('\u{2014}', 132.6), ('H', 148.7), ('1', 187.3), ('\u{5e2}', 234.5), ('\u{5e9}', 267.4)] {
assert!((left(c) - chrome).abs() < 2.5, "{c:?} at {} (Chrome {chrome})", left(c));
}
}
}