Skip to content

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

57.1 KB
Raw Blame
//! Right-hand panels: member list (live), search results; pinned popout.

use super::{format_timestamp, paint_avatar, paint_status_dot};
use crate::app::RustCord;
use crate::store::{ListItem, Store};
use crate::style::{bold, icon, icon_font};
use discord::model::{Id, Message, User};
use eframe::egui::{
    self, pos2, vec2, Align2, Color32, FontId, Frame, Margin, Order, Rect, RichText, ScrollArea, Sense, Stroke, Ui,
};

/// The boost gem's pink (Discord's GUILD_BOOSTING_PINK).
const BOOST_PINK: Color32 = Color32::from_rgb(0xff, 0x73, 0xfa);

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

impl RustCord {
    pub fn member_list_ui(&mut self, ui: &mut Ui) {
        let t = self.theme.clone();
        let Some(ch) = self.current_channel else { return };
        let Some((gid, list_id)) = self.store.list_id_for(ch) else { return };
        // Borrowed, not cloned: this runs every frame.
        let roles: &[discord::model::Role] = self.store.guilds.get(&gid).map(|g| g.guild.roles.as_slice()).unwrap_or(&[]);
        let role_name = |id: &str| -> String {
            match id {
                "online" => "Online".into(),
                "offline" => "Offline".into(),
                other => roles.iter().find(|r| r.id.to_string() == other).map(|r| r.name.clone()).unwrap_or_else(|| other.into()),
            }
        };
        let name_color = |member_roles: &[Id]| -> Color32 {
            roles
                .iter()
                .filter(|r| r.color != 0 && member_roles.contains(&r.id))
                .max_by_key(|r| r.position)
                .map(|r| rgb(r.color))
                // (Accessibility → Role Colours: only "in names" colours the list.)
                .filter(|_| super::ROLE_COLORS.load(std::sync::atomic::Ordering::Relaxed) == 0)
                .unwrap_or(t.interactive_normal)
        };

        let list = self.store.member_lists.get(&(gid, list_id));
        let crowned = self.store.crowned_owner(gid);
        let mut open: Option<(User, egui::Pos2)> = None;
        // Right-click: the member menu (moderation.rs).
        let mut menu: Option<(User, egui::Pos2)> = None;
        let mut need_more = false;
        let mut loaded_items = 0;
        ScrollArea::vertical().id_salt(("members", ch.0)).auto_shrink([false, false]).show(ui, |ui| {
            // Discord: rows exactly 44 px apart, each group heading 20 px below.
            ui.spacing_mut().item_spacing.y = 0.0;
            let Some(list) = list else {
                ui.add_space(30.0);
                ui.vertical_centered(|ui| {
                    ui.spinner();
                });
                return;
            };
            let mut offline = false;
            for item in list.items.iter() {
                match item {
                    Some(ListItem::Group { id, count }) => {
                        offline = id == "offline";
                        // The real size comes from the update's `groups` list.
                        let count = list.group_counts.get(id).copied().unwrap_or(*count);
                        // "Bot Developer — 1": 14 px medium, 16 px in.
                        ui.add_space(20.0);
                        let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 18.0), Sense::hover());
                        let p = ui.painter_at(r.with_max_x(r.right() - 8.0));
                        p.text(pos2(r.left() + 16.0, r.center().y), Align2::LEFT_CENTER, format!("{} — {}", role_name(id), count), crate::style::medium(14.0), t.channel_default);
                        ui.add_space(4.0);
                    }
                    Some(ListItem::Member { user, nick, roles: member_roles, presence, boosting_since, .. }) => {
                        let styled = self.user_in(user, Some(gid));
                        let user: &discord::model::User = &styled;
                        let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), super::dense(44.0)), Sense::click());
                        let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
                        if !ui.is_rect_visible(rect) {
                            continue;
                        }
                        let inner = rect.shrink2(vec2(8.0, 1.0));
                        // Nameplate under the row; filled in once the name's width is known.
                        let plate_slot = ui.painter().add(egui::Shape::Noop);
                        if resp.hovered() {
                            ui.painter().rect_filled(inner, 6.0, t.bg_hover);
                            self.profiles_wanted.borrow_mut().push((user.id, Some(gid)));
                        }
                        // Discord: an offline member's whole row (avatar, name, tags)
                        // is drawn at 30 % opacity, back to full while hovered.
                        let dim = offline && !resp.hovered();
                        let opacity = ui.opacity();
                        if dim {
                            ui.multiply_opacity(0.3);
                        }
                        let av = Rect::from_center_size(pos2(inner.left() + 24.0, inner.center().y), vec2(32.0, 32.0));
                        let name = nick.clone().unwrap_or_else(|| user.display_name().to_string());
                        paint_avatar(ui, av, Some(super::avatar_uri(user, 64, resp.hovered())), &name);
                        if let Some(deco) = super::decoration_uri(user, resp.hovered()) {
                            egui::Image::new(deco).paint_at(ui, av.expand(av.width() * 0.1));
                        }
                        if !dim {
                            paint_status_dot(ui, av.right_bottom() - vec2(3.0, 3.0), 5.0, if presence.on_mobile() { "mobile" } else { &presence.status }, if resp.hovered() { t.bg_hover } else { t.bg_primary });
                        }
                        let sub = super::SubLine::of(presence);
                        let painter = ui.painter_at(inner.with_max_x(inner.right() - 4.0));
                        let font = super::name_font(user, crate::style::medium(16.0));
                        let has_role_color = self.store.role_color(Some(gid), member_roles).is_some();
                        let style_color = super::name_style_colors(user).and_then(|c| c.first().copied()).map(|c| Color32::from_rgb((c >> 16) as u8, (c >> 8) as u8, c as u8));
                        let color = if has_role_color { name_color(member_roles) } else { style_color.unwrap_or_else(|| name_color(member_roles)) };
                        let y = if sub.is_some() { inner.center().y - 8.0 } else { inner.center().y };
                        let galley = painter.layout_no_wrap(name, font, color);
                        let name_w = galley.size().x;
                        painter.galley(pos2(av.right() + 12.0, y - galley.size().y / 2.0), galley, color);
                        if !dim {
                            let shapes = super::nameplate_shapes(ui, inner, 6.0, user, super::Plate::MemberList, resp.hovered(), false, Some(av.right() + 12.0 + name_w));
                            ui.painter().set(plate_slot, egui::Shape::Vec(shapes));
                        }
                        // After the name, as Discord orders them: the server tag,
                        // then the APP tag, the owner's crown and the boost gem.
                        let mut x = av.right() + 12.0 + name_w;
                        if let Some((tag, badge)) = user.server_tag() {
                            x += 4.0 + super::paint_tag_chip(ui, &painter, x + 4.0, y, &tag, badge.as_deref(), &t);
                        }
                        if let Some(right) = super::paint_bot_badge(&painter, x + 4.0, y, user, &t) {
                            x = right;
                        }
                        if crowned == Some(user.id) {
                            let crown = Rect::from_min_size(pos2(x + 4.0, y - 7.0), vec2(14.0, 14.0));
                            painter.text(crown.center(), Align2::CENTER_CENTER, icon::CROWN, icon_font(14.0), super::group_dm::CROWN);
                            if ui.rect_contains_pointer(crown) {
                                resp.clone().on_hover_text("Server Owner");
                            }
                            x = crown.right();
                        }
                        if let Some(since) = boosting_since {
                            let gem = Rect::from_min_size(pos2(x + 3.0, y - 6.0), vec2(14.0, 14.0));
                            painter.text(gem.center(), Align2::CENTER_CENTER, icon::BOOST, icon_font(14.0), BOOST_PINK);
                            if ui.rect_contains_pointer(gem) {
                                let date = chrono::DateTime::parse_from_rfc3339(since).map(|d| super::popups::long_date(d.timestamp_millis() as u64)).unwrap_or_default();
                                resp.clone().on_hover_text(format!("Server boosting since {date}"));
                            }
                        }
                        if let Some(sub) = &sub {
                            sub.paint(ui, &painter, pos2(av.right() + 12.0, inner.center().y + 9.0), t.text_muted);
                        }
                        ui.set_opacity(opacity);
                        if resp.clicked() {
                            open = Some((user.clone(), rect.left_top()));
                        }
                        if resp.secondary_clicked() {
                            menu = Some((user.clone(), resp.interact_pointer_pos().unwrap_or(rect.center())));
                        }
                    }
                    None => {
                        // Not loaded yet (outside the subscribed range).
                        ui.allocate_exact_size(vec2(ui.available_width(), super::dense(44.0)), Sense::hover());
                    }
                }
            }
            // Near the end of what RustCord has: ask Discord for the next 100.
            let loaded = list.items.len();
            loaded_items = loaded;
            let total = (list.member_count as usize).max(loaded);
            if loaded > 0 && loaded < total && ui.is_rect_visible(Rect::from_min_size(ui.cursor().min, vec2(1.0, 1.0))) {
                need_more = true;
            }
            ui.add_space(super::USER_PANEL_SPACE / 2.0);
        });
        // Only once the windows RustCord asked for are full: in a private channel
        // Discord's member_count is the whole server's, so "fewer than the
        // total" stayed true and this asked for a window more every frame —
        // and Discord ends the session (4002) when a subscription has more
        // ranges than it accepts, then again after every reconnect.
        if need_more {
            let w = self.member_windows.entry(ch).or_insert(1);
            if *w < crate::backend::MAX_MEMBER_WINDOWS && loaded_items >= *w * 100 {
                *w += 1;
                self.subscribe_members(ch);
            }
        }
        if let Some((user, at)) = open {
            self.open_profile(user, Some(gid), at - vec2(352.0, 0.0));
        }
        if let Some((user, at)) = menu {
            self.open_member_menu(gid, user, at);
        }
    }

    /// The header's Threads popout: the channel's active threads (click one to
    /// open it) and a Create button, like Discord's.
    pub fn threads_popout_ui(&mut self, ctx: &egui::Context) {
        let Some((ch, anchor, opened)) = self.threads_popout else { return };
        let t = self.theme.clone();
        let mut close = ctx.input(|i| i.key_pressed(egui::Key::Escape)) || self.current_channel != Some(ch);
        // Newest first (thread ids are their creation time).
        let mut threads: Vec<(Id, String)> = self
            .store
            .channels
            .values()
            .filter(|c| c.parent_id == Some(ch) && discord::model::channel_kind::is_thread(c.kind))
            .map(|c| (c.id, Store::channel_label(c)))
            .collect();
        threads.sort_by(|a, b| b.0.cmp(&a.0));
        let (mut open, mut create) = (None, false);
        let area = egui::Area::new(egui::Id::new("threads_popout"))
            .order(Order::Foreground)
            .pivot(Align2::RIGHT_TOP)
            .fixed_pos(anchor)
            .constrain(true)
            .show(ctx, |ui| {
                Frame::none()
                    .fill(t.bg_floating)
                    .rounding(8.0)
                    .stroke(Stroke::new(1.0_f32, t.border_subtle))
                    .shadow(egui::epaint::Shadow { offset: vec2(0.0, 8.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(140) })
                    .show(ui, |ui| {
                        ui.set_width(440.0);
                        Frame::none().inner_margin(Margin::symmetric(16.0, 12.0)).show(ui, |ui| {
                            ui.horizontal(|ui| {
                                ui.label(RichText::new(icon::THREADS).font(icon_font(16.0)).color(t.interactive_normal));
                                ui.label(bold("Threads").size(16.0).color(t.header_primary));
                                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                                    let b = egui::Button::new(bold("Create").size(14.0).color(Color32::WHITE)).fill(t.accent).rounding(8.0).min_size(vec2(64.0, 28.0));
                                    create = ui.add(b).on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
                                });
                            });
                        });
                        ui.painter().hline(ui.max_rect().x_range(), ui.cursor().top(), Stroke::new(1.0_f32, t.border_subtle));
                        ScrollArea::vertical().max_height(420.0).show(ui, |ui| {
                            Frame::none().inner_margin(12.0).show(ui, |ui| {
                                ui.set_width(416.0);
                                if threads.is_empty() {
                                    ui.add_space(24.0);
                                    ui.vertical_centered(|ui| {
                                        ui.label(bold("There are no active threads.").size(16.0).color(t.header_primary));
                                        ui.add_space(4.0);
                                        ui.label(RichText::new("Stay focused on a conversation with a thread: a temporary text channel.").size(14.0).color(t.text_muted));
                                    });
                                    ui.add_space(24.0);
                                    return;
                                }
                                let n = threads.len();
                                ui.label(bold(format!("{n} Active Thread{}", if n == 1 { "" } else { "s" })).size(12.0).color(t.text_muted));
                                ui.add_space(6.0);
                                for (id, name) in &threads {
                                    let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), super::dense(44.0)), Sense::click());
                                    let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
                                    ui.painter().rect(r, 8.0, if resp.hovered() { t.bg_hover } else { t.bg_primary }, Stroke::new(1.0_f32, t.border_subtle));
                                    super::paint_icon(ui.painter(), Rect::from_center_size(pos2(r.left() + 22.0, r.center().y), vec2(20.0, 20.0)), icon::THREAD, t.channel_default);
                                    let clip = ui.painter().with_clip_rect(r.shrink2(vec2(12.0, 0.0)));
                                    clip.text(pos2(r.left() + 42.0, r.center().y), Align2::LEFT_CENTER, name, crate::style::medium(16.0), t.header_primary);
                                    if resp.clicked() {
                                        open = Some(*id);
                                    }
                                    ui.add_space(8.0);
                                }
                            });
                        });
                    });
            });
        if let Some(id) = open {
            self.select_channel(Some(id));
            close = true;
        }
        if create {
            self.compose.new_thread = Some(crate::features::ThreadDraft { channel: ch, name: String::new(), message: String::new(), private: false });
            close = true;
        }
        // (The click on the header button that opened it is "elsewhere" too.)
        if area.response.clicked_elsewhere() && ctx.cumulative_pass_nr() > opened + 1 {
            close = true;
        }
        if close {
            self.threads_popout = None;
        }
    }

    /// Pinned messages popout under the header's pin button, and the
    /// "pin / unpin this?" question on top of everything.
    pub fn pins_popout(&mut self, ctx: &egui::Context) {
        self.pins_list_ui(ctx);
        self.pin_confirm_ui(ctx);
    }

    /// Open the pins popout for `ch` under the header's pin button (the
    /// header leaves the button's rect in egui's temp data) and load its pins.
    pub(super) fn open_pins(&mut self, ch: Id) {
        let button: Option<Rect> = self.ctx.data(|d| d.get_temp(pins_button_id()));
        let at = button.map(pins_anchor).unwrap_or_else(|| {
            let s = self.ctx.screen_rect();
            pos2(s.right() - 8.0, s.top() + super::HEADER + 40.0)
        });
        self.pins = Some((ch, at, None));
        self.pins_opened = self.ctx.cumulative_pass_nr();
        self.backend.send(crate::backend::Command::FetchPins(ch));
    }

    /// Discord's pins popout: 420 wide, at most 80 % of the window tall; each
    /// pin a card with the message laid out as in the chat, "Jump" (and ✕ to
    /// unpin, if you may) at its top right while hovered.
    fn pins_list_ui(&mut self, ctx: &egui::Context) {
        let Some((ch, anchor, result)) = self.pins.clone() else { return };
        let t = self.theme.clone();
        // While the question is up, its clicks and keys aren't the popout's.
        let asking = self.pin_confirm.is_some();
        // Follows the button when the window is resized.
        let anchor = ctx.data(|d| d.get_temp::<Rect>(pins_button_id())).map_or(anchor, pins_anchor);
        let can_unpin = self.can_pin(ch);
        let in_dm = self.store.channels.get(&ch).is_some_and(|c| c.guild_id.is_none());
        // (56: the header above the list.)
        let max_h = (ctx.screen_rect().height() * 0.8 - 56.0).max(120.0);
        let mut close = !asking && ctx.input(|i| i.key_pressed(egui::Key::Escape));
        let mut actions = Vec::new();
        let mut jump: Option<(Id, Id)> = None;
        let mut unpin: Option<Message> = None;
        let area = egui::Area::new(egui::Id::new("pins_popout"))
            .order(Order::Foreground)
            .pivot(Align2::RIGHT_TOP)
            .fixed_pos(anchor)
            .constrain(true)
            .show(ctx, |ui| {
                Frame::none()
                    .fill(t.bg_floating)
                    .rounding(8.0)
                    // Discord: no border, a ring of white at 8 %.
                    .stroke(Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)))
                    .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(PINS_W);
                        ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                        Frame::none().inner_margin(16.0).show(ui, |ui| {
                            ui.horizontal(|ui| {
                                ui.spacing_mut().item_spacing.x = 8.0;
                                let (r, _) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::hover());
                                super::paint_icon(ui.painter(), r, icon::PIN, t.interactive_normal);
                                ui.label(bold("Pinned Messages").size(20.0).color(t.header_primary));
                            });
                        });
                        match &result {
                            None => {
                                ui.add_space(40.0);
                                ui.vertical_centered(|ui| ui.spinner());
                                ui.add_space(40.0);
                            }
                            Some(Err(e)) => {
                                Frame::none().inner_margin(Margin { left: 16.0, right: 16.0, top: 0.0, bottom: 16.0 }).show(ui, |ui| {
                                    ui.add(egui::Label::new(RichText::new(e).size(14.0).color(t.danger)).wrap());
                                });
                            }
                            Some(Ok(list)) if list.is_empty() => pins_empty(ui, &t, in_dm),
                            Some(Ok(list)) => {
                                // (min_scrolled_height: the popout's own remembered
                                // size must not keep a long list short.)
                                ScrollArea::vertical().max_height(max_h).min_scrolled_height(max_h).show(ui, |ui| {
                                    ui.add_space(8.0);
                                    for m in list {
                                        let card = ui
                                            .horizontal_top(|ui| {
                                                ui.add_space(8.0);
                                                self.pin_card(ui, m, &mut actions)
                                            })
                                            .inner;
                                        if !asking && ui.rect_contains_pointer(card) {
                                            let mut right = card.right() - 8.0;
                                            if can_unpin {
                                                let r = Rect::from_min_size(pos2(right - 32.0, card.top() + 8.0), vec2(32.0, 32.0));
                                                if card_button(ui, &t, r, ("pin_remove", m.id.0), None) {
                                                    unpin = Some(m.clone());
                                                }
                                                right = r.left() - 4.0;
                                            }
                                            let r = Rect::from_min_size(pos2(right - 60.0, card.top() + 8.0), vec2(60.0, 32.0));
                                            if card_button(ui, &t, r, ("pin_jump", m.id.0), Some("Jump")) {
                                                jump = Some((m.channel_id, m.id));
                                            }
                                        }
                                        ui.add_space(8.0);
                                    }
                                });
                            }
                        }
                    });
            });
        for a in actions {
            self.apply_action(a);
        }
        if let Some((c, msg)) = jump {
            self.pins = None;
            self.jump_to(c, msg);
            return;
        }
        if let Some(m) = unpin {
            self.ask_pin(m, false);
            return;
        }
        // The click on the pin button that opened it is "elsewhere" too.
        if !asking && area.response.clicked_elsewhere() && ctx.cumulative_pass_nr() > self.pins_opened + 1 {
            close = true;
        }
        if close && self.pins.as_ref().is_some_and(|p| p.0 == ch) {
            self.pins = None;
        }
    }

    /// One pin: Discord's lighter card, 400 wide, with the message laid out
    /// as in the chat (avatar, name, time, text, attachments, embeds) in a
    /// 312 px column. Returns the card's rect.
    fn pin_card(&self, ui: &mut Ui, m: &Message, actions: &mut Vec<super::chat::UiAction>) -> Rect {
        let t = &self.theme;
        Frame::none()
            .fill(t.surface_high)
            .rounding(8.0)
            .stroke(Stroke::new(1.0_f32, t.border_subtle))
            .inner_margin(16.0)
            .show(ui, |ui| {
                ui.set_width(PIN_CARD_W - 32.0);
                ui.horizontal_top(|ui| {
                    ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                    // Discord: the avatar sits 2 px below the text's top.
                    let (r, _) = ui.allocate_exact_size(vec2(40.0, 42.0), Sense::hover());
                    let av = Rect::from_min_size(r.min + vec2(0.0, 2.0), vec2(40.0, 40.0));
                    paint_avatar(ui, av, Some(super::avatar_uri(&m.author, 80, false)), m.display_name());
                    if let Some(deco) = super::decoration_uri(&m.author, false) {
                        egui::Image::new(deco).paint_at(ui, av.expand(av.width() * 0.1));
                    }
                    ui.add_space(16.0);
                    ui.vertical(|ui| {
                        ui.set_width(PIN_TEXT_W);
                        // An embed or player wider than the column is cut at
                        // the card's padding rather than drawn over its edge.
                        let left = ui.max_rect().left();
                        let mut clip = ui.clip_rect();
                        clip.min.x = clip.min.x.max(left);
                        clip.max.x = clip.max.x.min(left + PIN_TEXT_W);
                        ui.set_clip_rect(clip);
                        ui.spacing_mut().item_spacing = vec2(8.0, 3.0);
                        ui.horizontal(|ui| {
                            ui.spacing_mut().item_spacing.x = 6.0;
                            let name_font = self.author_font(m, crate::style::medium(16.0));
                            ui.label(RichText::new(self.author_name(m)).font(name_font).color(self.name_color(m)));
                            if let Some((tag, badge)) = m.author.server_tag() {
                                if let (Some(pos), Some(guild)) = (self.tag_chip(ui, &tag, badge), m.author.server_tag_guild()) {
                                    actions.push(super::chat::UiAction::OpenTag { guild, pos });
                                }
                            }
                            super::bot_badge(ui, t, &m.author);
                            ui.add_space(2.0);
                            ui.label(RichText::new(format_timestamp(&m.timestamp)).font(crate::style::medium(12.0)).color(t.text_muted));
                        });
                        // The chat's 22 px header line.
                        ui.add_space(-2.0);
                        if !m.content.is_empty() && !super::chat::link_only_media(m) {
                            self.render_markdown_sized(ui, m, &m.content, 16.0, t.text_normal, actions);
                        }
                        self.attachments_ui(ui, &m.attachments, actions);
                        self.embeds_ui(ui, m, actions);
                    });
                });
            })
            .response
            .rect
    }

    /// Discord's pin notice: "**X** pinned **a message** to this channel.
    /// See all **pinned messages**." — the first link jumps to the pinned
    /// message, the second opens the pins popout.
    pub(super) fn pin_notice(&self, ui: &mut Ui, m: &Message, actions: &mut Vec<super::chat::UiAction>) {
        use super::chat::UiAction;
        let t = &self.theme;
        ui.horizontal_wrapped(|ui| {
            ui.spacing_mut().item_spacing.x = 0.0;
            let plain = |ui: &mut Ui, s: &str| {
                ui.label(RichText::new(s).size(16.0).color(t.text_muted));
            };
            ui.label(RichText::new(self.author_name(m)).font(self.author_font(m, crate::style::medium(16.0))).color(self.name_color(m)));
            plain(ui, " pinned ");
            match m.message_reference.as_ref().and_then(|r| r.message_id) {
                Some(pinned) => {
                    if notice_link(ui, t, egui::Id::new(("pin_notice_msg", m.id.0)), "a message") {
                        actions.push(UiAction::JumpTo { channel: m.channel_id, msg: pinned });
                    }
                }
                // (Nothing to jump to.)
                None => {
                    ui.label(RichText::new("a message").font(crate::style::medium(16.0)).color(t.header_primary));
                }
            }
            plain(ui, " to this channel. See all ");
            if notice_link(ui, t, egui::Id::new(("pin_notice_all", m.id.0)), "pinned messages") {
                actions.push(UiAction::OpenPins(m.channel_id));
            }
            plain(ui, ".");
            ui.add_space(4.0);
            ui.label(RichText::new(format_timestamp(&m.timestamp)).font(crate::style::medium(12.0)).color(t.text_muted));
        });
    }

    /// Discord's question before a pin ("Pin It. Pin It Good.") or an unpin
    /// ("Unpin Message"): the message, Cancel and the deed. Enter confirms;
    /// Esc, ✕ or a click on the dimmed window cancels.
    fn pin_confirm_ui(&mut self, ctx: &egui::Context) {
        let Some(pc) = self.pin_confirm.take() else { return };
        let t = self.theme.clone();
        let m = &pc.message;
        let place = match self.store.channels.get(&m.channel_id) {
            Some(c) if c.guild_id.is_some() => format!("#{}", Store::channel_label(c)),
            _ => "this conversation".into(),
        };
        let (title, subtitle, ok_label, ok_fill) = if pc.pin {
            (
                "Pin It. Pin It Good.",
                format!("Hey, just double-checking that you want to pin this message to {place} for posterity and greatness?"),
                "Oh yeah. Pin it",
                Color32::from_rgb(0x58, 0x65, 0xf2),
            )
        } else {
            ("Unpin Message", "You sure you want to remove this pinned message?".to_string(), "Remove it please!", Color32::from_rgb(210, 45, 57))
        };
        const W: f32 = 480.0;
        // The confirm button holds the keyboard focus: Enter presses it, and
        // the message box (which sends on Enter) doesn't have it meanwhile.
        let ok_id = egui::Id::new("pin_confirm_ok");
        let mut cancel = ctx.input(|i| i.key_pressed(egui::Key::Escape));
        let mut confirm = ctx.memory(|mem| mem.has_focus(ok_id)) && ctx.input(|i| i.key_pressed(egui::Key::Enter));
        let mut actions = Vec::new();

        let screen = ctx.screen_rect();
        let dim = egui::Area::new(egui::Id::new("pin_confirm_dim")).order(Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
            let (_, r) = ui.allocate_exact_size(screen.size(), Sense::click());
            ui.painter().rect_filled(screen, 0.0, Color32::from_black_alpha(170));
            r.clicked()
        });
        // Above the pins popout it may have been opened from.
        ctx.move_to_top(dim.response.layer_id);
        let card = egui::Area::new(egui::Id::new("pin_confirm")).order(Order::Foreground).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
            Frame::none()
                .fill(t.surface_high)
                .rounding(12.0)
                .stroke(Stroke::new(1.0_f32, t.border_subtle))
                .shadow(egui::epaint::Shadow { offset: vec2(0.0, 8.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(140) })
                .show(ui, |ui| {
                    ui.set_width(W);
                    ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                    Frame::none().inner_margin(Margin { left: 24.0, right: 24.0, top: 16.0, bottom: 8.0 }).show(ui, |ui| {
                        ui.set_width(W - 48.0);
                        let top = ui.cursor().min;
                        ui.label(bold(title).size(20.0).color(t.header_primary));
                        let x = Rect::from_center_size(pos2(top.x + W - 48.0 - 10.0, top.y + 12.0), vec2(28.0, 28.0));
                        let xr = ui.interact(x, egui::Id::new("pin_confirm_close"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                        if xr.hovered() {
                            ui.painter().rect_filled(x, 6.0, t.bg_hover);
                        }
                        ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(14.0), if xr.hovered() { t.header_primary } else { t.interactive_normal });
                        cancel |= xr.clicked();
                        ui.add_space(8.0);
                        let mut job = egui::text::LayoutJob::single_section(
                            subtitle,
                            egui::TextFormat { font_id: FontId::proportional(16.0), color: t.header_secondary, line_height: Some(20.0), ..Default::default() },
                        );
                        job.wrap.max_width = W - 48.0;
                        ui.label(job);
                    });
                    ui.add_space(8.0);
                    // The message, in a darker box (a long one scrolls).
                    ui.horizontal(|ui| {
                        ui.add_space(16.0);
                        Frame::none().fill(t.bg_tertiary).rounding(3.0).inner_margin(Margin::symmetric(12.0, 10.0)).show(ui, |ui| {
                            ui.set_width(W - 32.0 - 24.0);
                            ui.spacing_mut().item_spacing = vec2(8.0, 3.0);
                            ScrollArea::vertical().id_salt("pin_confirm_preview").max_height(240.0).show(ui, |ui| {
                                ui.set_width(ui.available_width());
                                self.message_card_body(ui, m, &mut actions);
                            });
                        });
                    });
                    Frame::none().inner_margin(Margin { left: 24.0, right: 24.0, top: 16.0, bottom: 24.0 }).show(ui, |ui| {
                        ui.horizontal(|ui| {
                            ui.spacing_mut().item_spacing.x = 8.0;
                            let size = vec2((W - 48.0 - 8.0) / 2.0, 40.0);
                            let (r, resp) = ui.allocate_exact_size(size, Sense::click());
                            let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
                            ui.painter().rect_filled(r, 8.0, crate::style::overlay(if resp.hovered() { 0.2 } else { 0.12 }));
                            ui.painter().text(r.center(), Align2::CENTER_CENTER, "Cancel", crate::style::medium(16.0), t.header_primary);
                            cancel |= resp.clicked();
                            let (r, _) = ui.allocate_exact_size(size, Sense::hover());
                            let resp = ui.interact(r, ok_id, Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                            ui.painter().rect_filled(r, 8.0, if resp.hovered() { ok_fill.lerp_to_gamma(Color32::BLACK, 0.12) } else { ok_fill });
                            ui.painter().text(r.center(), Align2::CENTER_CENTER, ok_label, crate::style::medium(16.0), Color32::WHITE);
                            confirm |= resp.clicked();
                        });
                    });
                });
        });
        // Right above the dim, whichever was pressed last.
        ctx.set_sublayer(dim.response.layer_id, card.response.layer_id);
        cancel |= dim.inner;
        for a in actions {
            self.apply_action(a);
        }
        if confirm {
            ctx.memory_mut(|mem| mem.surrender_focus(ok_id));
            self.set_pinned(m.channel_id, m.id, pc.pin);
        } else if cancel {
            ctx.memory_mut(|mem| mem.surrender_focus(ok_id));
        } else {
            ctx.memory_mut(|mem| mem.request_focus(ok_id));
            self.pin_confirm = Some(pc);
        }
    }

    /// Title bar inbox: recent mentions, newest first. Discord's (measured
    /// 2026-11-22): 560 wide on surface-high, 16 px header with a 20 px icon and
    /// "Inbox" in 20/24 semibold, a tab strip (14 px semibold, the open one
    /// underlined 2 px in brand colour), then one card per channel: 12 px
    /// corners on surface-higher, a 12 px padded header (32 px server icon,
    /// "# channel" 16/20 semibold over "Server" 12/16) and the messages laid
    /// out like chat (40 px avatar, text from 72 px).
    pub fn inbox_popout(&mut self, ctx: &egui::Context) {
        let Some((anchor, result)) = self.inbox.clone() else { return };
        let t = self.theme.clone();
        let mut close = ctx.input(|i| i.key_pressed(egui::Key::Escape));
        let mut actions = Vec::new();
        let mut goto: Option<Id> = None;
        let brand = Color32::from_rgb(0x94, 0x9c, 0xf7);
        let area = egui::Area::new(egui::Id::new("inbox_popout"))
            .order(Order::Foreground)
            .pivot(Align2::RIGHT_TOP)
            .fixed_pos(anchor)
            .constrain(true)
            .show(ctx, |ui| {
                Frame::none()
                    .fill(t.surface_high)
                    .rounding(8.0)
                    .stroke(Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)))
                    .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(560.0);
                        ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                        // Header: title row (34 tall) and the tab strip under it.
                        let (head, _) = ui.allocate_exact_size(vec2(560.0, 16.0 + 34.0 + 16.0 + 20.0), Sense::hover());
                        let p = ui.painter();
                        let mid = head.top() + 16.0 + 17.0;
                        p.text(pos2(head.left() + 26.0, mid), Align2::CENTER_CENTER, icon::INBOX, icon_font(20.0), t.header_primary);
                        p.text(pos2(head.left() + 44.0, mid), Align2::LEFT_CENTER, "Inbox", FontId::new(20.0, egui::FontFamily::Name(crate::style::BOLD.into())), t.header_primary);
                        // The tab strip: Mentions is the one RustCord has.
                        let tab_font = FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into()));
                        let tab = Rect::from_min_size(pos2(head.left() + 16.0, head.bottom() - 20.0), vec2(105.6, 20.0));
                        p.text(pos2(tab.center().x, tab.top() + 7.0), Align2::CENTER_CENTER, "Mentions", tab_font, brand);
                        p.rect_filled(Rect::from_min_max(pos2(tab.left(), tab.bottom() - 2.0), tab.right_bottom()), egui::Rounding { nw: 2.0, ne: 2.0, sw: 0.0, se: 0.0 }, brand);
                        p.hline(head.x_range(), head.bottom() - 0.5, Stroke::new(1.0_f32, t.border_subtle));
                        ScrollArea::vertical().max_height(512.0).min_scrolled_height(512.0).auto_shrink([false, false]).show(ui, |ui| {
                            Frame::none().inner_margin(Margin { left: 16.0, right: 16.0, top: 16.0, bottom: 0.0 }).show(ui, |ui| {
                                ui.set_width(528.0);
                                match &result {
                                    None => {
                                        ui.add_space(20.0);
                                        ui.vertical_centered(|ui| ui.spinner());
                                        ui.add_space(36.0);
                                    }
                                    Some(Err(e)) => {
                                        ui.colored_label(t.danger, e);
                                        ui.add_space(16.0);
                                    }
                                    Some(Ok(list)) if list.is_empty() => {
                                        ui.add_space(24.0);
                                        ui.vertical_centered(|ui| {
                                            ui.label(bold("Nobody's mentioned you yet.").size(16.0).color(t.header_primary));
                                            ui.add_space(4.0);
                                            ui.label(RichText::new("When someone @mentions you, it'll show up here.").size(14.0).color(t.text_muted));
                                        });
                                        ui.add_space(40.0);
                                    }
                                    Some(Ok(list)) => {
                                        // Runs of mentions from the same channel share a card.
                                        let mut i = 0;
                                        while i < list.len() {
                                            let ch_id = list[i].channel_id;
                                            let n = list[i..].iter().take_while(|m| m.channel_id == ch_id).count();
                                            let group = &list[i..i + n];
                                            i += n;
                                            if self.inbox_card(ui, &t, group, &mut actions) {
                                                goto = Some(ch_id);
                                            }
                                            ui.add_space(16.0);
                                        }
                                    }
                                }
                            });
                        });
                    });
            });
        for a in actions {
            self.apply_action(a);
        }
        if area.response.clicked_elsewhere() && self.inbox_opened_frame + 1 < ctx.cumulative_pass_nr() {
            close = true;
        }
        if let Some(c) = goto {
            let guild = self.store.channels.get(&c).and_then(|c| c.guild_id);
            self.current_guild = guild;
            self.select_channel(Some(c));
            close = true;
        }
        if close {
            self.inbox = None;
        }
    }

    /// One channel's card in the inbox. Returns true when it was clicked (jump).
    fn inbox_card(&self, ui: &mut Ui, t: &crate::style::Theme, group: &[Message], actions: &mut Vec<super::chat::UiAction>) -> bool {
        let first = &group[0];
        let ch = self.store.channels.get(&first.channel_id);
        let guild = ch.and_then(|c| c.guild_id).or(first.guild_id).and_then(|g| self.store.guilds.get(&g));
        let (title, sub) = match (ch, guild) {
            (Some(c), Some(g)) => (Store::channel_label(c), Some(g.guild.name.clone())),
            (Some(c), None) => (self.store.label(c), None),
            (None, Some(g)) => ("Unknown channel".to_string(), Some(g.guild.name.clone())),
            (None, None) => ("Unknown channel".to_string(), None),
        };
        let icon_url = guild.and_then(|g| g.guild.icon_url(64)).or_else(|| ch.and_then(|c| c.recipients.first()).map(|u| u.avatar_or_default(64)));
        let in_guild = ch.is_some_and(|c| c.guild_id.is_some());
        let card = Frame::none()
            .fill(t.bg_floating)
            .rounding(12.0)
            .stroke(Stroke::new(1.0_f32, t.border_subtle))
            .show(ui, |ui| {
                ui.set_width(ui.available_width());
                ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                // Header: 12 px padding, 32 px icon, name over the server.
                let (h, _) = ui.allocate_exact_size(vec2(ui.available_width(), 60.0), Sense::hover());
                let icon = Rect::from_min_size(pos2(h.left() + 12.0, h.top() + 14.0), vec2(32.0, 32.0));
                match &icon_url {
                    Some(u) => egui::Image::new(u.as_str()).rounding(if in_guild { 8.0 } else { 16.0 }).paint_at(ui, icon),
                    None => {
                        ui.painter().rect_filled(icon, 8.0, t.bg_primary);
                        let initial = sub.as_deref().and_then(|g| g.chars().next()).unwrap_or('#').to_string();
                        ui.painter().text(icon.center(), Align2::CENTER_CENTER, initial, crate::style::medium(14.0), t.header_primary);
                    }
                }
                let x = h.left() + 56.0;
                let clip = ui.painter().with_clip_rect(Rect::from_min_max(pos2(x, h.top()), pos2(h.right() - 12.0, h.bottom())));
                let name_y = if sub.is_some() { h.top() + 22.0 } else { h.center().y };
                let name_font = FontId::new(16.0, egui::FontFamily::Name(crate::style::BOLD.into()));
                if in_guild {
                    clip.text(pos2(x + 8.0, name_y), Align2::CENTER_CENTER, icon::HASH, icon_font(16.0), t.channel_default);
                    clip.text(pos2(x + 18.0, name_y), Align2::LEFT_CENTER, &title, name_font, t.header_primary);
                } else {
                    clip.text(pos2(x, name_y), Align2::LEFT_CENTER, &title, name_font, t.header_primary);
                }
                if let Some(g) = &sub {
                    clip.text(pos2(x, h.top() + 40.0), Align2::LEFT_CENTER, g, crate::style::medium(12.0), t.text_muted);
                }
                for m in group {
                    self.inbox_message(ui, t, m, actions);
                }
                ui.add_space(12.0);
            });
        let r = card.response.rect;
        let hit = ui.interact(r, egui::Id::new(("inbox_hit", first.id.0)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text("Jump");
        hit.clicked() && ch.is_some()
    }

    /// A mention laid out like a cozy chat message: 40 px avatar 16 px in, name
    /// (16 medium, role colour) and time (12) then the text (16/22) from 72 px.
    fn inbox_message(&self, ui: &mut Ui, t: &crate::style::Theme, m: &Message, actions: &mut Vec<super::chat::UiAction>) {
        ui.add_space(2.0);
        ui.horizontal_top(|ui| {
            ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
            ui.add_space(16.0);
            let (r, _) = ui.allocate_exact_size(vec2(40.0, 42.0), Sense::hover());
            paint_avatar(ui, Rect::from_min_size(r.min + vec2(0.0, 2.0), vec2(40.0, 40.0)), Some(super::avatar_uri(&m.author, 80, false)), m.display_name());
            ui.add_space(16.0);
            ui.vertical(|ui| {
                ui.set_width(ui.available_width() - 16.0);
                let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::hover());
                let p = ui.painter_at(row);
                let name = p.text(pos2(row.left(), row.center().y), Align2::LEFT_CENTER, self.author_name(m), crate::style::medium(16.0), self.name_color(m));
                p.text(pos2(name.right() + 4.0, row.center().y + 1.0), Align2::LEFT_CENTER, format_timestamp(&m.timestamp), crate::style::medium(12.0), t.text_muted);
                if !m.content.is_empty() {
                    self.render_markdown_sized(ui, m, &m.content, 16.0, t.text_normal, actions);
                }
                if !m.attachments.is_empty() {
                    ui.label(RichText::new(format!("{} attachment(s)", m.attachments.len())).size(14.0).color(t.text_muted));
                }
            });
        });
        ui.add_space(2.0);
    }

    /// Compact message preview used by pins and search results.
    fn message_card(&self, ui: &mut Ui, m: &Message, actions: &mut Vec<super::chat::UiAction>) -> egui::Response {
        let t = &self.theme;
        Frame::none()
            .fill(t.bg_primary)
            .rounding(8.0)
            .stroke(Stroke::new(1.0_f32, t.border_subtle))
            .inner_margin(12.0)
            .show(ui, |ui| {
                ui.set_width(ui.available_width());
                self.message_card_body(ui, m, actions);
            })
            .response
    }

    /// What's inside a [`message_card`] (also the pin question's preview).
    fn message_card_body(&self, ui: &mut Ui, m: &Message, actions: &mut Vec<super::chat::UiAction>) {
        let t = &self.theme;
        ui.horizontal_top(|ui| {
            let (r, _) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::hover());
            paint_avatar(ui, r, Some(m.author.avatar_or_default(64)), m.display_name());
            ui.add_space(8.0);
            ui.vertical(|ui| {
                ui.horizontal(|ui| {
                    ui.label(bold(self.author_name(m)).size(15.0).color(t.header_primary));
                    ui.label(RichText::new(format_timestamp(&m.timestamp)).size(11.5).color(t.text_muted));
                });
                if !m.content.is_empty() {
                    self.render_markdown_sized(ui, m, &m.content, 14.0, t.text_normal, actions);
                }
                if !m.attachments.is_empty() {
                    ui.label(RichText::new(format!("{} attachment(s)", m.attachments.len())).size(12.0).color(t.text_muted));
                }
            });
        });
    }

    /// Search results panel (replaces the member list while open).
    pub fn search_panel(&mut self, ui: &mut Ui) {
        let t = self.theme.clone();
        let Some((query, result)) = self.search.clone() else { return };
        let mut close = false;
        let mut goto: Option<(Id, Id)> = None;
        let mut actions = Vec::new();
        Frame::none().inner_margin(Margin::symmetric(16.0, 10.0)).show(ui, |ui| {
            ui.horizontal(|ui| {
                let label = match &result {
                    Some(Ok((total, _))) => format!("{total} Results"),
                    Some(Err(_)) => "Search failed".into(),
                    None => "Searching…".into(),
                };
                ui.label(bold(label).size(16.0).color(t.header_primary));
                ui.label(RichText::new(format!("for \"{query}\"")).color(t.text_muted));
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    let (r, b) = ui.allocate_exact_size(vec2(24.0, 24.0), Sense::click());
                    let b = b.on_hover_cursor(egui::CursorIcon::PointingHand);
                    ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(12.0), if b.hovered() { t.header_primary } else { t.interactive_normal });
                    close = b.on_hover_text("Close").clicked();
                });
            });
        });
        ui.painter().hline(ui.max_rect().x_range(), ui.cursor().top(), Stroke::new(1.0_f32, t.border_subtle));
        ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
            Frame::none().inner_margin(12.0).show(ui, |ui| {
                ui.set_width(ui.available_width());
                match &result {
                    None => {
                        ui.add_space(30.0);
                        ui.vertical_centered(|ui| ui.spinner());
                    }
                    Some(Err(e)) => {
                        ui.colored_label(t.danger, e);
                    }
                    Some(Ok((_, hits))) if hits.is_empty() => {
                        ui.label(RichText::new("No results. Try a different search.").color(t.text_muted));
                    }
                    Some(Ok((_, hits))) => {
                        for m in hits {
                            let channel = self
                                .store
                                .channels
                                .get(&m.channel_id)
                                .map(|c| format!("# {}", Store::channel_label(c)))
                                .unwrap_or_default();
                            ui.label(bold(channel).size(12.0).color(t.channel_default));
                            let r = self.message_card(ui, m, &mut actions);
                            if jump_pill(ui, &t, r.rect, ("search_hit", m.id.0)) {
                                goto = Some((m.channel_id, m.id));
                            }
                            ui.add_space(10.0);
                        }
                    }
                }
            });
        });
        for a in actions {
            self.apply_action(a);
        }
        if close {
            self.search = None;
        }
        if let Some((c, msg)) = goto {
            self.jump_to(c, msg);
        }
    }
}

/// Discord's "Jump" pill at the top-right of a message card (pins, search
/// results), shown while the card is hovered. True when clicked.
fn jump_pill(ui: &mut Ui, t: &crate::style::Theme, card: Rect, id: impl std::hash::Hash) -> bool {
    if !ui.rect_contains_pointer(card) {
        return false;
    }
    let font = FontId::new(12.0, egui::FontFamily::Name(crate::style::BOLD.into()));
    let galley = ui.painter().layout_no_wrap("Jump".into(), font, t.text_normal);
    let r = Rect::from_min_size(pos2(card.right() - galley.size().x - 20.0, card.top() + 6.0), vec2(galley.size().x + 12.0, 22.0));
    let resp = ui.interact(r, egui::Id::new(id), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
    ui.painter().rect(r, 4.0, if resp.hovered() { t.bg_selected } else { t.bg_tertiary }, Stroke::new(1.0_f32, t.border_subtle));
    ui.painter().galley(pos2(r.left() + 6.0, r.center().y - galley.size().y / 2.0), galley, t.text_normal);
    resp.clicked()
}

/// The pins popout, its cards (4 px short of the list, which starts 8 px in)
/// and a card's text column (72 px in, 16 px padding on the right).
const PINS_W: f32 = 420.0;
const PIN_CARD_W: f32 = 400.0;
const PIN_TEXT_W: f32 = PIN_CARD_W - 72.0 - 16.0;

/// Where the chat header leaves its pin button's rect each frame (egui temp
/// data), for the popout to hang under.
pub(super) fn pins_button_id() -> egui::Id {
    egui::Id::new("pins_button_rect")
}

/// The pins popout's top-right corner: Discord puts its right edge 5 px
/// right of the pin button's and its top 8 px below the header.
fn pins_anchor(button: Rect) -> egui::Pos2 {
    pos2(button.right() + 5.0, button.center().y + super::HEADER / 2.0 + 8.0)
}

/// "Jump" (60 × 32) or, without a label, the ✕ that unpins (32 × 32) at the
/// top right of a hovered pin. True when clicked.
fn card_button(ui: &mut Ui, t: &crate::style::Theme, r: Rect, id: impl std::hash::Hash, label: Option<&str>) -> bool {
    let resp = ui.interact(r, egui::Id::new(id), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
    // Opaque underneath: the message's first line may run below the button.
    ui.painter().rect_filled(r, 8.0, t.surface_high);
    ui.painter().rect_filled(r, 8.0, crate::style::overlay(if resp.hovered() { 0.24 } else { 0.12 }));
    match label {
        Some(label) => {
            ui.painter().text(r.center(), Align2::CENTER_CENTER, label, crate::style::medium(14.0), t.header_primary);
            resp.clicked()
        }
        None => {
            super::paint_icon(ui.painter(), Rect::from_center_size(r.center(), vec2(16.0, 16.0)), icon::CLOSE, t.header_primary);
            resp.on_hover_text("Unpin").clicked()
        }
    }
}

/// A link inside a system message: header-primary, underlined with a hand
/// cursor while hovered. True when clicked.
fn notice_link(ui: &mut Ui, t: &crate::style::Theme, id: egui::Id, text: &str) -> bool {
    // Last frame's hover: the text is laid out before its response exists.
    let was = ui.ctx().data(|d| d.get_temp::<bool>(id)).unwrap_or(false);
    let mut rich = RichText::new(text).font(crate::style::medium(16.0)).color(t.header_primary);
    if was {
        rich = rich.underline();
    }
    let r = ui.add(egui::Label::new(rich).selectable(false).sense(Sense::click())).on_hover_cursor(egui::CursorIcon::PointingHand);
    if r.hovered() != was {
        ui.ctx().data_mut(|d| d.insert_temp(id, r.hovered()));
        ui.ctx().request_repaint();
    }
    r.clicked()
}

/// Wrapped text with every line centred in the width that's left.
fn centred_text(ui: &mut Ui, text: &str, font: FontId, color: Color32, line_height: f32, max_width: f32) {
    let mut job = egui::text::LayoutJob::single_section(text.into(), egui::TextFormat { font_id: font, color, line_height: Some(line_height), ..Default::default() });
    job.wrap.max_width = max_width;
    job.halign = egui::Align::Center;
    let galley = ui.fonts(|f| f.layout_job(job));
    let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), galley.size().y), Sense::hover());
    ui.painter().galley(pos2(r.center().x, r.top()), galley, color);
}

/// The pins popout with nothing pinned: a picture, Discord's line, and its
/// "Protip" strip across the bottom.
fn pins_empty(ui: &mut Ui, t: &crate::style::Theme, in_dm: bool) {
    ui.add_space(16.0);
    // (A pin in a soft circle stands in for Discord's illustration.)
    let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 120.0), Sense::hover());
    ui.painter().circle_filled(r.center(), 56.0, crate::style::overlay(0.08));
    super::paint_icon(ui.painter(), Rect::from_center_size(r.center(), vec2(64.0, 64.0)), icon::PIN, t.interactive_muted);
    ui.add_space(20.0);
    centred_text(ui, "This channel doesn't have any\npinned messages... yet.", crate::style::medium(16.0), t.text_normal, 20.0, PINS_W - 32.0);
    ui.add_space(32.0);
    let strip = ui.painter().add(egui::Shape::Noop);
    let top = ui.cursor().top();
    ui.add_space(26.0);
    let semibold = FontId::new(14.0, egui::FontFamily::Name(crate::style::BOLD.into()));
    centred_text(ui, "Protip:", semibold, Color32::from_rgb(69, 196, 107), 18.0, PINS_W - 32.0);
    let tip = if in_dm {
        "Anyone in this conversation can pin a message from its context menu."
    } else {
        "Users with the ‘Pin Messages’ permission can pin a message from its context menu."
    };
    centred_text(ui, tip, FontId::proportional(14.0), t.text_normal, 16.0, PINS_W - 32.0);
    ui.add_space(26.0);
    let x = ui.max_rect().x_range();
    let rect = Rect::from_x_y_ranges(x, top..=ui.cursor().top());
    // The popout's own bottom corners.
    ui.painter().set(strip, egui::Shape::rect_filled(rect, egui::Rounding { sw: 8.0, se: 8.0, ..Default::default() }, crate::style::overlay(0.12)));
}

impl RustCord {
    /// Open `channel` at `msg` (Discord's "Jump"): now if the channel's
    /// messages are here, else once they've loaded.
    pub(super) fn jump_to(&mut self, channel: Id, msg: Id) {
        let guild = self.store.channels.get(&channel).and_then(|c| c.guild_id);
        self.current_guild = guild;
        self.select_channel(Some(channel));
        if self.store.messages.contains_key(&channel) {
            self.jump_to_message(channel, msg, 0);
        } else {
            self.pending_jump = Some((channel, msg, 0));
        }
    }
}