Skip to content

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

62.2 KB
Raw Blame
//! The call view: what the main area shows for a voice channel. In the call,
//! a grid of participant tiles (avatar on the person's profile colour or
//! banner, a green ring while they talk) over a control bar; otherwise who's
//! there and a Join button. Discord's layout, with calmer colours, rounder
//! tiles and no Activities.

use super::{paint_avatar, paint_cover, paint_text_emoji, HEADER};
use crate::app::RustCord;
use crate::style::{icon, icon_font, overlay, rgba, Theme};
use crate::voice_call::{HANG_UP, VOICE_GREEN};
use discord::model::{permissions, Id, User};
use eframe::egui::{self, pos2, vec2, Align2, Color32, CursorIcon, FontId, Order, Rect, Rounding, Sense, Stroke, Ui, Vec2};

const MIC_OFF: &str = "\u{F781}";
const SPEAKER_OFF: &str = "\u{E74F}";
const ADD_PERSON: &str = "\u{E8FA}";
/// Tiles never get wider than this (one person shouldn't fill a 4K screen).
const MAX_TILE_W: f32 = 880.0;
/// Below this the grid scrolls instead of shrinking further.
const MIN_TILE_W: f32 = 200.0;
const TILE_GAP: f32 = 12.0;
/// Tile colours for people without a profile colour: deep, calm tones that
/// keep white text readable (picked by user ID, so they stay put).
const TILE_COLORS: [u32; 8] = [0x3d4f9f, 0x2e7470, 0x6d3f86, 0x8a5130, 0x2f6497, 0x5d6e2e, 0x96405f, 0x4b5470];

/// One person in the call, as a tile shows them.
struct Tile {
    id: Id,
    user: Option<User>,
    name: String,
    color: Color32,
    banner: Option<String>,
    muted: bool,
    deafened: bool,
    /// Muted / deafened by a moderator.
    server: bool,
    speaking: bool,
    /// Live (Go Live): a LIVE badge, and others' tiles offer "Watch Stream".
    streaming: bool,
    /// Discord's preview thumbnail URL for a live stream.
    stream_preview: Option<String>,
    /// Your own screen on your tile while you're live.
    preview: Option<egui::TextureHandle>,
    /// This is you.
    me: bool,
    /// Being rung (DM calls): Discord's dimmed tile with a pulsing outline.
    ringing: bool,
}

fn rgb(c: u32) -> Color32 {
    Color32::from_rgb((c >> 16) as u8, (c >> 8) as u8, c as u8)
}

/// "12:34" or "1:02:03".
fn elapsed(d: std::time::Duration) -> String {
    let s = d.as_secs();
    if s >= 3600 {
        format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
    } else {
        format!("{}:{:02}", s / 60, s % 60)
    }
}

/// Columns and tile size that make `n` 16:9 tiles as big as possible in `area`.
fn tile_grid(n: usize, area: Vec2, gap: f32) -> (usize, Vec2) {
    let mut best = (1, Vec2::ZERO);
    for cols in 1..=n.max(1) {
        let rows = n.max(1).div_ceil(cols);
        let w = (area.x - gap * (cols - 1) as f32) / cols as f32;
        let h = (area.y - gap * (rows - 1) as f32) / rows as f32;
        if w <= 0.0 || h <= 0.0 {
            continue;
        }
        let size = if w / h > 16.0 / 9.0 { vec2(h * 16.0 / 9.0, h) } else { vec2(w, w * 9.0 / 16.0) };
        if size.x > best.1.x {
            best = (cols, size);
        }
    }
    let scale = (MAX_TILE_W / best.1.x.max(1.0)).min(1.0);
    (best.0, best.1 * scale)
}

/// A rounded rectangle with a vertical gradient: a fan mesh over the rounded
/// outline (the tile's 1px edge stroke smooths the mesh's unfeathered rim).
fn gradient_rrect(p: &egui::Painter, rect: Rect, r: f32, top: Color32, bottom: Color32) {
    let r = r.min(rect.width() / 2.0).min(rect.height() / 2.0);
    let at = |y: f32| top.lerp_to_gamma(bottom, ((y - rect.top()) / rect.height().max(1.0)).clamp(0.0, 1.0));
    let mut mesh = egui::Mesh::default();
    mesh.colored_vertex(rect.center(), at(rect.center().y));
    // Corners clockwise from bottom-right (screen y points down).
    let corners = [
        (pos2(rect.right() - r, rect.bottom() - r), 0.0_f32),
        (pos2(rect.left() + r, rect.bottom() - r), 90.0),
        (pos2(rect.left() + r, rect.top() + r), 180.0),
        (pos2(rect.right() - r, rect.top() + r), 270.0),
    ];
    const STEPS: usize = 8;
    for (c, start) in corners {
        for i in 0..=STEPS {
            let a = (start + 90.0 * i as f32 / STEPS as f32).to_radians();
            let pt = pos2(c.x + r * a.cos(), c.y + r * a.sin());
            mesh.colored_vertex(pt, at(pt.y));
        }
    }
    let n = mesh.vertices.len() as u32;
    for i in 1..n - 1 {
        mesh.add_triangle(0, i, i + 1);
    }
    mesh.add_triangle(0, n - 1, 1);
    p.add(egui::Shape::mesh(mesh));
}

/// A rounded button face: fill, hover state and an icon. Returns the response.
fn round_button(ui: &mut Ui, rect: Rect, id: egui::Id, fill: Color32, hover: Color32, glyph: &str, size: f32, color: Color32, tip: &str) -> egui::Response {
    let resp = ui.interact(rect, id, Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
    ui.painter().rect_filled(rect, 12.0, if resp.hovered() { hover } else { fill });
    ui.painter().text(rect.center(), Align2::CENTER_CENTER, glyph, icon_font(size), color);
    resp.on_hover_text(tip)
}

impl RustCord {
    /// A server voice channel is selected: the main area shows its call view.
    pub fn showing_call_view(&self) -> bool {
        self.current_guild.is_some() && self.current_channel.and_then(|c| self.store.channels.get(&c)).is_some_and(|c| discord::model::channel_kind::is_voice(c.kind))
    }

    /// The main area for a voice channel (see the module docs).
    pub fn call_view_ui(&mut self, ui: &mut Ui) {
        let t = self.theme.clone();
        let Some(channel) = self.current_channel else { return };
        let full = ui.max_rect();
        ui.painter().rect_filled(full, 0.0, t.bg_tertiary);
        let gid = self.store.channels.get(&channel).and_then(|c| c.guild_id);
        let name = self.store.channels.get(&channel).and_then(|c| c.name.clone()).unwrap_or_default();
        let in_call = self.voice.as_ref().is_some_and(|v| v.channel == channel);
        let can_invite = gid.is_some_and(|g| self.store.has_perm(g, permissions::CREATE_INSTANT_INVITE));
        let mut invite = false;

        // Header: channel, call timer (or the stream you watch: who, what
        // they're doing, viewers, quality), voice chat, invite.
        let header = Rect::from_min_size(full.min, vec2(full.width(), HEADER));
        let cy = header.center().y;
        let p = ui.painter_at(header);
        p.text(pos2(header.left() + 24.0, cy), Align2::CENTER_CENTER, icon::SPEAK, icon_font(18.0), t.interactive_normal);
        let bold = |size: f32| FontId::new(size, egui::FontFamily::Name(crate::style::BOLD.into()));
        let title = paint_text_emoji(ui, &p, pos2(header.left() + 42.0, cy), &name, bold(16.0), t.header_primary);
        let watching = self.focused_watch().filter(|w| w.channel == channel).map(|w| (w.streamer, w.viewers.clone()));
        let mut right = header.right() - 12.0;
        let mut header_button = |ui: &mut Ui, id: &str, glyph: &str, on: bool, tip: &str| -> bool {
            let b = Rect::from_center_size(pos2(right - 17.0, cy), vec2(34.0, 34.0));
            right -= 40.0;
            let r = ui.interact(b, egui::Id::new(id), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            if r.hovered() || on {
                ui.painter().rect_filled(b, 8.0, t.bg_hover);
            }
            ui.painter().text(b.center(), Align2::CENTER_CENTER, glyph, icon_font(18.0), if r.hovered() || on { t.header_primary } else { t.interactive_normal });
            r.on_hover_text(tip).clicked()
        };
        if can_invite {
            invite |= header_button(ui, "call_header_invite", ADD_PERSON, false, "Invite to Voice");
        }
        let chat_on = self.golive_ui.chat_open;
        if header_button(ui, "call_header_chat", crate::style::icon::MESSAGE, chat_on, if chat_on { "Hide Chat" } else { "Show Chat" }) {
            self.golive_ui.chat_open = !chat_on;
        }
        if let Some((streamer, viewers)) = &watching {
            self.paint_watching_header(ui, &p, &t, channel, gid, *streamer, viewers, title.right(), right, cy, true);
        } else if in_call {
            let (text, color) = match self.voice.as_ref().and_then(|v| v.connected_at) {
                Some(at) => (elapsed(at.elapsed()), VOICE_GREEN),
                None => (
                    match self.voice.as_ref().map(|v| v.phase) {
                        Some("securing") => "Securing…".to_string(),
                        Some("discovering") => "Connecting (network)…".to_string(),
                        _ => "Connecting…".to_string(),
                    },
                    t.text_muted,
                ),
            };
            p.circle_filled(pos2(title.right() + 12.0, cy), 2.0, t.text_muted);
            p.text(pos2(title.right() + 22.0, cy), Align2::LEFT_CENTER, text, FontId::proportional(13.0), color);
        }
        ui.painter().hline(header.x_range(), header.bottom() - 0.5, Stroke::new(1.0_f32, t.border_subtle));

        let bar_h: f32 = if in_call { 88.0 } else { 0.0 };
        // The voice channel's text chat, on the right.
        let chat_w = if self.golive_ui.chat_open { (full.width() * 0.34).clamp(300.0, 420.0) } else { 0.0 };
        let main_right = full.right() - chat_w;
        let body = Rect::from_min_max(pos2(full.left() + 16.0, header.bottom() + 16.0), pos2(main_right - 16.0, full.bottom() - bar_h.max(16.0)));
        if in_call {
            let tiles_area = if watching.is_some() { self.watching_stage(ui, &t, body) } else { body };
            invite |= self.call_tiles(ui, &t, tiles_area, channel, gid, can_invite && watching.is_none());
            self.call_controls(ui, &t, Rect::from_min_max(pos2(full.left(), full.bottom() - bar_h), pos2(main_right, full.bottom())), can_invite);
        } else {
            self.call_lobby(ui, &t, body, channel, &name);
        }
        if chat_w > 0.0 {
            let panel = Rect::from_min_max(pos2(main_right, header.bottom()), full.max);
            ui.painter().vline(panel.left(), panel.y_range(), Stroke::new(1.0_f32, t.border_subtle));
            let mut child = ui.new_child(egui::UiBuilder::new().max_rect(panel).layout(egui::Layout::top_down(egui::Align::Min)));
            if self.voice_chat_panel(&mut child, channel) {
                self.golive_ui.chat_open = false;
            }
        }
        if invite {
            self.open_invite(channel);
        }
    }

    /// Streamer name, activity, viewer faces, quality badge and LIVE pill for a watched stream.
    #[allow(clippy::too_many_arguments)]
    fn paint_watching_header(&self, ui: &mut Ui, p: &egui::Painter, t: &Theme, channel: Id, gid: Option<Id>, streamer: Id, viewers: &[Id], left_start: f32, right_start: f32, cy: f32, show_chevron: bool) {
        let bold = |size: f32| FontId::new(size, egui::FontFamily::Name(crate::style::BOLD.into()));
        let mut right = right_start;
        let stats = self.watching_stats();
        // LIVE, then the quality ("1440p 60FPS").
        let pg = p.layout_no_wrap("LIVE".into(), bold(11.0), Color32::WHITE);
        let live = Rect::from_min_max(pos2(right - pg.size().x - 12.0, cy - 10.0), pos2(right - 2.0, cy + 10.0));
        p.rect_filled(live, Rounding { nw: 0.0, sw: 0.0, ne: 6.0, se: 6.0 }, crate::golive::LIVE_RED);
        p.galley(live.center() - pg.size() / 2.0, pg, Color32::WHITE);
        right = live.left();
        if let Some(q) = crate::app::RustCord::quality_label(&stats) {
            let qg = p.layout_no_wrap(format!("{}  {q}", crate::golive::SCREEN), icon_font(12.0), Color32::WHITE);
            let badge = Rect::from_min_max(pos2(right - qg.size().x - 14.0, cy - 10.0), pos2(right, cy + 10.0));
            p.rect_filled(badge, Rounding { nw: 6.0, sw: 6.0, ne: 0.0, se: 0.0 }, Color32::from_black_alpha(170));
            p.galley(pos2(badge.left() + 7.0, cy - qg.size().y / 2.0), qg, Color32::WHITE);
            let tip = if crate::golive::quality_tier(stats.width, stats.height) > 720 || crate::golive::quality_fps(stats.fps) > 30 { "Nitro streaming quality" } else { "Streaming quality" };
            ui.interact(badge, egui::Id::new("call_quality_badge"), Sense::hover()).on_hover_text(tip);
            right = badge.left();
        }
        // Viewers: up to four faces, then "+N".
        if !viewers.is_empty() {
            right -= 10.0;
            let extra = viewers.len().saturating_sub(4);
            if extra > 0 {
                let g = p.layout_no_wrap(format!("+{extra}"), bold(12.0), t.header_primary);
                let r = Rect::from_center_size(pos2(right - 13.0, cy), vec2(26.0, 22.0));
                p.rect_filled(r, 11.0, overlay(0.2));
                p.galley(r.center() - g.size() / 2.0, g, t.header_primary);
                right = r.left() + 6.0;
            }
            let names: Vec<String> = viewers.iter().filter_map(|v| self.store.users.get(v).map(|u| u.display_name().to_string())).collect();
            let first = right;
            for v in viewers.iter().take(4).rev() {
                let user = self.store.users.get(v);
                let av = Rect::from_center_size(pos2(right - 11.0, cy), vec2(22.0, 22.0));
                p.circle_filled(av.center(), 12.5, t.bg_tertiary);
                paint_avatar(ui, av, user.map(|u| u.avatar_or_default(48)), user.map_or("?", |u| u.display_name()));
                right -= 16.0;
            }
            let spectators = Rect::from_min_max(pos2(right, cy - 12.0), pos2(first, cy + 12.0));
            ui.interact(spectators, egui::Id::new("call_spectators"), Sense::hover()).on_hover_text(format!("Watching: {}", names.join(", ")));
        }
        let mut x = left_start;
        if show_chevron {
            p.text(pos2(x + 12.0, cy), Align2::CENTER_CENTER, crate::style::icon::CHEVRON, icon_font(10.0), t.text_muted);
            x += 24.0;
        }
        let left_clip = ui.painter_at(Rect::from_min_max(pos2(x, cy - 16.0), pos2((right - 8.0).max(x), cy + 16.0)));
        let user = self.store.users.get(&streamer).cloned();
        let av = Rect::from_center_size(pos2(x + 11.0, cy), vec2(22.0, 22.0));
        paint_avatar(ui, av, user.as_ref().map(|u| u.avatar_or_default(48)), user.as_ref().map_or("?", |u| u.display_name()));
        x = av.right() + 8.0;
        let nick = self.store.nick_in(gid, Some(channel), streamer);
        let shown = nick.or_else(|| user.as_ref().map(|u| u.display_name().to_string())).unwrap_or_default();
        let handle = user.as_ref().map(|u| format!(" (@{})", u.username)).unwrap_or_default();
        let r = paint_text_emoji(ui, &left_clip, pos2(x, cy), &format!("{shown}{handle}"), bold(14.5), t.header_primary);
        x = r.right();
        if let Some((verb, what, _, _)) = self.stream_activity(streamer) {
            left_clip.text(pos2(x + 6.0, cy), Align2::LEFT_CENTER, format!("{verb} {what}"), FontId::proportional(14.0), t.text_muted);
        }
    }

    /// Everyone in `channel` (you first when you're in it, even before the gateway confirms).
    fn call_tile_data(&self, channel: Id, gid: Option<Id>) -> Vec<Tile> {
        let me = self.store.me_id();
        let in_call = self.voice.as_ref().is_some_and(|v| v.channel == channel);
        let mut ids = self.store.voice.get(&channel).cloned().unwrap_or_default();
        if let Some(me) = me {
            if in_call {
                ids.retain(|u| *u != me);
                ids.insert(0, me);
            }
        }
        // A DM call's people being rung have a tile too, as in Discord (and
        // people who are neither there nor rung have none).
        let ringing: Vec<Id> = match gid {
            None => self.calls.get(&channel).map(|c| c.ringing.iter().filter(|u| !ids.contains(u)).copied().collect()).unwrap_or_default(),
            Some(_) => Vec::new(),
        };
        ids.into_iter()
            .map(|id| (id, false))
            .chain(ringing.into_iter().map(|id| (id, true)))
            .map(|(id, ringing)| {
                let user = if Some(id) == me { self.store.me.clone() } else { self.store.users.get(&id).cloned() };
                let nick = self.store.nick_in(gid, Some(channel), id);
                let name = nick.or_else(|| user.as_ref().map(|u| u.display_name().to_string())).unwrap_or_else(|| "Loading…".into());
                let profile = self.profiles.get(&(id, gid)).or_else(|| self.profiles.get(&(id, None))).and_then(|r| r.as_ref().ok());
                let color = profile
                    .and_then(|p| p.theme_colors().map(|(a, _)| a).or_else(|| p.accent_color()))
                    .or_else(|| user.as_ref().and_then(|u| u.accent_color))
                    .map(rgb)
                    .unwrap_or_else(|| rgb(TILE_COLORS[(id.0 >> 22) as usize % TILE_COLORS.len()]));
                // Animated banners stay still here: a call can run for hours.
                let banner = profile.and_then(|p| p.banner_url()).map(|u| u.replace(".gif", ".png"));
                let flags = self.store.voice_flags.get(&id).copied().unwrap_or_default();
                let (muted, deafened) = if Some(id) == me { (self.self_mute || self.self_deaf, self.self_deaf) } else { (flags.muted, flags.deafened) };
                let me_tile = Some(id) == me;
                let streaming = !ringing && if me_tile { self.go_live.as_ref().is_some_and(|g| g.channel == channel) } else { flags.streaming };
                let speaking = !ringing && self.is_speaking(id);
                Tile { id, user, name, color, banner, muted, deafened, server: flags.server_muted, speaking, streaming, stream_preview: None, preview: None, me: me_tile, ringing }
            })
            .collect()
    }

    /// The participant grid. Returns true if "Invite to Voice" was clicked.
    fn call_tiles(&mut self, ui: &mut Ui, t: &Theme, area: Rect, channel: Id, gid: Option<Id>, can_invite: bool) -> bool {
        let mut tiles = self.call_tile_data(channel, gid);
        let ctx = ui.ctx().clone();
        // Your tile shows your stream, else your camera.
        let own = self.own_stream_texture(&ctx).or_else(|| self.camera_texture(&ctx));
        // The streams you watch play in their tiles, but for the one on the stage.
        let on_stage = (!self.golive_ui.stream_grid).then(|| self.focused_watch().map(|w| w.streamer)).flatten();
        let watched: Vec<(Id, Option<egui::TextureHandle>)> =
            self.watching.iter().filter(|w| w.channel == channel).map(|w| (w.streamer, w.frame.clone())).collect();
        let in_this_call = self.voice.as_ref().is_some_and(|v| v.channel == channel);
        for tile in tiles.iter_mut() {
            if tile.me {
                tile.preview = own.clone();
            } else if in_this_call {
                // Their camera.
                tile.preview = self.camera.remote_texture(&ctx, tile.id.0);
            }
            if let Some((_, frame)) = watched.iter().find(|(s, _)| *s == tile.id) {
                tile.streaming = false;
                if Some(tile.id) != on_stage && frame.is_some() {
                    tile.preview = frame.clone();
                }
            } else if tile.streaming && !tile.me && tile.preview.is_none() {
                let key = crate::golive::stream_key(gid, channel, tile.id);
                tile.stream_preview = self.stream_preview(&key);
            }
        }
        // "Show Non-Video Participants" off: only people sharing video.
        let hidden = if self.voice_ui.prefs.show_non_video { 0 } else { tiles.len() - tiles.iter().filter(|t| t.streaming || t.preview.is_some()).count() };
        if hidden > 0 {
            tiles.retain(|t| t.streaming || t.preview.is_some());
        }
        if tiles.is_empty() {
            let c = area.center();
            ui.painter().text(c - vec2(0.0, 22.0), Align2::CENTER_CENTER, "No one is sharing video", FontId::new(18.0, egui::FontFamily::Name(crate::style::BOLD.into())), t.header_primary);
            ui.painter().text(c + vec2(0.0, 4.0), Align2::CENTER_CENTER, format!("{hidden} non-video participant{} hidden", if hidden == 1 { "" } else { "s" }), FontId::proportional(14.0), t.text_muted);
            let b = Rect::from_center_size(c + vec2(0.0, 44.0), vec2(150.0, 36.0));
            let r = ui.interact(b, egui::Id::new("call_show_all"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            ui.painter().rect_filled(b, 8.0, if r.hovered() { overlay(0.24) } else { overlay(0.16) });
            ui.painter().text(b.center(), Align2::CENTER_CENTER, "Show Everyone", FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into())), t.header_primary);
            if r.clicked() {
                self.voice_ui.prefs.show_non_video = true;
                self.voice_ui.changed();
            }
            return false;
        }
        // Small calls: fetch profiles for their colours and banners.
        if tiles.len() <= 8 {
            self.profiles_wanted.borrow_mut().extend(tiles.iter().filter(|t| t.user.is_some()).map(|t| (t.id, gid)));
        }
        let alone = tiles.len() <= 1;
        // Room under a lone tile for "Invite to Voice".
        let below = if alone && can_invite { 64.0 } else { 0.0 };
        let grid = area.with_max_y(area.bottom() - below);
        let n = tiles.len().max(1);
        let (cols, size) = tile_grid(n, grid.size(), TILE_GAP);
        let mut clicked: Option<(usize, egui::Pos2)> = None;
        let mut menu: Option<(Id, egui::Pos2)> = None;
        let mut grid_bottom = area.bottom() - below;
        if size.x >= MIN_TILE_W {
            let rows = n.div_ceil(cols);
            let total_h = rows as f32 * size.y + (rows - 1) as f32 * TILE_GAP;
            let top = area.center().y - (total_h + below) / 2.0;
            grid_bottom = top + total_h;
            for (i, tile) in tiles.iter().enumerate() {
                let (row, col) = (i / cols, i % cols);
                let in_row = if row == rows - 1 { n - row * cols } else { cols };
                let row_w = in_row as f32 * size.x + (in_row - 1) as f32 * TILE_GAP;
                let min = pos2(grid.center().x - row_w / 2.0 + col as f32 * (size.x + TILE_GAP), top + row as f32 * (size.y + TILE_GAP));
                let resp = paint_tile(ui, t, Rect::from_min_size(min, size), tile);
                if resp.clicked() {
                    clicked = Some((i, resp.interact_pointer_pos().unwrap_or(min)));
                }
                if resp.secondary_clicked() {
                    menu = Some((tile.id, resp.interact_pointer_pos().unwrap_or(min)));
                }
            }
        } else {
            // Many people: fixed-size tiles that scroll.
            let size = vec2(MIN_TILE_W, MIN_TILE_W * 9.0 / 16.0);
            let cols = (((area.width() + TILE_GAP) / (size.x + TILE_GAP)).floor() as usize).max(1);
            let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area));
            egui::ScrollArea::vertical().id_salt("call_tiles").auto_shrink([false, false]).show(&mut child, |ui| {
                let rows = n.div_ceil(cols);
                let row_w = cols as f32 * size.x + (cols - 1) as f32 * TILE_GAP;
                let (space, _) = ui.allocate_exact_size(vec2(ui.available_width(), rows as f32 * (size.y + TILE_GAP)), Sense::hover());
                let left = space.center().x - row_w / 2.0;
                for (i, tile) in tiles.iter().enumerate() {
                    let min = pos2(left + (i % cols) as f32 * (size.x + TILE_GAP), space.top() + (i / cols) as f32 * (size.y + TILE_GAP));
                    let resp = paint_tile(ui, t, Rect::from_min_size(min, size), tile);
                    if resp.clicked() {
                        clicked = Some((i, resp.interact_pointer_pos().unwrap_or(min)));
                    }
                    if resp.secondary_clicked() {
                        menu = Some((tile.id, resp.interact_pointer_pos().unwrap_or(min)));
                    }
                }
            });
        }
        if let Some((uid, at)) = menu {
            self.toggle_voice_menu(super::voice_menu::VoiceMenuKind::User(uid), Rect::from_min_size(at, vec2(1.0, 1.0)));
        }
        if let Some((i, at)) = clicked {
            if watched.iter().any(|(s, _)| *s == tiles[i].id) {
                // A stream you watch: onto the stage.
                self.focus_stream(Some(tiles[i].id));
            } else if tiles[i].streaming && !tiles[i].me {
                self.watch_from_list(tiles[i].id, channel);
            } else if let Some(user) = tiles[i].user.clone() {
                self.open_profile(user, gid, at + vec2(12.0, -60.0));
            }
        }
        if alone && can_invite {
            let b = Rect::from_center_size(pos2(area.center().x, grid_bottom + 20.0 + 16.0), vec2(168.0, 40.0));
            let r = ui.interact(b, egui::Id::new("call_invite"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            ui.painter().rect_filled(b, 10.0, if r.hovered() { overlay(0.28) } else { overlay(0.18) });
            ui.painter().text(pos2(b.left() + 26.0, b.center().y), Align2::CENTER_CENTER, ADD_PERSON, icon_font(16.0), t.header_primary);
            ui.painter().text(pos2(b.left() + 44.0, b.center().y), Align2::LEFT_CENTER, "Invite to Voice", FontId::proportional(14.0), t.header_primary);
            return r.clicked();
        }
        false
    }

    /// Not in this call: who's here and a Join button.
    fn call_lobby(&mut self, ui: &mut Ui, t: &Theme, area: Rect, channel: Id, name: &str) {
        let users = self.store.voice.get(&channel).cloned().unwrap_or_default();
        let c = area.center();
        let p = ui.painter_at(area);
        let ring = pos2(c.x, c.y - 96.0);
        p.circle_filled(ring, 38.0, overlay(0.14));
        p.text(ring, Align2::CENTER_CENTER, icon::SPEAK, icon_font(30.0), t.header_primary);
        let font = FontId::new(24.0, egui::FontFamily::Name(crate::style::BOLD.into()));
        let w = p.layout_no_wrap(name.to_string(), font.clone(), t.header_primary).size().x;
        paint_text_emoji(ui, &p, pos2(c.x - w / 2.0, c.y - 32.0), name, font, t.header_primary);
        let sub = match users.len() {
            0 => "No one is in voice right now.".to_string(),
            1 => "1 person is in voice".to_string(),
            n => format!("{n} people are in voice"),
        };
        p.text(pos2(c.x, c.y + 2.0), Align2::CENTER_CENTER, sub, FontId::proportional(15.0), t.text_muted);
        let mut y = c.y + 30.0;
        if !users.is_empty() {
            // Up to eight faces, then "+N".
            let shown = users.len().min(8);
            let extra = users.len() - shown;
            let step = 30.0;
            let row_w = (shown - 1) as f32 * step + 36.0 + if extra > 0 { 40.0 } else { 0.0 };
            let mut x = c.x - row_w / 2.0 + 18.0;
            for uid in users.iter().take(shown) {
                let user = self.store.users.get(uid);
                let av = Rect::from_center_size(pos2(x, y + 18.0), vec2(36.0, 36.0));
                p.circle_filled(av.center(), 20.0, t.bg_tertiary);
                paint_avatar(ui, av, user.map(|u| u.avatar_or_default(64)), user.map_or("?", |u| u.display_name()));
                x += step;
            }
            if extra > 0 {
                p.text(pos2(x + 8.0, y + 18.0), Align2::LEFT_CENTER, format!("+{extra}"), FontId::proportional(14.0), t.text_muted);
            }
            y += 56.0;
        }
        let b = Rect::from_center_size(pos2(c.x, y + 24.0), vec2(156.0, 42.0));
        let r = ui.interact(b, egui::Id::new("call_join"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
        let fill = if r.hovered() { VOICE_GREEN.lerp_to_gamma(Color32::WHITE, 0.1) } else { VOICE_GREEN };
        ui.painter().rect_filled(b, 10.0, fill);
        ui.painter().text(b.center(), Align2::CENTER_CENTER, "Join Voice", FontId::new(15.0, egui::FontFamily::Name(crate::style::BOLD.into())), Color32::WHITE);
        if let Some(other) = self.voice.as_ref().map(|v| v.channel).filter(|c| *c != channel) {
            let other = self.store.channels.get(&other).and_then(|c| c.name.clone()).unwrap_or_default();
            p.text(pos2(c.x, b.bottom() + 16.0), Align2::CENTER_CENTER, format!("You'll leave {other}."), FontId::proportional(13.0), t.text_muted);
        }
        if r.clicked() {
            self.join_voice(channel);
        }
    }

    /// Discord's control bar: [mic | chevron] · [share screen, soundboard, …] ·
    /// hang up, centred; Invite on the left; stream volume and full screen on
    /// the right while you watch a stream.
    fn call_controls(&mut self, ui: &mut Ui, t: &Theme, bar: Rect, can_invite: bool) {
        use super::voice_menu::{chevron, left_half, right_half, VoiceMenuKind, MUTED_RED};
        self.voice_ui.menu_drawn = ui.ctx().cumulative_pass_nr();
        let muted = self.self_mute || self.self_deaf;
        let cy = bar.center().y;
        let (btn, gap, pad) = (40.0, 8.0, 4.0);
        let group1_w = btn + 1.0 + 20.0 + pad * 2.0;
        let group2_w = btn * 4.0 + gap * 3.0 + pad * 2.0;
        let hang_w = 66.0;
        let total = group1_w + 12.0 + group2_w + 12.0 + hang_w;
        let mut x = bar.center().x - total / 2.0;
        let group_bg = Color32::from_black_alpha(150);
        let group = |ui: &mut Ui, r: Rect| {
            ui.painter().rect_filled(r, 12.0, group_bg);
            ui.painter().rect_stroke(r, 12.0, Stroke::new(1.0_f32, overlay(0.16)));
        };
        // Mic and its options chevron.
        let g1 = Rect::from_min_size(pos2(x, cy - 25.0), vec2(group1_w, 50.0));
        group(ui, g1);
        let mic = Rect::from_min_size(pos2(g1.left() + pad, cy - 20.0), vec2(btn, btn));
        let nub = Rect::from_min_size(pos2(mic.right() + 1.0, cy - 20.0), vec2(20.0, btn));
        let mr = ui.interact(mic, egui::Id::new("call_mic"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
        let nr = ui.interact(nub, egui::Id::new("call_mic_more"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
        let open = self.voice_menu_open(VoiceMenuKind::CallMic);
        let fill = |hovered: bool| match (muted, hovered) {
            (true, false) => rgba(210, 45, 57, 31),
            (true, true) => rgba(210, 45, 57, 56),
            (false, true) => overlay(0.16),
            (false, false) => Color32::TRANSPARENT,
        };
        ui.painter().rect_filled(mic, left_half(8.0), fill(mr.hovered()));
        ui.painter().rect_filled(nub, right_half(8.0), fill(nr.hovered() || open));
        let color = if muted { MUTED_RED } else { Color32::WHITE };
        ui.painter().text(mic.center(), Align2::CENTER_CENTER, if muted { MIC_OFF } else { icon::MIC }, icon_font(20.0), color);
        ui.painter().text(nub.center(), Align2::CENTER_CENTER, chevron(open), icon_font(10.0), color);
        if mr.on_hover_text(if muted { "Unmute" } else { "Mute" }).clicked() {
            self.toggle_self_mute();
        }
        let group_rect = mic.union(nub);
        self.voice_menu_anchor(VoiceMenuKind::CallMic, group_rect);
        let nr = if open { nr } else { nr.on_hover_text("More Microphone Options") };
        if nr.clicked() {
            self.toggle_voice_menu(VoiceMenuKind::CallMic, group_rect);
        }
        x = g1.right() + 12.0;

        // Share screen, soundboard, more.
        let g2 = Rect::from_min_size(pos2(x, cy - 25.0), vec2(group2_w, 50.0));
        group(ui, g2);
        let slot = |i: usize| Rect::from_min_size(pos2(g2.left() + pad + i as f32 * (btn + gap), cy - 20.0), vec2(btn, btn));
        // Camera.
        let cam_on = self.camera.on.is_some();
        let connected = self.voice.as_ref().is_some_and(|v| v.connected);
        let (fill, hover, tip) = if cam_on {
            (VOICE_GREEN, VOICE_GREEN.lerp_to_gamma(Color32::BLACK, 0.15), "Turn Off Camera")
        } else if self.camera.pending {
            (overlay(0.2), overlay(0.2), "Starting your camera…")
        } else {
            (Color32::TRANSPARENT, overlay(0.16), if connected { "Turn On Camera" } else { "Turn On Camera (once you're connected)" })
        };
        let cr = square_button(ui, slot(0), egui::Id::new("call_camera"), fill, hover, crate::camera::CAMERA, if connected { Color32::WHITE } else { t.text_muted }, tip);
        if cr.clicked() && connected {
            self.toggle_camera();
        }
        let live = self.go_live.is_some();
        let can_share = live || self.can_go_live();
        let (fill, hover, tip) = if live {
            (crate::golive::LIVE_RED, crate::golive::LIVE_RED.lerp_to_gamma(Color32::BLACK, 0.15), "Stop Streaming")
        } else {
            (Color32::TRANSPARENT, overlay(0.16), if can_share { "Share Your Screen" } else { "Share Your Screen (once you're connected)" })
        };
        let sr = square_button(ui, slot(1), egui::Id::new("call_share"), fill, hover, crate::golive::SCREEN, if can_share { Color32::WHITE } else { t.text_muted }, tip);
        if sr.clicked() {
            if live {
                self.stop_go_live();
            } else {
                self.open_share_picker();
            }
        }
        let sb_open = self.soundboard_open();
        let sb = slot(2);
        let br = square_button(ui, sb, egui::Id::new("call_soundboard"), if sb_open { overlay(0.2) } else { Color32::TRANSPARENT }, overlay(0.16), crate::ui::soundboard::SOUNDBOARD, Color32::WHITE, "Open Soundboard");
        self.soundboard_anchor(sb);
        if br.clicked() {
            self.toggle_soundboard(sb);
        }
        let more = slot(3);
        let more_open = self.voice_menu_open(VoiceMenuKind::CallMore);
        let mo = square_button(ui, more, egui::Id::new("call_more"), if more_open { overlay(0.2) } else { Color32::TRANSPARENT }, overlay(0.16), icon::MORE, Color32::WHITE, "More Options");
        self.voice_menu_anchor(VoiceMenuKind::CallMore, more);
        if mo.clicked() {
            self.toggle_voice_menu(VoiceMenuKind::CallMore, more);
        }
        x = g2.right() + 12.0;

        // Hang up (or, while watching a stream, stop watching).
        let end = Rect::from_min_size(pos2(x, cy - 25.0), vec2(hang_w, 50.0));
        let red = Color32::from_rgb(210, 45, 57);
        // The focused stream gets the bar's volume and full screen.
        let focused = self.focused_watch().map(|w| (w.streamer, w.volume, w.fullscreen));
        if focused.is_some() {
            if round_button(ui, end, egui::Id::new("call_stop_watching"), red, red.lerp_to_gamma(Color32::BLACK, 0.15), crate::style::icon::CLOSE, 18.0, Color32::WHITE, "Stop Watching").clicked() {
                self.stop_watching();
            }
        } else if round_button(ui, end, egui::Id::new("call_hang_up"), red, red.lerp_to_gamma(Color32::BLACK, 0.15), HANG_UP, 22.0, Color32::WHITE, "Disconnect").clicked() {
            self.leave_voice();
        }

        // Left tray: Invite.
        if can_invite {
            let inv = Rect::from_center_size(pos2(bar.left() + 28.0, cy), vec2(32.0, 32.0));
            let r = ui.interact(inv, egui::Id::new("call_tray_invite"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            if r.hovered() {
                ui.painter().rect_filled(inv, 8.0, overlay(0.16));
            }
            ui.painter().text(inv.center(), Align2::CENTER_CENTER, ADD_PERSON, icon_font(19.0), if r.hovered() { Color32::WHITE } else { t.interactive_normal });
            if r.on_hover_text("Invite").clicked() {
                if let Some(c) = self.voice.as_ref().map(|v| v.channel) {
                    self.open_invite(c);
                }
            }
        }
        if let Some((streamer, volume, fullscreen)) = focused {
            // Right end: stream volume (click for the slider), full screen and,
            // while a stream is on the stage, Discord's grid view.
            let full = Rect::from_center_size(pos2(bar.right() - 34.0, cy), vec2(40.0, 40.0));
            let vol = Rect::from_center_size(pos2(bar.right() - 80.0, cy), vec2(40.0, 40.0));
            if round_button(ui, full, egui::Id::new("call_fullscreen"), Color32::TRANSPARENT, overlay(0.16), if fullscreen { crate::golive::EXIT_FULLSCREEN } else { crate::golive::FULLSCREEN }, 17.0, t.header_primary, if fullscreen { "Exit Full Screen" } else { "Full Screen" }).clicked() {
                self.toggle_watch_fullscreen(streamer);
            }
            if !self.golive_ui.stream_grid {
                let lay = Rect::from_center_size(pos2(bar.right() - 126.0, cy), vec2(40.0, 40.0));
                if round_button(ui, lay, egui::Id::new("call_grid_view"), Color32::TRANSPARENT, overlay(0.16), "", 17.0, t.header_primary, "Grid View").clicked() {
                    self.focus_stream(None);
                }
                let icon = super::add_server::tinted_svg("grid-square", include_bytes!("../../assets/call/grid-square.svg"), t.header_primary);
                egui::Image::new(icon).fit_to_exact_size(vec2(20.0, 20.0)).paint_at(ui, Rect::from_center_size(lay.center(), vec2(20.0, 20.0)));
            }
            let glyph = if volume <= 0.001 { SPEAKER_OFF } else { crate::style::icon::SPEAK };
            let vr = round_button(ui, vol, egui::Id::new("call_stream_volume"), Color32::TRANSPARENT, overlay(0.16), glyph, 17.0, t.header_primary, "Stream Volume");
            let open_id = egui::Id::new("call_stream_volume_open");
            let mut open = ui.data(|d| d.get_temp::<bool>(open_id).unwrap_or(false));
            if vr.clicked() {
                open = !open;
            }
            if open {
                let pop = Rect::from_min_size(pos2(vol.center().x - 30.0, vol.top() - 168.0), vec2(60.0, 156.0));
                let resp = egui::Area::new(egui::Id::new("call_stream_volume_pop")).order(Order::Foreground).fixed_pos(pop.min).show(ui.ctx(), |ui| {
                    let (r, _) = ui.allocate_exact_size(pop.size(), Sense::hover());
                    ui.painter().rect_filled(r, 10.0, t.bg_floating);
                    ui.painter().rect_stroke(r, 10.0, Stroke::new(1.0_f32, t.border_subtle));
                    let track = Rect::from_center_size(pos2(r.center().x, r.top() + 72.0), vec2(6.0, 110.0));
                    let tr = ui.interact(track.expand2(vec2(18.0, 8.0)), egui::Id::new("call_stream_volume_track"), Sense::click_and_drag());
                    let mut v = volume;
                    if let Some(pos) = tr.interact_pointer_pos().filter(|_| tr.dragged() || tr.clicked()) {
                        v = ((track.bottom() - pos.y) / track.height()).clamp(0.0, 1.0) * 2.0;
                    }
                    ui.painter().rect_filled(track, 3.0, overlay(0.2));
                    let fill_h = track.height() * v / 2.0;
                    ui.painter().rect_filled(Rect::from_min_max(pos2(track.left(), track.bottom() - fill_h), track.max), 3.0, super::voice_menu::BLURPLE);
                    ui.painter().circle_filled(pos2(track.center().x, track.bottom() - fill_h), 8.0, Color32::WHITE);
                    ui.painter().text(pos2(r.center().x, r.bottom() - 16.0), Align2::CENTER_CENTER, format!("{:.0}%", v * 100.0), FontId::proportional(12.0), t.text_normal);
                    (v, tr.drag_stopped() || tr.clicked())
                });
                let (v, done) = resp.inner;
                if (v - volume).abs() > f32::EPSILON || done {
                    self.set_watch_volume(streamer, v, done);
                }
                let outside = ui.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !resp.response.rect.contains(p) && !vol.contains(p)));
                if outside {
                    open = false;
                }
            }
            ui.data_mut(|d| d.insert_temp(open_id, open));
        }
    }
}

/// A 40 px call-bar button (Discord's rounded square). Returns the response.
#[allow(clippy::too_many_arguments)]
fn square_button(ui: &mut Ui, rect: Rect, id: egui::Id, fill: Color32, hover: Color32, glyph: &str, color: Color32, tip: &str) -> egui::Response {
    let resp = ui.interact(rect, id, Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
    ui.painter().rect_filled(rect, 8.0, if resp.hovered() { hover } else { fill });
    ui.painter().text(rect.center(), Align2::CENTER_CENTER, glyph, icon_font(20.0), color);
    resp.on_hover_text(tip)
}

/// One participant: colour or banner, avatar (green ring while talking),
/// name pill with mute / deafen marks.
fn paint_tile(ui: &mut Ui, t: &Theme, rect: Rect, tile: &Tile) -> egui::Response {
    if !tile.ringing {
        return paint_tile_body(ui, t, rect, tile);
    }
    // Discord's ringing tile: the whole tile at 30 %, and around it a 3 px
    // outline that pulses twice every 2.5 s, growing 2.5 % as it fades.
    let mut dim = ui.new_child(egui::UiBuilder::new().max_rect(rect.expand(rect.width().max(rect.height()) * 0.0125 + 4.0)));
    dim.multiply_opacity(0.3);
    let resp = paint_tile_body(&mut dim, t, rect, tile);
    let outline = |grow: f32, alpha: f32| {
        let r = Rect::from_center_size(rect.center(), rect.size() * grow).expand(1.5);
        dim.painter().rect_stroke(r, 15.5, Stroke::new(3.0_f32, Color32::WHITE.gamma_multiply(alpha)));
    };
    if super::REDUCED_MOTION.load(std::sync::atomic::Ordering::Relaxed) {
        outline(1.0, 1.0);
    } else {
        let phase = (ui.input(|i| i.time) / 2.5).fract() as f32;
        // Two pulses: at 0 (fading in over the first 11.56 %) and at 39.04 %,
        // each gone by 39.02 % / 66.48 %.
        let pulse = |start: f32, end: f32, fade_in: f32| {
            let k = (phase - start) / (end - start);
            (0.0..=1.0).contains(&k).then(|| {
                let alpha = if phase < fade_in { (phase - start) / (fade_in - start) } else { 1.0 - (phase - fade_in) / (end - fade_in) };
                (1.0 + 0.025 * k, alpha.clamp(0.0, 1.0))
            })
        };
        if let Some((grow, alpha)) = pulse(0.0, 0.3902, 0.1156).or_else(|| pulse(0.3904, 0.6648, 0.3904)) {
            outline(grow, alpha);
        }
        ui.ctx().request_repaint_after(std::time::Duration::from_millis(33));
    }
    resp
}

fn paint_tile_body(ui: &mut Ui, t: &Theme, rect: Rect, tile: &Tile) -> egui::Response {
    let resp = ui.interact(rect, egui::Id::new(("call_tile", tile.id.0)), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
    let r = 14.0;
    let p = ui.painter_at(rect.expand(2.0));
    gradient_rrect(&p, rect, r, tile.color.lerp_to_gamma(Color32::BLACK, 0.32), tile.color.lerp_to_gamma(Color32::BLACK, 0.62));
    if let Some(url) = &tile.stream_preview {
        paint_cover(ui, rect, url, Rounding::same(r));
        p.rect_filled(rect, r, Color32::from_black_alpha(95));
    } else if let Some(url) = &tile.banner {
        paint_cover(ui, rect, url, Rounding::same(r));
        p.rect_filled(rect, r, Color32::from_black_alpha(120));
    }
    if resp.hovered() {
        p.rect_filled(rect, r, rgba(255, 255, 255, 10));
    }
    // Speaking fades in and out; nothing animates while nobody talks.
    let s = if super::REDUCED_MOTION.load(std::sync::atomic::Ordering::Relaxed) {
        f32::from(u8::from(tile.speaking))
    } else {
        ui.ctx().animate_bool_with_time(egui::Id::new(("call_speaking", tile.id.0)), tile.speaking, 0.16)
    };
    let show_avatar = tile.preview.is_some() || tile.stream_preview.is_none() || rect.height() < 130.0;
    if show_avatar {
        let size = (rect.width().min(rect.height() * 1.6) * 0.22).clamp(40.0, 112.0).min(rect.height() * 0.5);
        let av = Rect::from_center_size(rect.center() - vec2(0.0, rect.height() * 0.03), vec2(size, size));
        if s > 0.0 {
            p.circle_filled(av.center(), size / 2.0 + 4.0 + 6.0 * s, VOICE_GREEN.gamma_multiply(0.16 * s));
        }
        // A thin dark ring keeps light avatars off light tiles.
        p.circle_filled(av.center(), size / 2.0 + 3.0, Color32::from_black_alpha(70));
        paint_avatar(ui, av, tile.user.as_ref().map(|u| u.avatar_or_default(if size > 64.0 { 256 } else { 128 })), &tile.name);
        if s > 0.0 {
            p.circle_stroke(av.center(), size / 2.0 + 3.0, Stroke::new(3.0_f32, VOICE_GREEN.gamma_multiply(s)));
        }
    }
    // Your own screen while you're live, over the avatar.
    if let Some(tex) = &tile.preview {
        let sz = tex.size_vec2();
        let scale = (rect.width() / sz.x.max(1.0)).min(rect.height() / sz.y.max(1.0));
        let pic = Rect::from_center_size(rect.center(), sz * scale);
        p.rect_filled(rect, r, Color32::BLACK);
        egui::Image::new((tex.id(), pic.size())).rounding(Rounding::same(r)).paint_at(ui, pic);
    }
    p.rect_stroke(rect, r, Stroke::new(1.0_f32, rgba(255, 255, 255, 16)));
    if s > 0.0 {
        p.rect_stroke(rect.shrink(1.0), r - 1.0, Stroke::new(2.0_f32, VOICE_GREEN.gamma_multiply(s)));
    }
    if tile.streaming {
        crate::golive::paint_live(&p, pos2(rect.left() + 12.0, rect.top() + 20.0), 11.0);
        // Someone else's stream: always show "Watch Stream" on full tiles, and on hover in compact strips.
        if !tile.me && (rect.height() >= 130.0 || resp.hovered()) {
            let compact = rect.height() < 130.0;
            let b = Rect::from_center_size(
                if compact { rect.center() } else { rect.center() + vec2(0.0, rect.height() * 0.24) },
                vec2(if compact { 84.0 } else { 142.0 }, if compact { 26.0 } else { 34.0 }),
            );
            p.rect_filled(b, 10.0, Color32::from_black_alpha(if resp.hovered() { 225 } else { 175 }));
            p.rect_stroke(b, 10.0, Stroke::new(1.0_f32, rgba(255, 255, 255, if resp.hovered() { 70 } else { 28 })));
            p.text(
                b.center(),
                Align2::CENTER_CENTER,
                if compact { "Watch" } else { "Watch Stream" },
                FontId::new(if compact { 12.0 } else { 13.0 }, egui::FontFamily::Name(crate::style::BOLD.into())),
                Color32::WHITE,
            );
        }
    }
    // Name pill, bottom-left.
    let font = FontId::proportional(13.0);
    let mark = if tile.deafened { Some(crate::style::icon::DEAFENED) } else if tile.muted { Some(MIC_OFF) } else { None };
    let name_w = p.layout_no_wrap(tile.name.clone(), font.clone(), Color32::WHITE).size().x;
    let pill_w = (name_w + 20.0 + if mark.is_some() { 20.0 } else { 0.0 }).min(rect.width() - 20.0);
    let pill = Rect::from_min_size(pos2(rect.left() + 10.0, rect.bottom() - 34.0), vec2(pill_w, 24.0));
    p.rect_filled(pill, 8.0, Color32::from_black_alpha(150));
    let mut x = pill.left() + 10.0;
    if let Some(glyph) = mark {
        let c = if tile.server { t.danger } else { Color32::from_rgb(0xff, 0x6b, 0x6e) };
        p.text(pos2(x + 7.0, pill.center().y), Align2::CENTER_CENTER, glyph, icon_font(13.0), c);
        x += 20.0;
    }
    let clip = ui.painter_at(pill.shrink2(vec2(6.0, 0.0)));
    paint_text_emoji(ui, &clip, pos2(x, pill.center().y), &tile.name, font, Color32::WHITE);
    resp.on_hover_text(&tile.name)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn grid_fills_the_area_with_16_9_tiles() {
        let (cols, size) = tile_grid(1, vec2(1600.0, 900.0), TILE_GAP);
        assert_eq!(cols, 1);
        assert!((size.x - MAX_TILE_W).abs() < 0.1, "a lone tile is capped");
        let (cols, size) = tile_grid(4, vec2(1000.0, 600.0), TILE_GAP);
        assert_eq!(cols, 2);
        assert!((size.x / size.y - 16.0 / 9.0).abs() < 0.01);
        let (cols, _) = tile_grid(3, vec2(1600.0, 300.0), TILE_GAP);
        assert_eq!(cols, 3, "wide areas put people side by side");
        assert_eq!(elapsed(std::time::Duration::from_secs(75)), "1:15");
        assert_eq!(elapsed(std::time::Duration::from_secs(3723)), "1:02:03");
    }

    #[test]
    fn dm_avatars_fit_narrow_calls() {
        let (size, gap) = dm_avatar_layout(500.0, 200.0, 4);
        assert_eq!(size, 80.0);
        assert_eq!(gap, 32.0);
        let (size_tight, gap_tight) = dm_avatar_layout(300.0, 200.0, 8);
        assert!(8.0 * size_tight + 7.0 * gap_tight <= 276.0 + 0.01);
    }
}

// ---- DM calls ------------------------------------------------------------------------

/// Avatar size and spacing that keep `count` participants centred inside `avail_w`.
fn dm_avatar_layout(avail_w: f32, height: f32, count: usize) -> (f32, f32) {
    let count = count.max(1);
    let usable = (avail_w - 24.0).max(32.0);
    let min_gap = 8.0_f32;
    let (base_size, max_gap) = ((height * 0.5).clamp(48.0, 80.0), 32.0);
    let max_size = ((usable - (count - 1) as f32 * min_gap) / count as f32).max(24.0);
    let size = base_size.min(max_size);
    let gap = if count > 1 { ((usable - count as f32 * size) / (count - 1) as f32).clamp(min_gap, max_gap) } else { max_gap };
    (size, gap)
}

/// How a DM participant shows in the call area.
#[derive(Clone, Copy, PartialEq)]
enum Presence {
    InCall,
    Ringing,
    Absent,
}

/// Discord's ringing animation: two rings growing out of the avatar and fading.
fn paint_ringing(ui: &Ui, p: &egui::Painter, center: egui::Pos2, radius: f32) {
    if super::REDUCED_MOTION.load(std::sync::atomic::Ordering::Relaxed) {
        p.circle_stroke(center, radius + 6.0, Stroke::new(2.0_f32, rgba(255, 255, 255, 60)));
        return;
    }
    let time = ui.input(|i| i.time);
    for k in 0..2 {
        let phase = ((time / 1.6 + f64::from(k) * 0.5) % 1.0) as f32;
        p.circle_stroke(center, radius + 2.0 + 22.0 * phase, Stroke::new(2.0_f32, Color32::WHITE.gamma_multiply(0.45 * (1.0 - phase))));
    }
    ui.ctx().request_repaint_after(std::time::Duration::from_millis(33));
}

impl RustCord {
    /// Whether this DM / group DM call currently has any video, Go Live stream,
    /// or watched stream (used to switch the DM call panel into grid / stage mode).
    pub fn dm_call_has_video(&self, channel: Id) -> bool {
        let in_call = self.voice.as_ref().is_some_and(|v| v.channel == channel);
        if in_call && (self.watching.iter().any(|w| w.channel == channel) || self.go_live.as_ref().is_some_and(|g| g.channel == channel) || self.camera.on.is_some()) {
            return true;
        }
        self.store.voice.get(&channel).is_some_and(|users| users.iter().any(|id| self.store.voice_flags.get(id).is_some_and(|f| f.streaming || f.video)))
    }

    /// Discord's call area above a DM's messages: everyone in the DM (in the call, being
    /// rung, or not there), switching to video tiles / stage when someone streams or uses
    /// camera, then the call controls, or "Join Call" while you're not in it.
    pub fn dm_call_panel(&mut self, ui: &mut Ui, channel: Id) {
        let t = self.theme.clone();
        let area = ui.max_rect();
        let me = self.store.me_id();
        let in_call = self.voice.as_ref().is_some_and(|v| v.channel == channel);
        let connected = self.voice.as_ref().is_some_and(|v| v.channel == channel && v.connected);
        let there = self.store.voice.get(&channel).cloned().unwrap_or_default();
        let ringing = self.calls.get(&channel).map(|c| c.ringing.clone()).unwrap_or_default();
        let bar_h = 76.0;
        let stage = Rect::from_min_max(area.min, pos2(area.right(), area.bottom() - bar_h));
        let watched = in_call.then(|| self.focused_watch().filter(|w| w.channel == channel).map(|w| (w.streamer, w.viewers.clone()))).flatten();
        if self.dm_call_has_video(channel) {
            if let Some((streamer, viewers)) = watched {
                let hdr = Rect::from_min_size(stage.min, vec2(stage.width(), 32.0));
                let hp = ui.painter_at(hdr);
                self.paint_watching_header(ui, &hp, &t, channel, None, streamer, &viewers, hdr.left() + 12.0, hdr.right() - 12.0, hdr.center().y, false);
                hp.hline(hdr.x_range(), hdr.bottom() - 0.5, Stroke::new(1.0_f32, t.border_subtle));
                let stage_body = stage.with_min_y(hdr.bottom()).shrink2(vec2(12.0, 4.0));
                let tiles_area = self.watching_stage(ui, &t, stage_body);
                self.call_tiles(ui, &t, tiles_area, channel, None, false);
            } else {
                self.call_tiles(ui, &t, stage.shrink2(vec2(12.0, 8.0)), channel, None, false);
            }
        } else {
            // Voice-only call: centred circular avatars, speaking rings and status text.
            let mut people: Vec<(Id, Option<User>)> = Vec::new();
            if let Some(me) = me {
                people.push((me, self.store.me.clone()));
            }
            for user in self.store.channels.get(&channel).map(|c| c.recipients.clone()).unwrap_or_default() {
                if Some(user.id) != me {
                    people.push((user.id, Some(user)));
                }
            }
            for uid in &there {
                if !people.iter().any(|(id, _)| id == uid) {
                    people.push((*uid, self.store.users.get(uid).cloned()));
                }
            }
            let (size, gap) = dm_avatar_layout(stage.width(), stage.height(), people.len());
            let row_w = people.len() as f32 * size + people.len().saturating_sub(1) as f32 * gap;
            let mut x = stage.center().x - row_w / 2.0;
            let p = ui.painter_at(area);
            let mut open: Option<(User, egui::Pos2)> = None;
            let mut menu: Option<(Id, egui::Pos2)> = None;
            for (id, user) in &people {
                let is_me = Some(*id) == me;
                let presence = if (is_me && in_call) || there.contains(id) {
                    Presence::InCall
                } else if ringing.contains(id) {
                    Presence::Ringing
                } else {
                    Presence::Absent
                };
                let av = Rect::from_min_size(pos2(x, stage.center().y - size / 2.0), vec2(size, size));
                x += size + gap;
                let name = user.as_ref().map_or("?", |u| u.display_name()).to_string();
                if presence == Presence::Ringing {
                    paint_ringing(ui, &p, av.center(), size / 2.0);
                }
                paint_avatar(ui, av, user.as_ref().map(|u| u.avatar_or_default(256)), &name);
                if presence != Presence::InCall {
                    // Not in the call (yet): dimmed, as in Discord.
                    p.circle_filled(av.center(), size / 2.0 + 0.5, Color32::from_black_alpha(if presence == Presence::Ringing { 110 } else { 170 }));
                }
                let speaking = presence == Presence::InCall && self.is_speaking(*id);
                let s = if super::REDUCED_MOTION.load(std::sync::atomic::Ordering::Relaxed) {
                    f32::from(u8::from(speaking))
                } else {
                    ui.ctx().animate_bool_with_time(egui::Id::new(("dm_call_speaking", id.0)), speaking, 0.12)
                };
                if s > 0.0 {
                    // Discord's speaking ring: 2 px of green, 2 px out from the avatar.
                    p.circle_stroke(av.center(), size / 2.0 + 3.0, Stroke::new(2.0_f32, VOICE_GREEN.gamma_multiply(s)));
                }
                if presence == Presence::InCall {
                    let flags = self.store.voice_flags.get(id).copied().unwrap_or_default();
                    let (muted, deafened) = if is_me { (self.self_mute || self.self_deaf, self.self_deaf) } else { (flags.muted, flags.deafened) };
                    if muted || deafened {
                        let badge = pos2(av.right() - 8.0, av.bottom() - 8.0);
                        p.circle_filled(badge, 12.0, Color32::BLACK);
                        p.circle_filled(badge, 10.0, Color32::from_rgb(0x2b, 0x2d, 0x31));
                        p.text(badge, Align2::CENTER_CENTER, if deafened { crate::style::icon::DEAFENED } else { MIC_OFF }, icon_font(11.0), Color32::from_rgb(0xf2, 0x3f, 0x43));
                    }
                }
                let resp = ui.interact(av, egui::Id::new(("dm_call_person", id.0)), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
                if let (true, Some(user)) = (resp.clicked(), user) {
                    open = Some((user.clone(), av.right_top()));
                }
                if resp.secondary_clicked() && presence == Presence::InCall {
                    menu = Some((*id, resp.interact_pointer_pos().unwrap_or(av.center())));
                }
                resp.on_hover_text(match presence {
                    Presence::InCall => name,
                    Presence::Ringing => format!("{name} (ringing…)"),
                    Presence::Absent => format!("{name} (not in the call)"),
                });
            }
            // What the call is doing, under the faces.
            let status = if in_call && !connected {
                Some("Connecting…".to_string())
            } else if in_call && ringing.iter().any(|r| Some(*r) != me) && there.iter().filter(|u| Some(**u) != me).count() == 0 {
                Some("Calling…".to_string())
            } else if in_call {
                self.voice.as_ref().and_then(|v| v.connected_at).map(|at| elapsed(at.elapsed()))
            } else if me.is_some_and(|m| ringing.contains(&m)) {
                Some("Incoming Call…".to_string())
            } else {
                None
            };
            if let Some(status) = status {
                p.text(pos2(stage.center().x, stage.center().y + size / 2.0 + 22.0), Align2::CENTER_CENTER, status, FontId::proportional(13.0), rgba(255, 255, 255, 170));
            }
            if let Some((uid, at)) = menu {
                self.toggle_voice_menu(super::voice_menu::VoiceMenuKind::User(uid), Rect::from_min_size(at, vec2(1.0, 1.0)));
            } else if let Some((user, at)) = open {
                self.open_profile(user, None, at + vec2(12.0, 0.0));
            }
        }
        let bar = Rect::from_min_max(pos2(area.left(), area.bottom() - bar_h), area.max);
        if in_call {
            self.call_controls(ui, &t, bar, false);
        } else {
            // Join Call (and Decline while it rings you).
            let rings_me = me.is_some_and(|m| ringing.contains(&m)) && !self.dismissed_calls.contains(&channel);
            let bold = FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into()));
            let (w, h, gap) = (112.0, 38.0, 12.0);
            let total = if rings_me { w * 2.0 + gap } else { w };
            let join = Rect::from_min_size(pos2(bar.center().x - total / 2.0, bar.center().y - h / 2.0), vec2(w, h));
            let jr = ui.interact(join, egui::Id::new("dm_call_join"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
            ui.painter().rect_filled(join, 8.0, if jr.hovered() { VOICE_GREEN.lerp_to_gamma(Color32::BLACK, 0.12) } else { VOICE_GREEN });
            ui.painter().text(join.center(), Align2::CENTER_CENTER, "Join Call", bold.clone(), Color32::WHITE);
            if jr.clicked() {
                self.accept_call(channel);
            }
            if rings_me {
                let red = Color32::from_rgb(210, 45, 57);
                let dec = Rect::from_min_size(pos2(join.right() + gap, join.top()), vec2(w, h));
                let dr = ui.interact(dec, egui::Id::new("dm_call_decline"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
                ui.painter().rect_filled(dec, 8.0, if dr.hovered() { red.lerp_to_gamma(Color32::BLACK, 0.15) } else { red });
                ui.painter().text(dec.center(), Align2::CENTER_CENTER, "Decline", bold, Color32::WHITE);
                if dr.clicked() {
                    self.decline_call(channel);
                }
            }
        }
        ui.painter().hline(area.x_range(), area.bottom() - 0.5, Stroke::new(1.0_f32, t.border_subtle));
    }

    /// Discord's incoming call box: who is calling, "Incoming Call…", decline and accept.
    /// Shown over everything unless that DM (with its own call area) is what's open.
    pub fn incoming_call_ui(&mut self, ctx: &egui::Context) {
        let Some(channel) = self.incoming_call() else { return };
        if self.current_guild.is_none() && self.current_channel == Some(channel) && !self.friends_open {
            return;
        }
        let t = self.theme.clone();
        let chan = self.store.channels.get(&channel).cloned();
        let caller = chan.as_ref().and_then(|c| {
            // Whoever is in the call already; in a 1:1 DM, the other person.
            let there = self.store.voice.get(&channel).cloned().unwrap_or_default();
            c.recipients.iter().find(|u| there.contains(&u.id)).or(c.recipients.first()).cloned()
        });
        let name = chan.as_ref().map(|c| self.store.label(c)).unwrap_or_else(|| "Unknown".into());
        let (mut accept, mut decline) = (false, false);
        egui::Area::new(egui::Id::new("incoming_call")).order(Order::Foreground).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
            egui::Frame::none()
                .fill(t.bg_floating)
                .rounding(12.0)
                .stroke(Stroke::new(1.0_f32, t.border_subtle))
                .shadow(egui::epaint::Shadow { offset: vec2(0.0, 8.0), blur: 28.0, spread: 0.0, color: Color32::from_black_alpha(140) })
                .show(ui, |ui| {
                    let (rect, _) = ui.allocate_exact_size(vec2(232.0, 286.0), Sense::hover());
                    let p = ui.painter_at(rect);
                    let av = Rect::from_center_size(pos2(rect.center().x, rect.top() + 80.0), vec2(80.0, 80.0));
                    paint_ringing(ui, &p, av.center(), 40.0);
                    paint_avatar(ui, av, caller.as_ref().map(|u| u.avatar_or_default(256)), &name);
                    let bold = |size: f32| FontId::new(size, egui::FontFamily::Name(crate::style::BOLD.into()));
                    let clip = ui.painter_at(rect.shrink2(vec2(12.0, 0.0)));
                    let w = clip.layout_no_wrap(name.clone(), bold(20.0), t.header_primary).size().x.min(rect.width() - 24.0);
                    paint_text_emoji(ui, &clip, pos2(rect.center().x - w / 2.0, av.bottom() + 34.0), &name, bold(20.0), t.header_primary);
                    p.text(pos2(rect.center().x, av.bottom() + 60.0), Align2::CENTER_CENTER, "Incoming Call…", FontId::proportional(14.0), t.text_muted);
                    let y = rect.bottom() - 48.0;
                    let red = Color32::from_rgb(210, 45, 57);
                    let no = Rect::from_center_size(pos2(rect.center().x - 40.0, y), vec2(56.0, 56.0));
                    let yes = Rect::from_center_size(pos2(rect.center().x + 40.0, y), vec2(56.0, 56.0));
                    let nr = ui.interact(no, egui::Id::new("incoming_call_decline"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
                    let yr = ui.interact(yes, egui::Id::new("incoming_call_accept"), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
                    p.circle_filled(no.center(), 28.0, if nr.hovered() { red.lerp_to_gamma(Color32::BLACK, 0.15) } else { red });
                    p.text(no.center(), Align2::CENTER_CENTER, crate::style::icon::CLOSE, icon_font(20.0), Color32::WHITE);
                    p.circle_filled(yes.center(), 28.0, if yr.hovered() { VOICE_GREEN.lerp_to_gamma(Color32::BLACK, 0.12) } else { VOICE_GREEN });
                    p.text(yes.center(), Align2::CENTER_CENTER, crate::style::icon::PHONE_CALL, icon_font(24.0), Color32::WHITE);
                    decline = nr.on_hover_text("Decline").clicked();
                    accept = yr.on_hover_text("Join Call").clicked();
                });
        });
        if accept {
            self.accept_call(channel);
        } else if decline {
            self.decline_call(channel);
        }
    }
}