Skip to content

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

22.0 KB
Raw Blame
//! Discord's soundboard: the picker (call bar / Voice Connected panel), sending
//! a sound to the call, and playing the sounds people send
//! (VOICE_CHANNEL_EFFECT_SEND). Sounds aren't part of the voice stream: every
//! client downloads and plays them itself, so without this RustCord users heard
//! nothing when someone used the soundboard.

use super::SizedOffScreen;
use crate::app::RustCord;
use crate::style::{icon, icon_font, overlay, Theme};
use discord::model::Id;
use eframe::egui::{self, pos2, vec2, Align2, Color32, CursorIcon, FontId, Frame, Margin, Order, Rect, ScrollArea, Sense, Stroke, TextEdit, Ui};
use serde_json::Value;
use std::collections::HashMap;
use std::time::{Duration, Instant};

/// Segoe Fluent "Audio" (a speaker with waves): the soundboard button.
pub const SOUNDBOARD: &str = "\u{E995}";
const PICKER_W: f32 = 500.0;
const PICKER_H: f32 = 480.0;

#[derive(Clone, Debug)]
pub struct Sound {
    pub id: Id,
    pub name: String,
    /// Discord's per-sound volume (0–1).
    pub volume: f32,
    pub emoji_id: Option<Id>,
    pub emoji_name: Option<String>,
    /// `None` for Discord's default sounds.
    pub guild: Option<Id>,
    pub available: bool,
}

impl Sound {
    fn parse(v: &Value, guild: Option<Id>) -> Option<Sound> {
        Some(Sound {
            id: Id::from_value(&v["sound_id"])?,
            name: v["name"].as_str().unwrap_or("Sound").to_string(),
            volume: v["volume"].as_f64().unwrap_or(1.0) as f32,
            emoji_id: Id::from_value(&v["emoji_id"]),
            emoji_name: v["emoji_name"].as_str().filter(|s| !s.is_empty()).map(String::from),
            guild: guild.or_else(|| Id::from_value(&v["guild_id"])),
            available: v["available"].as_bool().unwrap_or(true),
        })
    }

    pub fn url(id: Id) -> String {
        format!("https://cdn.discordapp.com/soundboard-sounds/{id}")
    }
}

#[derive(Default)]
pub struct Soundboard {
    /// The picker: the button it hangs from and the frame it opened.
    pub open: Option<(Rect, u64)>,
    pub search: String,
    /// Each server's sounds (SOUNDBOARD_SOUNDS), once asked for.
    pub guild_sounds: HashMap<Id, Vec<Sound>>,
    pub requested: bool,
    /// Downloads to play when they land: URL → volume.
    pub pending: HashMap<String, f32>,
    /// The last sound you sent, so its echo from the gateway doesn't play twice.
    last_sent: Option<(Id, Instant)>,
    volume_open: bool,
}

impl RustCord {
    pub fn soundboard_open(&self) -> bool {
        self.soundboard.open.is_some()
    }

    pub fn soundboard_anchor(&mut self, anchor: Rect) {
        if let Some(o) = self.soundboard.open.as_mut() {
            if o.0.center().distance(anchor.center()) < 400.0 {
                o.0 = anchor;
            }
        }
    }

    /// The soundboard button: open the picker above it (or close it).
    pub fn toggle_soundboard(&mut self, anchor: Rect) {
        if self.soundboard.open.take().is_some() {
            return;
        }
        self.soundboard.open = Some((anchor, self.ctx.cumulative_pass_nr()));
        self.soundboard.search.clear();
        self.api_get_once("soundboard-defaults", "/soundboard-default-sounds");
        if !self.soundboard.requested {
            self.soundboard.requested = true;
            let ids: Vec<String> = self.store.guilds.keys().map(|g| g.to_string()).collect();
            self.backend.send(crate::backend::Command::GatewaySend(serde_json::json!({ "op": 31, "d": { "guild_ids": ids } })));
        }
    }

    /// SOUNDBOARD_SOUNDS and the sound create / update / delete dispatches.
    pub fn soundboard_dispatch(&mut self, name: &str, d: &Value) {
        match name {
            "SOUNDBOARD_SOUNDS" | "GUILD_SOUNDBOARD_SOUNDS_UPDATE" => {
                let Some(g) = Id::from_value(&d["guild_id"]) else { return };
                let list = d["soundboard_sounds"].as_array().into_iter().flatten().filter_map(|s| Sound::parse(s, Some(g))).collect();
                self.soundboard.guild_sounds.insert(g, list);
            }
            "GUILD_SOUNDBOARD_SOUND_CREATE" | "GUILD_SOUNDBOARD_SOUND_UPDATE" => {
                let Some(g) = Id::from_value(&d["guild_id"]) else { return };
                let Some(sound) = Sound::parse(d, Some(g)) else { return };
                let list = self.soundboard.guild_sounds.entry(g).or_default();
                match list.iter_mut().find(|s| s.id == sound.id) {
                    Some(s) => *s = sound,
                    None => list.push(sound),
                }
            }
            "GUILD_SOUNDBOARD_SOUND_DELETE" => {
                let (Some(g), Some(id)) = (Id::from_value(&d["guild_id"]), Id::from_value(&d["sound_id"])) else { return };
                if let Some(list) = self.soundboard.guild_sounds.get_mut(&g) {
                    list.retain(|s| s.id != id);
                }
            }
            // Someone (maybe you) played a sound in a call.
            "VOICE_CHANNEL_EFFECT_SEND" => {
                let Some(sound) = Id::from_value(&d["sound_id"]) else { return };
                let Some(channel) = Id::from_value(&d["channel_id"]) else { return };
                if self.voice.as_ref().map(|v| v.channel) != Some(channel) || self.self_deaf {
                    return;
                }
                let user = Id::from_value(&d["user_id"]);
                if user.is_some_and(|u| self.voice_ui.locally_muted(u)) {
                    return;
                }
                let ours = user.is_some() && user == self.store.me_id();
                if ours && self.soundboard.last_sent.is_some_and(|(id, at)| id == sound && at.elapsed() < Duration::from_secs(4)) {
                    return;
                }
                let volume = d["sound_volume"].as_f64().unwrap_or(1.0) as f32;
                self.play_sound(sound, volume);
            }
            _ => {}
        }
    }

    /// Play a sound locally at Discord's volume × the soundboard and output volumes.
    pub fn play_sound(&mut self, id: Id, volume: f32) {
        let gain = volume.clamp(0.0, 1.0) * self.voice_ui.prefs.soundboard_volume / 100.0 * self.voice_ui.prefs.output_volume / 100.0;
        let url = Sound::url(id);
        match self.audio.cache.get(&url).cloned() {
            Some(bytes) => self.audio.play_effect(bytes, gain),
            None => {
                self.soundboard.pending.insert(url.clone(), gain);
                self.backend.send(crate::backend::Command::FetchBytes(url));
            }
        }
    }

    /// A download finished: true if it was a sound waiting to play.
    pub fn soundboard_bytes(&mut self, url: &str, bytes: Option<std::sync::Arc<[u8]>>) -> bool {
        let Some(gain) = self.soundboard.pending.remove(url) else { return false };
        if let Some(b) = bytes {
            self.audio.play_effect(b, gain);
        } else {
            log::warn!("soundboard: couldn't download {}", crate::net_images::log_url(url));
        }
        true
    }

    /// Play `sound` for everyone in the call.
    fn send_sound(&mut self, sound: &Sound) {
        let Some(v) = self.voice.as_ref().filter(|v| v.connected) else {
            self.toast("Join a voice channel to use the soundboard.", true);
            return;
        };
        if self.self_deaf {
            self.toast("You can't use the soundboard while deafened.", true);
            return;
        }
        let mut body = serde_json::json!({ "sound_id": sound.id.to_string() });
        if let Some(g) = sound.guild {
            body["source_guild_id"] = Value::String(g.to_string());
        }
        let channel = v.channel;
        self.api("soundboard-send", reqwest::Method::POST, format!("/channels/{channel}/send-soundboard-sound"), Some(body));
        self.soundboard.last_sent = Some((sound.id, Instant::now()));
        *self.voice_ui.prefs.sound_uses.entry(sound.id.0).or_default() += 1;
        self.voice_ui.changed();
        self.play_sound(sound.id, sound.volume);
    }

    /// The picker: search, Frequently Used, then each server's sounds and
    /// Discord's defaults, three to a row.
    pub fn soundboard_ui(&mut self, ctx: &egui::Context) {
        if let Some(Err(e)) = self.api_take("soundboard-send") {
            self.toast(format!("Couldn't play the sound: {e}"), true);
        }
        let Some((anchor, opened)) = self.soundboard.open else { return };
        if self.voice.is_none() {
            self.soundboard.open = None;
            return;
        }
        let t = self.theme.clone();
        let defaults: Vec<Sound> = match self.api_result("soundboard-defaults") {
            Some(Ok(Value::Array(list))) => list.iter().filter_map(|s| Sound::parse(s, None)).collect(),
            _ => Vec::new(),
        };
        let call_guild = self.voice.as_ref().and_then(|v| v.guild);
        let nitro = self.store.me.as_ref().and_then(|m| m.premium_type).is_some_and(|p| p > 0);
        // Sections: the call's server first, then the rest by name.
        let mut guilds: Vec<(Id, String, Option<String>)> = self
            .soundboard
            .guild_sounds
            .iter()
            .filter(|(_, s)| !s.is_empty())
            .filter_map(|(g, _)| self.store.guilds.get(g).map(|gs| (*g, gs.guild.name.clone(), gs.guild.icon_url(64))))
            .collect();
        guilds.sort_by(|a, b| (Some(a.0) != call_guild).cmp(&(Some(b.0) != call_guild)).then_with(|| a.1.to_lowercase().cmp(&b.1.to_lowercase())));
        let query = self.soundboard.search.trim().to_lowercase();
        let matches = |s: &Sound| query.is_empty() || s.name.to_lowercase().contains(&query);
        let usable = |s: &Sound| s.available && (s.guild.is_none() || s.guild == call_guild || nitro);
        let mut all: HashMap<Id, Sound> = HashMap::new();
        for s in self.soundboard.guild_sounds.values().flatten().chain(defaults.iter()) {
            all.insert(s.id, s.clone());
        }
        let mut frequent: Vec<(u32, Sound)> = self
            .voice_ui
            .prefs
            .sound_uses
            .iter()
            .filter_map(|(id, n)| all.get(&Id(*id)).filter(|s| usable(s)).map(|s| (*n, s.clone())))
            .collect();
        frequent.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.name.cmp(&b.1.name)));
        frequent.truncate(6);
        let loading = self.soundboard.guild_sounds.is_empty() && defaults.is_empty();

        let mut send: Option<Sound> = None;
        let mut preview: Option<Sound> = None;
        let mut search = std::mem::take(&mut self.soundboard.search);
        let mut volume = self.voice_ui.prefs.soundboard_volume;
        let mut volume_open = self.soundboard.volume_open;
        let mut volume_done = false;
        let screen = ctx.screen_rect();
        // min/max, not clamp: a window narrower than the picker (or minimized)
        // makes the range empty, and f32::clamp panics on that.
        let x = (anchor.center().x - PICKER_W / 2.0).min(screen.right() - PICKER_W - 8.0).max(screen.left() + 8.0);
        let pos = pos2(x, anchor.top() - 8.0);
        let area = egui::Area::new(egui::Id::new("soundboard_picker")).order(Order::Foreground).pivot(Align2::LEFT_BOTTOM).fixed_pos(pos).constrain(true).sized_off_screen(ctx).show(ctx, |ui| {
            Frame::none()
                .fill(t.bg_floating)
                .rounding(8.0)
                .stroke(Stroke::new(1.0_f32, t.border_subtle))
                .shadow(egui::epaint::Shadow { offset: vec2(0.0, 12.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(90) })
                .inner_margin(Margin::same(10.0))
                .show(ui, |ui| {
                    ui.set_width(PICKER_W - 20.0);
                    ui.set_height(PICKER_H - 20.0);
                    // Search, and the soundboard volume.
                    let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::hover());
                    let field = bar.with_max_x(bar.right() - 40.0);
                    let id = egui::Id::new("soundboard_search");
                    let focused = ui.memory(|m| m.has_focus(id));
                    ui.painter().rect(field, 8.0, t.bg_tertiary, Stroke::new(1.0_f32, if focused { super::voice_menu::BLURPLE } else { t.border_subtle }));
                    ui.painter().text(pos2(field.left() + 16.0, field.center().y), Align2::CENTER_CENTER, icon::SEARCH, icon_font(14.0), t.text_muted);
                    let edit = Rect::from_min_max(pos2(field.left() + 30.0, field.top()), pos2(field.right() - 8.0, field.bottom()));
                    let mut eui = ui.new_child(egui::UiBuilder::new().max_rect(edit).layout(egui::Layout::left_to_right(egui::Align::Center)));
                    let r = eui.add(
                        TextEdit::singleline(&mut search)
                            .id(id)
                            .frame(false)
                            .hint_text(egui::RichText::new("Find the perfect sound").color(t.text_muted))
                            .font(FontId::proportional(15.0))
                            .text_color(t.text_normal)
                            .desired_width(edit.width()),
                    );
                    if ctx.cumulative_pass_nr() <= opened + 1 {
                        r.request_focus();
                    }
                    let vb = Rect::from_center_size(pos2(bar.right() - 18.0, bar.center().y), vec2(32.0, 32.0));
                    let vr = ui.interact(vb, egui::Id::new("soundboard_volume"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
                    if vr.hovered() || volume_open {
                        ui.painter().rect_filled(vb, 8.0, overlay(0.16));
                    }
                    ui.painter().text(vb.center(), Align2::CENTER_CENTER, icon::SPEAK, icon_font(18.0), if vr.hovered() || volume_open { t.header_primary } else { t.interactive_normal });
                    if vr.on_hover_text("Soundboard Volume").clicked() {
                        volume_open = !volume_open;
                    }
                    if volume_open {
                        ui.add_space(6.0);
                        let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::hover());
                        ui.painter().text(pos2(row.left() + 4.0, row.center().y), Align2::LEFT_CENTER, "Soundboard Volume", FontId::new(13.0, egui::FontFamily::Name(crate::style::BOLD.into())), t.text_normal);
                        let track = Rect::from_min_max(pos2(row.left() + 150.0, row.top() + 3.0), pos2(row.right() - 8.0, row.bottom() - 3.0));
                        let (_, done) = super::voice_menu::paint_slider(ui, &t, egui::Id::new("soundboard_volume_slider"), track, &mut volume, 100.0);
                        volume_done = done;
                    }
                    ui.add_space(8.0);
                    ScrollArea::vertical().id_salt("soundboard_scroll").auto_shrink([false, false]).show(ui, |ui| {
                        ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                        let mut section = |ui: &mut Ui, title: &str, icon_url: Option<String>, glyph: Option<&str>, sounds: Vec<&Sound>| {
                            let sounds: Vec<&Sound> = sounds.into_iter().filter(|s| matches(s)).collect();
                            if sounds.is_empty() {
                                return;
                            }
                            let (h, _) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::hover());
                            let mut x = h.left() + 4.0;
                            if let Some(url) = icon_url {
                                let r = Rect::from_center_size(pos2(x + 9.0, h.center().y), vec2(18.0, 18.0));
                                egui::Image::new(url).rounding(5.0).paint_at(ui, r);
                                x += 24.0;
                            } else if let Some(g) = glyph {
                                ui.painter().text(pos2(x + 8.0, h.center().y), Align2::CENTER_CENTER, g, icon_font(14.0), t.text_muted);
                                x += 22.0;
                            }
                            let clip = ui.painter_at(h);
                            super::paint_text_emoji(ui, &clip, pos2(x, h.center().y), title, FontId::new(13.0, egui::FontFamily::Name(crate::style::BOLD.into())), t.text_muted);
                            let cols = 3;
                            let gap = 8.0;
                            let w = (ui.available_width() - gap * (cols as f32 - 1.0)) / cols as f32;
                            for chunk in sounds.chunks(cols) {
                                let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 40.0), Sense::hover());
                                for (i, s) in chunk.iter().enumerate() {
                                    let r = Rect::from_min_size(pos2(row.left() + i as f32 * (w + gap), row.top()), vec2(w, 32.0));
                                    let ok = usable(s);
                                    let resp = ui.interact(r, egui::Id::new(("sound", s.id.0, title)), Sense::click());
                                    let resp = if ok { resp.on_hover_cursor(CursorIcon::PointingHand) } else { resp };
                                    // Hover by position: the preview button on top would otherwise take the
                                    // tile's hover away, hide itself, and let the click play the sound.
                                    let over = ui.rect_contains_pointer(r);
                                    let fill = if over && ok { overlay(0.24) } else { overlay(0.12) };
                                    ui.painter().rect_filled(r, 8.0, fill);
                                    let fg = if ok { t.header_primary } else { t.text_muted };
                                    let mut x = r.left() + 10.0;
                                    if let Some(e) = s.emoji_id {
                                        let er = Rect::from_center_size(pos2(x + 9.0, r.center().y), vec2(18.0, 18.0));
                                        egui::Image::new(format!("https://cdn.discordapp.com/emojis/{e}.webp?size=48")).paint_at(ui, er);
                                        x += 24.0;
                                    } else if let Some(e) = &s.emoji_name {
                                        let er = super::paint_text_emoji(ui, &ui.painter_at(r), pos2(x, r.center().y), e, FontId::proportional(15.0), fg);
                                        x = er.right() + 6.0;
                                    }
                                    let preview_w = if over && ok { 26.0 } else { 0.0 };
                                    let clip = ui.painter_at(Rect::from_min_max(r.min, pos2(r.right() - 6.0 - preview_w, r.bottom())));
                                    super::paint_text_emoji(ui, &clip, pos2(x, r.center().y), &s.name, FontId::new(13.5, egui::FontFamily::Name(crate::style::BOLD.into())), fg);
                                    // Preview: hear it yourself without playing it to the call.
                                    let mut previewed = false;
                                    if preview_w > 0.0 {
                                        let pr = Rect::from_center_size(pos2(r.right() - 16.0, r.center().y), vec2(22.0, 22.0));
                                        let p = ui.interact(pr, egui::Id::new(("sound_preview", s.id.0, title)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                                        ui.painter().text(pr.center(), Align2::CENTER_CENTER, icon::AUDIO, icon_font(13.0), if p.hovered() { t.header_primary } else { t.interactive_normal });
                                        if p.on_hover_text("Preview").clicked() {
                                            preview = Some((*s).clone());
                                            previewed = true;
                                        }
                                    }
                                    let resp = if ok { resp.on_hover_text(&s.name) } else { resp.on_hover_text("Get Nitro to use sounds from other servers") };
                                    if resp.clicked() && ok && !previewed {
                                        send = Some((*s).clone());
                                    }
                                }
                            }
                            ui.add_space(6.0);
                        };
                        if !frequent.is_empty() {
                            section(ui, "Frequently Used", None, Some("\u{E823}"), frequent.iter().map(|(_, s)| s).collect());
                        }
                        for (g, name, icon_url) in &guilds {
                            let list: Vec<&Sound> = self.soundboard.guild_sounds.get(g).map(|l| l.iter().collect()).unwrap_or_default();
                            section(ui, name, icon_url.clone(), None, list);
                        }
                        if !defaults.is_empty() {
                            section(ui, "Discord", None, Some(SOUNDBOARD), defaults.iter().collect());
                        }
                        if loading {
                            ui.add_space(20.0);
                            ui.vertical_centered(|ui| ui.label(egui::RichText::new("Loading sounds…").color(t.text_muted)));
                        }
                    });
                });
        });
        self.soundboard.search = search;
        self.soundboard.volume_open = volume_open;
        if (volume - self.voice_ui.prefs.soundboard_volume).abs() > f32::EPSILON || volume_done {
            self.voice_ui.prefs.soundboard_volume = volume;
            if volume_done {
                self.voice_ui.changed();
            }
        }
        if let Some(s) = preview {
            self.play_sound(s.id, s.volume);
        }
        if let Some(s) = send {
            self.send_sound(&s);
        }
        let rect = area.response.rect;
        let frame = ctx.cumulative_pass_nr();
        let outside = frame > opened && ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !rect.contains(p) && !anchor.contains(p)));
        if outside || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
            self.soundboard.open = None;
        }
    }
}

/// The soundboard button's colour in the panels.
pub fn button_fill(open: bool, hovered: bool, t: &Theme) -> Color32 {
    if open || hovered {
        overlay(0.2)
    } else {
        t.bg_tertiary.gamma_multiply(0.6)
    }
}