Skip to content

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

57.4 KB
Raw Blame
//! The server icon's right-click menu, the actions both server menus share,
//! and the dialogs they open: Notification Settings, Privacy Settings,
//! Security Actions, Report a Raid and Active Threads. Items, order and
//! strings follow Discord's web app (read 2026-11-23).

use crate::app::RustCord;
use crate::store::{GuildNotify, Store};
use crate::style::{bold, icon, Theme};
use discord::model::{channel_kind, permissions, Id};
use discord::settings_proto::GuildMove;
use eframe::egui::{
    self, pos2, vec2, Align, Align2, Color32, FontId, Frame, Key, Layout, Margin, Order, Pos2, Rect, RichText, ScrollArea,
    Sense, Stroke, Ui,
};
use reqwest::Method;
use serde_json::{json, Value};

/// Permission bits the model doesn't name.
const KICK_MEMBERS: u64 = 1 << 1;
const BAN_MEMBERS: u64 = 1 << 2;
const MODERATE_MEMBERS: u64 = 1 << 40;
/// Discord shows Security Actions to these (any of them).
pub(super) const INCIDENT_PERMS: u64 = permissions::ADMINISTRATOR | permissions::MANAGE_GUILD | BAN_MEMBERS | KICK_MEMBERS | MODERATE_MEMBERS;

/// Mute lengths for servers and channels (seconds; -1 = until turned back on).
pub(super) const MUTE_TIMES: [(i64, &str); 6] = [
    (900, "For 15 Minutes"),
    (3600, "For 1 Hour"),
    (10800, "For 3 Hours"),
    (28800, "For 8 Hours"),
    (86400, "For 24 Hours"),
    (-1, "Until I turn it back on"),
];

/// Security Actions' pause lengths (hours).
const PAUSE_HOURS: [u32; 6] = [1, 2, 4, 6, 12, 24];

/// Report a Raid's choices: (Discord's value, label).
const RAID_KINDS: [(&str, &str); 5] = [
    ("MESSAGE_SPAM", "Spamming channels"),
    ("DM_SPAM", "Spamming DMs"),
    ("MENTION_SPAM", "Spamming mentions"),
    ("SUSPICIOUS_USERS", "Nothing yet, but suspicious new members"),
    ("SETTINGS_SPAM", "Changing server and channel settings"),
];

/// Something a server menu row does.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum GuildAct {
    MarkRead,
    Invite,
    /// Mute for this many seconds (-1: until unmuted).
    Mute(i64),
    Unmute,
    Notify(u8),
    SuppressEveryone,
    SuppressRoles,
    Highlights,
    MuteEvents,
    MobilePush,
    HideMuted,
    ShowAllChannels,
    /// Server Settings, on a page (Discord's section key) or its first.
    Settings(Option<&'static str>),
    Insights,
    Privacy,
    Notifications,
    PerServerProfile,
    CreateChannel,
    CreateCategory,
    CreateEvent,
    ActiveThreads,
    AppDirectory,
    Boost,
    SecurityActions,
    ReportRaid,
    Move(GuildMove),
    Leave,
    CopyId,
}

/// A dialog opened from a server menu.
#[derive(Clone)]
pub enum GuildDialog {
    Notifications { guild: Id, override_pick: bool },
    Privacy { guild: Id },
    Security { guild: Id, invites: Option<bool>, dms: Option<bool>, hours: u32 },
    ReportRaid { guild: Id, picked: Vec<&'static str> },
    ActiveThreads { guild: Id },
}

/// A menu row (the server and channel menus share them); submenus open
/// beside their row while hovered. `sub` is a muted second line.
pub(super) enum Row<A = GuildAct> {
    Item { glyph: Option<&'static str>, label: String, sub: Option<String>, act: A, danger: bool, enabled: bool },
    Check { glyph: Option<&'static str>, label: String, on: bool, act: A },
    Radio { label: String, sub: Option<String>, on: bool, act: A },
    Sub { glyph: Option<&'static str>, label: String, sub: Option<String>, rows: Vec<Row<A>> },
    Sep,
}

pub(super) fn item<A>(glyph: Option<&'static str>, label: &str, act: A) -> Row<A> {
    Row::Item { glyph, label: label.into(), sub: None, act, danger: false, enabled: true }
}

/// Server Settings pages for the right-click submenu: (Discord's section
/// key, label, permission that opens it). Server Settings decides the rest.
pub const SETTINGS_PAGES: [(&str, &str); 19] = [
    ("PROFILE", "Server Profile"),
    ("TAG", "Server Tag"),
    ("ENGAGEMENT", "Engagement"),
    ("BOOST_PERKS", "Boost Perks"),
    ("EMOJI", "Emoji"),
    ("STICKERS", "Stickers"),
    ("SOUNDBOARD", "Soundboard"),
    ("MEMBERS", "Members"),
    ("ROLES", "Roles"),
    ("INVITES", "Invites"),
    ("ACCESS", "Access"),
    ("INTEGRATIONS", "Integrations"),
    ("MODERATION", "Safety Setup"),
    ("AUDIT_LOG", "Audit Log"),
    ("BANS", "Bans"),
    ("GUILD_AUTOMOD", "AutoMod"),
    ("COMMUNITY", "Community Settings"),
    ("ANALYTICS", "Server Insights"),
    ("GUILD_TEMPLATES", "Server Template"),
];

impl RustCord {
    /// Right-click on a server icon.
    pub fn open_guild_menu(&mut self, guild: Id, at: Pos2) {
        self.server_menu = None;
        self.channel_menu = None;
        self.dm_menu = None;
        self.guild_menu = Some((guild, at, self.ctx.cumulative_pass_nr()));
        self.ctx.data_mut(|d| d.remove::<Vec<usize>>(sub_path_id()));
    }

    /// Discord's guild context menu (the server icon's right-click menu).
    pub fn guild_menu_ui(&mut self, ctx: &egui::Context) {
        let Some((g, at, opened)) = self.guild_menu else { return };
        if !self.store.guilds.contains_key(&g) {
            self.guild_menu = None;
            return;
        }
        let rows = self.guild_menu_rows(g);
        let t = self.theme.clone();
        let mut picked = None;
        let mut rects = Vec::new();
        draw_menu(ctx, &t, egui::Id::new("guild_menu"), at, &rows, 0, &mut picked, &mut rects);
        let now = ctx.cumulative_pass_nr();
        let outside = now > opened + 1
            && ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !rects.iter().any(|r: &Rect| r.contains(p))));
        if picked.is_some() || outside || ctx.input(|i| i.key_pressed(Key::Escape)) {
            self.guild_menu = None;
        }
        if let Some(act) = picked {
            self.guild_act(g, act);
        }
    }

    /// The right-click menu's rows for `g`, from your permissions and settings.
    fn guild_menu_rows(&self, g: Id) -> Vec<Row> {
        let Some(gs) = self.store.guilds.get(&g) else { return Vec::new() };
        let perms = self.store.guild_perms(g);
        let has = |p: u64| perms & p != 0;
        let owner = gs.guild.owner_id.is_some() && gs.guild.owner_id == self.store.me_id();
        let community = super::guild_pages::has_feature(&gs.guild, "COMMUNITY");
        let n = self.store.guild_notify.get(&g).cloned().unwrap_or_default();
        let level = self.store.notify_level.get(&g).copied().unwrap_or(0);
        let muted = self.store.muted_guilds.contains(&g);
        let mut rows = Vec::new();

        rows.push(Row::Item { glyph: None, label: "Mark as Read".into(), sub: None, act: GuildAct::MarkRead, danger: false, enabled: self.store.guild_unread(g) });
        rows.push(Row::Sep);
        if has(permissions::CREATE_INSTANT_INVITE) {
            rows.push(item(None, "Invite to Server", GuildAct::Invite));
            rows.push(Row::Sep);
        }
        if muted {
            let sub = n.mute_until.as_deref().and_then(mute_until_label);
            rows.push(Row::Item { glyph: None, label: "Unmute Server".into(), sub, act: GuildAct::Unmute, danger: false, enabled: true });
        } else {
            rows.push(Row::Sub { glyph: None, label: "Mute Server".into(), sub: None, rows: MUTE_TIMES.iter().map(|(s, l)| item(None, l, GuildAct::Mute(*s))).collect() });
        }
        rows.push(Row::Sub { glyph: None, label: "Notification Settings".into(), sub: Some(level_label(level).into()), rows: notify_rows(&n, level) });
        rows.push(Row::Check { glyph: None, label: "Hide Muted Channels".into(), on: self.store.hide_muted.contains(&g), act: GuildAct::HideMuted });
        if community {
            rows.push(Row::Check { glyph: None, label: "Show All Channels".into(), on: n.flags & GuildNotify::OPT_IN_CHANNELS_ON == 0, act: GuildAct::ShowAllChannels });
        }
        rows.push(Row::Sep);
        let pages = self.server_settings_pages(g);
        if !pages.is_empty() {
            let sub = SETTINGS_PAGES.iter().filter(|(k, _)| pages.contains(k)).map(|(k, l)| item(None, l, GuildAct::Settings(Some(k)))).collect();
            rows.push(Row::Sub { glyph: None, label: "Server Settings".into(), sub: None, rows: sub });
        }
        rows.push(item(None, "Privacy Settings", GuildAct::Privacy));
        rows.push(item(None, "Edit Per-server Profile", GuildAct::PerServerProfile));
        let can_channels = has(permissions::MANAGE_CHANNELS);
        let can_events = has(super::guild_pages::MANAGE_EVENTS | super::guild_pages::CREATE_EVENTS);
        if can_channels || can_events {
            rows.push(Row::Sep);
            if can_channels {
                rows.push(item(None, "Create Channel", GuildAct::CreateChannel));
                rows.push(item(None, "Create Category", GuildAct::CreateCategory));
            }
            if can_events {
                rows.push(item(None, "Create Event", GuildAct::CreateEvent));
            }
        }
        rows.push(Row::Sep);
        let folders: Vec<Row> = self
            .store
            .folders
            .iter()
            .filter_map(|f| Some((f.id?, f)))
            .filter(|(_, f)| !f.guild_ids.contains(&g))
            .map(|(id, f)| item(None, f.name.as_deref().unwrap_or("Server Folder"), GuildAct::Move(GuildMove::Folder(id))))
            .collect();
        let mut move_rows = Vec::new();
        if !folders.is_empty() {
            move_rows.push(Row::Sub { glyph: None, label: "Folder".into(), sub: None, rows: folders });
            move_rows.push(Row::Sep);
        }
        move_rows.push(item(None, "First in List", GuildAct::Move(GuildMove::First)));
        move_rows.push(item(None, "Last in List", GuildAct::Move(GuildMove::Last)));
        rows.push(Row::Sub { glyph: None, label: "Move to...".into(), sub: None, rows: move_rows });
        if !owner {
            rows.push(Row::Sep);
            rows.push(Row::Item { glyph: None, label: "Leave Server".into(), sub: None, act: GuildAct::Leave, danger: true, enabled: true });
        }
        rows.push(Row::Sep);
        rows.push(item(Some(icon::ID), "Copy Server ID", GuildAct::CopyId));
        rows
    }

    /// Discord's section keys of the Server Settings pages you can open.
    fn server_settings_pages(&self, g: Id) -> Vec<&'static str> {
        SETTINGS_PAGES.iter().map(|(k, _)| *k).filter(|k| self.server_settings_has(g, k)).collect()
    }

    /// Do what a server menu row asked.
    pub fn guild_act(&mut self, g: Id, act: GuildAct) {
        let settings = |app: &mut RustCord, patch: Value| app.backend.send(crate::backend::Command::GuildSettings { guild: g, patch });
        let notify = self.store.guild_notify.get(&g).cloned().unwrap_or_default();
        match act {
            GuildAct::MarkRead => self.mark_guild_read(g),
            GuildAct::Invite => {
                let ch = self
                    .current_channel
                    .filter(|c| self.store.channels.get(c).is_some_and(|c| c.guild_id == Some(g)))
                    .or_else(|| self.store.first_text_channel(Some(g)));
                if let Some(ch) = ch {
                    self.open_invite(ch);
                }
            }
            GuildAct::Mute(secs) => {
                self.store.muted_guilds.insert(g);
                let end = (secs > 0).then(|| (chrono::Utc::now() + chrono::Duration::seconds(secs)).to_rfc3339_opts(chrono::SecondsFormat::Millis, true));
                if let Some(n) = self.store.guild_notify.get_mut(&g) {
                    n.mute_until = end.clone();
                }
                settings(self, json!({ "muted": true, "mute_config": { "selected_time_window": secs, "end_time": end } }));
            }
            GuildAct::Unmute => {
                self.store.muted_guilds.remove(&g);
                settings(self, json!({ "muted": false }));
            }
            GuildAct::Notify(n) => {
                self.store.notify_level.insert(g, n);
                settings(self, json!({ "message_notifications": n }));
            }
            GuildAct::SuppressEveryone => {
                self.store.guild_notify.entry(g).or_default().suppress_everyone = !notify.suppress_everyone;
                settings(self, json!({ "suppress_everyone": !notify.suppress_everyone }));
            }
            GuildAct::SuppressRoles => {
                self.store.guild_notify.entry(g).or_default().suppress_roles = !notify.suppress_roles;
                settings(self, json!({ "suppress_roles": !notify.suppress_roles }));
            }
            GuildAct::Highlights => {
                // Discord: suppressing sets 1 (off), un-suppressing 2 (on).
                let v = if notify.highlights == 1 { 2 } else { 1 };
                self.store.guild_notify.entry(g).or_default().highlights = v;
                settings(self, json!({ "notify_highlights": v }));
            }
            GuildAct::MuteEvents => {
                self.store.guild_notify.entry(g).or_default().mute_events = !notify.mute_events;
                settings(self, json!({ "mute_scheduled_events": !notify.mute_events }));
            }
            GuildAct::MobilePush => {
                self.store.guild_notify.entry(g).or_default().mobile_push = !notify.mobile_push;
                settings(self, json!({ "mobile_push": !notify.mobile_push }));
            }
            GuildAct::HideMuted => {
                let on = !self.store.hide_muted.contains(&g);
                if on {
                    self.store.hide_muted.insert(g);
                } else {
                    self.store.hide_muted.remove(&g);
                }
                settings(self, json!({ "hide_muted_channels": on }));
            }
            GuildAct::ShowAllChannels => self.toggle_show_all_channels(g),
            GuildAct::Settings(page) => match page {
                Some(k) => self.open_server_settings_at(g, k),
                None => self.open_server_settings(g),
            },
            GuildAct::Insights => self.open_server_settings_at(g, "ANALYTICS"),
            GuildAct::Privacy => {
                self.api_get_once("us:settings", "/users/@me/settings");
                self.guild_dialog = Some(GuildDialog::Privacy { guild: g });
            }
            GuildAct::Notifications => self.guild_dialog = Some(GuildDialog::Notifications { guild: g, override_pick: false }),
            GuildAct::PerServerProfile => self.open_per_server_profile(g),
            GuildAct::CreateChannel | GuildAct::CreateCategory => {
                self.server_dialog = Some(crate::features::ServerDialog::CreateChannel {
                    guild: g,
                    parent: None,
                    name: String::new(),
                    kind: 0,
                    private: false,
                    category: act == GuildAct::CreateCategory,
                })
            }
            GuildAct::CreateEvent => self.open_events(g, true),
            GuildAct::ActiveThreads => self.guild_dialog = Some(GuildDialog::ActiveThreads { guild: g }),
            GuildAct::AppDirectory => self.open_app_directory(Some(g)),
            GuildAct::Boost => self.open_guild_page(g, super::guild_pages::GuildPage::Boosts),
            GuildAct::SecurityActions => {
                self.api(&tag_guild(g), Method::GET, format!("/guilds/{g}"), None);
                self.guild_dialog = Some(GuildDialog::Security { guild: g, invites: None, dms: None, hours: 2 });
            }
            GuildAct::ReportRaid => {
                self.api_get_once(&tag_guild(g), format!("/guilds/{g}"));
                self.guild_dialog = Some(GuildDialog::ReportRaid { guild: g, picked: Vec::new() });
            }
            GuildAct::Move(to) => self.move_guild(g, to),
            GuildAct::Leave => self.server_dialog = Some(crate::features::ServerDialog::LeaveServer { guild: g }),
            GuildAct::CopyId => {
                self.ctx.copy_text(g.to_string());
                self.toast("Server ID copied.", false);
            }
        }
    }

    /// Move a server in your server list ("Move to…", or dragged on the rail) and save the
    /// list to your account, as Discord does.
    pub fn move_guild(&mut self, g: Id, to: discord::settings_proto::GuildMove) {
        match self.account_proto.move_guild(g, to) {
            Ok(Some(patch)) => {
                self.store.folders = self.account_proto.folders();
                self.api("gm:move", Method::PATCH, "/users/@me/settings-proto/1", Some(json!({ "settings": patch })));
            }
            Ok(None) => {}
            Err(_) => self.toast("Couldn't read your server list to move this server.", true),
        }
    }

    /// Move a server folder in your server list (dragged on the rail) and save the list.
    pub fn move_folder(&mut self, folder: u64, to: GuildMove) {
        match self.account_proto.move_folder(folder, to) {
            Ok(Some(patch)) => {
                self.store.folders = self.account_proto.folders();
                self.api("gm:move", Method::PATCH, "/users/@me/settings-proto/1", Some(json!({ "settings": patch })));
            }
            Ok(None) => {}
            Err(_) => self.toast("Couldn't read your server list to move this folder.", true),
        }
    }

    /// "Mark as Read": every unread channel and thread of the server, in one
    /// bulk ack like Discord's.
    pub fn mark_guild_read(&mut self, g: Id) {
        let ids: Vec<Id> = self
            .store
            .channels
            .values()
            .filter(|c| c.guild_id == Some(g) && (self.store.is_unread(c.id) || self.store.mentions(c.id) > 0))
            .map(|c| c.id)
            .collect();
        let mut states = Vec::new();
        for ch in ids {
            self.unread_marker.remove(&ch);
            if let Some(msg) = self.store.mark_read(ch) {
                states.push(json!({ "channel_id": ch.to_string(), "message_id": msg.to_string(), "read_state_type": 0 }));
            }
        }
        if self.new_since.is_some_and(|n| self.store.channels.get(&n.channel).is_some_and(|c| c.guild_id == Some(g))) {
            self.new_since = None;
        }
        // Discord's client sends at most 100 per request.
        for chunk in states.chunks(100) {
            self.api("gm:ack", Method::POST, "/read-states/ack-bulk", Some(json!({ "read_states": chunk })));
        }
    }

    /// "Show All Channels" (Community servers): switch between every channel
    /// and only the ones you picked. Like Discord, switching it off the first
    /// time picks every channel you can see, so nothing disappears.
    fn toggle_show_all_channels(&mut self, g: Id) {
        let n = self.store.guild_notify.get(&g).cloned().unwrap_or_default();
        let opt_in = n.flags & GuildNotify::OPT_IN_CHANNELS_ON != 0;
        let flags = n.flags ^ GuildNotify::OPT_IN_CHANNELS_ON;
        let mut patch = json!({ "flags": flags });
        let picked_any = self.store.guilds.get(&g).is_some_and(|gs| {
            gs.channels.iter().any(|c| self.store.channel_flags.get(c).is_some_and(|f| f & GuildNotify::CHANNEL_OPT_IN != 0))
        });
        if !opt_in && !picked_any {
            let mut overrides = serde_json::Map::new();
            let visible: Vec<Id> = self
                .store
                .guilds
                .get(&g)
                .map(|gs| {
                    gs.channels
                        .iter()
                        .filter_map(|c| self.store.channels.get(c))
                        .filter(|c| c.kind != channel_kind::GUILD_CATEGORY && channel_kind::is_listed(c.kind) && self.store.can_view(c))
                        .map(|c| c.id)
                        .collect()
                })
                .unwrap_or_default();
            for c in visible {
                let f = self.store.channel_flags.get(&c).copied().unwrap_or(0) | GuildNotify::CHANNEL_OPT_IN;
                self.store.channel_flags.insert(c, f);
                overrides.insert(c.to_string(), json!({ "flags": f }));
            }
            patch["channel_overrides"] = Value::Object(overrides);
        }
        self.store.guild_notify.entry(g).or_default().flags = flags;
        self.backend.send(crate::backend::Command::GuildSettings { guild: g, patch });
    }

    /// "Edit Per-server Profile": your nickname in this server (Discord opens
    /// the per-server profile editor; RustCord's covers the nickname).
    fn open_per_server_profile(&mut self, g: Id) {
        let nick = self.store.me_id().and_then(|me| self.store.members.get(&(g, me))).and_then(|m| m.nick.clone()).unwrap_or_default();
        if let Some(me) = self.store.me_id() {
            self.want_profile(me, Some(g));
        }
        self.server_dialog = Some(crate::features::ServerDialog::Nickname { guild: g, nick, pronouns: None, bio: None });
    }

    /// The dialogs opened from the server menus (called every frame).
    pub fn guild_dialog_ui(&mut self, ctx: &egui::Context) {
        self.guild_menu_ui(ctx);
        self.channel_menu_ui(ctx);
        for tag in ["gm:move", "gm:ack", "gm:privacy", "gm:raid", "gm:incident", "pp:save"] {
            match self.api_take(tag) {
                Some(Err(e)) => self.toast(format!("{}: {e}", failure(tag)), true),
                Some(Ok(v)) if tag == "gm:incident" => {
                    if let Some(Ok(gv)) = self.guild_dialog_guild().map(tag_guild).and_then(|t| self.api_results.get_mut(&t)) {
                        gv["incidents_data"] = v;
                    }
                }
                Some(Ok(_)) if tag == "gm:raid" => self.toast("Raid report submitted", false),
                Some(Ok(_)) if tag == "pp:save" => self.toast("Server profile saved.", false),
                _ => {}
            }
        }
        let Some(mut d) = self.guild_dialog.take() else { return };
        if !self.store.guilds.contains_key(&dialog_guild(&d)) {
            return;
        }
        let close = match &mut d {
            GuildDialog::Notifications { guild, override_pick } => self.notifications_dialog(ctx, *guild, override_pick),
            GuildDialog::Privacy { guild } => self.privacy_dialog(ctx, *guild),
            GuildDialog::Security { guild, invites, dms, hours } => self.security_dialog(ctx, *guild, invites, dms, hours),
            GuildDialog::ReportRaid { guild, picked } => self.raid_dialog(ctx, *guild, picked),
            GuildDialog::ActiveThreads { guild } => self.threads_dialog(ctx, *guild),
        };
        if !close && self.guild_dialog.is_none() {
            self.guild_dialog = Some(d);
        }
    }

    fn guild_dialog_guild(&self) -> Option<Id> {
        self.guild_dialog.as_ref().map(dialog_guild)
    }

    // ---- Notification Settings -----------------------------------------------------

    fn notifications_dialog(&mut self, ctx: &egui::Context, g: Id, override_pick: &mut bool) -> bool {
        let t = self.theme.clone();
        let name = self.store.guilds.get(&g).map(|gs| gs.guild.name.clone()).unwrap_or_default();
        let n = self.store.guild_notify.get(&g).cloned().unwrap_or_default();
        let level = self.store.notify_level.get(&g).copied().unwrap_or(0);
        let muted = self.store.muted_guilds.contains(&g);
        let overrides: Vec<(Id, String, Option<u8>, bool)> = self.notify_overrides(g);
        let pickable: Vec<(Id, String)> = if *override_pick { self.override_candidates(g, &overrides) } else { Vec::new() };
        let mut acts: Vec<GuildAct> = Vec::new();
        let mut channel_patch: Option<(Id, Value)> = None;
        let mut done = false;
        let out = dialog(ctx, &t, "Notification Settings", Some(&name), 560.0, |ui| {
            ScrollArea::vertical().max_height(ui.ctx().screen_rect().height() * 0.6).auto_shrink([false, true]).show(ui, |ui| {
                let label = format!("Mute {name}");
                if switch(ui, &t, &label, Some("Muting a server prevents unread indicators and notifications from appearing unless you are mentioned."), muted) {
                    acts.push(if muted { GuildAct::Unmute } else { GuildAct::Mute(-1) });
                }
                if muted {
                    ui.add_space(8.0);
                    ui.label(bold("Mute duration").size(14.0).color(t.header_primary));
                    ui.add_space(4.0);
                    let current = n.mute_until.as_deref().and_then(mute_until_label).unwrap_or_else(|| "Until I turn it back on".into());
                    egui::ComboBox::from_id_salt("gm_mute_duration").width(ui.available_width()).selected_text(current).show_ui(ui, |ui| {
                        for (secs, label) in MUTE_TIMES {
                            if ui.selectable_label(false, label).clicked() {
                                acts.push(GuildAct::Mute(secs));
                            }
                        }
                    });
                }
                sep(ui, &t);
                ui.label(bold("Server Notification Settings").size(16.0).color(t.header_primary));
                ui.add_space(8.0);
                for (v, label) in [(0u8, "All Messages"), (1, "Only @mentions"), (2, "Nothing")] {
                    if radio_row(ui, &t, label, level == v) {
                        acts.push(GuildAct::Notify(v));
                    }
                }
                sep(ui, &t);
                for (label, desc, on, act) in [
                    ("Suppress @everyone and @here", None, n.suppress_everyone, GuildAct::SuppressEveryone),
                    ("Suppress All Role @mentions", None, n.suppress_roles, GuildAct::SuppressRoles),
                    (
                        "Suppress Highlights",
                        Some("Highlights provide occasional updates when your friends are chatting in busy servers and more."),
                        n.highlights == 1,
                        GuildAct::Highlights,
                    ),
                    ("Mute New Events", None, n.mute_events, GuildAct::MuteEvents),
                    ("Mobile Push Notifications", None, n.mobile_push, GuildAct::MobilePush),
                ] {
                    if switch(ui, &t, label, desc, on) {
                        acts.push(act);
                    }
                    ui.add_space(6.0);
                }
                sep(ui, &t);
                ui.label(bold("Notification Overrides").size(16.0).color(t.header_primary));
                ui.add_space(4.0);
                ui.label(RichText::new("Add a channel to override its default notification settings").size(13.0).color(t.text_muted));
                ui.add_space(8.0);
                if *override_pick {
                    egui::ComboBox::from_id_salt("gm_override_pick").width(ui.available_width()).selected_text("Select a channel or category…").show_ui(ui, |ui| {
                        for (id, label) in &pickable {
                            if ui.selectable_label(false, label).clicked() {
                                channel_patch = Some((*id, json!({ "message_notifications": level })));
                                *override_pick = false;
                            }
                        }
                    });
                } else if ui.button("Select a channel or category…").on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                    *override_pick = true;
                }
                if !overrides.is_empty() {
                    ui.add_space(10.0);
                    egui::Grid::new("gm_overrides").num_columns(6).spacing(vec2(14.0, 8.0)).show(ui, |ui| {
                        for h in ["Channel or Category", "All", "Mentions", "Nothing", "Mute", ""] {
                            ui.label(bold(h).size(12.0).color(t.text_muted));
                        }
                        ui.end_row();
                        for (id, label, lvl, ch_muted) in &overrides {
                            ui.label(RichText::new(label).size(14.0).color(t.header_primary));
                            for v in 0..3u8 {
                                if radio_dot(ui, &t, *lvl == Some(v)) {
                                    channel_patch = Some((*id, json!({ "message_notifications": v })));
                                }
                            }
                            if check_box(ui, &t, *ch_muted) {
                                channel_patch = Some((*id, json!({ "muted": !ch_muted })));
                            }
                            let x = ui.add(egui::Button::new(RichText::new(icon::CLOSE).font(crate::style::icon_font(11.0)).color(t.interactive_normal)).frame(false));
                            if x.on_hover_text(format!("Remove notification override for {label}")).clicked() {
                                // Discord: back to the server default, not muted.
                                channel_patch = Some((*id, json!({ "message_notifications": 3, "muted": false })));
                            }
                            ui.end_row();
                        }
                    });
                }
            });
            ui.add_space(16.0);
            footer(ui, |ui| {
                done |= primary(ui, &t, "Done").clicked();
            });
        });
        for a in acts {
            self.guild_act(g, a);
        }
        if let Some((ch, v)) = channel_patch {
            self.set_channel_override(g, ch, v);
        }
        done || out
    }

    /// Channels with their own notification settings: (id, label, level, muted).
    fn notify_overrides(&self, g: Id) -> Vec<(Id, String, Option<u8>, bool)> {
        let Some(gs) = self.store.guilds.get(&g) else { return Vec::new() };
        let mut v: Vec<(Id, String, Option<u8>, bool)> = gs
            .channels
            .iter()
            .filter(|c| self.store.channel_notify.contains_key(c) || self.store.muted_channels.contains(c))
            .filter_map(|c| self.store.channels.get(c))
            .map(|c| (c.id, override_label(c), self.store.channel_notify.get(&c.id).copied(), self.store.muted_channels.contains(&c.id)))
            .collect();
        v.sort_by(|a, b| a.1.cmp(&b.1));
        v
    }

    /// Channels and categories that could get an override.
    fn override_candidates(&self, g: Id, have: &[(Id, String, Option<u8>, bool)]) -> Vec<(Id, String)> {
        let Some(gs) = self.store.guilds.get(&g) else { return Vec::new() };
        let mut v: Vec<(Id, String)> = gs
            .channels
            .iter()
            .filter(|c| !have.iter().any(|h| h.0 == **c))
            .filter_map(|c| self.store.channels.get(c))
            .filter(|c| channel_kind::is_listed(c.kind) && self.store.can_view(c))
            .map(|c| (c.id, override_label(c)))
            .collect();
        v.sort_by(|a, b| a.1.cmp(&b.1));
        v
    }

    /// Change one channel's notification override (here and on Discord).
    fn set_channel_override(&mut self, g: Id, ch: Id, v: Value) {
        if let Some(m) = v["muted"].as_bool() {
            if m {
                self.store.muted_channels.insert(ch);
            } else {
                self.store.muted_channels.remove(&ch);
            }
        }
        match v["message_notifications"].as_u64() {
            Some(n @ 0..=2) => {
                self.store.channel_notify.insert(ch, n as u8);
            }
            Some(_) => {
                self.store.channel_notify.remove(&ch);
            }
            None => {}
        }
        let patch = json!({ "channel_overrides": { ch.to_string(): v } });
        self.backend.send(crate::backend::Command::GuildSettings { guild: g, patch });
    }

    // ---- Privacy Settings ----------------------------------------------------------

    fn privacy_dialog(&mut self, ctx: &egui::Context, g: Id) -> bool {
        let t = self.theme.clone();
        let name = self.store.guilds.get(&g).map(|gs| gs.guild.name.clone()).unwrap_or_default();
        let settings = match self.api_result("us:settings") {
            Some(Ok(v)) => Some(v.clone()),
            _ => None,
        };
        let in_list = |key: &str| settings.as_ref().is_some_and(|s| s[key].as_array().is_some_and(|a| a.iter().any(|v| Id::from_value(v) == Some(g))));
        let mut flip: Option<&'static str> = None;
        let mut done = false;
        let out = dialog(ctx, &t, &format!("Privacy Settings\u{2014}{name}"), None, 440.0, |ui| {
            let Some(_) = &settings else {
                ui.spinner();
                return;
            };
            for (key, title, desc) in [
                ("restricted_guilds", "Direct Messages", "Allow DMs from other members in this server"),
                ("message_request_restricted_guild_ids", "Message requests", "Filter messages from server members you may not know."),
                ("activity_restricted_guild_ids", "Share my activity", "Share activity information from games and connected apps I use, including when and how I engage."),
                ("activity_joining_restricted_guild_ids", "Activity joining", "Allow users to join your activity in this server."),
            ] {
                // Message requests is on while the server is NOT in its list; the rest likewise.
                if switch(ui, &t, title, Some(desc), !in_list(key)) {
                    flip = Some(key);
                }
                ui.add_space(10.0);
            }
            ui.label(RichText::new("Learn about enhanced safety measures in Community Servers here.").size(13.0).color(t.text_muted));
            ui.add_space(16.0);
            footer(ui, |ui| {
                done |= primary(ui, &t, "Done").clicked();
            });
        });
        if let (Some(key), Some(mut s)) = (flip, settings) {
            let mut list: Vec<Value> = s[key].as_array().cloned().unwrap_or_default();
            if list.iter().any(|v| Id::from_value(v) == Some(g)) {
                list.retain(|v| Id::from_value(v) != Some(g));
            } else {
                list.push(json!(g.to_string()));
            }
            s[key] = Value::Array(list.clone());
            self.api_results.insert("us:settings".into(), Ok(s));
            self.api("gm:privacy", Method::PATCH, "/users/@me/settings", Some(json!({ key: list })));
        }
        done || out
    }

    // ---- Security Actions ------------------------------------------------------------

    fn security_dialog(&mut self, ctx: &egui::Context, g: Id, invites: &mut Option<bool>, dms: &mut Option<bool>, hours: &mut u32) -> bool {
        let t = self.theme.clone();
        let incident = match self.api_result(&tag_guild(g)) {
            Some(Ok(v)) => Some(v["incidents_data"].clone()),
            _ => None,
        };
        let paused = |key: &str| incident.as_ref().and_then(|i| i[key].as_str()).and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()).is_some_and(|d| d > chrono::Utc::now());
        let invites_disabled = self.store.guilds.get(&g).is_some_and(|gs| super::guild_pages::has_feature(&gs.guild, "INVITES_DISABLED"));
        let (inv_now, dm_now) = (paused("invites_disabled_until") || invites_disabled, paused("dms_disabled_until"));
        if incident.is_some() {
            invites.get_or_insert(inv_now);
            dms.get_or_insert(dm_now);
        }
        let mut save = false;
        let mut cancel = false;
        let out = dialog(ctx, &t, "Security Actions", None, 440.0, |ui| {
            let (Some(inv), Some(dm)) = (invites.as_mut(), dms.as_mut()) else {
                ui.spinner();
                return;
            };
            egui::ComboBox::from_id_salt("gm_pause_hours").width(ui.available_width()).selected_text(hours_label(*hours)).show_ui(ui, |ui| {
                for h in PAUSE_HOURS {
                    ui.selectable_value(hours, h, hours_label(h));
                }
            });
            ui.add_space(14.0);
            if invites_disabled {
                ui.label(RichText::new("Invites to this server are currently permanently disabled.").size(13.0).color(t.text_muted));
            }
            if switch(ui, &t, "Pause Invites", Some("Temporarily stop new members from joining this server via invite or vanity links."), *inv) {
                *inv = !*inv;
            }
            ui.add_space(10.0);
            if switch(
                ui,
                &t,
                "Pause DMs",
                Some("Temporarily stop new direct messages from being sent between members in your server. Friends can still DM each other, moderators can still DM members and your Apps can still DM members."),
                *dm,
            ) {
                *dm = !*dm;
            }
            ui.add_space(18.0);
            footer(ui, |ui| {
                save = primary(ui, &t, "Save").clicked();
                cancel = secondary(ui, &t, "Cancel").clicked();
            });
        });
        if save {
            let (inv, dm) = (invites.unwrap_or(false), dms.unwrap_or(false));
            let on = inv || dm;
            let until = on.then(|| (chrono::Utc::now() + chrono::Duration::hours(i64::from(*hours))).to_rfc3339_opts(chrono::SecondsFormat::Millis, true));
            let body = json!({
                "invites_disabled_until": if inv { until.clone() } else { None },
                "dms_disabled_until": if dm { until.clone() } else { None },
                "lockdown_duration_hours": if on { Some(*hours) } else { None },
            });
            self.api("gm:incident", Method::PUT, format!("/guilds/{g}/incident-actions"), Some(body));
        }
        save || cancel || out
    }

    // ---- Report a Raid ----------------------------------------------------------------

    fn raid_dialog(&mut self, ctx: &egui::Context, g: Id, picked: &mut Vec<&'static str>) -> bool {
        let t = self.theme.clone();
        let mut submit = false;
        let mut cancel = false;
        let out = dialog(
            ctx,
            &t,
            "Report a Raid",
            Some("Which behaviour best describes how this raid is currently disrupting your server?"),
            440.0,
            |ui| {
                for (value, label) in RAID_KINDS {
                    let on = picked.contains(&value);
                    let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 40.0), Sense::click());
                    if resp.hovered() {
                        ui.painter().rect_filled(r, 6.0, t.bg_hover);
                    }
                    paint_check(ui, &t, Rect::from_center_size(pos2(r.left() + 16.0, r.center().y), vec2(20.0, 20.0)), on);
                    ui.painter().text(pos2(r.left() + 36.0, r.center().y), Align2::LEFT_CENTER, label, FontId::proportional(15.0), t.header_primary);
                    if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                        if on {
                            picked.retain(|v| *v != value);
                        } else {
                            picked.push(value);
                        }
                    }
                }
                ui.add_space(18.0);
                footer(ui, |ui| {
                    submit = primary(ui, &t, "Submit").clicked();
                    cancel = secondary(ui, &t, "Cancel").clicked();
                });
            },
        );
        if submit {
            // Discord only files the report when the server has a channel for
            // safety alerts (or community updates) to post it in.
            let has_channel = match self.api_result(&tag_guild(g)) {
                Some(Ok(v)) => v["safety_alerts_channel_id"].is_string() || v["public_updates_channel_id"].is_string(),
                _ => true,
            };
            if has_channel {
                self.api("gm:raid", Method::POST, format!("/guilds/{g}/auto-moderation/report-raid"), None);
            } else {
                self.toast("Raid report submitted", false);
            }
        }
        submit || cancel || out
    }

    // ---- Active Threads ---------------------------------------------------------------

    fn threads_dialog(&mut self, ctx: &egui::Context, g: Id) -> bool {
        let t = self.theme.clone();
        // Active threads the gateway told RustCord about, newest first, by channel.
        let mut threads: Vec<(String, Id, String, u32)> = self
            .store
            .channels
            .values()
            .filter(|c| c.guild_id == Some(g) && channel_kind::is_thread(c.kind) && !c.archived())
            .filter(|c| c.parent_id.and_then(|p| self.store.channels.get(&p)).is_some_and(|p| self.store.can_view(p)))
            .map(|c| {
                let parent = c.parent_id.and_then(|p| self.store.channels.get(&p)).map(Store::channel_label).unwrap_or_default();
                (parent, c.id, Store::channel_label(c), c.message_count.unwrap_or(0))
            })
            .collect();
        threads.sort_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1)));
        let mut open: Option<Id> = None;
        let out = dialog(ctx, &t, "Active Threads", None, 520.0, |ui| {
            if threads.is_empty() {
                ui.label(RichText::new("There are no active threads.").color(t.text_muted));
                return;
            }
            ScrollArea::vertical().max_height(ui.ctx().screen_rect().height() * 0.6).show(ui, |ui| {
                let mut last = String::new();
                for (parent, id, name, count) in &threads {
                    if *parent != last {
                        ui.add_space(8.0);
                        ui.label(bold(format!("# {parent}").to_uppercase()).size(12.0).color(t.text_muted));
                        ui.add_space(4.0);
                        last = parent.clone();
                    }
                    let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::click());
                    ui.painter().rect_filled(r, 8.0, if resp.hovered() { t.bg_hover } else { t.bg_secondary });
                    super::paint_icon(ui.painter(), Rect::from_center_size(pos2(r.left() + 20.0, r.center().y), vec2(18.0, 18.0)), icon::THREAD, t.interactive_normal);
                    ui.painter().text(pos2(r.left() + 40.0, r.center().y), Align2::LEFT_CENTER, name, crate::style::medium(15.0), t.header_primary);
                    let msgs = if *count == 1 { "1 Message".to_string() } else { format!("{count} Messages") };
                    ui.painter().text(pos2(r.right() - 12.0, r.center().y), Align2::RIGHT_CENTER, msgs, FontId::proportional(13.0), t.text_muted);
                    if resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                        open = Some(*id);
                    }
                    ui.add_space(6.0);
                }
            });
        });
        if let Some(id) = open {
            self.select_channel(Some(id));
            return true;
        }
        out
    }
}

// ---- drawing ---------------------------------------------------------------------------

pub(super) fn sub_path_id() -> egui::Id {
    egui::Id::new("guild_menu_sub_path")
}

fn tag_guild(g: Id) -> String {
    format!("gm:guild:{g}")
}

fn dialog_guild(d: &GuildDialog) -> Id {
    match d {
        GuildDialog::Notifications { guild, .. }
        | GuildDialog::Privacy { guild }
        | GuildDialog::Security { guild, .. }
        | GuildDialog::ReportRaid { guild, .. }
        | GuildDialog::ActiveThreads { guild } => *guild,
    }
}

fn failure(tag: &str) -> &'static str {
    match tag {
        "gm:move" => "Couldn't save your server list",
        "gm:ack" => "Couldn't mark the server as read",
        "gm:privacy" => "Couldn't save the privacy setting",
        "gm:raid" => "Couldn't report the raid",
        "pp:save" => "Couldn't save your server profile",
        _ => "Couldn't save the security actions",
    }
}

pub(super) fn level_label(level: u8) -> &'static str {
    match level {
        1 => "Only @mentions",
        2 => "Nothing",
        _ => "All Messages",
    }
}

fn hours_label(h: u32) -> String {
    if h == 1 {
        "1 hour".into()
    } else {
        format!("{h} hours")
    }
}

/// "Muted until 21:30" (today) or "Muted until 24/11/2026, 21:30".
pub(super) fn mute_until_label(end: &str) -> Option<String> {
    let end = chrono::DateTime::parse_from_rfc3339(end).ok()?.with_timezone(&chrono::Local);
    let when = if end.date_naive() == chrono::Local::now().date_naive() { end.format("%H:%M").to_string() } else { end.format("%d/%m/%Y, %H:%M").to_string() };
    Some(format!("Muted until {when}"))
}

/// A channel as the override list names it: "#name" or "CATEGORY".
fn override_label(c: &discord::model::Channel) -> String {
    let name = Store::channel_label(c);
    if c.kind == channel_kind::GUILD_CATEGORY {
        name.to_uppercase()
    } else {
        format!("# {name}")
    }
}

/// The right-click menu's Notification Settings submenu.
fn notify_rows(n: &GuildNotify, level: u8) -> Vec<Row> {
    let mut rows: Vec<Row> = [(0u8, "All Messages"), (1, "Only @mentions"), (2, "Nothing")]
        .iter()
        .map(|(v, l)| Row::Radio { label: (*l).into(), sub: None, on: level == *v, act: GuildAct::Notify(*v) })
        .collect();
    rows.push(Row::Sep);
    rows.push(Row::Check { glyph: None, label: "Suppress @everyone and @here".into(), on: n.suppress_everyone, act: GuildAct::SuppressEveryone });
    rows.push(Row::Check { glyph: None, label: "Suppress All Role @mentions".into(), on: n.suppress_roles, act: GuildAct::SuppressRoles });
    rows.push(Row::Check { glyph: None, label: "Suppress Highlights".into(), on: n.highlights == 1, act: GuildAct::Highlights });
    rows.push(Row::Check { glyph: None, label: "Mute New Events".into(), on: n.mute_events, act: GuildAct::MuteEvents });
    rows.push(Row::Sep);
    rows.push(Row::Check { glyph: None, label: "Mobile Push Notifications".into(), on: n.mobile_push, act: GuildAct::MobilePush });
    rows
}

/// Draw a menu (and, recursively, the submenu that's open) at `at`.
/// `level` is its depth; `rects` collects every menu's rect so a click
/// outside all of them closes the menu.
#[allow(clippy::too_many_arguments)]
pub(super) fn draw_menu<A: Copy>(ctx: &egui::Context, t: &Theme, id: egui::Id, at: Pos2, rows: &[Row<A>], level: usize, picked: &mut Option<A>, rects: &mut Vec<Rect>) {
    let mut path: Vec<usize> = ctx.data(|d| d.get_temp(sub_path_id())).unwrap_or_default();
    let mut open_sub: Option<(usize, Rect)> = None;
    let mut hovered_row: Option<usize> = None;
    let width = menu_width(ctx, rows);
    let area = egui::Area::new(id).order(Order::Foreground).fixed_pos(at).constrain(true).show(ctx, |ui| {
        super::ctx_menu_frame(t).show(ui, |ui| {
            ui.spacing_mut().item_spacing.y = 0.0;
            ui.set_width(width);
            for (i, row) in rows.iter().enumerate() {
                match row {
                    Row::Sep => super::ctx_separator(ui, t),
                    Row::Item { glyph, label, sub, act, danger, enabled } => {
                        let resp = match sub {
                            Some(s) => sub_row(ui, t, *glyph, label, s, None, *enabled),
                            None => super::ctx_row(ui, t, *glyph, label, None, *danger, *enabled),
                        };
                        if resp.hovered() {
                            hovered_row = Some(i);
                        }
                        if resp.clicked() {
                            *picked = Some(*act);
                        }
                    }
                    Row::Check { glyph, label, on, act } => {
                        let resp = super::ctx_row(ui, t, *glyph, label, None, false, true);
                        paint_check(ui, t, Rect::from_center_size(pos2(resp.rect.right() - 18.0, resp.rect.center().y), vec2(18.0, 18.0)), *on);
                        if resp.hovered() {
                            hovered_row = Some(i);
                        }
                        if resp.clicked() {
                            *picked = Some(*act);
                        }
                    }
                    Row::Radio { label, sub, on, act } => {
                        let resp = match sub {
                            Some(s) => sub_row(ui, t, None, label, s, None, true),
                            None => super::ctx_row(ui, t, None, label, None, false, true),
                        };
                        paint_radio(ui, t, pos2(resp.rect.right() - 18.0, resp.rect.center().y), *on);
                        if resp.hovered() {
                            hovered_row = Some(i);
                        }
                        if resp.clicked() {
                            *picked = Some(*act);
                        }
                    }
                    Row::Sub { glyph, label, sub, .. } => {
                        let resp = match sub {
                            Some(s) => sub_row(ui, t, *glyph, label, s, Some(icon::CHEVRON), true),
                            None => super::ctx_row(ui, t, *glyph, label, Some(icon::CHEVRON), false, true),
                        };
                        if resp.hovered() {
                            hovered_row = Some(i);
                        }
                        if path.get(level) == Some(&i) {
                            ui.painter().rect_filled(resp.rect, 4.0, t.bg_hover.gamma_multiply(0.6));
                            open_sub = Some((i, resp.rect));
                        }
                    }
                }
            }
        });
    });
    rects.push(area.response.rect);
    // Hovering a row opens its submenu (or closes a deeper one).
    if let Some(i) = hovered_row {
        let is_sub = matches!(rows.get(i), Some(Row::Sub { .. }));
        if path.get(level) != Some(&i) || !is_sub {
            path.truncate(level);
            if is_sub {
                path.push(i);
            }
            ctx.data_mut(|d| d.insert_temp(sub_path_id(), path.clone()));
            ctx.request_repaint();
        }
    }
    if let Some((i, row_rect)) = open_sub {
        if let Some(Row::Sub { rows: sub, .. }) = rows.get(i) {
            // Beside the row, flipped to the left when there's no room.
            let screen = ctx.screen_rect();
            let w = menu_width(ctx, sub) + 16.0;
            let x = if row_rect.right() + 12.0 + w < screen.right() { row_rect.right() + 12.0 } else { row_rect.left() - 12.0 - w };
            draw_menu(ctx, t, id.with(("sub", level, i)), pos2(x, row_rect.top() - 8.0), sub, level + 1, picked, rects);
        }
    }
}

/// Like Discord's menus: as wide as the longest row (188-320 px), counting
/// its icon and the checkbox, radio or arrow on the right.
fn menu_width<A>(ctx: &egui::Context, rows: &[Row<A>]) -> f32 {
    let text = |label: &str| ctx.fonts(|f| f.layout_no_wrap(label.to_string(), crate::style::medium(14.0), Color32::WHITE).size().x);
    let widest = rows
        .iter()
        .map(|r| match r {
            Row::Item { glyph, label, .. } => text(label) + if glyph.is_some() { 28.0 } else { 0.0 },
            Row::Check { glyph, label, .. } => text(label) + 36.0 + if glyph.is_some() { 28.0 } else { 0.0 },
            Row::Radio { label, .. } => text(label) + 36.0,
            Row::Sub { glyph, label, .. } => text(label) + 32.0 + if glyph.is_some() { 28.0 } else { 0.0 },
            Row::Sep => 0.0,
        })
        .fold(0.0, f32::max);
    (widest + 24.0).clamp(188.0, 320.0)
}

/// A two-line menu row: label with a muted line under it ("All Messages").
fn sub_row(ui: &mut Ui, t: &Theme, glyph: Option<&str>, label: &str, sub: &str, right: Option<&str>, enabled: bool) -> egui::Response {
    let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), if enabled { Sense::click() } else { Sense::hover() });
    let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
    if enabled && resp.hovered() {
        ui.painter().rect_filled(r, 4.0, t.bg_hover);
    }
    let mut x = r.left() + 8.0;
    if let Some(g) = glyph {
        super::paint_icon(ui.painter(), Rect::from_center_size(pos2(x + 10.0, r.center().y), vec2(20.0, 20.0)), g, t.interactive_normal);
        x += 28.0;
    }
    ui.painter().text(pos2(x, r.center().y - 8.0), Align2::LEFT_CENTER, label, crate::style::medium(14.0), t.header_primary);
    ui.painter().text(pos2(x, r.center().y + 9.0), Align2::LEFT_CENTER, sub, FontId::proportional(12.0), t.text_muted);
    if let Some(g) = right {
        super::paint_icon(ui.painter(), Rect::from_center_size(pos2(r.right() - 18.0, r.center().y), vec2(12.0, 12.0)), g, t.interactive_normal);
    }
    resp
}

/// Discord's menu checkbox: 18 px, 4 px corners; brand fill and a white
/// check when on, a 1.5 px outline when off.
fn paint_check(ui: &Ui, t: &Theme, b: Rect, on: bool) {
    if on {
        ui.painter().rect_filled(b, 4.0, t.accent);
        ui.painter().text(b.center(), Align2::CENTER_CENTER, icon::CHECK, crate::style::icon_font(b.width() * 0.6), Color32::WHITE);
    } else {
        ui.painter().rect_stroke(b, 4.0, Stroke::new(1.5_f32, t.interactive_normal));
    }
}

fn paint_radio(ui: &Ui, t: &Theme, c: Pos2, on: bool) {
    if on {
        ui.painter().circle_filled(c, 9.0, t.accent);
        ui.painter().circle_filled(c, 3.5, Color32::WHITE);
    } else {
        ui.painter().circle_stroke(c, 8.0, Stroke::new(1.5_f32, t.interactive_normal));
    }
}

/// A centred dialog over the dimmed app: title (and subtitle), a close
/// button and the body. Returns true when closed by ×, Escape or a click on
/// the dimmed app.
fn dialog(ctx: &egui::Context, t: &Theme, title: &str, subtitle: Option<&str>, width: f32, body: impl FnOnce(&mut Ui)) -> bool {
    let screen = ctx.screen_rect();
    egui::Area::new(egui::Id::new("guild_dialog_dim")).order(Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
        ui.allocate_exact_size(screen.size(), Sense::click());
        ui.painter().rect_filled(screen, 0.0, Color32::from_black_alpha(150));
    });
    let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
    let area = egui::Area::new(egui::Id::new("guild_dialog")).order(Order::Tooltip).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
        Frame::none()
            .fill(t.surface_high)
            .rounding(12.0)
            .stroke(Stroke::new(1.0_f32, super::modal_border(t)))
            .shadow(egui::epaint::Shadow { offset: vec2(0.0, 8.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(140) })
            .inner_margin(Margin::same(24.0))
            .show(ui, |ui| {
                ui.set_width(width);
                let top = ui.cursor().min;
                ui.label(bold(title).size(20.0).color(t.header_primary));
                if let Some(s) = subtitle {
                    ui.add_space(4.0);
                    ui.add(egui::Label::new(RichText::new(s).size(14.0).color(t.text_muted)).wrap());
                }
                let x = Rect::from_center_size(pos2(top.x + width - 10.0, top.y + 12.0), vec2(24.0, 24.0));
                let xr = ui.interact(x, egui::Id::new("guild_dialog_x"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, crate::style::icon_font(15.0), if xr.hovered() { t.header_primary } else { t.interactive_normal });
                close |= xr.clicked();
                ui.add_space(18.0);
                body(ui);
            });
    });
    close || super::pressed_outside(ctx, area.response.rect)
}

/// A label (and description) with a toggle on the right; true when flipped.
fn switch(ui: &mut Ui, t: &Theme, label: &str, desc: Option<&str>, on: bool) -> bool {
    let mut v = on;
    ui.horizontal(|ui| {
        ui.vertical(|ui| {
            ui.set_width(ui.available_width() - 56.0);
            ui.label(RichText::new(label).font(crate::style::medium(15.0)).color(t.header_primary));
            if let Some(d) = desc {
                ui.add(egui::Label::new(RichText::new(d).size(13.0).color(t.text_muted)).wrap());
            }
        });
        ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
            super::toggle_switch(ui, &mut v, t);
        });
    });
    v != on
}

fn radio_row(ui: &mut Ui, t: &Theme, label: &str, on: bool) -> bool {
    let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());
    if resp.hovered() {
        ui.painter().rect_filled(r, 6.0, t.bg_hover);
    }
    paint_radio(ui, t, pos2(r.left() + 14.0, r.center().y), on);
    ui.painter().text(pos2(r.left() + 34.0, r.center().y), Align2::LEFT_CENTER, label, crate::style::medium(15.0), t.header_primary);
    resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() && !on
}

fn radio_dot(ui: &mut Ui, t: &Theme, on: bool) -> bool {
    let (r, resp) = ui.allocate_exact_size(vec2(36.0, 22.0), Sense::click());
    paint_radio(ui, t, r.center(), on);
    resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() && !on
}

fn check_box(ui: &mut Ui, t: &Theme, on: bool) -> bool {
    let (r, resp) = ui.allocate_exact_size(vec2(36.0, 22.0), Sense::click());
    paint_check(ui, t, Rect::from_center_size(r.center(), vec2(18.0, 18.0)), on);
    resp.on_hover_cursor(egui::CursorIcon::PointingHand).clicked()
}

fn primary(ui: &mut Ui, t: &Theme, text: &str) -> egui::Response {
    ui.add(egui::Button::new(bold(text).size(14.0).color(Color32::WHITE)).fill(t.accent).rounding(8.0).min_size(vec2(96.0, 38.0))).on_hover_cursor(egui::CursorIcon::PointingHand)
}

fn secondary(ui: &mut Ui, t: &Theme, text: &str) -> egui::Response {
    ui.add(egui::Button::new(bold(text).size(14.0).color(t.header_primary)).fill(crate::style::overlay(0.12)).rounding(8.0).min_size(vec2(96.0, 38.0))).on_hover_cursor(egui::CursorIcon::PointingHand)
}

/// A dialog's button row, right-aligned (only as tall as its buttons).
fn footer(ui: &mut Ui, add: impl FnOnce(&mut Ui)) {
    ui.allocate_ui_with_layout(vec2(ui.available_width(), 40.0), Layout::right_to_left(Align::Center), add);
}

fn sep(ui: &mut Ui, t: &Theme) {
    ui.add_space(14.0);
    let y = ui.cursor().top();
    ui.painter().hline(ui.max_rect().x_range(), y, Stroke::new(1.0_f32, t.border_subtle));
    ui.add_space(14.0);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn labels() {
        assert_eq!(level_label(1), "Only @mentions");
        assert_eq!(hours_label(1), "1 hour");
        assert_eq!(hours_label(12), "12 hours");
        assert!(mute_until_label("not a date").is_none());
    }

    #[test]
    fn settings_pages_are_unique() {
        let mut keys: Vec<_> = SETTINGS_PAGES.iter().map(|(k, _)| *k).collect();
        keys.sort();
        keys.dedup();
        assert_eq!(keys.len(), SETTINGS_PAGES.len());
    }
}