Skip to content

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

47.8 KB
Raw Blame
//! Server Settings → Stickers and Soundboard, and the pieces the pages in
//! `ss_*.rs` share: their dialogs, their Discord calls in flight and their
//! state in egui's temp memory.

use super::{Act, Btn, Theme};
use crate::app::RustCord;
use crate::style::{bold, icon, icon_font, overlay};
use discord::model::{GuildEmoji, Id, User};
use eframe::egui::{
    self, epaint::Shadow, pos2, vec2, Align, Align2, Color32, CursorIcon, FontId, Frame, Key, Label, Layout, Margin, Order,
    Rect, Response, RichText, Rounding, Sense, Stroke, Ui, Vec2,
};
use reqwest::Method;
use serde::Deserialize;
use serde_json::{json, Value};
use std::path::Path;
use std::sync::Arc;

// ---- shared by the pages in ss_*.rs ----------------------------------------------

/// Discord calls a page has in flight: (api tag, what the call was for).
#[derive(Clone)]
pub(super) struct Calls<Op>(Vec<(String, Op)>);

impl<Op> Default for Calls<Op> {
    fn default() -> Self {
        Self(Vec::new())
    }
}

impl<Op: Clone + 'static> Calls<Op> {
    /// Start a call: `send` makes it, answering under the tag it's given.
    pub(super) fn start(&mut self, acts: &mut Vec<Act>, op: Op, send: impl FnOnce(&mut RustCord, &str) + 'static) {
        let tag = format!("ss:page-call:{}", super::next_seq());
        self.0.push((tag.clone(), op));
        acts.push(Act::Run(Box::new(move |app: &mut RustCord| send(app, &tag))));
    }

    /// Is a call like this in flight?
    pub(super) fn busy(&self, f: impl Fn(&Op) -> bool) -> bool {
        self.0.iter().any(|(_, op)| f(op))
    }

    /// Hand the calls Discord has answered to `done` (run after the frame,
    /// with `&mut RustCord`).
    pub(super) fn poll(&mut self, app: &RustCord, acts: &mut Vec<Act>, done: fn(&mut RustCord, Op, Result<Value, String>)) {
        self.0.retain(|(tag, op)| {
            if app.api_result(tag).is_none() {
                return true;
            }
            let (tag, op) = (tag.clone(), op.clone());
            acts.push(Act::Run(Box::new(move |app: &mut RustCord| {
                if let Some(r) = app.api_take(&tag) {
                    done(app, op, r);
                }
            })));
            false
        });
    }
}

/// A page's state from egui's temp memory (a fresh one the first time).
pub(super) fn page_state<T: Clone + Default + Send + Sync + 'static>(ui: &Ui, id: egui::Id) -> T {
    ui.data(|d| d.get_temp(id)).unwrap_or_default()
}

/// Change a page's state from an `Act::Run` (after the frame was drawn).
pub(super) fn with_state<T: Clone + Default + Send + Sync + 'static>(app: &RustCord, id: egui::Id, f: impl FnOnce(&mut T)) {
    app.ctx.data_mut(|d| f(d.get_temp_mut_or_default::<T>(id)));
}

/// True on the first frame of a visit to a page (it wasn't drawn the frame
/// before): pages fetch their lists afresh then.
pub(super) fn new_visit(ui: &Ui, id: egui::Id) -> bool {
    let pass = ui.ctx().cumulative_pass_nr();
    let id = id.with("visit");
    let last = ui.data_mut(|d| {
        let last = d.get_temp::<u64>(id);
        d.insert_temp(id, pass);
        last
    });
    last.is_none_or(|l| l + 1 < pass)
}

/// The dialog's popup id: while one is open, Server Settings leaves Esc to it
/// instead of closing the whole screen.
fn dialog_id() -> egui::Id {
    egui::Id::new("ss_page_dialog")
}

/// Drop the Esc guard a closed dialog left behind. Pages call this before
/// drawing; `dialog` takes the guard again while one is showing.
pub(super) fn release_dialog(ui: &Ui) {
    release_dialog_ctx(ui.ctx());
}

/// [`release_dialog`] without a `Ui` (Server Settings calls it once closed).
pub(super) fn release_dialog_ctx(ctx: &egui::Context) {
    ctx.memory_mut(|m| {
        if m.is_popup_open(dialog_id()) {
            m.close_popup();
        }
    });
}

/// A Discord dialog over the settings screen, drawn like `ss_modal`'s:
/// dimmed backdrop, title, `body`, then Cancel and the `confirm` button.
/// Some(true) when confirmed, Some(false) when dismissed (Cancel, Esc or a
/// click outside), None otherwise.
pub(super) fn dialog(ui: &Ui, t: &Theme, heading: &str, confirm: &str, kind: Btn, enabled: bool, body: impl FnOnce(&mut Ui)) -> Option<bool> {
    let ctx = ui.ctx().clone();
    ctx.memory_mut(|m| m.open_popup(dialog_id()));
    let screen = ctx.screen_rect();
    let mut out = None;
    egui::Area::new(egui::Id::new("ss_page_dialog_dim")).order(Order::Tooltip).fixed_pos(screen.min).show(&ctx, |ui| {
        let (r, resp) = ui.allocate_exact_size(screen.size(), Sense::click());
        ui.painter().rect_filled(r, 0.0, Color32::from_black_alpha(170));
        if resp.clicked() {
            out = Some(false);
        }
    });
    egui::Area::new(dialog_id()).order(Order::Tooltip).anchor(Align2::CENTER_CENTER, Vec2::ZERO).show(&ctx, |ui| {
        ui.ctx().move_to_top(ui.layer_id());
        Frame::none()
            .fill(t.bg_primary)
            .rounding(12.0)
            .stroke(Stroke::new(1.0_f32, t.border_subtle))
            .shadow(Shadow { offset: vec2(0.0, 8.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(140) })
            .show(ui, |ui| {
                ui.set_width(440.0);
                let gap = ui.spacing().item_spacing.y;
                ui.spacing_mut().item_spacing.y = 0.0;
                Frame::none().inner_margin(Margin { left: 16.0, right: 16.0, top: 20.0, bottom: 20.0 }).show(ui, |ui| {
                    ui.set_width(ui.available_width());
                    ui.add(Label::new(bold(heading).size(20.0).color(t.header_primary)).truncate());
                    ui.add_space(14.0);
                    ui.spacing_mut().item_spacing.y = gap;
                    body(ui);
                });
                Frame::none()
                    .fill(t.bg_secondary)
                    .rounding(Rounding { nw: 0.0, ne: 0.0, sw: 12.0, se: 12.0 })
                    .inner_margin(Margin::symmetric(16.0, 14.0))
                    .show(ui, |ui| {
                        ui.set_width(ui.available_width());
                        ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                            if super::btn(ui, t, kind, confirm, enabled).clicked() {
                                out = Some(true);
                            }
                            ui.add_space(8.0);
                            if super::link(ui, "Cancel", t.text_normal).clicked() {
                                out = Some(false);
                            }
                        });
                    });
            });
    });
    if ctx.input(|i| i.key_pressed(Key::Escape)) {
        out = Some(false);
    }
    if out.is_some() {
        ctx.memory_mut(|m| m.close_popup());
    }
    out
}

/// A labelled text box (in a dialog or a form).
#[allow(clippy::too_many_arguments)]
pub(super) fn field(ui: &mut Ui, t: &Theme, label: &str, id: egui::Id, text: &mut String, hint: &str, rows: usize, limit: usize) {
    super::section(ui, t, label);
    let w = ui.available_width();
    super::input(ui, t, id, text, hint, rows, limit, w);
    ui.add_space(16.0);
}

/// Whether `s` (trimmed) is `min..=max` characters long.
pub(super) fn length_ok(s: &str, min: usize, max: usize) -> bool {
    (min..=max).contains(&s.trim().chars().count())
}

/// A file picked for upload, with a `bytes://` URI for its preview.
#[derive(Clone)]
struct Upload {
    name: String,
    stem: String,
    bytes: Arc<[u8]>,
    mime: &'static str,
    uri: String,
}

impl Upload {
    /// Read a file Discord takes (`kind` sniffs its MIME type and extension
    /// from the first bytes), up to `max` bytes.
    fn read(path: &Path, max: usize, kind: fn(&[u8]) -> Option<(&'static str, &'static str)>, wrong: &str) -> Result<Upload, String> {
        let bytes = std::fs::read(path).map_err(|e| format!("Couldn't read the file: {e}"))?;
        let (mime, ext) = kind(&bytes).ok_or_else(|| wrong.to_string())?;
        if bytes.len() > max {
            return Err(format!("That file is too big (the limit is {} KB).", max / 1024));
        }
        let name = path.file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_else(|| format!("upload.{ext}"));
        let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
        let uri = format!("bytes://ss-upload-{}.{ext}", super::next_seq());
        Ok(Upload { name, stem, bytes: bytes.into(), mime, uri })
    }

    /// A name for it from the file name, cut to `max` characters.
    fn suggested_name(&self, max: usize) -> String {
        let s: String = self.stem.trim().chars().take(max).collect();
        if s.chars().count() >= 2 {
            s
        } else {
            String::new()
        }
    }
}

fn sticker_kind(b: &[u8]) -> Option<(&'static str, &'static str)> {
    if b.starts_with(&[0x89, b'P', b'N', b'G']) {
        Some(("image/png", "png"))
    } else if b.starts_with(b"GIF8") {
        Some(("image/gif", "gif"))
    } else {
        None
    }
}

fn sound_kind(b: &[u8]) -> Option<(&'static str, &'static str)> {
    // An ID3 tag, or straight into an MPEG audio frame (11 sync bits).
    if b.starts_with(b"ID3") || (b.len() > 1 && b[0] == 0xff && b[1] & 0xe0 == 0xe0) {
        Some(("audio/mpeg", "mp3"))
    } else if b.starts_with(b"OggS") {
        Some(("audio/ogg", "ogg"))
    } else {
        None
    }
}

/// How long a sound plays, when its headers say (no decoding).
fn sound_length(bytes: &Arc<[u8]>, hint: &str) -> Option<std::time::Duration> {
    use rodio::Source;
    rodio::Decoder::builder()
        .with_data(std::io::Cursor::new(bytes.clone()))
        .with_byte_len(bytes.len() as u64)
        .with_hint(hint)
        .build()
        .ok()?
        .total_duration()
}

/// An emoji typed into a "Related Emoji" box: the emoji itself ("🔥"), its
/// name ("fire", ":fire:") or, where allowed, one of this server's (":party:").
#[derive(Clone, PartialEq)]
enum EmojiPick {
    Unicode { emoji: String, name: String },
    Custom { id: Id, animated: bool },
}

impl EmojiPick {
    fn resolve(text: &str, server: &[GuildEmoji]) -> Option<EmojiPick> {
        let bare = text.trim().trim_matches(':');
        if bare.is_empty() {
            return None;
        }
        let chars: Vec<char> = bare.chars().collect();
        if crate::emoji::emoji_len(&chars, 0) == Some(chars.len()) {
            let name = crate::emoji::shortcode_of(bare).unwrap_or(bare).to_string();
            return Some(EmojiPick::Unicode { emoji: bare.to_string(), name });
        }
        if let Some(e) = server.iter().find(|e| e.name.as_deref() == Some(bare)) {
            return Some(EmojiPick::Custom { id: e.id?, animated: e.animated });
        }
        let emoji = crate::emoji::from_shortcode(bare)?;
        Some(EmojiPick::Unicode { emoji, name: bare.to_string() })
    }

    fn image(&self) -> String {
        match self {
            EmojiPick::Unicode { emoji, .. } => crate::emoji::twemoji_url(emoji),
            EmojiPick::Custom { id, animated } => super::super::emoji_img(*id, *animated, 48),
        }
    }
}

/// The "Related Emoji" box with a preview of what it found.
fn emoji_field(ui: &mut Ui, t: &Theme, label: &str, id: egui::Id, text: &mut String, server: &[GuildEmoji]) {
    super::section(ui, t, label);
    let w = ui.available_width();
    ui.horizontal(|ui| {
        super::input(ui, t, id, text, "An emoji, like 🔥 or :fire:", 1, 64, w - 48.0);
        let (r, _) = ui.allocate_exact_size(vec2(36.0, 36.0), Sense::hover());
        ui.painter().rect_filled(r, 8.0, overlay(0.06));
        match EmojiPick::resolve(text, server) {
            Some(p) => egui::Image::new(p.image()).paint_at(ui, r.shrink(6.0)),
            None => {
                ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::EMOJI, icon_font(16.0), t.interactive_muted);
            }
        }
    });
    ui.add_space(16.0);
}

/// A file row in an upload dialog: "Browse" and the picked file's name.
fn file_row(ui: &mut Ui, t: &Theme, label: &str, file: Option<&Upload>, hint: &str) -> bool {
    super::section(ui, t, label);
    let mut browse = false;
    ui.horizontal(|ui| {
        browse = super::btn(ui, t, Btn::Secondary, "Browse", true).clicked();
        ui.add_space(4.0);
        let (text, color) = match file {
            Some(f) => (f.name.as_str(), t.text_normal),
            None => ("No file chosen", t.text_muted),
        };
        ui.add(Label::new(RichText::new(text).size(14.0).color(color)).truncate());
    });
    ui.add_space(6.0);
    super::help(ui, t, hint);
    ui.add_space(16.0);
    browse
}

/// A round button with a glyph (play, edit), filled on hover.
fn round_button(ui: &Ui, t: &Theme, center: egui::Pos2, id: egui::Id, glyph: &str, radius: f32) -> Response {
    let r = Rect::from_center_size(center, vec2(radius * 2.0, radius * 2.0));
    let resp = ui.interact(r, id, Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
    ui.painter().circle_filled(center, radius, if resp.hovered() { overlay(0.2) } else { overlay(0.12) });
    let color = if resp.hovered() { t.interactive_hover } else { t.interactive_normal };
    ui.painter().text(center, Align2::CENTER_CENTER, glyph, icon_font(radius * 0.8), color);
    resp
}

/// The red "×" on a hovered row or tile; a spinner while it's deleting.
fn delete_button(ui: &mut Ui, t: &Theme, r: Rect, id: egui::Id, show: bool, deleting: bool) -> bool {
    if deleting {
        ui.put(r, egui::Spinner::new().size(14.0));
        return false;
    }
    let xr = ui.interact(r, id, Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
    if show || xr.hovered() {
        ui.painter().circle_filled(r.center(), 12.0, if xr.hovered() { t.danger } else { overlay(0.12) });
        ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(10.0), if xr.hovered() { Color32::WHITE } else { t.danger });
    }
    xr.on_hover_text("Delete").clicked()
}

/// "Uploaded by …" from a sticker's or sound's `user`.
fn uploader(v: &Value) -> Option<User> {
    v.get("user").and_then(|u| User::deserialize(u).ok())
}

/// Can you edit / delete it: anyone's with Manage Expressions, your own with
/// Create Expressions.
fn can_change(perms: u64, me: Option<Id>, v: &Value) -> bool {
    perms & super::MANAGE_GUILD_EXPRESSIONS != 0
        || (perms & super::CREATE_GUILD_EXPRESSIONS != 0 && me.is_some() && super::vid(&v["user"], "id") == me)
}

/// "Free Slots" (or "Level N") and how many slots are left.
fn slots_header(ui: &mut Ui, t: &Theme, level: u8, used: usize, slots: usize) {
    ui.horizontal(|ui| {
        let heading = if level == 0 { "Free Slots".to_string() } else { format!("Level {level}") };
        ui.label(bold(heading).size(16.0).color(t.header_primary));
        ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
            let free = slots.saturating_sub(used);
            ui.label(RichText::new(format!("{free} of {slots} slots available")).size(14.0).color(t.text_muted));
        });
    });
    ui.add_space(12.0);
}

/// Discord's card for servers without boosts.
fn boost_card(ui: &mut Ui, t: &Theme, text: &str) {
    Frame::none().fill(overlay(0.06)).rounding(8.0).inner_margin(Margin::same(16.0)).show(ui, |ui| {
        ui.set_width(ui.available_width());
        ui.horizontal_top(|ui| {
            ui.label(RichText::new(icon::BOOST).font(icon_font(22.0)).color(Color32::from_rgb(0xff, 0x73, 0xfa)));
            ui.add_space(8.0);
            ui.vertical(|ui| {
                ui.label(bold("Get Boosted").size(16.0).color(t.header_primary));
                ui.add_space(4.0);
                ui.label(RichText::new(text).size(14.0).color(t.text_muted));
            });
        });
    });
    ui.add_space(24.0);
}

/// Segoe Fluent "Lock".
const LOCK: &str = "\u{E72E}";

/// What the next boost levels add: (level, boosts it takes, slots it adds).
fn level_perks(ui: &mut Ui, t: &Theme, level: u8, perks: &[(u8, u32, usize)], slots: &[usize; 4], what: &str) {
    for &(lvl, boosts, more) in perks.iter().filter(|(l, ..)| *l > level) {
        let w = ui.available_width();
        let (r, _) = ui.allocate_exact_size(vec2(w, 48.0), Sense::hover());
        let p = ui.painter();
        p.text(pos2(r.left(), r.center().y), Align2::LEFT_CENTER, LOCK, icon_font(14.0), t.interactive_muted);
        p.text(pos2(r.left() + 24.0, r.center().y), Align2::LEFT_CENTER, format!("Level {lvl}"), super::bold_font(15.0), t.header_primary);
        let lw = p.layout_no_wrap(format!("Level {lvl}"), super::bold_font(15.0), t.header_primary).size().x;
        p.text(pos2(r.left() + 34.0 + lw, r.center().y), Align2::LEFT_CENTER, format!("{boosts} Boosts"), FontId::proportional(14.0), t.text_muted);
        p.text(
            pos2(r.right(), r.center().y),
            Align2::RIGHT_CENTER,
            format!("+{more} {what} Slots ({} total)", slots[lvl as usize]),
            FontId::proportional(14.0),
            t.text_normal,
        );
        p.hline(r.x_range(), r.bottom(), Stroke::new(1.0_f32, t.border_subtle));
    }
}

// ---- Stickers ---------------------------------------------------------------------

/// Sticker slots by boost level.
const STICKER_SLOTS: [usize; 4] = [5, 15, 30, 60];
const STICKER_PERKS: [(u8, u32, usize); 3] = [(1, 2, 10), (2, 7, 15), (3, 14, 30)];
const STICKER_MAX_BYTES: usize = 512 * 1024;
const TILE: Vec2 = vec2(128.0, 150.0);
const TILE_GAP: f32 = 12.0;

fn tag_stickers(g: Id) -> String {
    format!("ss:stickers:{g}")
}

fn stickers_id(g: Id) -> egui::Id {
    egui::Id::new(("ss_stickers", g.0))
}

#[derive(Clone, Default)]
struct StickersUi {
    calls: Calls<StickerCall>,
    dialog: Option<StickerDialog>,
}

#[derive(Clone)]
enum StickerCall {
    Upload(Id),
    Edit(Id, Id),
    Delete(Id, Id),
}

#[derive(Clone)]
enum StickerDialog {
    Upload(StickerForm),
    Edit { id: Id, format: u8, by: Option<String>, orig: StickerForm, form: StickerForm },
    Delete { id: Id, name: String },
}

#[derive(Clone, Default, PartialEq)]
struct StickerForm {
    name: String,
    /// The related emoji as typed.
    emoji: String,
    description: String,
}

impl StickerForm {
    /// Discord keeps the related emoji as its name ("fire"); unicode only.
    fn tags(&self) -> Option<String> {
        match EmojiPick::resolve(&self.emoji, &[])? {
            EmojiPick::Unicode { name, .. } => Some(name),
            EmojiPick::Custom { .. } => None,
        }
    }

    fn valid(&self) -> bool {
        length_ok(&self.name, 2, 30) && self.tags().is_some() && (self.description.trim().is_empty() || length_ok(&self.description, 2, 100))
    }
}

impl RustCord {
    pub(super) fn ss_stickers(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id) {
        super::title(ui, t, "Stickers");
        let Some(gs) = self.store.guilds.get(&g) else { return };
        let id = stickers_id(g);
        let (tag, path) = (tag_stickers(g), format!("/guilds/{g}/stickers"));
        let mut s: StickersUi = page_state(ui, id);
        release_dialog(ui);
        if new_visit(ui, id) {
            s.dialog = None;
            drop_upload_file(ui, id);
            acts.push(Act::Refetch(tag.clone(), path.clone()));
        }
        s.calls.poll(self, acts, sticker_done);

        let level = super::super::guild_pages::boost_level(&gs.guild).0.min(3);
        if level == 0 {
            boost_card(
                ui,
                t,
                "Enjoy more stickers and other perks by boosting your server to Level 1. Each Level unlocks more sticker slots and new benefits for everyone.",
            );
        }
        if let Some(v) = self.ss_loaded(ui, t, &tag, &path, acts) {
            let list = v.as_array().map(Vec::as_slice).unwrap_or(&[]);
            self.sticker_grid(ui, t, &mut s, g, list, level);
        }
        ui.add_space(24.0);
        level_perks(ui, t, level, &STICKER_PERKS, &STICKER_SLOTS, "Sticker");
        self.sticker_dialog(ui, t, acts, g, &mut s);
        ui.data_mut(|d| d.insert_temp(id, s));
    }

    fn sticker_grid(&self, ui: &mut Ui, t: &Theme, s: &mut StickersUi, g: Id, list: &[Value], level: u8) {
        let slots = STICKER_SLOTS[level as usize];
        let perms = self.store.guild_perms(g);
        let me = self.store.me_id();
        slots_header(ui, t, level, list.len(), slots);
        let can_create = perms & (super::CREATE_GUILD_EXPRESSIONS | super::MANAGE_GUILD_EXPRESSIONS) != 0;
        let uploading = s.calls.busy(|c| matches!(c, StickerCall::Upload(_)));
        let label = if uploading { "Uploading…" } else { "Upload Sticker" };
        if super::btn(ui, t, Btn::Primary, label, can_create && !uploading && list.len() < slots).clicked() {
            s.dialog = Some(StickerDialog::Upload(StickerForm::default()));
        }
        ui.add_space(16.0);
        if list.is_empty() {
            super::help(ui, t, "No stickers yet. Upload one to get started.");
            return;
        }
        let cols = ((ui.available_width() + TILE_GAP) / (TILE.x + TILE_GAP)).floor().max(1.0) as usize;
        for row in list.chunks(cols) {
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = TILE_GAP;
                for v in row {
                    self.sticker_tile(ui, t, s, v, can_change(perms, me, v));
                }
            });
            ui.add_space(TILE_GAP);
        }
    }

    /// One sticker: the picture (playing while hovered), its emoji and name.
    /// Click to edit; the "×" deletes.
    fn sticker_tile(&self, ui: &mut Ui, t: &Theme, s: &mut StickersUi, v: &Value, can: bool) {
        let Some(id) = super::vid(v, "id") else { return };
        let (r, resp) = ui.allocate_exact_size(TILE, if can { Sense::click() } else { Sense::hover() });
        let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
        if !ui.is_rect_visible(r) {
            return;
        }
        let hovered = ui.rect_contains_pointer(r);
        ui.painter().rect_filled(r, 8.0, overlay(if hovered { 0.1 } else { 0.06 }));
        let format = super::vu64(v, "format_type") as u8;
        let img = Rect::from_center_size(pos2(r.center().x, r.top() + 58.0), vec2(96.0, 96.0));
        super::super::expression::paint_sticker(ui, img, id, format, hovered, None);

        let name = super::vstr(v, "name");
        let tags = super::vstr(v, "tags");
        let y = r.bottom() - 22.0;
        let mut x = r.left() + 10.0;
        if let Some(url) = super::super::emoji_image(None, tags.split(',').next(), false) {
            egui::Image::new(url).paint_at(ui, Rect::from_min_size(pos2(x, y - 8.0), vec2(16.0, 16.0)));
            x += 20.0;
        }
        ui.painter_at(r.shrink2(vec2(8.0, 0.0))).text(pos2(x, y), Align2::LEFT_CENTER, name, super::bold_font(14.0), t.header_primary);

        if !can {
            return;
        }
        let deleting = s.calls.busy(|c| matches!(c, StickerCall::Delete(_, d) if *d == id));
        let x = Rect::from_center_size(pos2(r.right() - 16.0, r.top() + 16.0), vec2(24.0, 24.0));
        if delete_button(ui, t, x, egui::Id::new(("ss_sticker_delete", id.0)), hovered, deleting) {
            s.dialog = Some(StickerDialog::Delete { id, name: name.to_string() });
        } else if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
            let form = StickerForm { name: name.to_string(), emoji: tags.to_string(), description: super::vstr(v, "description").to_string() };
            let by = uploader(v).map(|u| u.display_name().to_string());
            s.dialog = Some(StickerDialog::Edit { id, format, by, orig: form.clone(), form });
        }
    }

    fn sticker_dialog(&self, ui: &Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, s: &mut StickersUi) {
        let StickersUi { calls, dialog: open } = s;
        let Some(d) = open.as_mut() else { return };
        let mut close = false;
        match d {
            StickerDialog::Upload(form) => {
                let file = upload_file(ui, stickers_id(g));
                let busy = calls.busy(|c| matches!(c, StickerCall::Upload(_)));
                let ok = file.is_some() && form.valid() && !busy;
                let out = dialog(ui, t, "Upload Sticker", if busy { "Uploading…" } else { "Upload" }, Btn::Primary, ok, |ui| {
                    sticker_preview(ui, |ui, r| match &file {
                        Some(f) => egui::Image::from_bytes(f.uri.clone(), f.bytes.clone()).maintain_aspect_ratio(true).paint_at(ui, r),
                        None => {
                            ui.painter().text(r.center(), Align2::CENTER_CENTER, "Preview", FontId::proportional(14.0), t.text_muted);
                        }
                    });
                    if file_row(ui, t, "File*", file.as_ref(), "PNG, APNG or GIF, 320x320 px, up to 512 KB.") {
                        acts.push(Act::Run(Box::new(move |app: &mut RustCord| pick_sticker(app, g))));
                    }
                    sticker_fields(ui, t, form);
                });
                match out {
                    Some(true) => {
                        let (Some(f), Some(tags)) = (file, form.tags()) else { return };
                        let fields = vec![
                            ("name".to_string(), form.name.trim().to_string()),
                            ("tags".to_string(), tags),
                            ("description".to_string(), form.description.trim().to_string()),
                        ];
                        calls.start(acts, StickerCall::Upload(g), move |app, tag| {
                            app.api_upload(tag, format!("/guilds/{g}/stickers"), fields, (f.name, f.bytes.to_vec(), f.mime.to_string()))
                        });
                    }
                    Some(false) => close = true,
                    None => {}
                }
            }
            StickerDialog::Edit { id, format, by, orig, form } => {
                let id = *id;
                let busy = calls.busy(|c| matches!(c, StickerCall::Edit(_, e) if *e == id));
                let out = dialog(ui, t, "Edit Sticker", if busy { "Saving…" } else { "Save" }, Btn::Primary, form.valid() && !busy, |ui| {
                    sticker_preview(ui, |ui, r| super::super::expression::paint_sticker(ui, r, id, *format, true, None));
                    if let Some(by) = by {
                        super::help(ui, t, &format!("Uploaded by {by}"));
                        ui.add_space(16.0);
                    }
                    sticker_fields(ui, t, form);
                });
                match out {
                    Some(true) if form == orig => close = true,
                    Some(true) => {
                        let mut body = serde_json::Map::new();
                        if form.name != orig.name {
                            body.insert("name".into(), json!(form.name.trim()));
                        }
                        if form.emoji != orig.emoji {
                            body.insert("tags".into(), json!(form.tags()));
                        }
                        if form.description != orig.description {
                            body.insert("description".into(), json!(form.description.trim()));
                        }
                        let path = format!("/guilds/{g}/stickers/{id}");
                        calls.start(acts, StickerCall::Edit(g, id), move |app, tag| app.api(tag, Method::PATCH, path, Some(Value::Object(body))));
                    }
                    Some(false) => close = true,
                    None => {}
                }
            }
            StickerDialog::Delete { id, name } => {
                let id = *id;
                let out = dialog(ui, t, "Delete Sticker", "Delete", Btn::Danger, true, |ui| {
                    ui.label(RichText::new(format!("Are you sure you want to delete {name}? This can't be undone.")).size(15.0).color(t.text_normal));
                });
                if out == Some(true) {
                    let path = format!("/guilds/{g}/stickers/{id}");
                    calls.start(acts, StickerCall::Delete(g, id), move |app, tag| app.api(tag, Method::DELETE, path, None));
                }
                close = out.is_some();
            }
        }
        if close {
            *open = None;
            drop_upload_file(ui, stickers_id(g));
        }
    }
}

// ---- the file an upload dialog picked --------------------------------------------
//
// Kept apart from the page state (which is cloned every frame) so the bytes
// are only shared, never copied: one `Upload` per page, under its own id.

fn upload_file(ui: &Ui, page: egui::Id) -> Option<Upload> {
    ui.data(|d| d.get_temp::<Option<Upload>>(page.with("file"))).flatten()
}

fn set_upload_file(app: &RustCord, page: egui::Id, file: Option<Upload>) {
    let old = app.ctx.data_mut(|d| std::mem::replace(d.get_temp_mut_or_default::<Option<Upload>>(page.with("file")), file));
    if let Some(old) = old {
        app.ctx.forget_image(&old.uri);
    }
}

fn drop_upload_file(ui: &Ui, page: egui::Id) {
    let old = ui.data_mut(|d| d.remove_temp::<Option<Upload>>(page.with("file"))).flatten();
    if let Some(old) = old {
        ui.ctx().forget_image(&old.uri);
    }
}

/// The sticker's picture, centred on a faint square.
fn sticker_preview(ui: &mut Ui, paint: impl FnOnce(&mut Ui, Rect)) {
    let w = ui.available_width();
    let (r, _) = ui.allocate_exact_size(vec2(w, 176.0), Sense::hover());
    let tile = Rect::from_center_size(r.center(), vec2(160.0, 160.0));
    ui.painter().rect_filled(tile, 8.0, overlay(0.06));
    paint(ui, tile.shrink(8.0));
    ui.add_space(16.0);
}

fn sticker_fields(ui: &mut Ui, t: &Theme, form: &mut StickerForm) {
    field(ui, t, "Sticker Name*", egui::Id::new("ss_sticker_name"), &mut form.name, "", 1, 30);
    emoji_field(ui, t, "Related Emoji*", egui::Id::new("ss_sticker_emoji"), &mut form.emoji, &[]);
    field(ui, t, "Description", egui::Id::new("ss_sticker_description"), &mut form.description, "", 1, 100);
}

/// "Browse": pick the sticker file (after the frame: the file dialog blocks).
fn pick_sticker(app: &mut RustCord, g: Id) {
    let Some(path) = rfd::FileDialog::new().set_title("Upload Sticker").add_filter("Stickers", &["png", "apng", "gif"]).pick_file() else {
        return;
    };
    match Upload::read(&path, STICKER_MAX_BYTES, sticker_kind, "Stickers must be PNG, APNG or GIF files.") {
        Ok(f) => {
            let name = f.suggested_name(30);
            with_state::<StickersUi>(app, stickers_id(g), |s| {
                if let Some(StickerDialog::Upload(form)) = s.dialog.as_mut().filter(|_| !name.is_empty()) {
                    if form.name.trim().is_empty() {
                        form.name = name;
                    }
                }
            });
            set_upload_file(app, stickers_id(g), Some(f));
        }
        Err(e) => app.toast(e, true),
    }
}

fn sticker_done(app: &mut RustCord, call: StickerCall, r: Result<Value, String>) {
    let v = match r {
        Ok(v) => v,
        Err(e) => {
            let what = match call {
                StickerCall::Upload(_) => "Couldn't upload the sticker",
                StickerCall::Edit(..) => "Couldn't save the sticker",
                StickerCall::Delete(..) => "Couldn't delete the sticker",
            };
            app.toast(format!("{what}: {e}"), true);
            return;
        }
    };
    match call {
        StickerCall::Upload(g) => {
            app.ss_list_upsert(&tag_stickers(g), &v);
            with_state::<StickersUi>(app, stickers_id(g), |s| {
                if matches!(s.dialog, Some(StickerDialog::Upload(_))) {
                    s.dialog = None;
                }
            });
            set_upload_file(app, stickers_id(g), None);
        }
        StickerCall::Edit(g, id) => {
            app.ss_list_upsert(&tag_stickers(g), &v);
            with_state::<StickersUi>(app, stickers_id(g), |s| {
                if matches!(s.dialog, Some(StickerDialog::Edit { id: e, .. }) if e == id) {
                    s.dialog = None;
                }
            });
        }
        StickerCall::Delete(g, id) => app.ss_list_remove(&tag_stickers(g), |s| super::vid(s, "id") == Some(id)),
    }
}

// ---- Soundboard -------------------------------------------------------------------

/// Sound slots by boost level.
const SOUND_SLOTS: [usize; 4] = [8, 24, 36, 48];
const SOUND_PERKS: [(u8, u32, usize); 3] = [(1, 2, 16), (2, 7, 12), (3, 14, 12)];
const SOUND_MAX_BYTES: usize = 512 * 1024;
/// Discord's longest sound, in seconds.
const SOUND_MAX_SECS: f32 = 5.2;

fn tag_sounds(g: Id) -> String {
    format!("ss:sounds:{g}")
}

fn sounds_id(g: Id) -> egui::Id {
    egui::Id::new(("ss_soundboard", g.0))
}

#[derive(Clone, Default)]
struct SoundsUi {
    calls: Calls<SoundCall>,
    dialog: Option<SoundDialog>,
}

#[derive(Clone)]
enum SoundCall {
    Upload(Id),
    Edit(Id, Id),
    Delete(Id, Id),
}

#[derive(Clone)]
enum SoundDialog {
    Upload(SoundForm),
    Edit { id: Id, orig: SoundForm, form: SoundForm },
    Delete { id: Id, name: String },
}

#[derive(Clone, PartialEq)]
struct SoundForm {
    name: String,
    /// The emoji as typed (optional).
    emoji: String,
    /// 0–100 (Discord keeps 0–1).
    volume: f32,
}

impl Default for SoundForm {
    fn default() -> Self {
        Self { name: String::new(), emoji: String::new(), volume: 100.0 }
    }
}

impl SoundForm {
    fn from_value(v: &Value, server: &[GuildEmoji]) -> Self {
        let emoji = match super::vid(v, "emoji_id") {
            Some(id) => server.iter().find(|e| e.id == Some(id)).and_then(|e| e.name.as_deref()).map(|n| format!(":{n}:")).unwrap_or_default(),
            None => super::vstr(v, "emoji_name").to_string(),
        };
        let volume = v.get("volume").and_then(Value::as_f64).unwrap_or(1.0) as f32 * 100.0;
        Self { name: super::vstr(v, "name").to_string(), emoji, volume: volume.round() }
    }

    fn valid(&self, server: &[GuildEmoji]) -> bool {
        length_ok(&self.name, 2, 32) && (self.emoji.trim().is_empty() || EmojiPick::resolve(&self.emoji, server).is_some())
    }

    /// Everything Discord takes but the sound itself.
    fn body(&self, server: &[GuildEmoji]) -> serde_json::Map<String, Value> {
        let (emoji_id, emoji_name) = match EmojiPick::resolve(&self.emoji, server) {
            Some(EmojiPick::Custom { id, .. }) => (json!(id.to_string()), Value::Null),
            Some(EmojiPick::Unicode { emoji, .. }) => (Value::Null, json!(emoji)),
            None => (Value::Null, Value::Null),
        };
        let mut m = serde_json::Map::new();
        m.insert("name".into(), json!(self.name.trim()));
        m.insert("volume".into(), json!((self.volume / 100.0).clamp(0.0, 1.0)));
        m.insert("emoji_id".into(), emoji_id);
        m.insert("emoji_name".into(), emoji_name);
        m
    }
}

/// The loaded sound list (`{"items": [...]}`), to change in place.
fn sound_items(app: &mut RustCord, g: Id) -> Option<&mut Vec<Value>> {
    match app.api_results.get_mut(&tag_sounds(g)) {
        Some(Ok(v)) => v.get_mut("items").and_then(Value::as_array_mut),
        _ => None,
    }
}

impl RustCord {
    pub(super) fn ss_soundboard(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id) {
        super::title(ui, t, "Soundboard");
        super::help(
            ui,
            t,
            "Upload custom sound reactions that anyone in this server can use. Nitro members will be able to access these sounds in any server on Discord.",
        );
        ui.add_space(20.0);
        let Some(gs) = self.store.guilds.get(&g) else { return };
        let id = sounds_id(g);
        let (tag, path) = (tag_sounds(g), format!("/guilds/{g}/soundboard-sounds"));
        let mut s: SoundsUi = page_state(ui, id);
        release_dialog(ui);
        if new_visit(ui, id) {
            s.dialog = None;
            drop_upload_file(ui, id);
            acts.push(Act::Refetch(tag.clone(), path.clone()));
        }
        s.calls.poll(self, acts, sound_done);

        let level = super::super::guild_pages::boost_level(&gs.guild).0.min(3);
        if let Some(v) = self.ss_loaded(ui, t, &tag, &path, acts) {
            let list = v.get("items").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]);
            self.sound_list(ui, t, acts, &mut s, g, list, level);
        }
        ui.add_space(24.0);
        level_perks(ui, t, level, &SOUND_PERKS, &SOUND_SLOTS, "Sound");
        self.sound_dialog(ui, t, acts, g, &mut s, &gs.guild.emojis);
        ui.data_mut(|d| d.insert_temp(id, s));
    }

    #[allow(clippy::too_many_arguments)]
    fn sound_list(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, s: &mut SoundsUi, g: Id, list: &[Value], level: u8) {
        let slots = SOUND_SLOTS[level as usize];
        let perms = self.store.guild_perms(g);
        let me = self.store.me_id();
        let server: &[GuildEmoji] = self.store.guilds.get(&g).map(|gs| gs.guild.emojis.as_slice()).unwrap_or(&[]);
        slots_header(ui, t, level, list.len(), slots);
        let can_create = perms & (super::CREATE_GUILD_EXPRESSIONS | super::MANAGE_GUILD_EXPRESSIONS) != 0;
        let uploading = s.calls.busy(|c| matches!(c, SoundCall::Upload(_)));
        let label = if uploading { "Uploading…" } else { "Upload Sound" };
        if super::btn(ui, t, Btn::Primary, label, can_create && !uploading && list.len() < slots).clicked() {
            s.dialog = Some(SoundDialog::Upload(SoundForm::default()));
        }
        ui.add_space(16.0);
        if list.is_empty() {
            super::empty_state(ui, t, "No Sounds", "Get the party started by uploading a sound");
            return;
        }

        let w = ui.available_width();
        let (hr, _) = ui.allocate_exact_size(vec2(w, 26.0), Sense::hover());
        let user_x = hr.left() + w * 0.48;
        let vol_x = hr.left() + w * 0.76;
        for (x, h) in [(hr.left(), "SOUND"), (user_x, "UPLOADED BY"), (vol_x, "VOLUME")] {
            ui.painter().text(pos2(x, hr.center().y), Align2::LEFT_CENTER, h, super::bold_font(12.0), t.header_secondary);
        }
        ui.painter().hline(hr.x_range(), hr.bottom(), Stroke::new(1.0_f32, t.border_subtle));
        for v in list {
            let Some(id) = super::vid(v, "sound_id") else { continue };
            let (row, _) = ui.allocate_exact_size(vec2(w, 56.0), Sense::hover());
            if !ui.is_rect_visible(row) {
                continue;
            }
            let hovered = ui.rect_contains_pointer(row);
            if hovered {
                ui.painter().rect_filled(row.shrink2(vec2(0.0, 2.0)), 6.0, overlay(0.06));
            }
            let volume = v.get("volume").and_then(Value::as_f64).unwrap_or(1.0) as f32;
            if round_button(ui, t, pos2(row.left() + 18.0, row.center().y), egui::Id::new(("ss_sound_play", id.0)), icon::PLAY, 16.0)
                .on_hover_text("Preview")
                .clicked()
            {
                acts.push(Act::Run(Box::new(move |app: &mut RustCord| app.play_sound(id, volume))));
            }
            let mut x = row.left() + 46.0;
            let emoji = match super::vid(v, "emoji_id") {
                Some(e) => Some(super::super::emoji_img(e, false, 48)),
                None => v.get("emoji_name").and_then(Value::as_str).filter(|e| !e.is_empty()).map(crate::emoji::twemoji_url),
            };
            if let Some(url) = emoji {
                egui::Image::new(url).paint_at(ui, Rect::from_center_size(pos2(x + 11.0, row.center().y), vec2(22.0, 22.0)));
                x += 30.0;
            }
            let name_clip = ui.painter_at(Rect::from_min_max(row.min, pos2(user_x - 16.0, row.bottom())));
            name_clip.text(pos2(x, row.center().y), Align2::LEFT_CENTER, super::vstr(v, "name"), super::bold_font(15.0), t.header_primary);

            if let Some(u) = uploader(v) {
                let av = Rect::from_center_size(pos2(user_x + 12.0, row.center().y), vec2(24.0, 24.0));
                super::super::paint_avatar(ui, av, Some(u.avatar_or_default(64)), u.display_name());
                let p = ui.painter_at(Rect::from_min_max(pos2(av.right() + 8.0, row.top()), pos2(vol_x - 12.0, row.bottom())));
                p.text(pos2(av.right() + 8.0, row.center().y), Align2::LEFT_CENTER, u.display_name(), FontId::proportional(14.0), t.text_normal);
            }
            ui.painter().text(pos2(vol_x, row.center().y), Align2::LEFT_CENTER, format!("{:.0}%", volume * 100.0), FontId::proportional(14.0), t.text_normal);

            if can_change(perms, me, v) {
                let edit = round_button(ui, t, pos2(row.right() - 54.0, row.center().y), egui::Id::new(("ss_sound_edit", id.0)), icon::EDIT, 14.0);
                if edit.on_hover_text("Edit").clicked() {
                    let form = SoundForm::from_value(v, server);
                    s.dialog = Some(SoundDialog::Edit { id, orig: form.clone(), form });
                }
                let deleting = s.calls.busy(|c| matches!(c, SoundCall::Delete(_, d) if *d == id));
                let x = Rect::from_center_size(pos2(row.right() - 18.0, row.center().y), vec2(24.0, 24.0));
                if delete_button(ui, t, x, egui::Id::new(("ss_sound_delete", id.0)), hovered, deleting) {
                    s.dialog = Some(SoundDialog::Delete { id, name: super::vstr(v, "name").to_string() });
                }
            }
            ui.painter().hline(row.x_range(), row.bottom(), Stroke::new(1.0_f32, t.border_subtle));
        }
    }

    fn sound_dialog(&self, ui: &Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, s: &mut SoundsUi, server: &[GuildEmoji]) {
        let SoundsUi { calls, dialog: open } = s;
        let Some(d) = open.as_mut() else { return };
        let mut close = false;
        match d {
            SoundDialog::Upload(form) => {
                let file = upload_file(ui, sounds_id(g));
                let busy = calls.busy(|c| matches!(c, SoundCall::Upload(_)));
                let ok = file.is_some() && form.valid(server) && !busy;
                let out = dialog(ui, t, "Upload Sound", if busy { "Uploading…" } else { "Upload" }, Btn::Primary, ok, |ui| {
                    if file_row(ui, t, "File*", file.as_ref(), "MP3 or OGG, up to 512 KB and 5.2 seconds long.") {
                        acts.push(Act::Run(Box::new(move |app: &mut RustCord| pick_sound(app, g))));
                    }
                    if let Some(f) = &file {
                        if super::link(ui, "Preview", t.text_link).clicked() {
                            let (bytes, gain) = (f.bytes.clone(), form.volume / 100.0);
                            acts.push(Act::Run(Box::new(move |app: &mut RustCord| app.audio.play_effect(bytes, gain))));
                        }
                        ui.add_space(12.0);
                    }
                    sound_fields(ui, t, form, server);
                });
                match out {
                    Some(true) => {
                        let Some(f) = file else { return };
                        let mut body = form.body(server);
                        calls.start(acts, SoundCall::Upload(g), move |app, tag| {
                            body.insert("sound".into(), json!(format!("data:{};base64,{}", f.mime, super::base64(&f.bytes))));
                            app.api(tag, Method::POST, format!("/guilds/{g}/soundboard-sounds"), Some(Value::Object(body)))
                        });
                    }
                    Some(false) => close = true,
                    None => {}
                }
            }
            SoundDialog::Edit { id, orig, form } => {
                let id = *id;
                let busy = calls.busy(|c| matches!(c, SoundCall::Edit(_, e) if *e == id));
                let out = dialog(ui, t, "Edit Sound", if busy { "Saving…" } else { "Save" }, Btn::Primary, form.valid(server) && !busy, |ui| {
                    if super::link(ui, "Preview", t.text_link).clicked() {
                        let gain = form.volume / 100.0;
                        acts.push(Act::Run(Box::new(move |app: &mut RustCord| app.play_sound(id, gain))));
                    }
                    ui.add_space(12.0);
                    sound_fields(ui, t, form, server);
                });
                match out {
                    Some(true) if form == orig => close = true,
                    Some(true) => {
                        let body = form.body(server);
                        let path = format!("/guilds/{g}/soundboard-sounds/{id}");
                        calls.start(acts, SoundCall::Edit(g, id), move |app, tag| app.api(tag, Method::PATCH, path, Some(Value::Object(body))));
                    }
                    Some(false) => close = true,
                    None => {}
                }
            }
            SoundDialog::Delete { id, name } => {
                let id = *id;
                let out = dialog(ui, t, "Delete Sound", "Delete", Btn::Danger, true, |ui| {
                    ui.label(RichText::new(format!("Are you sure you want to delete {name}? This can't be undone.")).size(15.0).color(t.text_normal));
                });
                if out == Some(true) {
                    let path = format!("/guilds/{g}/soundboard-sounds/{id}");
                    calls.start(acts, SoundCall::Delete(g, id), move |app, tag| app.api(tag, Method::DELETE, path, None));
                }
                close = out.is_some();
            }
        }
        if close {
            *open = None;
            drop_upload_file(ui, sounds_id(g));
        }
    }
}

fn sound_fields(ui: &mut Ui, t: &Theme, form: &mut SoundForm, server: &[GuildEmoji]) {
    field(ui, t, "Sound Name*", egui::Id::new("ss_sound_name"), &mut form.name, "", 1, 32);
    emoji_field(ui, t, "Related Emoji", egui::Id::new("ss_sound_emoji"), &mut form.emoji, server);
    super::section(ui, t, "Sound Volume");
    ui.horizontal(|ui| {
        ui.spacing_mut().slider_width = (ui.available_width() - 56.0).max(80.0);
        ui.add(egui::Slider::new(&mut form.volume, 0.0..=100.0).show_value(false));
        ui.label(RichText::new(format!("{:.0}%", form.volume)).size(14.0).color(t.text_normal));
    });
}

/// "Browse": pick the sound file (after the frame: the file dialog blocks).
fn pick_sound(app: &mut RustCord, g: Id) {
    let Some(path) = rfd::FileDialog::new().set_title("Upload Sound").add_filter("Sounds", &["mp3", "ogg"]).pick_file() else {
        return;
    };
    let f = match Upload::read(&path, SOUND_MAX_BYTES, sound_kind, "Sounds must be MP3 or OGG files.") {
        Ok(f) => f,
        Err(e) => return app.toast(e, true),
    };
    // Only when the file's headers tell; otherwise Discord's answer will.
    let hint = if f.mime == "audio/ogg" { "ogg" } else { "mp3" };
    if sound_length(&f.bytes, hint).is_some_and(|d| d.as_secs_f32() > SOUND_MAX_SECS) {
        return app.toast("Sounds can be up to 5.2 seconds long.", true);
    }
    let name = f.suggested_name(32);
    with_state::<SoundsUi>(app, sounds_id(g), |s| {
        if let Some(SoundDialog::Upload(form)) = s.dialog.as_mut().filter(|_| !name.is_empty()) {
            if form.name.trim().is_empty() {
                form.name = name;
            }
        }
    });
    set_upload_file(app, sounds_id(g), Some(f));
}

fn sound_done(app: &mut RustCord, call: SoundCall, r: Result<Value, String>) {
    let v = match r {
        Ok(v) => v,
        Err(e) => {
            let what = match call {
                SoundCall::Upload(_) => "Couldn't upload the sound",
                SoundCall::Edit(..) => "Couldn't save the sound",
                SoundCall::Delete(..) => "Couldn't delete the sound",
            };
            app.toast(format!("{what}: {e}"), true);
            return;
        }
    };
    match call {
        SoundCall::Upload(g) | SoundCall::Edit(g, _) => {
            let id = super::vid(&v, "sound_id");
            if let Some(list) = sound_items(app, g) {
                match list.iter_mut().find(|x| id.is_some() && super::vid(x, "sound_id") == id) {
                    Some(slot) => *slot = v,
                    None => list.push(v),
                }
            }
            with_state::<SoundsUi>(app, sounds_id(g), |s| match (&s.dialog, &call) {
                (Some(SoundDialog::Upload(_)), SoundCall::Upload(_)) => s.dialog = None,
                (Some(SoundDialog::Edit { id: e, .. }), SoundCall::Edit(_, id)) if e == id => s.dialog = None,
                _ => {}
            });
            if matches!(call, SoundCall::Upload(_)) {
                set_upload_file(app, sounds_id(g), None);
            }
        }
        SoundCall::Delete(g, id) => {
            if let Some(list) = sound_items(app, g) {
                list.retain(|x| super::vid(x, "sound_id") != Some(id));
            }
        }
    }
}