Skip to content

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

74.3 KB
Raw Blame
//! Rich embeds and message components (buttons, select menus and the
//! "Components V2" layout), following Discord's own embed component:
//!
//! * which media an embed shows is decided like Discord's sanitiser (an
//!   article's thumbnail is its big image, a video needs a poster…);
//! * media-only embeds (a bare image, GIF or video link) are drawn inline,
//!   without a card;
//! * a card is at most 516 px of grid + its borders, 8 / 16 / 16 / 12 px
//!   padding, 8 px between parts (16 before media), three inline fields per
//!   row on a 12-column grid, an 80 px thumbnail top-right;
//! * videos with a real file play in RustCord's player, the others
//!   (YouTube, Twitch, SoundCloud…) in the provider's own player once you
//!   press play; Spotify and Apple Music links get their players too.

use super::chat::{fit, spoiler_colors, UiAction};
use crate::app::RustCord;
use crate::style::{icon, icon_font, overlay};
use discord::model::{Component, Embed, EmbedMedia, Message, ReactionEmoji};
use eframe::egui::{self, pos2, vec2, Align2, Color32, CursorIcon, FontId, Frame, Margin, Rect, Response, RichText, Rounding, Sense, Stroke, Ui, Vec2};

/// Discord's `.gridContainer` limit; the card adds its 4 + 1 px borders.
const GRID_W: f32 = 516.0;
const BRAND: Color32 = Color32::from_rgb(0x58, 0x65, 0xf2);
const BRAND_HOVER: Color32 = Color32::from_rgb(0x47, 0x52, 0xc4);
/// `revealed` keys for spoilered embeds: this + the embed's index.
const SPOILER_KEY: usize = 1_000_000;
/// The external-link glyph (Discord's "open in browser" on players).
const EXTERNAL: &str = "\u{E8A7}";

fn strong(size: f32) -> FontId {
    FontId::new(size, egui::FontFamily::Name(crate::style::BOLD.into()))
}

fn media_url(m: &EmbedMedia) -> String {
    m.proxy_url.clone().filter(|u| !u.is_empty()).unwrap_or_else(|| m.url.clone())
}

/// The picture's address for showing it `w` × `h` points big: Discord's
/// media proxy is asked for a copy that size (as Discord's own client does)
/// instead of the original, which for a link preview or a bot's embed is
/// often a few megapixels: megabytes to download, 10+ MB decoded, and as
/// much again on the GPU, for a picture drawn 400 px (or 80 px) wide.
/// GIFs keep their own file (so they play), as does anything not on the proxy.
fn media_sized(ui: &Ui, m: &EmbedMedia, w: f32, h: f32) -> String {
    let url = media_url(m);
    let path = url.split(['?', '#']).next().unwrap_or(&url).to_ascii_lowercase();
    let proxied = url.starts_with("https://media.discordapp.net/") || (url.starts_with("https://images-ext-") && url.contains(".discordapp.net/"));
    if !proxied || path.ends_with(".gif") || url.contains("width=") {
        return url;
    }
    let ppp = ui.ctx().pixels_per_point();
    let (pw, ph) = ((w * ppp).ceil().max(1.0) as u32, (h * ppp).ceil().max(1.0) as u32);
    // (Never bigger than the picture is.)
    if m.width.is_some_and(|nw| nw <= pw) && m.height.is_some_and(|nh| nh <= ph) {
        return url;
    }
    format!("{url}{}width={pw}&height={ph}", if url.contains('?') { '&' } else { '?' })
}

fn dims(m: &EmbedMedia, default: (f32, f32)) -> (f32, f32) {
    (m.width.map_or(default.0, |w| w as f32), m.height.map_or(default.1, |h| h as f32))
}

/// Discord only uses media that says how big it is.
fn valid(m: &&EmbedMedia) -> bool {
    m.width.unwrap_or(0) > 0 && m.height.unwrap_or(0) > 0
}

/// Image URL for a component / reaction emoji.
fn emoji_url(e: &ReactionEmoji) -> Option<String> {
    match (e.id, e.name.as_deref()) {
        (Some(id), _) => Some(super::emoji_img(id, e.animated, 48)),
        (None, Some(n)) if !n.is_empty() => Some(crate::emoji::twemoji_url(n)),
        _ => None,
    }
}

/// Width of `text` as `paint_text_emoji` draws it on one line.
fn text_emoji_width(ui: &Ui, text: &str, font: &FontId) -> f32 {
    let chars: Vec<char> = text.chars().collect();
    let emoji_w = font.size * 1.15 + 2.0;
    ui.fonts(|f| {
        let (mut x, mut i) = (0.0, 0);
        while i < chars.len() {
            if let Some(n) = crate::emoji::emoji_len(&chars, i) {
                x += emoji_w;
                i += n;
            } else {
                x += match chars[i] {
                    '\u{FE0F}' | '\u{FE0E}' | '\u{200D}' => 0.0,
                    '\u{30FB}' | '\u{FF65}' => f.glyph_width(font, ' ') * 2.0 + f.glyph_width(font, '·'),
                    c => f.glyph_width(font, c),
                };
                i += 1;
            }
        }
        x
    })
}

/// "Today at 6:53 pm" / "Yesterday at …" / "04/11/2026 6:53 pm", like
/// Discord's embed footers.
fn footer_time(ts: &str) -> String {
    let Ok(dt) = chrono::DateTime::parse_from_rfc3339(ts) else { return String::new() };
    let local = dt.with_timezone(&chrono::Local);
    let today = chrono::Local::now().date_naive();
    let time = local.format(super::time_fmt());
    if local.date_naive() == today {
        format!("Today at {time}")
    } else if Some(local.date_naive()) == today.pred_opt() {
        format!("Yesterday at {time}")
    } else {
        format!("{} {time}", local.format("%d/%m/%Y"))
    }
}

/// What an embed shows, decided the way Discord's client does.
struct Parts<'a> {
    kind: &'a str,
    image: Option<&'a EmbedMedia>,
    thumbnail: Option<&'a EmbedMedia>,
    video: Option<&'a EmbedMedia>,
    /// The video's still picture.
    poster: Option<String>,
}

impl<'a> Parts<'a> {
    fn of(e: &'a Embed) -> Self {
        let kind = e.kind.as_deref().unwrap_or("rich");
        let (mut image, mut thumbnail) = (None, None);
        // An article's or image's thumbnail is its picture.
        if let Some(t) = e.thumbnail.as_ref().filter(valid) {
            if matches!(kind, "article" | "image") {
                image = Some(t);
            } else {
                thumbnail = Some(t);
            }
        }
        if let Some(i) = e.image.as_ref().filter(valid) {
            image = Some(i);
        }
        let mut poster = thumbnail.map(media_url);
        let mut video = None;
        if let Some(v) = e.video.as_ref() {
            let proxy = v.proxy_url.as_deref().filter(|p| !p.is_empty());
            if let (None, Some(p), true) = (&poster, proxy, valid(&v)) {
                poster = Some(format!("{p}{}format=webp", if p.contains('?') { '&' } else { '?' }));
            }
            let sketchfab = e.provider.as_ref().is_some_and(|p| p.name.to_ascii_lowercase().contains("sketchfab")) || v.url.starts_with("https://sketchfab.com");
            if poster.is_some() && valid(&v) && !sketchfab && (proxy.is_some() || v.url.starts_with("https:")) {
                video = Some(v);
            }
        }
        Self { kind, image, thumbnail, video, poster }
    }

    /// Media with nothing to say around it is drawn without a card.
    fn inline(&self, e: &Embed) -> bool {
        (self.image.is_some() || self.video.is_some()) && (self.kind == "gifv" || self.kind != "rich" && e.author.is_none() && e.title.is_none())
    }

    /// Largest media box: 400 × 300, taller for TikTok and upright YouTube.
    fn max_media(&self, e: &Embed) -> (f32, f32) {
        let provider = e.provider.as_ref().map(|p| p.name.as_str());
        let upright_youtube = self.video.is_some_and(|v| v.height > v.width && (provider == Some("YouTube") || v.url.starts_with("https://www.youtube.com/")));
        if provider == Some("TikTok") || upright_youtube {
            (400.0, 450.0)
        } else {
            (400.0, 300.0)
        }
    }
}

/// Is this embed's link inside a `||spoiler||` of the message?
fn spoilered(m: &Message, e: &Embed) -> bool {
    let Some(url) = e.url.as_deref().filter(|u| !u.is_empty()) else { return false };
    let bare = url.trim_end_matches('/');
    m.content.split("||").skip(1).step_by(2).any(|inside| inside.contains(bare))
}

/// Discord merges embeds that share a URL: the first keeps its place and
/// collects the others' images (a tweet's four pictures). (index, embed,
/// extra images).
fn merged(embeds: &[Embed]) -> Vec<(usize, &Embed, Vec<&EmbedMedia>)> {
    let mut out: Vec<(usize, &Embed, Vec<&EmbedMedia>)> = Vec::new();
    for (i, e) in embeds.iter().enumerate() {
        if let Some(url) = e.url.as_deref() {
            if let Some(first) = out.iter_mut().find(|(_, f, _)| f.url.as_deref() == Some(url)) {
                if let Some(img) = e.image.as_ref().filter(valid) {
                    first.2.push(img);
                }
                continue;
            }
        }
        out.push((i, e, Vec::new()));
    }
    out
}

/// Discord's play pill on a video poster (48 px tall, black at 60 %): a
/// play icon and, with `external`, an open-in-browser icon; each dims until
/// hovered. Returns (play clicked, open clicked).
fn play_pill(ui: &mut Ui, center: egui::Pos2, id: egui::Id, play: bool, external: bool) -> (bool, bool) {
    let w = 24.0 + if play { 24.0 } else { 0.0 } + if external { 24.0 } else { 0.0 } + if play && external { 6.0 } else { 0.0 };
    let pill = Rect::from_center_size(center, vec2(w, 48.0));
    ui.painter().rect_filled(pill, 24.0, Color32::from_black_alpha(153));
    let mut x = pill.left() + 12.0;
    let mut clicked = (false, false);
    let button = |ui: &mut Ui, x: f32, glyph: &str, size: f32, key: &str, tip: &str| -> bool {
        let r = Rect::from_min_size(pos2(x, pill.top() + 12.0), vec2(24.0, 24.0));
        let resp = ui.interact(r, id.with(key), Sense::click());
        let color = Color32::WHITE.gamma_multiply(if resp.hovered() { 1.0 } else { 0.6 });
        if key == "play" {
            if resp.hovered() {
                hint_player(ui.ctx());
            }
            play_triangle(ui.painter(), r.center(), size, color);
        } else {
            ui.painter().text(r.center(), Align2::CENTER_CENTER, glyph, icon_font(size), color);
        }
        resp.on_hover_cursor(CursorIcon::PointingHand).on_hover_text(tip).clicked()
    };
    if play {
        clicked.0 = button(ui, x, icon::PLAY, 24.0, "play", "Play");
        x += 24.0 + if external { 2.0 } else { 0.0 };
    }
    if external {
        clicked.1 = button(ui, x, EXTERNAL, 18.0, "open", "Open in Browser");
    }
    clicked
}

/// The pointer is on something that opens a provider's player: tell the app
/// (with since when), so it can get the webview ready before the click.
fn hint_player(ctx: &egui::Context) {
    let (id, pass, now) = (egui::Id::new("embed_view_warm"), ctx.cumulative_pass_nr(), ctx.input(|i| i.time));
    let since = ctx.data(|d| d.get_temp::<(u64, f64)>(id)).filter(|(p, _)| p + 1 >= pass).map_or(now, |(_, since)| since);
    ctx.data_mut(|d| d.insert_temp(id, (pass, since)));
    // (The app waits for the pointer to rest a moment; nothing else may
    // repaint meanwhile.)
    if now - since < 0.2 {
        ctx.request_repaint_after(std::time::Duration::from_millis(120));
    }
}

/// A point of Discord's 24 px icon box, drawn `size` big around `c`.
fn icon_pt(c: egui::Pos2, size: f32, x: f32, y: f32) -> egui::Pos2 {
    c + vec2(x - 12.0, y - 12.0) * (size / 24.0)
}

/// Discord's play icon: a filled 15 × 18 triangle with soft corners, 1 px
/// right of the middle of its 24 px box (the icon font only has an outline).
fn play_triangle(painter: &egui::Painter, c: egui::Pos2, size: f32, color: Color32) {
    let corners = [icon_pt(c, size, 6.0, 3.0), icon_pt(c, size, 21.0, 12.0), icon_pt(c, size, 6.0, 21.0)];
    let r = 1.75 * size / 24.0;
    let mut points = Vec::with_capacity(15);
    for i in 0..3 {
        let (prev, cur, next) = (corners[(i + 2) % 3], corners[i], corners[(i + 1) % 3]);
        let (a, b) = (cur + (prev - cur).normalized() * r, cur + (next - cur).normalized() * r);
        // Each corner is a small curve from one side to the other.
        for k in 0..=4 {
            let t = k as f32 / 4.0;
            points.push(a.lerp(cur, t).lerp(cur.lerp(b, t), t));
        }
    }
    painter.add(egui::Shape::convex_polygon(points, color, Stroke::NONE));
}

/// Discord's pause icon: two bars, 5 × 16, 1 px corners.
fn pause_bars(painter: &egui::Painter, c: egui::Pos2, size: f32, color: Color32) {
    for x in [5.0, 14.0] {
        painter.rect_filled(Rect::from_min_max(icon_pt(c, size, x, 4.0), icon_pt(c, size, x + 5.0, 20.0)), size / 24.0, color);
    }
}

/// Discord's full-screen icon: a bracket in each corner (2 px line, the
/// corner itself rounded).
fn fullscreen_brackets(painter: &egui::Painter, c: egui::Pos2, size: f32, color: Color32) {
    let stroke = Stroke::new(2.0 * size / 24.0, color);
    for (fx, fy) in [(false, false), (true, false), (true, true), (false, true)] {
        let at = |x: f32, y: f32| icon_pt(c, size, if fx { 24.0 - x } else { x }, if fy { 24.0 - y } else { y });
        // (3,9) up to (3,6), a quarter circle around (6,6), on to (9,3).
        let mut points = vec![at(3.0, 9.0)];
        for k in 0..=6 {
            let a = std::f32::consts::PI * (1.0 + k as f32 / 12.0);
            points.push(at(6.0 + 3.0 * a.cos(), 6.0 + 3.0 * a.sin()));
        }
        points.push(at(9.0, 3.0));
        for end in [points[0], points[points.len() - 1]] {
            painter.circle_filled(end, stroke.width / 2.0, color);
        }
        painter.add(egui::Shape::line(points, stroke));
    }
}

/// Discord's "SPOILER" tag in the middle of hidden media.
fn spoiler_tag(ui: &Ui, rect: Rect, hovered: bool) {
    let g = ui.painter().layout_no_wrap("SPOILER".into(), strong(15.0), Color32::WHITE);
    let pill = Rect::from_center_size(rect.center(), g.size() + vec2(24.0, 16.0));
    ui.painter().rect_filled(pill, 20.0, Color32::from_black_alpha(if hovered { 230 } else { 153 }));
    ui.painter().galley(pill.center() - g.size() / 2.0, g, Color32::WHITE);
}

/// A picture as Discord blurs hidden media: a tiny copy from its media
/// proxy, stretched (so no full-size download before it is revealed).
pub(super) fn blurred(url: &str) -> String {
    let base = url.split('#').next().unwrap_or(url);
    format!("{base}{}format=webp&width=24&height=24", if base.contains('?') { '&' } else { '?' })
}

impl RustCord {
    /// All of a message's embeds, below its text.
    pub(super) fn embeds_ui(&self, ui: &mut Ui, m: &Message, actions: &mut Vec<UiAction>) {
        let cards = self.discord_setting("render_embeds", true);
        let (me, guild) = (self.store.me_id(), m.guild_id.or_else(|| self.store.channels.get(&m.channel_id).and_then(|c| c.guild_id)));
        // You can remove embeds from your own messages, and with Manage
        // Messages from anyone's.
        let can_suppress = me == Some(m.author.id) || guild.is_some_and(|g| self.store.has_perm(g, 1 << 13));
        // Discord's accessories box: 2 px above its first item, 4 px between
        // items, 2 px below the last.
        let mut shown = 0usize;
        let mut gap = |ui: &mut Ui| {
            ui.add_space(if shown == 0 && m.attachments.is_empty() && m.sticker_items.is_empty() && m.poll.is_none() { 2.0 } else { 4.0 });
            shown += 1;
        };
        for (idx, e, extras) in merged(&m.embeds) {
            if e.kind.as_deref() == Some("poll_result") {
                continue;
            }
            let parts = Parts::of(e);
            let hidden = spoilered(m, e) && !self.spoiler_shown((m.id, SPOILER_KEY + idx));
            // Spotify and Apple Music links are their players.
            let provider = e.provider.as_ref().map(|p| p.name.as_str());
            let music = match (provider, e.url.as_deref()) {
                (Some("Spotify"), Some(url)) if parts.kind == "link" => crate::embed_view::spotify_embed(url).map(|(src, h)| (src, h, 400.0, Color32::from_rgb(0x28, 0x28, 0x28), 12.0)),
                (Some("Apple Music"), Some(url)) if matches!(parts.kind, "article" | "link") => crate::embed_view::apple_music_embed(url).map(|(src, h)| (src, h, 660.0, Color32::from_rgb(0x1c, 0x1c, 0x1e), 10.0)),
                _ => None,
            };
            if let Some((src, height, max_w, bg, rounding)) = music.filter(|_| cards) {
                gap(ui);
                self.music_card(ui, m, idx, e, &parts, src, vec2(ui.available_width().min(max_w), height), bg, rounding, actions);
                continue;
            }
            if parts.inline(e) {
                gap(ui);
                self.inline_media(ui, m, idx, e, &parts, hidden, actions);
                continue;
            }
            let empty = e.title.is_none() && e.description.is_none() && e.fields.is_empty() && e.author.is_none() && e.footer.is_none() && e.provider.is_none() && parts.image.is_none() && parts.thumbnail.is_none() && parts.video.is_none();
            if !cards || empty {
                continue;
            }
            gap(ui);
            self.embed_card(ui, m, idx, e, &parts, &extras, hidden, can_suppress, actions);
        }
        if shown > 0 && m.components.is_empty() && m.reactions.is_empty() {
            ui.add_space(2.0);
        }
    }

    /// A media-only embed: the picture, GIF or video itself.
    #[allow(clippy::too_many_arguments)]
    fn inline_media(&self, ui: &mut Ui, m: &Message, idx: usize, e: &Embed, parts: &Parts, hidden: bool, actions: &mut Vec<UiAction>) {
        let (max_w, max_h) = parts.max_media(e);
        if hidden {
            let Some(media) = parts.video.or(parts.image).or(parts.thumbnail) else { return };
            let (dw, dh) = dims(media, (400.0, 300.0));
            let (w, h) = fit(dw, dh, max_w, max_h);
            let (rect, resp) = ui.allocate_exact_size(vec2(w, h), Sense::click());
            ui.painter().rect_filled(rect, 8.0, spoiler_colors(&self.theme).0);
            if let Some(still) = parts.poster.clone().or_else(|| parts.image.map(media_url)).filter(|u| u.contains("discordapp.")) {
                egui::Image::new(blurred(&still)).rounding(8.0).paint_at(ui, rect);
            }
            spoiler_tag(ui, rect, resp.hovered());
            if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                actions.push(UiAction::Reveal(m.id, SPOILER_KEY + idx));
            }
            return;
        }
        if parts.kind == "gifv" {
            let Some(media) = e.thumbnail.as_ref().or(e.image.as_ref()).or(e.video.as_ref()) else { return };
            let (dw, dh) = dims(media, (400.0, 300.0));
            let (w, h) = fit(dw, dh, max_w, max_h);
            let still = media_sized(ui, media, w, h);
            // GIF embeds are looping MP4 clips: play the decoded frames
            // (still thumbnail until they're ready). Real GIFs play as GIFs.
            // While the clip loads, only the still shows: the GIF file some
            // providers (Tenor, Giphy) also give as the thumbnail is megabytes
            // to fetch and decode, for a picture the clip replaces a moment
            // later. It plays only if the clip can't.
            let video = e.video_url();
            let url = match video.as_deref() {
                Some(v) if !crate::video::failed(v) => crate::video::current_frame(ui.ctx(), v, super::animating()).unwrap_or_else(|| still.clone()),
                _ => super::animated_or_still(ui, e.gif_url().as_deref(), &still, vec2(w, h)),
            };
            let r = ui.add(egui::Image::new(url).fit_to_exact_size(vec2(w, h)).rounding(8.0).sense(Sense::click()));
            super::note_media(ui, &r, &e.gif_url().unwrap_or_else(|| still.clone()), e.url.as_deref().unwrap_or(&media.url));
            if r.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                let image = e.gif_url().unwrap_or_else(|| still.clone());
                let link = e.url.clone().unwrap_or_else(|| media.url.clone());
                actions.push(UiAction::View(crate::features::MediaView { image, video, link, size: Some((dw, dh)) }));
            }
            return;
        }
        if parts.video.is_some() {
            self.embed_video(ui, m, idx, e, parts, max_w, max_h, 8.0, actions);
        } else if let Some(img) = parts.image {
            self.embed_image(ui, img, max_w, max_h, 8.0, actions);
        }
    }

    /// One picture, fitted; a click opens the viewer.
    fn embed_image(&self, ui: &mut Ui, img: &EmbedMedia, max_w: f32, max_h: f32, rounding: f32, actions: &mut Vec<UiAction>) {
        let (dw, dh) = dims(img, (400.0, 300.0));
        let (w, h) = fit(dw, dh, max_w.min(ui.available_width()), max_h);
        let url = media_url(img);
        let shown = media_sized(ui, img, w, h);
        let r = super::media_image(ui, super::anim(&shown), vec2(w, h), rounding, img.placeholder.as_deref());
        super::note_media(ui, &r, &url, &img.url);
        if r.on_hover_cursor(CursorIcon::PointingHand).clicked() {
            actions.push(UiAction::View(crate::features::MediaView { image: url, video: None, link: img.url.clone(), size: Some((dw, dh)) }));
        }
    }

    /// An embed's video: RustCord's player when Discord proxies the file,
    /// otherwise the poster with Discord's play pill, which swaps in the
    /// provider's player.
    #[allow(clippy::too_many_arguments)]
    fn embed_video(&self, ui: &mut Ui, m: &Message, idx: usize, e: &Embed, parts: &Parts, max_w: f32, max_h: f32, rounding: f32, actions: &mut Vec<UiAction>) {
        let Some(v) = parts.video else { return };
        let (dw, dh) = dims(v, (1280.0, 720.0));
        let (w, h) = fit(dw, dh, max_w.min(ui.available_width()), max_h);
        // Discord never lets a player get smaller than 150 × 144.
        let size = vec2(w.max(150.0).min(ui.available_width()), h.max(144.0));
        if let Some(file) = v.proxy_url.as_deref().filter(|p| !p.is_empty()) {
            self.video_box(ui, file, parts.poster.as_deref(), size, rounding, actions);
            return;
        }
        let provider = e.provider.as_ref().map(|p| p.name.as_str());
        let key = (m.id, idx);
        let (rect, _) = ui.allocate_exact_size(size, Sense::hover());
        ui.painter().rect_filled(rect, rounding, Color32::BLACK);
        if self.embed_playing(key) {
            self.report_player(ui, key, rect);
            return;
        }
        if let Some(p) = &parts.poster {
            super::paint_cover(ui, rect, p, Rounding::same(rounding));
        }
        let src = crate::embed_view::player_src(provider, &v.url);
        let (play, open) = play_pill(ui, rect.center(), ui.id().with(("embed_play", m.id.0, idx)), src.is_some(), e.url.is_some());
        if let (true, Some(src)) = (play, src) {
            actions.push(UiAction::PlayEmbed { key, channel: m.channel_id, src, bg: Color32::BLACK });
        }
        if let (true, Some(url)) = (open, &e.url) {
            actions.push(UiAction::OpenUrl(url.clone()));
        }
    }

    /// Is the provider's player open (or opening) for this embed?
    fn embed_playing(&self, key: crate::embed_view::Key) -> bool {
        self.embed_view.as_ref().is_some_and(|v| v.playing.is_some_and(|(k, _)| k == key)) ||self.embed_request.as_ref().is_some_and(|r| r.key == key)
    }

    /// Tell the app where this frame's player box is (it moves the webview
    /// there after the frame), and whether anything is drawn over it.
    fn report_player(&self, ui: &Ui, key: crate::embed_view::Key, rect: Rect) {
        let on_top = [rect.center(), rect.left_top() + vec2(2.0, 2.0), rect.right_bottom() - vec2(2.0, 2.0)]
            .iter()
            .all(|p| !ui.clip_rect().contains(*p) || ui.ctx().layer_id_at(*p).map_or(true, |l| l == ui.layer_id()));
        let place = crate::app::PlayerPlace { key, rect, clip: ui.clip_rect(), on_top, pass: ui.ctx().cumulative_pass_nr() };
        ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new("embed_view_place"), place));
    }

    /// A Spotify / Apple Music link: a card the size of the service's player
    /// (cover, title, artist) that becomes the real player when clicked. The
    /// player is only loaded on that click, so music links cost nothing until
    /// you play one.
    #[allow(clippy::too_many_arguments)]
    fn music_card(&self, ui: &mut Ui, m: &Message, idx: usize, e: &Embed, parts: &Parts, src: String, size: Vec2, bg: Color32, rounding: f32, actions: &mut Vec<UiAction>) {
        let key = (m.id, idx);
        let (rect, resp) = ui.allocate_exact_size(size, Sense::click());
        let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
        ui.painter().rect_filled(rect, rounding, bg);
        if self.embed_playing(key) {
            self.report_player(ui, key, rect);
            return;
        }
        if resp.hovered() {
            hint_player(ui.ctx());
        }
        let compact = size.y <= 100.0;
        let pad = if compact { 8.0 } else { 16.0 };
        let art = if compact { size.y - 16.0 } else { 120.0 };
        let art_rect = Rect::from_min_size(rect.min + vec2(pad, pad), vec2(art, art));
        if let Some(cover) = parts.thumbnail.or(parts.image) {
            super::paint_cover(ui, art_rect, &media_sized(ui, cover, art, art), Rounding::same(if compact { 6.0 } else { 8.0 }));
        } else {
            ui.painter().rect_filled(art_rect, 6.0, crate::style::rgba(255, 255, 255, 20));
        }
        let x = art_rect.right() + 12.0;
        let text = ui.painter_at(Rect::from_min_max(pos2(x, rect.top()), pos2(rect.right() - 56.0, rect.bottom())));
        let mid = if compact { rect.center().y } else { art_rect.top() + 36.0 };
        let provider = e.provider.as_ref().map(|p| p.name.as_str()).unwrap_or("");
        text.text(pos2(x, mid - 22.0), Align2::LEFT_CENTER, provider, FontId::proportional(11.0), crate::style::rgba(255, 255, 255, 150));
        if let Some(title) = &e.title {
            super::paint_text_emoji(ui, &text, pos2(x, mid - 4.0), title, strong(14.0), Color32::WHITE);
        }
        if let Some(d) = e.description.as_deref().and_then(|d| d.lines().next()) {
            super::paint_text_emoji(ui, &text, pos2(x, mid + 15.0), d, FontId::proportional(12.0), crate::style::rgba(255, 255, 255, 170));
        }
        if !compact {
            ui.painter().text(pos2(rect.left() + pad, art_rect.bottom() + 24.0), Align2::LEFT_CENTER, format!("Press play to load the {provider} player"), FontId::proportional(13.0), crate::style::rgba(255, 255, 255, 120));
        }
        // The service's round play button.
        let c = pos2(rect.right() - 32.0, if compact { rect.center().y } else { art_rect.center().y });
        ui.painter().circle_filled(c, if resp.hovered() { 17.0 } else { 16.0 }, Color32::WHITE);
        ui.painter().text(c + vec2(1.0, 0.0), Align2::CENTER_CENTER, icon::PLAY, icon_font(14.0), Color32::BLACK);
        // Open in the browser, top right.
        let open = Rect::from_center_size(pos2(rect.right() - 14.0, rect.top() + 14.0), vec2(20.0, 20.0));
        let open_resp = ui.interact(open, ui.id().with(("music_open", m.id.0, idx)), Sense::click());
        ui.painter().text(open.center(), Align2::CENTER_CENTER, EXTERNAL, icon_font(12.0), crate::style::rgba(255, 255, 255, if open_resp.hovered() { 255 } else { 140 }));
        if let (true, Some(url)) = (open_resp.on_hover_cursor(CursorIcon::PointingHand).on_hover_text("Open in Browser").clicked(), &e.url) {
            actions.push(UiAction::OpenUrl(url.clone()));
        } else if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
            actions.push(UiAction::PlayEmbed { key, channel: m.channel_id, src, bg });
        }
    }

    /// Discord's video player box: poster and a round play button, then the
    /// playing picture with its controls (shown while hovered or paused).
    pub(super) fn video_box(&self, ui: &mut Ui, url: &str, poster: Option<&str>, size: Vec2, rounding: f32, actions: &mut Vec<UiAction>) {
        let (rect, resp) = ui.allocate_exact_size(size, Sense::click());
        let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
        ui.painter().rect_filled(rect, rounding, Color32::BLACK);
        let player = self.video_player.as_ref().filter(|p| p.url == url);
        // Nothing but the black box to show yet?
        let mut bare = true;
        match player.and_then(|p| p.texture.as_ref()) {
            Some(tex) => {
                let ts = tex.size_vec2();
                let scale = (rect.width() / ts.x).min(rect.height() / ts.y);
                egui::Image::from_texture(tex).rounding(rounding).paint_at(ui, Rect::from_center_size(rect.center(), ts * scale));
                bare = false;
            }
            None => {
                if let Some(p) = poster {
                    let image = egui::Image::new(p).rounding(rounding);
                    bare = !matches!(image.load_for_size(ui.ctx(), rect.size()), Ok(egui::load::TexturePoll::Ready { .. }));
                    image.paint_at(ui, rect);
                }
            }
        }
        self.video_overlay(ui, rect, &resp, url, rounding, bare, actions);
    }

    /// The player's buttons over `rect` (shared by the chat and full screen),
    /// as Discord's: a round play button in the middle until it plays, and a
    /// 32 px bar of controls at the bottom. `bare`: no picture under them.
    #[allow(clippy::too_many_arguments)]
    pub(super) fn video_overlay(&self, ui: &mut Ui, rect: Rect, resp: &Response, url: &str, rounding: f32, bare: bool, actions: &mut Vec<UiAction>) {
        let painter = ui.painter_at(rect);
        let centre_button = |hovered: bool| {
            // Discord's is black at 60 %, which would vanish on a black box.
            let fill = if bare { crate::style::rgba(255, 255, 255, if hovered { 46 } else { 31 }) } else { Color32::from_black_alpha(if hovered { 200 } else { 153 }) };
            painter.circle_filled(rect.center(), 24.0, fill);
            play_triangle(&painter, rect.center(), 24.0, Color32::WHITE);
        };
        let Some(p) = self.video_player.as_ref().filter(|p| p.url == url) else {
            centre_button(resp.hovered());
            if resp.clone().on_hover_cursor(CursorIcon::PointingHand).clicked() {
                actions.push(UiAction::VideoToggle(url.to_string()));
            }
            return;
        };
        let st = p.state();
        if let Some(err) = &st.error {
            painter.rect_filled(rect, rounding, Color32::from_black_alpha(170));
            painter.text(rect.center() - vec2(0.0, 10.0), Align2::CENTER_CENTER, err, FontId::proportional(13.0), Color32::WHITE);
            painter.text(rect.center() + vec2(0.0, 12.0), Align2::CENTER_CENTER, "Click to open it in your browser", FontId::proportional(12.0), crate::style::rgba(255, 255, 255, 170));
            if resp.clone().on_hover_cursor(CursorIcon::PointingHand).clicked() {
                actions.push(UiAction::OpenUrl(url.to_string()));
            }
            return;
        }
        if st.loading {
            egui::Spinner::new().size(32.0).color(Color32::WHITE).paint_at(ui, Rect::from_center_size(rect.center(), vec2(32.0, 32.0)));
        } else if !st.playing {
            centre_button(false);
        }
        let bar = Rect::from_min_max(pos2(rect.left(), rect.bottom() - 32.0), rect.max);
        // (From this box's own id: the same video can be on screen twice.)
        let id = resp.id.with("video_ctl");
        let seek_id = id.with("seek");
        let seeking = ui.ctx().is_being_dragged(seek_id);
        if ui.rect_contains_pointer(rect) || !st.playing || seeking {
            painter.rect_filled(bar, Rounding { sw: rounding, se: rounding, nw: 0.0, ne: 0.0 }, Color32::from_black_alpha(153));
            // 32 px buttons with white 24 px icons: play at the far left,
            // volume and full screen at the far right.
            let button = |ui: &mut Ui, left: f32, key: &str, tip: &str| -> (egui::Pos2, bool) {
                let r = Rect::from_min_size(pos2(left, bar.top()), vec2(32.0, 32.0));
                let b = ui.interact(r, id.with(key), Sense::click());
                (r.center(), b.on_hover_cursor(CursorIcon::PointingHand).on_hover_text(tip).clicked())
            };
            let (c, clicked) = button(ui, bar.left(), "play", if st.playing { "Pause" } else { "Play" });
            if st.playing {
                pause_bars(&painter, c, 24.0, Color32::WHITE);
            } else {
                play_triangle(&painter, c, 24.0, Color32::WHITE);
            }
            if clicked {
                actions.push(UiAction::VideoToggle(url.to_string()));
            }
            let (c, clicked) = button(ui, bar.right() - 32.0, "full", if p.fullscreen { "Exit Full Screen" } else { "Full Screen" });
            fullscreen_brackets(&painter, c, 24.0, Color32::WHITE);
            if clicked {
                actions.push(UiAction::VideoFullscreen);
            }
            let (c, clicked) = button(ui, bar.right() - 64.0, "mute", if p.muted { "Unmute" } else { "Mute" });
            painter.text(c, Align2::CENTER_CENTER, if p.muted { icon::MUTE } else { icon::SPEAK }, icon_font(18.0), Color32::WHITE);
            if clicked {
                actions.push(UiAction::VideoMute);
            }
            // "0:01 / 0:36" after an 8 px gap: 4 px around the text, 2 px
            // around the slash. Left out where the box is too narrow for it.
            let total = st.duration.map(crate::video_player::fmt_time).unwrap_or_else(|| "-:--".into());
            let mut x = bar.left() + 32.0 + 8.0 + 4.0;
            let parts = [crate::video_player::fmt_time(st.position), "/".to_string(), total].map(|s| painter.layout_no_wrap(s, crate::style::medium(12.0), Color32::WHITE));
            let time_w = parts.iter().map(|g| g.size().x).sum::<f32>() + 4.0;
            if x + time_w + 4.0 <= bar.right() - 64.0 {
                for (i, g) in parts.into_iter().enumerate() {
                    let w = g.size().x;
                    painter.galley(pos2(x, bar.center().y - g.size().y / 2.0), g, Color32::WHITE);
                    x += w + if i < 2 { 2.0 } else { 4.0 };
                }
            } else {
                x = bar.left() + 32.0;
            }
            // Seek bar in what is left (7 px either side): a 6 px rail with
            // round ends, blurple up to the position, a knob on hover.
            let rail = Rect::from_min_max(pos2(x + 7.0, bar.center().y - 3.0), pos2(bar.right() - 64.0 - 7.0, bar.center().y + 3.0));
            if rail.width() > 24.0 {
                let sr = ui.interact(rail.expand2(vec2(0.0, 9.0)), seek_id, Sense::click_and_drag());
                let frac = match st.duration {
                    Some(d) if d > 0.0 => (st.position / d).clamp(0.0, 1.0) as f32,
                    _ => 0.0,
                };
                let at = |x: f32| ((x - rail.left()) / rail.width()).clamp(0.0, 1.0);
                let shown = match sr.interact_pointer_pos().filter(|_| sr.dragged()) {
                    Some(pos) => at(pos.x),
                    None => frac,
                };
                painter.rect_filled(rail, 3.0, crate::style::rgba(201, 202, 206, 77));
                let filled = Rect::from_min_max(rail.min, pos2(rail.left() + rail.width() * shown, rail.max.y));
                painter.rect_filled(filled, 3.0, BRAND);
                if sr.hovered() || sr.dragged() {
                    painter.circle_filled(pos2(filled.right(), rail.center().y), 6.0, Color32::WHITE);
                }
                if sr.clicked() || sr.drag_stopped() {
                    if let Some(pos) = sr.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())) {
                        actions.push(UiAction::VideoSeek(url.to_string(), at(pos.x)));
                    }
                }
                sr.on_hover_cursor(CursorIcon::PointingHand);
            }
        }
        // A click on the picture itself plays / pauses.
        if resp.clicked() && resp.interact_pointer_pos().is_some_and(|pos| !bar.contains(pos)) {
            actions.push(UiAction::VideoToggle(url.to_string()));
        }
    }

    /// The playing video filling the window (the player's full-screen
    /// button; Esc leaves).
    pub fn video_fullscreen_ui(&mut self, ctx: &egui::Context) {
        let Some(url) = self.video_player.as_ref().filter(|p| p.fullscreen).map(|p| p.url.clone()) else { return };
        if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
            if let Some(p) = &mut self.video_player {
                p.fullscreen = false;
            }
            return;
        }
        let screen = ctx.screen_rect();
        let mut actions = Vec::new();
        egui::Area::new(egui::Id::new("video_fullscreen")).order(egui::Order::Tooltip).fixed_pos(screen.min).show(ctx, |ui| {
            let (rect, resp) = ui.allocate_exact_size(screen.size(), Sense::click());
            ui.painter().rect_filled(rect, 0.0, Color32::BLACK);
            let tex = self.video_player.as_ref().and_then(|p| p.texture.as_ref());
            if let Some(tex) = tex {
                let ts = tex.size_vec2();
                let scale = (rect.width() / ts.x).min(rect.height() / ts.y);
                egui::Image::from_texture(tex).paint_at(ui, Rect::from_center_size(rect.center(), ts * scale));
            }
            self.video_overlay(ui, rect, &resp, &url, 0.0, tex.is_none(), &mut actions);
        });
        for a in actions {
            self.apply_action(a);
        }
    }

    /// One rich embed card.
    #[allow(clippy::too_many_arguments)]
    fn embed_card(&self, ui: &mut Ui, m: &Message, idx: usize, e: &Embed, parts: &Parts, extras: &[&EmbedMedia], hidden: bool, can_suppress: bool, actions: &mut Vec<UiAction>) {
        let t = &self.theme;
        // No colour, or white, is the default grey bar.
        let bar = e.color.filter(|c| *c != 0xffffff).map(|c| Color32::from_rgb((c >> 16) as u8, (c >> 8) as u8, c as u8)).unwrap_or(overlay(0.2));
        let (max_mw, max_mh) = parts.max_media(e);
        // Media: a video, a gallery, or one picture.
        let gallery = parts.video.is_none() && parts.image.is_some() && !extras.is_empty();
        let has_media = parts.video.is_some() || parts.image.is_some();
        // The 80 px thumbnail shows when there is no media (and next to a
        // rich embed's picture).
        let thumb = parts.thumbnail.filter(|_| !has_media || matches!(parts.kind, "rich" | "audio") && parts.video.is_none());
        // Card width: as wide as its media when that is big enough.
        let mut max_w = GRID_W + 5.0;
        if let Some(o) = parts.image.or(parts.video) {
            let (dw, dh) = dims(o, (400.0, 300.0));
            let (w, _) = fit(dw, dh, max_mw, max_mh);
            if parts.kind == "video" || w >= 300.0 {
                max_w = w.max(if parts.video.is_some() { 150.0 } else { 0.0 }) + 32.0;
            } else if parts.kind == "rich" && gallery {
                max_w = 520.0;
            }
        }
        let width = ui.available_width().min(max_w);
        let mut local = Vec::new();
        // Discord: --background-surface-high, or --background-mod-subtle over a
        // client theme; 4 px corners.
        let frame = Frame::none()
            .fill(if t.gradient.is_some() { t.bg_hover } else { t.surface_high })
            .stroke(Stroke::new(1.0_f32, t.border_subtle))
            .rounding(4.0)
            // Discord: 2 px of grid padding (+1 border) above the first part's 8 px margin.
            .inner_margin(Margin { left: 16.0, right: 17.0, top: 3.0, bottom: 17.0 })
            .show(ui, |ui| {
                ui.set_max_width(width - 33.0);
                ui.spacing_mut().item_spacing.y = 0.0;
                let inner_w = ui.available_width();
                let actions = &mut local;
                // Footer: icon, text • timestamp (12 px medium, wraps).
                let footer = e.footer.as_ref().filter(|f| !f.text.is_empty());
                let footer_icon = footer.and_then(|f| f.proxy_icon_url.clone().or_else(|| f.icon_url.clone())).filter(|u| !u.is_empty());
                let mut footer_text = footer.map(|f| f.text.clone()).unwrap_or_default();
                if let Some(ts) = &e.timestamp {
                    let when = footer_time(ts);
                    footer_text = if footer_text.is_empty() { when } else { format!("{footer_text} • {when}") };
                }
                let footer_font = crate::style::medium(12.0);
                let footer_w = if footer_text.is_empty() { 0.0 } else { text_emoji_width(ui, &footer_text, &footer_font) + if footer_icon.is_some() { 28.0 } else { 0.0 } };
                // Like Discord's, the card is only as wide as what's in it:
                // its widest line of text, its media, its footer.
                let media_w = match parts.video.or(parts.image) {
                    Some(_) if gallery => inner_w,
                    Some(o) => {
                        let (dw, dh) = dims(o, (400.0, 300.0));
                        let w = fit(dw, dh, max_mw.min(inner_w), max_mh).0;
                        if parts.video.is_some() { w.max(150.0) } else { w }
                    }
                    None => 0.0,
                };
                let thumb_w = if thumb.is_some() { 96.0 } else { 0.0 };
                let floor = (media_w.max(footer_w.ceil()).min(inner_w) - thumb_w).max(0.0);
                ui.horizontal_top(|ui| {
                    ui.spacing_mut().item_spacing.x = 0.0;
                    let col_w = (inner_w - thumb_w).max(120.0);
                    ui.vertical(|ui| {
                        ui.set_max_width(col_w);
                        ui.set_min_width(floor.min(col_w));
                        ui.spacing_mut().item_spacing.y = 0.0;
                        self.markup_wrapped.set(false);
                        self.embed_text(ui, m, e, parts, col_w, actions);
                        // Text that wrapped fills the whole width.
                        if self.markup_wrapped.get() {
                            ui.set_min_width(col_w);
                        }
                    });
                    if let Some(th) = thumb {
                        ui.add_space(16.0);
                        ui.vertical(|ui| {
                            ui.add_space(8.0);
                            let (dw, dh) = dims(th, (80.0, 80.0));
                            let (w, h) = fit(dw, dh, 80.0, 80.0);
                            let url = media_url(th);
                            let shown = media_sized(ui, th, w, h);
                            let r = super::media_image(ui, super::anim(&shown), vec2(w, h), 4.0, th.placeholder.as_deref());
                            super::note_media(ui, &r, &url, &th.url);
                            if r.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                                actions.push(UiAction::View(crate::features::MediaView { image: url, video: None, link: th.url.clone(), size: Some((dw, dh)) }));
                            }
                        });
                    }
                });

                if parts.video.is_some() {
                    ui.add_space(16.0);
                    self.embed_video(ui, m, idx, e, parts, max_mw.min(inner_w), max_mh, 4.0, actions);
                } else if let Some(img) = parts.image {
                    ui.add_space(16.0);
                    if gallery {
                        let mut all: Vec<&EmbedMedia> = vec![img];
                        all.extend_from_slice(extras);
                        all.truncate(4);
                        self.gallery(ui, &all, inner_w, max_mh, actions);
                    } else {
                        self.embed_image(ui, img, max_mw.min(inner_w), max_mh, 4.0, actions);
                    }
                }

                if !footer_text.is_empty() {
                    ui.add_space(8.0);
                    let (text, font) = (footer_text, footer_font);
                    ui.horizontal(|ui| {
                        ui.spacing_mut().item_spacing.x = 8.0;
                        if let Some(icon) = footer_icon {
                            ui.add(egui::Image::new(icon).fit_to_exact_size(vec2(20.0, 20.0)).rounding(10.0));
                        }
                        let text_w = text_emoji_width(ui, &text, &font);
                        if text_w <= ui.available_width() {
                            // (16 px lines; 20 next to the icon.)
                            let (row, _) = ui.allocate_exact_size(vec2(text_w.ceil(), if ui.min_rect().width() > 1.0 { 20.0 } else { 16.0 }), Sense::hover());
                            super::paint_text_emoji(ui, ui.painter(), pos2(row.left(), row.center().y), &text, font, t.text_normal);
                        } else {
                            ui.add(egui::Label::new(RichText::new(text).font(font).line_height(Some(16.0)).color(t.text_normal)).wrap());
                        }
                    });
                }
            });
        let r = frame.response.rect;
        if hidden {
            // A spoilered embed: covered until clicked (Discord blurs it).
            let cover = ui.interact(r, ui.id().with(("embed_spoiler", m.id.0, idx)), Sense::click());
            let (bg, bg_hover, _) = spoiler_colors(t);
            ui.painter().rect_filled(r, 4.0, if cover.hovered() { bg_hover } else { bg });
            spoiler_tag(ui, r, cover.hovered());
            if cover.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                actions.push(UiAction::Reveal(m.id, SPOILER_KEY + idx));
            }
            return;
        }
        actions.append(&mut local);
        ui.painter().rect_filled(Rect::from_min_size(r.min, vec2(4.0, r.height())), Rounding { nw: 4.0, sw: 4.0, ne: 0.0, se: 0.0 }, bar);
        // Discord's "remove all embeds" ✕, just right of the card while hovered.
        if can_suppress {
            let x = Rect::from_min_size(pos2(r.right(), r.top() - 2.0), vec2(20.0, 26.0));
            if ui.rect_contains_pointer(r.union(x)) && self.context_menu.is_none() {
                let b = ui.interact(x, ui.id().with(("embed_suppress", m.id.0, idx)), Sense::click());
                ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(11.0), if b.hovered() { t.interactive_hover } else { t.interactive_normal });
                if b.on_hover_cursor(CursorIcon::PointingHand).on_hover_text("Remove all embeds (hold Shift to skip the confirmation)").clicked() {
                    actions.push(UiAction::SuppressEmbeds { channel: m.channel_id, msg: m.id });
                }
            }
        }
    }

    /// Provider, author, title, description and fields.
    fn embed_text(&self, ui: &mut Ui, m: &Message, e: &Embed, parts: &Parts, w: f32, actions: &mut Vec<UiAction>) {
        let t = &self.theme;
        if let Some(p) = e.provider.as_ref().filter(|p| !p.name.is_empty()) {
            ui.add_space(8.0);
            // 12 px; a link is grey until hovered, then underlined.
            let id = ui.id().with(("embed_provider", m.id.0, p.name.len()));
            let hovered = p.url.is_some() && ui.ctx().read_response(id).is_some_and(|r| r.hovered());
            let mut text = RichText::new(&p.name).size(12.0).color(if hovered {
                t.interactive_hover
            } else if p.url.is_some() {
                t.interactive_normal
            } else {
                t.text_normal
            });
            if hovered {
                text = text.underline();
            }
            let r = ui.add(egui::Label::new(text).sense(Sense::hover()));
            if let Some(url) = p.url.as_deref() {
                if ui.interact(r.rect, id, Sense::click()).on_hover_cursor(CursorIcon::PointingHand).clicked() {
                    actions.push(UiAction::OpenUrl(url.to_string()));
                }
            }
        }
        if let Some(a) = e.author.as_ref().filter(|a| !a.name.is_empty()) {
            ui.add_space(8.0);
            let icon_url = a.proxy_icon_url.clone().or_else(|| a.icon_url.clone()).filter(|u| !u.is_empty());
            let name_w = text_emoji_width(ui, &a.name, &strong(14.0)).ceil() + if icon_url.is_some() { 32.0 } else { 0.0 };
            let (row, resp) = ui.allocate_exact_size(vec2(name_w.min(w), if icon_url.is_some() { 24.0 } else { 22.0 }), Sense::click());
            let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
            let mut x = row.left();
            if let Some(icon) = icon_url {
                egui::Image::new(icon).rounding(12.0).paint_at(ui, Rect::from_min_size(row.min, vec2(24.0, 24.0)));
                x += 32.0;
            }
            let p = ui.painter_at(row);
            let color = t.header_primary;
            let r = super::paint_text_emoji(ui, &p, pos2(x, row.center().y), &a.name, strong(14.0), color);
            if let Some(url) = a.url.as_deref() {
                let over = resp.hover_pos().is_some_and(|pos| pos.x >= x && pos.x <= r.right());
                if over {
                    ui.painter().hline(r.x_range(), r.bottom() - 1.0, Stroke::new(1.0_f32, color));
                    ui.ctx().set_cursor_icon(CursorIcon::PointingHand);
                    if resp.clicked() {
                        actions.push(UiAction::OpenUrl(url.to_string()));
                    }
                }
            }
        }
        if let Some(title) = e.title.as_ref().filter(|s| !s.is_empty()) {
            ui.add_space(8.0);
            let linked = e.url.is_some();
            let color = if linked { t.text_link } else { t.header_primary };
            // (Discord's embed titles and field names are semibold, not bold.)
            self.markup_semibold.set(true);
            let r = ui.scope(|ui| self.render_markdown_with(ui, m, &format!("**{}**", title.replace("**", "")), 16.0, color, linked, actions)).response;
            self.markup_semibold.set(false);
            if let Some(url) = e.url.as_deref() {
                let click = ui.interact(r.rect, ui.id().with(("embed_title", m.id.0, title.len())), Sense::click());
                if click.hovered() {
                    // Underlined while hovered, like Discord's links.
                    ui.painter().hline(r.rect.x_range(), r.rect.bottom() - 1.0, Stroke::new(1.0_f32, color));
                }
                if click.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                    actions.push(UiAction::OpenUrl(url.to_string()));
                }
            }
        }
        // Image, video and GIF embeds have no description.
        if let Some(d) = e.description.as_ref().filter(|s| !s.is_empty() && !matches!(parts.kind, "image" | "video" | "gifv")) {
            ui.add_space(8.0);
            self.render_markdown_with(ui, m, d, 14.0, t.text_normal, false, actions);
        }
        // Fields: up to three inline ones share a row, on a 12-column grid
        // with 8 px gaps (so two are halves, three are thirds).
        let mut rows: Vec<&[discord::model::EmbedField]> = Vec::new();
        let mut i = 0;
        while i < e.fields.len() {
            let mut n = 1;
            if e.fields[i].inline {
                while n < 3 && i + n < e.fields.len() && e.fields[i + n].inline {
                    n += 1;
                }
            }
            rows.push(&e.fields[i..i + n]);
            i += n;
        }
        // Discord lays fields on a 12-column grid that is as wide as the
        // card's content: columns sized by the widest field of a shared row,
        // or wider when the text above (or a wrapped line) is.
        let field_w = |f: &discord::model::EmbedField| {
            self.markup_semibold.set(true);
            let name = self.markdown_width(ui, m, &f.name, 14.0, true);
            self.markup_semibold.set(false);
            name.max(self.markdown_width(ui, m, &f.value, 14.0, false)).ceil() + 1.0
        };
        let mut grid_w = if self.markup_wrapped.get() { w } else { ui.min_rect().width() };
        for row in rows.iter().filter(|r| r.len() > 1) {
            let n = row.len() as f32;
            let widest = row.iter().map(|f| field_w(f)).fold(0.0, f32::max);
            grid_w = grid_w.max(widest * n + 8.0 * (n - 1.0));
        }
        let grid_w = grid_w.min(w);
        for row in rows {
            ui.add_space(8.0);
            if row.len() == 1 {
                self.embed_field(ui, m, &row[0], actions);
                continue;
            }
            let col = (grid_w - 8.0 * (row.len() as f32 - 1.0)) / row.len() as f32;
            ui.horizontal_top(|ui| {
                ui.spacing_mut().item_spacing.x = 8.0;
                for f in row {
                    ui.vertical(|ui| {
                        ui.set_width(col);
                        ui.spacing_mut().item_spacing.y = 0.0;
                        self.embed_field(ui, m, f, actions);
                    });
                }
            });
        }
    }

    fn embed_field(&self, ui: &mut Ui, m: &Message, f: &discord::model::EmbedField, actions: &mut Vec<UiAction>) {
        let t = &self.theme;
        if !f.name.trim().is_empty() {
            self.markup_semibold.set(true);
            self.render_markdown_with(ui, m, &format!("**{}**", f.name.replace("**", "")), 14.0, t.header_primary, false, actions);
            self.markup_semibold.set(false);
            ui.add_space(2.0);
        }
        if !f.value.trim().is_empty() {
            self.render_markdown_with(ui, m, &f.value, 14.0, t.text_normal, false, actions);
        }
    }

    /// Discord's embed gallery (2–4 pictures): two columns 4 px apart inside
    /// one rounded box `max_h` tall; with three, the first fills the left
    /// column; each is cropped to fill its cell and opens the viewer.
    fn gallery(&self, ui: &mut Ui, images: &[&EmbedMedia], w: f32, max_h: f32, actions: &mut Vec<UiAction>) {
        let gap = 4.0;
        let (rect, _) = ui.allocate_exact_size(vec2(w, max_h), Sense::hover());
        let col_w = (w - gap) / 2.0;
        let half_h = (max_h - gap) / 2.0;
        let (left, right) = (rect.left(), rect.left() + col_w + gap);
        let cell = |x: f32, row: usize, rows: usize| {
            let (y, h) = if rows == 1 { (rect.top(), max_h) } else { (rect.top() + row as f32 * (half_h + gap), half_h) };
            Rect::from_min_size(pos2(x, y), vec2(col_w, h))
        };
        // Discord's order: 1 top-left, 2 top-right, 3 bottom-left (or
        // bottom-right when there are three), 4 bottom-right.
        let cells: Vec<Rect> = match images.len() {
            2 => vec![cell(left, 0, 1), cell(right, 0, 1)],
            3 => vec![cell(left, 0, 1), cell(right, 0, 2), cell(right, 1, 2)],
            _ => vec![cell(left, 0, 2), cell(right, 0, 2), cell(left, 1, 2), cell(right, 1, 2)],
        };
        for (i, (img, r)) in images.iter().zip(cells).enumerate() {
            let near = |a: f32, b: f32| (a - b).abs() < 0.5;
            let c = |on: bool| if on { 4.0 } else { 0.0 };
            let rounding = Rounding {
                nw: c(near(r.left(), rect.left()) && near(r.top(), rect.top())),
                ne: c(near(r.right(), rect.right()) && near(r.top(), rect.top())),
                sw: c(near(r.left(), rect.left()) && near(r.bottom(), rect.bottom())),
                se: c(near(r.right(), rect.right()) && near(r.bottom(), rect.bottom())),
            };
            let url = media_url(img);
            let (nw, nh) = dims(img, (400.0, 300.0));
            let cover = (r.width() / nw.max(1.0)).max(r.height() / nh.max(1.0));
            let shown = media_sized(ui, img, nw * cover, nh * cover);
            super::paint_cover(ui, r, &super::anim(&shown), rounding);
            let resp = ui.interact(r, ui.id().with(("gallery", i, &img.url)), Sense::click());
            super::note_media(ui, &resp, &url, &img.url);
            if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                actions.push(UiAction::View(crate::features::MediaView { image: url, video: None, link: img.url.clone(), size: Some(dims(img, (400.0, 300.0))) }));
            }
        }
    }

    // ---- components -------------------------------------------------------------

    pub(super) fn components_ui(&self, ui: &mut Ui, m: &Message, comps: &[Component], actions: &mut Vec<UiAction>) {
        if !comps.is_empty() {
            // Discord: 4 px under the embeds, 6 px between rows (the column
            // adds its own 3 px to each).
            ui.add_space(1.0);
            for (i, c) in comps.iter().enumerate() {
                if i > 0 && matches!(c.kind, 1 | 3 | 5 | 6 | 7 | 8) {
                    ui.add_space(3.0);
                }
                self.component_ui(ui, m, c, actions);
            }
        }
        self.message_notes(ui, m, actions);
    }

    /// Under a message's embeds and buttons: "(edited)" when there is no
    /// text for it to follow, a failed interaction, and Discord's "Only you
    /// can see this" line with its dismiss link.
    fn message_notes(&self, ui: &mut Ui, m: &Message, actions: &mut Vec<UiAction>) {
        let t = &self.theme;
        if m.content.is_empty() && m.edited_timestamp.is_some() && m.meta.edit_history.is_empty() && !m.meta.deleted {
            ui.label(RichText::new("(edited)").size(10.0).color(t.text_muted));
        }
        if self.interaction_failed == Some(m.id) {
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 4.0;
                let (r, _) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::hover());
                ui.painter().circle_filled(r.center(), 7.0, t.danger);
                ui.painter().text(r.center(), Align2::CENTER_CENTER, "!", strong(11.0), Color32::WHITE);
                ui.label(RichText::new("This interaction failed").size(12.0).color(t.danger));
            });
        }
        if m.flags & (1 << 6) != 0 {
            ui.add_space(1.0);
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 0.0;
                // Discord's eye.
                let (r, _) = ui.allocate_exact_size(vec2(20.0, 16.0), Sense::hover());
                let c = pos2(r.left() + 8.0, r.center().y);
                let col = t.text_muted;
                let eye: Vec<egui::Pos2> = (0..=16)
                    .map(|k| {
                        let a = std::f32::consts::TAU * k as f32 / 16.0;
                        pos2(c.x + 7.0 * a.cos(), c.y + 4.5 * a.sin())
                    })
                    .collect();
                ui.painter().add(egui::Shape::closed_line(eye, Stroke::new(1.3_f32, col)));
                ui.painter().circle_filled(c, 2.2, col);
                ui.label(RichText::new("Only you can see this • ").size(12.0).color(t.text_muted));
                let id = ui.id().with(("dismiss", m.id.0));
                let hovered = ui.ctx().read_response(id).is_some_and(|r| r.hovered());
                let mut text = RichText::new("Dismiss message").size(12.0).color(t.text_link);
                if hovered {
                    text = text.underline();
                }
                let r = ui.add(egui::Label::new(text).sense(Sense::hover()));
                if ui.interact(r.rect, id, Sense::click()).on_hover_cursor(CursorIcon::PointingHand).clicked() {
                    actions.push(UiAction::Dismiss { channel: m.channel_id, msg: m.id });
                }
            });
        }
    }

    fn component_ui(&self, ui: &mut Ui, m: &Message, c: &Component, actions: &mut Vec<UiAction>) {
        let t = &self.theme;
        match c.kind {
            // Action row.
            1 => {
                ui.horizontal_wrapped(|ui| {
                    ui.spacing_mut().item_spacing = vec2(8.0, 8.0);
                    for child in &c.components {
                        self.component_ui(ui, m, child, actions);
                    }
                });
            }
            2 => {
                if let Some(a) = component_button(ui, m, c, self.interaction_state(m.id, c.custom_id.as_deref())) {
                    actions.push(a);
                }
            }
            3 | 5 | 6 | 7 | 8 => self.select_menu(ui, m, c, actions),
            // Section: text on the left, a thumbnail / button on the right.
            9 => {
                ui.add_space(4.0);
                let w = ui.available_width().min(560.0);
                ui.horizontal_top(|ui| {
                    let side = match c.accessory.as_deref().map(|a| a.kind) {
                        Some(11) => 85.0 + 16.0,
                        Some(2) => 140.0,
                        _ => 0.0,
                    };
                    ui.vertical(|ui| {
                        ui.set_width((w - side).max(120.0));
                        for child in &c.components {
                            self.component_ui(ui, m, child, actions);
                        }
                    });
                    if let Some(acc) = c.accessory.as_deref() {
                        ui.add_space(16.0);
                        ui.vertical(|ui| self.component_ui(ui, m, acc, actions));
                    }
                });
            }
            10 => {
                if let Some(text) = c.content.as_deref() {
                    self.render_markdown_with(ui, m, text, 16.0, t.text_normal, false, actions);
                }
            }
            11 => {
                if let Some(media) = &c.media {
                    let url = media.best_url();
                    let r = ui.add(egui::Image::new(super::anim(&url)).fit_to_exact_size(vec2(85.0, 85.0)).rounding(8.0).sense(Sense::click()));
                    super::note_media(ui, &r, &url, &media.url);
                    if r.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                        let size = media.width.zip(media.height).map(|(w, h)| (w as f32, h as f32));
                        actions.push(UiAction::View(crate::features::MediaView { image: url, video: None, link: media.url.clone(), size }));
                    }
                }
            }
            12 => {
                ui.add_space(4.0);
                let w = ui.available_width().min(520.0);
                let items: Vec<EmbedMedia> = c
                    .items
                    .iter()
                    .map(|i| EmbedMedia { url: i.media.url.clone(), proxy_url: i.media.proxy_url.clone(), width: i.media.width, height: i.media.height, placeholder: None })
                    .collect();
                if items.len() == 1 {
                    let img = &items[0];
                    let (iw, ih) = fit(img.width.unwrap_or(520) as f32, img.height.unwrap_or(300) as f32, w, 350.0);
                    let url = media_url(img);
                    let shown = media_sized(ui, img, iw, ih);
                    let r = super::media_image(ui, super::anim(&shown), vec2(iw, ih), 8.0, img.placeholder.as_deref());
                    super::note_media(ui, &r, &url, &img.url);
                    if r.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                        let size = img.width.zip(img.height).map(|(w, h)| (w as f32, h as f32));
                        actions.push(UiAction::View(crate::features::MediaView { image: url, video: None, link: img.url.clone(), size }));
                    }
                } else {
                    let refs: Vec<&EmbedMedia> = items.iter().collect();
                    self.gallery(ui, &refs[..refs.len().min(4)], w, (w * 0.6).round(), actions);
                }
            }
            13 => {
                if let Some(f) = &c.file {
                    let name = f.url.rsplit('/').next().unwrap_or("file").to_string();
                    Frame::none().fill(t.surface_high).stroke(Stroke::new(1.0_f32, t.border_subtle)).rounding(8.0).inner_margin(Margin::same(12.0)).show(ui, |ui| {
                        ui.horizontal(|ui| {
                            ui.label(RichText::new(crate::style::icon::FILE).font(crate::style::icon_font(22.0)).color(t.interactive_normal));
                            ui.label(RichText::new(name).size(15.0).color(t.text_link));
                        });
                    });
                }
            }
            // Separator: a gap, optionally with a line.
            14 => {
                let gap = if c.spacing == Some(2) { 16.0 } else { 8.0 };
                ui.add_space(gap);
                if c.divider.unwrap_or(true) {
                    let w = ui.available_width().min(560.0);
                    let y = ui.cursor().top();
                    ui.painter().hline(ui.cursor().left()..=ui.cursor().left() + w, y, Stroke::new(1.0_f32, t.border_subtle));
                }
                ui.add_space(gap);
            }
            // Container: a card with an optional accent bar, like an embed.
            17 => {
                ui.add_space(4.0);
                let w = ui.available_width().min(600.0);
                let frame = Frame::none()
                    .fill(t.surface_high)
                    .stroke(Stroke::new(1.0_f32, t.border_subtle))
                    .rounding(8.0)
                    .inner_margin(Margin { left: if c.accent_color.is_some() { 20.0 } else { 16.0 }, right: 16.0, top: 16.0, bottom: 16.0 })
                    .show(ui, |ui| {
                        ui.set_width(w - 36.0);
                        ui.spacing_mut().item_spacing.y = 4.0;
                        for child in &c.components {
                            self.component_ui(ui, m, child, actions);
                        }
                    });
                if let Some(col) = c.accent_color {
                    let r = frame.response.rect;
                    let bar = Color32::from_rgb((col >> 16) as u8, (col >> 8) as u8, col as u8);
                    ui.painter().rect_filled(Rect::from_min_size(r.min, vec2(4.0, r.height())), Rounding { nw: 8.0, sw: 8.0, ne: 0.0, se: 0.0 }, bar);
                }
            }
            _ => {}
        }
    }

    /// A select menu like Discord's: a 400 × 40 box with the placeholder (or
    /// the default pick) and a chevron; clicking drops the option list
    /// (above when there is no room below); choosing one sends it to the app.
    fn select_menu(&self, ui: &mut Ui, m: &Message, c: &Component, actions: &mut Vec<UiAction>) {
        let t = &self.theme;
        let w = ui.available_width().min(400.0);
        let custom_id = c.custom_id.clone().unwrap_or_default();
        let waiting = self.interaction_state(m.id, Some(&custom_id));
        let off = c.disabled || waiting.is_some();
        let fade = if off { 0.5 } else { 1.0 };
        let current = c.options.iter().find(|o| o.default);
        let label = current.map(|o| o.label.clone()).or_else(|| c.placeholder.clone()).unwrap_or_else(|| "Make a selection".into());
        let open = !off && self.open_select.as_ref().is_some_and(|(msg, id)| *msg == m.id && *id == custom_id);
        let (rect, resp) = ui.allocate_exact_size(vec2(w, 40.0), if off { Sense::hover() } else { Sense::click() });
        let border = if open { BRAND } else { overlay(0.2) };
        ui.painter().rect(rect, 8.0, Color32::from_black_alpha(31).gamma_multiply(fade), Stroke::new(1.0_f32, border.gamma_multiply(fade)));
        if waiting == Some(true) {
            super::interactions::loading_dots(ui, rect.center(), t.text_normal);
        } else {
            let mut x = rect.left() + 12.0;
            if let Some(url) = current.and_then(|o| o.emoji.as_ref()).and_then(emoji_url) {
                egui::Image::new(url).tint(Color32::WHITE.gamma_multiply(fade)).paint_at(ui, Rect::from_center_size(pos2(x + 11.0, rect.center().y), vec2(22.0, 22.0)));
                x += 30.0;
            }
            let fg = if current.is_some() { t.text_normal } else { t.text_muted };
            let p = ui.painter_at(Rect::from_min_max(pos2(x, rect.top()), pos2(rect.right() - 34.0, rect.bottom())));
            super::paint_text_emoji(ui, &p, pos2(x, rect.center().y), &label, crate::style::medium(16.0), fg.gamma_multiply(fade));
        }
        // Discord's chevron (18 px box; up while open).
        let cc = pos2(rect.right() - 17.0, rect.center().y);
        let dy = if open { -3.0 } else { 3.0 };
        let chevron = vec![pos2(cc.x - 5.0, cc.y - dy), pos2(cc.x, cc.y + dy), pos2(cc.x + 5.0, cc.y - dy)];
        ui.painter().add(egui::Shape::line(chevron, Stroke::new(1.8_f32, t.interactive_normal.gamma_multiply(fade))));
        let resp = resp.on_hover_cursor(if off { CursorIcon::NotAllowed } else { CursorIcon::PointingHand });
        if resp.clicked() {
            actions.push(UiAction::ToggleSelect { msg: m.id, custom_id: custom_id.clone() });
        }
        if !open {
            return;
        }
        // The list: 8 px from the box, at most 282 px tall.
        let row_h = |o: &discord::model::SelectOption| if o.description.is_some() { 56.0 } else { 40.0 };
        let list_h = (c.options.iter().map(row_h).sum::<f32>().max(40.0) + 2.0).min(282.0);
        let below = rect.bottom() + 8.0 + list_h <= ui.ctx().screen_rect().bottom() - 8.0;
        let pos = if below { pos2(rect.left(), rect.bottom() + 8.0) } else { pos2(rect.left(), rect.top() - 8.0 - list_h) };
        let area = egui::Area::new(egui::Id::new(("select_list", m.id.0, &custom_id))).order(egui::Order::Foreground).fixed_pos(pos).show(ui.ctx(), |ui| {
            Frame::none()
                .fill(t.bg_floating)
                .stroke(Stroke::new(1.0_f32, t.border_subtle))
                .rounding(8.0)
                .shadow(egui::epaint::Shadow { offset: vec2(0.0, 12.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(61) })
                .show(ui, |ui| {
                    ui.set_width(w - 2.0);
                    ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                    egui::ScrollArea::vertical().max_height(list_h - 2.0).show(ui, |ui| {
                        ui.set_width(w - 2.0);
                        if c.options.is_empty() {
                            let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 40.0), Sense::hover());
                            ui.painter().text(r.left_center() + vec2(12.0, 0.0), Align2::LEFT_CENTER, "Pick in Discord (user, role and channel menus aren't supported yet)", FontId::proportional(13.0), t.text_muted);
                        }
                        for o in &c.options {
                            let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h(o)), Sense::click());
                            if resp.hovered() || o.default {
                                ui.painter().rect_filled(r, 0.0, t.bg_hover);
                            }
                            let mut x = r.left() + 8.0;
                            if let Some(url) = o.emoji.as_ref().and_then(emoji_url) {
                                egui::Image::new(url).paint_at(ui, Rect::from_center_size(pos2(x + 11.0, r.center().y), vec2(22.0, 22.0)));
                                x += 30.0;
                            }
                            let p = ui.painter_at(Rect::from_min_max(pos2(x, r.top()), pos2(r.right() - if o.default { 36.0 } else { 8.0 }, r.bottom())));
                            let ty = if o.description.is_some() { r.top() + 17.0 } else { r.center().y };
                            super::paint_text_emoji(ui, &p, pos2(x, ty), &o.label, strong(14.0), t.header_primary);
                            if let Some(d) = &o.description {
                                super::paint_text_emoji(ui, &p, pos2(x, r.top() + 39.0), d, FontId::proportional(14.0), t.text_muted);
                            }
                            if o.default {
                                let cc = pos2(r.right() - 20.0, r.center().y);
                                ui.painter().circle_filled(cc, 10.0, BRAND);
                                ui.painter().text(cc, Align2::CENTER_CENTER, icon::CHECK, icon_font(10.0), Color32::WHITE);
                            }
                            if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                                actions.push(UiAction::Interact { channel: m.channel_id, msg: m.id, component_type: c.kind, custom_id: custom_id.clone(), values: Some(vec![o.value.clone()]) });
                            }
                        }
                    });
                });
        });
        // A click anywhere else (not on the box, which toggles) or Esc closes it.
        let outside = area.response.clicked_elsewhere() && !resp.clicked() && !ui.rect_contains_pointer(rect);
        if outside || ui.input(|i| i.key_pressed(egui::Key::Escape)) {
            actions.push(UiAction::ToggleSelect { msg: m.id, custom_id });
        }
    }
}

/// A bot button as Discord draws it: 32 px tall, 12 px at the sides, 14 px
/// medium label, a 19 px emoji 4 px before it, an external-link mark on
/// link buttons, half faded when disabled. `waiting` is the message's
/// interaction in flight: three dots on the button that was clicked
/// (`Some(true)`), the others off until the app answers.
fn component_button(ui: &mut Ui, m: &Message, c: &Component, waiting: Option<bool>) -> Option<UiAction> {
    let style = c.style.unwrap_or(2);
    let label = c.label.clone().unwrap_or_default();
    let emoji = c.emoji.as_ref().and_then(emoji_url);
    let link = style == 5;
    let off = c.disabled || (waiting.is_some() && !link);
    let g = ui.painter().layout_no_wrap(label.clone(), crate::style::medium(14.0), Color32::PLACEHOLDER);
    let mut content_w = g.size().x;
    if emoji.is_some() {
        content_w += 19.0 + if label.is_empty() { 0.0 } else { 4.0 };
    }
    if link {
        content_w += 20.0;
    }
    let w = (content_w + 24.0).ceil().max(if label.is_empty() { 44.0 } else { 60.0 });
    let (rect, resp): (Rect, Response) = ui.allocate_exact_size(vec2(w, 32.0), if off { Sense::hover() } else { Sense::click() });
    let hovered = resp.hovered() && !off;
    let (fill, hover_fill, stroke) = match style {
        1 => (BRAND, BRAND_HOVER, crate::style::rgba(255, 255, 255, 20)),
        3 => (Color32::from_rgb(0x00, 0x86, 0x3a), Color32::from_rgb(0x01, 0x70, 0x31), crate::style::rgba(255, 255, 255, 20)),
        4 => (Color32::from_rgb(0xd2, 0x2d, 0x39), Color32::from_rgb(0xb4, 0x22, 0x2c), crate::style::rgba(255, 255, 255, 20)),
        _ => (overlay(0.12), overlay(0.2), overlay(0.04)),
    };
    let alpha = if off { 0.5 } else { 1.0 };
    ui.painter().rect(rect, 8.0, if hovered { hover_fill } else { fill }.gamma_multiply(alpha), Stroke::new(1.0_f32, stroke.gamma_multiply(alpha)));
    let fg = if matches!(style, 1 | 3 | 4) { Color32::WHITE } else { Color32::from_rgb(251, 251, 251) }.gamma_multiply(alpha);
    if waiting == Some(true) && !link {
        super::interactions::loading_dots(ui, rect.center(), Color32::WHITE);
        resp.on_hover_cursor(CursorIcon::NotAllowed);
        return None;
    }
    let mut x = rect.center().x - content_w / 2.0;
    if let Some(url) = &emoji {
        let r = Rect::from_center_size(pos2(x + 9.5, rect.center().y), vec2(19.0, 19.0));
        egui::Image::new(url.as_str()).tint(Color32::WHITE.gamma_multiply(alpha)).paint_at(ui, r);
        x += 19.0 + if label.is_empty() { 0.0 } else { 4.0 };
    }
    if !label.is_empty() {
        let gw = g.size().x;
        ui.painter().galley(pos2(x, rect.center().y - g.size().y / 2.0), g, fg);
        x += gw;
    }
    if link {
        ui.painter().text(pos2(x + 12.0, rect.center().y), Align2::CENTER_CENTER, EXTERNAL, crate::style::icon_font(13.0), fg);
    }
    let resp = if link { resp.on_hover_text(c.url.clone().unwrap_or_default()) } else { resp };
    if !resp.on_hover_cursor(if off { CursorIcon::NotAllowed } else { CursorIcon::PointingHand }).clicked() {
        return None;
    }
    if link {
        return c.url.clone().map(UiAction::OpenUrl);
    }
    Some(UiAction::Interact {
        channel: m.channel_id,
        msg: m.id,
        component_type: 2,
        custom_id: c.custom_id.clone().unwrap_or_default(),
        values: None,
    })
}