Skip to content

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

64.8 KB
Raw Blame
//! Message actions and popups state: emoji picker, forwarding, uploads,
//! pins, Mark Unread, Copy Link, Speak, and user profiles.

use crate::app::RustCord;
use crate::backend::Command;
use discord::model::{Id, MessageReference, OutgoingMessage, ReactionEmoji, User};
use eframe::egui::{self, Pos2};
use std::path::{Path, PathBuf};

/// Discord's "Pin It. Pin It Good." / "Unpin Message" question about a
/// message (a copy: one from the pins popout may not be loaded in the chat).
pub struct PinConfirm {
    pub message: discord::model::Message,
    /// Pin it (true) or remove the pin.
    pub pin: bool,
}

const MAX_UPLOADS: usize = 10;

pub enum PickerTarget {
    React { channel: Id, msg: Id },
    /// A reaction to someone's custom status (it goes to your DM with them).
    StatusReact { user: Id, status: String },
    Insert { channel: Id },
    /// The emoji beside one of the poll draft's answers.
    PollAnswer(usize),
}

impl PickerTarget {
    /// The channel the emoji goes to (a poll's: the poll draft's).
    pub fn channel(&self, poll: Option<&PollDraft>) -> Option<Id> {
        match self {
            Self::React { channel, .. } | Self::Insert { channel } => Some(*channel),
            Self::PollAnswer(_) => poll.map(|p| p.channel),
            Self::StatusReact { .. } => None,
        }
    }
}

/// Whether a server emoji can be used in a message, reaction or poll.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum EmojiAccess {
    Usable,
    /// Needs Nitro: shown with a lock, can't be picked.
    Locked,
    /// The channel forbids other servers' emoji: not offered at all.
    Hidden,
}

/// The current account's emoji rules in one channel, worked out once per
/// frame. Discord's `getEmojiUnavailableReason` (web module 690521) for
/// chat and reactions: without Nitro, emoji from other servers (all of them
/// in DMs) and animated emoji anywhere are locked; integration (`managed`)
/// emoji work in other servers. A server channel without Use External Emojis
/// hides other servers' emoji, Nitro or not.
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub struct EmojiRules {
    /// The channel's server.
    pub here: Option<Id>,
    pub nitro: bool,
    /// Other servers' emoji are allowed in this channel.
    pub external: bool,
}

impl EmojiRules {
    pub fn access(&self, from: Id, animated: bool, managed: bool) -> EmojiAccess {
        let own = self.here == Some(from);
        if !own && !self.external {
            EmojiAccess::Hidden
        } else if !self.nitro && ((!own && !managed) || animated) {
            EmojiAccess::Locked
        } else {
            EmojiAccess::Usable
        }
    }
}

/// What the composer's "+" menu, sticker picker and app launcher have open.
#[derive(Default)]
pub struct ComposeTools {
    /// "+" menu: (channel, the button's rect, frame opened).
    pub plus_menu: Option<(Id, egui::Rect, u64)>,
    /// The message box's right-click menu: (channel, where, frame opened).
    pub text_menu: Option<(Id, egui::Pos2, u64)>,
    /// The misspelled word that menu was opened on: its byte range in the
    /// draft and the word (suggestions go at the top of the menu).
    pub text_menu_word: Option<(std::ops::Range<usize>, String)>,
    /// Ctrl+V went down this frame (see `crate::clipboard`).
    pub paste_key: bool,
    pub poll: Option<PollDraft>,
    pub new_thread: Option<ThreadDraft>,
    /// The composer's next message goes out at this time instead of now.
    pub schedule: Option<(Id, chrono::DateTime<chrono::Local>)>,
    pub schedule_dialog: Option<ScheduleDraft>,
    pub command: Option<CommandDraft>,
    /// The composer's rect this frame (the command list sits above it).
    pub composer_rect: Option<(Id, egui::Rect)>,
    /// Escape closed the command list for this draft.
    pub apps_dismissed: Option<(Id, String)>,
    /// Highlighted command, pending arrow presses, Enter/Tab pressed.
    pub apps_sel: usize,
    pub apps_nav: i32,
    pub apps_pick: bool,
    pub apps_scroll: bool,
    /// The "@word" at the caret this frame (the member list sits above the box).
    pub mention: Option<MentionQuery>,
    /// Rows in that list last frame (arrows / Enter / Tab go to it when > 0).
    pub mention_rows: usize,
    /// Highlighted row, pending arrow presses, Enter/Tab pressed.
    pub mention_sel: usize,
    pub mention_nav: i32,
    pub mention_pick: bool,
    /// Escape closed the list for the "@" at this (channel, position).
    pub mention_dismissed: Option<(Id, usize)>,
    /// The last (server, text) Discord was asked to find members for.
    pub mention_searched: Option<(Id, String)>,
    /// Put the cursor in the composer next frame.
    pub focus_composer: bool,
    /// You clicked away from this channel's message box: it stays without the
    /// cursor until you click it again (or change channel).
    pub blurred: Option<Id>,
    /// The expression picker (GIFs / Stickers / Emoji tabs) over the composer.
    pub expression: Option<ExpressionPicker>,
    /// The composer's GIF, sticker and emoji buttons this frame: a click
    /// there toggles the picker instead of closing it.
    pub expression_buttons: Option<egui::Rect>,
    /// Discord's frecency settings (favourite GIFs, sticker use), and when
    /// they were fetched.
    pub frecency: Option<discord::settings_proto::Frecency>,
    pub frecency_at: Option<std::time::Instant>,
    /// A favourite-GIF change waiting for Discord: (gif, add, already retried).
    pub frecency_patch: Option<(discord::settings_proto::FavoriteGif, bool, bool)>,
    /// Emoji uses Discord hasn't been told about yet (see `emoji_frecency`),
    /// when to tell it, and how many the request on its way carries.
    pub emoji_pending: Vec<crate::ui::emoji_frecency::PendingUse>,
    pub emoji_sync_at: Option<std::time::Instant>,
    pub emoji_sent: usize,
    /// Stickers sent from RustCord, newest first (None until read from disk).
    pub recent_stickers: Option<Vec<Id>>,
}

/// An "@word" being typed in a message box: where it is (in characters,
/// from the "@" to the caret) and the word so far.
#[derive(Clone, Debug, PartialEq)]
pub struct MentionQuery {
    pub channel: Id,
    /// '@' (members and roles) or '#' (channels).
    pub sigil: char,
    pub start: usize,
    pub end: usize,
    pub query: String,
}

/// Discord's "Create a Poll" dialog.
pub struct PollDraft {
    pub channel: Id,
    pub question: String,
    /// (text, emoji: unicode or "<:name:id>").
    pub answers: Vec<(String, Option<PickedEmoji>)>,
    pub hours: u32,
    pub multi: bool,
}

/// The "New Thread" side panel.
pub struct ThreadDraft {
    pub channel: Id,
    pub name: String,
    pub message: String,
    pub private: bool,
}

/// "Schedule Message → Custom…": a date and a quarter hour.
pub struct ScheduleDraft {
    pub channel: Id,
    pub date: chrono::NaiveDate,
    /// Minutes after midnight, in 15-minute steps.
    pub minutes: u32,
}

/// A slash command being filled in above the composer.
pub struct CommandDraft {
    pub channel: Id,
    /// The command as the index gave it, and its app.
    pub cmd: serde_json::Value,
    pub app_name: String,
    /// The chosen subcommand path ("group sub"), if it has those.
    pub path: Vec<String>,
    /// Option name → typed value.
    pub values: Vec<(String, String)>,
}

pub struct EmojiPicker {
    pub target: PickerTarget,
    pub pos: Pos2,
    pub search: String,
    pub opened_frame: u64,
    /// (preview image, :name:, server) of the hovered emoji, for the footer.
    pub hovered: Option<(String, String, Option<Id>)>,
}

pub struct ForwardState {
    /// Text to send instead of forwarding a message ("Share Profile": the
    /// profile's link).
    pub share: Option<String>,
    pub channel: Id,
    pub msg: Id,
    pub search: String,
    pub note: String,
    pub target: Option<Id>,
}

pub struct PendingUpload {
    pub name: String,
    /// Pictures are in memory (for the preview); other files stay on disk
    /// until they are sent.
    pub data: discord::model::UploadData,
    pub size: u64,
    pub is_image: bool,
    /// `bytes://` URI so egui can preview it.
    pub uri: String,
}

pub struct ProfilePopout {
    pub user: User,
    pub guild: Option<Id>,
    pub pos: Pos2,
    pub opened_frame: u64,
    /// "Message @user" box at the bottom of the card.
    pub dm_draft: String,
}

/// The big profile window (click an avatar in a profile card): card on the
/// left, Activity / Mutual Friends / Mutual Servers tabs on the right.
pub struct FullProfile {
    pub user: User,
    pub guild: Option<Id>,
    /// 0 Activity, 1 Mutual Friends, 2 Mutual Servers.
    pub tab: u8,
    pub opened_frame: u64,
}

/// Home's other pages (left of the DM list).
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum StorePage {
    Nitro,
    Shop,
    Quests,
}

#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub enum FriendsTab {
    #[default]
    Online,
    All,
    Pending,
    Blocked,
    AddFriend,
}

/// Your own profile card + account menu (status, custom status, copy ID).
pub struct AccountMenu {
    pub pos: Pos2,
    pub opened_frame: u64,
    /// Status flyout (Online / Idle / DND / Invisible).
    pub status_open: bool,
    /// "Switch Accounts" flyout.
    pub switch_open: bool,
    /// The "N Orbs" row's wallet flyout.
    pub orbs_open: bool,
}

/// Dialogs opened from the server menu and channel gear.
#[derive(Clone, Debug)]
pub enum ServerDialog {
    EditChannel { channel: Id, name: String, topic: String, slowmode: u32, nsfw: bool, confirm_delete: bool },
    /// `category`: making a category rather than a channel.
    /// `kind`: 0 text, 2 voice, 15 forum. `private`: hidden from @everyone.
    CreateChannel { guild: Id, parent: Option<Id>, name: String, kind: u8, private: bool, category: bool },
    /// "Edit Per-server Profile": nickname, and with Nitro the server's own
    /// pronouns and bio (`None` until your server profile has loaded).
    Nickname { guild: Id, nick: String, pronouns: Option<String>, bio: Option<String> },
    LeaveServer { guild: Id },
    /// The channel menu's "Delete Channel" confirmation.
    DeleteChannel { channel: Id, category: bool },
}

/// What "Add a Server" asks Discord for (kept to send again after a captcha).
#[derive(Clone, Debug)]
pub enum AddServerRequest {
    /// `POST /guilds` with this body.
    Create(serde_json::Value),
    /// Accept invite `code`; `input` is what was typed.
    Join { code: String, input: String, session: Option<String> },
}

/// An image (or GIF clip) open in the in-app media viewer.
#[derive(Clone, Debug)]
pub struct MediaView {
    /// What to draw (already sized / animated as needed).
    pub image: String,
    /// GIF embed clip to play instead, when there is one.
    pub video: Option<String>,
    /// Original file, for "Open in Browser" / "Copy Link".
    pub link: String,
    /// Natural size, if known.
    pub size: Option<(f32, f32)>,
}

/// The expression picker's GIF tab: Discord's own GIF search, via Tenor.
pub struct GifPicker {
    pub channel: Id,
    pub search: String,
    /// What the shown results are for: None = trending.
    pub query: Option<String>,
    /// None while loading.
    pub results: Option<Result<Vec<discord::model::Gif>, String>>,
    /// When the search box last changed (searches are debounced).
    pub edited: Option<std::time::Instant>,
    /// Every clip and still the picker has shown: let go when it closes.
    pub shown: std::collections::HashSet<String>,
}

/// Something chosen in the emoji picker.
#[derive(Clone)]
pub enum PickedEmoji {
    Unicode(String),
    Custom { id: Id, name: String, animated: bool },
}

fn frequent_path(dir: Option<&Path>) -> Option<PathBuf> {
    dir.map(|d| d.join("frequent-emoji.json"))
}

pub fn load_frequent(dir: Option<&Path>) -> Vec<String> {
    frequent_path(dir)
        .and_then(|p| std::fs::read_to_string(p).ok())
        .and_then(|s| serde_json::from_str::<Vec<String>>(&s).ok())
        .filter(|v| !v.is_empty())
        .unwrap_or_else(|| crate::emoji_data::DEFAULT_FREQUENT.iter().map(|s| s.to_string()).collect())
}

/// Settings → Account: the change being made (username, email, password,
/// logging a device out). What you type lives here only until it's sent or
/// you cancel.
#[derive(Default)]
pub struct AccountEdit {
    /// 0 nothing, 1 username, 2 email, 3 password, 4 log a device out.
    pub kind: u8,
    /// The new value (username, email or password).
    pub value: String,
    pub password: String,
    pub confirm: String,
    /// Email: the code Discord mailed you, and what it was exchanged for.
    pub code: String,
    pub email_sent: bool,
    pub email_token: Option<String>,
    /// The device being logged out (its session hash) and its name.
    pub device: String,
    pub device_name: String,
    /// Which request the answer in flight belongs to.
    pub step: u8,
    /// Discord asked to verify it's you: (ticket, the ways it accepts).
    pub mfa: Option<(String, Vec<String>)>,
    pub mfa_kind: String,
    pub mfa_data: String,
    pub error: Option<String>,
    /// The request to send again once verified.
    pub pending: Option<(reqwest::Method, String, Option<serde_json::Value>)>,
}

/// RustCord-only preferences (Discord keeps these per device too).
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct LocalPrefs {
    /// UI zoom (1.0 = 100%).
    pub zoom: f32,
    pub reduced_motion: bool,
    pub hour24: bool,
    /// Server list + channel list width (Discord: 375 by default, dragged
    /// between 264 and 432).
    pub sidebar_width: f32,
    /// Your Discord "Play sticker animations" setting as last seen (0 always,
    /// 1 on hover, 2 never), used from launch until your settings arrive:
    /// before, stickers played for the first seconds and then stopped.
    pub animate_stickers: u8,
    /// The Nitro colour theme RustCord shows: None = your account's (as set in
    /// Discord), "none" = Discord's plain colours, "preset:<id>" = one of
    /// Discord's gradient presets.
    pub theme_color: Option<String>,
    /// Underline misspelled words in the message box (Discord's "Spellcheck").
    pub spellcheck: bool,
    /// Tell the RustCord registry you use RustCord (the RustCord badge on
    /// your profile, as other RustCord users see it).
    pub share_rustcord: bool,
    /// The emoji picker's skin tone: 0 none, 1 light … 5 dark.
    pub skin_tone: u8,
    /// Closing the window keeps RustCord running in the notification area:
    /// Discord's "Minimize to Tray", on out of the box as in Discord. (0.4.40
    /// had it off as `close_to_tray`; a new name, so the default reaches
    /// everyone that file already says "off" for.)
    pub minimize_to_tray: bool,
    // ---- Notifications ----
    /// Windows notifications for DMs and mentions while you're elsewhere.
    pub desktop_notifications: bool,
    /// The red badge on the taskbar button (mention count, or a dot for unreads).
    pub unread_badge: bool,
    /// Sounds: a new DM or mention, one in the channel you're reading, an incoming call.
    pub sound_message: bool,
    pub sound_current_channel: bool,
    pub sound_ring: bool,
    /// "Disable All Notification Sounds" (voice chimes included).
    pub sounds_off: bool,
    /// Call sounds switched off one by one (Discord's names: "mute", "user_join"…).
    pub muted_cues: Vec<String>,
    // ---- Appearance ----
    /// Follow Windows' light / dark mode.
    pub theme_follow_device: bool,
    /// The theme to go back to in dark mode while following Windows.
    pub theme_dark: String,
    /// Write the theme you pick to your Discord account too.
    pub sync_theme: bool,
    /// A send button in the message box.
    pub send_button: bool,
    pub streamer_mode: bool,
    pub streamer_hide_personal: bool,
    pub streamer_hide_invites: bool,
    pub streamer_no_sounds: bool,
    pub streamer_no_notifications: bool,
    // ---- Accessibility ----
    /// Chat text size in px (Discord: 12–24, 16 by default).
    pub chat_font_size: f32,
    /// Space above a group of messages in px (Discord: 0–24, 16 by default).
    pub group_spacing: f32,
    pub underline_links: bool,
    /// Colour saturation of the interface, 0–1.
    pub saturation: f32,
    /// Role colours: 0 in names, 1 a dot next to names, 2 not shown.
    pub role_colors: u8,
    /// ✓ / ✕ drawn in switches.
    pub switch_icons: bool,
    /// Reduced motion follows Windows' "Animation effects".
    pub reduced_motion_sync: bool,
    /// People's Nitro display-name fonts (Accessibility → Display Name Styles).
    pub name_styles: bool,
    /// Popouts, menus and dialogs ease in and out (see `ui/motion.rs`).
    pub open_animations: bool,
    // ---- Typing effects (RustCord's own; see ui/typing_fx.rs) ----
    /// How the message box's letters move as you type: 0 off, 1 bounce, 2 wave,
    /// 3 ripple, 4 shake, 5 pop, 6 drop.
    pub typing_animation: u8,
    /// The message box's text colour: 0 the theme's, 1 solid, 2 gradient, 3 animated.
    pub typing_color_mode: u8,
    /// Animated colours: 0 rainbow, 1 flowing gradient, 2 pulse.
    pub typing_color_anim: u8,
    pub typing_color_a: [u8; 3],
    pub typing_color_b: [u8; 3],
    // ---- More of Discord's own switches ----
    /// Chat Message Display → Compact: time, name and text on one line.
    pub compact_chat: bool,
    /// Small avatars beside names in Compact.
    pub compact_avatars: bool,
    /// Other people's profiles in their own colours (their Nitro profile theme).
    pub profile_themes: bool,
    /// Saturation also greys role colours.
    pub saturation_custom: bool,
    pub high_contrast: bool,
    /// High contrast follows Windows' contrast themes.
    pub contrast_sync: bool,
    /// Speak Message speed, as Windows counts it: -10 (slowest) to 10.
    pub tts_rate: i32,
    /// The "ALT" tag on pictures that have a description.
    pub image_descriptions: bool,
    /// A plain message box: no emoji pictures, no typing effects.
    pub legacy_chat_input: bool,
    pub debug_logging: bool,
    /// List rows (channels, DMs, members): 0 compact, 1 default, 2 spacious.
    pub ui_density: u8,
    /// How long RustCord's pop-up messages stay, in seconds (5 by default).
    pub toast_seconds: u32,
    /// Settings → Experimental.
    pub experiments: Experiments,
    /// Sites whose links open without "Leaving RustCord" (their subdomains too).
    pub trusted_domains: Vec<String>,
}

/// Settings → Experimental: RustCord features still being tried out.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct Experiments {
    /// Warn when what you do looks like spam or a bot to Discord (on by default).
    pub spam_warnings: bool,
    /// Record every request RustCord sends (the Request Log window).
    pub request_log: bool,
    /// The Spotify controller above the user panel.
    pub spotify_player: bool,
    /// Send your emoji use to Discord (Frequently Used, as in Discord's apps).
    #[serde(default)]
    pub emoji_sync: bool,
}

impl Default for Experiments {
    fn default() -> Self {
        Self { spam_warnings: true, request_log: false, spotify_player: false, emoji_sync: false }
    }
}

impl LocalPrefs {
    /// Streamer Mode is on and hiding this.
    pub fn streaming_hides(&self, what: fn(&LocalPrefs) -> bool) -> bool {
        self.streamer_mode && what(self)
    }

    /// May a sound play at all (notification sounds and call chimes)?
    pub fn sounds_allowed(&self) -> bool {
        !self.sounds_off && !self.streaming_hides(|p| p.streamer_no_sounds)
    }
}

impl Default for LocalPrefs {
    fn default() -> Self {
        Self { zoom: 1.0, reduced_motion: false, hour24: false, sidebar_width: crate::ui::SIDEBAR_DEFAULT, theme_color: None,
            spellcheck: true,
            // Off until switched on: it contacts RustCord's own server.
            share_rustcord: false,
            skin_tone: 0,
            minimize_to_tray: true,
            desktop_notifications: true,
            unread_badge: true,
            sound_message: true,
            sound_current_channel: false,
            sound_ring: true,
            sounds_off: false,
            muted_cues: Vec::new(),
            theme_follow_device: false,
            theme_dark: String::new(),
            sync_theme: true,
            send_button: false,
            streamer_mode: false,
            streamer_hide_personal: true,
            streamer_hide_invites: true,
            streamer_no_sounds: true,
            streamer_no_notifications: true,
            chat_font_size: 16.0,
            group_spacing: 16.0,
            underline_links: false,
            saturation: 1.0,
            role_colors: 0,
            switch_icons: false,
            reduced_motion_sync: false,
            name_styles: true,
            open_animations: true,
            typing_animation: 0,
            typing_color_mode: 0,
            typing_color_anim: 0,
            typing_color_a: [88, 101, 242],
            typing_color_b: [235, 69, 158],
            compact_chat: false,
            compact_avatars: false,
            profile_themes: true,
            saturation_custom: false,
            high_contrast: false,
            contrast_sync: false,
            tts_rate: 0,
            image_descriptions: true,
            legacy_chat_input: false,
            debug_logging: false,
            ui_density: 1,
            toast_seconds: 5,
            animate_stickers: 0,
            experiments: Experiments::default(),
            trusted_domains: Vec::new(),
        }
    }
}

/// The Nitro client theme saved on your Discord account (settings-proto):
/// a gradient preset, or your own colours with their angle and base mix.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AccountTheme {
    pub colors: Vec<String>,
    pub angle: f32,
    pub base_mix: Option<f32>,
    pub preset: Option<u32>,
}

/// The preferences as this process last read or wrote them. A save writes
/// only what changed since, on top of the file as it is now, so another
/// RustCord (a second window, an older one still running) can't put back
/// settings it loaded before you changed them.
static PREFS_SEEN: std::sync::Mutex<Option<serde_json::Value>> = std::sync::Mutex::new(None);

pub fn load_prefs(dir: Option<&Path>) -> LocalPrefs {
    let prefs: LocalPrefs =
        dir.and_then(|d| std::fs::read_to_string(d.join("prefs.json")).ok()).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
    if let (Ok(mut seen), Ok(v)) = (PREFS_SEEN.lock(), serde_json::to_value(&prefs)) {
        *seen = Some(v);
    }
    prefs
}

pub fn save_prefs(dir: Option<&Path>, prefs: &LocalPrefs) {
    let Some(d) = dir else { return };
    let Ok(now) = serde_json::to_value(prefs) else { return };
    let f = d.join("prefs.json");
    let Ok(mut seen) = PREFS_SEEN.lock() else { return };
    let on_disk = std::fs::read_to_string(&f).ok().and_then(|s| serde_json::from_str(&s).ok());
    let merged = merge_changed(on_disk, seen.as_ref(), &now);
    let _ = std::fs::create_dir_all(d);
    if let Ok(s) = serde_json::to_string_pretty(&merged) {
        // Written whole then renamed, so a crash never leaves half a file.
        let tmp = f.with_extension("json.tmp");
        if std::fs::write(&tmp, s).is_ok() && std::fs::rename(&tmp, &f).is_ok() {
            *seen = Some(now);
        }
    }
}

/// `on_disk` with the fields of `now` that differ from `seen` (all of `now`
/// when there's no file or nothing was seen yet).
fn merge_changed(on_disk: Option<serde_json::Value>, seen: Option<&serde_json::Value>, now: &serde_json::Value) -> serde_json::Value {
    let (Some(serde_json::Value::Object(mut disk)), Some(serde_json::Value::Object(seen)), serde_json::Value::Object(now)) = (on_disk, seen, now)
    else {
        return now.clone();
    };
    for (key, value) in now {
        if seen.get(key) != Some(value) || !disk.contains_key(key) {
            disk.insert(key.clone(), value.clone());
        }
    }
    serde_json::Value::Object(disk)
}

/// Where you were, kept across restarts: the open server and channel, each
/// server's last channel and how far its channel list was scrolled, and the
/// categories you folded (`nav.json` beside `prefs.json`). Chat scroll
/// positions are kept only while RustCord runs.
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
#[serde(default)]
pub struct NavState {
    /// The open server (None = Home), and channel.
    pub guild: Option<Id>,
    pub channel: Option<Id>,
    /// (server or None for Home, its last channel).
    pub last_channel: Vec<(Option<Id>, Id)>,
    /// Categories folded / unfolded here (see `RustCord::collapsed`).
    pub collapsed: Vec<Id>,
    /// (server or None for Home, its channel list's scroll offset in points).
    pub channel_scroll: Vec<(Option<Id>, f32)>,
}

/// The file an account's place is kept in: `nav.json` in its config folder,
/// or RUSTCORD_DEV_NAV's file (test windows, so they never touch yours).
pub fn nav_file(account: Option<Id>) -> Option<PathBuf> {
    crate::diagnostics::dev_var_os("RUSTCORD_DEV_NAV").map(PathBuf::from).or_else(|| crate::accounts::config_folder(account?).map(|d| d.join("nav.json")))
}

/// None when there's no saved place yet (first run).
pub fn load_nav(file: Option<&Path>) -> Option<NavState> {
    file.and_then(|f| std::fs::read_to_string(f).ok()).and_then(|s| serde_json::from_str(&s).ok())
}

pub fn save_nav(file: Option<&Path>, nav: &NavState) {
    if let Some(f) = file {
        write_json(f, nav);
    }
}

/// Write a small JSON file whole, then rename it into place, so a crash
/// never leaves half a file.
pub fn write_json<T: serde::Serialize>(file: &Path, value: &T) {
    if let Some(d) = file.parent() {
        let _ = std::fs::create_dir_all(d);
    }
    if let Ok(s) = serde_json::to_string(value) {
        let tmp = file.with_extension("json.tmp");
        if std::fs::write(&tmp, s).is_ok() {
            let _ = std::fs::rename(&tmp, file);
        }
    }
}

pub fn apply_zoom(ctx: &egui::Context, zoom: f32) {
    // Dev aid: RUSTCORD_DEV_ZOOM=1 shows this window at that zoom whatever the
    // saved one (pixel comparisons with Discord; nothing is written).
    let zoom = crate::diagnostics::dev_var("RUSTCORD_DEV_ZOOM").ok().and_then(|z| z.parse().ok()).unwrap_or(zoom);
    if (ctx.zoom_factor() - zoom).abs() > 0.001 {
        ctx.set_zoom_factor(zoom);
    }
}

pub fn apply_prefs(prefs: &LocalPrefs) {
    use std::sync::atomic::Ordering::Relaxed;
    let reduced = if prefs.reduced_motion_sync { !crate::tray::system_animations() } else { prefs.reduced_motion };
    crate::ui::REDUCED_MOTION.store(reduced, Relaxed);
    crate::ui::motion::ENABLED.store(prefs.open_animations, Relaxed);
    crate::ui::CHAT_TEXT.store(prefs.chat_font_size.clamp(12.0, 24.0).to_bits(), Relaxed);
    crate::ui::GROUP_SPACING.store(prefs.group_spacing.clamp(0.0, 24.0).to_bits(), Relaxed);
    crate::ui::UNDERLINE_LINKS.store(prefs.underline_links, Relaxed);
    crate::ui::SWITCH_ICONS.store(prefs.switch_icons, Relaxed);
    crate::ui::ROLE_COLORS.store(prefs.role_colors, Relaxed);
    crate::ui::NAME_STYLES.store(prefs.name_styles, Relaxed);
    discord::reqlog::set_enabled(prefs.experiments.request_log);
    crate::ui::COMPACT.store(prefs.compact_chat, Relaxed);
    crate::ui::DENSITY.store(prefs.ui_density.min(2), Relaxed);
    crate::ui::COMPACT_AVATARS.store(prefs.compact_avatars, Relaxed);
    crate::ui::PROFILE_THEMES.store(prefs.profile_themes, Relaxed);
    crate::ui::CUSTOM_SATURATION.store(if prefs.saturation_custom { prefs.saturation.clamp(0.0, 1.0) } else { 1.0 }.to_bits(), Relaxed);
    crate::ui::HIDE_INVITES.store(prefs.streaming_hides(|p| p.streamer_hide_invites), Relaxed);
    crate::ui::IMAGE_ALT.store(prefs.image_descriptions, Relaxed);
    crate::ui::LEGACY_INPUT.store(prefs.legacy_chat_input, Relaxed);
    crate::diagnostics::set_debug(prefs.debug_logging);
    crate::ui::HOUR24.store(prefs.hour24, Relaxed);
    crate::spellcheck::ENABLED.store(prefs.spellcheck, Relaxed);
    crate::ui::STICKER_ANIM.store(prefs.animate_stickers.min(2), Relaxed);
}

/// Server folders left open last time (Discord remembers them too).
pub fn load_open_folders(dir: Option<&Path>) -> std::collections::HashSet<u64> {
    dir.and_then(|d| std::fs::read_to_string(d.join("open-folders.json")).ok())
        .and_then(|s| serde_json::from_str::<Vec<u64>>(&s).ok())
        .map(|v| v.into_iter().collect())
        .unwrap_or_default()
}

pub fn save_open_folders(dir: Option<&Path>, open: &std::collections::HashSet<u64>) {
    let Some(d) = dir else { return };
    let mut v: Vec<u64> = open.iter().copied().collect();
    v.sort_unstable();
    let _ = std::fs::create_dir_all(d);
    if let Ok(s) = serde_json::to_string(&v) {
        let _ = std::fs::write(d.join("open-folders.json"), s);
    }
}

fn is_image_name(name: &str) -> bool {
    let n = name.to_ascii_lowercase();
    [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"].iter().any(|e| n.ends_with(e))
}

impl RustCord {
    fn frame(&self) -> u64 {
        self.ctx.cumulative_pass_nr()
    }

    // ---- emoji ------------------------------------------------------------

    /// Remember an emoji as recently used (Unicode emoji only).
    pub fn use_emoji(&mut self, emoji: &str) {
        self.frequent.retain(|e| e != emoji);
        self.frequent.insert(0, emoji.to_string());
        self.frequent.truncate(24);
        if let Some(path) = frequent_path(self.config_dir.as_deref()) {
            if let Ok(json) = serde_json::to_string(&self.frequent) {
                let _ = std::fs::write(path, json);
            }
        }
    }

    /// The emoji rules for `channel` (see [`EmojiRules`]).
    pub fn emoji_rules(&self, channel: Option<Id>) -> EmojiRules {
        let ch = channel.and_then(|c| self.store.channels.get(&c));
        let here = ch.and_then(|c| c.guild_id);
        let external = match ch.filter(|c| c.guild_id.is_some()) {
            Some(c) => self.store.channel_perms(c).map_or(true, |p| p & discord::model::permissions::USE_EXTERNAL_EMOJIS != 0),
            None => true,
        };
        EmojiRules { here, nitro: self.has_nitro(), external }
    }

    /// Whether the server emoji `id` can be used in `channel`. An emoji not
    /// found in any server you're in can't be.
    pub fn custom_emoji_access(&self, id: Id, channel: Option<Id>) -> EmojiAccess {
        let rules = self.emoji_rules(channel);
        self.store
            .guilds
            .iter()
            .find_map(|(gid, g)| g.guild.emojis.iter().find(|e| e.id == Some(id)).map(|e| rules.access(*gid, e.animated, e.managed)))
            .unwrap_or(EmojiAccess::Locked)
    }

    pub fn open_emoji_picker(&mut self, target: PickerTarget, pos: Pos2) {
        self.emoji_picker = Some(EmojiPicker {
            target,
            pos,
            search: String::new(),
            opened_frame: self.frame(),
            hovered: None,
        });
    }

    /// Apply a pick: react, or insert into the composer.
    pub fn pick_emoji(&mut self, picked: PickedEmoji, keep_open: bool) {
        let Some(picker) = self.emoji_picker.as_ref() else { return };
        // (The pickers don't offer these; a Nitro-locked emoji would reach
        // Discord as plain ":name:" text.)
        if let PickedEmoji::Custom { id, .. } = &picked {
            if self.custom_emoji_access(*id, picker.target.channel(self.compose.poll.as_ref())) != EmojiAccess::Usable {
                return;
            }
        }
        match (&picker.target, &picked) {
            (PickerTarget::React { channel, msg }, PickedEmoji::Unicode(e)) => {
                let (c, m) = (*channel, *msg);
                self.add_reaction(c, m, ReactionEmoji::unicode(e));
            }
            (PickerTarget::React { channel, msg }, PickedEmoji::Custom { id, name, animated }) => {
                let (c, m) = (*channel, *msg);
                self.add_reaction(c, m, ReactionEmoji { id: Some(*id), name: Some(name.clone()), animated: *animated });
            }
            (PickerTarget::StatusReact { user, status }, _) => {
                let (user, status) = (*user, status.clone());
                let emoji = match &picked {
                    PickedEmoji::Unicode(e) => e.clone(),
                    PickedEmoji::Custom { id, name, animated } => format!("<{}:{name}:{id}>", if *animated { "a" } else { "" }),
                };
                self.emoji_picker = None;
                self.status_interaction(user, &status, "Reacted", &emoji);
                return;
            }
            (PickerTarget::PollAnswer(i), _) => {
                let i = *i;
                if let Some(a) = self.compose.poll.as_mut().and_then(|p| p.answers.get_mut(i)) {
                    a.1 = Some(picked.clone());
                }
                self.emoji_picker = None;
                return;
            }
            (PickerTarget::Insert { channel }, _) => {
                // The composer draws <:name:id> tokens as the emoji image, like Discord.
                let text = match &picked {
                    PickedEmoji::Unicode(e) => e.clone(),
                    PickedEmoji::Custom { id, name, animated } => format!("<{}:{name}:{id}>", if *animated { "a" } else { "" }),
                };
                let draft = self.drafts.entry(*channel).or_default();
                draft.push_str(&text);
            }
        }
        if let PickedEmoji::Unicode(e) = &picked {
            self.use_emoji(e);
        }
        if !keep_open {
            self.emoji_picker = None;
        }
    }

    /// Add your reaction (never removes; the picker and menu always add).
    pub fn add_reaction(&mut self, channel: Id, msg: Id, emoji: ReactionEmoji) {
        let already = self
            .store
            .message(channel, msg)
            .is_some_and(|m| m.reactions.iter().any(|r| r.me && r.emoji.same(&emoji)));
        if !already {
            self.track_reaction(&emoji);
            self.backend.send(Command::React { channel, msg, emoji, add: true });
        }
    }

    /// Turn `:name:` into `<:name:id>` (server emoji you may use in
    /// `channel`, its server first) or the Unicode emoji (`:smile:` → 😄),
    /// like Discord does when you send. A Nitro-locked emoji stays `:name:`
    /// text. Text inside `code` is left alone.
    pub fn expand_shortcodes(&self, text: &str, channel: Id) -> String {
        let rules = self.emoji_rules(Some(channel));
        let mut guilds = self.store.guild_order.clone();
        if let Some(g) = rules.here {
            guilds.retain(|x| *x != g);
            guilds.insert(0, g);
        }
        let lookup = |name: &str| -> Option<String> {
            for g in &guilds {
                let found = self.store.guilds.get(g).and_then(|gs| {
                    gs.guild.emojis.iter().find(|e| {
                        e.name.as_deref() == Some(name)
                            && e.id.is_some()
                            && e.available != Some(false)
                            && rules.access(*g, e.animated, e.managed) == EmojiAccess::Usable
                    })
                });
                if let Some(e) = found {
                    return Some(format!("<{}:{}:{}>", if e.animated { "a" } else { "" }, name, e.id.unwrap_or_default()));
                }
            }
            crate::emoji::by_any_name(name)
                .map(str::to_string)
                .or_else(|| crate::emoji::from_shortcode(name))
                .map(|e| crate::emoji::in_chosen_tone(&e).into_owned())
        };
        let mut out = String::with_capacity(text.len());
        let mut in_code = false;
        let mut rest = text;
        while let Some(i) = rest.find([':', '`', '<']) {
            out.push_str(&rest[..i]);
            let c = rest.as_bytes()[i];
            rest = &rest[i..];
            if c == b'`' {
                in_code = !in_code;
                out.push('`');
                rest = &rest[1..];
                continue;
            }
            if c == b'<' {
                // Skip existing <...> tokens untouched.
                match rest.find('>') {
                    Some(end) if end < 120 => {
                        out.push_str(&rest[..=end]);
                        rest = &rest[end + 1..];
                    }
                    _ => {
                        out.push('<');
                        rest = &rest[1..];
                    }
                }
                continue;
            }
            // ':' — try to read ":name:"
            let after = &rest[1..];
            let len = after.find(':').filter(|&l| (2..=32).contains(&l));
            match len {
                Some(l) if !in_code && after[..l].chars().all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-') => {
                    match lookup(&after[..l]) {
                        Some(rep) => {
                            out.push_str(&rep);
                            rest = &after[l + 1..];
                        }
                        None => {
                            out.push(':');
                            rest = after;
                        }
                    }
                }
                _ => {
                    out.push(':');
                    rest = after;
                }
            }
        }
        out.push_str(rest);
        out
    }

    // ---- uploads ----------------------------------------------------------

    /// A file for the next message. How big it may be is Discord's call
    /// (Nitro, server boosts, rollouts): it says so when the message is sent.
    pub fn add_upload(&mut self, channel: Id, name: String, data: discord::model::UploadData, size: u64) {
        // Like Discord: no files where you can't attach them (the message
        // would be refused with "Missing Permissions" once sent).
        let perms = self.store.channels.get(&channel).and_then(|c| self.store.channel_perms(c));
        if perms.is_some_and(|p| p & discord::model::permissions::ATTACH_FILES == 0) {
            self.toast("You don't have permission to attach files", true);
            return;
        }
        let list = self.uploads.entry(channel).or_default();
        if list.len() >= MAX_UPLOADS {
            self.toast("You can upload up to 10 files at once.", true);
            return;
        }
        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        list.push(PendingUpload {
            uri: format!("bytes://upload/{n}/{name}"),
            is_image: is_image_name(&name),
            data,
            size,
            name,
        });
    }

    /// Bytes already in memory (a pasted picture).
    pub fn add_upload_bytes(&mut self, channel: Id, name: String, bytes: Vec<u8>) {
        let size = bytes.len() as u64;
        self.add_upload(channel, name, discord::model::UploadData::Memory(bytes.into()), size);
    }

    /// Files or a picture pasted into the message box: uploads, like Discord.
    pub fn add_clip(&mut self, channel: Id, clip: crate::clipboard::Clip) {
        match clip {
            crate::clipboard::Clip::Files(paths) => self.add_upload_paths(channel, paths),
            crate::clipboard::Clip::Image(png) => self.add_upload_bytes(channel, "image.png".into(), png),
            crate::clipboard::Clip::Text(_) => {}
        }
    }

    pub fn add_upload_paths(&mut self, channel: Id, paths: Vec<PathBuf>) {
        for path in paths {
            let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file".into());
            // Pictures are read for their preview; anything else is read
            // while it's sent.
            let read = if is_image_name(&name) {
                std::fs::read(&path).map(|b| (b.len() as u64, discord::model::UploadData::Memory(b.into())))
            } else {
                std::fs::metadata(&path).map(|m| (m.len(), discord::model::UploadData::Disk(path.clone())))
            };
            match read {
                Ok((size, data)) => self.add_upload(channel, name, data, size),
                Err(e) => self.toast(format!("Couldn't read {name}: {e}"), true),
            }
        }
    }

    /// Native file dialog (the composer's "+" button).
    pub fn pick_files(&mut self, channel: Id) {
        if let Some(paths) = rfd::FileDialog::new().set_title("Upload a file").pick_files() {
            self.add_upload_paths(channel, paths);
        }
    }

    pub fn remove_upload(&mut self, channel: Id, index: usize) {
        if let Some(list) = self.uploads.get_mut(&channel) {
            if index < list.len() {
                let u = list.remove(index);
                self.ctx.forget_image(&u.uri);
            }
        }
    }

    // ---- audio ------------------------------------------------------------

    pub fn audio_toggle(&mut self, url: &str) {
        match self.audio.toggle(url) {
            Ok(Some(download)) => self.backend.send(Command::FetchBytes(download)),
            Ok(None) => {}
            Err(e) => self.toast(e, true),
        }
    }

    // ---- message actions --------------------------------------------------

    pub fn start_forward(&mut self, channel: Id, msg: Id) {
        self.forward = Some(ForwardState { share: None, channel, msg, search: String::new(), note: String::new(), target: None });
    }

    /// "Share Profile": pick where their profile link goes.
    pub fn start_share(&mut self, link: String) {
        self.forward = Some(ForwardState { share: Some(link), channel: Id(0), msg: Id(0), search: String::new(), note: String::new(), target: None });
    }

    pub fn send_forward(&mut self) {
        let Some(f) = self.forward.take() else { return };
        let Some(target) = f.target else { return };
        let guild_id = self.store.channels.get(&f.channel).and_then(|c| c.guild_id);
        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1 << 11);
        let nonce = || {
            let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed) & 0xFFF;
            let ms = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis() as u64)
                .unwrap_or(0);
            Id(Id::from_timestamp_ms(ms).0 | n).to_string()
        };
        let message = match &f.share {
            Some(text) => OutgoingMessage { channel_id: target, content: text.clone(), nonce: nonce(), ..Default::default() },
            None => OutgoingMessage {
                channel_id: target,
                nonce: nonce(),
                message_reference: Some(MessageReference { kind: 1, message_id: f.msg, channel_id: f.channel, guild_id }),
                ..Default::default()
            },
        };
        self.backend.send(Command::Send(message));
        if !f.note.trim().is_empty() {
            let mut note = OutgoingMessage { channel_id: target, content: f.note.trim().to_string(), nonce: nonce(), ..Default::default() };
            if self.rencord.before_send(&mut note) {
                self.backend.send(Command::Send(note));
            }
        }
        self.toast(format!("Forwarded to {}", self.destination_name(target)), false);
    }

    pub fn destination_name(&self, channel: Id) -> String {
        match self.store.channels.get(&channel) {
            Some(c) if c.guild_id.is_some() => format!("#{}", crate::store::Store::channel_label(c)),
            Some(c) => self.store.label(c),
            None => "channel".into(),
        }
    }

    /// Whether `channel`'s messages offer "Add Reaction" and the quick
    /// reactions (see [`crate::store::Store::can_add_reactions`]).
    pub fn can_add_reactions(&self, channel: Id) -> bool {
        self.store.channels.get(&channel).is_none_or(|c| self.store.can_add_reactions(c))
    }

    /// Whether you may pin and unpin in `channel`: always in DMs and group
    /// DMs; in a server with Manage Messages or Discord's newer Pin Messages
    /// (the channel's overwrites applied when RustCord knows them).
    pub fn can_pin(&self, channel: Id) -> bool {
        const MANAGE_MESSAGES: u64 = 1 << 13;
        const PIN_MESSAGES: u64 = 1 << 51;
        let Some(ch) = self.store.channels.get(&channel) else { return false };
        let Some(guild) = ch.guild_id else { return true };
        match self.store.channel_perms(ch) {
            Some(p) => p & (MANAGE_MESSAGES | PIN_MESSAGES) != 0,
            None => self.store.has_perm(guild, MANAGE_MESSAGES | PIN_MESSAGES),
        }
    }

    /// Pin (or unpin) `message` once you've confirmed it, like Discord — or
    /// at once with Shift held.
    pub fn ask_pin(&mut self, message: discord::model::Message, pin: bool) {
        if self.ctx.input(|i| i.modifiers.shift) {
            self.set_pinned(message.channel_id, message.id, pin);
        } else {
            self.pin_confirm = Some(PinConfirm { message, pin });
        }
    }

    /// Pin / unpin now. Shown at once (undone by `Event::PinFailed`); no
    /// toast, as on Discord.
    pub fn set_pinned(&mut self, channel: Id, msg: Id, pinned: bool) {
        if let Some(m) = self.store.message_mut(channel, msg) {
            m.pinned = pinned;
        }
        // The open popout drops an unpinned message right away; a new pin
        // arrives with the reload CHANNEL_PINS_UPDATE triggers.
        if let (false, Some((c, _, Some(Ok(list))))) = (pinned, self.pins.as_mut()) {
            if *c == channel {
                list.retain(|m| m.id != msg);
            }
        }
        self.backend.send(Command::Pin { channel, msg, pinned });
    }

    pub fn mark_unread(&mut self, channel: Id, msg: Id) {
        self.unread_marker.insert(channel, msg);
        self.store.mark_unread_from(channel, msg);
        // Discord's "Mark Unread" acks the message *before* the chosen one.
        let previous = self
            .store
            .messages
            .get(&channel)
            .and_then(|cm| cm.list.iter().rev().find(|m| m.id < msg).map(|m| m.id))
            .unwrap_or(Id(msg.0.saturating_sub(1)));
        self.backend.send(Command::AckManual { channel, msg: previous, mentions: 0 });
    }

    // ---- status -------------------------------------------------------------

    /// Set your status ("online" | "idle" | "dnd" | "invisible") and custom status.
    pub fn set_status(&mut self, status: &str, custom: Option<discord::settings_proto::CustomStatus>) {
        self.store.my_status = status.to_string();
        self.store.my_custom = custom.clone();
        self.backend.send(Command::SetStatus { status: status.to_string(), custom });
    }

    /// Resting the pointer on a channel / DM for a moment starts loading its
    /// messages, so they're usually there by the time you click.
    pub fn hover_prefetch(&mut self, channel: Id) {
        let is_text = self.store.channels.get(&channel).is_some_and(|c| discord::model::channel_kind::is_text(c.kind));
        if !is_text {
            return;
        }
        match self.hover_prefetch {
            Some((c, since)) if c == channel => {
                if since.elapsed() >= std::time::Duration::from_millis(150) {
                    self.ensure_loaded(channel);
                } else {
                    self.ctx.request_repaint_after(std::time::Duration::from_millis(160));
                }
            }
            _ => {
                self.hover_prefetch = Some((channel, std::time::Instant::now()));
                self.ctx.request_repaint_after(std::time::Duration::from_millis(160));
            }
        }
    }

    /// Accept or ignore a message request (shown at once; Discord confirms).
    pub fn answer_request(&mut self, channel: Id, accept: bool) {
        self.backend.send(Command::AnswerRequest { channel, accept });
        if accept {
            if let Some(c) = self.store.channels.get_mut(&channel) {
                c.is_message_request = false;
            }
            self.requests_open = false;
            self.select_channel(Some(channel));
        } else {
            self.store.channels.remove(&channel);
            if self.current_channel == Some(channel) {
                self.current_channel = None;
                self.friends_open = true;
                self.requests_open = true;
            }
        }
    }

    /// Home → Nitro Home / Shop / Quests (loads its data the first time;
    /// Quests refresh every time, since progress moves).
    pub fn open_store_page(&mut self, page: StorePage) {
        self.friends_open = true;
        self.requests_open = false;
        self.store_page = Some(page);
        self.current_channel = None;
        match page {
            StorePage::Quests => self.backend.send(Command::FetchQuests),
            StorePage::Shop if !matches!(self.shop, Some(Ok(_))) => {
                self.shop = None;
                self.backend.send(Command::FetchShop);
                if self.orbs.is_none() {
                    // The Orbs balance comes with the quests.
                    self.backend.send(Command::FetchQuests);
                }
            }
            StorePage::Nitro if !matches!(self.nitro, Some(Ok(_))) => {
                self.nitro = None;
                self.backend.send(Command::FetchNitro);
            }
            _ => {}
        }
    }

    /// Home → Message Requests.
    pub fn open_message_requests(&mut self) {
        self.friends_open = true;
        self.requests_open = true;
        self.store_page = None;
        self.current_channel = None;
        let missing: Vec<Id> = self
            .store
            .channels
            .values()
            .filter(|c| c.is_message_request && !self.request_previews.contains_key(&c.id))
            .map(|c| c.id)
            .collect();
        if !missing.is_empty() {
            self.backend.send(Command::FetchRequestPreviews(missing));
        }
    }

    /// Clicked a server tag: show that server's card (click again to close).
    pub fn open_tag_popout(&mut self, guild: Id, pos: Pos2) {
        if self.tag_popout.is_some_and(|(g, _, _)| g == guild) {
            self.tag_popout = None;
            return;
        }
        if !matches!(self.guild_profiles.get(&guild), Some(Ok(_))) {
            self.guild_profiles.remove(&guild);
            self.backend.send(Command::FetchGuildProfile(guild));
        }
        self.tag_popout = Some((guild, pos, self.frame()));
    }

    /// "Set a custom status" dialog, starting from the current text.
    pub fn open_custom_status_dialog(&mut self) {
        self.account_menu = None;
        self.custom_status_dialog = Some(self.store.my_custom.as_ref().map(|c| c.text.clone()).unwrap_or_default());
    }

    pub fn toggle_account_menu(&mut self, anchor: Pos2) {
        if self.account_menu.is_some() {
            self.account_menu = None;
            return;
        }
        self.profile = None;
        self.account_menu = Some(AccountMenu { pos: anchor, opened_frame: self.frame(), status_open: false, switch_open: false, orbs_open: false });
        if let Some(me) = self.store.me.clone() {
            if !self.profiles.contains_key(&(me.id, None)) {
                self.backend.send(Command::FetchProfile { user: me.id, guild: None });
            }
        }
    }

    /// Accept / add (true) or decline / remove (false). `location`: where the
    /// click was, as Discord's client names it ("Friends", "User Profile",
    /// "DM Channel", "Context Menu"). The backend sends these one at a time,
    /// paced; a person already waiting in that queue isn't queued twice.
    pub fn relationship(&mut self, user: Id, add: bool, location: &'static str) {
        if !self.relationship_busy.insert(user) {
            return;
        }
        if self.relationship_busy.len() == 3 {
            self.toast("Sending friend requests one at a time, so Discord doesn't flag your account.", false);
        }
        self.backend.send(Command::Relationship { user, add, location });
    }

    /// A friend-list change for `user` is waiting or on its way.
    pub fn relationship_pending(&self, user: Id) -> bool {
        self.relationship_busy.contains(&user)
    }

    pub fn copy_link(&mut self, channel: Id, msg: Id) {
        if let Some(m) = self.store.message(channel, msg) {
            self.ctx.copy_text(m.link());
            self.toast("Message link copied.", false);
        }
    }

    /// Read a message aloud with the OS speech synthesizer.
    pub fn speak(&mut self, channel: Id, msg: Id) {
        let Some(m) = self.store.message(channel, msg) else { return };
        let who = self.store.nick_in(None, Some(channel), m.author.id).unwrap_or_else(|| m.display_name().to_string());
        let text = format!("{who} said {}", m.content);
        #[cfg(windows)]
        {
            use std::os::windows::process::CommandExt;
            const CREATE_NO_WINDOW: u32 = 0x0800_0000;
            // The text goes through an environment variable, never the command line.
            let spawned = std::process::Command::new("powershell")
                .args([
                    "-NoProfile",
                    "-NonInteractive",
                    "-Command",
                    "Add-Type -AssemblyName System.Speech; $s = New-Object System.Speech.Synthesis.SpeechSynthesizer; $s.Rate = [int]$env:RUSTCORD_TTS_RATE; $s.Speak($env:RUSTCORD_TTS)",
                ])
                .env("RUSTCORD_TTS", text)
                .env("RUSTCORD_TTS_RATE", self.prefs.tts_rate.clamp(-10, 10).to_string())
                .creation_flags(CREATE_NO_WINDOW)
                .spawn();
            if let Err(e) = spawned {
                self.toast(format!("Couldn't start text-to-speech: {e}"), true);
            }
        }
        // speech-dispatcher, which most desktops have. Its rate runs -100..100.
        #[cfg(target_os = "linux")]
        {
            let rate = (self.prefs.tts_rate.clamp(-10, 10) * 10).to_string();
            if let Err(e) = std::process::Command::new("spd-say").args(["-r", &rate, "--", &text]).spawn() {
                self.toast(format!("Couldn't start text-to-speech (spd-say): {e}"), true);
            }
        }
        // macOS's own voice. The rate is in words a minute (about 175 by
        // default); -10..10 spans a third of that to three times it, as on Windows.
        #[cfg(target_os = "macos")]
        {
            let words_per_minute = (175.0 * 3f32.powf(self.prefs.tts_rate.clamp(-10, 10) as f32 / 10.0)).round().to_string();
            if let Err(e) = std::process::Command::new("say").args(["-r", &words_per_minute, "--", &text]).spawn() {
                self.toast(format!("Couldn't start text-to-speech (say): {e}"), true);
            }
        }
        #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
        {
            let _ = text;
            self.toast("Speak Message isn't available on this system yet.", false);
        }
    }

    // ---- profiles ---------------------------------------------------------

    pub fn open_profile(&mut self, user: User, guild: Option<Id>, pos: Pos2) {
        if !self.profiles.contains_key(&(user.id, guild)) || self.profiles.get(&(user.id, guild)).is_some_and(|r| r.is_err()) {
            self.backend.send(Command::FetchProfile { user: user.id, guild });
        }
        // (A reply to their status left unfinished last time is forgotten.)
        self.ctx.data_mut(|d| d.remove::<String>(egui::Id::new(("status_reply", user.id.0))));
        self.profile = Some(ProfilePopout { user, guild, pos, opened_frame: self.frame(), dm_draft: String::new() });
    }

    // ---- GIFs ---------------------------------------------------------------

    /// The expression picker on its GIF tab (or closed, if that's showing).
    /// `pos`: the composer's top-right corner; the picker sits above it.
    pub fn toggle_gif_picker(&mut self, channel: Id, pos: Pos2) {
        self.toggle_expression(channel, ExpressionTab::Gifs, pos);
    }

    /// The GIF tab's search state.
    pub fn start_gif_search(&mut self, channel: Id) {
        if self.gif_picker.as_ref().is_some_and(|g| g.channel == channel) {
            return;
        }
        // Trending GIFs were fetched at startup: show them straight away and
        // refresh quietly.
        let cached = self.gif_trending.clone();
        self.backend.send(Command::FetchGifs(None));
        self.gif_picker = Some(GifPicker {
            channel,
            search: String::new(),
            query: None,
            results: cached.map(Ok),
            edited: None,
            shown: Default::default(),
        });
    }

    /// After login, quietly fetch what the pickers list (trending GIFs,
    /// favourites, sticker use): the lists only, no pictures. Those load
    /// when a picker is opened.
    pub fn warm_up(&mut self) {
        if self.gif_trending.is_none() {
            self.backend.send(Command::FetchGifs(None));
        }
        // Favourite GIFs and sticker use, for the expression picker.
        self.want_frecency();
        // Your Discord settings (embeds, reactions, animated emoji…).
        if !self.demo {
            self.api_get_once("us:settings", "/users/@me/settings");
        }
    }

    /// Run the debounced search once typing pauses.
    pub fn gif_search_tick(&mut self) {
        let Some(g) = self.gif_picker.as_mut() else { return };
        let Some(at) = g.edited else { return };
        if at.elapsed() < std::time::Duration::from_millis(350) {
            self.ctx.request_repaint_after(std::time::Duration::from_millis(120));
            return;
        }
        g.edited = None;
        let q = g.search.trim().to_string();
        let query = (!q.is_empty()).then_some(q);
        if query != g.query || g.results.as_ref().is_some_and(|r| r.is_err()) {
            g.query = query.clone();
            g.results = None;
            self.backend.send(Command::FetchGifs(query));
        }
    }

    /// Send a GIF: Discord posts the Tenor link and embeds it.
    pub fn send_gif(&mut self, url: String) {
        let Some(channel) = self.gif_picker.as_ref().map(|g| g.channel) else { return };
        // (Closes the GIF picker too, letting its clips go.)
        self.close_expression();
        self.close_gif_picker();
        self.send_message(channel, url);
    }

    /// Close the GIF picker and give back what its tiles decoded: their
    /// clips' frames and their stills (the files stay in the disk cache, so
    /// opening it again costs a decode, not a download).
    pub fn close_gif_picker(&mut self) {
        if let Some(g) = self.gif_picker.take() {
            for uri in &g.shown {
                self.ctx.forget_image(uri);
            }
            if !g.shown.is_empty() {
                crate::diagnostics::release_unused_memory();
            }
        }
    }

    /// Open the DM with `user` and, if `text` isn't empty, send it there.
    pub fn open_dm_with(&mut self, user: Id, text: String) {
        self.profile = None;
        let existing = self.store.channels.values().find(|c| {
            c.kind == discord::model::channel_kind::DM && c.recipients.first().is_some_and(|u| u.id == user)
        });
        match existing.map(|c| c.id) {
            Some(id) => {
                self.current_guild = None;
                self.select_channel(Some(id));
                if !text.is_empty() {
                    self.ensure_loaded(id);
                    self.send_message(id, text);
                }
            }
            None => {
                self.pending_dm = (!text.is_empty()).then_some((user, text));
                self.backend.send(Command::OpenDm(user));
            }
        }
    }

    /// Files dropped onto the window go to the current channel.
    pub fn handle_dropped_files(&mut self, ctx: &egui::Context) {
        let dropped = ctx.input(|i| i.raw.dropped_files.clone());
        if dropped.is_empty() {
            return;
        }
        let Some(channel) = self.current_channel else { return };
        for f in dropped {
            match (f.path, f.bytes) {
                (Some(path), _) => self.add_upload_paths(channel, vec![path]),
                (None, Some(bytes)) => {
                    let size = bytes.len() as u64;
                    self.add_upload(channel, f.name.clone(), discord::model::UploadData::Memory(bytes), size);
                }
                _ => {}
            }
        }
    }
}

/// The expression picker's tabs, in Discord's order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExpressionTab {
    Gifs,
    Stickers,
    Emoji,
}

/// What the GIF tab shows while its search box is empty.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GifPage {
    /// Favourites / Trending / category tiles.
    #[default]
    Home,
    Favourites,
    Trending,
}

/// Discord's expression picker over the composer: GIFs | Stickers | Emoji
/// in one popup. (The GIF tab's search lives in `RustCord::gif_picker`.)
pub struct ExpressionPicker {
    pub channel: Id,
    pub tab: ExpressionTab,
    /// The composer's top-right corner: the picker sits above it.
    pub anchor: Pos2,
    pub opened_frame: u64,
    /// Frame the tab last changed (its search box takes the cursor).
    pub tab_frame: u64,
    pub sticker_search: String,
    /// Sticker shown in the footer (the last one hovered).
    pub sticker_hovered: Option<Id>,
    pub emoji_search: String,
    /// (image, :name:, server) of the hovered emoji, for the footer.
    pub emoji_hovered: Option<(String, String, Option<Id>)>,
    pub gif_page: GifPage,
    /// Search box of the Favourites page.
    pub favourites_search: String,
}

fn recent_stickers_path(dir: Option<&Path>) -> Option<PathBuf> {
    dir.map(|d| d.join("recent-stickers.json"))
}

/// Stickers sent from RustCord, newest first.
pub fn load_recent_stickers(dir: Option<&Path>) -> Vec<Id> {
    recent_stickers_path(dir)
        .and_then(|p| std::fs::read_to_string(p).ok())
        .and_then(|s| serde_json::from_str::<Vec<String>>(&s).ok())
        .map(|v| v.iter().filter_map(|s| s.parse().ok()).map(Id).collect())
        .unwrap_or_default()
}

pub fn save_recent_stickers(dir: Option<&Path>, list: &[Id]) {
    let Some(path) = recent_stickers_path(dir) else { return };
    let ids: Vec<String> = list.iter().map(|i| i.0.to_string()).collect();
    if let Ok(json) = serde_json::to_string(&ids) {
        let _ = std::fs::write(path, json);
    }
}

/// A sticker's popout (Discord's StickerPopout), opened by clicking a sticker
/// in a message. Its data comes from `GET /stickers/{id}` ("sticker:{id}"),
/// then the pack list ("sticker-packs") or the server's public card
/// ("sticker-guild:{id}").
pub struct StickerPopout {
    pub sticker: discord::model::StickerItem,
    /// The channel the message is in (whether it's "this server").
    pub channel: Id,
    /// The message it's in (one sticker can be in many messages).
    pub message: Id,
    /// The sticker's rect in the message: the popout sits 8 px to its right.
    pub anchor: egui::Rect,
    /// Frame it opened (the click that opened it doesn't close it).
    pub opened: u64,
    /// "Show More Stickers" is open.
    pub show_more: bool,
}

impl RustCord {
    /// Clicked a sticker: open its popout (again on the same one closes it).
    pub fn open_sticker_popout(&mut self, sticker: discord::model::StickerItem, channel: Id, message: Id, anchor: egui::Rect) {
        if self.sticker_popout.as_ref().is_some_and(|p| p.sticker.id == sticker.id && p.message == message) {
            self.sticker_popout = None;
            return;
        }
        let id = sticker.id;
        // (A failed lookup is asked again when the popout opens again.)
        if matches!(self.api_result(&format!("sticker:{id}")), Some(Err(_))) {
            self.api_take(&format!("sticker:{id}"));
        }
        self.api_get_once(&format!("sticker:{id}"), format!("/stickers/{id}"));
        self.sticker_popout = Some(StickerPopout { sticker, channel, message, anchor, opened: self.frame(), show_more: false });
    }
}

#[cfg(test)]
mod tests {
    use super::merge_changed;
    use serde_json::json;

    #[test]
    fn typing_animation_keeps_keyboard_zoom() {
        let ctx = eframe::egui::Context::default();
        let mut prefs = super::LocalPrefs { zoom: 1.2, ..Default::default() };
        super::apply_zoom(&ctx, prefs.zoom);
        let _ = ctx.run(Default::default(), |ctx| eframe::egui::gui_zoom::zoom_in(ctx));
        let _ = ctx.run(Default::default(), |_| {});
        let zoom = ctx.zoom_factor();
        assert!(zoom > prefs.zoom);

        prefs.typing_animation = 1;
        super::apply_prefs(&prefs);
        let _ = ctx.run(Default::default(), |_| {});
        assert_eq!(ctx.zoom_factor(), zoom);

        super::apply_zoom(&ctx, 1.0);
        let _ = ctx.run(Default::default(), |_| {});
        assert_eq!(ctx.zoom_factor(), 1.0);
    }

    #[test]
    fn a_save_keeps_what_another_window_changed() {
        // This window loaded 120% and only moved the sidebar; another set 110%.
        let seen = json!({ "zoom": 1.2, "sidebar_width": 312.0 });
        let now = json!({ "zoom": 1.2, "sidebar_width": 340.0 });
        let disk = json!({ "zoom": 1.1, "sidebar_width": 312.0 });
        assert_eq!(merge_changed(Some(disk), Some(&seen), &now), json!({ "zoom": 1.1, "sidebar_width": 340.0 }));
    }

    #[test]
    fn a_first_save_or_a_missing_file_writes_everything() {
        let now = json!({ "zoom": 1.1, "hour24": true });
        assert_eq!(merge_changed(None, Some(&now), &now), now);
        assert_eq!(merge_changed(Some(json!({ "zoom": 1.5 })), None, &now), now);
        // A field the file doesn't have yet (a newer RustCord's) is added.
        assert_eq!(merge_changed(Some(json!({ "zoom": 1.5 })), Some(&now), &now), json!({ "zoom": 1.5, "hour24": true }));
    }
}