Skip to content

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

41.3 KB
Raw Blame
//! Discord's voice option menus, drawn the way Discord draws them: the user
//! panel's mic / headphone chevrons ("Input Options", "Output Options"), the
//! call view's microphone chevron ("More Microphone Options") and "More
//! Options" (…), and the right-click menu on someone in a DM call (User
//! Volume, local Mute). In a server's voice channel that right-click opens
//! the member menu instead (moderation.rs), which has these rows too.
//!
//! One menu is open at a time (`VoiceUi::menu`). Rows with a chevron open a
//! submenu on hover (devices, input profile); sliders apply while dragged and
//! save when let go.

use super::SizedOffScreen;
use crate::app::{RustCord, SettingsTab};
use crate::style::{icon, icon_font, overlay, rgba, Theme};
use discord::model::{permissions, Id};
use eframe::egui::{self, pos2, vec2, Align2, Color32, CursorIcon, FontId, Frame, Margin, Order, Rect, Rounding, Sense, Stroke, Ui};

/// Discord's menu: 222 px wide, 8 px padding.
const MENU_W: f32 = 222.0;
const SUB_W: f32 = 188.0;
const PAD: f32 = 8.0;
/// Discord's slider / radio / checkbox blurple.
pub const BLURPLE: Color32 = Color32::from_rgb(88, 101, 242);
/// Discord's red for muted / deafened controls.
pub const MUTED_RED: Color32 = Color32::from_rgb(218, 62, 68);
pub const CHEVRON_UP: &str = "\u{E70E}";
const ADD_PERSON: &str = "\u{E8FA}";

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VoiceMenuKind {
    /// User panel mic chevron.
    Input,
    /// User panel headphones chevron.
    Output,
    /// Call view mic chevron.
    CallMic,
    /// Call view "More Options" (…).
    CallMore,
    /// Right-click on someone in voice.
    User(Id),
    /// Right-click on the stream you're watching (its streamer).
    Stream(Id),
    /// The channel header's bell: mute the channel, its notification level.
    Notify(Id),
}

impl VoiceMenuKind {
    /// Menus that belong to the call view's control bar.
    fn in_call_view(self) -> bool {
        matches!(self, VoiceMenuKind::CallMic | VoiceMenuKind::CallMore)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Sub {
    InputDevice,
    InputProfile,
    OutputDevice,
    /// "Mute Channel" durations.
    MuteFor,
}

#[derive(Clone, Copy, Debug)]
pub struct VoiceMenu {
    pub kind: VoiceMenuKind,
    /// The button (group) it hangs from; for `User`, a point-sized rect at the click.
    pub anchor: Rect,
    /// Frame it opened (the opening click doesn't close it).
    pub opened: u64,
    /// The submenu shown, with the top of the row that opened it.
    pub sub: Option<(Sub, f32)>,
}

/// What a click in the menu asks for (applied after drawing).
enum Act {
    PickDevice { input: bool, id: Option<String>, name: Option<String> },
    Isolation(bool),
    InputVolume(f32, bool),
    OutputVolume(f32, bool),
    ToggleDeafen,
    ListenToMic,
    Sensitivity(f32, bool),
    Settings,
    Invite,
    ShowNonVideo,
    UserVolume(Id, f32, bool),
    StreamVolume(Id, f32, bool),
    StreamFullscreen(Id),
    WatchStream(Id),
    StopWatching(Id),
    LocalMute(Id),
    Profile(Id),
    Mention(Id),
    Message(Id),
    ServerMute(Id, bool),
    ServerDeaf(Id, bool),
    Disconnect(Id),
    CopyId(Id),
    /// Mute a channel for this many seconds (-1: until unmuted), or unmute (None).
    MuteChannel(Id, Option<i64>),
    /// A channel's notification level (3: use the category / server default).
    ChannelNotify(Id, u8),
}

fn label_font() -> FontId {
    crate::style::medium(14.0)
}

/// The menu card: floating background, hairline border, Discord's soft shadow.
pub fn menu_frame(t: &Theme) -> Frame {
    Frame::none()
        .fill(t.bg_floating)
        .rounding(8.0)
        .stroke(Stroke::new(1.0_f32, super::ctx_menu_border(t)))
        .shadow(egui::epaint::Shadow { offset: vec2(0.0, 12.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(61) })
        .inner_margin(Margin::same(PAD))
}

fn hover_fill() -> Color32 {
    overlay(0.16)
}

/// A row's hover background and text colour.
fn row_bg(ui: &Ui, t: &Theme, row: Rect, hovered: bool) -> Color32 {
    if hovered {
        ui.painter().rect_filled(row, 4.0, hover_fill());
        t.header_primary
    } else {
        t.text_normal
    }
}

/// "Input Device / Default ›": a two-line row that opens a submenu.
fn sub_row(ui: &mut Ui, t: &Theme, label: &str, sub: &str, open: bool) -> egui::Response {
    let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 52.0), Sense::click());
    let fg = row_bg(ui, t, row, resp.hovered() || open);
    if open && !resp.hovered() {
        ui.painter().rect_filled(row, 4.0, hover_fill());
    }
    let clip = ui.painter_at(row.with_max_x(row.right() - 28.0));
    clip.text(pos2(row.left() + 8.0, row.top() + 17.0), Align2::LEFT_CENTER, label, label_font(), if open { t.header_primary } else { fg });
    clip.text(pos2(row.left() + 8.0, row.top() + 35.0), Align2::LEFT_CENTER, sub, FontId::proportional(12.0), t.text_muted);
    ui.painter().text(pos2(row.right() - 14.0, row.center().y), Align2::CENTER_CENTER, icon::CHEVRON, icon_font(11.0), if open { t.header_primary } else { fg });
    resp.on_hover_cursor(CursorIcon::PointingHand)
}

/// A one-line row, with an optional icon on the left (Discord's "⚙ Voice Settings").
fn item_row(ui: &mut Ui, t: &Theme, glyph: Option<&str>, label: &str, danger: bool) -> egui::Response {
    let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());
    let fg = if danger {
        if resp.hovered() {
            ui.painter().rect_filled(row, 4.0, MUTED_RED);
            Color32::WHITE
        } else {
            MUTED_RED
        }
    } else {
        row_bg(ui, t, row, resp.hovered())
    };
    let mut x = row.left() + 8.0;
    if let Some(g) = glyph {
        ui.painter().text(pos2(x + 10.0, row.center().y), Align2::CENTER_CENTER, g, icon_font(17.0), fg);
        x += 28.0;
    }
    ui.painter_at(row).text(pos2(x, row.center().y), Align2::LEFT_CENTER, label, label_font(), fg);
    resp.on_hover_cursor(CursorIcon::PointingHand)
}

/// A row with Discord's checkbox on the right.
fn check_row(ui: &mut Ui, t: &Theme, label: &str, checked: bool) -> egui::Response {
    let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());
    let fg = row_bg(ui, t, row, resp.hovered());
    ui.painter_at(row.with_max_x(row.right() - 34.0)).text(pos2(row.left() + 8.0, row.center().y), Align2::LEFT_CENTER, label, label_font(), fg);
    let b = Rect::from_center_size(pos2(row.right() - 18.0, row.center().y), vec2(18.0, 18.0));
    if checked {
        ui.painter().rect_filled(b, 4.0, BLURPLE);
        ui.painter().text(b.center(), Align2::CENTER_CENTER, icon::CHECK, icon_font(11.0), Color32::WHITE);
    } else {
        ui.painter().rect_stroke(b.shrink(0.75), 4.0, Stroke::new(1.5_f32, t.interactive_normal));
    }
    resp.on_hover_cursor(CursorIcon::PointingHand)
}

/// A row with Discord's radio on the right.
fn radio_row(ui: &mut Ui, t: &Theme, label: &str, selected: bool) -> egui::Response {
    let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());
    let fg = row_bg(ui, t, row, resp.hovered());
    ui.painter_at(row.with_max_x(row.right() - 34.0)).text(pos2(row.left() + 8.0, row.center().y), Align2::LEFT_CENTER, label, label_font(), if selected { t.header_primary } else { fg });
    let c = pos2(row.right() - 18.0, row.center().y);
    if selected {
        ui.painter().circle_filled(c, 9.0, BLURPLE);
        ui.painter().circle_filled(c, 3.5, Color32::WHITE);
    } else {
        ui.painter().circle_stroke(c, 8.25, Stroke::new(1.5_f32, t.interactive_normal));
    }
    resp.on_hover_cursor(CursorIcon::PointingHand).on_hover_text(label)
}

fn separator(ui: &mut Ui, t: &Theme) {
    ui.add_space(8.0);
    let y = ui.cursor().top();
    ui.painter().hline(ui.max_rect().shrink2(vec2(4.0, 0.0)).x_range(), y, Stroke::new(1.0_f32, t.border_subtle));
    ui.add_space(9.0);
}

/// "Input Volume": label over Discord's slider (4 px bar, blurple fill, white
/// 16 px grabber, the value in a bubble while hovered). Returns (changed, let go).
pub fn slider_row(ui: &mut Ui, t: &Theme, id: egui::Id, label: &str, value: &mut f32, max: f32) -> (bool, bool) {
    slider_row_fmt(ui, t, id, label, value, max, |v| format!("{v:.0}%"))
}

/// [`slider_row`] with its own text for the bubble (decibels, say).
pub fn slider_row_fmt(ui: &mut Ui, t: &Theme, id: egui::Id, label: &str, value: &mut f32, max: f32, text: impl Fn(f32) -> String) -> (bool, bool) {
    let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 58.0), Sense::hover());
    ui.painter().text(pos2(row.left() + 8.0, row.top() + 17.0), Align2::LEFT_CENTER, label, label_font(), t.text_normal);
    let track = Rect::from_min_max(pos2(row.left() + 8.0, row.top() + 30.0), pos2(row.right() - 8.0, row.top() + 54.0));
    paint_slider_fmt(ui, t, id, track, value, max, text)
}

/// The slider itself in `track` (24 px tall).
pub fn paint_slider(ui: &mut Ui, t: &Theme, id: egui::Id, track: Rect, value: &mut f32, max: f32) -> (bool, bool) {
    paint_slider_fmt(ui, t, id, track, value, max, |v| format!("{v:.0}%"))
}

pub fn paint_slider_fmt(ui: &mut Ui, t: &Theme, id: egui::Id, track: Rect, value: &mut f32, max: f32, text: impl Fn(f32) -> String) -> (bool, bool) {
    let resp = ui.interact(track, id, Sense::click_and_drag()).on_hover_cursor(CursorIcon::PointingHand);
    // The grabber travels 5 px short of each end, like Discord's.
    let travel = track.shrink2(vec2(5.0, 0.0));
    let mut changed = false;
    if resp.is_pointer_button_down_on() || resp.clicked() {
        if let Some(p) = ui.ctx().pointer_interact_pos() {
            let v = (((p.x - travel.left()) / travel.width()).clamp(0.0, 1.0) * max).round();
            if (v - *value).abs() > f32::EPSILON {
                *value = v;
                changed = true;
            }
        }
    }
    let frac = (*value / max).clamp(0.0, 1.0);
    let bar = Rect::from_center_size(track.center(), vec2(track.width(), 4.0));
    let x = travel.left() + frac * travel.width();
    let p = ui.painter();
    p.rect_filled(bar, 2.0, t.bg_tertiary.lerp_to_gamma(Color32::WHITE, 0.08));
    p.rect_filled(bar.with_max_x(x), 2.0, BLURPLE);
    let knob = pos2(x, track.center().y);
    p.circle_filled(knob + vec2(0.0, 1.0), 8.5, Color32::from_black_alpha(70));
    p.circle_filled(knob, 8.0, Color32::WHITE);
    if resp.hovered() || resp.dragged() {
        // The value in a dark bubble over the grabber.
        let tip = ui.ctx().layer_painter(egui::LayerId::new(Order::Tooltip, id.with("tip")));
        let g = tip.layout_no_wrap(text(*value), label_font(), Color32::WHITE);
        let bubble = Rect::from_center_size(pos2(knob.x, track.top() - 14.0), g.size() + vec2(16.0, 10.0));
        tip.rect_filled(bubble, 6.0, Color32::from_rgb(0x11, 0x12, 0x14));
        tip.galley(bubble.center() - g.size() / 2.0, g, Color32::WHITE);
    }
    (changed, resp.drag_stopped() || resp.clicked())
}

/// "Input Level": Discord's tick meter, green up to the microphone level.
/// Ticks below the input sensitivity are dimmer: that part is not sent.
fn level_row(ui: &mut Ui, t: &Theme, level_db: f32, threshold_db: f32) {
    let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 58.0), Sense::hover());
    ui.painter().text(pos2(row.left() + 8.0, row.top() + 17.0), Align2::LEFT_CENTER, "Input Level", label_font(), t.text_normal);
    let meter = Rect::from_min_max(pos2(row.left() + 8.0, row.top() + 34.0), pos2(row.right() - 8.0, row.top() + 50.0));
    // -70 dBFS (silence) to 0 (full scale).
    let frac = ((level_db + 70.0) / 70.0).clamp(0.0, 1.0);
    let ticks = ((meter.width() + 2.0) / 4.0).floor() as usize;
    let lit = (frac * ticks as f32).round() as usize;
    let sent = (((threshold_db + 70.0) / 70.0).clamp(0.0, 1.0) * ticks as f32).round() as usize;
    for i in 0..ticks {
        let x = meter.left() + i as f32 * 4.0;
        let r = Rect::from_min_size(pos2(x, meter.top()), vec2(2.0, meter.height()));
        let c = if i >= lit {
            overlay(0.28)
        } else if i < sent {
            crate::voice_call::VOICE_GREEN.gamma_multiply(0.45)
        } else {
            crate::voice_call::VOICE_GREEN
        };
        ui.painter().rect_filled(r, 1.0, c);
    }
}

impl RustCord {
    /// Open `kind` (or close it if it's the one open): the chevrons call this.
    pub fn toggle_voice_menu(&mut self, kind: VoiceMenuKind, anchor: Rect) {
        // Someone in a server's voice channel: the member menu, which has the
        // voice rows too (volume, mute, server mute…) plus roles and moderation.
        if let VoiceMenuKind::User(uid) = kind {
            let user = if Some(uid) == self.store.me_id() { self.store.me.clone() } else { self.store.users.get(&uid).cloned() };
            if let (Some((Some(g), _)), Some(user)) = (self.voice_place_of(uid), user) {
                return self.open_member_menu(g, user, anchor.min);
            }
        }
        let frame = self.ctx.cumulative_pass_nr();
        self.voice_ui.menu = match self.voice_ui.menu {
            Some(m) if m.kind == kind => None,
            _ => Some(VoiceMenu { kind, anchor, opened: frame, sub: None }),
        };
    }

    pub fn voice_menu_open(&self, kind: VoiceMenuKind) -> bool {
        self.voice_ui.menu.is_some_and(|m| m.kind == kind)
    }

    /// Keep an open menu attached to its button (layouts move).
    pub fn voice_menu_anchor(&mut self, kind: VoiceMenuKind, anchor: Rect) {
        if let Some(m) = self.voice_ui.menu.as_mut().filter(|m| m.kind == kind) {
            m.anchor = anchor;
        }
    }

    /// Short device name for a row's second line ("Default" or the device).
    fn device_subtitle(&self, input: bool) -> String {
        let id = if input { &self.voice_ui.prefs.input_device } else { &self.voice_ui.prefs.output_device };
        if id.is_none() {
            "Default".into()
        } else {
            self.voice_ui.device_label(input)
        }
    }

    /// The guild and channel a user is in voice in (for the moderator actions).
    fn voice_place_of(&self, user: Id) -> Option<(Option<Id>, Id)> {
        let (ch, _) = self.store.voice.iter().find(|(_, users)| users.contains(&user))?;
        Some((self.store.channels.get(ch).and_then(|c| c.guild_id), *ch))
    }

    /// Draw the open voice menu (every frame, after the panels that anchor it).
    pub fn voice_menu_ui(&mut self, ctx: &egui::Context) {
        match self.api_take("voice-mod") {
            Some(Err(e)) => self.toast(format!("Couldn't do that: {e}"), true),
            Some(Ok(_)) | None => {}
        }
        let Some(menu) = self.voice_ui.menu else { return };
        let frame = ctx.cumulative_pass_nr();
        // A stream's menu goes with the stream.
        if matches!(menu.kind, VoiceMenuKind::Stream(streamer) if self.watched_stream_volume(streamer).is_none()) {
            self.voice_ui.menu = None;
            return;
        }
        // The call bar's menus go with the call view.
        if menu.kind.in_call_view() && (self.voice_ui.menu_drawn + 1 < frame || self.voice.is_none()) {
            self.voice_ui.menu = None;
            return;
        }
        let t = self.theme.clone();
        let kind = menu.kind;
        let needs_devices = matches!(kind, VoiceMenuKind::Input | VoiceMenuKind::Output | VoiceMenuKind::CallMic);
        if needs_devices {
            self.voice_ui.want_devices(ctx);
        }
        let in_call = self.voice.as_ref().is_some_and(|v| v.connected);
        let level = if in_call && !self.self_mute && !self.self_deaf { voice::call_input_level_db() } else { -100.0 };
        if in_call && matches!(kind, VoiceMenuKind::Input | VoiceMenuKind::CallMic) {
            ctx.request_repaint_after(std::time::Duration::from_millis(50));
        }
        let in_sub = self.device_subtitle(true);
        let out_sub = self.device_subtitle(false);
        let iso = self.voice_ui.prefs.voice_isolation;
        let listen = self.voice_ui.prefs.listen_to_mic;
        let sens = self.voice_ui.prefs.input_sensitivity.clamp(-70.0, 0.0);
        let mut in_vol = self.voice_ui.prefs.input_volume;
        let mut out_vol = self.voice_ui.prefs.output_volume;
        let deaf = self.self_deaf;
        let show_non_video = self.voice_ui.prefs.show_non_video;
        let call_channel = self.voice.as_ref().map(|v| v.channel);
        let can_invite = call_channel
            .and_then(|c| self.store.channels.get(&c))
            .and_then(|c| c.guild_id)
            .is_some_and(|g| self.store.has_perm(g, permissions::CREATE_INSTANT_INVITE));
        // Someone in voice: what you may do to them.
        let me = self.store.me_id();
        let (user_ctx, mod_perms) = match kind {
            VoiceMenuKind::User(uid) => {
                let place = self.voice_place_of(uid);
                let gid = place.and_then(|(g, _)| g);
                let perm = |p: u64| gid.is_some_and(|g| self.store.has_perm(g, p));
                let flags = self.store.voice_flags.get(&uid).copied().unwrap_or_default();
                (
                    Some((uid, Some(uid) == me, self.voice_ui.user_volume(uid), self.voice_ui.locally_muted(uid), flags)),
                    (perm(permissions::MUTE_MEMBERS), perm(permissions::DEAFEN_MEMBERS), perm(permissions::MOVE_MEMBERS)),
                )
            }
            _ => (None, (false, false, false)),
        };
        let stream_volume = match kind {
            VoiceMenuKind::User(uid) | VoiceMenuKind::Stream(uid) => self.watched_stream_volume(uid),
            _ => None,
        };
        let fullscreen = matches!(kind, VoiceMenuKind::Stream(s) if self.watch_is_fullscreen(s));

        let (pivot, pos) = match kind {
            VoiceMenuKind::Input | VoiceMenuKind::Output => (Align2::LEFT_BOTTOM, pos2(menu.anchor.left(), menu.anchor.top() - 4.0)),
            VoiceMenuKind::CallMic => (Align2::CENTER_BOTTOM, pos2(menu.anchor.center().x, menu.anchor.top() - 8.0)),
            VoiceMenuKind::CallMore => (Align2::RIGHT_BOTTOM, pos2(menu.anchor.right(), menu.anchor.top() - 8.0)),
            VoiceMenuKind::User(_) | VoiceMenuKind::Stream(_) => (Align2::LEFT_TOP, menu.anchor.min),
            VoiceMenuKind::Notify(_) => (Align2::RIGHT_TOP, pos2(menu.anchor.right(), menu.anchor.bottom() + 8.0)),
        };
        let notify_state = match kind {
            VoiceMenuKind::Notify(ch) => Some((ch, self.store.muted_channels.contains(&ch), self.store.channel_notify.get(&ch).copied().unwrap_or(3))),
            _ => None,
        };
        let mut acts: Vec<Act> = Vec::new();
        let mut new_sub: Option<(Sub, f32)> = None;
        let mut clear_sub = false;
        let open_sub = menu.sub.map(|(s, _)| s);
        // One area per kind of menu, each placed by its own size: sharing one,
        // a menu would open placed by the size of the last kind shown.
        let area = egui::Area::new(egui::Id::new(("voice_menu", std::mem::discriminant(&kind))))
            // Above the full-screen stream too.
            .order(if matches!(kind, VoiceMenuKind::Stream(_)) { Order::Tooltip } else { Order::Foreground })
            .pivot(pivot)
            .fixed_pos(pos)
            .constrain(true)
            .sized_off_screen(ctx)
            .show(ctx, |ui| {
                menu_frame(&t).show(ui, |ui| {
                    // Discord's "More Options" is a little wider (its labels are long).
                    let width = if kind == VoiceMenuKind::CallMore { 256.0 } else { MENU_W };
                    ui.set_width(width - 2.0 * PAD);
                    ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                    let mut sub = |ui: &mut Ui, which: Sub, label: &str, subtitle: &str| {
                        let r = sub_row(ui, &t, label, subtitle, open_sub == Some(which));
                        if r.hovered() || r.clicked() {
                            new_sub = Some((which, r.rect.top()));
                        }
                    };
                    let profile = if iso { "Voice Isolation" } else { "Studio" };
                    match kind {
                        VoiceMenuKind::Input | VoiceMenuKind::CallMic => {
                            sub(ui, Sub::InputDevice, "Input Device", &in_sub);
                            sub(ui, Sub::InputProfile, "Input Profile", profile);
                            if kind == VoiceMenuKind::CallMic {
                                sub(ui, Sub::OutputDevice, "Output Device", &out_sub);
                            }
                        }
                        VoiceMenuKind::Output => sub(ui, Sub::OutputDevice, "Output Device", &out_sub),
                        VoiceMenuKind::Notify(_) => {
                            if let Some((ch, muted, _)) = notify_state {
                                if muted {
                                    let r = item_row(ui, &t, None, "Unmute Channel", false);
                                    if r.hovered() {
                                        clear_sub = true;
                                    }
                                    if r.clicked() {
                                        acts.push(Act::MuteChannel(ch, None));
                                    }
                                } else {
                                    sub(ui, Sub::MuteFor, "Mute Channel", "Stop notifications and unreads");
                                }
                            }
                        }
                        _ => {}
                    }
                    match kind {
                        VoiceMenuKind::Input | VoiceMenuKind::Output | VoiceMenuKind::CallMic => {
                            separator(ui, &t);
                            let top = ui.cursor().top();
                            if kind != VoiceMenuKind::Output {
                                let (changed, done) = slider_row(ui, &t, egui::Id::new("vm_in_vol"), "Input Volume", &mut in_vol, 100.0);
                                if changed || done {
                                    acts.push(Act::InputVolume(in_vol, done));
                                }
                                if in_call {
                                    level_row(ui, &t, level, sens);
                                }
                                // Same scale as the meter above: -70 dB at the left, 0 at the right.
                                let mut v = sens + 70.0;
                                let (changed, done) =
                                    slider_row_fmt(ui, &t, egui::Id::new("vm_in_sens"), "Input Sensitivity", &mut v, 70.0, |v| format!("{:.0} dB", v - 70.0));
                                if changed || done {
                                    acts.push(Act::Sensitivity(v - 70.0, done));
                                }
                            }
                            if kind != VoiceMenuKind::Input {
                                let (changed, done) = slider_row(ui, &t, egui::Id::new("vm_out_vol"), "Output Volume", &mut out_vol, 200.0);
                                if changed || done {
                                    acts.push(Act::OutputVolume(out_vol, done));
                                }
                            }
                            let sliders = Rect::from_min_max(pos2(ui.max_rect().left(), top), pos2(ui.max_rect().right(), ui.cursor().top()));
                            if ui.rect_contains_pointer(sliders) {
                                clear_sub = true;
                            }
                            separator(ui, &t);
                            if kind == VoiceMenuKind::CallMic {
                                let r = check_row(ui, &t, "Deafen", deaf);
                                if r.hovered() {
                                    clear_sub = true;
                                }
                                if r.clicked() {
                                    acts.push(Act::ToggleDeafen);
                                }
                            }
                            if kind != VoiceMenuKind::Output {
                                let r = check_row(ui, &t, "Listen to Microphone", listen)
                                    .on_hover_text("Hear your own microphone while you're in a call.");
                                if r.hovered() {
                                    clear_sub = true;
                                }
                                if r.clicked() {
                                    acts.push(Act::ListenToMic);
                                }
                            }
                            let r = item_row(ui, &t, Some(icon::SETTINGS), "Voice Settings", false);
                            if r.hovered() {
                                    clear_sub = true;
                                }
                            if r.clicked() {
                                acts.push(Act::Settings);
                            }
                        }
                        VoiceMenuKind::CallMore => {
                            if can_invite {
                                if item_row(ui, &t, Some(ADD_PERSON), "Invite to Voice", false).clicked() {
                                    acts.push(Act::Invite);
                                }
                                separator(ui, &t);
                            }
                            if check_row(ui, &t, "Show Non-Video Participants", show_non_video).clicked() {
                                acts.push(Act::ShowNonVideo);
                            }
                            separator(ui, &t);
                            if item_row(ui, &t, Some(icon::SETTINGS), "Voice & Video Settings", false).clicked() {
                                acts.push(Act::Settings);
                            }
                        }
                        VoiceMenuKind::Stream(streamer) => {
                            let mut v = stream_volume.unwrap_or(100.0);
                            let (changed, done) = slider_row(ui, &t, egui::Id::new(("vm_stream_vol", streamer.0)), "Stream Volume", &mut v, 200.0);
                            if changed || done {
                                acts.push(Act::StreamVolume(streamer, v, done));
                            }
                            separator(ui, &t);
                            if item_row(ui, &t, None, if fullscreen { "Exit Full Screen" } else { "Full Screen" }, false).clicked() {
                                acts.push(Act::StreamFullscreen(streamer));
                            }
                            if item_row(ui, &t, None, "Stop Watching", true).clicked() {
                                acts.push(Act::StopWatching(streamer));
                            }
                        }
                        VoiceMenuKind::Notify(_) => {
                            let Some((ch, _, level)) = notify_state else { return };
                            separator(ui, &t);
                            for (n, label) in [(3u8, "Use Category Default"), (0, "All Messages"), (1, "Only @mentions"), (2, "Nothing")] {
                                let r = radio_row(ui, &t, label, level == n);
                                if r.hovered() {
                                    clear_sub = true;
                                }
                                if r.clicked() && level != n {
                                    acts.push(Act::ChannelNotify(ch, n));
                                }
                            }
                        }
                        VoiceMenuKind::User(_) => {
                            let Some((uid, is_me, vol, local_mute, flags)) = user_ctx else { return };
                            if item_row(ui, &t, None, "Profile", false).clicked() {
                                acts.push(Act::Profile(uid));
                            }
                            if item_row(ui, &t, None, "Mention", false).clicked() {
                                acts.push(Act::Mention(uid));
                            }
                            if !is_me && item_row(ui, &t, None, "Message", false).clicked() {
                                acts.push(Act::Message(uid));
                            }
                            if !is_me {
                                if flags.streaming {
                                    let watching_them = self.watching.iter().any(|w| w.streamer == uid);
                                    let label = if watching_them { "Stop Watching" } else { "Watch Stream" };
                                    if item_row(ui, &t, Some(crate::golive::SCREEN), label, false).clicked() {
                                        acts.push(if watching_them { Act::StopWatching(uid) } else { Act::WatchStream(uid) });
                                    }
                                }
                                separator(ui, &t);
                                let mut v = vol;
                                let (changed, done) = slider_row(ui, &t, egui::Id::new(("vm_user_vol", uid.0)), "User Volume", &mut v, 200.0);
                                if changed || done {
                                    acts.push(Act::UserVolume(uid, v, done));
                                }
                                if let Some(mut v) = stream_volume {
                                    let (changed, done) = slider_row(ui, &t, egui::Id::new(("vm_stream_vol", uid.0)), "Stream Volume", &mut v, 200.0);
                                    if changed || done {
                                        acts.push(Act::StreamVolume(uid, v, done));
                                    }
                                }
                                if check_row(ui, &t, "Mute", local_mute).clicked() {
                                    acts.push(Act::LocalMute(uid));
                                }
                            } else {
                                separator(ui, &t);
                                if check_row(ui, &t, "Deafen", deaf).clicked() {
                                    acts.push(Act::ToggleDeafen);
                                }
                            }
                            let (can_mute, can_deafen, can_move) = mod_perms;
                            if can_mute || can_deafen || can_move || is_me {
                                separator(ui, &t);
                            }
                            if can_mute && check_row(ui, &t, "Server Mute", flags.server_mute).clicked() {
                                acts.push(Act::ServerMute(uid, !flags.server_mute));
                            }
                            if can_deafen && check_row(ui, &t, "Server Deafen", flags.server_deaf).clicked() {
                                acts.push(Act::ServerDeaf(uid, !flags.server_deaf));
                            }
                            if (can_move || is_me) && item_row(ui, &t, None, "Disconnect", true).clicked() {
                                acts.push(Act::Disconnect(uid));
                            }
                            separator(ui, &t);
                            if item_row(ui, &t, Some(icon::ID), "Copy User ID", false).clicked() {
                                acts.push(Act::CopyId(uid));
                            }
                        }
                    }
                });
            });
        let main_rect = area.response.rect;

        // The submenu, to the right of its row (left if there's no room).
        let mut sub_state = menu.sub;
        if let Some(s) = new_sub {
            sub_state = Some(s);
        } else if clear_sub {
            sub_state = None;
        }
        let mut sub_rect = None;
        if let Some((which, row_top)) = sub_state {
            let screen = ctx.screen_rect();
            let right = main_rect.right() - 5.0 + 300.0 <= screen.right();
            let (pivot, at) = if right { (Align2::LEFT_TOP, pos2(main_rect.right() - 5.0, row_top - PAD - 1.0)) } else { (Align2::RIGHT_TOP, pos2(main_rect.left() + 5.0, row_top - PAD - 1.0)) };
            let choices = match which {
                Sub::InputDevice => Some(self.voice_ui.device_choices(true)),
                Sub::OutputDevice => Some(self.voice_ui.device_choices(false)),
                Sub::InputProfile | Sub::MuteFor => None,
            };
            let loading = self.voice_ui.devices.is_none();
            // Wide enough for the longest device name (Discord's grows too).
            let widest = choices.iter().flatten().map(|c| ctx.fonts(|f| f.layout_no_wrap(c.label.clone(), label_font(), Color32::WHITE).size().x)).fold(0.0_f32, f32::max);
            let sub_w = (widest + 8.0 + 34.0 + 2.0 * PAD + 4.0).clamp(SUB_W, 420.0);
            let sub_area = egui::Area::new(egui::Id::new("voice_submenu")).order(Order::Tooltip).pivot(pivot).fixed_pos(at).constrain(true).show(ctx, |ui| {
                menu_frame(&t).show(ui, |ui| {
                    ui.set_width(sub_w - 2.0 * PAD);
                    ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                    match &choices {
                        Some(list) => {
                            for c in list {
                                let label = if c.id.is_none() { "Default" } else { c.label.as_str() };
                                if radio_row(ui, &t, label, c.selected).clicked() {
                                    acts.push(Act::PickDevice { input: which == Sub::InputDevice, id: c.id.clone(), name: c.name.clone() });
                                }
                            }
                            if loading {
                                ui.label(egui::RichText::new("  Looking for devices…").size(13.0).color(t.text_muted));
                            }
                        }
                        None if which == Sub::MuteFor => {
                            let ch = notify_state.map(|(c, _, _)| c);
                            for (secs, label) in [(900i64, "For 15 Minutes"), (3600, "For 1 Hour"), (10800, "For 3 Hours"), (28800, "For 8 Hours"), (86400, "For 24 Hours"), (-1, "Until I turn it back on")] {
                                if item_row(ui, &t, None, label, false).clicked() {
                                    if let Some(ch) = ch {
                                        acts.push(Act::MuteChannel(ch, Some(secs)));
                                    }
                                }
                            }
                        }
                        None => {
                            for (on, title) in [(true, "Voice Isolation"), (false, "Studio")] {
                                let r = radio_row(ui, &t, title, iso == on);
                                let r = r.on_hover_text(if on { "Cuts background noise (RNNoise)." } else { "No processing: your microphone as it is." });
                                if r.clicked() {
                                    acts.push(Act::Isolation(on));
                                }
                            }
                        }
                    }
                });
            });
            sub_rect = Some(sub_area.response.rect);
        }

        // Click elsewhere (not on the button that opened it) or Escape closes it.
        let inside = |p: egui::Pos2| main_rect.contains(p) || sub_rect.is_some_and(|r| r.contains(p)) || menu.anchor.contains(p);
        let outside = frame > menu.opened && ctx.input(|i| (i.pointer.any_pressed()) && i.pointer.interact_pos().is_some_and(|p| !inside(p)));
        let mut close = outside || ctx.input(|i| i.key_pressed(egui::Key::Escape));
        if let Some(m) = self.voice_ui.menu.as_mut() {
            m.sub = sub_state;
        }

        for act in acts {
            match act {
                Act::PickDevice { input, id, name } => {
                    self.voice_ui.choose_device(input, id, name);
                    close = true;
                }
                Act::Isolation(on) => {
                    self.voice_ui.set_voice_isolation(on);
                    close = true;
                }
                Act::InputVolume(v, done) => {
                    self.voice_ui.prefs.input_volume = v;
                    if done {
                        self.voice_ui.changed();
                    } else {
                        self.voice_ui.apply();
                    }
                }
                Act::OutputVolume(v, done) => {
                    self.voice_ui.prefs.output_volume = v;
                    if done {
                        self.voice_ui.changed();
                    } else {
                        self.voice_ui.apply();
                    }
                }
                Act::Sensitivity(db, done) => {
                    self.voice_ui.prefs.input_sensitivity = db;
                    if done {
                        self.voice_ui.changed();
                    } else {
                        self.voice_ui.apply();
                    }
                }
                Act::ToggleDeafen => self.toggle_self_deaf(),
                Act::ListenToMic => {
                    self.voice_ui.prefs.listen_to_mic = !self.voice_ui.prefs.listen_to_mic;
                    self.voice_ui.changed();
                }
                Act::Settings => {
                    self.settings_tab = SettingsTab::VoiceVideo;
                    self.settings_open = true;
                    close = true;
                }
                Act::Invite => {
                    if let Some(c) = call_channel {
                        self.open_invite(c);
                    }
                    close = true;
                }
                Act::ShowNonVideo => {
                    self.voice_ui.prefs.show_non_video = !self.voice_ui.prefs.show_non_video;
                    self.voice_ui.changed();
                }
                Act::UserVolume(uid, v, done) => self.set_user_volume(uid, v, done),
                Act::StreamVolume(uid, v, done) => self.set_watch_volume(uid, v / 100.0, done),
                Act::StreamFullscreen(uid) => {
                    self.toggle_watch_fullscreen(uid);
                    close = true;
                }
                Act::WatchStream(uid) => {
                    if let Some((_, ch)) = self.voice_place_of(uid) {
                        self.watch_from_list(uid, ch);
                    }
                    close = true;
                }
                Act::StopWatching(uid) => {
                    self.stop_watch(uid);
                    close = true;
                }
                Act::LocalMute(uid) => self.toggle_local_mute(uid),
                Act::Profile(uid) => {
                    let gid = self.voice_place_of(uid).and_then(|(g, _)| g);
                    let user = if Some(uid) == me { self.store.me.clone() } else { self.store.users.get(&uid).cloned() };
                    if let Some(u) = user {
                        self.open_profile(u, gid, menu.anchor.min);
                    }
                    close = true;
                }
                Act::Mention(uid) => {
                    // Into the chat you're looking at (the call's own chat in the call view).
                    if let Some(ch) = self.current_channel {
                        let draft = self.drafts.entry(ch).or_default();
                        if !draft.is_empty() && !draft.ends_with(' ') {
                            draft.push(' ');
                        }
                        draft.push_str(&format!("<@{uid}> "));
                        self.compose.focus_composer = true;
                    }
                    close = true;
                }
                Act::Message(uid) => {
                    self.open_dm_with(uid, String::new());
                    close = true;
                }
                Act::ServerMute(uid, on) => {
                    if let Some(g) = self.voice_place_of(uid).and_then(|(g, _)| g) {
                        self.api("voice-mod", reqwest::Method::PATCH, format!("/guilds/{g}/members/{uid}"), Some(serde_json::json!({ "mute": on })));
                    }
                }
                Act::ServerDeaf(uid, on) => {
                    if let Some(g) = self.voice_place_of(uid).and_then(|(g, _)| g) {
                        self.api("voice-mod", reqwest::Method::PATCH, format!("/guilds/{g}/members/{uid}"), Some(serde_json::json!({ "deaf": on })));
                    }
                }
                Act::Disconnect(uid) => {
                    if Some(uid) == me {
                        self.leave_voice();
                    } else if let Some(g) = self.voice_place_of(uid).and_then(|(g, _)| g) {
                        self.api("voice-mod", reqwest::Method::PATCH, format!("/guilds/{g}/members/{uid}"), Some(serde_json::json!({ "channel_id": null })));
                    }
                    close = true;
                }
                Act::CopyId(uid) => {
                    ctx.copy_text(uid.to_string());
                    close = true;
                }
                Act::MuteChannel(ch, until) => {
                    self.mute_channel(ch, until);
                    close = true;
                }
                Act::ChannelNotify(ch, n) => {
                    self.set_channel_notify(ch, n);
                    close = true;
                }
            }
        }
        if close {
            self.voice_ui.menu = None;
        }
    }
}

/// Fill for a muted / deafened control (Discord's red tint), and its hover.
pub fn muted_fill(hovered: bool) -> Color32 {
    if hovered {
        rgba(218, 62, 68, 56)
    } else {
        rgba(218, 62, 68, 31)
    }
}

/// Which way a control's chevron points: up while its menu is open.
pub fn chevron(open: bool) -> &'static str {
    if open {
        CHEVRON_UP
    } else {
        icon::CHEVRON_DOWN
    }
}

/// Rounded left / right halves of a split button.
pub fn left_half(r: f32) -> Rounding {
    Rounding { nw: r, sw: r, ne: 0.0, se: 0.0 }
}

pub fn right_half(r: f32) -> Rounding {
    Rounding { nw: 0.0, sw: 0.0, ne: r, se: r }
}