Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

103 KB
Raw Blame
//! egui rendering. Each submodule adds `impl RustCord` blocks.

mod call;
mod chat;
mod chat_placeholder;
pub mod emoji_frecency;
mod compose_tools;
mod connections;
mod embeds;
pub mod reactions;
mod expression;
pub mod forum;
mod friends;
pub mod friend_nickname;
pub mod guild_pages;
pub mod boosts;
pub mod interactions;
mod login;
mod members;
mod mentions;
pub mod search;
pub mod motion;
mod popups;
pub mod process_viewer;
mod profile;
pub use profile::ProfileMore;
mod profile_effect;
mod profile_theme;
mod server;
mod server_settings;
pub mod tag_badges;
pub mod tag_adopt;
mod settings;
mod settings_icons;
mod shortcuts;
mod brand_icons;
mod sidebar;
mod typing_fx;
pub mod voice_menu;
pub mod soundboard;
pub mod badges;
pub mod invite;
mod store;
pub mod switch_accounts;
pub mod moderation;
pub mod guild_menu;
pub mod channel_menu;
pub mod group_dm;
pub mod autoscroll;
pub mod add_server;
pub mod request_log;
mod experimental;
pub mod spam_warnings;
pub mod leaving;
pub mod spotify_player;
pub mod app_directory;
pub mod voice_notice;
pub mod updates;

use crate::app::{RustCord, Screen};
use crate::style::{color_for, icon, icon_font, Theme};
use discord::model::channel_kind;
use eframe::egui::{
    self, pos2, vec2, viewport::ResizeDirection, Align2, CentralPanel, Color32, CursorIcon, FontId, Frame, Margin,
    Order, Rect, Response, Sense, SidePanel, Stroke, TopBottomPanel, Ui, ViewportCommand,
};
use std::time::Duration;

/// Layout sizes from Discord's own CSS (visual refresh).
pub const TITLE_BAR: f32 = 32.0;
pub const GUILD_BAR: f32 = 72.0;
/// Server list + channel list together (Discord's --custom-guild-sidebar-width):
/// 375 by default, resizable between 264 and 432 by dragging its edge.
pub const SIDEBAR_DEFAULT: f32 = 375.0;
pub const SIDEBAR_MIN: f32 = 264.0;
pub const SIDEBAR_MAX: f32 = 432.0;
/// The channel list's default width.
pub const SIDEBAR: f32 = SIDEBAR_DEFAULT - GUILD_BAR;
pub const MEMBERS: f32 = 264.0;
pub const HEADER: f32 = 48.0;
/// Space kept free under the server and channel lists for the floating user panel.
pub const USER_PANEL_SPACE: f32 = 72.0;

impl RustCord {
    /// Discord-style title bar: where you are in the middle, window buttons on
    /// the right; drag to move, double-click to maximise.
    pub fn title_bar(&mut self, ctx: &egui::Context) {
        let t = self.theme.clone();
        let location: Option<(Option<String>, String)> = match self.screen {
            Screen::Login => Some((None, "RustCord".into())),
            Screen::Main => match self.current_guild {
                Some(crate::app::FAVORITES) => Some((None, "Favourites".into())),
                // A server without an icon gets its acronym tile, as in Discord.
                Some(g) => self.store.guilds.get(&g).map(|gs| (gs.guild.icon_url(32).or_else(|| Some(format!("acronym:{}", acronym(&gs.guild.name)))), gs.guild.name.clone())),
                None if self.friends_open || self.current_channel.is_none() => {
                    use crate::features::StorePage;
                    // Discord: the page's own icon before its name.
                    let (glyph, title) = match (self.requests_open, self.store_page) {
                        (true, _) => (icon::MAIL, "Message Requests"),
                        (_, Some(StorePage::Nitro)) => (icon::NITRO, "Nitro"),
                        (_, Some(StorePage::Shop)) => (icon::SHOP, "Shop"),
                        (_, Some(StorePage::Quests)) => (icon::QUESTS, "Quests"),
                        _ => (icon::FRIENDS, "Friends"),
                    };
                    Some((Some(format!("glyph:{glyph}")), title.into()))
                }
                // Discord: every DM and group DM is titled "Direct Messages",
                // after its logo.
                None => Some((Some("logo:".into()), "Direct Messages".into())),
            },
        };
        let maximized = ctx.input(|i| i.viewport().maximized.unwrap_or(false));
        TopBottomPanel::top("title_bar")
            .exact_height(TITLE_BAR)
            .show_separator_line(false)
            .frame(Frame::none().fill(if t.gradient.is_some() { Color32::TRANSPARENT } else { t.bg_tertiary }))
            .show(ctx, |ui| {
                let bar = ui.max_rect();
                paint_theme_surface(ctx, ui.painter(), bar, 0.0, surface::FRAME, &t);
                // Window buttons. macOS has the window's own traffic lights,
                // at the left end instead.
                let mut x = bar.right();
                let own_buttons = if cfg!(target_os = "macos") { 0 } else { 3 };
                for (tip, cmd) in [("Close", 0), (if maximized { "Restore" } else { "Maximize" }, 1), ("Minimize", 2)].into_iter().take(own_buttons) {
                    let r = Rect::from_min_max(pos2(x - 46.0, bar.top()), pos2(x, bar.bottom()));
                    x -= 46.0;
                    let b = ui.interact(r, egui::Id::new(("window_btn", cmd)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                    if b.hovered() {
                        ui.painter().rect_filled(r, 0.0, if cmd == 0 { Color32::from_rgb(0xda, 0x37, 0x3c) } else { t.bg_hover });
                    }
                    let c = if b.hovered() && cmd == 0 { Color32::WHITE } else { t.interactive_normal };
                    paint_caption_glyph(ui.painter(), ui.painter().round_pos_to_pixels(r.center()), cmd, maximized, c);
                    if b.on_hover_text(tip).clicked() {
                        match cmd {
                            0 => ctx.send_viewport_cmd(ViewportCommand::Close),
                            1 => ctx.send_viewport_cmd(ViewportCommand::Maximized(!maximized)),
                            _ => ctx.send_viewport_cmd(ViewportCommand::Minimized(true)),
                        }
                    }
                }
                let main = self.screen == Screen::Main;
                // Help and Inbox, left of the window buttons.
                let mut open_inbox = None;
                if main {
                    x -= 8.0;
                    for (glyph, tip, which) in [(icon::HELP, "Help", 0), (icon::INBOX, "Inbox", 1)] {
                        let r = Rect::from_center_size(pos2(x - 14.0, bar.center().y), vec2(28.0, 24.0));
                        x -= 32.0;
                        let b = ui.interact(r, egui::Id::new(("title_tool", which)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                        let active = which == 1 && self.inbox.is_some();
                        if b.hovered() || active {
                            ui.painter().rect_filled(r, 4.0, t.bg_hover);
                        }
                        let c = if b.hovered() || active { t.header_primary } else { t.interactive_normal };
                        ui.painter().text(r.center(), Align2::CENTER_CENTER, glyph, icon_font(15.0), c);
                        if b.on_hover_text(tip).clicked() {
                            if which == 0 {
                                ctx.open_url(egui::OpenUrl::new_tab("https://support.discord.com"));
                            } else {
                                open_inbox = Some(pos2(r.right(), bar.bottom() + 4.0));
                            }
                        }
                    }
                }
                // Discord's update button, green, left of them: clickable once
                // the update is installed, greyed while it downloads.
                let mut update = false;
                if let Some(ready) = self.updater.as_ref().and_then(|u| u.title_bar_button()) {
                    let r = Rect::from_center_size(pos2(x - 14.0, bar.center().y), vec2(28.0, 24.0));
                    x -= 32.0;
                    let b = ui.interact(r, egui::Id::new("title_update"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                    if ready && b.hovered() {
                        ui.painter().rect_filled(r, 4.0, t.bg_hover);
                    }
                    let green = updates::GREEN;
                    ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::DOWNLOAD, icon_font(15.0), if ready { green } else { green.gamma_multiply(0.5) });
                    let b = b.on_hover_text(if ready { updates::READY } else { updates::DOWNLOADING });
                    update = ready && b.on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
                }
                if update {
                    self.install_update(ctx);
                }
                // Back / forward, far left (on macOS after the traffic lights,
                // which full screen hides).
                let traffic_lights = cfg!(target_os = "macos") && !ctx.input(|i| i.viewport().fullscreen.unwrap_or(false));
                let mut left = bar.left() + if traffic_lights { 76.0 } else { 8.0 };
                let mut nav = None;
                if main {
                    for (glyph, tip, fwd, enabled) in [
                        (icon::BACK, "Back", false, !self.nav_back.is_empty()),
                        (icon::FORWARD_NAV, "Forward", true, !self.nav_forward.is_empty()),
                    ] {
                        let r = Rect::from_min_size(pos2(left, bar.center().y - 12.0), vec2(28.0, 24.0));
                        left += 30.0;
                        let b = ui.interact(r, egui::Id::new(("title_nav", fwd)), if enabled { Sense::click() } else { Sense::hover() }).on_hover_cursor(if enabled { egui::CursorIcon::PointingHand } else { egui::CursorIcon::Default });
                        if enabled && b.hovered() {
                            ui.painter().rect_filled(r, 4.0, t.bg_hover);
                        }
                        let c = if !enabled { t.interactive_normal.gamma_multiply(0.35) } else if b.hovered() { t.header_primary } else { t.interactive_normal };
                        ui.painter().text(r.center(), Align2::CENTER_CENTER, glyph, icon_font(12.0), c);
                        if enabled && b.on_hover_text(tip).clicked() {
                            nav = Some(fwd);
                        }
                    }
                }
                if let Some(fwd) = nav {
                    self.navigate_history(fwd);
                }
                if let Some(at) = open_inbox {
                    if self.inbox.take().is_none() {
                        self.inbox = Some((at, None));
                        self.inbox_opened_frame = ctx.cumulative_pass_nr();
                        self.backend.send(crate::backend::Command::FetchMentions);
                    }
                }
                // Drag area (everything else).
                let drag = Rect::from_min_max(pos2(left, bar.top()), pos2(x, bar.bottom()));
                let d = ui.interact(drag, egui::Id::new("title_drag"), Sense::click_and_drag());
                if d.drag_started() {
                    ctx.send_viewport_cmd(ViewportCommand::StartDrag);
                }
                if d.double_clicked() {
                    ctx.send_viewport_cmd(ViewportCommand::Maximized(!maximized));
                }
                // Where you are, centred.
                // Discord: 14 px medium, a 16 px icon (4 px corners) 8 px before it.
                if let Some((icon_url, label)) = location {
                    let galley = ui.painter().layout_no_wrap(label, crate::style::medium(14.0), t.text_normal);
                    let w = galley.size().x + if icon_url.is_some() { 24.0 } else { 0.0 };
                    let mut pos = pos2(bar.center().x - w / 2.0, bar.center().y);
                    if let Some(u) = icon_url {
                        let r = Rect::from_center_size(pos2(pos.x + 8.0, pos.y), vec2(16.0, 16.0));
                        if let Some(a) = u.strip_prefix("acronym:") {
                            ui.painter().rect_filled(r, 4.0, Color32::from_rgb(15, 15, 29));
                            ui.painter().text(r.center(), Align2::CENTER_CENTER, a, crate::style::medium(6.0), t.text_normal);
                        } else if let Some(g) = u.strip_prefix("glyph:") {
                            paint_icon(ui.painter(), r, g, t.interactive_normal);
                        } else if u == "logo:" {
                            let c = t.interactive_normal;
                            let rgb = (c.r() as u32) << 16 | (c.g() as u32) << 8 | c.b() as u32;
                            egui::Image::new(brand_icons::discord_logo(rgb)).paint_at(ui, r);
                        } else {
                            egui::Image::new(u).rounding(4.0).paint_at(ui, r);
                        }
                        pos.x += 24.0;
                    }
                    ui.painter().galley(pos2(pos.x, pos.y - galley.size().y / 2.0), galley, t.text_normal);
                }
            });
        self.resize_edges(ctx);
    }

    /// Frameless windows need their own resize handles at the edges. (macOS
    /// windows keep their frame, which resizes them.)
    fn resize_edges(&self, ctx: &egui::Context) {
        if cfg!(target_os = "macos") || ctx.input(|i| i.viewport().maximized.unwrap_or(false)) {
            return;
        }
        let Some(p) = ctx.input(|i| i.pointer.hover_pos()) else { return };
        let r = ctx.screen_rect();
        const E: f32 = 5.0;
        let (l, rt, tp, b) = (p.x - r.left() < E, r.right() - p.x < E, p.y - r.top() < E, r.bottom() - p.y < E);
        let dir = match (l, rt, tp, b) {
            (true, _, true, _) => Some((ResizeDirection::NorthWest, CursorIcon::ResizeNwSe)),
            (_, true, true, _) => Some((ResizeDirection::NorthEast, CursorIcon::ResizeNeSw)),
            (true, _, _, true) => Some((ResizeDirection::SouthWest, CursorIcon::ResizeNeSw)),
            (_, true, _, true) => Some((ResizeDirection::SouthEast, CursorIcon::ResizeNwSe)),
            (true, ..) => Some((ResizeDirection::West, CursorIcon::ResizeHorizontal)),
            (_, true, ..) => Some((ResizeDirection::East, CursorIcon::ResizeHorizontal)),
            (_, _, true, _) => Some((ResizeDirection::North, CursorIcon::ResizeVertical)),
            (.., true) => Some((ResizeDirection::South, CursorIcon::ResizeVertical)),
            _ => None,
        };
        if let Some((d, cursor)) = dir {
            ctx.set_cursor_icon(cursor);
            if ctx.input(|i| i.pointer.primary_pressed()) {
                ctx.send_viewport_cmd(ViewportCommand::BeginResize(d));
            }
        }
    }

    pub fn main_ui(&mut self, ctx: &egui::Context) {
        let t = self.theme.clone();
        let start = std::time::Instant::now();
        let themed = t.gradient.is_some();
        let fill = |c: Color32| if themed { Color32::TRANSPARENT } else { c };
        SidePanel::left("guild_bar")
            .exact_width(GUILD_BAR)
            .resizable(false)
            .show_separator_line(false)
            .frame(Frame::none().fill(fill(t.bg_tertiary)))
            .show(ctx, |ui| {
                paint_theme_surface(ctx, ui.painter(), ui.max_rect(), 0.0, surface::FRAME, &t);
                self.guild_bar(ui)
            });
        self.perf.add("servers", start);
        // Notices sit above the channel list and chat, right of the server list.
        let notice = self.voice_notice_shown();
        self.voice_notice_ui(ctx);
        let start = std::time::Instant::now();
        // Like Discord's, the channel list's right edge drags (the whole
        // sidebar 264–432 wide); the width is remembered.
        let saved = self.prefs.sidebar_width.clamp(SIDEBAR_MIN, SIDEBAR_MAX) - GUILD_BAR;
        // The saved width is the truth: egui keeps the panel's last rect and
        // shrinks it for good whenever the window is momentarily smaller
        // (minimised, hidden to the tray, the first frames of a start), so
        // unless the edge is being dragged the panel is put back to it.
        let panel_id = egui::Id::new("channel_sidebar");
        let (dragging, dropped) = ctx.read_response(panel_id.with("__resize")).map_or((false, false), |r| (r.dragged(), r.drag_stopped()));
        if !dragging {
            let rect = Rect::from_min_size(egui::Pos2::ZERO, vec2(saved, 0.0));
            ctx.data_mut(|d| d.insert_persisted(panel_id, egui::containers::panel::PanelState { rect }));
        }
        let sidebar = SidePanel::left(panel_id)
            .default_width(saved)
            .width_range((SIDEBAR_MIN - GUILD_BAR)..=(SIDEBAR_MAX - GUILD_BAR))
            .resizable(true)
            .show_separator_line(false)
            .frame(Frame::none().fill(fill(t.bg_secondary)))
            .show(ctx, |ui| {
                let full = ui.max_rect();
                paint_theme_surface(ctx, ui.painter(), full, 0.0, surface::FRAME, &t);
                // Contents in a child that can't widen the panel: a resizable
                // panel keeps any overflow and would grow every frame.
                let mut inner = ui.new_child(egui::UiBuilder::new().max_rect(full).layout(*ui.layout()));
                inner.set_clip_rect(full.intersect(ui.clip_rect()));
                self.channel_sidebar(&mut inner);
                ui.advance_cursor_after_rect(full);
            });
        // Only a drag of the edge changes the width; saved when it's let go.
        if dragging {
            self.prefs.sidebar_width = (sidebar.response.rect.width() + GUILD_BAR).round();
        }
        if dropped {
            crate::features::save_prefs(self.config_dir.as_deref(), &self.prefs);
        }
        self.perf.add("sidebar", start);
        let start = std::time::Instant::now();
        // Members / Server Boosts / Server Shop replace the chat.
        let guild_page = self.guild_page_active();
        // (The member list and the DM profile sit under the chat header, as in
        // Discord: see `chat_side_panel`.)
        if self.search.is_some() {
            SidePanel::right("search_panel")
                .exact_width(420.0)
                .resizable(false)
                .frame(Frame::none().fill(t.bg_primary))
                .show(ctx, |ui| self.search_panel(ui));
        } else if self.compose.new_thread.as_ref().is_some_and(|d| Some(d.channel) == self.current_channel) {
            SidePanel::right("new_thread")
                .exact_width(420.0)
                .resizable(false)
                .frame(Frame::none().fill(t.bg_primary))
                .show(ctx, |ui| self.new_thread_panel(ui));
        }
        self.perf.add("right panel", start);
        let start = std::time::Instant::now();
        CentralPanel::default()
            .frame(Frame::none().fill(fill(t.bg_primary)))
            .show(ctx, |ui| {
                paint_theme_surface(ctx, ui.painter(), ui.max_rect(), 0.0, surface::CHAT, &t);
                if guild_page {
                    self.guild_page_ui(ui)
                } else if self.showing_call_view() {
                    self.call_view_ui(ui)
                } else {
                    self.chat_ui(ui)
                }
            });
        self.perf.add("chat", start);

        // The refreshed layout's content panel: hairline border with a rounded
        // top-left corner around the channel list + chat.
        let content = Rect::from_min_max(sidebar.response.rect.min, ctx.screen_rect().max + vec2(2.0, 2.0));
        // (Stopping above the floating user panel: this layer can end up over that
        // card, and its left edge then ran down between your avatar and your name.)
        let above_panel = ctx.screen_rect().with_max_y(ctx.screen_rect().bottom() - 8.0 - self.user_panel_height());
        let frame = ctx.layer_painter(egui::LayerId::new(Order::Middle, egui::Id::new("content_frame"))).with_clip_rect(above_panel);
        let border = Stroke::new(1.0_f32, t.border_subtle);
        if notice {
            // Under a notice (Discord): square corners, and the line under the
            // notice runs along the channel list only.
            let (l, top) = (content.left() + 0.5, content.top() + 0.5);
            frame.line_segment([pos2(l, content.top()), pos2(l, content.bottom())], border);
            frame.line_segment([pos2(content.left(), top), pos2(sidebar.response.rect.right(), top)], border);
        } else {
            frame.rect_stroke(content, egui::Rounding { nw: 8.0, ..Default::default() }, border);
        }

        self.floating_user_panel(ctx, sidebar.response.rect.right());
        self.voice_menu_ui(ctx);
        self.soundboard_ui(ctx);
        self.pins_popout(ctx);
        self.stranger_confirm_ui(ctx);
        self.update_confirm_ui(ctx);
        self.friend_nickname_ui(ctx);
        self.group_invite_ui(ctx);
        self.leave_group_ui(ctx);
        self.bot_modal_ui(ctx);
        self.threads_popout_ui(ctx);
        self.inbox_popout(ctx);
        self.context_menu_ui(ctx);
        self.moderation_ui(ctx);
        self.guild_dialog_ui(ctx);
        self.dm_menu_ui(ctx);
        self.app_directory_ui(ctx);
        self.compose_tick();
        self.plus_menu_ui(ctx);
        self.poll_dialog_ui(ctx);
        self.schedule_dialog_ui(ctx);
        self.expression_picker_ui(ctx);
        self.app_launcher_ui(ctx);
        self.mention_list_ui(ctx);
        self.emoji_picker_ui(ctx);
        self.forward_ui(ctx);
        self.profile_ui(ctx);
        self.full_profile_ui(ctx);
        self.profile_more_ui(ctx);
        self.recent_activity_menu_ui(ctx);
        self.remove_friend_ui(ctx);
        self.share_picker_ui(ctx);
        self.stream_card_ui(ctx);
        self.watching_fullscreen_ui(ctx);
        self.server_settings_ui(ctx);
        self.quest_video_ui(ctx);
        self.account_menu_ui(ctx);
        self.manage_accounts_ui(ctx);
        self.custom_status_dialog_ui(ctx);
        self.reactions_dialog_ui(ctx);
        self.switcher_ui(ctx);
        self.tag_popout_ui(ctx);
        self.tag_adopt_ui(ctx);
        self.sticker_popout_ui(ctx);
        self.server_dialog_ui(ctx);
        self.add_server_ui(ctx);
        self.badges_ui(ctx);
        self.fetch_wanted_badges();
        self.fetch_wanted_registry();
        self.media_viewer_ui(ctx);
        self.camera_confirm_ui(ctx);
        self.video_fullscreen_ui(ctx);
        self.drop_overlay(ctx);
        self.handle_dropped_files(ctx);
    }

    /// The refreshed user panel: a card floating over the bottom of the server
    /// and channel lists.
    /// Under the chat header, on the right: the member list (server text
    /// channels and group DMs) or the DM's profile, unless search / a new
    /// thread has the window's right side.
    pub(crate) fn chat_side_panel(&mut self, ui: &mut Ui) {
        let t = self.theme.clone();
        if self.search.is_some() || self.compose.new_thread.as_ref().is_some_and(|d| Some(d.channel) == self.current_channel) {
            return;
        }
        let in_guild_text = self.current_guild.is_some()
            && self.current_channel.and_then(|c| self.store.channels.get(&c)).is_some_and(|c| channel_kind::is_text(c.kind));
        let group = self.current_channel.filter(|c| self.store.channels.get(c).is_some_and(|c| c.kind == channel_kind::GROUP_DM));
        let ctx = ui.ctx().clone();
        if let Some(ch) = group.filter(|_| self.show_group_members) {
            SidePanel::right("group_members")
                .exact_width(MEMBERS)
                .resizable(false)
                .show_separator_line(false)
                .frame(Frame::none().fill(t.page(t.bg_primary)))
                .show_inside(ui, |ui| {
                    paint_theme_surface(&ctx, ui.painter(), ui.max_rect(), 0.0, surface::CHAT, &t);
                    let r = ui.max_rect();
                    ui.painter().vline(r.left() + 0.5, r.y_range(), Stroke::new(1.0_f32, t.border_subtle));
                    self.group_member_list_ui(ui, ch)
                });
        } else if in_guild_text && self.show_members {
            SidePanel::right("member_list")
                .exact_width(MEMBERS)
                .resizable(false)
                .show_separator_line(false)
                .frame(Frame::none().fill(t.page(t.bg_primary)))
                .show_inside(ui, |ui| {
                    paint_theme_surface(&ctx, ui.painter(), ui.max_rect(), 0.0, surface::CHAT, &t);
                    // Discord's hairline down its left edge.
                    let r = ui.max_rect();
                    ui.painter().vline(r.left() + 0.5, r.y_range(), Stroke::new(1.0_f32, t.border_subtle));
                    self.member_list_ui(ui)
                });
        } else if let Some(user) = self.dm_recipient().filter(|_| self.show_dm_profile && dm_profile_fits(&ctx)) {
            // Discord's 320 px aside over the chat's own background, the
            // profile card floating inside it.
            SidePanel::right("dm_profile")
                .exact_width(320.0)
                .resizable(false)
                .show_separator_line(false)
                .frame(Frame::none().fill(t.page(t.bg_primary)))
                .show_inside(ui, |ui| {
                    paint_theme_surface(&ctx, ui.painter(), ui.max_rect(), 0.0, surface::CHAT, &t);
                    self.dm_profile_panel(ui, &user)
                });
        }
    }

    /// The floating user panel's height (Discord's --custom-app-panels-height):
    /// the 56 px account row inside a 1 px border, plus "Voice Connected" in a call.
    pub fn user_panel_height(&self) -> f32 {
        let voice = if self.voice.is_some() { 88.0 } else { 0.0 };
        58.0 + voice + self.spotify_panel_height()
    }

    /// Space the server and channel lists stop short of the window's bottom:
    /// their scrollers end a little under the panel's top edge (Discord: the
    /// panel's height + 8 − 16), so nothing shows beside or below the panel.
    pub fn lists_bottom_gap(&self) -> f32 {
        self.user_panel_height() + 8.0 - 16.0
    }

    fn floating_user_panel(&mut self, ctx: &egui::Context, sidebar_right: f32) {
        let t = self.theme.clone();
        let screen = ctx.screen_rect();
        // In a call, Discord's "Voice Connected" box sits on top of it.
        let in_voice = self.voice.is_some();
        let h = self.user_panel_height();
        // 8 px in from the window's left edge and the sidebar's right edge.
        let rect = Rect::from_min_size(pos2(screen.left() + 8.0, screen.bottom() - 8.0 - h), vec2((sidebar_right - screen.left() - 16.0).max(200.0), h));
        egui::Area::new(egui::Id::new("floating_user_panel"))
            .order(Order::Middle)
            .fixed_pos(rect.min)
            .show(ctx, |ui| {
                motion::tag(ui, motion::Motion::Still, 0);
                // The whole card takes the pointer: nothing under it reacts.
                let _ = ui.allocate_rect(rect, Sense::hover());
                gray_text(ui, true);
                // Discord: --background-gradient-highest (the theme gradient with
                // a 0.497 black overlay), else --background-base-low.
                if !paint_theme_surface(ctx, ui.painter(), rect, 8.0, surface::PANEL, &t) {
                    ui.painter().rect_filled(rect, 8.0, t.bg_secondary_alt);
                }
                ui.painter().rect_stroke(rect, 8.0, Stroke::new(1.0_f32, t.border_subtle));
                let account = Rect::from_min_max(pos2(rect.left(), rect.bottom() - 58.0), rect.max);
                // Top down: the Spotify controller, the call, your account.
                let spotify_h = self.spotify_panel_height();
                if spotify_h > 0.0 {
                    let area = Rect::from_min_size(rect.min, vec2(rect.width(), spotify_h));
                    self.spotify_panel_ui(ui, area, &t);
                    ui.painter().hline(rect.x_range(), area.bottom(), Stroke::new(1.0_f32, t.border_subtle));
                }
                if in_voice {
                    let top = Rect::from_min_max(pos2(rect.left() + 6.0, rect.top() + spotify_h + 6.0), pos2(rect.right() - 6.0, account.top()));
                    let mut child = ui.new_child(egui::UiBuilder::new().max_rect(top).layout(egui::Layout::top_down(egui::Align::Min)));
                    self.voice_panel(&mut child, &t);
                    ui.painter().hline(rect.x_range(), account.top(), Stroke::new(1.0_f32, t.border_subtle));
                }
                self.user_panel(ui, account, &t);
                gray_text(ui, false);
            });
    }

    /// While files are dragged over the window: "Upload to #channel".
    fn drop_overlay(&self, ctx: &egui::Context) {
        if ctx.input(|i| i.raw.hovered_files.is_empty()) {
            return;
        }
        let Some(ch) = self.current_channel else { return };
        let t = &self.theme;
        let screen = ctx.screen_rect();
        let painter = ctx.layer_painter(egui::LayerId::new(Order::Foreground, egui::Id::new("drop_overlay")));
        painter.rect_filled(screen, 0.0, Color32::from_black_alpha(160));
        let card = Rect::from_center_size(screen.center(), vec2(320.0, 200.0));
        painter.rect(card, 12.0, t.accent.gamma_multiply(0.9), Stroke::new(1.5_f32, Color32::WHITE));
        let name = self.destination_name(ch);
        painter.text(card.center() - vec2(0.0, 14.0), Align2::CENTER_CENTER, format!("Upload to {name}"), FontId::new(20.0, egui::FontFamily::Name(crate::style::BOLD.into())), Color32::WHITE);
        painter.text(card.center() + vec2(0.0, 18.0), Align2::CENTER_CENTER, "Up to 10 files", FontId::proportional(14.0), Color32::WHITE);
    }

    pub fn toasts_ui(&mut self, ctx: &egui::Context) {
        let stay = Duration::from_secs(self.prefs.toast_seconds.clamp(5, 60) as u64);
        self.toasts.retain(|t| t.at.elapsed() < stay);
        if self.toasts.is_empty() {
            return;
        }
        let t = self.theme.clone();
        egui::Area::new(egui::Id::new("toasts"))
            .anchor(Align2::RIGHT_BOTTOM, vec2(-16.0, -96.0))
            .order(Order::Tooltip)
            .interactable(false)
            .show(ctx, |ui| {
                for toast in &self.toasts {
                    Frame::none()
                        .fill(t.bg_floating)
                        .rounding(6.0)
                        .inner_margin(Margin::symmetric(12.0, 8.0))
                        .stroke(Stroke::new(1.0_f32,if toast.error { t.danger } else { t.accent }))
                        .show(ui, |ui| {
                            ui.set_max_width(360.0);
                            ui.label(egui::RichText::new(&toast.text).color(t.text_normal));
                        });
                    ui.add_space(6.0);
                }
            });
    }
}

/// A title bar button's glyph (`cmd` 0 close, 1 maximize or restore, 2
/// minimize), centred on `m`. Painted rather than typed on every platform:
/// Segoe's caption glyphs exist only on Windows. The shapes are Segoe Fluent
/// Icons' at 10 px: a 10 px box, lines one pixel thick, slightly rounded
/// corners, minimize one row above the middle.
fn paint_caption_glyph(p: &egui::Painter, m: egui::Pos2, cmd: u8, maximized: bool, c: Color32) {
    let stroke = Stroke::new(1.0_f32, c);
    // (A path, not `rect_stroke`: that rounds the corners to whole pixels,
    // which puts a one pixel line across two.)
    let window = |rect: Rect| {
        let mut points = Vec::new();
        egui::epaint::tessellator::path::rounded_rectangle(&mut points, rect, egui::Rounding::same(1.0));
        egui::Shape::closed_line(points, stroke)
    };
    match cmd {
        0 => {
            p.line_segment([m + vec2(-5.0, -5.0), m + vec2(5.0, 5.0)], stroke);
            p.line_segment([m + vec2(-5.0, 5.0), m + vec2(5.0, -5.0)], stroke);
        }
        1 if maximized => {
            // The window in front, lower left...
            p.add(window(Rect::from_min_max(m + vec2(-4.5, -2.5), m + vec2(2.5, 4.5))));
            // ...and the top and right edges of the one behind it.
            let corner = m + vec2(3.0, -3.0);
            let arc = (0..=4).map(|i| {
                let a = i as f32 * std::f32::consts::FRAC_PI_8;
                corner + 1.5 * vec2(a.sin(), -a.cos())
            });
            let points = std::iter::once(m + vec2(-2.5, -4.5)).chain(arc).chain([m + vec2(4.5, 2.5)]).collect();
            p.add(egui::Shape::line(points, stroke));
        }
        1 => {
            p.add(window(Rect::from_center_size(m, vec2(9.0, 9.0))));
        }
        _ => {
            p.rect_filled(Rect::from_min_max(m + vec2(-5.0, -1.0), m + vec2(5.0, 0.0)), 0.0, c);
        }
    }
}

/// Whether GIFs / animated emoji play right now (only while RustCord is the
/// focused window, like Discord's default; a playing GIF redraws the window
/// many times a second).
static ANIMATE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);

pub fn set_animating(on: bool) {
    ANIMATE.store(on, std::sync::atomic::Ordering::Relaxed);
}

pub fn animating() -> bool {
    ANIMATE.load(std::sync::atomic::Ordering::Relaxed) && !REDUCED_MOTION.load(std::sync::atomic::Ordering::Relaxed)
}

/// Settings → Accessibility → Reduced motion: nothing animates.
pub static REDUCED_MOTION: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Settings → Chat → "Play animated emoji" (Discord's animate_emoji).
pub static ANIMATE_EMOJI: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
/// Discord's "Play sticker animations": 0 always, 1 on hover, 2 never.
pub static STICKER_ANIM: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);

pub fn sticker_animation() -> u8 {
    STICKER_ANIM.load(std::sync::atomic::Ordering::Relaxed)
}
/// Settings → Language & Time → 24-hour clock.
pub static HOUR24: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Accessibility choices read all over the UI (set by `features::apply_prefs`).
pub static CHAT_TEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(16.0f32.to_bits());
pub static GROUP_SPACING: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(16.0f32.to_bits());
pub static UNDERLINE_LINKS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub static SWITCH_ICONS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub static NAME_STYLES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
/// Accessibility → Chat Message Display → Compact, and its small avatars.
pub static COMPACT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub static COMPACT_AVATARS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Accessibility → UI Density: 0 compact, 1 default, 2 spacious.
pub static DENSITY: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(1);

/// A list row's height (channels, DMs, members) at the chosen UI Density.
pub fn dense(h: f32) -> f32 {
    match DENSITY.load(std::sync::atomic::Ordering::Relaxed) {
        0 => h - 6.0,
        2 => h + 6.0,
        _ => h,
    }
}
/// Appearance → other people's profiles in their own colours.
pub static PROFILE_THEMES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
/// Streamer Mode is hiding invite links.
pub static HIDE_INVITES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// The "ALT" tag on pictures with a description.
pub static IMAGE_ALT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
/// The legacy (plain) message box.
pub static LEGACY_INPUT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Saturation for custom colours (role colours), 0–1 as f32 bits (1: untouched).
pub static CUSTOM_SATURATION: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0x3f80_0000);

/// A custom colour (0xRRGGBB) with Accessibility → Saturation applied, when
/// "Apply saturation setting to custom colours" is on.
pub fn custom_color(c: u32) -> u32 {
    let k = f32::from_bits(CUSTOM_SATURATION.load(std::sync::atomic::Ordering::Relaxed));
    if k >= 0.995 {
        return c;
    }
    let (r, g, b) = ((c >> 16 & 255) as f32, (c >> 8 & 255) as f32, (c & 255) as f32);
    let grey = 0.299 * r + 0.587 * g + 0.114 * b;
    let mix = |v: f32| (grey + (v - grey) * k).round() as u32;
    // (Never 0: that means "no colour".)
    (mix(r) << 16 | mix(g) << 8 | mix(b)).max(1)
}
/// Role colours: 0 in names, 1 a dot next to names, 2 not shown.
pub static ROLE_COLORS: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
/// "Show spoiler content": 0 on click, 1 on servers I moderate, 2 always.
pub static SPOILERS: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);

/// The chat text size in px (Accessibility → Text size in chat).
pub fn chat_text() -> f32 {
    f32::from_bits(CHAT_TEXT.load(std::sync::atomic::Ordering::Relaxed))
}

fn hour24() -> bool {
    HOUR24.load(std::sync::atomic::Ordering::Relaxed)
}

/// Clock format for message times: "06:53 pm" or "18:53".
pub fn time_fmt() -> &'static str {
    if hour24() {
        "%H:%M"
    } else {
        "%I:%M %P"
    }
}

/// URI to draw a GIF with: the frame the shared player (`video`) is on while
/// animations play, its first frame while they don't or until it's decoded.
/// Anything that isn't a GIF comes back as it is. (A GIF's bare address
/// shows its first frame too; nothing but the player plays GIFs.)
pub fn anim(url: &str) -> String {
    let path = url.split(['?', '#']).next().unwrap_or(url);
    if !path.ends_with(".gif") {
        return url.to_string();
    }
    let base = url.split('#').next().unwrap_or(url);
    // First frame as a plain image (decoded in the background) while the
    // animation loads, or when animations are paused. Discord's CDN serves
    // that frame as its own small PNG for avatars, banners, icons and emoji,
    // so the card fills in at once instead of waiting for the whole GIF.
    let cdn_still = base.starts_with("https://cdn.discordapp.com/")
        && ["/avatars/", "/banners/", "/icons/", "/emojis/", "/role-icons/", "/guild-tag-badges/"].iter().any(|p| base.contains(p));
    let still = if cdn_still {
        match base.split_once('?') {
            Some((p, q)) => format!("{}.png?{q}", p.trim_end_matches(".gif")),
            None => format!("{}.png", base.trim_end_matches(".gif")),
        }
    } else {
        // (The same file the player fetches: one download for both.)
        format!("{base}#still")
    };
    if !animating() {
        return still;
    }
    // Playing: through the shared animation player (bounded memory, one clock).
    crate::video::frame_uri(base, true).unwrap_or(still)
}

/// The surfaces Discord lays its client-theme overlays on.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Surface {
    /// Server list, channel list, title bar (Discord's app frame).
    Frame,
    /// Chat, member list and other main pages.
    Chat,
    /// The floating user panel and the composer (--background-gradient-highest).
    Panel,
}

/// Names for the surfaces (`surface::FRAME`, …).
pub mod surface {
    pub const FRAME: super::Surface = super::Surface::Frame;
    pub const CHAT: super::Surface = super::Surface::Chat;
    pub const PANEL: super::Surface = super::Surface::Panel;
}

/// The overlay colour (black / white at the theme's strength) for `s`.
fn overlay_color(t: &crate::style::Theme, s: Surface) -> Color32 {
    let o = &t.overlays;
    let a = match s {
        Surface::Frame => o.frame,
        Surface::Chat => o.chat,
        Surface::Panel => o.panel,
    };
    let c = o.color;
    crate::style::rgba(c.r(), c.g(), c.b(), (a.clamp(0.0, 1.0) * 255.0).round() as u8)
}

/// The theme's gradient rendered once for the window's shape (256 px wide;
/// linear filtering keeps it smooth), reused by every surface until the
/// theme or the window's proportions change.
fn gradient_texture(ctx: &egui::Context, g: &crate::style::Gradient) -> egui::TextureId {
    use std::hash::{Hash, Hasher};
    let screen = ctx.screen_rect();
    let w = 256usize;
    let h = ((w as f32 * screen.height() / screen.width().max(1.0)).round() as usize).clamp(32, 512);
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    for (c, p) in &g.stops {
        c.to_array().hash(&mut hasher);
        p.to_bits().hash(&mut hasher);
    }
    g.angle.to_bits().hash(&mut hasher);
    h.hash(&mut hasher);
    let key = hasher.finish();
    let id = egui::Id::new("theme_gradient_texture");
    if let Some((k, tex)) = ctx.data(|d| d.get_temp::<(u64, egui::TextureHandle)>(id)) {
        if k == key {
            return tex.id();
        }
    }
    // Sample in a box of the window's proportions (the angle depends on them).
    let area = Rect::from_min_size(pos2(0.0, 0.0), vec2(w as f32, h as f32));
    let mut pixels = Vec::with_capacity(w * h);
    for y in 0..h {
        for x in 0..w {
            pixels.push(g.color_at(pos2(x as f32 + 0.5, y as f32 + 0.5), area));
        }
    }
    let image = egui::ColorImage { size: [w, h], pixels };
    let tex = ctx.load_texture("theme-gradient", image, egui::TextureOptions::LINEAR);
    let tid = tex.id();
    ctx.data_mut(|d| d.insert_temp(id, (key, tex)));
    tid
}

/// Under a client theme, paint the theme's gradient (fixed to the window, as
/// Discord's is) under `rect`, then Discord's overlay for the surface.
/// False (nothing drawn) without one: the caller fills as usual.
pub fn paint_theme_surface(ctx: &egui::Context, painter: &egui::Painter, rect: Rect, rounding: f32, surface: Surface, t: &crate::style::Theme) -> bool {
    match theme_surface_shapes(ctx, rect, rounding, surface, t) {
        Some(shapes) => {
            painter.extend(shapes);
            true
        }
        None => false,
    }
}

/// [`paint_theme_surface`]'s shapes (for a slot reserved under a frame).
pub fn theme_surface_shapes(ctx: &egui::Context, rect: Rect, rounding: f32, surface: Surface, t: &crate::style::Theme) -> Option<Vec<egui::Shape>> {
    theme_overlay_shapes(ctx, rect, rounding, overlay_color(t, surface), t)
}

/// Under a client theme, paint the gradient under `rect` with the theme's
/// overlay colour at `strength` (0-1): Discord's --background-gradient-lowest
/// / -lower surfaces, which no [`Surface`] names. False without a client theme.
pub fn paint_theme_overlay(ctx: &egui::Context, painter: &egui::Painter, rect: Rect, rounding: f32, strength: f32, t: &crate::style::Theme) -> bool {
    let c = t.overlays.color;
    let overlay = crate::style::rgba(c.r(), c.g(), c.b(), (strength.clamp(0.0, 1.0) * 255.0).round() as u8);
    match theme_overlay_shapes(ctx, rect, rounding, overlay, t) {
        Some(shapes) => {
            painter.extend(shapes);
            true
        }
        None => false,
    }
}

/// The theme's gradient under `rect` with `overlay` laid over it.
fn theme_overlay_shapes(ctx: &egui::Context, rect: Rect, rounding: f32, overlay: Color32, t: &crate::style::Theme) -> Option<Vec<egui::Shape>> {
    let g = t.gradient.as_ref().filter(|g| !g.stops.is_empty())?;
    let tex = gradient_texture(ctx, g);
    let screen = ctx.screen_rect();
    let uv = |p: egui::Pos2| pos2((p.x - screen.left()) / screen.width().max(1.0), (p.y - screen.top()) / screen.height().max(1.0));
    let mut mesh = egui::Mesh::with_texture(tex);
    if rounding <= 0.0 {
        for p in [rect.left_top(), rect.right_top(), rect.left_bottom(), rect.right_bottom()] {
            mesh.vertices.push(egui::epaint::Vertex { pos: p, uv: uv(p), color: Color32::WHITE });
        }
        mesh.add_triangle(0, 1, 2);
        mesh.add_triangle(1, 2, 3);
    } else {
        let mut outline = Vec::new();
        egui::epaint::tessellator::path::rounded_rectangle(&mut outline, rect, egui::Rounding::same(rounding));
        mesh.vertices.push(egui::epaint::Vertex { pos: rect.center(), uv: uv(rect.center()), color: Color32::WHITE });
        for p in &outline {
            mesh.vertices.push(egui::epaint::Vertex { pos: *p, uv: uv(*p), color: Color32::WHITE });
        }
        let n = outline.len() as u32;
        for i in 0..n {
            mesh.add_triangle(0, 1 + i, 1 + (i + 1) % n);
        }
    }
    Some(vec![egui::Shape::mesh(mesh), egui::Shape::rect_filled(rect, rounding, overlay)])
}

/// A user's avatar to draw: an animated one plays while `playing` (Discord
/// plays them on hover, and always in profiles), still otherwise.
pub fn avatar_uri(user: &discord::model::User, size: u32, playing: bool) -> String {
    if playing && user.avatar.as_deref().is_some_and(|h| h.starts_with("a_")) {
        anim(&user.avatar_animated(size))
    } else {
        user.avatar_or_default(size)
    }
}

/// A user's avatar decoration (frame): Discord's animated PNG while `playing`
/// (played by the animation player), the still otherwise or while it loads.
pub fn decoration_uri(user: &discord::model::User, playing: bool) -> Option<String> {
    let d = user.avatar_decoration_data.as_ref().filter(|d| !d.asset.is_empty())?;
    let still = format!("https://cdn.discordapp.com/avatar-decoration-presets/{}.png?size=96&passthrough=false", d.asset);
    if playing && animating() && d.asset.starts_with("a_") {
        let moving = format!("https://cdn.discordapp.com/avatar-decoration-presets/{}.png?size=96&passthrough=true", d.asset);
        if let Some(frame) = crate::video::frame_uri(&moving, true) {
            return Some(frame);
        }
    }
    Some(still)
}

/// Image for an emoji given the way Discord's APIs do: a custom emoji ID, or
/// a name that is either the emoji itself ("🪖") or its shortcode
/// ("military_helmet").
pub fn emoji_image(id: Option<discord::model::Id>, name: Option<&str>, animated: bool) -> Option<String> {
    if let Some(id) = id.filter(|i| i.0 != 0) {
        return Some(emoji_img(id, animated, 48));
    }
    let name = name?.trim().trim_matches(':');
    let chars: Vec<char> = name.chars().collect();
    if crate::emoji::emoji_len(&chars, 0).is_some() {
        return Some(crate::emoji::twemoji_url(name));
    }
    if let Some(e) = crate::emoji::from_shortcode(name) {
        return Some(crate::emoji::twemoji_url(&e));
    }
    crate::emoji_data::CATEGORIES
        .iter()
        .flat_map(|(_, items)| items.iter())
        .find(|(_, n)| *n == name)
        .map(|(e, _)| crate::emoji::twemoji_url(e))
}

/// Custom emoji image, animated when it is.
pub fn emoji_img(id: discord::model::Id, animated: bool, size: u32) -> String {
    let animated = animated && ANIMATE_EMOJI.load(std::sync::atomic::Ordering::Relaxed);
    anim(&discord::model::emoji_url(id, animated, size))
}

/// An image that should play if it's a GIF: shows `still` until (or unless)
/// the animated version loads.
pub fn animated_or_still(ui: &Ui, animated: Option<&str>, still: &str, size: egui::Vec2) -> String {
    if let Some(a) = animated {
        let uri = anim(a);
        match egui::Image::new(uri.clone()).load_for_size(ui.ctx(), size) {
            Ok(egui::load::TexturePoll::Ready { .. }) => return uri,
            Ok(egui::load::TexturePoll::Pending { .. }) | Err(_) => {}
        }
    }
    still.to_string()
}

/// Paint a single line of text with its emoji as Twemoji images (like
/// Discord's channel names), left edge at `pos.x`, centred on `pos.y`.
/// Returns the drawn rect.
pub fn paint_text_emoji(ui: &Ui, painter: &egui::Painter, pos: egui::Pos2, text: &str, font: FontId, color: Color32) -> Rect {
    let chars: Vec<char> = text.chars().collect();
    let size = font.size * 1.15;
    let mut x = pos.x;
    let mut run = String::new();
    let flush = |run: &mut String, x: &mut f32| {
        if run.is_empty() {
            return;
        }
        let r = painter.text(pos2(*x, pos.y), Align2::LEFT_CENTER, std::mem::take(run), font.clone(), color);
        *x = r.right();
    };
    let mut i = 0;
    while i < chars.len() {
        if let Some(n) = crate::emoji::emoji_len(&chars, i) {
            flush(&mut run, &mut x);
            let seq: String = chars[i..i + n].iter().collect();
            let r = Rect::from_min_size(pos2(x + 1.0, pos.y - size / 2.0), vec2(size, size));
            if painter.clip_rect().contains_rect(r) {
                egui::Image::new(crate::emoji::twemoji_url(&seq)).paint_at(ui, r);
            }
            x = r.right() + 1.0;
            i += n;
        } else {
            match chars[i] {
                // Joiners / variation selectors on their own have no glyph.
                '\u{FE0F}' | '\u{FE0E}' | '\u{200D}' => {}
                // The full-width "・" servers use as a separator: the fallback
                // font draws it small and high; Discord shows a centred dot.
                '\u{30FB}' | '\u{FF65}' => run.push_str(" · "),
                c => run.push(c),
            }
            i += 1;
        }
    }
    flush(&mut run, &mut x);
    Rect::from_min_max(pos2(pos.x, pos.y - size / 2.0), pos2(x, pos.y + size / 2.0))
}

/// `text` as `paint_text_emoji` draws it, cut with "…" to fit `max_w`
/// (Discord's `text-overflow: ellipsis`). Emoji are never split.
pub fn elide_text_emoji<'a>(ui: &Ui, text: &'a str, font: &FontId, max_w: f32) -> std::borrow::Cow<'a, str> {
    let chars: Vec<char> = text.chars().collect();
    let emoji_w = font.size * 1.15 + 2.0;
    // (end index in `chars`, width up to there)
    let mut ends: Vec<(usize, f32)> = Vec::with_capacity(chars.len());
    let (dots, total) = ui.fonts(|f| {
        let mut x = 0.0;
        let mut i = 0;
        while i < chars.len() {
            if let Some(n) = crate::emoji::emoji_len(&chars, i) {
                x += emoji_w;
                i += n;
            } else {
                x += match chars[i] {
                    '\u{FE0F}' | '\u{FE0E}' | '\u{200D}' => 0.0,
                    '\u{30FB}' | '\u{FF65}' => f.glyph_width(font, ' ') * 2.0 + f.glyph_width(font, '·'),
                    c => f.glyph_width(font, c),
                };
                i += 1;
            }
            ends.push((i, x));
        }
        (f.glyph_width(font, '…'), x)
    });
    // (Half a pixel of slack: kerning and rounding.)
    if total <= max_w + 0.5 {
        return text.into();
    }
    let keep = ends.iter().take_while(|(_, w)| w + dots <= max_w).last().map_or(0, |(i, _)| *i);
    let head: String = chars[..keep].iter().collect();
    format!("{}…", head.trim_end()).into()
}

fn rgb_u32(c: u32) -> Color32 {
    Color32::from_rgb((c >> 16) as u8, (c >> 8) as u8, c as u8)
}

/// Paint an image filling `rect`, cropped to keep its proportions (CSS
/// `object-fit: cover`, how Discord shows banners).
/// Discord's blurred preview for a picture, as a small texture (cached per preview).
fn thumb_texture(ctx: &egui::Context, placeholder: &str) -> Option<egui::TextureHandle> {
    use base64::Engine;
    let id = egui::Id::new(("thumbhash", placeholder));
    if let Some(known) = ctx.data(|d| d.get_temp::<Option<egui::TextureHandle>>(id)) {
        return known;
    }
    let texture = base64::engine::general_purpose::STANDARD
        .decode(placeholder.trim_end_matches('='))
        .or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(placeholder.trim_end_matches('=')))
        .ok()
        .and_then(|hash| thumbhash::thumb_hash_to_rgba(&hash).ok())
        .filter(|(w, h, rgba)| *w > 0 && *h > 0 && rgba.len() == w * h * 4)
        .map(|(w, h, rgba)| ctx.load_texture(format!("thumbhash-{placeholder}"), egui::ColorImage::from_rgba_unmultiplied([w, h], &rgba), egui::TextureOptions::LINEAR));
    ctx.data_mut(|d| d.insert_temp(id, texture.clone()));
    texture
}

/// A clickable picture of `size`. While it loads, Discord's blurred preview of it
/// (`placeholder`) fills its place, or a quiet grey box, instead of a spinner.
/// Where a right-clicked picture waits for the message menu that opens on it.
const MENU_MEDIA_CLICK: &str = "menu_media_click";
const MENU_MEDIA: &str = "menu_media";

/// A right-click landed on this picture: remember it (the file to copy and
/// the link to share) for the message menu's Copy Image / Save Image /
/// Copy Link / Open Link.
pub fn note_media(ui: &Ui, resp: &egui::Response, image: &str, link: &str) {
    if ui.input(|i| i.pointer.secondary_clicked()) && ui.rect_contains_pointer(resp.rect) {
        let frame = ui.ctx().cumulative_pass_nr();
        ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new(MENU_MEDIA_CLICK), (image.to_string(), link.to_string(), frame)));
    }
}

/// The message menu is opening: it gets the picture right-clicked just now, if any.
pub fn claim_menu_media(ctx: &egui::Context) {
    let frame = ctx.cumulative_pass_nr();
    ctx.data_mut(|d| {
        let click = d.remove_temp::<(String, String, u64)>(egui::Id::new(MENU_MEDIA_CLICK));
        match click.filter(|c| c.2 + 1 >= frame) {
            Some((image, link, _)) => d.insert_temp(egui::Id::new(MENU_MEDIA), (image, link)),
            None => d.remove::<(String, String)>(egui::Id::new(MENU_MEDIA)),
        }
    });
}

/// The open message menu's picture: (file, link).
pub fn menu_media(ctx: &egui::Context) -> Option<(String, String)> {
    ctx.data(|d| d.get_temp(egui::Id::new(MENU_MEDIA)))
}

pub fn media_image(ui: &mut Ui, url: String, size: egui::Vec2, rounding: f32, placeholder: Option<&str>) -> egui::Response {
    let ready = matches!(egui::Image::new(url.as_str()).load_for_size(ui.ctx(), size), Ok(egui::load::TexturePoll::Ready { .. }));
    if ready {
        return ui.add(egui::Image::new(url).fit_to_exact_size(size).rounding(rounding).sense(Sense::click()));
    }
    let (rect, resp) = ui.allocate_exact_size(size, Sense::click());
    let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
    match placeholder.and_then(|p| thumb_texture(ui.ctx(), p)) {
        Some(texture) => egui::Image::new((texture.id(), rect.size())).rounding(rounding).paint_at(ui, rect),
        None => {
            ui.painter().rect_filled(rect, rounding, crate::style::overlay(0.06));
        }
    }
    resp
}

pub fn paint_cover(ui: &Ui, rect: Rect, uri: &str, rounding: egui::Rounding) {
    let img = egui::Image::new(uri.to_string());
    if let Ok(egui::load::TexturePoll::Ready { texture }) = img.load_for_size(ui.ctx(), rect.size()) {
        let (tw, th) = (texture.size.x.max(1.0), texture.size.y.max(1.0));
        let scale = (rect.width() / tw).max(rect.height() / th);
        let (vw, vh) = ((rect.width() / scale / tw).min(1.0), (rect.height() / scale / th).min(1.0));
        let uv = Rect::from_min_max(pos2((1.0 - vw) / 2.0, (1.0 - vh) / 2.0), pos2((1.0 + vw) / 2.0, (1.0 + vh) / 2.0));
        egui::Image::new(uri.to_string()).uv(uv).rounding(rounding).paint_at(ui, rect);
    }
}

/// A shape at `alpha` of its strength (meshes and filled rects; others as is).
pub fn fade_shape(shape: egui::Shape, alpha: f32) -> egui::Shape {
    match shape {
        egui::Shape::Mesh(mut m) => {
            for v in &mut m.vertices {
                v.color = v.color.gamma_multiply(alpha);
            }
            egui::Shape::Mesh(m)
        }
        egui::Shape::Rect(mut r) => {
            r.fill = r.fill.gamma_multiply(alpha);
            egui::Shape::Rect(r)
        }
        other => other,
    }
}

/// The badge Discord puts before a server's name (its "flower star").
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum GuildBadge {
    Verified,
    Partnered,
    /// A Community server; `boosted` gets Discord's pink badge.
    Community { boosted: bool },
}

pub fn guild_badge(g: &discord::model::Guild) -> Option<GuildBadge> {
    let has = |f: &str| g.features.as_ref().is_some_and(|fs| fs.iter().any(|x| x == f));
    if has("VERIFIED") {
        Some(GuildBadge::Verified)
    } else if has("PARTNERED") {
        Some(GuildBadge::Partnered)
    } else if has("COMMUNITY") {
        Some(GuildBadge::Community { boosted: g.premium_tier.unwrap_or(0) >= 1 })
    } else {
        None
    }
}

/// Discord's 18 px flower star (ten rounded points) with the badge's icon.
pub fn paint_guild_badge(p: &egui::Painter, c: egui::Pos2, badge: GuildBadge) {
    let (top, bottom, glyph, fg) = match badge {
        GuildBadge::Verified => (Color32::from_rgb(35, 165, 90), Color32::from_rgb(35, 165, 90), icon::CHECK, Color32::WHITE),
        GuildBadge::Partnered => (Color32::from_rgb(88, 101, 242), Color32::from_rgb(88, 101, 242), "\u{E716}", Color32::WHITE),
        GuildBadge::Community { boosted: true } => (Color32::from_rgb(201, 121, 242), Color32::from_rgb(245, 144, 190), "\u{E80F}", Color32::WHITE),
        GuildBadge::Community { boosted: false } => (Color32::WHITE, Color32::WHITE, "\u{E80F}", Color32::from_rgb(78, 80, 88)),
    };
    let mut mesh = egui::Mesh::default();
    let color_at = |y: f32| top.lerp_to_gamma(bottom, ((y - (c.y - 9.0)) / 18.0).clamp(0.0, 1.0));
    mesh.colored_vertex(c, color_at(c.y));
    let n = 80u32;
    for i in 0..n {
        let a = i as f32 / n as f32 * std::f32::consts::TAU - std::f32::consts::FRAC_PI_2;
        // Ten points every 36°, a dip straight up (Discord's path: radius
        // 8 at the points, 6.77 between, in a 16 px box).
        let r = 7.385 - 0.615 * (10.0 * (a + std::f32::consts::FRAC_PI_2)).cos();
        let q = c + vec2(a.cos(), a.sin()) * (r * 18.0 / 16.0);
        mesh.colored_vertex(q, color_at(q.y));
    }
    for i in 0..n {
        mesh.add_triangle(0, 1 + i, 1 + (i + 1) % n);
    }
    p.add(egui::Shape::mesh(mesh));
    p.text(c, Align2::CENTER_CENTER, glyph, icon_font(10.0), fg);
}

/// For floating areas pinned by their bottom edge above what opens them.
pub trait SizedOffScreen {
    /// The area's first frame laid out off screen.
    ///
    /// egui lays out an area it hasn't shown before once, invisibly, to learn
    /// its size, placing it as though it were 400 px tall. An area pinned by
    /// its bottom then lands too low, over the button that was just clicked.
    /// egui works out what the pointer is over from the last frame's widgets,
    /// so on the next frame a row of the area takes the hover from that
    /// button: a row that opens a flyout on hover opens it (the account
    /// menu's status picker), and the button loses its hover for a frame.
    fn sized_off_screen(self, ctx: &egui::Context) -> Self;
}

impl SizedOffScreen for egui::Area {
    fn sized_off_screen(self, ctx: &egui::Context) -> Self {
        if ctx.memory(|m| m.area_rect(self.layer().id).is_some()) {
            return self;
        }
        self.fixed_pos(pos2(-100_000.0, -100_000.0)).constrain(false)
    }
}

/// Discord's server-icon shape ("blob mask"): a squircle whose corners are
/// three cubic curves, from its 40 × 40 SVG path, as a convex outline of `r`.
pub fn squircle(r: Rect) -> Vec<egui::Pos2> {
    // Top-left corner, from the left edge up to the top edge (units of 40).
    const SEGS: [[(f32, f32); 4]; 3] = [
        [(0.0, 17.4545), (0.0, 11.3449), (0.0, 8.29005), (1.18902, 5.95647)],
        [(1.18902, 5.95647), (2.23491, 3.90379), (3.90379, 2.23491), (5.95647, 1.18902)],
        [(5.95647, 1.18902), (8.29005, 0.0), (11.3449, 0.0), (17.4545, 0.0)],
    ];
    let mut tl: Vec<(f32, f32)> = Vec::new();
    for s in SEGS {
        for i in 0..6 {
            let t = i as f32 / 6.0;
            let u = 1.0 - t;
            let (w0, w1, w2, w3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
            tl.push(((w0 * s[0].0 + w1 * s[1].0 + w2 * s[2].0 + w3 * s[3].0) / 40.0, (w0 * s[0].1 + w1 * s[1].1 + w2 * s[2].1 + w3 * s[3].1) / 40.0));
        }
    }
    tl.push((17.4545 / 40.0, 0.0));
    let at = |x: f32, y: f32| pos2(r.left() + x * r.width(), r.top() + y * r.height());
    let mut out: Vec<egui::Pos2> = tl.iter().map(|&(x, y)| at(x, y)).collect();
    out.extend(tl.iter().rev().map(|&(x, y)| at(1.0 - x, y)));
    out.extend(tl.iter().map(|&(x, y)| at(1.0 - x, 1.0 - y)));
    out.extend(tl.iter().rev().map(|&(x, y)| at(x, 1.0 - y)));
    out
}

/// A squircle filled with `color`.
pub fn fill_squircle(painter: &egui::Painter, r: Rect, color: Color32) {
    painter.add(egui::Shape::convex_polygon(squircle(r), color, Stroke::NONE));
}

/// Text painted in `ui`'s layer after `gray_text(ui, true)` and before
/// `gray_text(ui, false)` is antialiased in grayscale instead of per LCD
/// subpixel (ClearType). Discord's app (Chromium) only uses ClearType where a
/// layer has an opaque background: the server and channel lists, the headers
/// and the member list do, the messages, the message box and the account
/// panel don't, and their text is visibly softer and free of colour fringes.
pub fn gray_text(ui: &Ui, on: bool) {
    use std::sync::atomic::Ordering;
    use std::sync::{Arc, OnceLock};
    type Callback = Arc<eframe::egui_glow::CallbackFn>;
    static CALLBACKS: OnceLock<(Callback, Callback)> = OnceLock::new();
    let (start, end) = CALLBACKS.get_or_init(|| {
        let switch = |on: bool| Arc::new(eframe::egui_glow::CallbackFn::new(move |_, _| eframe::egui_glow::painter::TEXT_GRAY.store(on, Ordering::Relaxed)));
        (switch(true), switch(false))
    });
    // Over the whole window, so the switch is never clipped away.
    let rect = ui.ctx().screen_rect();
    let callback = if on { start.clone() } else { end.clone() };
    ui.painter().with_clip_rect(rect).add(egui::PaintCallback { rect, callback });
}

/// An image (server icon) cut to Discord's squircle. False while it loads.
/// Texture filtering for downscaled pictures (server icons, avatars):
/// trilinear with mipmaps, so a 128 px icon shrunk to 40 px stays smooth
/// instead of aliasing.
pub const SMOOTH: egui::TextureOptions = egui::TextureOptions { mipmap_mode: Some(egui::TextureFilter::Linear), ..egui::TextureOptions::LINEAR };

/// The smallest size Discord's CDN serves that covers `px` physical pixels.
/// Asking for the drawn size keeps pictures sharp: the CDN resizes them
/// well (like a browser does), and they're drawn 1:1 instead of blended
/// from a big image's mipmaps, which looks soft.
pub fn cdn_size(px: f32) -> u32 {
    const SIZES: [u32; 26] = [16, 20, 22, 24, 28, 32, 40, 44, 48, 56, 60, 64, 80, 96, 100, 128, 160, 240, 256, 300, 320, 480, 512, 600, 640, 1024];
    let px = px.round() as u32;
    SIZES.iter().copied().find(|&s| s >= px).unwrap_or(1024)
}

/// A CDN URL with its `size=` set to `size`.
pub fn sized(url: &str, size: u32) -> String {
    match url.find("size=") {
        Some(i) => {
            let end = url[i + 5..].find(|c: char| !c.is_ascii_digit()).map_or(url.len(), |j| i + 5 + j);
            format!("{}size={size}{}", &url[..i], &url[end..])
        }
        None => url.to_string(),
    }
}

pub fn paint_squircle_image(ui: &Ui, r: Rect, uri: &str) -> bool {
    // On whole pixels: a picture fetched at the size it's drawn is then
    // sampled texel for pixel. At a fractional position (a list scrolled by
    // a fraction, as touchpads and smooth scrolling leave it) every pixel
    // blends two texels and the icon goes soft.
    let r = ui.painter().round_rect_to_pixels(r);
    let Ok(egui::load::TexturePoll::Ready { texture }) = egui::Image::new(uri.to_string()).texture_options(SMOOTH).load_for_size(ui.ctx(), r.size()) else { return false };
    let mut mesh = egui::Mesh::with_texture(texture.id);
    let uv = |p: egui::Pos2| pos2((p.x - r.left()) / r.width(), (p.y - r.top()) / r.height());
    mesh.vertices.push(egui::epaint::Vertex { pos: r.center(), uv: uv(r.center()), color: Color32::WHITE });
    // The edge is feathered the way egui antialiases its own shapes: opaque
    // half a pixel inside the outline, transparent half a pixel outside. (A
    // bare mesh has hard, stair-stepped edges.)
    let outline = squircle(r);
    let n = outline.len();
    let feather = 0.5 / ui.ctx().pixels_per_point();
    for i in 0..n {
        let (prev, p, next) = (outline[(i + n - 1) % n], outline[i], outline[(i + 1) % n]);
        // The outline runs clockwise on screen: the outward normal of a
        // direction (x, y) is (y, −x).
        let d = (next - prev).normalized();
        let out = vec2(d.y, -d.x) * feather;
        mesh.vertices.push(egui::epaint::Vertex { pos: p - out, uv: uv(p - out), color: Color32::WHITE });
        mesh.vertices.push(egui::epaint::Vertex { pos: p + out, uv: uv(p + out), color: Color32::TRANSPARENT });
    }
    let n = n as u32;
    for i in 0..n {
        let j = (i + 1) % n;
        let (inner_i, outer_i, inner_j, outer_j) = (1 + 2 * i, 2 + 2 * i, 1 + 2 * j, 2 + 2 * j);
        mesh.add_triangle(0, inner_i, inner_j);
        mesh.add_triangle(inner_i, outer_i, outer_j);
        mesh.add_triangle(inner_i, outer_j, inner_j);
    }
    ui.painter().add(egui::Shape::mesh(mesh));
    true
}

/// Where a nameplate is shown; Discord tints and fades it differently in each.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Plate {
    /// The user panel (bottom left).
    Account,
    /// A DM row in the Direct Messages list.
    Channel,
    MemberList,
}

/// Fill the convex outline of `rect` (rounded by `rounding`) as a mesh whose
/// colour (and texture coordinates) vary piecewise-linearly in x, breaking at
/// `xs`: the outline is cut into vertical strips at each break so every
/// triangle interpolates exactly. Used for Discord's nameplate gradients,
/// masks and pictures inside rounded rows.
fn strip_mesh(
    rect: Rect,
    rounding: f32,
    xs: &[f32],
    color_at: impl Fn(f32) -> Color32,
    texture: Option<(egui::TextureId, Rect, Rect)>,
) -> egui::Mesh {
    let mut outline = Vec::new();
    egui::epaint::tessellator::path::rounded_rectangle(&mut outline, rect, egui::Rounding::same(rounding));
    let mut mesh = match texture {
        Some((id, ..)) => egui::Mesh::with_texture(id),
        None => egui::Mesh::default(),
    };
    let uv_at = |p: egui::Pos2| match texture {
        Some((_, img, uv)) => pos2(
            egui::emath::remap(p.x, img.x_range(), uv.x_range()),
            egui::emath::remap(p.y, img.y_range(), uv.y_range()),
        ),
        None => egui::epaint::WHITE_UV,
    };
    // Clip a convex polygon to a ≤ x ≤ b.
    let clip = |poly: &[egui::Pos2], x: f32, keep_right: bool| -> Vec<egui::Pos2> {
        let inside = |p: &egui::Pos2| if keep_right { p.x >= x } else { p.x <= x };
        let mut out = Vec::new();
        for i in 0..poly.len() {
            let (a, b) = (poly[i], poly[(i + 1) % poly.len()]);
            match (inside(&a), inside(&b)) {
                (true, true) => out.push(b),
                (true, false) | (false, true) => {
                    let t = (x - a.x) / (b.x - a.x);
                    let cut = pos2(x, a.y + (b.y - a.y) * t);
                    out.push(cut);
                    if inside(&b) {
                        out.push(b);
                    }
                }
                (false, false) => {}
            }
        }
        out
    };
    let mut cuts: Vec<f32> = xs.iter().copied().filter(|x| *x > rect.left() && *x < rect.right()).collect();
    cuts.sort_by(f32::total_cmp);
    let mut edges = vec![rect.left()];
    edges.extend(cuts);
    edges.push(rect.right());
    for w in edges.windows(2) {
        let poly = clip(&clip(&outline, w[0], true), w[1], false);
        if poly.len() < 3 {
            continue;
        }
        let base = mesh.vertices.len() as u32;
        for p in &poly {
            mesh.vertices.push(egui::epaint::Vertex { pos: *p, uv: uv_at(*p), color: color_at(p.x) });
        }
        for i in 1..poly.len() as u32 - 1 {
            mesh.add_triangle(base, base + i, base + i + 1);
        }
    }
    mesh
}

/// A user's nameplate (shop cosmetic) behind `rect`, the way Discord draws
/// it: a horizontal tint in the nameplate's palette colour, and the picture
/// fitted to the row's height on the right at the placement's opacity. In
/// lists the whole plate is faded to 30 % behind the name (`name_right`) and
/// comes in fully 50 px after it.
pub fn paint_nameplate(ui: &Ui, rect: Rect, rounding: f32, user: &discord::model::User, place: Plate, hovered: bool, selected: bool, name_right: Option<f32>) {
    for s in nameplate_shapes(ui, rect, rounding, user, place, hovered, selected, name_right) {
        ui.painter().add(s);
    }
}

/// [`paint_nameplate`]'s shapes, for rows that know where their name ends
/// only after drawing it (put them in a slot reserved beforehand).
pub fn nameplate_shapes(ui: &Ui, rect: Rect, rounding: f32, user: &discord::model::User, place: Plate, hovered: bool, selected: bool, name_right: Option<f32>) -> Vec<egui::Shape> {
    let mut out = Vec::new();
    let Some(url) = user.nameplate_url() else { return out };
    if !ui.is_rect_visible(rect) {
        return out;
    }
    let tint = user.nameplate_color().map(rgb_u32);
    let a = |hex: u8| hex as f32 / 255.0;
    let with_alpha = |c: Color32, alpha: f32| crate::style::rgba(c.r(), c.g(), c.b(), (alpha.clamp(0.0, 1.0) * 255.0).round() as u8);
    // The list fade: 0.3 behind the name, 1 from 50 px after it.
    // (Discord's member list shows the plate unfaded.)
    let mask_x = name_right.filter(|_| place == Plate::Channel).map(|r| r - 5.0);
    let mask = |x: f32| match (place, mask_x) {
        (Plate::Account, _) | (_, None) => 1.0,
        (_, Some(m)) => 0.3 + 0.7 * ((x - m) / 50.0).clamp(0.0, 1.0),
    };
    let mut xs: Vec<f32> = Vec::new();
    if let Some(m) = mask_x {
        xs.extend([m, m + 50.0]);
    }
    // Palette tint.
    if let Some(c) = tint {
        let (l, w) = (rect.left(), rect.width().max(1.0));
        let alpha_at = |x: f32| {
            let f = ((x - l) / w).clamp(0.0, 1.0);
            match place {
                Plate::Account => egui::lerp(a(0x1A)..=a(if hovered { 0x4D } else { 0x66 }), f),
                _ => {
                    let end = a(if selected { 0x80 } else if hovered && place == Plate::MemberList { 0x4D } else { 0x33 });
                    if f < 0.2 {
                        egui::lerp(0.0..=a(0x14), f / 0.2)
                    } else if f < 0.5 {
                        a(0x14)
                    } else {
                        egui::lerp(a(0x14)..=end, (f - 0.5) / 0.5)
                    }
                }
            }
        };
        let mut stops = xs.clone();
        if place != Plate::Account {
            stops.extend([l + w * 0.2, l + w * 0.5]);
        }
        out.push(egui::Shape::mesh(strip_mesh(rect, rounding, &stops, |x| with_alpha(c, alpha_at(x) * mask(x)), None)));
    }
    // The picture: full height, right-aligned, keeping its proportions.
    let opacity = match place {
        Plate::Account => 0.4,
        _ if selected => 0.9,
        Plate::Channel if hovered => 0.4,
        _ => 0.6,
    };
    if let Ok(egui::load::TexturePoll::Ready { texture }) = egui::Image::new(url).load_for_size(ui.ctx(), rect.size()) {
        let aspect = texture.size.x.max(1.0) / texture.size.y.max(1.0);
        let img = Rect::from_min_max(pos2(rect.right() - rect.height() * aspect, rect.top()), rect.max);
        let shown = rect.intersect(img);
        if shown.width() > 0.5 {
            let mut stops = xs.clone();
            stops.push(shown.left());
            let full = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
            // Cut the rounded outline to the picture's columns.
            let mesh = strip_mesh(rect, rounding, &stops, |x| Color32::WHITE.gamma_multiply(opacity * mask(x)), Some((texture.id, img, full)));
            let keep = shown.left() - 0.01;
            let mut kept = egui::Mesh::with_texture(texture.id);
            for tri in mesh.indices.chunks(3) {
                if tri.iter().all(|&i| mesh.vertices[i as usize].pos.x >= keep) {
                    let base = kept.vertices.len() as u32;
                    for &i in tri {
                        kept.vertices.push(mesh.vertices[i as usize]);
                    }
                    kept.add_triangle(base, base + 1, base + 2);
                }
            }
            out.push(egui::Shape::mesh(kept));
        }
    }
    out
}

/// The colour a status-dot ring should be over the user panel: the panel's
/// own surface where the dot sits (Discord cuts the ring out of the avatar).
pub fn theme_surface_color(ctx: &egui::Context, at: egui::Pos2, surface: Surface, t: &crate::style::Theme, plain: Color32) -> Color32 {
    let Some(g) = t.gradient.as_ref().filter(|g| !g.stops.is_empty()) else { return plain };
    let c = g.color_at(at, ctx.screen_rect());
    // The overlay is premultiplied: lay it over the gradient's colour.
    let o = overlay_color(t, surface);
    let a = o.a() as f32 / 255.0;
    let mix = |g: u8, o: u8| (g as f32 * (1.0 - a) + o as f32).round().clamp(0.0, 255.0) as u8;
    Color32::from_rgb(mix(c.r(), o.r()), mix(c.g(), o.g()), mix(c.b(), o.b()))
}

impl RustCord {
    /// `user` as they appear in `guild`: Discord lets a member set a display
    /// name style per server, which replaces their own one there.
    pub(crate) fn user_in<'a>(&self, user: &'a discord::model::User, guild: Option<discord::model::Id>) -> std::borrow::Cow<'a, discord::model::User> {
        match self.store.member_style(guild, user.id) {
            Some(style) => {
                let mut user = user.clone();
                user.display_name_styles = Some(style.clone());
                std::borrow::Cow::Owned(user)
            }
            None => std::borrow::Cow::Borrowed(user),
        }
    }
}

/// `font` in the user's Nitro display-name font (when they have one and
/// RustCord has it), same size.
pub fn name_font(user: &discord::model::User, font: FontId) -> FontId {
    if !NAME_STYLES.load(std::sync::atomic::Ordering::Relaxed) {
        return font;
    }
    match user.display_name_styles.as_ref().and_then(|s| crate::style::dns_family(s.font_id)) {
        Some(family) => FontId::new(font.size, family),
        None => font,
    }
}

/// The user's Nitro display-name colours, unless Accessibility → Display
/// Name Styles is off (then names keep their plain or role colour).
pub fn name_style_colors(user: &discord::model::User) -> Option<&[u32]> {
    user.name_colors().filter(|_| NAME_STYLES.load(std::sync::atomic::Ordering::Relaxed))
}

/// Extra letter spacing (px) Discord gives a display-name font at `size`.
fn name_spacing(user: &discord::model::User, size: f32) -> f32 {
    user.display_name_styles.as_ref().filter(|_| NAME_STYLES.load(std::sync::atomic::Ordering::Relaxed)).map_or(0.0, |s| crate::style::dns_letter_spacing(s.font_id) * size)
}

/// HSL helpers for Discord's display-name palette (chroma.js semantics).
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, min) = (r.max(g).max(b), r.min(g).min(b));
    let l = (max + min) / 2.0;
    if (max - min).abs() < f32::EPSILON {
        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 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))
}

/// Discord's shades of a display-name colour: (light1, light2, dark1, dark2,
/// toon stroke, neon stroke).
fn name_shades(c: Color32) -> (Color32, Color32, Color32, Color32, Color32, Color32) {
    let (h, s, l) = to_hsl(c);
    (
        from_hsl(h, s, (1.2 * l).min(1.0)),
        from_hsl(h, s, (1.6 * l).min(1.0)),
        from_hsl(h, s, (0.6 * l).max(0.0)),
        from_hsl(h, s, (0.2 * l).max(0.0)),
        from_hsl(h, s, (0.4 * l).max(0.12)),
        from_hsl(h, (1.2 * s).min(1.0), (l + 0.1).min(0.6)),
    )
}

/// Lay out `text` with per-character colours from `color_at(i, n)`.
fn name_job(text: &str, font: &FontId, spacing: f32, color_at: impl Fn(usize, usize) -> Color32) -> egui::text::LayoutJob {
    let n = text.chars().count();
    let mut job = egui::text::LayoutJob::default();
    for (i, ch) in text.chars().enumerate() {
        let mut buf = [0u8; 4];
        let mut fmt = egui::TextFormat::simple(font.clone(), color_at(i, n));
        fmt.extra_letter_spacing = spacing;
        job.append(ch.encode_utf8(&mut buf), 0.0, fmt);
    }
    job
}

/// Colour at `t` (0–1) along evenly spaced stops.
fn along(stops: &[Color32], t: f32) -> Color32 {
    match stops.len() {
        0 => Color32::WHITE,
        1 => stops[0],
        n => {
            let x = t.clamp(0.0, 1.0) * (n - 1) as f32;
            let i = (x.floor() as usize).min(n - 2);
            stops[i].lerp_to_gamma(stops[i + 1], x - i as f32)
        }
    }
}

/// Discord's gradient name: `linear-gradient(to right bottom, first 10 %,
/// … last 90 %)` over the name's box, clipped to its letters. "To right
/// bottom" runs at right angles to the box's bottom-left → top-right
/// diagonal, so on a wide name it changes mostly down each letter and a
/// little along the name. Each glyph corner gets its colour, which the GPU
/// blends across the letter as the browser does.
///
/// The letters are a mask the gradient shows through, as in the browser:
/// drawn with plain antialiasing and without the weight ordinary text gets
/// (the renderer's mask marker: u moved up by the font texture's width × 2).
fn diagonal_gradient(painter: &egui::Painter, galley: &std::sync::Arc<egui::Galley>, stops: &[Color32]) -> std::sync::Arc<egui::Galley> {
    let size = galley.size();
    let mask_shift = 2.0 * painter.ctx().fonts(|f| f.font_image_size())[0] as f32;
    let mut out = (**galley).clone();
    for row in &mut out.rows {
        for v in &mut row.visuals.mesh.vertices {
            let t = to_right_bottom(v.pos, size);
            v.color = along(stops, ((t - 0.1) / 0.8).clamp(0.0, 1.0));
            v.uv.x += mask_shift;
            v.uv.y = -v.uv.y.abs();
        }
    }
    std::sync::Arc::new(out)
}

/// Where `p` falls (0 at the top-left corner, 1 at the bottom-right) on a
/// CSS `to right bottom` gradient over a box of `size`.
fn to_right_bottom(p: egui::Pos2, size: egui::Vec2) -> f32 {
    let (w, h) = (size.x.max(1.0), size.y.max(1.0));
    let diagonal = (w * w + h * h).sqrt();
    let length = 2.0 * w * h / diagonal;
    ((p.x - w / 2.0) * h / diagonal + (p.y - h / 2.0) * w / diagonal) / length + 0.5
}

/// A display name the way Discord draws Nitro "Display Name Styles": the
/// user's font, and their effect — solid, gradient, neon (white with a glow),
/// toon (outlined), pop (offset shadow), glow, prism or gummy — in their
/// colours; `fallback` colour without a style. Returns the drawn rect.
pub fn paint_styled_name(
    painter: &egui::Painter,
    pos: egui::Pos2,
    align: Align2,
    text: &str,
    font: FontId,
    user: &discord::model::User,
    fallback: Color32,
) -> Rect {
    let font = name_font(user, font);
    let spacing = name_spacing(user, font.size);
    // (With Display Name Styles off there are no colours, so no effect either.)
    let colors: Vec<Color32> = name_style_colors(user).map(|c| c.iter().map(|&c| rgb_u32(c)).collect()).unwrap_or_default();
    let effect = user.display_name_styles.as_ref().map(|s| s.effect_id).unwrap_or(0);
    let Some(&main) = colors.first() else {
        let galley = painter.layout_job(name_job(text, &font, spacing, |_, _| fallback));
        let rect = align.anchor_size(pos, galley.size());
        painter.galley(rect.min, galley, fallback);
        return rect;
    };
    let (light1, _light2, _dark1, dark2, toon_stroke, neon_stroke) = name_shades(main);
    let solid = |c: Color32| name_job(text, &font, spacing, move |_, _| c);
    // The fill's layout gives the size every layer shares.
    let fill_job = match effect {
        // Gradient / glow: coloured below, corner by corner.
        2 | 6 => solid(main),
        // Prism: the colours cycle along the name.
        7 => name_job(text, &font, spacing, |i, _| {
            let cycle = colors.len() as f32 + 1.0;
            let t = (i as f32 * 0.5) % cycle / cycle;
            let mut ring = colors.clone();
            ring.push(colors[0]);
            along(&ring, t)
        }),
        // Gummy: each letter in the next colour.
        8 => name_job(text, &font, spacing, |i, _| colors[i % colors.len()]),
        3 | 5 => solid(Color32::WHITE),
        4 => solid(light1),
        _ => solid(main),
    };
    let mut galley = painter.layout_job(fill_job);
    if matches!(effect, 2 | 6) {
        galley = diagonal_gradient(painter, &galley, &colors);
    }
    let rect = align.anchor_size(pos, galley.size());
    let at = rect.min;
    let ring = |r: f32| [(-r, 0.0), (r, 0.0), (0.0, -r), (0.0, r), (-r, -r), (r, r), (-r, r), (r, -r)];
    match effect {
        // Neon: white letters, a coloured outline, and a soft glow around them.
        3 => {
            let glow = painter.layout_job(solid(main));
            for r in [3.5_f32, 2.0] {
                for (dx, dy) in ring(r) {
                    painter.galley_with_override_text_color(at + vec2(dx, dy), glow.clone(), main.gamma_multiply(0.10));
                }
            }
            let stroke = painter.layout_job(solid(neon_stroke));
            for (dx, dy) in ring(1.0) {
                painter.galley(at + vec2(dx, dy), stroke.clone(), neon_stroke);
            }
        }
        // Toon: a thick dark outline under lighter letters.
        4 => {
            let stroke = painter.layout_job(solid(toon_stroke));
            for r in [1.6_f32, 0.8] {
                for (dx, dy) in ring(r) {
                    painter.galley(at + vec2(dx, dy), stroke.clone(), toon_stroke);
                }
            }
        }
        // Pop: a solid copy dropped below, both outlined in the darkest shade.
        5 => {
            let drop = vec2(0.0, (font.size * 0.08).max(1.0) + 1.0);
            let outline = painter.layout_job(solid(dark2));
            for (dx, dy) in ring(1.2) {
                painter.galley(at + drop + vec2(dx, dy), outline.clone(), dark2);
            }
            painter.galley(at + drop, painter.layout_job(solid(main)), main);
            for (dx, dy) in ring(1.2) {
                painter.galley(at + vec2(dx, dy), outline.clone(), dark2);
            }
        }
        // Glow: the gradient with a halo in its first colour.
        6 => {
            let glow = painter.layout_job(solid(main));
            for (dx, dy) in ring(2.0) {
                painter.galley_with_override_text_color(at + vec2(dx, dy), glow.clone(), main.gamma_multiply(0.12));
            }
        }
        _ => {}
    }
    painter.galley(at, galley, main);
    rect
}

/// What Discord shows under a name in the DM and member lists (its
/// `ActivityStatus`, read from the web app 2026-11-22): the first activity
/// (icon + its text), "+N" for more, then "•" and the custom status. When the
/// custom status has text, the activity shrinks to its icon.
pub enum SubLine {
    Status {
        /// Icon glyph and text of the first activity (not custom status / hang).
        activity: Option<(&'static str, String)>,
        /// How many more activities there are.
        more: usize,
        /// Custom status: emoji image URL and text.
        custom: Option<(Option<String>, String)>,
    },
    Text(String),
}

impl SubLine {
    pub fn of(p: &discord::model::Presence) -> Option<SubLine> {
        // Like Discord: custom status and "hang" aside, and one per app / name.
        let mut acts: Vec<&discord::model::Activity> = Vec::new();
        for a in p.activities.iter().filter(|a| a.kind != 4 && a.kind != 6) {
            let same = |b: &&discord::model::Activity| (a.application_id.is_some() && a.application_id == b.application_id) || (!a.name.is_empty() && a.name == b.name);
            if !acts.iter().any(same) {
                acts.push(a);
            }
        }
        let activity = acts.first().map(|a| {
            let non_empty = |s: &Option<String>| s.clone().filter(|s| !s.is_empty());
            let text = match a.kind {
                2 if a.name == "Spotify" => non_empty(&a.state).map(|s| s.replace("; ", ", ")).unwrap_or_else(|| a.name.clone()),
                1 => non_empty(&a.details).unwrap_or_else(|| a.name.clone()),
                _ => a.name.clone(),
            };
            (Self::activity_icon(a), text)
        });
        let custom = p.custom_status().and_then(|cs| {
            let text = cs.state.as_deref().map(str::trim).unwrap_or_default().to_string();
            let emoji = cs.emoji.as_ref().and_then(|e| match (e.id, &e.name) {
                (Some(id), _) => Some(emoji_img(id, e.animated, 32)),
                (None, Some(n)) => Some(crate::emoji::twemoji_url(n)),
                _ => None,
            });
            (emoji.is_some() || !text.is_empty()).then_some((emoji, text))
        });
        (activity.is_some() || custom.is_some()).then(|| SubLine::Status { activity, more: acts.len().saturating_sub(1), custom })
    }

    /// The icon before an activity (Discord's `ActivityStatus`, read from the
    /// web app 2026-11-23): an app played inside a call (flag 256), or the
    /// "Conjuring" placeholder, has the apps icon; playing and competing the
    /// game controller (Rich Presence games too); listening a music note;
    /// watching and streaming a TV. Anything else has none ("").
    fn activity_icon(a: &discord::model::Activity) -> &'static str {
        if a.flags & 256 != 0 || (a.kind == 0 && a.name == "Conjuring" && a.application_id.is_none()) {
            return icon::APPS;
        }
        match a.kind {
            0 | 5 => icon::GAME_CONTROLLER,
            2 => icon::MUSIC,
            1 | 3 => icon::TV,
            _ => "",
        }
    }

    /// Paint it with its left edge at `pos` (vertically centred on `pos.y`).
    pub fn paint(&self, ui: &Ui, painter: &egui::Painter, pos: egui::Pos2, color: Color32) {
        // body-xs: 12 px; pieces 4 px apart.
        let font = crate::style::medium(12.0);
        match self {
            SubLine::Status { activity, more, custom } => {
                let mut x = pos.x;
                let custom_text = custom.as_ref().is_some_and(|(_, t)| !t.is_empty());
                if let Some((glyph, text)) = activity {
                    // Discord draws it 12 px in the "online" green, 4 px before the text.
                    if !glyph.is_empty() {
                        painter.text(pos2(x + 6.0, pos.y), Align2::CENTER_CENTER, *glyph, icon_font(12.0), status_color("online"));
                        x += 16.0;
                    }
                    if !custom_text {
                        x = painter.text(pos2(x, pos.y), Align2::LEFT_CENTER, text, font.clone(), color).right() + 4.0;
                    }
                    if *more > 0 {
                        let c = if custom_text { Color32::from_rgb(0x43, 0xa2, 0x5a) } else { color };
                        x = painter.text(pos2(x, pos.y), Align2::LEFT_CENTER, format!("+{more}"), font.clone(), c).right() + 4.0;
                    }
                    if custom.is_some() {
                        x = painter.text(pos2(x, pos.y), Align2::LEFT_CENTER, "•", FontId::proportional(12.0), color).right() + 4.0;
                    }
                }
                if let Some((emoji, text)) = custom {
                    if let Some(url) = emoji {
                        let r = Rect::from_center_size(pos2(x + 7.0, pos.y), vec2(14.0, 14.0));
                        if painter.clip_rect().contains_rect(r) {
                            egui::Image::new(url.as_str()).paint_at(ui, r);
                        }
                        x += 18.0;
                    }
                    painter.text(pos2(x, pos.y), Align2::LEFT_CENTER, text, font, color);
                }
            }
            SubLine::Text(text) => {
                painter.text(pos, Align2::LEFT_CENTER, text, font, color);
            }
        }
    }
}

/// A painted server tag chip (badge + tag) starting at `left` x, centred on
/// `y`. Returns the chip's width.
pub fn paint_tag_chip(ui: &Ui, painter: &egui::Painter, left: f32, y: f32, tag: &str, badge: Option<&str>, t: &Theme) -> f32 {
    let font = FontId::new(11.0, egui::FontFamily::Name(crate::style::BOLD.into()));
    let galley = painter.layout_no_wrap(tag.to_string(), font, t.header_primary);
    let badge_w = if badge.is_some() { 15.0 } else { 0.0 };
    let w = 4.0 + badge_w + galley.size().x + 5.0;
    let rect = Rect::from_min_size(pos2(left, y - 9.0), vec2(w, 18.0));
    painter.rect_filled(rect, 4.0, crate::style::overlay(0.16));
    if let Some(b) = badge {
        let r = Rect::from_center_size(pos2(left + 4.0 + 6.0, y), vec2(12.0, 12.0));
        if painter.clip_rect().contains_rect(r) {
            egui::Image::new(b.to_string()).paint_at(ui, r);
        }
    }
    painter.galley(pos2(left + 4.0 + badge_w, y - galley.size().y / 2.0), galley, t.header_primary);
    w
}

/// Round avatar (image if available, otherwise a coloured initial).
pub fn paint_avatar(ui: &Ui, rect: Rect, url: Option<String>, name: &str) {
    let r = rect.width() / 2.0;
    match url {
        Some(url) => egui::Image::new(url).texture_options(SMOOTH).rounding(r).paint_at(ui, rect),
        None => {
            ui.painter().circle_filled(rect.center(), r, color_for(name));
            let initial: String = name.chars().next().map(|c| c.to_uppercase().collect()).unwrap_or_default();
            ui.painter().text(
                rect.center(),
                Align2::CENTER_CENTER,
                initial,
                FontId::proportional(rect.width() * 0.45),
                Color32::WHITE,
            );
        }
    }
}

/// Discord's name badges: "✓ OFFICIAL" for Discord's system account, "APP" for
/// bots ("✓ APP" when verified). Nothing for normal users.
pub fn bot_badge(ui: &mut Ui, t: &Theme, user: &discord::model::User) {
    let label = if user.system {
        "\u{E73E} OFFICIAL"
    } else if user.verified_bot() {
        "\u{E73E} APP"
    } else if user.bot {
        "APP"
    } else {
        return;
    };
    Frame::none().fill(t.accent).rounding(4.0).inner_margin(Margin::symmetric(4.0, 1.0)).show(ui, |ui| {
        ui.spacing_mut().item_spacing.x = 2.0;
        ui.horizontal(|ui| {
            for (i, part) in label.split(' ').enumerate() {
                if part == "\u{E73E}" {
                    ui.label(egui::RichText::new(part).font(icon_font(9.0)).color(Color32::WHITE));
                } else {
                    if i > 0 {
                        ui.add_space(1.0);
                    }
                    ui.label(crate::style::bold(part).size(10.0).color(Color32::WHITE));
                }
            }
        });
    });
}

/// [`bot_badge`] for painter-drawn rows (DM list, member list). Returns the
/// badge's right edge, or None for normal users.
pub fn paint_bot_badge(painter: &egui::Painter, left: f32, y: f32, user: &discord::model::User, t: &Theme) -> Option<f32> {
    let (check, word) = if user.system {
        (true, "OFFICIAL")
    } else if user.verified_bot() {
        (true, "APP")
    } else if user.bot {
        (false, "APP")
    } else {
        return None;
    };
    let font = FontId::new(10.0, egui::FontFamily::Name(crate::style::BOLD.into()));
    let g = painter.layout_no_wrap(word.to_string(), font, Color32::WHITE);
    let check_w = if check { 12.0 } else { 0.0 };
    let rect = Rect::from_min_size(pos2(left, y - 8.0), vec2(g.size().x + check_w + 8.0, 16.0));
    painter.rect_filled(rect, 4.0, t.accent);
    if check {
        painter.text(pos2(rect.left() + 9.0, y), Align2::CENTER_CENTER, icon::CHECK, icon_font(9.0), Color32::WHITE);
    }
    painter.galley(pos2(rect.left() + 4.0 + check_w, y - g.size().y / 2.0), g, Color32::WHITE);
    Some(rect.right())
}

pub fn status_color(status: &str) -> Color32 {
    match status {
        // Discord web's current status colours (read 2026-11-23).
        "online" | "mobile" => Color32::from_rgb(0x45, 0xa3, 0x66),
        "idle" => Color32::from_rgb(0xff, 0xc0, 0x4e),
        "dnd" => Color32::from_rgb(0xda, 0x3e, 0x44),
        _ => Color32::from_rgb(0x80, 0x84, 0x8e),
    }
}

pub fn status_label(status: &str) -> &'static str {
    match status {
        "online" | "mobile" => "Online",
        "idle" => "Idle",
        "dnd" => "Do Not Disturb",
        "invisible" => "Invisible",
        _ => "Offline",
    }
}

/// Discord's channel hashtag (its 24×24 icon), filling `rect`.
pub fn paint_hashtag(painter: &egui::Painter, rect: Rect, color: Color32) {
    paint_icon(painter, rect, crate::style::icon::HASH, color);
}

/// Discord's icon for a channel type (#, speaker, megaphone, forum, stage, thread).
pub fn channel_icon(kind: u8) -> &'static str {
    use discord::model::channel_kind;
    use crate::style::icon;
    match kind {
        k if k == channel_kind::GUILD_STAGE_VOICE => icon::STAGE,
        k if channel_kind::is_voice(k) => icon::VOICE,
        channel_kind::GUILD_ANNOUNCEMENT => icon::ANNOUNCEMENT,
        channel_kind::GUILD_FORUM | channel_kind::GUILD_MEDIA => icon::FORUM,
        k if channel_kind::is_thread(k) => icon::THREAD,
        _ => icon::HASH,
    }
}

/// Discord's locked variant of a channel icon (private channels).
pub fn locked_icon(glyph: &str) -> &str {
    use crate::style::icon;
    match glyph {
        icon::HASH => icon::TEXT_LOCK,
        icon::VOICE => icon::VOICE_LOCK,
        icon::ANNOUNCEMENT => icon::ANNOUNCEMENT_LOCK,
        icon::FORUM => icon::FORUM_LOCK,
        g => g,
    }
}

/// Icon-font characters: Segoe's Private Use Area and RustCord's U+F1001….
pub fn is_icon_char(c: char) -> bool {
    ('\u{E000}'..='\u{F8FF}').contains(&c) || ('\u{F0000}'..='\u{FFFFD}').contains(&c)
}

/// One of the icon font's glyphs filling `rect` (Discord's icons are drawn
/// edge to edge in a 24×24 box, so `rect` is that box).
pub fn paint_icon(painter: &egui::Painter, rect: Rect, glyph: &str, color: Color32) {
    painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, crate::style::icon_font(rect.height()), color);
}

/// Discord's status dot: filled (online), crescent (idle), bar (dnd), hollow
/// (offline), or a little phone ("mobile": online only on their phone).
pub fn paint_status_dot(ui: &Ui, center: egui::Pos2, r: f32, status: &str, ring: Color32) {
    let p = ui.painter();
    let c = status_color(status);
    if status == "mobile" {
        // Taller than the dot, bottom-aligned with where the dot would be.
        let body = Rect::from_min_max(pos2(center.x - r * 0.72, center.y - r * 1.55), pos2(center.x + r * 0.72, center.y + r));
        p.rect_filled(body.expand(2.5), r * 0.6, ring);
        p.rect_filled(body, r * 0.35, c);
        let screen = Rect::from_min_max(body.min + vec2(r * 0.28, r * 0.3), pos2(body.right() - r * 0.28, body.bottom() - r * 0.62));
        p.rect_filled(screen, r * 0.08, ring);
        return;
    }
    p.circle_filled(center, r + 2.5, ring);
    p.circle_filled(center, r, c);
    match status {
        "idle" => {
            p.circle_filled(center - vec2(r * 0.45, r * 0.45), r * 0.62, ring);
        }
        "dnd" => {
            p.rect_filled(Rect::from_center_size(center, vec2(r * 1.2, r * 0.45)), r * 0.2, ring);
        }
        "online" => {}
        _ => {
            p.circle_filled(center, r * 0.45, ring);
        }
    }
}

/// Server-icon text for guilds without an icon: "Rust Lounge" → "RL".
pub fn acronym(name: &str) -> String {
    let a: String = name
        .split_whitespace()
        .filter_map(|w| w.chars().next())
        .take(4)
        .collect();
    if a.is_empty() {
        "?".into()
    } else {
        a
    }
}

/// Clicking off a dialog closes it: true when the mouse button went down
/// outside `rect` this frame (on the dimmed app behind it), unless one of the
/// dialog's own drop-downs is open (those reach outside it).
pub fn pressed_outside(ctx: &egui::Context, rect: Rect) -> bool {
    !ctx.memory(|m| m.any_popup_open()) && ctx.input(|i| i.pointer.primary_pressed() && i.pointer.interact_pos().is_some_and(|p| !rect.contains(p)))
}

/// An on/off switch. Returns a response that is `changed()` when toggled.
pub fn toggle_switch(ui: &mut Ui, on: &mut bool, t: &Theme) -> Response {
    let (rect, mut resp) = ui.allocate_exact_size(vec2(40.0, 24.0), Sense::click());
    if resp.clicked() {
        *on = !*on;
        resp.mark_changed();
    }
    let how_on = ui.ctx().animate_bool(resp.id, *on);
    let bg = if *on { Color32::from_rgb(0x23, 0xa5, 0x5a) } else { t.interactive_muted };
    ui.painter().rect_filled(rect, 12.0, bg);
    let x = egui::lerp((rect.left() + 12.0)..=(rect.right() - 12.0), how_on);
    ui.painter().circle_filled(pos2(x, rect.center().y), 9.0, Color32::WHITE);
    switch_mark(ui, pos2(x, rect.center().y), *on, bg);
    resp.on_hover_cursor(egui::CursorIcon::PointingHand)
}

/// Accessibility → "Show on/off indicators": a tick or a cross in a switch's knob.
pub fn switch_mark(ui: &Ui, c: egui::Pos2, on: bool, color: Color32) {
    if !SWITCH_ICONS.load(std::sync::atomic::Ordering::Relaxed) {
        return;
    }
    let s = Stroke::new(1.6_f32, color);
    let p = ui.painter();
    if on {
        p.line_segment([c + vec2(-3.5, 0.0), c + vec2(-1.0, 2.5)], s);
        p.line_segment([c + vec2(-1.0, 2.5), c + vec2(3.5, -2.5)], s);
    } else {
        p.line_segment([c + vec2(-3.0, -3.0), c + vec2(3.0, 3.0)], s);
        p.line_segment([c + vec2(-3.0, 3.0), c + vec2(3.0, -3.0)], s);
    }
}

pub fn format_timestamp(ts: &str) -> String {
    let Ok(dt) = chrono::DateTime::parse_from_rfc3339(ts) else { return String::new() };
    let local = dt.with_timezone(&chrono::Local);
    let today = chrono::Local::now().date_naive();
    let day = local.date_naive();
    if day == today {
        local.format(time_fmt()).to_string()
    } else if Some(day) == today.pred_opt() {
        format!("Yesterday at {}", local.format(time_fmt()))
    } else {
        format!("{}, {}", local.format("%d/%m/%Y"), local.format(time_fmt()))
    }
}

pub fn short_time(ts: &str) -> String {
    chrono::DateTime::parse_from_rfc3339(ts)
        .map(|dt| dt.with_timezone(&chrono::Local).format(time_fmt()).to_string())
        .unwrap_or_default()
}

/// Discord `<t:unix:style>` timestamps.
pub fn format_unix(unix: i64, style: char) -> String {
    let Some(dt) = chrono::DateTime::from_timestamp(unix, 0) else { return unix.to_string() };
    let local = dt.with_timezone(&chrono::Local);
    match style {
        't' => local.format(time_fmt()).to_string(),
        'T' => local.format(if hour24() { "%H:%M:%S" } else { "%-I:%M:%S %p" }).to_string(),
        'd' => local.format("%m/%d/%Y").to_string(),
        'D' => local.format("%B %-d, %Y").to_string(),
        'F' => format!("{} {}", local.format("%A, %B %-d, %Y"), local.format(time_fmt())),
        'R' => relative_time(unix - chrono::Utc::now().timestamp()),
        _ => format!("{} {}", local.format("%B %-d, %Y"), local.format(time_fmt())),
    }
}

/// Discord's `<t:…:R>` wording (moment.js thresholds): "a few seconds ago",
/// "a minute ago", "5 minutes ago", "an hour ago", "a day ago", "in 3 days"…
pub fn relative_time(secs: i64) -> String {
    let s = secs.unsigned_abs() as f64;
    let (m, h, d) = (s / 60.0, s / 3600.0, s / 86_400.0);
    let text = if s < 45.0 {
        "a few seconds".to_string()
    } else if s < 90.0 {
        "a minute".to_string()
    } else if m < 45.0 {
        format!("{} minutes", m.round() as i64)
    } else if m < 90.0 {
        "an hour".to_string()
    } else if h < 22.0 {
        format!("{} hours", h.round() as i64)
    } else if h < 36.0 {
        "a day".to_string()
    } else if d < 26.0 {
        format!("{} days", d.round() as i64)
    } else if d < 45.0 {
        "a month".to_string()
    } else if d < 320.0 {
        format!("{} months", (d / 30.4).round().max(2.0) as i64)
    } else if d < 548.0 {
        "a year".to_string()
    } else {
        format!("{} years", (d / 365.0).round() as i64)
    };
    if secs > 0 {
        format!("in {text}")
    } else {
        format!("{text} ago")
    }
}

pub fn human_size(bytes: u64) -> String {
    let b = bytes as f64;
    if b >= 1_048_576.0 {
        format!("{:.1} MB", b / 1_048_576.0)
    } else if b >= 1024.0 {
        format!("{:.1} KB", b / 1024.0)
    } else {
        format!("{bytes} bytes")
    }
}

/// Discord's context menus (read from its web app 2026-11-22): surface-higher
/// card, 1 px border-strong, 8 px corners, 8 px padding all round and a
/// 0 12 24 rgba(0,0,0,.24) shadow.
pub fn ctx_menu_frame(t: &Theme) -> Frame {
    Frame::none()
        .fill(t.bg_floating)
        .rounding(8.0)
        .stroke(Stroke::new(1.0_f32, ctx_menu_border(t)))
        .shadow(egui::epaint::Shadow { offset: vec2(0.0, 12.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(61) })
        .inner_margin(Margin::same(8.0))
}

/// Discord's --border-strong (rgba(143,143,153,.44) over dark surfaces).
pub fn ctx_menu_border(t: &Theme) -> Color32 {
    if t.light {
        crate::style::rgba(0, 0, 0, 40)
    } else {
        crate::style::rgba(143, 143, 153, 112)
    }
}

/// Discord's red menu label (Block, Leave, Delete…).
pub const MENU_DANGER: Color32 = Color32::from_rgb(251, 155, 152);

/// One context-menu row as Discord draws it: label in 14/18 medium,
/// text-strong (red for danger); an optional 20 px icon 8 px in on the left
/// (text-subtle, white while hovered) and an optional glyph on the right;
/// 34 px tall, 36 with an icon; hover fill mod 12 % with 4 px corners.
pub fn ctx_row(ui: &mut Ui, t: &Theme, left: Option<&str>, label: &str, right: Option<&str>, danger: bool, enabled: bool) -> Response {
    let h = if left.is_some() || right.is_some() { 36.0 } else { 34.0 };
    let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), dense(h)), if enabled { Sense::click() } else { Sense::hover() });
    let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
    let hovered = enabled && resp.hovered();
    if hovered {
        ui.painter().rect_filled(r, 4.0, if danger { t.danger } else { t.bg_hover });
    }
    let (fg, icon_c) = if !enabled {
        (t.text_muted.gamma_multiply(0.6), t.text_muted.gamma_multiply(0.6))
    } else if danger {
        if hovered { (Color32::WHITE, Color32::WHITE) } else { (MENU_DANGER, MENU_DANGER) }
    } else if hovered {
        (t.header_primary, t.header_primary)
    } else {
        (t.header_primary, t.interactive_normal)
    };
    let mut x = r.left() + 8.0;
    if let Some(g) = left {
        paint_icon(ui.painter(), Rect::from_center_size(pos2(x + 10.0, r.center().y), vec2(20.0, 20.0)), g, icon_c);
        x += 28.0;
    }
    let clip = ui.painter().with_clip_rect(r.with_max_x(r.right() - if right.is_some() { 32.0 } else { 8.0 }).intersect(ui.clip_rect()));
    clip.text(pos2(x, r.center().y), Align2::LEFT_CENTER, label, crate::style::medium(14.0), fg);
    if let Some(g) = right {
        let size = if g == icon::CHEVRON { 12.0 } else { 20.0 };
        paint_icon(ui.painter(), Rect::from_center_size(pos2(r.right() - 18.0, r.center().y), vec2(size, size)), g, icon_c);
    }
    if enabled {
        resp.on_hover_cursor(egui::CursorIcon::PointingHand)
    } else {
        resp
    }
}

/// The line between groups of menu rows: 8 px above and below, 1 px
/// border-subtle.
pub fn ctx_separator(ui: &mut Ui, t: &Theme) {
    ui.add_space(8.0);
    let y = ui.cursor().top() + 0.5;
    let x = ui.max_rect().x_range();
    ui.painter().hline(x, y, Stroke::new(1.0_f32, t.border_subtle));
    ui.add_space(9.0);
}

/// Discord's --border-normal around modals (rgba(143,143,152,.2)).
pub fn modal_border(t: &Theme) -> Color32 {
    if t.light {
        crate::style::rgba(0, 0, 0, 30)
    } else {
        crate::style::rgba(143, 143, 152, 51)
    }
}

/// Discord shows a DM's profile panel only while the window is at least
/// 1132 px wide (`window.innerWidth >= 1132` in its web app).
pub fn dm_profile_fits(ctx: &egui::Context) -> bool {
    ctx.screen_rect().width() >= 1132.0
}

#[cfg(test)]
mod name_gradient_tests {
    #[test]
    fn name_gradient_runs_like_css() {
        use super::to_right_bottom;
        use eframe::egui;
        let size = egui::vec2(139.0, 24.0);
        let near = |a: f32, b: f32| (a - b).abs() < 0.01;
        // Corners: the gradient's ends; the other two corners share its middle.
        assert!(near(to_right_bottom(egui::pos2(0.0, 0.0), size), 0.0));
        assert!(near(to_right_bottom(egui::pos2(139.0, 24.0), size), 1.0));
        assert!(near(to_right_bottom(egui::pos2(139.0, 0.0), size), 0.5));
        assert!(near(to_right_bottom(egui::pos2(0.0, 24.0), size), 0.5));
        // Halfway down a wide name, it runs a quarter to three quarters.
        assert!(near(to_right_bottom(egui::pos2(0.0, 12.0), size), 0.25));
    }
}