Skip to content

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

193 KB
Raw Blame
//! Application state and the glue between the network backend, the store,
//! Rencord plugins and the UI.

use crate::backend::{Backend, Command, Event};
use crate::store::Store;
use crate::style::{self, Theme};
use discord::gateway::GatewayEvent;
use discord::model::{
    AllowedMentions, Id, LocalMeta, Message, MessageReference, OutgoingMessage, ReactionEmoji,
};
use eframe::egui::{self, Pos2};
use rencord::theme::Translation;
use rencord::{DeleteAction, Rencord};
use serde::Deserialize;
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Screen {
    Login,
    Main,
}

#[derive(Clone, PartialEq, Eq)]
pub enum ConnState {
    Offline,
    Connecting,
    Online,
    Reconnecting(String),
    Failed(String),
}

#[derive(Default)]
pub struct LoginState {
    /// Shown in the notice bar above the login page.
    pub notice: Option<String>,
    /// Why the login page couldn't be opened (WebView2 failed to start).
    pub open_error: Option<String>,
    /// Where the login page goes: under the title bar and the notice bar.
    pub webview_rect: Option<egui::Rect>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum SettingsTab {
    Account,
    Profiles,
    DataPrivacy,
    Messaging,
    Notifications,
    Nitro,
    ServerBoost,
    Subscriptions,
    GiftInventory,
    Billing,
    VoiceVideo,
    Appearance,
    Accessibility,
    System,
    Language,
    ActivityPrivacy,
    Connections,
    Developer,
    ProcessViewer,
    Experimental,
    Plugins,
    Themes,
    About,
}

pub struct ReplyTarget {
    pub channel: Id,
    pub msg: Id,
    pub author: String,
    pub mention: bool,
}

pub struct EditState {
    pub channel: Id,
    pub msg: Id,
    pub text: String,
    /// Focus the edit box on the next frame it's drawn.
    pub focus: bool,
}

/// Stand-in "server" ID for the Favourites server (no real guild has it).
pub const FAVORITES: Id = Id(1);

/// Why a plain-http theme isn't loaded: anyone on the network could swap it.
const THEME_HTTPS_ONLY: &str = "Themes load over https:// only (a plain http:// link could be changed on its way to you).";

/// A place in the app, for back / forward.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct NavEntry {
    pub guild: Option<Id>,
    pub channel: Option<Id>,
    pub friends: bool,
}

/// Messages you missed in a channel: everything after `last_read`.
#[derive(Clone, Copy, Debug)]
pub struct NewSince {
    pub channel: Id,
    pub last_read: Id,
    /// The bar is up. Clicking it or scrolling up to the NEW line hides it;
    /// the line itself stays until you leave the channel.
    pub bar: bool,
}

#[derive(Clone, Copy)]
pub struct ContextMenu {
    pub channel: Id,
    pub msg: Id,
    pub pos: Pos2,
    pub opened_frame: u64,
}

pub struct Toast {
    pub text: String,
    pub error: bool,
    pub at: Instant,
}

/// What is being dragged on the server rail.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum RailDrag {
    Server(Id),
    Folder(u64),
}

pub struct RustCord {
    pub ctx: egui::Context,
    pub backend: Backend,
    pub demo: bool,
    pub screen: Screen,
    pub conn: ConnState,
    pub login: LoginState,

    pub store: Store,
    pub rencord: Rencord,

    pub theme: Theme,
    pub theme_css: String,
    pub theme_report: Option<Translation>,
    pub theme_status: String,
    pub theme_input: String,
    pub quick_css_input: String,

    pub current_guild: Option<Id>,
    pub current_channel: Option<Id>,
    pub last_channel: HashMap<Option<Id>, Id>,
    /// Each server's channel list scroll offset (None = Home), kept in nav.json.
    pub channel_scroll: HashMap<Option<Id>, f32>,
    /// Lists whose saved offset was put back this run (once each).
    pub channel_scroll_restored: HashSet<Option<Id>>,
    /// A list still being put back: (list, offset, since when).
    pub channel_scroll_pending: Option<(Option<Id>, f32, Instant)>,
    pub collapsed: HashSet<Id>,
    /// Chats you'd scrolled up in this session: channel → (message at the
    /// view's top, px from its top to the view's). Kept by the message list;
    /// switching back to a server puts its chat back there.
    pub scroll_marks: std::cell::RefCell<HashMap<Id, (Id, f32)>>,
    /// Put a chat back where you were: (channel, message, px, older pages
    /// loaded looking for it).
    pub scroll_restore: std::cell::Cell<Option<(Id, Id, f32, u8)>>,
    /// Where to reopen after a restart: (server, channel), used once the
    /// servers are known.
    pub restore_nav: Option<(Option<Id>, Option<Id>)>,
    /// nav.json has changes to write (since when).
    pub nav_dirty: std::cell::Cell<Option<Instant>>,
    /// A keyboard zoom not written to prefs.json yet (since when).
    pub zoom_unsaved: Option<Instant>,

    pub drafts: HashMap<Id, String>,
    pub reply: Option<ReplyTarget>,
    pub last_typing_sent: Option<(Id, Instant)>,
    pub editing: Option<EditState>,
    pub context_menu: Option<ContextMenu>,
    pub revealed: HashSet<(Id, usize)>,
    /// Message whose hover toolbar was drawn last frame, and where. The
    /// toolbar overlaps the message above, so it needs to keep hover.
    pub hover_toolbar: std::cell::Cell<Option<(Id, egui::Rect)>>,
    /// Rencord's MessageSelect: the channel and its checked-off messages.
    pub picked_msgs: (Id, std::collections::BTreeSet<Id>),
    /// MessageSelect is on and Ctrl + Shift is held: clicks pick messages.
    pub picking: bool,

    pub settings_open: bool,
    pub settings_tab: SettingsTab,
    pub shortcuts_open: bool,
    pub toasts: Vec<Toast>,

    pub config_dir: Option<std::path::PathBuf>,
    /// Most recently used emoji first.
    pub frequent: Vec<String>,
    pub emoji_picker: Option<crate::features::EmojiPicker>,
    pub forward: Option<crate::features::ForwardState>,
    pub uploads: HashMap<Id, Vec<crate::features::PendingUpload>>,
    /// "Mark Unread": channel → first unread message (draws the NEW line).
    pub unread_marker: HashMap<Id, Id>,
    /// Messages you missed in the open channel (Discord's blue "N new
    /// messages since …" bar and red NEW line).
    pub new_since: Option<NewSince>,
    /// A jump waiting for older messages to load: (channel, message, pages tried).
    pub pending_jump: Option<(Id, Id, u8)>,
    pub profile: Option<crate::features::ProfilePopout>,
    /// The big profile window (avatar clicked in a profile card).
    pub full_profile: Option<crate::features::FullProfile>,
    /// The composer's "+" menu tools, sticker picker and app launcher.
    pub compose: crate::features::ComposeTools,
    /// Channel or category being dragged in the channel list.
    pub channel_drag: Option<Id>,
    /// Server or folder being dragged on the server rail.
    pub rail_drag: Option<RailDrag>,
    /// Middle-click autoscroll (see ui/autoscroll.rs).
    pub autoscroll: crate::ui::autoscroll::Autoscroll,
    /// Server pages from the channel list header (Members, Server Boosts,
    /// Server Shop) and the Events popup.
    pub guild_pages: crate::ui::guild_pages::GuildPages,
    /// Text to send once a newly opened DM channel arrives.
    pub pending_dm: Option<(Id, String)>,
    pub audio: crate::audio::AudioPlayer,
    /// The inline video that is playing (one at a time), and its channel.
    pub video_player: Option<crate::video_player::VideoPlayer>,
    pub video_channel: Option<Id>,
    /// A provider's player (YouTube, Spotify…) open over an embed.
    pub embed_view: Option<crate::embed_view::EmbedView>,
    /// Where the last frame drew the playing embed's box (and the chat's
    /// visible area): the webview is moved there once that frame is shown.
    pub pending_place: Option<(crate::embed_view::Key, egui::Rect, egui::Rect)>,
    /// A player the chat asked for; opened once its box has been laid out.
    pub embed_request: Option<EmbedRequest>,
    /// "Remove all embeds" was clicked once on this message (a second click
    /// within a few seconds does it).
    pub suppress_armed: Option<(Id, Instant)>,
    pub last_ack: Option<Instant>,
    /// Friends page is showing (Home → Friends).
    pub friends_open: bool,
    pub friends_tab: crate::features::FriendsTab,
    pub friends_search: String,
    /// A friend row's ⋮ menu: (user, where, frame it opened, confirming removal).
    pub friend_menu: Option<(Id, Pos2, u64, bool)>,
    /// Right-click menu of a DM in the list: (channel, where, frame it opened).
    pub dm_menu: Option<(Id, Pos2, u64)>,
    /// "Looking for accounts you've blocked or ignored?" still showing.
    pub blocked_notice: bool,
    pub expanded_folders: HashSet<u64>,
    /// RustCord-only preferences (zoom, reduced motion, clock).
    pub prefs: crate::features::LocalPrefs,
    /// Account menu (click your own avatar in the user panel).
    pub account_menu: Option<crate::features::AccountMenu>,
    /// The accounts you can switch between.
    pub accounts: crate::accounts::Saved,
    /// The account of the running session (None in the demo or logged out).
    pub account: Option<Id>,
    /// The running session's token (for Ctrl+R).
    token: Option<String>,
    /// Counts sessions: events of a replaced one are ignored (see `Command::Login`).
    session: u64,
    /// The login page was opened by "Add an account" (closing it goes back).
    pub adding_account: bool,
    /// The "Manage Accounts" window.
    pub manage_accounts: Option<crate::ui::switch_accounts::ManageAccounts>,
    /// Quick switcher ("Find or start a conversation").
    pub switcher: Option<String>,
    /// The embedded Discord login page, while open.
    pub login_view: Option<crate::login_view::LoginView>,
    /// A captcha Discord demanded for a message, waiting for the person to solve it.
    pub captcha: Option<CaptchaPrompt>,
    /// When the login page opened (dev aid `RUSTCORD_DEV_VIEW=login-done`).
    pub login_opened_at: Option<Instant>,
    /// Login page after a successful login: hidden, destroyed a bit later.
    pub retired_login_view: Option<(crate::login_view::LoginView, Instant)>,
    /// Member list on the right (server channels).
    pub show_members: bool,
    /// Member list on the right in group DMs (Discord keeps the two apart).
    pub show_group_members: bool,
    /// The "Invite to Group DM" / "Add Friends to DM" dialog.
    pub group_invite: Option<crate::ui::group_dm::GroupInvite>,
    /// The "Leave '<group>'" confirmation dialog.
    pub group_leave: Option<crate::ui::group_dm::LeaveGroup>,
    /// People being added to a group DM, until Discord answers.
    pub group_adds: Vec<Id>,
    /// How many 100-member windows RustCord has subscribed to, per channel.
    pub member_windows: HashMap<Id, usize>,
    /// Pinned messages popout: (channel, anchor, loaded result).
    pub pins: Option<(Id, Pos2, Option<Result<Vec<Message>, String>>)>,
    /// Frame the pins popout opened on (so that click doesn't close it).
    pub pins_opened: u64,
    /// The "pin / unpin this message?" question, while it is up.
    pub pin_confirm: Option<crate::features::PinConfirm>,
    /// Discord's "Accept friend request?" about this person (a stranger's
    /// request: no mutual friends or small servers), while it is up.
    pub stranger_confirm: Option<Id>,
    /// The "Add / Change Friend Nickname" dialog, while it is up.
    pub friend_nickname: Option<crate::ui::friend_nickname::FriendNickname>,
    /// People with a friend-list change queued or on its way (see
    /// `backend::relationship_queue`): their buttons wait.
    pub relationship_busy: std::collections::HashSet<Id>,
    /// Dev aid (`RUSTCORD_DEV_VIEW=wave-big:<user>` / `wave-pill:<user>`):
    /// that DM shows the "Wave to …" prompt in that form, and waving only
    /// shows a toast.
    pub dev_wave: Option<(Id, bool)>,
    /// The header's Threads popout: (channel, anchor, frame opened).
    pub threads_popout: Option<(Id, Pos2, u64)>,
    /// The forum channel that's open: its posts, filters and New Post form.
    pub forum: crate::ui::forum::ForumState,
    /// Markdown `**bold**` is drawn semibold (600) instead of bold (700)
    /// while this is set: Discord's weight for embed titles and field names.
    pub markup_semibold: std::cell::Cell<bool>,
    /// Set when a line of markdown wrapped onto a second row (an embed
    /// whose text wraps is as wide as it can be).
    pub markup_wrapped: std::cell::Cell<bool>,
    /// The bot button / select / form whose answer RustCord is waiting for.
    pub interaction: Option<crate::ui::interactions::PendingInteraction>,
    /// The message under which "This interaction failed" shows.
    pub interaction_failed: Option<Id>,
    /// A form (modal) an app opened.
    pub bot_modal: Option<crate::ui::interactions::BotModal>,
    /// The open select menu of a message: (message, its custom id).
    pub open_select: Option<(Id, String)>,
    pub search_input: String,
    /// The list of filters under the search box.
    pub search_suggest: crate::ui::search::SearchSuggest,
    /// Profile panel on the right of 1:1 DMs.
    pub show_dm_profile: bool,
    /// Back / forward navigation history (title bar arrows).
    pub nav_back: Vec<NavEntry>,
    pub nav_forward: Vec<NavEntry>,
    pub nav_current: Option<NavEntry>,
    /// Recent mentions popout (title bar inbox): anchor + result.
    pub inbox: Option<(Pos2, Option<Result<Vec<Message>, String>>)>,
    pub inbox_opened_frame: u64,
    /// GIF picker: (search text, results for that search).
    pub gif_picker: Option<crate::features::GifPicker>,
    /// Trending GIFs from the last fetch (the picker shows them at once).
    pub gif_trending: Option<Vec<discord::model::Gif>>,
    /// Answers to `api()` calls by tag, and the tags still in flight.
    pub api_results: HashMap<String, Result<Value, String>>,
    pub api_pending: HashSet<String>,
    pub profile_requested: HashSet<(Id, Option<Id>)>,
    /// User panel mic / headphone buttons.
    pub self_mute: bool,
    pub self_deaf: bool,
    /// "Set a custom status" dialog: (text, emoji kept from before).
    pub custom_status_dialog: Option<String>,
    /// Discord's "Reactions" dialog (who reacted with what).
    pub reactions_dialog: Option<crate::ui::reactions::ReactionsDialog>,
    /// In-app image / avatar viewer.
    pub viewer: Option<crate::features::MediaView>,
    /// Server cards for server tags, by server.
    pub guild_profiles: HashMap<Id, Result<discord::model::GuildProfile, String>>,
    /// Open server-tag popout: (server, where, frame it opened).
    pub tag_popout: Option<(Id, Pos2, u64)>,
    /// "Adopt this server's tag" modal (server dropdown → Server Tag).
    pub tag_adopt: Option<crate::ui::tag_adopt::TagAdopt>,
    /// Open sticker popout (a sticker in a message was clicked).
    pub sticker_popout: Option<crate::features::StickerPopout>,
    /// Server name dropdown: (server, frame it opened).
    pub server_menu: Option<(Id, u64)>,
    /// The member right-click menu and the moderation dialogs (kick, ban, timeout…).
    pub moderation: crate::ui::moderation::ModState,
    /// The server icon's right-click menu: server, where, frame it opened.
    pub guild_menu: Option<(Id, egui::Pos2, u64)>,
    /// A server channel's right-click menu: (channel, where, frame opened).
    pub channel_menu: Option<(Id, egui::Pos2, u64)>,
    /// A dialog opened from a server menu (Notification Settings, Privacy…).
    pub guild_dialog: Option<crate::ui::guild_menu::GuildDialog>,
    /// A dialog from the server menu / channel gear.
    pub server_dialog: Option<crate::features::ServerDialog>,
    /// Discord's "Add a Server" dialog (create one or join by invite), while open.
    pub add_server: Option<crate::ui::add_server::AddServer>,
    /// A server just created or joined: opened once the gateway delivers it.
    pub open_when_joined: Option<Id>,
    /// This gateway session's ID (READY), which Discord's client sends when
    /// accepting an invite.
    pub gateway_session: Option<String>,
    /// Discord's "Invite friends to …" modal, while open.
    pub invite: Option<crate::ui::invite::InviteModal>,
    /// Home → Message Requests page is showing (instead of Friends).
    pub requests_open: bool,
    /// Message Requests page: "Spam" tab instead of "Requests".
    pub requests_spam: bool,
    /// The request opened in the panel on the right of Message Requests.
    pub request_preview: Option<Id>,
    /// Home → Nitro Home / Shop / Quests page showing (instead of Friends).
    pub store_page: Option<crate::features::StorePage>,
    pub quests: Option<Result<discord::commerce::QuestList, String>>,
    /// Orbs balance (Quests' currency).
    pub orbs: Option<u64>,
    /// Quests page: "Claimed Quests" tab instead of "All Quests".
    pub quests_claimed_tab: bool,
    pub shop: Option<Result<discord::commerce::Shop, String>>,
    pub nitro: Option<Result<Vec<discord::commerce::Subscription>, String>>,
    /// A video quest playing in the in-app player.
    pub quest_video: Option<crate::quest_video::QuestVideo>,
    /// The voice channel you are in (or joining).
    pub voice: Option<crate::voice_call::VoiceSession>,
    /// DM / group DM calls Discord told RustCord about (CALL_CREATE / CALL_UPDATE), by channel.
    pub calls: std::collections::HashMap<Id, crate::voice_call::DmCall>,
    /// A call you started: ring the others once your side is connected.
    pub ring_when_connected: Option<Id>,
    /// A video call you started (the DM header's camera button): turn the
    /// camera on once your side is connected.
    pub camera_when_connected: Option<Id>,
    /// The call the last run closed in, offered by the "Reconnect" notice.
    pub last_call: Option<crate::ui::voice_notice::LastCall>,
    /// The call `last-call.json` holds now.
    pub last_call_saved: Option<crate::ui::voice_notice::LastCall>,
    /// A call you want to start: waiting for Discord to say whether the DM can be rung.
    pub call_check: Option<Id>,
    /// Incoming calls you dismissed here (their popup stays away).
    pub dismissed_calls: std::collections::HashSet<Id>,
    /// Voice & Video preferences, device list, mic test and call view menus.
    pub voice_ui: crate::voice_call::VoiceUi,
    /// The soundboard picker, the servers' sounds and sounds waiting to play.
    pub soundboard: crate::ui::soundboard::Soundboard,
    /// Games' Rich Presence by connection: (application ID, activity).
    pub rpc_activities: std::collections::BTreeMap<u64, (String, serde_json::Value)>,
    /// What RustCord last put in your presence, so it's only re-sent when it changes.
    pub rpc_sent: Option<Vec<(String, serde_json::Value)>>,
    /// When Spotify was last looked at (for "Listening to Spotify").
    pub spotify_at: Option<Instant>,
    /// The gateway session is new: what Spotify plays must be sent even if unchanged.
    pub spotify_fresh: bool,
    /// First message of each message request.
    pub request_previews: HashMap<Id, Message>,
    pub add_friend_input: String,
    /// Games (applications) for Game Collection, and which are being fetched.
    pub apps: HashMap<Id, discord::model::AppInfo>,
    pub apps_wanted: std::cell::RefCell<HashSet<Id>>,
    /// Profiles hovered this frame (fetched ahead of a click).
    pub profiles_wanted: std::cell::RefCell<Vec<(Id, Option<Id>)>>,
    /// Users whose badges (Discord's badge API) were asked for while drawing.
    pub badges_wanted: std::cell::RefCell<Vec<Id>>,
    /// The "Your badges" window.
    pub badge_window: Option<crate::ui::badges::BadgeWindow>,
    /// Your Nitro client theme's colours (from the account settings).
    pub client_theme: crate::features::AccountTheme,
    /// Settings → Account: a username / email / password change in progress.
    pub account_edit: crate::features::AccountEdit,
    /// Your Discord settings (settings-proto), for Settings to read and change.
    pub account_proto: discord::settings_proto::RawSettings,
    /// The main window (0 until it exists), and what its taskbar badge shows.
    hwnd: isize,
    badge: crate::tray::Badge,
    badge_at: Option<Instant>,
    /// Where the last Windows notification came from (clicking it goes there).
    notified: Option<(Option<Id>, Id)>,
    /// Windows' light / dark mode, looked at every few seconds while followed.
    device_theme_at: Option<Instant>,
    /// The notification-area icon's picks (Open, About, Reset, Restart, Quit).
    tray: Option<std::sync::mpsc::Receiver<crate::tray::TrayAction>>,
    /// Whether the tray icon is actually on screen (a Linux panel can restart).
    tray_usable: bool,
    /// The window is hidden in the notification area.
    window_hidden: bool,
    /// The window's size while it was last shown (see `raw_input_hook`).
    laid_out_at: Option<egui::Rect>,
    /// RustCord is quitting for real (the tray's Quit, a restart, another
    /// RustCord asking it to): the window's close isn't turned into a trip
    /// to the tray.
    quitting: bool,
    /// Where the window was last closed (`window.json`), and later where it
    /// was when it went to the tray; written again on exit.
    window_file: Option<std::path::PathBuf>,
    window_place: Option<crate::window_place::Placement>,
    /// Automatic updates (an installed copy on Windows only).
    pub updater: Option<crate::updater::Updater>,
    /// Discord's "Briefly leave voice?" before restarting into an update.
    pub update_confirm: bool,
    /// Windows 11 corner rounding asked for (once the window exists).
    corners_rounded: bool,
    pub apps_requested: HashSet<Id>,
    /// Channel the pointer is resting on, and since when (message prefetch).
    pub hover_prefetch: Option<(Id, Instant)>,
    pub perf: Perf,
    /// Settings → Performance → Process Viewer: what it has sampled.
    pub process_viewer: crate::ui::process_viewer::ProcessViewer,
    /// Settings → Experimental → Request Log's window.
    pub request_log: crate::ui::request_log::RequestLog,
    /// Settings → Experimental → Spam Warnings: the cards showing.
    pub spam_warnings: crate::ui::spam_warnings::SpamWarnings,
    /// Settings → Experimental → Spotify Controller.
    pub spotify_panel: crate::ui::spotify_player::SpotifyPanel,
    /// "Leaving RustCord": a link to a non-Discord site, waiting for an answer.
    pub leaving: Option<crate::ui::leaving::Leaving>,
    /// The link "Visit Site" just let through.
    pub allowed_link: Option<String>,
    /// "Your badges" window: (badges, selected).
    pub badges_view: Option<(Vec<discord::model::ProfileBadge>, usize)>,
    /// Search results panel: (query, None while loading, or the result).
    pub search: Option<(String, Option<Result<(u64, Vec<Message>), String>>)>,
    pub profiles: HashMap<(Id, Option<Id>), Result<discord::model::UserProfile, String>>,
    /// What the RustCord registry said about people (the RustCord badge):
    /// (joined, last seen) for RustCord users, its clock then, and when.
    pub registry: HashMap<Id, (Option<(u64, u64)>, u64, Instant)>,
    /// Users whose badge was wanted while drawing, and when each was last asked about.
    pub registry_wanted: std::cell::RefCell<Vec<Id>>,
    pub registry_asked: HashMap<Id, Instant>,
    /// The account the registry loop runs for.
    pub registry_for: Option<Id>,
    /// What the registry loop was last started with: (sharing, Invisible).
    pub registry_sent: (bool, bool),
    /// Listen Along: (whose Spotify, the track RustCord last started).
    pub listen_along: Option<(Id, String)>,
    /// Go Live: your stream, the ones you watch, the screen picker.
    pub go_live: Option<crate::golive::GoLive>,
    /// Your camera (see camera.rs).
    pub camera: crate::camera::CameraState,
    pub watching: Vec<crate::golive::Watching>,
    pub share_picker: Option<crate::golive::SharePicker>,
    pub golive_ui: crate::golive::GoLiveUi,
    /// Your full profile's server tag dropdown: where it opens.
    pub tag_picker: Option<Pos2>,
    /// A profile's open "More" menu.
    pub profile_more: Option<crate::ui::ProfileMore>,
    /// "Remove Friend" picked on a profile, waiting for its confirmation:
    /// (who, their username).
    pub remove_friend: Option<(Id, String)>,
    /// "Invite to Server" picked there: (channel the invite is for, who gets it).
    pub profile_invites: Vec<(Id, Id)>,
}

/// What `main` starts before the window exists: the saved accounts are read
/// and the active one's session starts connecting (and its snapshot loading),
/// so the account is on screen as soon as the window is.
pub struct Launch {
    accounts: crate::accounts::Saved,
    /// The account and token of the session already started.
    session: Option<(Id, String)>,
}

/// The number of the session a launch starts (see `Command::Login`).
const LAUNCH_SESSION: u64 = 1;

impl Launch {
    pub fn begin(backend: &Backend, demo: bool) -> Self {
        if demo {
            return Self { accounts: Default::default(), session: None };
        }
        let accounts = crate::accounts::Saved::load();
        let session = accounts.active.and_then(|id| Some((id, crate::accounts::token(id)?)));
        if let Some((id, token)) = &session {
            log::info!("login: connecting with the saved login {}", crate::accounts::token_tag(token));
            backend.send(Command::Login { session: LAUNCH_SESSION, account: Some(*id), token: token.clone() });
        }
        Self { accounts, session }
    }
}

pub fn now_ms() -> u64 {
    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
}

impl RustCord {
    pub fn new(cc: &eframe::CreationContext, demo: bool, backend: Backend, launch: Launch) -> Self {
        backend.attach(cc.egui_ctx.clone());
        egui_extras::install_image_loaders(&cc.egui_ctx);
        crate::net_images::NetImages::install(&cc.egui_ctx);
        crate::net_images::LruTextures::install(&cc.egui_ctx);
        crate::net_images::FastImages::install(&cc.egui_ctx);
        crate::video::install(&cc.egui_ctx);
        crate::emoji::install_text_emoji(&cc.egui_ctx);
        style::install_fonts(&cc.egui_ctx);
        style::use_system_scroll_speed(&cc.egui_ctx);
        crate::spellcheck::install(&cc.egui_ctx);

        let config_dir = directories::ProjectDirs::from("dev", "RustCord", "RustCord")
            .map(|d| d.config_dir().to_path_buf());
        let rencord = Rencord::load(config_dir.as_ref().map(|d| d.join("rencord.json")));
        let frequent = crate::features::load_frequent(config_dir.as_deref());
        let blocked_notice = !config_dir.as_ref().is_some_and(|d| d.join("blocked-notice-dismissed").exists());
        let expanded_folders = crate::features::load_open_folders(config_dir.as_deref());
        let prefs = crate::features::load_prefs(config_dir.as_deref());
        let last_call = if demo { None } else { crate::ui::voice_notice::load(config_dir.as_deref()) };
        crate::emoji::set_skin_tone(prefs.skin_tone);
        crate::features::apply_zoom(&cc.egui_ctx, prefs.zoom);
        crate::features::apply_prefs(&prefs);
        let Launch { accounts, session } = launch;
        let nav = crate::features::load_nav(crate::features::nav_file(session.as_ref().map(|(id, _)| *id)).as_deref());
        let tray = crate::tray::start(cc.egui_ctx.clone());
        let tray_usable = tray.is_some();
        let window_file = crate::window_place::file(demo);
        let window_place = crate::window_place::load(window_file.as_deref());

        let mut app = Self {
            ctx: cc.egui_ctx.clone(),
            backend,
            demo,
            screen: Screen::Login,
            conn: ConnState::Offline,
            login: LoginState::default(),
            store: Store::default(),
            theme: Theme::default(),
            theme_css: String::new(),
            theme_report: None,
            theme_status: String::new(),
            theme_input: rencord.theme.source.clone().unwrap_or_default(),
            quick_css_input: rencord.theme.quick_css.clone(),
            rencord,
            current_guild: None,
            current_channel: None,
            last_channel: nav.as_ref().map(|n| n.last_channel.iter().copied().collect()).unwrap_or_default(),
            channel_scroll: nav.as_ref().map(|n| n.channel_scroll.iter().copied().collect()).unwrap_or_default(),
            channel_scroll_restored: HashSet::new(),
            channel_scroll_pending: None,
            collapsed: nav.as_ref().map(|n| n.collapsed.iter().copied().collect()).unwrap_or_default(),
            scroll_marks: Default::default(),
            scroll_restore: Default::default(),
            restore_nav: nav.as_ref().map(|n| (n.guild, n.channel)),
            nav_dirty: Default::default(),
            zoom_unsaved: None,
            drafts: HashMap::new(),
            reply: None,
            last_typing_sent: None,
            editing: None,
            context_menu: None,
            revealed: HashSet::new(),
            hover_toolbar: std::cell::Cell::new(None),
            picked_msgs: Default::default(),
            picking: false,
            settings_open: false,
            settings_tab: SettingsTab::Account,
            shortcuts_open: false,
            toasts: Vec::new(),
            config_dir,
            frequent,
            emoji_picker: None,
            forward: None,
            uploads: HashMap::new(),
            unread_marker: HashMap::new(),
            new_since: None,
            pending_jump: None,
            profile: None,
            full_profile: None,
            compose: Default::default(),
            channel_drag: None,
            rail_drag: None,
            autoscroll: Default::default(),
            guild_pages: Default::default(),
            pending_dm: None,
            audio: Default::default(),
            video_player: None,
            video_channel: None,
            embed_view: None,
            pending_place: None,
            embed_request: None,
            suppress_armed: None,
            last_ack: None,
            friends_open: false,
            friends_tab: Default::default(),
            friends_search: String::new(),
            friend_menu: None,
            dm_menu: None,
            blocked_notice,
            expanded_folders,
            prefs,
            account_menu: None,
            accounts,
            account: None,
            token: None,
            session: 0,
            adding_account: false,
            manage_accounts: None,
            switcher: None,
            login_view: None,
            captcha: None,
            login_opened_at: None,
            retired_login_view: None,
            show_members: true,
            show_group_members: true,
            group_invite: None,
            group_leave: None,
            group_adds: Vec::new(),
            member_windows: HashMap::new(),
            pins: None,
            pins_opened: 0,
            pin_confirm: None,
            stranger_confirm: None,
            friend_nickname: None,
            relationship_busy: Default::default(),
            dev_wave: None,
            threads_popout: None,
            forum: Default::default(),
            markup_semibold: Default::default(),
            markup_wrapped: Default::default(),
            interaction: None,
            interaction_failed: None,
            bot_modal: None,
            open_select: None,
            search_input: String::new(),
            search_suggest: Default::default(),
            show_dm_profile: true,
            nav_back: Vec::new(),
            nav_forward: Vec::new(),
            nav_current: None,
            inbox: None,
            inbox_opened_frame: 0,
            gif_picker: None,
            gif_trending: None,
            api_results: HashMap::new(),
            api_pending: HashSet::new(),
            profile_requested: HashSet::new(),
            self_mute: false,
            self_deaf: false,
            custom_status_dialog: None,
            reactions_dialog: None,
            viewer: None,
            guild_profiles: HashMap::new(),
            tag_popout: None,
            tag_adopt: None,
            sticker_popout: None,
            server_menu: None,
            moderation: Default::default(),
            guild_menu: None,
            channel_menu: None,
            guild_dialog: None,
            server_dialog: None,
            add_server: None,
            open_when_joined: None,
            gateway_session: None,
            invite: None,
            requests_open: false,
            requests_spam: false,
            request_preview: None,
            store_page: None,
            quests: None,
            orbs: None,
            quests_claimed_tab: false,
            shop: None,
            nitro: None,
            quest_video: None,
            voice: None,
            calls: Default::default(),
            ring_when_connected: None,
            camera_when_connected: None,
            last_call,
            last_call_saved: last_call,
            call_check: None,
            dismissed_calls: Default::default(),
            voice_ui: crate::voice_call::VoiceUi::load(),
            soundboard: Default::default(),
            rpc_activities: Default::default(),
            rpc_sent: None,
            spotify_at: None,
            spotify_fresh: false,
            registry: HashMap::new(),
            registry_wanted: Default::default(),
            registry_asked: HashMap::new(),
            registry_for: None,
            registry_sent: (false, false),
            request_previews: HashMap::new(),
            add_friend_input: String::new(),
            badges_view: None,
            hover_prefetch: None,
            perf: Perf { on: std::env::var("RUSTCORD_PERF").is_ok(), ..Default::default() },
            process_viewer: Default::default(),
            request_log: Default::default(),
            spam_warnings: Default::default(),
            spotify_panel: Default::default(),
            leaving: None,
            allowed_link: None,
            apps: HashMap::new(),
            apps_wanted: Default::default(),
            profiles_wanted: Default::default(),
            badges_wanted: Default::default(),
            badge_window: None,
            client_theme: Default::default(),
            account_proto: Default::default(),
            account_edit: Default::default(),
            hwnd: 0,
            badge: crate::tray::Badge::None,
            badge_at: None,
            notified: None,
            device_theme_at: None,
            tray,
            tray_usable,
            window_hidden: false,
            quitting: false,
            laid_out_at: None,
            window_file,
            window_place,
            updater: crate::updater::Updater::start(&cc.egui_ctx),
            update_confirm: false,
            corners_rounded: false,
            apps_requested: HashSet::new(),
            search: None,
            profiles: HashMap::new(),
            listen_along: None,
            go_live: None,
            camera: Default::default(),
            watching: Vec::new(),
            share_picker: None,
            golive_ui: Default::default(),
            tag_picker: None,
            profile_more: None,
            remove_friend: None,
            profile_invites: Vec::new(),
        };

        app.restore_theme();
        log::info!("startup: window up {} ms after start", crate::diagnostics::ms_since_start());

        // Downloaded copies of videos that could not be streamed last time.
        std::thread::spawn(crate::video_player::clear_temp);
        // (Not in the demo, which reads no saved accounts: an update's first
        // start takes the single account's caches over before they go.)
        if !demo {
            std::thread::spawn(crate::cache::remove_stale);
        }
        // Developer aid: with --demo, RUSTCORD_DEV_VIEW=login starts on the
        // login page (the demo account opens once a login completes); =login-done
        // also completes one by itself 10 s after the page opens.
        let dev = crate::diagnostics::dev_var("RUSTCORD_DEV_VIEW").unwrap_or_default();
        if demo && (dev == "login" || dev == "login-done") {
            app.screen = Screen::Login;
        } else if demo {
            app.start_session(None, "demo".into());
        } else if let Some((id, token)) = session {
            // (Already connecting: see `Launch`.)
            app.session = LAUNCH_SESSION;
            app.account = Some(id);
            app.token = Some(token);
            app.conn = ConnState::Connecting;
            app.screen = Screen::Main;
        }
        app
    }

    pub fn toast(&mut self, text: impl Into<String>, error: bool) {
        self.toasts.push(Toast { text: text.into(), error, at: Instant::now() });
    }

    // ---- login ----------------------------------------------------------

    /// Start a session with a token Discord handed over (the login page, or a
    /// password change): it is kept in Windows Credential Manager for next
    /// time, and its account becomes the active one.
    pub fn login_with_token(&mut self, token: String) {
        let account = crate::accounts::token_user(&token);
        // (The demo account has no login of its own.)
        if !self.demo {
            match account {
                Some(id) => {
                    log::info!("login: saving session to Windows Credential Manager");
                    self.accounts.add(id, &token);
                }
                // Kept once READY says whose it is.
                None => log::info!("login: the token doesn't say whose it is; saved once Discord does"),
            }
        }
        if self.account.is_some() && self.account != account {
            self.leave_account(account);
        }
        log::info!("login: connecting");
        self.start_session(account, token);
    }

    /// Start a session (replacing any running one). The account shows at
    /// once as it was last time, from its snapshot, while the gateway connects.
    fn start_session(&mut self, account: Option<Id>, token: String) {
        self.session += 1;
        self.account = account;
        self.token = Some(token.clone());
        self.conn = ConnState::Connecting;
        self.login.notice = None;
        self.adding_account = false;
        self.screen = Screen::Main;
        self.backend.send(Command::Login { session: self.session, account, token });
    }

    /// Switch to another saved account, as Discord's "Switch Accounts" does:
    /// this one's session ends here (it stays logged in, to come back to), and
    /// the other opens where you left it, from its snapshot while it connects.
    pub fn switch_account(&mut self, id: Id) {
        if self.account == Some(id) && self.screen == Screen::Main {
            return;
        }
        let Some(token) = crate::accounts::token(id) else {
            // Its login is gone from the credential store: log in again.
            self.accounts.forget(id);
            self.toast("That account needs to log in again.", true);
            self.open_add_account();
            return;
        };
        log::info!("accounts: switching account");
        self.leave_account(Some(id));
        self.accounts.set_active(id);
        self.start_session(Some(id), token);
    }

    /// Put the running account away before `next` takes over: its place is
    /// saved, and nothing of it stays on screen or in memory.
    fn leave_account(&mut self, next: Option<Id>) {
        self.screen = Screen::Main;
        self.save_nav();
        self.leave_voice();
        self.reset_session();
        self.close_session_ui();
        self.forget_loaded();
        self.ctx.forget_all_images();
        crate::diagnostics::release_unused_memory();
        let nav = crate::features::load_nav(crate::features::nav_file(next).as_deref());
        self.apply_nav(nav);
    }

    /// Open the login page to add another account (the running one carries on
    /// meanwhile; closing the page goes back to it).
    pub fn open_add_account(&mut self) {
        if self.accounts.is_full() {
            self.toast(format!("You can switch between up to {} accounts.", crate::accounts::MAX), true);
            return;
        }
        self.save_nav();
        self.account_menu = None;
        self.manage_accounts = None;
        self.settings_open = false;
        self.adding_account = self.account.is_some();
        self.screen = Screen::Login;
    }

    /// Close the "Add an account" login page and go back to the running account.
    pub fn cancel_add_account(&mut self) {
        if self.adding_account {
            self.adding_account = false;
            self.login.notice = None;
            self.screen = Screen::Main;
        }
    }

    /// Log out a saved account that isn't the running one: its session is
    /// ended at Discord and its login forgotten here.
    pub fn logout_other(&mut self, id: Id) {
        if let Some(token) = crate::accounts::token(id) {
            self.backend.send(Command::EndSession { token, done: None });
        }
        self.accounts.forget(id);
    }

    /// Use an account's saved place (each server's last channel, folded
    /// categories, where it was), or start fresh.
    fn apply_nav(&mut self, nav: Option<crate::features::NavState>) {
        self.last_channel = nav.as_ref().map(|n| n.last_channel.iter().copied().collect()).unwrap_or_default();
        self.channel_scroll = nav.as_ref().map(|n| n.channel_scroll.iter().copied().collect()).unwrap_or_default();
        self.channel_scroll_restored.clear();
        self.collapsed = nav.as_ref().map(|n| n.collapsed.iter().copied().collect()).unwrap_or_default();
        self.restore_nav = nav.as_ref().map(|n| (n.guild, n.channel));
    }

    /// Whether the title bar's X can hide the window in the notification
    /// area (Windows and Linux; macOS has no tray icon).
    pub fn tray_available(&self) -> bool {
        let window_known = self.hwnd != 0 || !cfg!(windows);
        cfg!(any(windows, target_os = "linux")) && window_known && self.tray.is_some() && self.tray_usable
    }

    /// "Minimize RustCord to System Tray", as Discord does it: closing the
    /// window any way (the title bar's X, Alt+F4, the taskbar's "Close
    /// window") hides it instead. Only the tray's Quit, a restart or another
    /// RustCord asking (a second launch, the installer: see
    /// `tray::ask_others_to_quit`) really quits.
    fn close_to_tray(&mut self, ctx: &egui::Context) {
        let asked = ctx.input(|i| i.viewport().close_requested());
        if asked && !self.quitting && self.prefs.minimize_to_tray && self.tray_available() {
            ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
            if !self.window_hidden {
                self.hide_to_tray(ctx);
            }
        }
    }

    /// Close the window for good.
    pub fn quit(&mut self, ctx: &egui::Context) {
        self.quitting = true;
        ctx.send_viewport_cmd(egui::ViewportCommand::Close);
    }

    /// Off to the notification area. On Windows the window leaves the
    /// taskbar and minimizes instead of hiding (see `tray::to_tray`).
    pub fn hide_to_tray(&mut self, ctx: &egui::Context) {
        if cfg!(windows) {
            // Its bounds now: once it's a tool window they read differently.
            self.window_place = crate::window_place::read(self.hwnd).or(self.window_place);
            crate::tray::to_tray(self.hwnd);
        } else {
            ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
        }
        self.window_hidden = true;
        log::info!("window: hidden in the notification area");
    }

    /// Bring the window back from the notification area (or up from the
    /// taskbar, if it was only minimized).
    fn show_window(&mut self, ctx: &egui::Context) {
        if cfg!(windows) && self.window_hidden {
            crate::tray::from_tray(self.hwnd);
            // Its taskbar button is a new one: put the badge back on it once
            // the taskbar has made it.
            self.badge = crate::tray::Badge::None;
            self.badge_at = Some(Instant::now());
            ctx.request_repaint_after(Duration::from_millis(1100));
        } else {
            ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
            ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
        }
        ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
        self.window_hidden = false;
    }

    /// Keep where the window is for the next start (on exit).
    fn save_window_place(&mut self) {
        // In the tray, its bounds are the ones kept when it went there.
        if !self.window_hidden {
            self.window_place = crate::window_place::read(self.hwnd).or(self.window_place);
        }
        if let Some(place) = &self.window_place {
            crate::window_place::save(self.window_file.as_deref(), place);
        }
    }

    /// What was picked on the tray icon.
    fn tray_actions(&mut self, ctx: &egui::Context) {
        let picks: Vec<crate::tray::TrayAction> = match &self.tray {
            Some(rx) => rx.try_iter().collect(),
            None => return,
        };
        use crate::tray::TrayAction;
        for pick in picks {
            match pick {
                TrayAction::Open | TrayAction::About => {
                    self.show_window(ctx);
                    if pick == TrayAction::About {
                        self.settings_tab = SettingsTab::About;
                        self.settings_open = true;
                    }
                }
                TrayAction::Notification => {
                    self.show_window(ctx);
                    if let Some((guild, channel)) = self.notified.take().filter(|(_, c)| self.store.channels.contains_key(c)) {
                        self.settings_open = false;
                        self.select_guild(guild);
                        self.select_channel(Some(channel));
                    }
                }
                TrayAction::Quit => self.quit(ctx),
                TrayAction::Restart => self.restart(ctx),
                // Linux: the desktop's notification-area host went away or
                // came back. Never leave the window hidden without an icon.
                #[cfg(target_os = "linux")]
                TrayAction::TrayUp => self.tray_usable = true,
                #[cfg(target_os = "linux")]
                TrayAction::TrayDown => {
                    self.tray_usable = false;
                    if self.window_hidden {
                        self.show_window(ctx);
                    }
                }
                TrayAction::Reset => {
                    // Like Vesktop's "Reset": log out, forget every setting and
                    // the cache, start fresh. (The log stays for diagnostics.)
                    // This RustCord closes right after: give Discord a moment to
                    // end the session first.
                    let deadline = Instant::now() + Duration::from_secs(4);
                    for ended in self.logout_everywhere() {
                        let _ = ended.recv_timeout(deadline.saturating_duration_since(Instant::now()));
                    }
                    if let Some(d) = directories::ProjectDirs::from("dev", "RustCord", "RustCord") {
                        if let Ok(entries) = std::fs::read_dir(d.config_dir()) {
                            for e in entries.flatten() {
                                let p = e.path();
                                if p.file_name().and_then(|n| n.to_str()) == Some("rustcord.log") {
                                    continue;
                                }
                                crate::cache::remove_tree(&p);
                            }
                        }
                        crate::cache::remove_tree(d.cache_dir());
                    }
                    log::info!("tray: reset RustCord (settings and cache cleared)");
                    self.restart(ctx);
                }
            }
        }
    }

    /// Start a fresh RustCord and close this one (the new one takes over).
    /// An installed copy starts the installed program: after an update, the
    /// new version.
    pub fn restart(&mut self, ctx: &egui::Context) {
        if let Some(exe) = self.updater.as_ref().map(|u| u.exe()).or_else(|| std::env::current_exe().ok()) {
            let args: Vec<String> = std::env::args().skip(1).collect();
            let mut cmd = std::process::Command::new(exe);
            cmd.args(args).env_remove("RUSTCORD_KEEP_OTHERS");
            match cmd.spawn() {
                Ok(_) => log::info!("tray: restarting"),
                Err(e) => log::warn!("tray: couldn't restart: {e}"),
            }
        }
        self.quit(ctx);
    }

    /// Ctrl + R, like Discord: reload the client where it stands. The session
    /// starts over (a new connection and a fresh READY), everything loaded so
    /// far (messages, member lists, profiles, pictures, playing GIFs) is
    /// dropped and loaded again, calls end, whatever was open closes, and you
    /// stay in the chat you were in. Drafts and unsent attachments are kept.
    pub fn refresh(&mut self, ctx: &egui::Context) {
        if self.screen != Screen::Main {
            return;
        }
        let Some(token) = self.token.clone() else { return };
        log::info!("refresh: reloading the client (Ctrl+R)");
        let place = (self.current_guild, self.current_channel);
        self.save_nav();
        self.leave_voice();
        let last_channel = std::mem::take(&mut self.last_channel);
        let channel_scroll = std::mem::take(&mut self.channel_scroll);
        let drafts = std::mem::take(&mut self.drafts);
        self.reset_session();
        self.last_channel = last_channel;
        self.channel_scroll = channel_scroll;
        self.drafts = drafts;
        // Reopened once the servers are known again (as after a restart).
        self.restore_nav = Some(place);
        self.close_session_ui();
        self.forget_loaded();

        // Pictures and clips: downloaded files, decoded frames and textures all
        // go (files come back from the disk cache), and the memory with them.
        ctx.forget_all_images();
        crate::diagnostics::release_unused_memory();

        // A new session, exactly as at start-up: the last snapshot of the
        // account shows while the gateway connects.
        self.start_session(self.account, token);
        ctx.request_repaint();
    }

    /// Close whatever is open: it belonged to the session that is ending.
    fn close_session_ui(&mut self) {
        self.settings_open = false;
        self.shortcuts_open = false;
        self.emoji_picker = None;
        self.forward = None;
        self.profile = None;
        self.full_profile = None;
        self.pins = None;
        self.pin_confirm = None;
        self.threads_popout = None;
        self.interaction = None;
        self.interaction_failed = None;
        self.bot_modal = None;
        self.open_select = None;
        self.inbox = None;
        self.gif_picker = None;
        self.custom_status_dialog = None;
        self.reactions_dialog = None;
        self.viewer = None;
        self.tag_popout = None;
        self.sticker_popout = None;
        self.tag_picker = None;
        self.server_menu = None;
        self.server_dialog = None;
        self.add_server = None;
        self.open_when_joined = None;
        self.gateway_session = None;
        self.invite = None;
        self.request_preview = None;
        self.account_menu = None;
        self.manage_accounts = None;
        self.switcher = None;
        self.friend_menu = None;
        self.dm_menu = None;
        self.group_invite = None;
        self.group_leave = None;
        self.badge_window = None;
        self.badges_view = None;
        self.search = None;
        self.share_picker = None;
        self.channel_drag = None;
        self.new_since = None;
        self.pending_jump = None;
        self.pending_dm = None;
        self.hover_prefetch = None;
        // Players stop: the inline video, a provider's player, a quest video.
        self.video_player = None;
        self.video_channel = None;
        self.embed_view = None;
        self.embed_request = None;
        self.pending_place = None;
        self.quest_video = None;
    }

    /// Drop everything fetched for the session (fetched again as needed).
    fn forget_loaded(&mut self) {
        self.profiles.clear();
        self.profile_requested.clear();
        self.guild_profiles.clear();
        self.api_results.clear();
        self.api_pending.clear();
        self.apps.clear();
        self.apps_requested.clear();
        self.member_windows.clear();
        self.request_previews.clear();
        self.revealed.clear();
        self.unread_marker.clear();
        self.calls.clear();
        self.dismissed_calls.clear();
        self.gif_trending = None;
        self.quests = None;
        self.shop = None;
        self.nitro = None;
        self.orbs = None;
    }

    /// Log out the running account: the session is ended at Discord, and its
    /// login and everything kept for it are forgotten here. Another saved
    /// account takes over if there is one. The receiver hears when Discord has
    /// answered (None in the demo, which has no session).
    pub fn logout(&mut self) -> Option<std::sync::mpsc::Receiver<()>> {
        let (done, ended) = std::sync::mpsc::channel();
        self.backend.send(Command::Logout { done: Some(done) });
        // (The demo has no login of its own: the saved ones and their caches
        // are real accounts', and stay.)
        if self.demo {
            self.leave_account(None);
            self.start_session(None, "demo".into());
            return None;
        }
        self.account_gone();
        Some(ended)
    }

    /// Log out every saved account (Reset). The receivers hear when Discord
    /// has answered for each.
    fn logout_everywhere(&mut self) -> Vec<std::sync::mpsc::Receiver<()>> {
        let mut ended = Vec::new();
        let others: Vec<Id> = self.accounts.list.iter().map(|a| a.id).filter(|&id| Some(id) != self.account).collect();
        for id in others {
            if let Some(token) = crate::accounts::token(id) {
                let (done, rx) = std::sync::mpsc::channel();
                self.backend.send(Command::EndSession { token, done: Some(done) });
                ended.push(rx);
            }
            self.accounts.forget(id);
        }
        ended.extend(self.logout());
        ended
    }

    /// The running account is gone (logged out, or Discord ended its session):
    /// it is forgotten here, and the next saved account takes over, or the
    /// login page shows when there is none.
    fn account_gone(&mut self) {
        // (Its place isn't saved: everything of it is being forgotten.)
        if let Some(id) = self.account.take() {
            self.accounts.forget(id);
        }
        let next = self.accounts.list.iter().find_map(|a| crate::accounts::token(a.id).map(|t| (a.id, t)));
        self.leave_account(next.as_ref().map(|(id, _)| *id));
        match next {
            Some((id, token)) => {
                self.accounts.set_active(id);
                self.start_session(Some(id), token);
            }
            None => {
                // The last account: what they all shared goes too (pictures,
                // the provider players' sign-ins).
                crate::cache::clear_shared();
                self.token = None;
                self.screen = Screen::Login;
            }
        }
    }

    fn reset_session(&mut self) {
        self.store = Store::default();
        self.registry.clear();
        self.registry_asked.clear();
        self.registry_wanted.borrow_mut().clear();
        self.registry_for = None;
        // Linked accounts and playlists belong to the account that just left.
        self.api_results.remove("us:connections");
        self.api_results.remove("spotify:playlists");
        self.conn = ConnState::Offline;
        self.current_guild = None;
        self.current_channel = None;
        self.last_channel.clear();
        self.channel_scroll.clear();
        self.channel_scroll_restored.clear();
        self.drafts.clear();
        self.reply = None;
        self.editing = None;
        self.context_menu = None;
    }

    // ---- events -----------------------------------------------------------

    pub fn pump_events(&mut self) {
        // (What a replaced session still sends is dropped.)
        let events: Vec<Event> = self.backend.rx.try_iter().filter(|(s, _)| s.is_none_or(|s| s == self.session)).map(|(_, e)| e).collect();
        for e in events {
            self.handle_event(e);
        }
    }

    fn handle_event(&mut self, event: Event) {
        match event {
            Event::Gateway(g) => match g {
                GatewayEvent::Connecting => {
                    if self.conn != ConnState::Online {
                        self.conn = ConnState::Connecting;
                    }
                }
                GatewayEvent::Connected => {
                    log::info!("gateway: connected");
                    self.conn = ConnState::Online
                }
                GatewayEvent::Disconnected { reason } => {
                    log::warn!("gateway: disconnected: {reason}");
                    self.conn = ConnState::Reconnecting(reason)
                }
                // Discord replaced this login's token (READY brought the new
                // one): requests use it from now on, and it is the one kept
                // for next time.
                GatewayEvent::TokenRefreshed(token) => {
                    let old = self.token.as_deref().map(crate::accounts::token_tag).unwrap_or_default();
                    log::info!("accounts: login {old} replaced by {}", crate::accounts::token_tag(&token));
                    if let Some(id) = self.account.or_else(|| crate::accounts::token_user(&token)) {
                        self.accounts.add(id, &token);
                        log::info!("accounts: Discord replaced the login token; the new one is saved");
                    }
                    self.token = Some(token.clone());
                    self.backend.send(Command::Token(token));
                }
                GatewayEvent::Fatal(e) => {
                    log::error!("gateway: fatal: {e}");
                    self.conn = ConnState::Failed(e)
                }
                GatewayEvent::AuthFailed => {
                    log::warn!("gateway: Discord rejected the session (login {})", self.token.as_deref().map(crate::accounts::token_tag).unwrap_or_default());
                    let name = self.store.me.as_ref().map(|me| me.username.clone());
                    self.account_gone();
                    let text = match name {
                        Some(n) => format!("Discord ended {n}'s session. Log in again."),
                        None => "Discord ended this session. Log in again.".to_string(),
                    };
                    if self.screen == Screen::Login {
                        self.login.notice = Some(text);
                    } else {
                        self.toast(text, true);
                    }
                }
                GatewayEvent::Dispatch { name, data } => self.handle_dispatch(&name, data),
            },
            Event::Messages { channel, before, result } => match result {
                Ok(msgs) => {
                    // History has no member objects: ask the gateway for the
                    // authors' roles and nicknames (name colours, like Discord).
                    if let Some(guild) = self.store.channels.get(&channel).and_then(|c| c.guild_id) {
                        let users = self.store.unknown_members(guild, &msgs);
                        for chunk in users.chunks(100) {
                            for u in chunk {
                                self.store.members_requested.insert((guild, *u));
                            }
                            self.backend.send(Command::RequestMembers { guild, users: chunk.to_vec() });
                        }
                    }
                    self.store.add_history(channel, before, msgs);
                    if let Some((c, msg, attempt)) = self.pending_jump.filter(|(c, _, _)| *c == channel) {
                        self.jump_to_message(c, msg, attempt);
                    }
                    // Like Discord, keep at least today's messages: load older
                    // pages until the oldest is from before midnight.
                    self.load_until_today(channel);
                    // Once that settles, keep the newest messages (all of
                    // today's) on disk for the next time.
                    if let (false, Some(account)) = (self.demo, self.account) {
                        if let Some(cm) = self.store.messages.get(&channel).filter(|cm| !cm.loading) {
                            crate::cache::save_messages(account, channel, &cm.list);
                        }
                    }
                }
                Err(e) => {
                    let cm = self.store.messages.entry(channel).or_default();
                    cm.loading = false;
                    cm.error = Some(e.clone());
                    self.toast(format!("Couldn't load messages: {e}"), true);
                }
            },
            Event::SendCaptcha { msg, challenge } => {
                log::info!("captcha: Discord wants one for a message to {}", msg.channel_id);
                // One at a time: a second challenged message fails like before.
                if let Some(old) = self.captcha.replace(CaptchaPrompt { msg: *msg, friend: None, friend_stranger: false, server: None, challenge, view: None, rect: None, error: None }) {
                    self.send_failed(old.msg.channel_id, &old.msg.nonce);
                }
            }
            Event::FriendCaptcha { user, challenge, stranger } => {
                log::info!("captcha: Discord wants one for a friend request to {user}");
                if let Some(old) = self.captcha.replace(CaptchaPrompt { msg: Default::default(), friend: Some(user), friend_stranger: stranger, server: None, challenge, view: None, rect: None, error: None }) {
                    self.send_failed(old.msg.channel_id, &old.msg.nonce);
                }
            }
            Event::AddServer { request, result, captcha } => self.add_server_done(request, result, captcha),
            Event::SpotifyPlayer(result) => self.spotify_player_answer(result),
            Event::SpotifyMyPlaylists(result) => self.spotify_playlists_answer(result),
            Event::SpotifyFailed(e) => {
                self.toast(e, true);
                self.backend.send(Command::Spotify(crate::backend::SpotifyRequest::State));
            }
            Event::FriendStranger { user } => self.stranger_confirm = Some(user),
            Event::RelationshipDone { user } => {
                self.relationship_busy.remove(&user);
            }
            Event::SendFailed { channel, nonce, error } => {
                log::warn!("send: message to {channel} failed: {error}");
                if let Some(cm) = self.store.messages.get_mut(&channel) {
                    for m in cm.list.iter_mut() {
                        if m.meta.pending && m.nonce_string().as_deref() == Some(nonce.as_str()) {
                            m.meta.pending = false;
                            m.meta.failed = true;
                            m.meta.uploading = 0;
                        }
                    }
                }
                self.toast(format!("Message failed to send: {error}"), true);
            }
            Event::Error(e) => self.toast(e, true),
            Event::Bytes { url, result } if self.soundboard.pending.contains_key(&url) => {
                self.soundboard_bytes(&url, result.as_ref().ok().cloned());
                if let Ok(bytes) = result {
                    self.audio.remember(url, bytes);
                }
            }
            Event::Bytes { url, result } if crate::audio::Cue::from_url(&url).is_some() => {
                match (crate::audio::Cue::from_url(&url), result) {
                    (Some(cue), Ok(bytes)) => self.audio.cue_downloaded(cue, bytes),
                    (_, Err(e)) => log::warn!("voice cue: couldn't download {url}: {e}"),
                    _ => {}
                }
            }
            Event::Bytes { url, result } => match result {
                Ok(bytes) => {
                    self.audio.remember(url.clone(), bytes.clone());
                    if self.audio.waiting_for.as_deref() == Some(url.as_str()) {
                        if let Err(e) = self.audio.start(&url, bytes) {
                            self.toast(e, true);
                        }
                    }
                }
                Err(e) => {
                    self.audio.waiting_for = None;
                    self.toast(format!("Couldn't download the file: {e}"), true);
                }
            },
            Event::Pins { channel, result } => {
                if let Some(p) = self.pins.as_mut().filter(|p| p.0 == channel) {
                    p.2 = Some(result);
                }
            }
            Event::PinFailed { channel, msg, pinned, error } => {
                // Undo the optimistic change, in the chat and in the open popout.
                if let Some(m) = self.store.message_mut(channel, msg) {
                    m.pinned = !pinned;
                }
                if self.pins.as_ref().is_some_and(|p| p.0 == channel) {
                    self.backend.send(crate::backend::Command::FetchPins(channel));
                }
                self.toast(format!("Couldn't {} the message: {error}", if pinned { "pin" } else { "unpin" }), true);
            }
            Event::Search { query, result } => {
                if self.search.as_ref().is_some_and(|s| s.0 == query) {
                    self.search = Some((query, Some(result)));
                }
            }
            Event::Info(text) => self.toast(text, false),
            Event::GroupLeft(channel) => self.remove_channel_and_navigate(channel, None),
            Event::Apps(apps) => {
                for a in apps {
                    self.apps.insert(a.id, a);
                }
            }
            Event::RequestPreviews(list) => {
                for (ch, m) in list {
                    self.request_previews.insert(ch, m);
                }
            }
            Event::FriendRequest(r) => match r {
                Ok(name) => {
                    self.add_friend_input.clear();
                    self.toast(format!("Success! Your friend request to {name} was sent."), false);
                }
                Err(e) => self.toast(format!("Hm, didn't work: {e}"), true),
            },
            Event::Invite { channel, result } => {
                // One asked for from a profile's "Invite to Server" goes to them.
                if let Some(at) = self.profile_invites.iter().position(|(c, _)| *c == channel) {
                    let (_, user) = self.profile_invites.remove(at);
                    self.send_profile_invite(user, result);
                } else {
                    match self.invite.as_mut().filter(|m| m.channel == channel) {
                        Some(m) => m.link = Some(result),
                        None => {
                            if let Err(e) = result {
                                self.toast(format!("Couldn't create an invite: {e}"), true);
                            }
                        }
                    }
                }
            }
            Event::Ignored { user, on, result } => match result {
                Ok(()) => {
                    let known = self.store.relationships.entry(user).or_insert_with(|| discord::model::Relationship { id: user, kind: 0, user_ignored: false, nickname: None, user: None, since: None });
                    known.user_ignored = on;
                    self.toast(if on { "You're ignoring them now." } else { "You're no longer ignoring them." }, false);
                }
                Err(e) => self.toast(format!("Couldn't {}: {e}", if on { "ignore them" } else { "stop ignoring them" }), true),
            },
            Event::InviteSent { user, result } => {
                if let Some(m) = self.invite.as_mut() {
                    m.sent.insert(user, Some(result.is_ok()));
                }
                if let Err(e) = result {
                    self.toast(format!("Couldn't send the invite: {e}"), true);
                }
            }
            Event::GuildProfile { guild, result } => {
                self.guild_profiles.insert(guild, result);
            }
            Event::Mentions(result) => {
                if let Some(inbox) = self.inbox.as_mut() {
                    inbox.1 = Some(result);
                }
            }
            Event::Gifs { query, result } => {
                if let (None, Ok(list)) = (&query, &result) {
                    // Keep trending for the next time the picker opens. (Nothing is
                    // downloaded ahead of that: a provider without stills made
                    // "the first stills" a dozen whole GIFs, 10-16 MB apiece,
                    // fetched and decoded at every start for a picker that
                    // may never be opened.)
                    self.gif_trending = Some(list.clone());
                }
                if let Some(g) = self.gif_picker.as_mut().filter(|g| g.query == query) {
                    g.results = Some(result);
                }
            }
            Event::Quests(result) => match result {
                Ok((list, orbs)) => {
                    self.quests = Some(Ok(list));
                    if orbs.is_some() {
                        self.orbs = orbs;
                    }
                }
                // Keep what RustCord had if a refresh fails.
                Err(e) if !matches!(self.quests, Some(Ok(_))) => self.quests = Some(Err(e)),
                Err(e) => log::warn!("quests: {e}"),
            },
            Event::Shop(result) => self.shop = Some(result),
            Event::Nitro(result) => self.nitro = Some(result),
            Event::Voice(gen, e) => self.on_voice_event(gen, e),
            Event::Camera(result) => self.on_camera(result),
            Event::CameraFeeds(feeds) => self.camera.set_feeds(feeds),
            Event::Stream(gen, e) => self.on_stream_event(gen, e),
            Event::StreamHandle(gen, own, watch) => self.on_stream_handle(gen, own, watch),
            // The POST of a button click / form: only a failure matters
            // (the answer itself comes over the gateway).
            Event::Api { tag, result } if tag.starts_with("interact:") => {
                self.api_pending.remove(&tag);
                if let Err(e) = result {
                    log::warn!("interaction: {e}");
                    self.interaction_done(&tag["interact:".len()..], false);
                }
            }
            Event::Api { tag, result } => {
                self.api_pending.remove(&tag);
                let settings = tag == "us:settings";
                self.api_results.insert(tag, result);
                if settings {
                    self.apply_discord_settings();
                }
            }
            Event::Settings(s) => {
                log::info!("settings: {} folders, status {}", s.folders.len(), s.status);
                self.apply_account_settings(s, true);
            }
            Event::Profile { user, guild, result } => {
                if Some(user) == self.store.me_id() {
                    if let Ok(p) = &result {
                        log::info!("profile: your theme colours {:06x?} (server profile: {})", p.theme_colors(), guild.is_some());
                    }
                }
                self.profiles.insert((user, guild), result);
            }
            Event::DmOpened(v) => {
                self.store.upsert_channel(&v);
                if let Some(id) = Id::from_value(&v["id"]) {
                    self.current_guild = None;
                    self.select_channel(Some(id));
                    let recipient = self.store.channels.get(&id).and_then(|c| c.recipients.first()).map(|u| u.id);
                    if let Some((user, text)) = self.pending_dm.take() {
                        if Some(user) == recipient {
                            self.ensure_loaded(id);
                            self.send_message(id, text);
                        }
                    }
                }
            }
            Event::Theme { source, result } => match result {
                Ok(css) => {
                    self.theme_css = css;
                    self.theme_status = format!("Loaded {source}");
                    self.apply_theme();
                }
                Err(e) => self.theme_status = format!("Couldn't load {source}: {e}"),
            },
            Event::Rpc(e) => {
                match e {
                    crate::rpc::RpcEvent::Activity { socket, client_id, activity: Some(a) } => {
                        self.rpc_activities.insert(socket, (client_id, a));
                    }
                    crate::rpc::RpcEvent::Activity { socket, activity: None, .. } | crate::rpc::RpcEvent::Closed { socket } => {
                        self.rpc_activities.remove(&socket);
                    }
                }
                self.sync_rpc_presence();
            }
            Event::Registry(answer) => {
                let at = Instant::now();
                for (user, row) in answer.users {
                    self.registry.insert(user, (row, answer.now, at));
                }
            }
            Event::CachedReady(v) => {
                // Only while nothing live has arrived yet: the real READY
                // replaces all of this (and marks loaded messages stale).
                if self.store.me.is_some() || self.screen != Screen::Main {
                    return;
                }
                let start = Instant::now();
                // Your folders and theme as they were (the status comes live).
                if let Some(s) = v["user_settings_proto"].as_str().and_then(|b| discord::settings_proto::decode(b).ok()) {
                    self.apply_account_settings(s, false);
                }
                self.store.load_ready(&v);
                self.rencord.set_me(self.store.me_id());
                self.remember_account();
                log::info!(
                    "cache: showing {} servers and {} channels from the last session ({} ms; {} ms after start) while connecting",
                    self.store.guilds.len(),
                    self.store.channels.len(),
                    start.elapsed().as_millis(),
                    crate::diagnostics::ms_since_start()
                );
                if self.current_channel.is_none() {
                    if crate::diagnostics::dev_var("RUSTCORD_DEV_VIEW").as_deref() == Ok("home") {
                        self.select_guild(None);
                    } else if !self.restore_saved_nav() {
                        self.select_guild(self.store.guild_order.first().copied());
                    }
                }
            }
        }
    }

    fn handle_dispatch(&mut self, name: &str, d: Value) {
        match name {
            "READY" => {
                self.gateway_session = d["session_id"].as_str().map(String::from);
                // Discord's sounds: from the cache, or fetched from Discord now.
                for url in self.audio.load_cues() {
                    self.backend.send(Command::FetchBytes(url));
                }
                // Calls don't survive a new session; Discord announces the live ones again.
                self.calls.clear();
                log::info!("gateway: READY received ({} ms after start), loading account data", crate::diagnostics::ms_since_start());
                self.store.load_ready(&d);
                log::info!(
                    "gateway: loaded {} servers, {} channels, {} relationships",
                    self.store.guilds.len(),
                    self.store.channels.len(),
                    self.store.relationships.len()
                );
                self.rencord.set_me(self.store.me_id());
                // Rich Presence: who games talk to, Discord's "share my activity"
                // setting, and (after a fresh session) the games' activities again.
                if let Some(me) = &self.store.me {
                    let user = serde_json::json!({
                        "id": me.id.to_string(), "username": me.username, "discriminator": "0",
                        "global_name": me.global_name, "avatar": me.avatar, "bot": false, "flags": 0,
                        "premium_type": me.premium_type.unwrap_or(0),
                    });
                    self.backend.send(crate::backend::Command::RpcUser(user));
                }
                self.api_get_once("us:settings", "/users/@me/settings");
                self.start_registry(false);
                self.rpc_sent = None;
                // (A new session starts with a bare presence: Spotify is told again.)
                self.spotify_fresh = true;
                self.spotify_at = None;
                self.sync_rpc_presence();
                let still_exists = self.current_channel.is_some_and(|c| self.store.channels.contains_key(&c));
                if crate::diagnostics::dev_var("RUSTCORD_DEV_VIEW").as_deref() == Ok("home") && self.current_channel.is_none() {
                    self.select_guild(None);
                } else if !still_exists && !self.restore_saved_nav() {
                    self.select_guild(self.store.guild_order.first().copied());
                } else if let Some(c) = self.current_channel {
                    // New session after a reconnect: subscriptions are gone.
                    self.subscribe_members(c);
                }
                // (So is the one for the server of the call you're in.)
                if let Some(guild) = self.voice.as_ref().and_then(|v| v.guild) {
                    self.backend.send(Command::SubscribeGuild(guild));
                }
                self.dev_view_after_ready();
                self.warm_up();
                self.voice_after_ready();
                // Your own card (account menu, popouts) opens complete.
                if let (Some(me), false) = (self.store.me_id(), self.demo) {
                    self.want_profile(me, None);
                }
                if !self.demo {
                    self.remember_account();
                }
                if let (false, Some(account)) = (self.demo, self.account) {
                    crate::cache::save_ready(account, d);
                }
            }
            "GUILD_UPDATE" => self.store.guild_update(&d),
            "GUILD_EMOJIS_UPDATE" => self.store.guild_emojis_update(&d),
            "GUILD_STICKERS_UPDATE" => self.store.guild_stickers_update(&d),
            // A command or button you used got no answer in time.
            "INTERACTION_FAILURE" => {
                if !self.interaction_done(d["nonce"].as_str().unwrap_or(""), false) {
                    self.toast("The application did not respond.", true);
                }
            }
            "INTERACTION_SUCCESS" => {
                self.interaction_done(d["nonce"].as_str().unwrap_or(""), true);
            }
            "INTERACTION_CREATE" => log::debug!("interaction accepted"),
            // An app answered a button or command with a form to fill in.
            "INTERACTION_MODAL_CREATE" => self.open_bot_modal(&d),
            "MESSAGE_POLL_VOTE_ADD" => self.store.poll_vote_event(true, &d),
            "MESSAGE_POLL_VOTE_REMOVE" => self.store.poll_vote_event(false, &d),
            "MESSAGE_REACTION_ADD_MANY" | "MESSAGE_POLL_VOTE_ADD_MANY" => self.store.add_many(name, &d),
            "PASSIVE_UPDATE_V2" => self.store.passive_update(&d),
            "GUILD_CREATE" => {
                self.store.upsert_guild(&d);
            }
            "GUILD_DELETE" => {
                if !d["unavailable"].as_bool().unwrap_or(false) {
                    if let Some(id) = Id::from_value(&d["id"]) {
                        self.store.remove_guild(id);
                        if self.current_guild == Some(id) {
                            self.select_guild(None);
                        }
                    }
                }
            }
            "CHANNEL_CREATE" | "CHANNEL_UPDATE" | "THREAD_CREATE" | "THREAD_UPDATE" => self.store.upsert_channel(&d),
            "CHANNEL_RECIPIENT_ADD" => self.store.group_recipient(&d, true),
            "CHANNEL_RECIPIENT_REMOVE" => self.store.group_recipient(&d, false),
            "CHANNEL_DELETE" | "THREAD_DELETE" => {
                if let Some(id) = Id::from_value(&d["id"]) {
                    self.remove_channel_and_navigate(id, Id::from_value(&d["parent_id"]));
                }
            }
            "THREAD_LIST_SYNC" => self.store.thread_list_sync(&d),
            "THREAD_MEMBERS_UPDATE" => self.store.thread_members_update(&d),
            // Your own membership of a thread (joined, or its settings changed).
            "THREAD_MEMBER_UPDATE" => {
                if let Some(id) = Id::from_value(&d["id"]) {
                    self.store.joined_threads.insert(id);
                }
            }
            // Something was pinned or unpinned there: the open popout reloads
            // (its list stays up meanwhile).
            "CHANNEL_PINS_UPDATE" => {
                if let Some(ch) = Id::from_value(&d["channel_id"]).filter(|c| self.pins.as_ref().is_some_and(|p| p.0 == *c)) {
                    self.backend.send(crate::backend::Command::FetchPins(ch));
                }
            }
            "GUILD_ROLE_CREATE" | "GUILD_ROLE_UPDATE" => self.store.upsert_role(&d),
            "GUILD_ROLE_DELETE" => self.store.remove_role(&d),
            "GUILD_MEMBER_UPDATE" => {
                if let Some(g) = Id::from_value(&d["guild_id"]) {
                    self.store.remember_member(g, &d);
                }
                self.store.member_update(&d)
            }
            "GUILD_MEMBERS_CHUNK" => {
                if let Some(g) = Id::from_value(&d["guild_id"]) {
                    for m in d["members"].as_array().into_iter().flatten() {
                        self.store.remember_member(g, m);
                        if let Ok(u) = discord::model::User::deserialize(&m["user"]) {
                            self.store.users.entry(u.id).or_insert(u);
                        }
                    }
                }
            }
            "TYPING_START" => self.store.typing_start(&d),
            "MESSAGE_REACTION_ADD"
            | "MESSAGE_REACTION_REMOVE"
            | "MESSAGE_REACTION_REMOVE_ALL"
            | "MESSAGE_REACTION_REMOVE_EMOJI" => self.store.reaction_event(name, &d),
            "MESSAGE_CREATE" => {
                if let (Some(g), Some(member)) = (Id::from_value(&d["guild_id"]), d.get("member")) {
                    let mut m = member.clone();
                    m["user"] = d["author"].clone();
                    self.store.remember_member(g, &m);
                }
                let Ok(mut msg) = Message::deserialize(&d) else { return };
                self.rencord.message_create(&mut msg);
                let channel = msg.channel_id;
                let author = msg.author.id;
                let pings = self.store.mentions_me(&msg);
                // "Only you can see this" replies never make a channel unread.
                let ephemeral = msg.flags & (1 << 6) != 0;
                // (Someone accepting your friend request: its text is your own note,
                // so the alert says what happened instead.)
                let text = if msg.kind == 67 { "Accepted your friend request.".to_string() } else { msg.content.clone() };
                let alert = (pings && !ephemeral).then(|| (msg.guild_id, self.store.nick_in(None, Some(channel), author).unwrap_or_else(|| msg.display_name().to_string()), text));
                if let Some(c) = self.store.channels.get_mut(&channel).filter(|_| !ephemeral) {
                    c.last_message_id = Some(msg.id);
                }
                self.store.typing_stop(channel, author);
                self.store.insert_message(msg);
                if Some(author) == self.store.me_id() {
                    // Your own messages never make a channel unread.
                    self.store.mark_read(channel);
                } else if pings {
                    self.store.read_states.entry(channel).or_default().mentions += 1;
                }
                if let Some((guild, who, text)) = alert {
                    self.message_alert(guild, channel, author, &who, &text);
                }
            }
            // Your settings changed (here or in another Discord app).
            "USER_SETTINGS_PROTO_UPDATE" => {
                let s = &d["settings"];
                if s["type"].as_u64() == Some(1) {
                    if let Some(newer) = s["proto"].as_str().and_then(|b| discord::settings_proto::RawSettings::from_base64(b).ok()) {
                        let mut raw = if d["partial"].as_bool() == Some(false) { Default::default() } else { self.account_proto.clone() };
                        raw.merge(&newer);
                        if let Ok(all) = discord::settings_proto::decode_wire(&raw.to_wire()) {
                            self.apply_account_settings(all, false);
                        }
                    }
                }
            }
            "MESSAGE_ACK" => self.store.message_ack(&d),
            "GUILD_MEMBER_LIST_UPDATE" => self.store.member_list_update(&d),
            "VOICE_STATE_UPDATE" => {
                // Discord's "stream started / ended" sounds: someone in your call (or
                // you) went live or stopped.
                let user = Id::from_value(&d["user_id"]);
                let ours = self.voice.as_ref().filter(|v| v.connected).map(|v| v.channel);
                let live = |app: &Self| user.and_then(|u| app.store.voice_flags.get(&u)).is_some_and(|f| f.streaming);
                let here = |app: &Self| ours.is_some_and(|c| user.is_some_and(|u| app.store.voice.get(&c).is_some_and(|l| l.contains(&u))));
                let (was_live, was_here) = (live(self), here(self));
                self.store.voice_state_update(&d);
                if was_live != live(self) && (was_here || here(self)) {
                    self.voice_cue(if was_live { crate::audio::Cue::StreamEnded } else { crate::audio::Cue::StreamStarted });
                }
                self.voice_dispatch(name, &d);
            }
            // (Several voice changes at once, each as it would come alone.)
            "VOICE_STATE_UPDATE_BATCH" => {
                for vs in d["voice_states"].as_array().into_iter().flatten() {
                    self.handle_dispatch("VOICE_STATE_UPDATE", vs.clone());
                }
            }
            "CALL_CREATE" | "CALL_UPDATE" | "CALL_DELETE" => self.call_dispatch(name, &d),
            "VOICE_SERVER_UPDATE" => self.voice_dispatch(name, &d),
            "VOICE_CHANNEL_EFFECT_SEND" | "SOUNDBOARD_SOUNDS" | "GUILD_SOUNDBOARD_SOUNDS_UPDATE" | "GUILD_SOUNDBOARD_SOUND_CREATE" | "GUILD_SOUNDBOARD_SOUND_UPDATE" | "GUILD_SOUNDBOARD_SOUND_DELETE" => {
                self.soundboard_dispatch(name, &d)
            }
            "STREAM_CREATE" | "STREAM_SERVER_UPDATE" | "STREAM_UPDATE" | "STREAM_DELETE" => self.stream_dispatch(name, &d),
            "PRESENCE_UPDATE" => self.store.presence_update(&d),
            "READY_SUPPLEMENTAL" => {
                // Servers' then friends' copies of each presence; the store
                // keeps the one Discord would show.
                let mp = &d["merged_presences"];
                for g in mp["guilds"].as_array().into_iter().flatten() {
                    for p in g.as_array().into_iter().flatten() {
                        self.store.presence_update(p);
                    }
                }
                for p in mp["friends"].as_array().into_iter().flatten() {
                    self.store.presence_update(p);
                }
                // Servers' voice states come here, not in READY, with the
                // members they involve (a list per server, in the same order).
                let members = d["merged_members"].as_array();
                for (i, g) in d["guilds"].as_array().into_iter().flatten().enumerate() {
                    for vs in g["voice_states"].as_array().into_iter().flatten() {
                        self.store.voice_state_update(vs);
                    }
                    let Some(gid) = Id::from_value(&g["id"]) else { continue };
                    for m in members.and_then(|m| m.get(i)).and_then(Value::as_array).into_iter().flatten() {
                        self.store.remember_member(gid, m);
                    }
                }
                // DMs a client that kept its own list is only now told about.
                for c in d["lazy_private_channels"].as_array().into_iter().flatten() {
                    self.store.add_private_channel(c);
                }
            }
            "RELATIONSHIP_ADD" | "RELATIONSHIP_UPDATE" => self.store.relationship_add(&d),
            "RELATIONSHIP_REMOVE" => self.store.relationship_remove(&d),
            "USER_GUILD_SETTINGS_UPDATE" => self.store.apply_guild_settings(&d),
            // An account was linked or unlinked: the list (Settings →
            // Connections, the /spotify, /roblox… commands) is read again.
            "USER_CONNECTIONS_UPDATE" => {
                self.api_results.remove("us:connections");
                self.api_results.remove("spotify:playlists");
            }
            // A connection's sign-in finished in the browser: Discord hands
            // the provider's code back here to complete the link.
            "USER_CONNECTIONS_CALLBACK" => self.connection_callback(&d),
            "SESSIONS_REPLACE" => self.store.sessions_replace(&d),
            "MESSAGE_UPDATE" => {
                let (Some(channel), Some(id)) = (Id::from_value(&d["channel_id"]), Id::from_value(&d["id"])) else { return };
                let Some(old) = self.store.message(channel, id).cloned() else { return };
                let mut new = old.clone();
                new.apply_partial(&d);
                self.rencord.message_update(&old, &mut new);
                if let Some(slot) = self.store.message_mut(channel, id) {
                    *slot = new;
                }
            }
            "MESSAGE_DELETE" => {
                let (Some(channel), Some(id)) = (Id::from_value(&d["channel_id"]), Id::from_value(&d["id"])) else { return };
                self.delete_message_locally(channel, id);
            }
            "MESSAGE_DELETE_BULK" => {
                let Some(channel) = Id::from_value(&d["channel_id"]) else { return };
                let ids: Vec<Id> = d["ids"].as_array().map(|a| a.iter().filter_map(Id::from_value).collect()).unwrap_or_default();
                for id in ids {
                    self.delete_message_locally(channel, id);
                }
            }
            _ => {}
        }
    }

    fn delete_message_locally(&mut self, channel: Id, id: Id) {
        let action = match self.store.message_mut(channel, id) {
            Some(msg) => self.rencord.message_delete(msg),
            None => return,
        };
        if action == DeleteAction::Remove {
            self.store.remove_message(channel, id);
        }
        if self.editing.as_ref().is_some_and(|e| e.msg == id) {
            self.editing = None;
        }
    }

    // ---- navigation ---------------------------------------------------------

    pub fn select_guild(&mut self, guild: Option<Id>) {
        self.current_guild = guild;
        // (One you can see, and not a kind the channel list leaves out, e.g.
        // the server hub; and still in this server.)
        let remembered = self
            .last_channel
            .get(&guild)
            .copied()
            .filter(|c| self.store.can_open_unasked(*c) && self.store.channels.get(c).is_some_and(|ch| guild == Some(FAVORITES) || ch.guild_id == guild));
        if guild.is_none() && remembered.is_none() {
            // Home opens on the Friends page, like Discord.
            self.select_channel(None);
            self.friends_open = true;
            return;
        }
        let channel = remembered.or_else(|| self.store.first_text_channel(guild));
        self.select_channel(channel);
    }

    /// Reopen the server and channel you had open last time (once the
    /// servers are known). False if there's nothing (left) to reopen.
    fn restore_saved_nav(&mut self) -> bool {
        let Some((guild, channel)) = self.restore_nav.take() else { return false };
        if guild.is_some_and(|g| g != FAVORITES && !self.store.guilds.contains_key(&g)) {
            return false;
        }
        match channel.filter(|c| self.store.can_open_unasked(*c)) {
            Some(c) => {
                self.current_guild = guild;
                self.select_channel(Some(c));
            }
            None => self.select_guild(guild),
        }
        true
    }

    /// Write nav.json. Test windows (started with RUSTCORD_KEEP_OTHERS) don't,
    /// so they can't move your place, unless given their own RUSTCORD_DEV_NAV file.
    pub fn save_nav(&self) {
        self.nav_dirty.set(None);
        let test_window = std::env::var_os("RUSTCORD_KEEP_OTHERS").is_some() && crate::diagnostics::dev_var_os("RUSTCORD_DEV_NAV").is_none();
        if self.demo || self.screen != Screen::Main || test_window {
            return;
        }
        let nav = crate::features::NavState {
            guild: self.current_guild,
            channel: self.current_channel,
            last_channel: self.last_channel.iter().map(|(&g, &c)| (g, c)).collect(),
            collapsed: self.collapsed.iter().copied().collect(),
            channel_scroll: self.channel_scroll.iter().map(|(&g, &y)| (g, y)).collect(),
        };
        crate::features::save_nav(crate::features::nav_file(self.account).as_deref(), &nav);
    }

    /// Keep the switcher's picture of the account as READY has it (and, if
    /// the token didn't say whose it was, the login under its account now).
    fn remember_account(&mut self) {
        let Some(me) = self.store.me.clone() else { return };
        if self.account != Some(me.id) {
            if let Some(token) = &self.token {
                self.accounts.add(me.id, token);
            }
            self.account = Some(me.id);
        }
        self.accounts.update(&me);
    }

    pub fn select_channel(&mut self, channel: Option<Id>) {
        if self.current_channel != channel {
            // Back where you were in that chat, if you'd scrolled up in it.
            self.scroll_restore.set(channel.and_then(|c| self.scroll_marks.borrow().get(&c).map(|&(m, o)| (c, m, o, 0))));
            if let Some((c, m, o, _)) = self.scroll_restore.get() {
                log::info!("nav: putting {c} back at message {m} (+{o:.0} px)");
            }
            self.nav_dirty.set(Some(Instant::now()));
            // Opening a channel with unread messages shows what you missed.
            self.new_since = channel.and_then(|c| self.unread_snapshot(c));
            self.reply = None;
            self.editing = None;
            self.context_menu = None;
            self.emoji_picker = None;
            self.profile = None;
            // Leaving a channel clears its "Mark Unread" line.
            if let Some(old) = self.current_channel {
                self.unread_marker.remove(&old);
            }
        }
        self.current_channel = channel;
        if let Some(c) = channel {
            // Remembered as this server's (or Home's / Favourites') last channel
            // only if it's one of its own.
            let here = self.current_guild;
            if here == Some(FAVORITES) || self.store.channels.get(&c).is_some_and(|ch| ch.guild_id == here) {
                self.last_channel.insert(here, c);
            }
            self.friends_open = false;
            self.store_page = None;
            self.pins = None;
            self.subscribe_members(c);
        }
    }

    /// Remove a deleted or left channel from local state and navigate away if
    /// it was currently open.
    pub fn remove_channel_and_navigate(&mut self, id: Id, parent_id: Option<Id>) {
        let was_open = self.current_channel == Some(id);
        let removed_kind = self.store.channels.get(&id).map(|c| c.kind);
        self.store.remove_channel_by_id(id);
        self.drafts.remove(&id);
        self.uploads.remove(&id);
        self.unread_marker.remove(&id);
        self.calls.remove(&id);
        self.dismissed_calls.remove(&id);
        self.member_windows.remove(&id);
        self.request_previews.remove(&id);
        self.last_channel.retain(|_, ch| *ch != id);
        self.scroll_marks.borrow_mut().remove(&id);
        if self.scroll_restore.get().is_some_and(|(ch, ..)| ch == id) {
            self.scroll_restore.set(None);
        }
        if self.reply.as_ref().is_some_and(|r| r.channel == id) {
            self.reply = None;
        }
        if self.editing.as_ref().is_some_and(|e| e.channel == id) {
            self.editing = None;
        }
        if self.context_menu.is_some_and(|m| m.channel == id) {
            self.context_menu = None;
        }
        if self.dm_menu.is_some_and(|(ch, _, _)| ch == id) {
            self.dm_menu = None;
        }
        if self.channel_menu.is_some_and(|(ch, _, _)| ch == id) {
            self.channel_menu = None;
        }
        if self.group_invite_open(id) {
            self.group_invite = None;
        }
        if self.group_leave.as_ref().is_some_and(|d| d.channel == id) {
            self.group_leave = None;
        }
        if self.pins.as_ref().is_some_and(|p| p.0 == id) {
            self.pins = None;
        }
        if self.new_since.is_some_and(|n| n.channel == id) {
            self.new_since = None;
        }
        if self.ring_when_connected == Some(id) {
            self.ring_when_connected = None;
        }
        if self.camera_when_connected == Some(id) {
            self.camera_when_connected = None;
        }
        if self.call_check == Some(id) {
            self.call_check = None;
        }
        if self.voice.as_ref().is_some_and(|v| v.channel == id) {
            self.leave_voice();
        }
        if was_open {
            let thread_parent = parent_id.filter(|p| {
                removed_kind.is_none_or(discord::model::channel_kind::is_thread)
                    && self.store.channels.get(p).is_some_and(|c| c.kind != discord::model::channel_kind::GUILD_CATEGORY)
            });
            if let Some(parent) = thread_parent {
                self.select_channel(Some(parent));
            } else if let Some(guild) = self.current_guild {
                let next = self.store.first_text_channel(Some(guild));
                self.select_channel(next);
            } else {
                self.select_channel(None);
                self.search = None;
                self.friends_open = true;
                self.requests_open = false;
                self.store_page = None;
            }
        }
    }

    fn nav_here(&self) -> NavEntry {
        NavEntry { guild: self.current_guild, channel: self.current_channel, friends: self.friends_open }
    }

    /// Record where you are for back / forward; call once per frame.
    pub fn track_navigation(&mut self) {
        let here = self.nav_here();
        if self.nav_current == Some(here) {
            return;
        }
        if let Some(prev) = self.nav_current {
            self.nav_back.push(prev);
            if self.nav_back.len() > 100 {
                self.nav_back.remove(0);
            }
            self.nav_forward.clear();
        }
        self.nav_current = Some(here);
    }

    /// Title bar arrows: go back (`forward == false`) or forward in history.
    pub fn navigate_history(&mut self, forward: bool) {
        let (from, to) = if forward { (&mut self.nav_forward, &mut self.nav_back) } else { (&mut self.nav_back, &mut self.nav_forward) };
        // Skip places that no longer exist (left server, closed DM).
        let target = loop {
            let Some(e) = from.pop() else { return };
            let exists = e.guild.map_or(true, |g| g == FAVORITES || self.store.guilds.contains_key(&g))
                && e.channel.map_or(true, |c| self.store.channels.contains_key(&c));
            if exists {
                break e;
            }
        };
        if let Some(cur) = self.nav_current {
            to.push(cur);
        }
        self.current_guild = target.guild;
        self.select_channel(target.channel);
        self.friends_open = target.friends;
        self.nav_current = Some(self.nav_here());
    }

    /// Developer aid for screenshots: RUSTCORD_DEV_VIEW=dm | dm-game |
    /// dm-system | inbox | gif opens that view once connected.
    /// The server the developer hooks act in, with its channels: your own
    /// testing server, "RustCord Testing Branch" or the one
    /// `RUSTCORD_DEV_SERVER` names.
    fn testing_server(&self) -> Option<(Id, Vec<Id>)> {
        let name = crate::diagnostics::dev_var("RUSTCORD_DEV_SERVER").unwrap_or_else(|_| "RustCord Testing Branch".into());
        self.store.guilds.values().find(|g| g.guild.name == name).map(|g| (g.guild.id, g.channels.clone()))
    }

    fn dev_view_after_ready(&mut self) {
        let dev = crate::diagnostics::dev_var("RUSTCORD_DEV_VIEW").unwrap_or_default();
        // `guild:<part of a server's name>` opens that server (its last channel);
        // `guild:<server>/<part of a channel's name>` opens that channel.
        if let Some(spec) = dev.strip_prefix("guild:") {
            let spec = spec.to_lowercase();
            let (part, channel) = spec.split_once('/').map_or((spec.as_str(), None), |(g, c)| (g, Some(c)));
            // An exact name first ("rust" isn't "rust lounge"), then a part.
            let exact = self.store.guilds.values().find(|g| g.guild.name.to_lowercase().trim() == part.trim());
            let found_guild = exact.or_else(|| self.store.guilds.values().find(|g| g.guild.name.to_lowercase().contains(part)));
            if let Some(g) = found_guild.map(|g| (g.guild.id, g.channels.clone())) {
                self.select_guild(Some(g.0));
                // "!boosts" / "!members" / "!shop": open that page.
                let page = match channel {
                    Some("!boosts") => Some(crate::ui::guild_pages::GuildPage::Boosts),
                    Some("!members") => Some(crate::ui::guild_pages::GuildPage::Members),
                    Some("!shop") => Some(crate::ui::guild_pages::GuildPage::Shop),
                    _ => None,
                };
                if let Some(page) = page {
                    self.open_guild_page(g.0, page);
                    return;
                }
                // "!tag": Server Settings → Server Tag.
                if channel == Some("!tag") {
                    self.open_server_tag(g.0);
                    return;
                }
                let found = channel.and_then(|c| {
                    g.1.iter().copied().find(|id| self.store.channels.get(id).is_some_and(|ch| (ch.kind == 0 || discord::model::channel_kind::is_forum(ch.kind)) && ch.name.as_deref().is_some_and(|n| n.to_lowercase().contains(c))))
                });
                if let Some(id) = found {
                    self.select_channel(Some(id));
                }
            }
            return;
        }
        // `wave-big:<user>` / `wave-pill:<user>`: that DM with "Wave to …" forced.
        let wave = dev.strip_prefix("wave-big:").map(|n| (n, false)).or_else(|| dev.strip_prefix("wave-pill:").map(|n| (n, true)));
        // `dm-call`: the first group DM with a call going on, as Discord would
        // announce it: one person live, one being rung (nothing is sent).
        if dev == "dm-call" {
            let group = self.store.dm_list().into_iter().find(|id| self.store.channels.get(id).is_some_and(|c| c.recipients.len() >= 2));
            if let Some(ch) = group {
                let people: Vec<Id> = self.store.channels[&ch].recipients.iter().map(|u| u.id).collect();
                self.store.voice.insert(ch, vec![people[0]]);
                self.store.voice_flags.entry(people[0]).or_default().streaming = true;
                self.calls.insert(ch, crate::voice_call::DmCall { ringing: vec![people[1]] });
            }
            self.current_guild = None;
            self.select_channel(group);
            return;
        }
        // `dm:<part of a username>` opens that 1:1 DM (profile panel and all).
        if let Some(name) = dev.strip_prefix("dm:").or(wave.map(|w| w.0)) {
            let name = name.to_lowercase();
            let pick = self.store.dm_list().into_iter().find(|id| {
                self.store.channels.get(id).is_some_and(|c| {
                    c.kind == discord::model::channel_kind::DM && c.recipients.first().is_some_and(|u| u.username.to_lowercase().contains(&name))
                })
            });
            self.current_guild = None;
            self.select_channel(pick);
            if let (Some(ch), Some((_, compact))) = (pick, wave) {
                self.dev_wave = Some((ch, compact));
            }
            return;
        }
        // `popout:<username>` / `full:<username>`: that person's profile popout
        // or full profile; `popout:<username>@<part of a server's name>` for
        // their profile in that server (roles and all).
        if let Some((full, spec)) = dev.strip_prefix("popout:").map(|s| (false, s)).or_else(|| dev.strip_prefix("full:").map(|s| (true, s))) {
            let (name, server) = spec.split_once('@').map_or((spec, None), |(n, s)| (n, Some(s.to_lowercase())));
            let name = name.to_lowercase();
            // (A server by that very name before one that merely has it in its name.)
            let named = |exact: bool, s: &str| self.store.guilds.values().find(|g| if exact { g.guild.name.to_lowercase() == s } else { g.guild.name.to_lowercase().contains(s) }).map(|g| g.guild.id);
            let guild = server.and_then(|s| named(true, &s).or_else(|| named(false, &s)));
            let exact = self.store.users.values().find(|u| u.username.to_lowercase() == name);
            let user = exact.or_else(|| self.store.users.values().find(|u| u.username.to_lowercase().contains(&name))).cloned();
            if let Some(u) = user {
                match guild {
                    Some(g) => self.select_guild(Some(g)),
                    None => self.current_guild = None,
                }
                if full {
                    self.open_full_profile(u, guild);
                    if let Some(fp) = self.full_profile.as_mut() {
                        fp.opened_frame += 5;
                    }
                } else {
                    self.open_profile(u, guild, Pos2::new(440.0, 120.0));
                    if let Some(p) = self.profile.as_mut() {
                        p.opened_frame += 5;
                    }
                }
            }
            return;
        }
        // `friend-nickname:<part of a username>`: "Add / Change Friend Nickname"
        // for that friend (use it with --demo: Save goes to the account).
        if let Some(name) = dev.strip_prefix("friend-nickname:") {
            let name = name.to_lowercase();
            let friend = self.store.relationships.values().filter(|r| r.kind == 1).map(|r| r.id).find(|id| self.store.users.get(id).is_some_and(|u| u.username.to_lowercase().contains(&name)));
            if let Some(id) = friend {
                self.open_friend_nickname(id);
            }
            return;
        }
        match dev.as_str() {
            // "Accept friend request?" about yourself; Accept sends nothing.
            "stranger-confirm" => {
                self.stranger_confirm = self.store.me_id();
                return;
            }
            // "Briefly leave voice?" before an update; confirming only shows a toast.
            "update-confirm" => {
                self.update_confirm = true;
                return;
            }
            // The captcha dialog with hCaptcha's public test key (it passes without a
            // puzzle); nothing is sent to Discord.
            "captcha" => {
                let challenge = crate::captcha_view::Challenge { sitekey: "10000000-ffff-ffff-ffff-000000000001".into(), rqdata: None, rqtoken: None, session_id: None };
                self.captcha = Some(CaptchaPrompt { msg: Default::default(), friend: None, friend_stranger: false, server: None, challenge, view: None, rect: None, error: None });
                return;
            }
            "favorites" => {
                self.select_guild(Some(FAVORITES));
                return;
            }
            // "Leaving RustCord" for a sample link.
            "leaving" => {
                self.ask_before_leaving("https://example.com/free-nitro?claim=1".into());
                return;
            }
            // A sample spam warning card.
            "spam-warning" => {
                self.spam_warnings.dev_show();
                return;
            }
            // The "Reconnect" notice for the first voice channel (nothing is joined
            // unless it's clicked, and the demo refuses to).
            "voice-notice" => {
                let me = self.store.me_id().map_or(0, |m| m.0);
                let first = self.store.channels.values().find(|c| c.kind == discord::model::channel_kind::GUILD_VOICE).map(|c| c.id.0);
                self.last_call = first.map(|channel| crate::ui::voice_notice::LastCall { user: me, channel });
                return;
            }
            // The Spotify controller, switched on for this run (not saved).
            "spotify" => {
                self.prefs.experiments.spotify_player = true;
                return;
            }
            // The Request Log window, recording for this run (not saved).
            "request-log" => {
                self.prefs.experiments.request_log = true;
                discord::reqlog::set_enabled(true);
                self.request_log.open = true;
                return;
            }
            // "Adopt this server's tag" for the first server with a tag
            // (`tag-adopt:<part of its name>` picks one); nothing is sent.
            v if v.starts_with("tag-adopt") => {
                let want = v.strip_prefix("tag-adopt:").unwrap_or("").to_lowercase();
                let pick = self.store.guild_order.iter().copied().find(|g| {
                    self.store.guilds.get(g).is_some_and(|gs| gs.guild.tag().is_some() && gs.guild.name.to_lowercase().contains(&want))
                });
                if let Some(g) = pick {
                    self.open_tag_adopt(g);
                }
                return;
            }
            // "Add a Server" on one of its pages (landing, intent, customize, join).
            v if v.starts_with("add-server") => {
                self.add_server = Some(crate::ui::add_server::AddServer::dev(v.strip_prefix("add-server:").unwrap_or("")));
                return;
            }
            "account" => {
                let at = Pos2::new(8.0, self.ctx.screen_rect().bottom() - 70.0);
                self.toggle_account_menu(at);
                if let Some(m) = self.account_menu.as_mut() {
                    m.opened_frame += 5;
                }
                return;
            }
            "compose" => {
                if let Some(ch) = self.current_channel {
                    self.drafts.insert(ch, "emoji show while typing 🦀🔥👍 like Discord".into());
                }
                return;
            }
            "requests" => {
                self.current_guild = None;
                self.open_message_requests();
                return;
            }
            "quests" | "shop" | "nitro" | "quest-video" => {
                use crate::features::StorePage;
                self.current_guild = None;
                self.open_store_page(match dev.as_str() {
                    "quests" | "quest-video" => StorePage::Quests,
                    "shop" => StorePage::Shop,
                    _ => StorePage::Nitro,
                });
                return;
            }
            "add-friend" | "pending" | "friend-menu" => {
                self.current_guild = None;
                self.select_channel(None);
                self.friends_open = true;
                self.friends_tab = match dev.as_str() {
                    "pending" => crate::features::FriendsTab::Pending,
                    "friend-menu" => crate::features::FriendsTab::Online,
                    _ => crate::features::FriendsTab::AddFriend,
                };
                if dev == "friend-menu" {
                    // The ⋮ menu of the first online friend, as if clicked.
                    let mut online: Vec<(String, Id)> = self
                        .store
                        .relationships
                        .values()
                        .filter(|r| r.kind == 1 && self.store.status_of(r.id) != "offline")
                        .map(|r| (self.store.users.get(&r.id).map(|u| u.display_name().to_lowercase()).unwrap_or_default(), r.id))
                        .collect();
                    online.sort();
                    if let Some((_, id)) = online.first() {
                        self.friend_menu = Some((*id, Pos2::new(860.0, 320.0), self.ctx.cumulative_pass_nr() + 100, false));
                    }
                }
                return;
            }
            s if s == "settings" || s.starts_with("settings-") => {
                self.settings_open = true;
                self.settings_tab = match dev.as_str() {
                    "settings-accessibility" => SettingsTab::Accessibility,
                    "settings-notifications" => SettingsTab::Notifications,
                    "settings-voice" => SettingsTab::VoiceVideo,
                    "settings-connections" => SettingsTab::Connections,
                    "settings-system" => SettingsTab::System,
                    "settings-about" => SettingsTab::About,
                    "settings-messaging" => SettingsTab::Messaging,
                    "settings-privacy" => SettingsTab::DataPrivacy,
                    "settings-boost" => SettingsTab::ServerBoost,
                    "settings-subscriptions" => SettingsTab::Subscriptions,
                    "settings-gifts" => SettingsTab::GiftInventory,
                    "settings-billing" => SettingsTab::Billing,
                    "settings-activity" => SettingsTab::ActivityPrivacy,
                    "settings-appearance" => SettingsTab::Appearance,
                    "settings-process" => SettingsTab::ProcessViewer,
                    "settings-experimental" => SettingsTab::Experimental,
                    _ => SettingsTab::Account,
                };
                return;
            }
            "voice-test" => {
                // Muted test call in the testing server (nothing is sent from
                // the microphone): in its "rustcord-voice-test" channel, else
                // its first voice channel, else one made for it.
                if let Some((gid, chans)) = self.testing_server() {
                    let voice = |named: Option<&str>| {
                        chans.iter().copied().find(|c| self.store.channels.get(c).is_some_and(|c| c.kind == 2 && named.is_none_or(|n| c.name.as_deref() == Some(n))))
                    };
                    let vc = voice(Some("rustcord-voice-test")).or_else(|| voice(None));
                    match vc {
                        Some(c) => {
                            self.self_mute = true;
                            self.select_guild(Some(gid));
                            self.join_voice(c);
                            log::info!("voice-test: joining {c} muted");
                        }
                        None => {
                            self.backend.send(Command::CreateChannel { guild: gid, body: serde_json::json!({ "name": "rustcord-voice-test", "type": 2 }) });
                            log::info!("voice-test: created a temporary voice channel; run again to join it");
                        }
                    }
                }
                return;
            }
            "plus-menu" | "plus-schedule" | "poll-dialog" | "schedule-dialog" | "schedule-bar" | "stickers" | "apps" | "new-thread" => {
                // The composer's tools, over the testing server's first channel.
                let Some((gid, _)) = self.testing_server() else { return };
                self.select_guild(Some(gid));
                let Some(ch) = self.current_channel else { return };
                let screen = self.ctx.screen_rect();
                let frame = self.ctx.cumulative_pass_nr() + 5;
                let plus = egui::Rect::from_min_size(Pos2::new(crate::ui::GUILD_BAR + crate::ui::SIDEBAR + 20.0, screen.bottom() - 74.0), egui::vec2(44.0, 44.0));
                let right = Pos2::new(screen.right() - crate::ui::MEMBERS - 60.0, screen.bottom() - 74.0);
                use crate::features::*;
                match dev.as_str() {
                    "plus-menu" | "plus-schedule" => {
                        self.compose.plus_menu = Some((ch, plus, frame));
                        if dev == "plus-schedule" {
                            self.ctx.data_mut(|d| d.insert_temp(egui::Id::new("plus_schedule_sub"), true));
                        }
                    }
                    "poll-dialog" => {
                        self.compose.poll = Some(PollDraft {
                            channel: ch,
                            question: "Best snack?".into(),
                            answers: vec![("Crisps".into(), Some(PickedEmoji::Unicode("🥔".into()))), ("Chocolate".into(), None)],
                            hours: 24,
                            multi: false,
                        })
                    }
                    "schedule-dialog" => self.compose.schedule_dialog = Some(ScheduleDraft { channel: ch, date: chrono::Local::now().date_naive(), minutes: 13 * 60 }),
                    "schedule-bar" => {
                        let at = chrono::Local::now() + chrono::Duration::hours(3);
                        self.compose.schedule = Some((ch, at));
                    }
                    "stickers" => self.toggle_expression(ch, ExpressionTab::Stickers, right),
                    "apps" => {
                        self.drafts.insert(ch, "/".into());
                    }
                    _ => self.compose.new_thread = Some(ThreadDraft { channel: ch, name: String::new(), message: String::new(), private: false }),
                }
                return;
            }
            "create-channel" => {
                if let Some((gid, chans)) = self.testing_server() {
                    self.select_guild(Some(gid));
                    let cat = chans.iter().copied().find(|c| self.store.channels.get(c).is_some_and(|c| c.kind == 4));
                    self.server_dialog = Some(crate::features::ServerDialog::CreateChannel { guild: gid, parent: cat, name: String::new(), kind: 0, private: false, category: false });
                }
                return;
            }
            "server-settings" | "channel-settings" => {
                if let Some(g) = self.testing_server() {
                    self.select_guild(Some(g.0));
                    if dev == "server-settings" {
                        self.open_server_settings(g.0);
                    } else if let Some(c) = g.1.iter().copied().find(|c| self.store.channels.get(c).is_some_and(|c| c.kind == 0)) {
                        self.open_channel_settings(c);
                    }
                }
                return;
            }
            "voice-test-cleanup" => {
                let ids: Vec<Id> = self.store.channels.values().filter(|c| c.name.as_deref() == Some("rustcord-voice-test")).map(|c| c.id).collect();
                for id in ids {
                    self.backend.send(Command::DeleteChannel(id));
                    log::info!("voice-test: deleted {id}");
                }
                return;
            }
            "full-profile-me" => {
                // Your own full profile inside the testing server (roles,
                // its icon in Member Since, "Add Connection").
                let guild = self.store.guilds.iter().find(|(_, g)| g.guild.name.contains("Bot Testing")).map(|(id, _)| *id);
                if let Some(me) = self.store.me.clone() {
                    self.open_full_profile(me, guild);
                    if let Some(fp) = self.full_profile.as_mut() {
                        fp.opened_frame += 5;
                    }
                }
                return;
            }
            "full-profile" => {
                // The first friend's full profile (the DM list order).
                let friend = self.store.dm_list().into_iter().filter_map(|c| self.store.channels.get(&c)).find_map(|c| {
                    c.recipients.first().filter(|u| self.store.relationships.get(&u.id).is_some_and(|r| r.kind == 1)).cloned()
                });
                if let Some(u) = friend {
                    self.current_guild = None;
                    self.open_full_profile(u, None);
                    if let Some(fp) = self.full_profile.as_mut() {
                        fp.opened_frame += 5;
                    }
                }
                return;
            }
            "profile-friend" => {
                // The first friend's popout (the DM list order).
                let friend = self.store.dm_list().into_iter().filter_map(|c| self.store.channels.get(&c)).find_map(|c| {
                    c.recipients.first().filter(|u| self.store.relationships.get(&u.id).is_some_and(|r| r.kind == 1)).cloned()
                });
                if let Some(u) = friend {
                    self.current_guild = None;
                    self.open_profile(u, None, Pos2::new(self.ctx.screen_rect().center().x - 150.0, 60.0));
                    if let Some(p) = self.profile.as_mut() {
                        p.opened_frame += 5;
                    }
                }
                return;
            }
            "profile" | "tag" | "viewer" | "server-menu" => {
                let screen = self.ctx.screen_rect();
                let me = self.store.me.clone();
                match (dev.as_str(), me) {
                    ("profile", Some(me)) => self.open_profile(me, self.current_guild, Pos2::new(screen.center().x - 170.0, 60.0)),
                    ("tag", Some(me)) => {
                        if let Some(g) = me.server_tag_guild() {
                            self.open_tag_popout(g, Pos2::new(screen.center().x - 150.0, 140.0));
                            self.tag_popout = self.tag_popout.map(|(g, p, f)| (g, p, f + 5));
                        }
                    }
                    ("viewer", Some(me)) => {
                        let big = me.avatar_animated(1024);
                        self.viewer = Some(crate::features::MediaView { image: big.clone(), video: None, link: big, size: Some((1024.0, 1024.0)) });
                    }
                    ("server-menu", _) => {
                        if let Some(g) = self.current_guild {
                            self.server_menu = Some((g, self.ctx.cumulative_pass_nr() + 5));
                        }
                    }
                    _ => {}
                }
                if let Some(p) = self.profile.as_mut() {
                    p.opened_frame += 5;
                }
                return;
            }
            "dm" | "dm-game" | "dm-system" | "inbox" | "gif" => {}
            _ => return,
        }
        let dms: Vec<Id> = self.store.dm_list();
        let pick = dms.into_iter().find(|id| {
            let Some(c) = self.store.channels.get(id) else { return false };
            let Some(u) = c.recipients.first().filter(|_| c.kind == discord::model::channel_kind::DM) else { return false };
            match dev.as_str() {
                "dm-system" => u.system,
                "dm-game" => self.store.presences.get(&u.id).is_some_and(|p| p.game().is_some()),
                _ => true,
            }
        });
        self.current_guild = None;
        self.select_channel(pick);
        match dev.as_str() {
            "inbox" => {
                let at = Pos2::new(self.ctx.screen_rect().right() - 150.0, 36.0);
                self.inbox = Some((at, None));
                self.inbox_opened_frame = self.ctx.cumulative_pass_nr() + 5;
                self.backend.send(Command::FetchMentions);
            }
            "gif" => {
                if let Some(ch) = pick {
                    // The picker hangs above this point (the composer's top-right corner).
                    let at = Pos2::new(self.ctx.screen_rect().right() - 360.0, self.ctx.screen_rect().bottom() - 76.0);
                    self.toggle_gif_picker(ch, at);
                }
            }
            _ => {}
        }
    }

    /// The other person in the open 1:1 DM (not group DMs).
    pub fn dm_recipient(&self) -> Option<discord::model::User> {
        if self.friends_open || self.current_guild.is_some() {
            return None;
        }
        let c = self.store.channels.get(&self.current_channel?)?;
        (c.kind == discord::model::channel_kind::DM).then(|| c.recipients.first().cloned()).flatten()
    }

    // ---- RustCord registry (the RustCord badge) ---------------------------------

    /// Start the registry loop for the logged-in account (once per account;
    /// `restart` after the "Show that I use RustCord" setting changed).
    pub fn start_registry(&mut self, restart: bool) {
        let Some(me) = self.store.me_id() else { return };
        if !restart && self.registry_for == Some(me) {
            return;
        }
        self.registry_for = Some(me);
        let (share, invisible) = (self.prefs.share_rustcord, self.store.my_status == "invisible");
        // Off, the registry is contacted only once: when you switch it off
        // (to take your badge down), never at start-up.
        let switched_off = restart && self.registry_sent.0 && !share;
        self.registry_sent = (share, invisible);
        if share || switched_off {
            self.backend.send(Command::Registry { me, share, invisible });
        }
    }

    /// Going Invisible (or coming back) restarts the registry loop: while
    /// Invisible it says nothing, so the badge doesn't show you online.
    pub fn registry_tick(&mut self) {
        if self.registry_for.is_some() && self.registry_sent != (self.prefs.share_rustcord, self.store.my_status == "invisible") {
            self.start_registry(true);
        }
    }

    /// Whether `user` is a RustCord user: since when, and whether they're on
    /// it right now (they said hello within the last few minutes). The first
    /// time (and when the answer has gone stale) the registry is asked, and
    /// the badge shows once it answers.
    pub fn rustcord_member(&self, user: Id) -> Option<crate::registry::Membership> {
        let known = self.registry.get(&user);
        if !known.is_some_and(|(_, _, at)| at.elapsed() < crate::registry::ANSWER_FRESH_FOR) {
            self.registry_wanted.borrow_mut().push(user);
        }
        let (row, then, at) = known?;
        let (joined, seen) = (*row)?;
        // The service's clock, carried forward by how long ago it answered.
        let now = then.saturating_add(at.elapsed().as_secs());
        Some(crate::registry::Membership { joined, online: now.saturating_sub(seen) <= crate::registry::ONLINE_FOR_SECS })
    }

    /// Ask the registry about the users whose badge was wanted this frame
    /// (each at most once a minute, answered or not).
    pub fn fetch_wanted_registry(&mut self) {
        let mut wanted: Vec<Id> = std::mem::take(&mut *self.registry_wanted.borrow_mut());
        // With "Show that I use RustCord" off, RustCord doesn't contact the
        // registry at all: no lookups either (they'd tell it whose profiles you open).
        if wanted.is_empty() || self.registry_for.is_none() || !self.prefs.share_rustcord || !(self.demo || crate::registry::url().is_some()) {
            return;
        }
        wanted.sort_unstable();
        wanted.dedup();
        wanted.retain(|u| !self.registry_asked.get(u).is_some_and(|at| at.elapsed() < std::time::Duration::from_secs(60)));
        if wanted.is_empty() {
            return;
        }
        let now = Instant::now();
        self.registry_asked.extend(wanted.iter().map(|u| (*u, now)));
        self.backend.send(Command::RegistryLookup(wanted));
    }

    /// Fetch a profile once (again only if the last try failed and it's been asked for anew).
    // ---- generic REST calls (settings screens) ---------------------------------

    /// Give RAM that isn't being used back to Windows: once when start-up
    /// has settled, and again whenever RustCord has grown well past what it
    /// needs in ordinary use and then gone quiet (a closed GIF picker, a
    /// media channel you scrolled through). Windows keeps the pages cached,
    /// so whatever is still in use comes straight back; the rest stays out.
    /// Not during a call or a stream (those touch their memory all the
    /// time), not while you're doing something, and not while it's growing.
    fn trim_memory(&mut self, ctx: &egui::Context) {
        use std::sync::atomic::{AtomicU64, Ordering};
        /// When it was last looked at / trimmed (seconds since start; 0: never).
        static CHECKED: AtomicU64 = AtomicU64::new(0);
        static LAST: AtomicU64 = AtomicU64::new(0);
        /// What it climbed back to after a trim while nothing was going on:
        /// its size in ordinary use. `SETTLING` gathers that for the trim
        /// just done (only looks taken while quiet count: a GIF picker opened
        /// right after a trim isn't ordinary use).
        static SETTLED: AtomicU64 = AtomicU64::new(0);
        static SETTLING: AtomicU64 = AtomicU64::new(0);
        /// Its size at the last look, and when you last did anything.
        static PREVIOUS: AtomicU64 = AtomicU64::new(0);
        static INPUT: AtomicU64 = AtomicU64::new(0);
        let (now, busy) = ctx.input(|i| (i.time as u64, !i.events.is_empty()));
        if busy {
            INPUT.store(now, Ordering::Relaxed);
        }
        if now < 14 || now < CHECKED.load(Ordering::Relaxed) + 10 {
            return;
        }
        CHECKED.store(now, Ordering::Relaxed);
        let size = crate::diagnostics::working_set_mb();
        let previous = PREVIOUS.swap(size, Ordering::Relaxed);
        let last = LAST.load(Ordering::Relaxed);
        let quiet = now >= INPUT.load(Ordering::Relaxed) + 10 && self.gif_picker.is_none() && self.emoji_picker.is_none();
        let due = if self.voice.is_some() {
            false
        } else if last == 0 {
            true
        } else if now < last + 40 {
            if quiet {
                SETTLING.fetch_max(size, Ordering::Relaxed);
            }
            false
        } else {
            let settling = SETTLING.swap(0, Ordering::Relaxed);
            if settling > 0 {
                SETTLED.store(settling, Ordering::Relaxed);
            }
            let settled = SETTLED.load(Ordering::Relaxed);
            let grown = size > settled + settled / 2 && size > settled + 80;
            grown && quiet && size <= previous && now >= last + 60
        };
        if due {
            crate::diagnostics::trim_working_set();
            LAST.store(now, Ordering::Relaxed);
            SETTLING.store(0, Ordering::Relaxed);
            log::info!("memory: {size} MB in RAM, unused pages handed back to the system");
        }
    }

    /// Call a Discord endpoint; the answer lands in `api_results[tag]`.
    pub fn api(&mut self, tag: &str, method: reqwest::Method, path: impl Into<String>, body: Option<Value>) {
        self.api_results.remove(tag);
        self.api_pending.insert(tag.to_string());
        self.backend.send(Command::Api { tag: tag.to_string(), method, path: path.into(), body });
    }

    /// [`Self::api`], answered whatever the status: `{"status", "body"}`.
    pub fn api_raw(&mut self, tag: &str, method: reqwest::Method, path: impl Into<String>, body: Option<Value>) {
        self.api_results.remove(tag);
        self.api_pending.insert(tag.to_string());
        self.backend.send(Command::ApiRaw { tag: tag.to_string(), method, path: path.into(), body });
    }

    /// [`Self::api`] with an audit-log reason (kicks, bans, timeouts); an
    /// empty reason sends none.
    pub fn api_reason(&mut self, tag: &str, method: reqwest::Method, path: impl Into<String>, body: Option<Value>, reason: &str) {
        let reason = reason.trim();
        if reason.is_empty() {
            return self.api(tag, method, path, body);
        }
        self.api_results.remove(tag);
        self.api_pending.insert(tag.to_string());
        self.backend.send(Command::ApiReason { tag: tag.to_string(), method, path: path.into(), body, reason: reason.to_string() });
    }

    /// A multipart upload (stickers, soundboard sounds): `fields` as text
    /// parts plus `file` = (file name, bytes, MIME type). Answer under `tag`.
    pub fn api_upload(&mut self, tag: &str, path: impl Into<String>, fields: Vec<(String, String)>, file: (String, Vec<u8>, String)) {
        self.api_results.remove(tag);
        self.api_pending.insert(tag.to_string());
        self.backend.send(Command::ApiUpload { tag: tag.to_string(), path: path.into(), fields, file });
    }

    /// Send (or, with `mfa`, send again verified) the account change in
    /// `account_edit.pending`; the answer arrives under "us:acct".
    pub fn account_request(&mut self, mfa: Option<(String, String, String)>) {
        let Some((method, path, body)) = self.account_edit.pending.clone() else { return };
        self.api_results.remove("us:acct");
        self.api_pending.insert("us:acct".to_string());
        self.backend.send(Command::Account { tag: "us:acct".into(), method, path, body, mfa });
    }

    /// GET `path` under `tag` unless it's loaded or loading already.
    pub fn api_get_once(&mut self, tag: &str, path: impl Into<String>) {
        if !self.api_results.contains_key(tag) && !self.api_pending.contains(tag) {
            self.api(tag, reqwest::Method::GET, path, None);
        }
    }

    pub fn api_result(&self, tag: &str) -> Option<&Result<Value, String>> {
        self.api_results.get(tag)
    }

    pub fn api_busy(&self, tag: &str) -> bool {
        self.api_pending.contains(tag)
    }

    /// Take a finished answer (for one-shot actions like "save").
    pub fn api_take(&mut self, tag: &str) -> Option<Result<Value, String>> {
        self.api_results.remove(tag)
    }

    pub fn want_profile(&mut self, user: Id, guild: Option<Id>) {
        if self.profiles.contains_key(&(user, guild)) || !self.profile_requested.insert((user, guild)) {
            return;
        }
        self.backend.send(Command::FetchProfile { user, guild });
    }

    /// Ask Discord for this channel's member list (and typing events).
    pub fn subscribe_members(&mut self, channel: Id) {
        let Some(guild) = self.store.channels.get(&channel).and_then(|c| c.guild_id) else { return };
        let windows = *self.member_windows.entry(channel).or_insert(1);
        self.backend.send(Command::SubscribeMembers { guild, channel, windows });
    }

    /// Where you'd read up to in `ch`, if it has unread messages.
    fn unread_snapshot(&self, ch: Id) -> Option<NewSince> {
        let last_read = self.store.read_states.get(&ch)?.last_read?;
        self.store.is_unread(ch).then_some(NewSince { channel: ch, last_read, bar: true })
    }

    /// Messages arriving in the open channel while RustCord isn't focused:
    /// remember where you'd read up to, so the new-messages bar and the NEW
    /// line are there when you come back.
    fn track_missed(&mut self, ctx: &egui::Context) {
        let Some(ch) = self.current_channel else { return };
        if self.screen != Screen::Main || ctx.input(|i| i.focused) || self.new_since.is_some_and(|n| n.channel == ch && n.bar) {
            return;
        }
        if let Some(n) = self.unread_snapshot(ch) {
            self.new_since = Some(n);
        }
    }

    /// The bar's "Mark As Read" (and Escape): read up to the newest message.
    pub fn mark_channel_read(&mut self, ch: Id) {
        self.unread_marker.remove(&ch);
        if self.new_since.is_some_and(|n| n.channel == ch) {
            self.new_since = None;
        }
        if let Some(msg) = self.store.mark_read(ch) {
            self.last_ack = Some(Instant::now());
            self.backend.send(Command::Ack { channel: ch, msg });
        }
    }

    /// Mark the open channel read (and tell Discord), like the official client
    /// does while you're looking at it. Throttled; skipped after "Mark Unread".
    fn auto_ack(&mut self, ctx: &egui::Context) {
        let Some(ch) = self.current_channel else { return };
        if self.screen != Screen::Main || !ctx.input(|i| i.focused) || self.unread_marker.contains_key(&ch) {
            return;
        }
        if !self.store.messages.get(&ch).is_some_and(|cm| cm.loaded) {
            return;
        }
        // Throttled, but never dropped: with the window idle nothing else
        // would draw a frame, so a channel opened (or a message arriving)
        // within 1.5 s of the last ack stayed unread until the mouse moved.
        const GAP: Duration = Duration::from_millis(1500);
        if let Some(wait) = self.last_ack.map(|t| t.elapsed()).filter(|e| *e < GAP).map(|e| GAP - e) {
            if self.store.is_unread(ch) || self.store.mentions(ch) > 0 {
                ctx.request_repaint_after(wait + Duration::from_millis(20));
            }
            return;
        }
        if let Some(msg) = self.store.mark_read(ch) {
            self.last_ack = Some(Instant::now());
            self.backend.send(Command::Ack { channel: ch, msg });
        }
    }

    /// Request history for a channel if it's not loaded (or stale).
    pub fn ensure_loaded(&mut self, channel: Id) {
        self.store.touch_messages(channel);
        let cm = self.store.messages.entry(channel).or_default();
        if cm.loading || cm.error.is_some() {
            return;
        }
        if !cm.loaded || cm.stale {
            // Show the page you saw last time straight away (from disk) while
            // the fresh one loads; the fresh page then replaces it.
            if !cm.loaded && cm.list.is_empty() && !self.demo {
                if let Some(cached) = self.account.and_then(|a| crate::cache::load_messages(a, channel)) {
                    cm.list = cached;
                    cm.loaded = true;
                    cm.from_cache = true;
                    cm.has_more = true;
                }
            }
            cm.loading = true;
            self.backend.send(Command::FetchMessages { channel, before: None });
        }
    }

    /// Scroll to `msg` and flash it (a reply's original, "View Poll"). If it's
    /// older than what's loaded, load earlier pages until it is (up to 10).
    pub fn jump_to_message(&mut self, channel: Id, msg: Id, attempt: u8) {
        let Some(cm) = self.store.messages.get(&channel) else { return };
        if cm.list.iter().any(|m| m.id == msg) {
            self.pending_jump = None;
            self.ctx.data_mut(|d| d.insert_temp(egui::Id::new(("jump_to", channel.0)), (msg, 0.0f64, false)));
            self.ctx.request_repaint();
            return;
        }
        // An in-flight history request can still contain the target. Retry
        // on completion without charging this jump for a page it didn't request.
        if cm.loading {
            self.pending_jump = Some((channel, msg, attempt));
            return;
        }
        let older = cm.list.first().is_some_and(|first| msg.0 < first.id.0);
        if older && cm.has_more && attempt < 10 {
            self.pending_jump = Some((channel, msg, attempt + 1));
            self.load_older(channel);
        } else {
            self.pending_jump = None;
            self.toast("Couldn't find that message (it may have been deleted).", false);
        }
    }

    /// Load older pages until the channel's oldest loaded message is from
    /// before local midnight. Bounded to 4 pages: opening busy channels must
    /// not page through history on its own (Discord's anti-spam counts it).
    fn load_until_today(&mut self, channel: Id) {
        let Some(cm) = self.store.messages.get(&channel) else { return };
        let today = crate::store::today_start_id();
        if cm.has_more && cm.error.is_none() && cm.list.len() < 200 && cm.list.first().is_some_and(|m| m.id >= today) {
            self.load_older(channel);
        }
    }

    pub fn load_older(&mut self, channel: Id) {
        let Some(cm) = self.store.messages.get_mut(&channel) else { return };
        if cm.loading || !cm.has_more {
            return;
        }
        let before = cm.list.first().map(|m| m.id);
        cm.loading = true;
        cm.error = None;
        self.backend.send(Command::FetchMessages { channel, before });
    }

    pub fn retry_load(&mut self, channel: Id) {
        if let Some(cm) = self.store.messages.get_mut(&channel) {
            cm.error = None;
        }
        self.ensure_loaded(channel);
    }

    // ---- sending ------------------------------------------------------------

    pub fn send_message(&mut self, channel: Id, content: String) {
        let Some(me) = self.store.me.clone() else { return };
        // Talking in a channel catches you up (no more bar or NEW line).
        if self.new_since.is_some_and(|n| n.channel == channel) {
            self.new_since = None;
        }
        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed) & 0xFFF;
        let nonce = Id(Id::from_timestamp_ms(now_ms()).0 | n);
        let guild_id = self.store.channels.get(&channel).and_then(|c| c.guild_id);
        let content = self.expand_shortcodes(&content, channel);
        let content = self.resolve_mentions(&content, channel);

        let reply = self.reply.take().filter(|r| r.channel == channel);
        let mut out = OutgoingMessage {
            channel_id: channel,
            content,
            nonce: nonce.to_string(),
            message_reference: reply
                .as_ref()
                .map(|r| MessageReference { kind: 0, message_id: r.msg, channel_id: channel, guild_id }),
            allowed_mentions: reply.as_ref().filter(|r| !r.mention).map(|_| AllowedMentions {
                parse: vec!["users".into(), "roles".into(), "everyone".into()],
                replied_user: false,
            }),
            ..Default::default()
        };

        if !self.rencord.before_send(&mut out) {
            self.toast("A Rencord plugin blocked this message.", false);
            return;
        }
        out.uploads = self
            .uploads
            .remove(&channel)
            .unwrap_or_default()
            .into_iter()
            .map(|u| discord::model::Upload { filename: u.name, data: u.data })
            .collect();
        if out.content.trim().is_empty() && out.uploads.is_empty() {
            return;
        }
        let uploading = out.uploads.len();

        let referenced = reply
            .as_ref()
            .and_then(|r| self.store.message(channel, r.msg).cloned())
            .map(Box::new);
        let local = Message {
            id: nonce,
            channel_id: channel,
            guild_id,
            author: me,
            content: out.content.clone(),
            timestamp: chrono::Utc::now().to_rfc3339(),
            nonce: Some(Value::String(out.nonce.clone())),
            kind: if referenced.is_some() { 19 } else { 0 },
            referenced_message: referenced,
            meta: LocalMeta { pending: true, uploading, ..Default::default() },
            ..Default::default()
        };
        self.store.insert_message(local);
        self.last_typing_sent = None;
        // (Counts towards Frequently Used, as Discord counts emoji you send.)
        self.track_emoji(crate::ui::emoji_frecency::keys_in_text(&out.content), false);
        self.backend.send(Command::Send(out));
    }

    pub fn maybe_send_typing(&mut self, channel: Id) {
        let fresh = self
            .last_typing_sent
            .is_some_and(|(c, t)| c == channel && t.elapsed() < Duration::from_secs(8));
        if fresh {
            return;
        }
        self.last_typing_sent = Some((channel, Instant::now()));
        if self.rencord.typing(channel) {
            self.backend.send(Command::Typing(channel));
        }
    }

    pub fn start_reply(&mut self, channel: Id, msg: Id) {
        let Some(m) = self.store.message(channel, msg) else { return };
        // Like Discord: replies ping the author, except when it's yourself
        // (or a plugin such as NoReplyMention starts them with "@" off).
        let mine = Some(m.author.id) == self.store.me_id();
        let author_id = m.author.id;
        let author = self.store.nick_in(None, Some(channel), author_id).unwrap_or_else(|| m.display_name().to_string());
        let mention = !mine && self.rencord.reply_mention(channel, author_id);
        self.reply = Some(ReplyTarget { channel, msg, author, mention });
        self.ctx.memory_mut(|mem| mem.request_focus(egui::Id::new(("composer", channel.0))));
    }

    /// Add your reaction if you haven't reacted with this emoji, else remove it.
    pub fn toggle_reaction(&mut self, channel: Id, msg: Id, emoji: ReactionEmoji) {
        let Some(m) = self.store.message(channel, msg) else { return };
        let mine = m.reactions.iter().any(|r| r.me && r.emoji.same(&emoji));
        if !mine {
            self.track_reaction(&emoji);
        }
        self.backend.send(Command::React { channel, msg, emoji, add: !mine });
    }

    pub fn start_edit(&mut self, channel: Id, msg: Id) {
        let Some(m) = self.store.message(channel, msg) else { return };
        self.editing = Some(EditState { channel, msg, text: m.content.clone(), focus: true });
    }

    pub fn save_edit(&mut self) {
        let Some(mut e) = self.editing.take() else { return };
        let unchanged = self.store.message(e.channel, e.msg).is_some_and(|m| m.content == e.text);
        if unchanged {
            return;
        }
        if e.text.trim().is_empty() {
            self.backend.send(Command::Delete { channel: e.channel, id: e.msg });
            return;
        }
        if !self.rencord.before_edit(e.channel, &mut e.text) {
            self.toast("A Rencord plugin blocked this edit.", false);
            return;
        }
        self.backend.send(Command::Edit { channel: e.channel, id: e.msg, content: e.text });
    }

    pub fn delete_message(&mut self, channel: Id, msg: Id) {
        let failed = self.store.message(channel, msg).is_some_and(|m| m.meta.failed || m.meta.pending);
        if failed {
            self.store.remove_message(channel, msg);
        } else {
            self.backend.send(Command::Delete { channel, id: msg });
        }
    }

    pub fn run_plugin_action(&mut self, channel: Id, msg: Id, plugin: usize, action: &str) {
        let outcome = match self.store.message_mut(channel, msg) {
            Some(m) => self.rencord.run_message_action(plugin, action, m),
            None => return,
        };
        if outcome == rencord::ActionOutcome::RemoveMessage {
            self.store.remove_message(channel, msg);
        }
    }

    // ---- themes -------------------------------------------------------------

    fn restore_theme(&mut self) {
        match self.rencord.theme.source.clone() {
            Some(src) if src.starts_with("https://") => {
                self.theme_status = format!("Loading {src}…");
                self.backend.send(Command::FetchTheme(src));
                self.apply_theme();
            }
            Some(src) if src.starts_with("http://") => {
                self.theme_status = THEME_HTTPS_ONLY.into();
                self.apply_theme();
            }
            Some(src) => self.load_theme_file(&src),
            None => self.apply_theme(),
        }
    }

    pub fn load_theme_source(&mut self, src: String) {
        let src = src.trim().to_string();
        if src.is_empty() {
            return;
        }
        if src.starts_with("http://") {
            self.theme_status = THEME_HTTPS_ONLY.into();
            return;
        }
        self.rencord.theme.source = Some(src.clone());
        self.rencord.save();
        if src.starts_with("https://") {
            self.theme_status = format!("Loading {src}…");
            self.backend.send(Command::FetchTheme(src));
        } else {
            self.load_theme_file(&src);
        }
    }

    fn load_theme_file(&mut self, path: &str) {
        match std::fs::read_to_string(path) {
            Ok(css) => {
                self.theme_css = css;
                self.theme_status = format!("Loaded {path}");
            }
            Err(e) => self.theme_status = format!("Couldn't read {path}: {e}"),
        }
        self.apply_theme();
    }

    pub fn clear_theme(&mut self) {
        self.rencord.theme.source = None;
        self.rencord.save();
        self.theme_css.clear();
        self.theme_input.clear();
        self.theme_status = "Using the default theme.".into();
        self.apply_theme();
    }

    pub fn save_quick_css(&mut self) {
        self.rencord.theme.quick_css = self.quick_css_input.clone();
        self.rencord.save();
        self.apply_theme();
    }

    pub fn apply_theme(&mut self) {
        let base = if self.rencord.theme.base.is_empty() { "dark".to_string() } else { self.rencord.theme.base.clone() };
        let css = format!("{}\n{}", self.theme_css, self.rencord.theme.quick_css);
        if css.trim().is_empty() {
            self.theme = Theme::preset(&base);
            self.theme_report = None;
            // The Nitro colour theme: RustCord's own pick (Settings → Appearance),
            // else your account's (a Discord preset or your custom gradient).
            let account_preset = self.client_theme.preset.and_then(crate::style::gradient_preset);
            let preset = match self.prefs.theme_color.as_deref() {
                Some(c) => c.strip_prefix("preset:").and_then(|id| id.parse().ok()).and_then(crate::style::gradient_preset),
                None => account_preset,
            };
            let colors: Vec<egui::Color32> = self.client_theme.colors.iter().filter_map(|c| crate::style::parse_hex(c)).collect();
            if let Some(p) = preset {
                // Light presets use Discord's light theme.
                let base = if p.light { "light" } else { base.as_str() };
                self.theme = Theme::preset(base).with_preset(p);
            } else if self.prefs.theme_color.is_none() && !colors.is_empty() {
                // (Without a base mix in the settings: 85, what Discord gives this theme.)
                self.theme = self.theme.clone().with_client_theme(&colors, self.client_theme.angle, self.client_theme.base_mix.unwrap_or(85.0));
            }
        } else {
            let report = rencord::theme::translate(&css);
            self.theme = Theme::from_palette(&base, &report.palette);
            self.theme_report = Some(report);
        }
        if self.prefs.saturation < 0.995 {
            self.theme = self.theme.clone().saturated(self.prefs.saturation);
        }
        if if self.prefs.contrast_sync { crate::tray::system_high_contrast() } else { self.prefs.high_contrast } {
            self.theme = self.theme.clone().high_contrast();
        }
        self.theme.apply(&self.ctx);
    }

    /// Your Discord settings arrived (at start, after a change of yours, or
    /// from the gateway when another app changed them: then your status is
    /// left alone, it has its own events).
    pub fn apply_account_settings(&mut self, s: discord::settings_proto::UserSettings, with_status: bool) {
        // The API answers in your language, like Discord's client asks it to.
        if let Some(l) = &s.locale {
            discord::http::set_account_locale(l);
        }
        self.store.folders = s.folders;
        self.store.favorites = s.favorites;
        if with_status {
            self.store.my_status = s.status;
            self.store.my_custom = s.custom_status;
        }
        let account = crate::features::AccountTheme { colors: s.client_theme_colors, angle: s.client_theme_angle.unwrap_or(0.0), base_mix: s.client_theme_base_mix, preset: s.client_theme_preset };
        self.account_proto = s.raw;
        self.apply_proto_settings();
        // (Some of what RustCord follows lives in both places: re-read it.)
        self.apply_discord_settings();
        log::info!("settings: sticker animations {} (0 always, 1 on interaction, 2 never)", crate::ui::STICKER_ANIM.load(std::sync::atomic::Ordering::Relaxed));
        if self.client_theme != account {
            log::info!("settings: client theme {account:?}");
            self.client_theme = account;
            self.apply_theme();
        }
    }

    /// Account settings RustCord follows itself.
    pub fn apply_proto_settings(&self) {
        let spoilers = match self.account_proto.string(&[6, 4]).as_deref() {
            Some("ALWAYS") => 2,
            Some("IF_MODERATOR") => 1,
            _ => 0,
        };
        crate::ui::SPOILERS.store(spoilers, std::sync::atomic::Ordering::Relaxed);
    }

    /// A DM or a mention arrived: the Windows notification and the sound
    /// (Settings → Notifications), unless you're looking at that channel.
    fn message_alert(&mut self, guild: Option<Id>, channel: Id, author: Id, who: &str, text: &str) {
        let muted = self.store.muted_channels.contains(&channel) || guild.is_some_and(|g| self.store.muted_guilds.contains(&g));
        let blocked = self.store.relationships.get(&author).is_some_and(|r| r.kind == 2 || r.user_ignored);
        if muted || blocked || self.store.my_status == "dnd" {
            return;
        }
        let reading = self.screen == Screen::Main && self.current_channel == Some(channel) && self.ctx.input(|i| i.focused);
        let sound = if reading { self.prefs.sound_current_channel } else { self.prefs.sound_message };
        if sound && self.prefs.sounds_allowed() {
            self.audio.cue(crate::audio::Cue::Message, self.voice_ui.prefs.output_volume / 100.0);
        }
        if reading || !self.prefs.desktop_notifications || self.prefs.streaming_hides(|p| p.streamer_no_notifications) {
            return;
        }
        let title = match guild.and_then(|g| self.store.guilds.get(&g)) {
            Some(g) => format!("{who} (#{}, {})", self.store.channel_name(channel), g.guild.name),
            None => who.to_string(),
        };
        // Mentions as Discord's notifications show them, not as raw <@id>.
        let mut body = String::with_capacity(text.len());
        let mut rest = text;
        while let Some(i) = rest.find("<@") {
            body.push_str(&rest[..i]);
            let tail = &rest[i + 2..];
            let id_len = tail.trim_start_matches(['!', '&']).chars().take_while(char::is_ascii_digit).count();
            let skip = tail.len() - tail.trim_start_matches(['!', '&']).len();
            match (id_len > 0, tail[skip + id_len..].starts_with('>')) {
                (true, true) => {
                    let id = tail[skip..skip + id_len].parse().ok().map(Id);
                    let name = id.and_then(|id| self.store.users.get(&id)).map(|u| self.store.name_in(guild, Some(channel), u));
                    body.push('@');
                    body.push_str(name.as_deref().unwrap_or(if skip > 0 && tail.starts_with('&') { "role" } else { "user" }));
                    rest = &tail[skip + id_len + 1..];
                }
                _ => {
                    body.push_str("<@");
                    rest = tail;
                }
            }
        }
        body.push_str(rest);
        let body = if body.trim().is_empty() { "Sent an attachment".to_string() } else { body };
        self.notified = Some((guild, channel));
        crate::tray::notify(&title, &body);
    }

    /// The taskbar button's badge, or the Dock icon's on macOS (Settings →
    /// Notifications → Badges): your mentions and DMs counted, else a dot for
    /// unread messages. Looked at once a second.
    fn update_badge(&mut self) {
        // (Windows needs the window's handle for it; the Dock doesn't.)
        let window_known = self.hwnd != 0 || cfg!(target_os = "macos");
        if !window_known || self.badge_at.is_some_and(|t| t.elapsed() < Duration::from_secs(1)) {
            return;
        }
        self.badge_at = Some(Instant::now());
        use crate::tray::Badge;
        let badge = if !self.prefs.unread_badge || self.screen != Screen::Main {
            Badge::None
        } else {
            let mentions: u32 = self.store.read_states.iter().filter(|(c, _)| !self.store.muted_channels.contains(c)).map(|(_, r)| r.mentions).sum();
            if mentions > 0 {
                Badge::Count(mentions)
            } else if self.store.guilds.keys().any(|g| self.store.guild_unread(*g)) {
                Badge::Dot
            } else {
                Badge::None
            }
        };
        if badge != self.badge {
            self.badge = badge;
            crate::tray::set_badge(self.hwnd, badge);
        }
    }

    /// Appearance → "Same as Device Theme": light with Windows' light mode,
    /// your dark theme otherwise.
    fn follow_device_theme(&mut self) {
        if !self.prefs.theme_follow_device || self.device_theme_at.is_some_and(|t| t.elapsed() < Duration::from_secs(3)) {
            return;
        }
        self.device_theme_at = Some(Instant::now());
        let light = crate::tray::system_light_theme();
        let current = if self.rencord.theme.base.is_empty() { "dark" } else { self.rencord.theme.base.as_str() };
        let want = if light {
            "light".to_string()
        } else if current == "light" {
            if self.prefs.theme_dark.is_empty() { "dark".into() } else { self.prefs.theme_dark.clone() }
        } else {
            return;
        };
        if want != current {
            self.set_base_theme(&want);
        }
    }

    /// Switch between Discord's Dark / Ash / Onyx.
    pub fn set_base_theme(&mut self, base: &str) {
        self.rencord.theme.base = base.to_string();
        self.rencord.save();
        self.apply_theme();
    }
}

impl RustCord {
    /// Open / move / close the login page, and pick up its token.
    fn manage_login_view(&mut self, frame: &eframe::Frame) {
        // A finished login page is retired at once (hidden and emptied) and
        // destroyed a few seconds later, so Windows Hello / WebView2 can wind
        // down first. Destroying it ends its WebView2 processes.
        if self.retired_login_view.as_ref().is_some_and(|(_, at)| at.elapsed() > Duration::from_secs(4)) {
            self.retired_login_view = None;
            crate::diagnostics::release_unused_memory();
            log::info!("login: login page destroyed");
        }
        if self.screen != Screen::Login {
            self.retire_login_view();
            return;
        }
        let Some(rect) = self.login.webview_rect else { return };
        let ppp = self.ctx.pixels_per_point();
        let Some(v) = &self.login_view else {
            match crate::login_view::LoginView::open(frame, &self.ctx, rect, ppp, self.theme.bg_tertiary) {
                Ok(v) => {
                    log::info!("login: login page opened");
                    self.login_view = Some(v);
                    self.login_opened_at = Some(Instant::now());
                }
                Err(e) => {
                    log::warn!("login: {e}");
                    self.login.open_error = Some(e);
                }
            }
            return;
        };
        v.set_bounds(rect, ppp);
        for url in v.links() {
            self.ctx.open_url(egui::OpenUrl::new_tab(url));
        }
        if let Some(note) = v.note() {
            self.login.notice = Some(note);
        }
        let mut token = v.token();
        // Dev aid (demo only): RUSTCORD_DEV_VIEW=login-done completes a login
        // 10 s after the page opened, the same way a real one does.
        if self.demo
            && crate::diagnostics::dev_var("RUSTCORD_DEV_VIEW").as_deref() == Ok("login-done")
            && self.login_opened_at.is_some_and(|t| t.elapsed() > Duration::from_secs(10))
        {
            token = Some("demo".into());
        }
        if let Some(token) = token {
            log::info!("login: got login {} from the login page", crate::accounts::token_tag(&token));
            self.retire_login_view();
            self.login_with_token(token);
        }
    }

    fn retire_login_view(&mut self) {
        if let Some(v) = self.login_view.take() {
            v.retire();
            self.retired_login_view = Some((v, Instant::now()));
            // A frame when it is due to go (an idle window draws none).
            self.ctx.request_repaint_after(Duration::from_millis(4100));
        }
    }
}

/// Frame timing (RUSTCORD_PERF=1): frames per second and where time goes.
#[derive(Default)]
pub struct Perf {
    pub on: bool,
    frames: u32,
    since: Option<Instant>,
    pub parts: Vec<(&'static str, f64)>,
}

impl Perf {
    pub fn add(&mut self, part: &'static str, start: Instant) {
        if !self.on {
            return;
        }
        self.add_ms(part, start.elapsed().as_secs_f64() * 1000.0);
    }

    pub fn add_ms(&mut self, part: &'static str, ms: f64) {
        if !self.on {
            return;
        }
        match self.parts.iter_mut().find(|(p, _)| *p == part) {
            Some((_, t)) => *t += ms,
            None => self.parts.push((part, ms)),
        }
    }

    fn frame_done(&mut self, ctx: &egui::Context) {
        if !self.on {
            return;
        }
        self.frames += 1;
        let since = *self.since.get_or_insert_with(Instant::now);
        if since.elapsed() >= Duration::from_secs(5) {
            let n = self.frames.max(1) as f64;
            let parts: Vec<String> = self.parts.iter().map(|(p, t)| format!("{p} {:.2}ms", t / n)).collect();
            // What the image pipeline holds: downloaded files, decoded
            // pixels (incl. animation frames) and textures.
            let loaders = ctx.loaders();
            let mb = |b: usize| b as f64 / (1024.0 * 1024.0);
            let bytes: usize = loaders.bytes.lock().iter().map(|l| l.byte_size()).sum();
            let images: usize = loaders.image.lock().iter().map(|l| l.byte_size()).sum();
            // (Which image loaders hold it, the big ones by name.)
            let by_loader: Vec<String> = loaders
                .image
                .lock()
                .iter()
                .filter(|l| l.byte_size() >= 1 << 20)
                .map(|l| format!("{} {:.0}", l.id().rsplit("::").next().unwrap_or(""), mb(l.byte_size())))
                .collect();
            let textures: usize = loaders.texture.lock().iter().map(|l| l.byte_size()).sum();
            let atlas = ctx.fonts(|f| (f.font_image_size(), f.font_atlas_fill_ratio()));
            log::info!(
                "perf: {:.1} fps; per frame: {}; image caches: files {:.1} MB, decoded {:.1} MB [{}], textures {:.1} MB; glyph atlas {}x{} ({:.0}% full); {}",
                n / since.elapsed().as_secs_f64(),
                parts.join(", "),
                mb(bytes),
                mb(images),
                by_loader.join(", "),
                mb(textures),
                atlas.0[0],
                atlas.0[1],
                atlas.1 * 100.0,
                crate::diagnostics::heap_summary()
            );
            self.frames = 0;
            self.since = Some(Instant::now());
            self.parts.clear();
        }
    }
}

/// A message Discord challenged with a captcha: the message, the challenge, and the
/// webview showing hCaptcha's widget once the dialog has a place for it.
pub struct CaptchaPrompt {
    pub msg: discord::model::OutgoingMessage,
    /// Set when the challenge was for a friend request to this person, not a message.
    pub friend: Option<Id>,
    /// That friend request was a stranger's, confirmed in "Accept friend request?".
    pub friend_stranger: bool,
    /// Set when the challenge was for creating or joining a server.
    pub server: Option<crate::features::AddServerRequest>,
    pub challenge: crate::captcha_view::Challenge,
    pub view: Option<crate::captcha_view::CaptchaView>,
    /// Where the dialog wants the widget (set by the dialog each frame).
    pub rect: Option<egui::Rect>,
    pub error: Option<String>,
}

impl RustCord {
    /// Mark a pending message as failed (its row turns red with "retry").
    fn send_failed(&mut self, channel: Id, nonce: &str) {
        if let Some(cm) = self.store.messages.get_mut(&channel) {
            for m in cm.list.iter_mut() {
                if m.meta.pending && m.nonce_string().as_deref() == Some(nonce) {
                    m.meta.pending = false;
                    m.meta.failed = true;
                    m.meta.uploading = 0;
                }
            }
        }
    }

    /// The captcha dialog (Discord's "Wait! Are you human?"): hCaptcha's widget for the
    /// person to solve, then the message is sent again with the widget's answer.
    fn manage_captcha(&mut self, ctx: &egui::Context, frame: &eframe::Frame) {
        if self.captcha.is_none() {
            return;
        }
        let t = self.theme.clone();
        let screen = ctx.screen_rect();
        let mut cancel = ctx.input(|i| i.key_pressed(egui::Key::Escape));
        let mut widget = None;
        let error = self.captcha.as_ref().and_then(|c| c.error.clone());
        egui::Area::new(egui::Id::new("captcha_dim")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
            let (rect, resp) = ui.allocate_exact_size(screen.size(), egui::Sense::click());
            ui.painter().rect_filled(rect, 0.0, egui::Color32::from_black_alpha(170));
            let _ = resp;
            let size = egui::vec2(440.0, 620.0_f32.min(screen.height() - 40.0));
            let dialog = egui::Rect::from_center_size(screen.center(), size);
            ui.painter().rect_filled(dialog, 12.0, t.bg_floating);
            ui.painter().rect_stroke(dialog, 12.0, egui::Stroke::new(1.0_f32, t.border_subtle));
            let bold = |s: f32| egui::FontId::new(s, egui::FontFamily::Name(crate::style::BOLD.into()));
            ui.painter().text(egui::pos2(dialog.center().x, dialog.top() + 34.0), egui::Align2::CENTER_CENTER, "Wait! Are you human?", bold(22.0), t.header_primary);
            ui.painter().text(egui::pos2(dialog.center().x, dialog.top() + 62.0), egui::Align2::CENTER_CENTER, "Please confirm you're not a robot.", egui::FontId::proportional(14.0), t.text_muted);
            let area = egui::Rect::from_min_max(dialog.min + egui::vec2(16.0, 84.0), dialog.max - egui::vec2(16.0, 60.0));
            ui.painter().rect_filled(area, 8.0, egui::Color32::from_rgb(0x2b, 0x2d, 0x31));
            match &error {
                Some(e) => {
                    ui.painter().text(area.center(), egui::Align2::CENTER_CENTER, e, egui::FontId::proportional(14.0), t.danger);
                }
                None => widget = Some(area),
            }
            let button = egui::Rect::from_min_size(egui::pos2(dialog.right() - 16.0 - 96.0, dialog.bottom() - 48.0), egui::vec2(96.0, 36.0));
            let r = ui.interact(button, egui::Id::new("captcha_cancel"), egui::Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            ui.painter().rect_filled(button, 8.0, if r.hovered() { crate::style::overlay(0.24) } else { crate::style::overlay(0.16) });
            ui.painter().text(button.center(), egui::Align2::CENTER_CENTER, "Cancel", bold(14.0), t.header_primary);
            cancel |= r.clicked();
        });
        let ppp = ctx.pixels_per_point();
        let Some(prompt) = self.captcha.as_mut() else { return };
        prompt.rect = widget;
        let mut solved = None;
        if let Some(rect) = widget {
            match &prompt.view {
                None => match crate::captcha_view::CaptchaView::open(frame, &prompt.challenge, rect, ppp) {
                    Ok(view) => prompt.view = Some(view),
                    Err(e) => {
                        log::warn!("captcha: {e}");
                        prompt.error = Some(e);
                    }
                },
                Some(view) => {
                    view.set_bounds(rect, ppp);
                    match view.answer() {
                        Some(Ok(answer)) => solved = Some(answer),
                        Some(Err(e)) => {
                            log::warn!("captcha: {e}");
                            view.hide();
                            prompt.error = Some(format!("{e}."));
                        }
                        None => {}
                    }
                }
            }
            // The widget lives in a webview that doesn't wake egui: look for its answer.
            ctx.request_repaint_after(Duration::from_millis(200));
        }
        if let Some(key) = solved {
            let Some(mut prompt) = self.captcha.take() else { return };
            if let Some(view) = &prompt.view {
                view.hide();
            }
            log::info!("captcha: solved ({} characters); sending the message again", key.len());
            if crate::diagnostics::dev_var("RUSTCORD_DEV_VIEW").as_deref() == Ok("captcha") {
                self.toast("Captcha solved (test).", false);
                return;
            }
            let answer = discord::model::CaptchaAnswer { key, rqtoken: prompt.challenge.rqtoken.clone(), session_id: prompt.challenge.session_id.clone() };
            if let Some(request) = prompt.server.take() {
                self.backend.send(Command::AddServer { request, captcha: Some(answer) });
                return;
            }
            match prompt.friend {
                Some(user) => self.backend.send(Command::AddFriendSolved { user, captcha: answer, stranger: prompt.friend_stranger }),
                None => {
                    prompt.msg.captcha = Some(answer);
                    self.backend.send(Command::Send(prompt.msg));
                }
            }
        } else if cancel {
            if let Some(prompt) = self.captcha.take() {
                log::info!("captcha: cancelled");
                if prompt.server.is_some() {
                    if let Some(a) = self.add_server.as_mut() {
                        a.busy = false;
                    }
                } else {
                    self.send_failed(prompt.msg.channel_id, &prompt.msg.nonce);
                }
            }
        }
    }
}

/// Dev aid (`RUSTCORD_DEV_INPUT=1`): replays `click x y`, `move x y`,
/// `drag x1 y1 x2 y2`, `scroll x y dy`, `key Enter`, `text …`, `paste`, `drop <file>` and `send <text>` lines written to
/// %TEMP%\rustcord-dev-input.txt, one action per frame, so tests can drive
/// the UI without moving the real mouse.
impl RustCord {
    /// "Is RustCord the window in use", from Windows itself rather than
    /// winit's flag. That flag is only flipped by focus messages, and can be
    /// left saying "not focused" while you type into RustCord (an embedded
    /// player's WebView2 taking the keyboard and handing it back is one way).
    /// Everything that waits for focus then stopped: egui draws the text
    /// caret only while focused (no white line in the message box), the open
    /// channel wasn't marked read (its unread dot stayed), and typing
    /// effects and GIFs stood still.
    fn sync_window_focus(&mut self, raw: &mut egui::RawInput) {
        use std::sync::atomic::{AtomicU32, Ordering};
        static FIXES: AtomicU32 = AtomicU32::new(0);
        if self.hwnd == 0 {
            return;
        }
        let Some(foreground) = crate::tray::is_foreground(self.hwnd) else { return };
        if foreground != raw.focused {
            // (Logged a few times: how often winit's flag is stale.)
            if FIXES.fetch_add(1, Ordering::Relaxed) < 5 {
                log::info!("focus: winit said focused={}, Windows says {}; using Windows'", raw.focused, foreground);
            }
            raw.focused = foreground;
        }
        // A click on RustCord's own UI takes the keyboard back from a child
        // window (a player's WebView2 keeps it after you click into it).
        if foreground && raw.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: true, .. })) {
            crate::tray::take_keyboard_focus(self.hwnd);
        }
    }
}

/// What a `send` / `paste` dev-input line asks of the app (see [`dev_input`]).
enum DevAction {
    Send(String),
    Paste,
}

static DEV_ACTION: std::sync::Mutex<Option<DevAction>> = std::sync::Mutex::new(None);

fn dev_action(action: DevAction) {
    if let Ok(mut a) = DEV_ACTION.lock() {
        *a = Some(action);
    }
}

fn dev_input(raw: &mut egui::RawInput) {
    use std::sync::Mutex;
    static QUEUE: Mutex<Vec<String>> = Mutex::new(Vec::new());
    static PRESSED: Mutex<Option<egui::Pos2>> = Mutex::new(None);
    if crate::diagnostics::dev_var_os("RUSTCORD_DEV_INPUT").is_none() {
        return;
    }
    let path = std::env::temp_dir().join("rustcord-dev-input.txt");
    let Ok(mut q) = QUEUE.lock() else { return };
    if q.is_empty() {
        if let Ok(text) = std::fs::read_to_string(&path) {
            let _ = std::fs::remove_file(&path);
            q.extend(text.lines().map(str::trim).filter(|l| !l.is_empty()).map(String::from).rev());
        }
    }
    // `hold ctrl+shift` keeps those modifiers down until `hold` (nothing).
    static HELD: Mutex<egui::Modifiers> = Mutex::new(egui::Modifiers::NONE);
    let modifiers = HELD.lock().map(|m| *m).unwrap_or_default();
    if modifiers.any() {
        raw.modifiers = modifiers;
    }
    // A press is released on the next frame, so egui sees a real click.
    if let Some(pos) = PRESSED.lock().ok().and_then(|mut p| p.take()) {
        raw.events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers });
        return;
    }
    let Some(line) = q.pop() else { return };
    let mut parts = line.splitn(2, ' ');
    let (cmd, rest) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""));
    let nums: Vec<f32> = rest.split_whitespace().filter_map(|n| n.parse().ok()).collect();
    match (cmd, nums.as_slice()) {
        ("move", [x, y, ..]) => raw.events.push(egui::Event::PointerMoved(egui::pos2(*x, *y))),
        // Move first; press on the next frame (a jump and a press in one
        // frame reads as a drag to scroll areas).
        ("click", [x, y, ..]) => {
            raw.events.push(egui::Event::PointerMoved(egui::pos2(*x, *y)));
            q.push(format!("_press {x} {y}"));
        }
        ("_press", [x, y, ..]) => {
            let pos = egui::pos2(*x, *y);
            raw.events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers });
            if let Ok(mut p) = PRESSED.lock() {
                *p = Some(pos);
            }
        }
        // `rclick x y`: a right click (move, press, release on later frames).
        ("rclick", [x, y, ..]) => {
            raw.events.push(egui::Event::PointerMoved(egui::pos2(*x, *y)));
            q.push(format!("_rrelease {x} {y}"));
            q.push(format!("_rpress {x} {y}"));
        }
        ("_rpress" | "_rrelease", [x, y, ..]) => {
            let pressed = cmd == "_rpress";
            raw.events.push(egui::Event::PointerButton { pos: egui::pos2(*x, *y), button: egui::PointerButton::Secondary, pressed, modifiers });
        }
        // `drag x1 y1 x2 y2`: press, move there in steps (one per frame), release.
        ("drag", [x1, y1, x2, y2, ..]) => {
            raw.events.push(egui::Event::PointerMoved(egui::pos2(*x1, *y1)));
            q.push(format!("up {x2} {y2}"));
            for i in (1..=12).rev() {
                let f = i as f32 / 12.0;
                q.push(format!("move {} {}", x1 + (x2 - x1) * f, y1 + (y2 - y1) * f));
            }
            q.push(format!("down {x1} {y1}"));
        }
        ("down", [x, y, ..]) => {
            let pos = egui::pos2(*x, *y);
            raw.events.push(egui::Event::PointerMoved(pos));
            raw.events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers });
        }
        ("up", [x, y, ..]) => {
            let pos = egui::pos2(*x, *y);
            raw.events.push(egui::Event::PointerMoved(pos));
            raw.events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers });
        }
        // `mdown x y` / `mup x y`: the middle button (autoscroll).
        ("mdown" | "mup", [x, y, ..]) => {
            let pos = egui::pos2(*x, *y);
            raw.events.push(egui::Event::PointerMoved(pos));
            raw.events.push(egui::Event::PointerButton { pos, button: egui::PointerButton::Middle, pressed: cmd == "mdown", modifiers });
        }
        ("scroll", [x, y, dy, ..]) => {
            raw.events.push(egui::Event::PointerMoved(egui::pos2(*x, *y)));
            raw.events.push(egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line, delta: egui::vec2(0.0, *dy), modifiers });
        }
        ("key", _) => {
            // `key Enter`, or with Ctrl/Cmd: `key ctrl+K` / `key cmd+K`.
            let trimmed = rest.trim();
            let (mods, name) = match trimmed.strip_prefix("ctrl+").or_else(|| trimmed.strip_prefix("cmd+")) {
                Some(n) => (egui::Modifiers::COMMAND, n),
                None => (modifiers, trimmed),
            };
            if let Some(key) = egui::Key::from_name(name) {
                for pressed in [true, false] {
                    raw.events.push(egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: mods });
                }
            }
        }
        ("text", _) => raw.events.push(egui::Event::Text(rest.to_string())),
        ("hold", _) => {
            if let Ok(mut held) = HELD.lock() {
                let ctrl = rest.contains("ctrl") || rest.contains("cmd");
                *held = egui::Modifiers { ctrl, command: ctrl, shift: rest.contains("shift"), ..Default::default() };
            }
        }
        // What Ctrl + C arrives as.
        ("copy", _) => raw.events.push(egui::Event::Copy),
        // `paste`: the clipboard's files or picture attached to the open channel.
        ("paste", _) => dev_action(DevAction::Paste),
        // `send <text>`: send that (with any attached files) to the open channel.
        ("send", _) => dev_action(DevAction::Send(rest.to_string())),
        // `drop C:\shots\pic.png`: that file dropped onto the window.
        ("drop", _) => raw.dropped_files.push(egui::DroppedFile { path: Some(rest.trim().into()), ..Default::default() }),
        _ => {}
    }
}

/// Where the chat drew a provider player's box this frame.
#[derive(Clone, Copy)]
pub struct PlayerPlace {
    pub key: crate::embed_view::Key,
    pub rect: egui::Rect,
    /// The chat's visible area (the player is cut off at its edges).
    pub clip: egui::Rect,
    /// Nothing (a menu, a dialog, the image viewer) is drawn over it.
    pub on_top: bool,
    pub pass: u64,
}

/// A provider player to open: which embed, and the iframe address.
pub struct EmbedRequest {
    pub key: crate::embed_view::Key,
    pub channel: Id,
    pub src: String,
    pub bg: egui::Color32,
    pub at: Instant,
}

impl RustCord {
    /// Keep the playing video and the provider player in step with the UI:
    /// new frames into the texture, the webview over its embed (hidden when
    /// the embed is scrolled away or covered), both closed when you leave
    /// the channel.
    fn manage_players(&mut self, ctx: &egui::Context, frame: &eframe::Frame) {
        // The emoji picker's skin tone was changed: remember it.
        let tone = crate::emoji::skin_tone();
        if tone != self.prefs.skin_tone {
            self.prefs.skin_tone = tone;
            crate::features::save_prefs(self.config_dir.as_deref(), &self.prefs);
        }
        if self.video_player.is_some() && self.video_channel != self.current_channel {
            self.video_player = None;
        }
        if let Some(p) = &mut self.video_player {
            p.pump(ctx, &mut self.audio);
        }
        use crate::embed_view::{EmbedView, KEEP_WARM};
        let here = self.current_channel;
        // Leaving the channel stops the player. Its webview is kept (hidden)
        // for the next play, since building one is what makes a player slow
        // to start, but not for long: it holds memory.
        if let Some(v) = self.embed_view.as_mut().filter(|v| v.playing.is_some_and(|(_, c)| Some(c) != here)) {
            v.stop();
        }
        match self.embed_view.as_ref().and_then(|v| v.idle()) {
            Some(idle) if idle >= KEEP_WARM => self.embed_view = None,
            Some(idle) => ctx.request_repaint_after(KEEP_WARM - idle),
            None => {}
        }
        if self.embed_request.as_ref().is_some_and(|r| Some(r.channel) != here || r.at.elapsed() > Duration::from_secs(3)) {
            self.embed_request = None;
        }
        let pass = ctx.cumulative_pass_nr();
        let place: Option<PlayerPlace> = ctx.data(|d| d.get_temp(egui::Id::new("embed_view_place"))).filter(|p: &PlayerPlace| p.pass == pass);
        let ppp = ctx.pixels_per_point();
        // The pointer rests on a play button: get the webview ready now, so
        // the click only has to load the page.
        let now = ctx.input(|i| i.time);
        let warm_id = egui::Id::new("embed_view_warm");
        let hovered = ctx.data(|d| d.get_temp::<(u64, f64)>(warm_id)).is_some_and(|(p, since)| p == pass && now - since >= 0.1);
        if hovered && self.embed_view.is_none() && self.embed_request.is_none() {
            let t = Instant::now();
            match EmbedView::warm(frame) {
                Ok(v) => {
                    log::info!("embed player: webview warmed up in {} ms", t.elapsed().as_millis());
                    self.embed_view = Some(v);
                }
                Err(e) => {
                    log::warn!("embed player (warm-up): {e}");
                    ctx.data_mut(|d| d.remove::<(u64, f64)>(warm_id));
                }
            }
        }
        if let (Some(req), Some(p)) = (&self.embed_request, place) {
            if p.key == req.key {
                let reused = self.embed_view.is_some();
                let t = Instant::now();
                let result = match &mut self.embed_view {
                    Some(v) => v.play(req.key, req.channel, &req.src, req.bg),
                    None => EmbedView::open(frame, req.key, req.channel, &req.src, req.bg, p.rect, ppp).map(|v| self.embed_view = Some(v)),
                };
                log::info!("embed player: loading {} ms after the click ({} ms in a {} webview)", req.at.elapsed().as_millis(), t.elapsed().as_millis(), if reused { "kept" } else { "new" });
                if let Err(e) = result {
                    log::warn!("embed player: {e}");
                    self.toast(e, true);
                }
                self.embed_request = None;
            }
        }
        let mut open = Vec::new();
        if let Some(v) = &mut self.embed_view {
            for ev in v.poll() {
                if let crate::embed_view::Event::Open(url) = ev {
                    open.push(url);
                }
            }
            let key = v.playing.map(|(k, _)| k);
            let want = match place.filter(|p| Some(p.key) == key) {
                Some(_) if v.fullscreen => Some((ctx.screen_rect(), ctx.screen_rect())),
                Some(p) if p.on_top && EmbedView::in_view(p.rect, p.clip) => Some((p.rect, p.clip)),
                _ => None,
            };
            match (want, key) {
                // Not moved here: this frame isn't on screen yet, and the
                // webview (a window of its own) would run ahead of the chat
                // while scrolling. `update` moves it first thing next frame.
                (Some((rect, clip)), Some(key)) => {
                    if v.misplaced(rect, clip, ppp) {
                        self.pending_place = Some((key, rect, clip));
                        ctx.request_repaint();
                    }
                }
                _ => {
                    self.pending_place = None;
                    v.hide();
                }
            }
        }
        for url in open {
            ctx.open_url(egui::OpenUrl::new_tab(url));
        }
    }
}

impl eframe::App for RustCord {
    fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
        // Minimized or in the tray, the window is a 160 x 28 sliver: lay out
        // at the size it had instead, so nothing gets squeezed (or dropped
        // and loaded again when it comes back).
        if self.window_hidden || raw.viewport().minimized == Some(true) {
            if self.laid_out_at.is_some() {
                raw.screen_rect = self.laid_out_at;
            }
        } else if raw.screen_rect.is_some_and(|r| r.width() >= 1.0 && r.height() >= 1.0) {
            self.laid_out_at = raw.screen_rect;
        }
        self.sync_window_focus(raw);
        // A test window driven by dev input sits in the background; it takes
        // typing as if it were in front (egui drops the text caret otherwise).
        if crate::diagnostics::dev_var_os("RUSTCORD_DEV_INPUT").is_some() {
            raw.focused = true;
        }
        dev_input(raw);
        self.autoscroll.filter(raw, !crate::hotkey::is_push_to_talk(crate::hotkey::MIDDLE_BUTTON));
    }

    fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
        self.save_nav();
        self.save_window_place();
        if self.zoom_unsaved.take().is_some() {
            self.save_prefs();
        }
    }

    fn update(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
        let frame_start = Instant::now();
        crate::emoji::pump_text_emoji(ctx);
        if !self.corners_rounded {
            self.corners_rounded = true;
            use wry::raw_window_handle::{HasWindowHandle, RawWindowHandle};
            if let Ok(h) = frame.window_handle() {
                if let RawWindowHandle::Win32(w) = h.as_raw() {
                    self.hwnd = w.hwnd.get();
                    crate::tray::round_corners(w.hwnd.get());
                    crate::tray::set_window_icons(w.hwnd.get());
                    // Where it was last closed. Still hidden: eframe shows
                    // the window once this first frame is drawn.
                    if let Some(place) = &self.window_place {
                        crate::window_place::apply(self.hwnd, place);
                    }
                }
            }
        }
        // The provider player goes where the previous frame drew its box, now
        // that this frame is on screen (see `manage_players`).
        if let Some((key, rect, clip)) = self.pending_place.take() {
            if let Some(v) = self.embed_view.as_mut().filter(|v| v.playing.is_some_and(|(k, _)| k == key)) {
                v.place(rect, clip, ctx.pixels_per_point());
            }
        }
        #[cfg(target_os = "linux")]
        {
            let web_page_open = self.login_view.is_some() || self.retired_login_view.is_some() || self.captcha.as_ref().is_some_and(|c| c.view.is_some()) || self.embed_view.is_some();
            crate::linux::pump(ctx, web_page_open);
        }
        self.tray_actions(ctx);
        self.close_to_tray(ctx);
        self.handle_shortcuts(ctx);
        self.pump_events();
        if let (Some(action), Some(ch)) = (DEV_ACTION.lock().ok().and_then(|mut a| a.take()), self.current_channel) {
            match action {
                DevAction::Send(text) => self.send_message(ch, text),
                DevAction::Paste => {
                    if let Some(clip) = crate::clipboard::read_attachments() {
                        self.add_clip(ch, clip);
                    }
                }
            }
        }
        self.perf.add("events", frame_start);
        // Dev aid: RUSTCORD_DEV_ANIMATE=1 plays animations while unfocused
        // (perf measurements with another window in front).
        static ALWAYS_ANIMATE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
        let always = *ALWAYS_ANIMATE.get_or_init(|| crate::diagnostics::dev_var_os("RUSTCORD_DEV_ANIMATE").is_some());
        crate::ui::set_animating(always || ctx.input(|i| i.focused));
        // Your place goes to disk 2 s after it last changed (and on exit).
        if self.nav_dirty.get().is_some_and(|t| t.elapsed() > Duration::from_secs(2)) {
            self.save_nav();
        }
        // Watched every frame (edges only count once), used by the message box.
        self.compose.paste_key = crate::clipboard::paste_pressed() && ctx.input(|i| i.focused);
        self.track_missed(ctx);
        self.update_badge();
        self.follow_device_theme();
        self.auto_ack(ctx);
        if self.screen == Screen::Main {
            self.track_navigation();
        }
        // Under a Nitro client theme: the gradient behind everything (gaps
        // between panels show it, not the window's clear colour).
        if self.theme.gradient.is_some() {
            let t = self.theme.clone();
            crate::ui::paint_theme_surface(ctx, &ctx.layer_painter(egui::LayerId::background()), ctx.screen_rect(), 0.0, crate::ui::surface::FRAME, &t);
        }
        self.autoscroll.before_ui(ctx);
        self.title_bar(ctx);
        match self.screen {
            Screen::Login => self.login_ui(ctx),
            Screen::Main => self.main_ui(ctx),
        }
        // Games the profile cards drew but RustCord doesn't know yet.
        let wanted: Vec<Id> = self.apps_wanted.borrow_mut().drain().filter(|id| self.apps_requested.insert(*id)).collect();
        if !wanted.is_empty() {
            self.backend.send(Command::FetchApps(wanted));
        }
        // Profiles hovered this frame: fetch ahead of the click.
        let hovered: Vec<(Id, Option<Id>)> = self.profiles_wanted.borrow_mut().drain(..).collect();
        for (user, guild) in hovered {
            self.want_profile(user, guild);
        }
        self.listen_along_tick();
        self.voice_tick();
        self.last_call_tick();
        self.camera_tick();
        self.spotify_tick();
        self.spotify_panel_tick(ctx);
        self.spam_warnings_tick();
        self.registry_tick();
        self.calls_tick();
        self.streams_tick();
        // An AutoMod alert's "Remove Restrictions" finished.
        match self.api_take("automod_clear_raid") {
            Some(Ok(_)) => self.toast("Restrictions removed.", false),
            Some(Err(e)) => self.toast(format!("Couldn't remove the restrictions: {e}"), true),
            None => {}
        }
        self.manage_login_view(frame);
        self.manage_captcha(ctx, frame);
        self.manage_players(ctx, frame);
        self.settings_window(ctx);
        self.keyboard_combos_ui(ctx);
        self.request_log_ui(ctx);
        self.spam_warnings_ui(ctx);
        self.leaving_ui(ctx);
        self.incoming_call_ui(ctx);
        self.toasts_ui(ctx);
        // Everything floating is drawn: ease in what just opened, out what closed.
        crate::ui::motion::end_frame(ctx);
        self.autoscroll.after_ui(ctx);
        // Typing indicators and toasts expire on their own; the audio seek bar moves.
        // With nothing on screen that changes by itself (no toast, nobody
        // typing, no call or stream), a slow heartbeat is enough: everything
        // else redraws when its event arrives.
        let lively = !self.toasts.is_empty() || self.store.typing.values().any(|t| !t.is_empty()) || self.voice.is_some() || self.go_live.is_some() || !self.watching.is_empty();
        let every = if self.audio.is_playing() {
            150
        } else if lively {
            1000
        } else {
            4000
        };
        ctx.request_repaint_after(Duration::from_millis(every));
        self.perf.add("total", frame_start);
        if self.perf.on {
            // The whole previous frame on the UI thread (update + tessellate
            // + paint), which "total" above doesn't cover.
            if let Some(cpu) = frame.info().cpu_usage {
                self.perf.add_ms("frame cpu", cpu as f64 * 1000.0);
            }
            // Who asked for this frame (file:line), to catch redraw loops.
            for c in ctx.repaint_causes() {
                let key: &'static str = Box::leak(format!("cause {}:{}", c.file.rsplit(['/', '\\']).next().unwrap_or(c.file), c.line).into_boxed_str());
                if !self.perf.parts.iter().any(|(p, _)| *p == key) {
                    self.perf.parts.push((key, 0.0));
                }
                if let Some(e) = self.perf.parts.iter_mut().find(|(p, _)| *p == key) {
                    e.1 += 1.0;
                }
            }
        }
        self.trim_memory(ctx);
        {
            let (input, foreground) = ctx.input(|i| (!i.events.is_empty(), i.focused && i.viewport().minimized != Some(true)));
            let in_call = self.voice.is_some() || self.go_live.is_some() || !self.watching.is_empty();
            let busy = self.audio.is_playing() || self.gif_picker.is_some() || self.emoji_picker.is_some();
            crate::diagnostics::idle::note(input, foreground, busy, in_call);
        }
        // Hand heap the allocator no longer uses back to Windows: shortly
        // after start-up (loading the account frees a lot at once) and then
        // every half minute. Nothing to do costs next to nothing.
        {
            use std::sync::atomic::{AtomicU64, Ordering};
            static NEXT: AtomicU64 = AtomicU64::new(6);
            let now = ctx.input(|i| i.time) as u64;
            if now >= NEXT.load(Ordering::Relaxed) {
                NEXT.store(now + if now < 30 { 8 } else { 30 }, Ordering::Relaxed);
                crate::net_images::drop_stale_files();
                crate::net_images::drop_stale_decoded();
                crate::diagnostics::release_unused_memory();
                // Dev aid (`--features memprof`): who owns the heap, once.
                #[cfg(feature = "memprof")]
                if (16..30).contains(&now) || (140..175).contains(&now) {
                    crate::memprof::dump();
                }
            }
        }
        // Links come from other people (messages, embeds, profiles, a game's
        // Rich Presence buttons). Only web addresses are handed to Windows:
        // anything else (`file:`, a program's own scheme, a network path)
        // could start something instead of opening a page.
        ctx.output_mut(|o| {
            if o.open_url.as_ref().is_some_and(|u| !crate::embed_view::is_web(&u.url)) {
                if let Some(u) = o.open_url.take() {
                    log::warn!("refused to open a link that isn't a web address ({})", crate::login_view::short(&u.url));
                }
            }
        });
        // A web link to somewhere that isn't Discord (or a site you trust)
        // waits for "Leaving RustCord" first; the one just confirmed goes.
        let pending = ctx.output_mut(|o| o.open_url.take());
        if let Some(u) = pending {
            if self.allowed_link.take().is_some_and(|a| a == u.url) || self.link_trusted(&u.url) {
                ctx.output_mut(|o| o.open_url = Some(u));
            } else {
                self.ask_before_leaving(u.url);
                ctx.request_repaint();
            }
        }
        self.perf.frame_done(ctx);
    }
}