Skip to content

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

81.0 KB
Raw Blame
//! Discord's expression picker: one popup over the composer with GIFs |
//! Stickers | Emoji tabs. Each composer button opens it on its own tab and
//! closes it when that tab is already showing; the tabs switch in place.
//! The reaction picker (message hover bar, poll answers) is the Emoji tab's
//! panel on its own, like Discord's.
//!
//! Every grid is virtualised: only the rows in view are laid out and only
//! their pictures are requested. (The old sticker picker laid out and loaded
//! every sticker of every server on each frame: on a 130-server account,
//! thousands of downloads and decodes the moment it opened.) Pictures show
//! a still frame; only the hovered one plays.

use super::{acronym, animating, paint_cover, paint_text_emoji, ANIMATE_EMOJI};
use crate::app::RustCord;
use crate::backend::Command;
use crate::emoji::twemoji_url;
use crate::emoji_data::CATEGORIES;
use crate::features::{EmojiAccess, EmojiPicker, EmojiRules, ExpressionPicker, ExpressionTab, GifPage, PickedEmoji, PickerTarget};
use crate::style::{icon, icon_font, overlay, rgba, Theme, BOLD};
use discord::model::{emoji_url, Gif, Guild, Id, Sticker};
use discord::settings_proto::{decode_frecency, encode_favorite_gif_patch, FavoriteGif, Frecency};
use eframe::egui::{
    self,
    load::{BytesPoll, ImageLoadResult, ImageLoader, ImagePoll, LoadError, SizeHint},
    pos2, vec2, Align2, Color32, ColorImage, CursorIcon, FontFamily, FontId, Frame, Key, Order, Pos2, Rect, RichText, ScrollArea,
    Sense, Shadow, Stroke, TextEdit, Ui, UiBuilder,
};
use reqwest::Method;
use serde_json::json;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::sync::{atomic::Ordering::Relaxed, Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};

/// Discord's expression picker, as measured in its web app (2026-11-17):
/// 498 × 486 with the tabs 17 px in (30 px tall pills), a 40 px search row
/// 12 px below them, a 48 px rail, 48 px cells holding 40 px pictures, 33 px
/// section headers and a 48 px strip at the bottom for the hovered item.
const W: f32 = 498.0;
const H: f32 = 486.0;
/// The reaction picker (emoji only, no tabs).
pub(super) const REACT_W: f32 = 430.0;
pub(super) const REACT_H: f32 = 440.0;
const PAD: f32 = 16.0;
const RAIL: f32 = 48.0;
const FOOTER: f32 = 48.0;
const SECTION_HEADER: f32 = 33.0;
/// A grid cell (an emoji with 4 px around it).
const CELL: f32 = 48.0;
/// Segoe Fluent Icons.
const GLYPH_RECENT: &str = "\u{E823}";
const GLYPH_STAR: &str = "\u{E734}";
const GLYPH_STAR_FILLED: &str = "\u{E735}";
const GOLD: Color32 = Color32::from_rgb(0xf0, 0xb2, 0x32);
const FREQUENT_STICKERS: usize = 16;
const FRECENCY_PATH: &str = "/users/@me/settings-proto/2";
/// GIF categories (Discord's own picker asks for MP4 clips).
const GIF_CATEGORIES_PATH: &str = "/gifs/trending?provider=tenor&locale=en-US&media_format=mp4";

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

fn shadow() -> Shadow {
    Shadow { offset: vec2(0.0, 8.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(140) }
}

/// The darker fill of the search box, server rail and footer.
fn sunken(t: &Theme) -> Color32 {
    t.bg_secondary.lerp_to_gamma(Color32::BLACK, 0.3)
}

fn signature(parts: impl Hash) -> u64 {
    let mut h = std::collections::hash_map::DefaultHasher::new();
    parts.hash(&mut h);
    h.finish()
}

// ---- layout pieces ----------------------------------------------------------

/// Where a picker's parts go.
pub(super) struct PanelRects {
    tabs: Rect,
    search: Rect,
    body: Rect,
    footer: Rect,
}

impl PanelRects {
    pub(super) fn body(&self) -> Rect {
        self.body
    }
}

pub(super) fn panel_rects(full: Rect, tabs: bool, footer: bool) -> PanelRects {
    let mut y = full.top() + PAD;
    let x = full.left() + PAD;
    let inner_w = full.width() - 2.0 * PAD;
    let tabs_r = if tabs {
        let r = Rect::from_min_size(pos2(x, y), vec2(inner_w, 30.0));
        y += 30.0 + 12.0;
        r
    } else {
        Rect::NOTHING
    };
    let search = Rect::from_min_size(pos2(x, y), vec2(inner_w, 40.0));
    y += 40.0 + 13.0;
    let footer_r = if footer {
        Rect::from_min_max(pos2(full.left() + 1.0, full.bottom() - FOOTER), full.max - vec2(1.0, 1.0))
    } else {
        Rect::from_min_max(pos2(full.left(), full.bottom()), full.max)
    };
    let body = Rect::from_min_max(pos2(full.left(), y), pos2(full.right(), footer_r.top()));
    PanelRects { tabs: tabs_r, search, body, footer: footer_r }
}

/// Body of the sticker / emoji panels: (server rail, grid).
fn split_body(body: Rect) -> (Rect, Rect) {
    let rail = Rect::from_min_max(pos2(body.left() + 1.0, body.top() + 0.5), pos2(body.left() + RAIL, body.bottom()));
    let grid = Rect::from_min_max(pos2(rail.right() + 8.0, body.top() + 4.0), pos2(body.right() - 8.0, body.bottom()));
    (rail, grid)
}

/// "GIFs  Stickers  Emoji" pills. Returns a tab that was clicked.
fn tab_pills(ui: &Ui, t: &Theme, rect: Rect, tab: ExpressionTab) -> Option<ExpressionTab> {
    let mut x = rect.left();
    let mut out = None;
    for (tb, label) in [(ExpressionTab::Gifs, "GIFs"), (ExpressionTab::Stickers, "Stickers"), (ExpressionTab::Emoji, "Emoji")] {
        let w = ui.fonts(|f| f.layout_no_wrap(label.to_string(), strong(14.0), Color32::WHITE).size().x) + 24.0;
        let r = Rect::from_min_size(pos2(x, rect.top()), vec2(w, rect.height()));
        x += w + 8.0;
        let resp = ui.interact(r, egui::Id::new(("expr_tab", label)), Sense::click());
        let on = tb == tab;
        if on {
            ui.painter().rect_filled(r, 8.0, t.bg_selected);
        } else if resp.hovered() {
            ui.painter().rect_filled(r, 8.0, t.bg_hover);
        }
        let c = if on {
            t.header_primary
        } else if resp.hovered() {
            t.interactive_hover
        } else {
            t.interactive_normal
        };
        ui.painter().text(r.center(), Align2::CENTER_CENTER, label, strong(14.0), c);
        if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() && !on {
            out = Some(tb);
        }
    }
    out
}

/// Discord's picker search box: magnifier, hint, clear button, accent ring
/// while typing. It keeps the cursor while the picker is open. Returns the
/// text box's response and whether the text changed (typed or cleared).
fn search_field(ui: &mut Ui, t: &Theme, text: &mut String, hint: &str, salt: &str, focus: bool) -> (egui::Response, bool) {
    let rect = ui.max_rect();
    let id = egui::Id::new(("expr_search", salt));
    let focused = ui.memory(|m| m.has_focus(id));
    ui.painter().rect(rect, 8.0, sunken(t), Stroke::new(1.0_f32, if focused { t.accent } else { t.border_subtle }));
    ui.painter().text(pos2(rect.left() + 16.0, rect.center().y), Align2::CENTER_CENTER, icon::SEARCH, icon_font(14.0), t.text_muted);
    let clear_w = if text.is_empty() { 0.0 } else { 28.0 };
    let edit_rect = Rect::from_min_max(pos2(rect.left() + 28.0, rect.top()), pos2(rect.right() - 8.0 - clear_w, rect.bottom()));
    let mut eui = ui.new_child(UiBuilder::new().max_rect(edit_rect).layout(egui::Layout::left_to_right(egui::Align::Center)));
    let r = eui.add(
        TextEdit::singleline(text)
            .id(id)
            .frame(false)
            .hint_text(RichText::new(hint).color(t.text_muted))
            .font(FontId::proportional(15.0))
            .text_color(t.text_normal)
            .desired_width(edit_rect.width())
            .margin(vec2(4.0, 0.0)),
    );
    let mut changed = r.changed();
    if focus || ui.memory(|m| m.focused().is_none()) {
        r.request_focus();
    }
    if !text.is_empty() {
        let cr = Rect::from_center_size(pos2(rect.right() - 20.0, rect.center().y), vec2(22.0, 22.0));
        let c = ui.interact(cr, id.with("clear"), Sense::click());
        ui.painter().text(cr.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(10.0), if c.hovered() { t.interactive_hover } else { t.text_muted });
        if c.on_hover_cursor(CursorIcon::PointingHand).clicked() {
            text.clear();
            r.request_focus();
            changed = true;
        }
    }
    (r, changed)
}

/// What a rail button / section header shows.
#[derive(Clone)]
enum Badge {
    /// Frequently Used: a clock.
    Recent,
    /// Favourites: a star.
    Favourite,
    /// A server icon.
    Icon(String),
    /// A server without an icon: its initials.
    Initials(String),
    /// An emoji category: its first emoji.
    Emoji(String),
}

fn guild_badge(g: &Guild) -> Badge {
    match g.icon_url(64) {
        Some(u) => Badge::Icon(u),
        None => Badge::Initials(acronym(&g.name)),
    }
}

fn paint_badge(ui: &Ui, t: &Theme, r: Rect, b: &Badge, color: Color32) {
    match b {
        Badge::Recent => {
            ui.painter().text(r.center(), Align2::CENTER_CENTER, GLYPH_RECENT, icon_font(r.height() * 0.72), color);
        }
        Badge::Favourite => {
            ui.painter().text(r.center(), Align2::CENTER_CENTER, icon::STAR, icon_font(r.height() * 0.72), color);
        }
        Badge::Icon(u) => egui::Image::new(u.as_str()).rounding(r.width() * 0.3).show_loading_spinner(false).paint_at(ui, r),
        Badge::Initials(s) => {
            ui.painter().rect_filled(r, r.width() * 0.3, overlay(0.16));
            ui.painter().text(r.center(), Align2::CENTER_CENTER, s, strong((r.height() * 0.34).max(7.0)), t.header_primary);
        }
        Badge::Emoji(u) => egui::Image::new(u.as_str()).show_loading_spinner(false).paint_at(ui, r),
    }
}

/// One section of a grid: a header, then items in rows.
struct Section<T> {
    /// Stable key (collapsed state): 0 Frequently Used, a server ID, or a
    /// category number.
    key: u64,
    title: String,
    badge: Badge,
    /// The server the items come from (footer: "from <server>").
    guild: Option<Id>,
    /// Every item needs Nitro here: its rail button gets a lock.
    locked: bool,
    items: Vec<T>,
}

type Sections<T> = Arc<Vec<Section<T>>>;

/// Sections are rebuilt only when what they're made from changes (not on
/// every frame while the pointer moves).
fn cached<T: Send + Sync + 'static>(ctx: &egui::Context, slot: &str, sig: u64, build: impl FnOnce() -> Vec<Section<T>>) -> Sections<T> {
    let id = egui::Id::new(("expr_sections", slot));
    if let Some((s, c)) = ctx.data(|d| d.get_temp::<(u64, Sections<T>)>(id)) {
        if s == sig {
            return c;
        }
    }
    let c = Arc::new(build());
    ctx.data_mut(|d| d.insert_temp(id, (sig, c.clone())));
    c
}

/// Drop the section lists once no picker shows them.
pub(super) fn forget_sections(ctx: &egui::Context) {
    ctx.data_mut(|d| {
        d.remove::<(u64, Sections<StickerItem>)>(egui::Id::new(("expr_sections", "stickers")));
        d.remove::<(u64, Sections<EmojiItem>)>(egui::Id::new(("expr_sections", "emoji")));
    });
}

/// Where each section starts, and the total height.
struct GridLayout {
    cols: usize,
    cell: f32,
    tops: Vec<f32>,
    total: f32,
}

fn grid_layout<T>(sections: &[Section<T>], width: f32, cols: usize, collapsed: &HashSet<u64>) -> GridLayout {
    let cols = cols.max(1);
    let cell = (width / cols as f32).floor().max(8.0);
    let mut tops = Vec::with_capacity(sections.len());
    let mut y = 0.0;
    for s in sections {
        tops.push(y);
        y += SECTION_HEADER;
        if !collapsed.contains(&s.key) {
            y += s.items.len().div_ceil(cols) as f32 * cell;
        }
        y += 6.0;
    }
    GridLayout { cols, cell, tops, total: y }
}

/// A virtualised grid of sections: only headers and rows in view are laid
/// out. `cell(ui, rect, section, item)` draws one item. `jump` scrolls a
/// section to the top. Returns (the section at the top, a header clicked).
fn section_grid<T>(
    ui: &mut Ui,
    t: &Theme,
    id: egui::Id,
    sections: &[Section<T>],
    g: &GridLayout,
    collapsed: &HashSet<u64>,
    jump: Option<usize>,
    mut cell: impl FnMut(&mut Ui, Rect, usize, usize),
) -> (usize, Option<u64>) {
    let mut area = ScrollArea::vertical().id_salt(id).auto_shrink([false, false]);
    if let Some(top) = jump.and_then(|j| g.tops.get(j)) {
        area = area.vertical_scroll_offset(*top);
    }
    let (mut active, mut toggled) = (0, None);
    area.show_viewport(ui, |ui, vp| {
        ui.set_height(g.total);
        let origin = ui.max_rect().min;
        let width = g.cell * g.cols as f32;
        for (si, s) in sections.iter().enumerate() {
            let top = g.tops[si];
            let bottom = g.tops.get(si + 1).copied().unwrap_or(g.total);
            if top <= vp.min.y + 1.0 {
                active = si;
            }
            if bottom < vp.min.y || top > vp.max.y {
                continue;
            }
            let shut = collapsed.contains(&s.key);
            let hr = Rect::from_min_size(origin + vec2(0.0, top), vec2(width, SECTION_HEADER));
            let resp = ui.interact(hr, id.with(("header", s.key)), Sense::click());
            let c = if resp.hovered() { t.interactive_hover } else { t.header_secondary };
            let badge = Rect::from_center_size(pos2(hr.left() + 16.0, hr.top() + 16.0), vec2(16.0, 16.0));
            paint_badge(ui, t, badge, &s.badge, c);
            let painter = ui.painter_at(hr.with_max_x(hr.right() - 18.0));
            let title = paint_text_emoji(ui, &painter, pos2(badge.right() + 4.0, hr.top() + 16.0), &s.title, strong(14.0), c);
            let chevron = if shut { icon::CHEVRON } else { icon::CHEVRON_DOWN };
            let cx = (title.right() + 10.0).min(hr.right() - 10.0);
            ui.painter().text(pos2(cx, hr.top() + 17.0), Align2::CENTER_CENTER, chevron, icon_font(9.0), c);
            if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                toggled = Some(s.key);
            }
            if shut {
                continue;
            }
            let grid_top = top + SECTION_HEADER;
            let rows = s.items.len().div_ceil(g.cols);
            let first = (((vp.min.y - grid_top) / g.cell).floor().max(0.0) as usize).min(rows);
            let last = (((vp.max.y - grid_top) / g.cell).ceil().max(0.0) as usize).min(rows);
            for row in first..last {
                for col in 0..g.cols {
                    let i = row * g.cols + col;
                    if i >= s.items.len() {
                        break;
                    }
                    let r = Rect::from_min_size(origin + vec2(col as f32 * g.cell, grid_top + row as f32 * g.cell), vec2(g.cell, g.cell));
                    cell(ui, r, si, i);
                }
            }
        }
    });
    (active, toggled)
}

/// The column of section buttons on the left (Frequently Used, servers,
/// categories). Only the buttons in view are drawn; the highlighted one
/// (the section in view) is kept in sight as the grid scrolls. Returns one
/// clicked.
fn rail<T>(ui: &mut Ui, t: &Theme, id: egui::Id, sections: &[Section<T>], active: usize) -> Option<usize> {
    const ROW: f32 = 40.0;
    let mut picked = None;
    let last_active = id.with("followed");
    let follow = ui.ctx().data(|d| d.get_temp::<usize>(last_active)) != Some(active);
    ui.ctx().data_mut(|d| d.insert_temp(last_active, active));
    ScrollArea::vertical()
        .id_salt(id)
        .auto_shrink([false, false])
        .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden)
        .show_viewport(ui, |ui, vp| {
            ui.set_height(sections.len() as f32 * ROW);
            let origin = ui.max_rect().min;
            let w = ui.max_rect().width();
            let row = |i: usize| Rect::from_min_size(origin + vec2(0.0, i as f32 * ROW), vec2(w, ROW));
            if follow {
                ui.scroll_to_rect(row(active), None);
            }
            let first = ((vp.min.y / ROW).floor().max(0.0) as usize).min(sections.len());
            let last = ((vp.max.y / ROW).ceil().max(0.0) as usize).min(sections.len());
            for i in first..last {
                let s = &sections[i];
                let r = row(i);
                let resp = ui.interact(r, id.with(("rail", i)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
                let on = i == active;
                let hot = resp.hovered();
                if on || hot {
                    let bg = Rect::from_center_size(r.center(), vec2(36.0, 36.0));
                    ui.painter().rect_filled(bg, 8.0, if on { t.bg_selected } else { t.bg_hover });
                }
                let c = if on || hot { t.interactive_hover } else { t.interactive_normal };
                let size = if matches!(s.badge, Badge::Recent | Badge::Favourite | Badge::Emoji(_)) { 22.0 } else { 28.0 };
                let badge = Rect::from_center_size(r.center(), vec2(size, size));
                paint_badge(ui, t, badge, &s.badge, c);
                if s.locked {
                    // Discord's: an 18 px black disc with a 10 px lock at the
                    // icon's bottom-right corner.
                    let at = badge.right_bottom() - vec2(4.0, 4.0);
                    ui.painter().circle_filled(at, 9.0, Color32::BLACK);
                    ui.painter().text(at, Align2::CENTER_CENTER, icon::LOCK, icon_font(10.0), t.interactive_normal);
                }
                if resp.on_hover_text(&s.title).on_hover_cursor(CursorIcon::PointingHand).clicked() {
                    picked = Some(i);
                }
            }
        });
    picked
}

/// Discord's skin tone selector: a clapping-hands button in the chosen tone
/// that drops a column of the six choices (none, light … dark) over itself;
/// 38 px squares with 24 px pictures in a 40 px wide box with 4 px corners.
/// Drawn last, so the column lies over the grid.
fn skin_tone_selector(ui: &mut Ui, t: &Theme, button: Rect, salt: &str) {
    const NAMES: [&str; 6] = ["None", "Light skin tone", "Medium-light skin tone", "Medium skin tone", "Medium-dark skin tone", "Dark skin tone"];
    let id = egui::Id::new(("expr_skin_tone", salt));
    let open: bool = ui.ctx().data(|d| d.get_temp(id)).unwrap_or(false);
    let now = crate::emoji::skin_tone();
    let picture = |tone: u8| twemoji_url(crate::emoji::toned("👏", tone).unwrap_or("👏"));
    let paint = |ui: &Ui, cell: Rect, tone: u8| {
        egui::Image::new(picture(tone)).show_loading_spinner(false).paint_at(ui, Rect::from_center_size(cell.center(), vec2(24.0, 24.0)));
    };
    if !open {
        let resp = ui.interact(button, id.with("button"), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        if resp.hovered() {
            ui.painter().rect_filled(button, 4.0, t.bg_hover);
        }
        paint(ui, button, now);
        if resp.on_hover_text(format!("Select emoji skin tone, {}", NAMES[now as usize])).on_hover_cursor(CursorIcon::PointingHand).clicked() {
            ui.ctx().data_mut(|d| d.insert_temp(id, true));
        }
        return;
    }
    // The chosen tone first (where the button was), then the others in order.
    let order: Vec<u8> = std::iter::once(now).chain((0..=5u8).filter(|tone| *tone != now)).collect();
    let column = Rect::from_min_size(button.min - vec2(1.0, 1.0), vec2(40.0, 38.0 * 6.0 + 2.0));
    ui.painter().rect(column, 4.0, sunken(t), Stroke::new(1.0_f32, t.border_subtle));
    let mut close = false;
    for (i, tone) in order.into_iter().enumerate() {
        let cell = Rect::from_min_size(button.min + vec2(0.0, 38.0 * i as f32), vec2(38.0, 38.0));
        let resp = ui.interact(cell, id.with(("tone", tone)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
        if resp.hovered() {
            ui.painter().rect_filled(cell, 4.0, t.bg_hover);
        }
        paint(ui, cell, tone);
        if resp.on_hover_text(NAMES[tone as usize]).on_hover_cursor(CursorIcon::PointingHand).clicked() {
            crate::emoji::set_skin_tone(tone);
            close = true;
        }
    }
    // A click anywhere else closes it without choosing.
    if close || ui.input(|i| i.pointer.any_click() && i.pointer.interact_pos().is_some_and(|p| !column.contains(p))) || ui.input(|i| i.key_pressed(Key::Escape)) {
        ui.ctx().data_mut(|d| d.insert_temp(id, false));
        ui.ctx().request_repaint();
    }
}

/// The strip at the bottom: the hovered item, big, with its name and where
/// it's from.
fn footer(ui: &Ui, t: &Theme, rect: Rect, picture: Option<&str>, title: &str, sub: &str, badge: Option<&Badge>) {
    let rounding = egui::Rounding { nw: 0.0, ne: 0.0, sw: 7.0, se: 7.0 };
    ui.painter().rect_filled(rect, rounding, sunken(t));
    ui.painter().hline(rect.x_range(), rect.top(), Stroke::new(1.0_f32, t.border_subtle));
    // (The rail's column runs down through it: the content starts after.)
    let mut x = rect.left() + RAIL + 16.0;
    if let Some(u) = picture {
        let r = Rect::from_center_size(pos2(x + 14.0, rect.center().y), vec2(28.0, 28.0));
        egui::Image::new(u).show_loading_spinner(false).paint_at(ui, r);
        x += 36.0;
    }
    let right = if badge.is_some() { rect.right() - 48.0 } else { rect.right() - 12.0 };
    let painter = ui.painter_at(Rect::from_min_max(pos2(x, rect.top()), pos2(right, rect.bottom())));
    if sub.is_empty() {
        paint_text_emoji(ui, &painter, pos2(x, rect.center().y), title, strong(16.0), t.header_primary);
    } else {
        paint_text_emoji(ui, &painter, pos2(x, rect.center().y - 7.0), title, strong(16.0), t.header_primary);
        paint_text_emoji(ui, &painter, pos2(x, rect.center().y + 11.0), sub, FontId::proportional(12.0), t.header_secondary);
    }
    if let Some(b) = badge {
        paint_badge(ui, t, Rect::from_center_size(pos2(rect.right() - 26.0, rect.center().y), vec2(24.0, 24.0)), b, t.interactive_normal);
    }
}

/// Only the hovered picture plays: when it changes, the last one's decoded
/// frames are dropped.
fn track_animation(ctx: &egui::Context, slot: &str, now: Option<String>) {
    let id = egui::Id::new(("expr_anim", slot));
    let before: Option<String> = ctx.data(|d| d.get_temp::<Option<String>>(id)).flatten();
    if before != now {
        if let Some(old) = before {
            ctx.forget_image(&old);
        }
        ctx.data_mut(|d| d.insert_temp(id, now));
    }
}

pub(super) fn stop_animation(ctx: &egui::Context, slot: &str) {
    track_animation(ctx, slot, None);
}

/// Animation frame for a hovered picture (`key` is the file plus `#anim`,
/// so its frames never replace the still's texture), if it's decoded.
fn playing(ui: &Ui, key: &str) -> Option<String> {
    animating().then(|| crate::video::current_frame(ui.ctx(), key, true)).flatten()
}

/// What to draw for a sticker `size` points square right now: its animation
/// frame while `play` (APNG, GIF and Lottie), else its still. Lottie
/// stickers (Discord's own packs) are drawn from their JSON, so their still is
/// the first frame drawn here too. None while nothing is ready yet.
pub(super) fn sticker_uri(ctx: &egui::Context, id: discord::model::Id, format: u8, size: f32, play: bool) -> Option<String> {
    let ppp = ctx.pixels_per_point();
    // Discord asks for 160 px, or 320 on high-density screens.
    let fetch = if ppp > 1.0 { 320 } else { 160 };
    let play = play && animating();
    if format == 3 {
        let json = Sticker::animated_url(id, 3, fetch)?;
        let px = (size * ppp).round().clamp(16.0, 512.0) as u32;
        let frame = play.then(|| crate::video::current_frame(ctx, &crate::video::lottie_key(&json, px, false), true)).flatten();
        return frame.or_else(|| crate::video::current_frame(ctx, &crate::video::lottie_key(&json, px, true), true));
    }
    let still = Sticker::image_url(id, format, fetch);
    if play {
        if let Some(anim) = Sticker::animated_url(id, format, fetch) {
            // `#anim` keeps the frames apart from the still's texture.
            if let Some(f) = crate::video::current_frame(ctx, &format!("{anim}#anim"), true) {
                return Some(f);
            }
        }
    }
    still
}

/// Draw a sticker into `rect` (a faint tile until it has loaded).
pub(super) fn paint_sticker(ui: &Ui, rect: egui::Rect, id: discord::model::Id, format: u8, play: bool, tint: Option<Color32>) {
    match sticker_uri(ui.ctx(), id, format, rect.width(), play) {
        Some(uri) => {
            let img = egui::Image::new(uri).show_loading_spinner(false).maintain_aspect_ratio(true);
            let img = match tint {
                Some(c) => img.tint(c),
                None => img,
            };
            img.paint_at(ui, rect);
        }
        None => {
            ui.painter().rect_filled(rect, 8.0, overlay(0.04));
        }
    }
}

// ---- poster frames (GIF / MP4 first frames) ---------------------------------

const POSTER: &str = "#rcposter";
const MAX_POSTER: u32 = 256;

/// The first frame of a GIF or MP4 file, small: tile backgrounds and
/// favourites without decoding whole clips.
fn poster(src: &str) -> String {
    format!("{src}{POSTER}")
}

enum Still {
    Pending,
    Ready(Arc<ColorImage>),
    Failed(String),
}

/// Image loader for `<url>#rcposter`, decoding on one background thread.
struct Posters {
    cache: Arc<Mutex<HashMap<String, Still>>>,
    jobs: Mutex<std::sync::mpsc::Sender<(String, Arc<[u8]>)>>,
}

static POSTERS: OnceLock<()> = OnceLock::new();

fn install_posters(ctx: &egui::Context) {
    if POSTERS.set(()).is_err() {
        return;
    }
    let cache: Arc<Mutex<HashMap<String, Still>>> = Default::default();
    let (tx, rx) = std::sync::mpsc::channel::<(String, Arc<[u8]>)>();
    let (shared, ctx2) = (cache.clone(), ctx.clone());
    let _ = std::thread::Builder::new().name("rustcord-posters".into()).spawn(move || {
        while let Ok((uri, bytes)) = rx.recv() {
            let still = match first_frame(&bytes) {
                Ok(img) => Still::Ready(Arc::new(img)),
                Err(e) => {
                    log::debug!("poster failed for {}: {e}", crate::net_images::log_url(&uri));
                    Still::Failed(e)
                }
            };
            if let Ok(mut c) = shared.lock() {
                // Only if not forgotten meanwhile.
                if matches!(c.get(&uri), Some(Still::Pending)) {
                    c.insert(uri, still);
                }
            }
            ctx2.request_repaint();
        }
    });
    ctx.add_image_loader(Arc::new(Posters { cache, jobs: Mutex::new(tx) }));
}

fn shrink(img: image::DynamicImage) -> ColorImage {
    let img = if img.width() > MAX_POSTER || img.height() > MAX_POSTER { img.thumbnail(MAX_POSTER, MAX_POSTER) } else { img };
    let rgba = img.to_rgba8();
    ColorImage::from_rgba_unmultiplied([rgba.width() as usize, rgba.height() as usize], rgba.as_raw())
}

fn first_frame(bytes: &[u8]) -> Result<ColorImage, String> {
    // Pictures, and a GIF's first frame.
    if let Ok(img) = image::load_from_memory(bytes) {
        return Ok(shrink(img));
    }
    #[cfg(windows)]
    {
        // An MP4 clip: decode one frame and stop.
        let mut first = None;
        let scale = |w: usize, h: usize, px: Vec<u8>| match image::RgbaImage::from_raw(w as u32, h as u32, px) {
            Some(img) => shrink(image::DynamicImage::ImageRgba8(img)),
            None => ColorImage::new([1, 1], Color32::TRANSPARENT),
        };
        crate::video::mp4_frames(bytes, &scale, &mut |_, img| {
            first = Some(img);
            false
        })?;
        first.ok_or_else(|| "no video frames".to_string())
    }
    #[cfg(not(windows))]
    Err("video stills need Windows".into())
}

impl ImageLoader for Posters {
    fn id(&self) -> &str {
        egui::generate_loader_id!(Posters)
    }

    fn load(&self, ctx: &egui::Context, uri: &str, _: SizeHint) -> ImageLoadResult {
        let Some(src) = uri.strip_suffix(POSTER) else { return Err(LoadError::NotSupported) };
        {
            let cache = self.cache.lock().map_err(|_| LoadError::Loading("poisoned".into()))?;
            match cache.get(uri) {
                Some(Still::Ready(image)) => return Ok(ImagePoll::Ready { image: image.clone() }),
                Some(Still::Pending) => return Ok(ImagePoll::Pending { size: None }),
                Some(Still::Failed(e)) => return Err(LoadError::Loading(e.clone())),
                None => {}
            }
        }
        match ctx.try_load_bytes(src)? {
            BytesPoll::Pending { size } => Ok(ImagePoll::Pending { size }),
            BytesPoll::Ready { bytes, .. } => {
                if let Ok(mut c) = self.cache.lock() {
                    c.insert(uri.to_string(), Still::Pending);
                }
                let sent = self.jobs.lock().map(|tx| tx.send((uri.to_string(), Arc::from(&bytes[..]))).is_ok()).unwrap_or(false);
                if sent {
                    Ok(ImagePoll::Pending { size: None })
                } else {
                    Err(LoadError::Loading("poster decoder not running".into()))
                }
            }
        }
    }

    fn forget(&self, uri: &str) {
        if let Ok(mut c) = self.cache.lock() {
            c.remove(uri);
        }
    }

    fn forget_all(&self) {
        if let Ok(mut c) = self.cache.lock() {
            c.clear();
        }
    }

    fn byte_size(&self) -> usize {
        self.cache
            .lock()
            .map(|c| c.values().map(|s| if let Still::Ready(i) = s { i.pixels.len() * 4 } else { 0 }).sum())
            .unwrap_or(0)
    }
}

// ---- items ------------------------------------------------------------------

#[derive(Clone)]
struct StickerItem {
    id: Id,
    name: String,
    format: u8,
    guild: Id,
}

#[derive(Clone)]
enum EmojiItem {
    Unicode { emoji: Cow<'static, str>, name: Cow<'static, str> },
    /// `locked`: needs Nitro in this channel (drawn with a lock, can't be
    /// picked).
    Custom { id: Id, name: String, animated: bool, locked: bool },
}

impl EmojiItem {
    fn locked(&self) -> bool {
        matches!(self, Self::Custom { locked: true, .. })
    }

    /// Still picture (animated emoji too: Discord serves their first frame).
    fn still(&self) -> String {
        match self {
            Self::Unicode { emoji, .. } => twemoji_url(emoji),
            Self::Custom { id, .. } => emoji_url(*id, false, 48),
        }
    }

    fn moving(&self) -> Option<String> {
        match self {
            Self::Custom { id, animated: true, .. } if ANIMATE_EMOJI.load(Relaxed) => Some(format!("{}#anim", emoji_url(*id, true, 48))),
            _ => None,
        }
    }

    fn label(&self) -> String {
        match self {
            Self::Unicode { name, .. } => format!(":{name}:"),
            Self::Custom { name, .. } => format!(":{name}:"),
        }
    }

    fn picked(&self) -> PickedEmoji {
        match self {
            Self::Unicode { emoji, .. } => PickedEmoji::Unicode(emoji.to_string()),
            Self::Custom { id, name, animated, .. } => PickedEmoji::Custom { id: *id, name: name.clone(), animated: *animated },
        }
    }
}

/// A GIF in a grid.
struct Tile {
    /// What gets sent.
    send: String,
    still: String,
    /// The animation's key (`<file>#anim`).
    moving: String,
    w: f32,
    h: f32,
    fav: FavoriteGif,
}

impl Tile {
    fn from_gif(g: &Gif) -> Self {
        let src = g.animated().to_string();
        let video = src.split(['?', '#']).next().is_some_and(|p| p.ends_with(".mp4"));
        // Without a still from Discord, the tile shows the clip's first frame
        // (decoded small, off the UI thread), never the whole animation.
        let still = match g.preview.as_deref().filter(|s| !s.is_empty()) {
            Some(p) if !p.split(['?', '#']).next().is_some_and(|p| p.ends_with(".gif") || p.ends_with(".mp4")) => p.to_string(),
            _ => poster(&src),
        };
        Self {
            send: g.url.clone(),
            still,
            moving: format!("{src}#anim"),
            w: g.width,
            h: g.height,
            fav: FavoriteGif { url: g.url.clone(), format: if video { 2 } else { 1 }, src, width: g.width as u32, height: g.height as u32, order: 0 },
        }
    }

    fn from_favourite(f: &FavoriteGif) -> Self {
        Self { send: f.url.clone(), still: poster(&f.src), moving: format!("{}#anim", f.src), w: f.width as f32, h: f.height as f32, fav: f.clone() }
    }
}

enum GifAction {
    Back,
    Send(String),
    Page(GifPage),
    Category(String),
    Favourite(FavoriteGif),
}

/// How long the pointer has to rest on a GIF before it plays (only when GIFs
/// don't play by themselves). Scrolling drags every tile under the pointer:
/// starting each one's download and decode on the way past made the grid
/// stutter.
const HOVER_SETTLE: f64 = 0.14;

/// The frame to draw for a GIF tile `rect`, playing it at the tile's size
/// (see [`crate::video::thumb_key`]). A clip not started yet waits while the
/// grid scrolls, so flinging past fifty tiles doesn't decode fifty clips.
/// Every clip asked for goes into `played`, to be let go with the picker.
fn tile_frame(ui: &Ui, rect: Rect, moving: &str, scrolling: bool, played: &mut Vec<String>) -> Option<String> {
    let ppp = ui.ctx().pixels_per_point();
    let key = crate::video::thumb_key(moving, rect.width() * ppp, rect.height() * ppp);
    if scrolling && !crate::video::known(&key) {
        return None;
    }
    let frame = playing(ui, &key);
    played.push(key);
    frame
}

/// Two-column masonry of GIFs. With `autoplay` (Discord's "Play GIFs when
/// Discord is focused") every tile in view plays, as in Discord; otherwise
/// tiles show a still and the hovered one plays once the pointer rests on
/// it. The hovered tile gets a star (favourite) when `favs` is loaded.
#[allow(clippy::too_many_arguments)]
fn masonry(ui: &mut Ui, t: &Theme, salt: &str, tiles: &[Tile], favs: Option<&Frecency>, autoplay: bool, action: &mut Option<GifAction>, played: &mut Vec<String>) {
    ScrollArea::vertical().id_salt(("gif_grid", salt)).auto_shrink([false, false]).show(ui, |ui| {
        let gap = 6.0;
        let col_w = ((ui.available_width() - gap) / 2.0).floor();
        let origin = ui.cursor().min;
        let mut heights = [0.0_f32; 2];
        // (Tile under the pointer, since when.) Scrolling restarts the wait.
        let rest_id = ui.id().with("gif_rest");
        let now = ui.input(|i| i.time);
        let scrolling = ui.input(|i| i.smooth_scroll_delta != egui::Vec2::ZERO || i.raw_scroll_delta != egui::Vec2::ZERO);
        let mut rest: (usize, f64) = ui.data(|d| d.get_temp(rest_id)).unwrap_or((usize::MAX, now));
        let mut any_hot = false;
        for (i, tile) in tiles.iter().enumerate() {
            let col = if heights[0] <= heights[1] { 0 } else { 1 };
            let h = if tile.w > 0.0 && tile.h > 0.0 { col_w * tile.h / tile.w } else { col_w }.clamp(60.0, 320.0);
            let rect = Rect::from_min_size(origin + vec2(col as f32 * (col_w + gap), heights[col]), vec2(col_w, h));
            heights[col] += h + gap;
            if !ui.is_rect_visible(rect) {
                continue;
            }
            let resp = ui.interact(rect, ui.id().with(("gif_tile", i)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            let hot = resp.hovered();
            ui.painter().rect_filled(rect, 6.0, overlay(0.06));
            if tile.still.ends_with(POSTER) {
                played.push(tile.still.clone());
            }
            let mut play = autoplay;
            if hot {
                any_hot = true;
                if rest.0 != i || scrolling {
                    rest = (i, now);
                }
                if now - rest.1 >= HOVER_SETTLE {
                    play = true;
                } else if !autoplay {
                    ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(HOVER_SETTLE));
                }
            }
            let frame = if play { tile_frame(ui, rect, &tile.moving, scrolling, played) } else { None };
            let uri = frame.unwrap_or_else(|| tile.still.clone());
            egui::Image::new(uri).rounding(6.0).show_loading_spinner(false).paint_at(ui, rect);
            if !hot {
                continue;
            }
            ui.painter().rect_stroke(rect, 6.0, Stroke::new(2.0_f32, t.accent));
            let mut on_star = false;
            if let Some(f) = favs {
                let fav = f.is_favorite_gif(&tile.fav.url);
                let sr = Rect::from_min_size(pos2(rect.right() - 34.0, rect.top() + 6.0), vec2(28.0, 28.0));
                on_star = ui.rect_contains_pointer(sr);
                ui.painter().rect_filled(sr, 6.0, Color32::from_black_alpha(if on_star { 210 } else { 150 }));
                let (glyph, c) = if fav { (GLYPH_STAR_FILLED, GOLD) } else { (GLYPH_STAR, if on_star { GOLD } else { Color32::WHITE }) };
                ui.painter().text(sr.center(), Align2::CENTER_CENTER, glyph, icon_font(15.0), c);
            }
            if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                *action = Some(if on_star { GifAction::Favourite(tile.fav.clone()) } else { GifAction::Send(tile.send.clone()) });
            }
        }
        if !any_hot {
            rest.0 = usize::MAX;
        }
        ui.data_mut(|d| d.insert_temp(rest_id, rest));
        ui.allocate_space(vec2(ui.available_width(), heights[0].max(heights[1])));
    });
}

/// Discord's trending-line glyph.
fn paint_trending(p: &egui::Painter, c: Pos2, color: Color32) {
    let s = Stroke::new(1.8_f32, color);
    p.rect_stroke(Rect::from_center_size(c, vec2(16.0, 14.0)), 3.0, s);
    p.add(egui::Shape::line(vec![c + vec2(-5.0, 3.0), c + vec2(-1.5, -0.5), c + vec2(1.0, 2.0), c + vec2(5.0, -2.5)], s));
}

/// The GIF tab's first page: Favourites, Trending GIFs and category tiles.
/// The GIF picker's first page: Favourites, Trending and Discord's categories,
/// each over a clip (`(still, clip)`) that plays like the grid's tiles.
#[allow(clippy::too_many_arguments)]
fn gif_home(ui: &mut Ui, t: &Theme, fav_bg: Option<(String, String)>, trending_bg: Option<(String, String)>, cats: &[(String, String)], autoplay: bool, action: &mut Option<GifAction>, played: &mut Vec<String>) {
    ScrollArea::vertical().id_salt("gif_home").auto_shrink([false, false]).show(ui, |ui| {
        let gap = 8.0;
        let w = ((ui.available_width() - gap) / 2.0).floor();
        let th = 110.0;
        let origin = ui.cursor().min;
        let count = 2 + cats.len();
        let scrolling = ui.input(|i| i.smooth_scroll_delta != egui::Vec2::ZERO || i.raw_scroll_delta != egui::Vec2::ZERO);
        for i in 0..count {
            let rect = Rect::from_min_size(origin + vec2((i % 2) as f32 * (w + gap), (i / 2) as f32 * (th + gap)), vec2(w, th));
            if !ui.is_rect_visible(rect) {
                continue;
            }
            let resp = ui.interact(rect, ui.id().with(("gif_home", i)), Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
            let hot = resp.hovered();
            let rounding = egui::Rounding::same(6.0);
            ui.painter().rect_filled(rect, rounding, overlay(0.08));
            let (label, bg) = match i {
                0 => ("Favourites", fav_bg.clone()),
                1 => ("Trending GIFs", trending_bg.clone()),
                _ => (cats[i - 2].0.as_str(), Some((poster(&cats[i - 2].1), format!("{}#anim", cats[i - 2].1)))),
            };
            if let Some((still, moving)) = bg {
                if still.ends_with(POSTER) {
                    played.push(still.clone());
                }
                // (Cropped to fill the tile: decoded as wide as the tile, at least.)
                let cover = Rect::from_min_size(rect.min, vec2(rect.width(), rect.width().max(rect.height())));
                let frame = if autoplay { tile_frame(ui, cover, &moving, scrolling, played) } else { None };
                paint_cover(ui, rect, frame.as_deref().unwrap_or(&still), rounding);
            }
            let shade = if i == 0 {
                rgba(t.accent.r(), t.accent.g(), t.accent.b(), if hot { 150 } else { 200 })
            } else {
                Color32::from_black_alpha(if hot { 90 } else { 140 })
            };
            ui.painter().rect_filled(rect, rounding, shade);
            if hot {
                ui.painter().rect_stroke(rect, rounding, Stroke::new(2.0_f32, if i == 0 { Color32::WHITE } else { t.accent }));
            }
            let font = strong(15.0);
            let text_w = ui.fonts(|f| f.layout_no_wrap(label.to_string(), font.clone(), Color32::WHITE).size().x);
            let mut x = rect.center().x - text_w / 2.0;
            if i == 1 {
                x += 12.0;
                paint_trending(ui.painter(), pos2(x - 16.0, rect.center().y), Color32::WHITE);
            }
            ui.painter_at(rect).text(pos2(x, rect.center().y), Align2::LEFT_CENTER, label, font, Color32::WHITE);
            if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                *action = Some(match i {
                    0 => GifAction::Page(GifPage::Favourites),
                    1 => GifAction::Page(GifPage::Trending),
                    _ => GifAction::Category(cats[i - 2].0.clone()),
                });
            }
        }
        ui.allocate_space(vec2(ui.available_width(), count.div_ceil(2) as f32 * (th + gap)));
    });
}

fn centred_note(ui: &Ui, t: &Theme, rect: Rect, text: &str) {
    ui.painter().text(rect.center_top() + vec2(0.0, 60.0), Align2::CENTER_CENTER, text, FontId::proportional(14.0), t.text_muted);
}

fn spinner_in(ui: &mut Ui, rect: Rect) {
    let r = Rect::from_center_size(rect.center_top() + vec2(0.0, 60.0), vec2(28.0, 28.0));
    ui.put(r, egui::Spinner::new().size(28.0));
}

/// Unicode emoji name ("thumbsup"), for Frequently Used.
fn unicode_name(e: &str) -> &'static str {
    CATEGORIES.iter().flat_map(|(_, items)| items.iter()).find(|(emoji, _)| *emoji == e).map(|(_, n)| *n).unwrap_or("")
}

impl RustCord {
    // ---- opening and closing --------------------------------------------

    /// A composer button: open the picker on `tab`, switch to it, or close
    /// the picker if that tab is already showing. `anchor`: the composer's
    /// top-right corner (the picker sits above it).
    pub fn toggle_expression(&mut self, channel: Id, tab: ExpressionTab, anchor: Pos2) {
        install_posters(&self.ctx);
        match self.compose.expression.as_mut() {
            Some(p) if p.channel == channel && p.tab == tab => self.close_expression(),
            Some(p) if p.channel == channel => {
                p.anchor = anchor;
                self.set_expression_tab(tab);
            }
            _ => {
                self.close_expression();
                self.emoji_picker = None;
                let frame = self.ctx.cumulative_pass_nr();
                self.compose.expression = Some(ExpressionPicker {
                    channel,
                    tab,
                    anchor,
                    opened_frame: frame,
                    tab_frame: frame,
                    sticker_search: String::new(),
                    sticker_hovered: None,
                    emoji_search: String::new(),
                    emoji_hovered: None,
                    gif_page: GifPage::Home,
                    favourites_search: String::new(),
                });
                self.enter_tab(tab);
            }
        }
    }

    /// Whether the composer of `channel` has the picker open on `tab`.
    pub fn expression_open(&self, channel: Id, tab: ExpressionTab) -> bool {
        self.compose.expression.as_ref().is_some_and(|p| p.channel == channel && p.tab == tab)
    }

    pub fn close_expression(&mut self) {
        if self.compose.expression.take().is_some() {
            self.close_gif_picker();
            stop_animation(&self.ctx, "expr");
            if self.emoji_picker.is_none() {
                forget_sections(&self.ctx);
            }
        }
    }

    fn set_expression_tab(&mut self, tab: ExpressionTab) {
        let frame = self.ctx.cumulative_pass_nr();
        let Some(p) = self.compose.expression.as_mut() else { return };
        if p.tab == tab {
            return;
        }
        let old = std::mem::replace(&mut p.tab, tab);
        p.tab_frame = frame;
        if old == ExpressionTab::Gifs {
            self.close_gif_picker();
        }
        stop_animation(&self.ctx, "expr");
        self.enter_tab(tab);
    }

    fn enter_tab(&mut self, tab: ExpressionTab) {
        let Some(channel) = self.compose.expression.as_ref().map(|p| p.channel) else { return };
        match tab {
            ExpressionTab::Gifs => {
                self.start_gif_search(channel);
                self.want_frecency();
            }
            ExpressionTab::Stickers => {
                if self.compose.recent_stickers.is_none() {
                    self.compose.recent_stickers = Some(crate::features::load_recent_stickers(self.config_dir.as_deref()));
                }
                self.want_frecency();
            }
            ExpressionTab::Emoji => {}
        }
    }

    // ---- Discord's frecency settings (favourite GIFs, sticker use) -------

    /// Fetch settings-proto 2 unless it's fresh or on its way.
    pub fn want_frecency(&mut self) {
        let fresh = self.compose.frecency_at.is_some_and(|t| t.elapsed() < Duration::from_secs(120));
        if self.demo || fresh || self.api_busy("expr:frecency") || self.api_busy("expr:fav") {
            return;
        }
        self.compose.frecency_at = Some(Instant::now());
        self.api("expr:frecency", Method::GET, FRECENCY_PATH, None);
    }

    fn frecency_tick(&mut self) {
        self.emoji_sync_tick();
        if let Some(r) = self.api_take("expr:frecency") {
            match r.map(|v| v["settings"].as_str().map(decode_frecency)) {
                Ok(Some(Ok(f))) => {
                    self.compose.frecency = Some(f);
                    self.replay_pending_emoji();
                }
                Ok(_) => log::warn!("frecency settings: couldn't decode"),
                Err(e) => log::warn!("frecency settings: {e}"),
            }
        }
        let Some(r) = self.api_take("expr:fav") else { return };
        let pending = self.compose.frecency_patch.take();
        match r {
            Ok(v) => {
                let fresh = v["settings"].as_str().and_then(|s| decode_frecency(s).ok());
                let out_of_date = v["out_of_date"].as_bool() == Some(true);
                match (fresh, out_of_date, pending) {
                    // Changed elsewhere meanwhile: apply RustCord's on top, once.
                    (Some(f), true, Some((gif, add, false))) => {
                        self.compose.frecency = Some(f);
                        self.replay_pending_emoji();
                        self.send_favorite(gif, add, true);
                    }
                    (Some(f), false, _) => {
                        self.compose.frecency = Some(f);
                        self.replay_pending_emoji();
                    }
                    _ => {
                        self.compose.frecency_at = None;
                        self.want_frecency();
                    }
                }
            }
            Err(e) => {
                self.toast(format!("Couldn't update your favourite GIFs: {e}"), true);
                self.compose.frecency_at = None;
                self.want_frecency();
            }
        }
    }

    /// The star on a GIF: favourite it, or unfavourite it.
    fn toggle_favorite_gif(&mut self, gif: FavoriteGif) {
        if self.api_busy("expr:fav") {
            return;
        }
        let Some(f) = self.compose.frecency.as_ref() else { return };
        let add = !f.is_favorite_gif(&gif.url);
        self.send_favorite(gif, add, false);
    }

    /// PATCH settings-proto 2 with just the favourite GIFs field (every
    /// other favourite and unknown field copied byte for byte), shown at once.
    fn send_favorite(&mut self, gif: FavoriteGif, add: bool, retried: bool) {
        let Some(f) = self.compose.frecency.as_mut() else { return };
        let patch = match encode_favorite_gif_patch(f, &gif, add) {
            Ok(p) => p,
            Err(e) => {
                self.toast(format!("Couldn't update your favourite GIFs: {e}"), true);
                return;
            }
        };
        let version = f.version;
        f.set_favorite_gif(&gif, add);
        self.compose.frecency_patch = Some((gif, add, retried));
        self.api("expr:fav", Method::PATCH, FRECENCY_PATH, Some(json!({ "settings": patch, "required_data_version": version })));
    }

    // ---- the popup --------------------------------------------------------

    pub fn expression_picker_ui(&mut self, ctx: &egui::Context) {
        self.frecency_tick();
        self.gif_search_tick();
        let Some(p) = self.compose.expression.as_ref() else { return };
        // Gone with its channel, or a reaction picker took over.
        if self.current_channel != Some(p.channel) || self.emoji_picker.is_some() {
            self.close_expression();
            return;
        }
        // Above the composer's right end, following it (window resized,
        // upload tray opened…).
        let anchor = match self.compose.composer_rect {
            Some((ch, r)) if ch == p.channel => r.right_top(),
            _ => p.anchor,
        };
        let (tab, opened, tab_frame) = (p.tab, p.opened_frame, p.tab_frame);
        // The Emoji tab's lists: your frecency settings and the server's top emoji.
        if tab == ExpressionTab::Emoji {
            let guild = self.store.channels.get(&p.channel).and_then(|c| c.guild_id);
            self.want_frecency();
            if let Some(g) = guild {
                self.want_top_emoji(g);
            }
        }
        let t = self.theme.clone();
        let frame = ctx.cumulative_pass_nr();
        let focus = frame <= tab_frame + 1;
        let screen = ctx.screen_rect();
        let w = W.min(screen.width() - 16.0);
        let h = H.min(anchor.y - screen.top() - 16.0).max(280.0);
        let pos = pos2(anchor.x - w, anchor.y - h - 8.0);
        let mut switch = None;
        let area = egui::Area::new(egui::Id::new("expression_picker"))
            .order(Order::Foreground)
            .fixed_pos(pos)
            .constrain(true)
            .show(ctx, |ui| {
                Frame::none().fill(t.bg_secondary).rounding(8.0).stroke(Stroke::new(1.0_f32, t.border_subtle)).shadow(shadow()).show(ui, |ui| {
                    ui.set_width(w);
                    ui.set_height(h);
                    let full = Rect::from_min_size(ui.max_rect().min, vec2(w, h));
                    let rects = panel_rects(full, true, tab != ExpressionTab::Gifs);
                    switch = tab_pills(ui, &t, rects.tabs, tab);
                    ui.painter().hline(full.x_range(), rects.body.top(), Stroke::new(1.0_f32, t.border_subtle));
                    match tab {
                        ExpressionTab::Gifs => self.gif_tab(ui, &t, &rects, focus),
                        ExpressionTab::Stickers => self.sticker_tab(ui, &t, &rects, focus),
                        ExpressionTab::Emoji => self.emoji_tab(ui, &t, &rects, focus),
                    }
                });
            });
        if let Some(tb) = switch {
            self.set_expression_tab(tb);
        }
        // A press outside closes it; the composer's own buttons toggle it.
        let panel = area.response.rect;
        let buttons = self.compose.expression_buttons;
        let pressed_outside = frame > opened + 1
            && ctx.input(|i| i.pointer.any_pressed())
            && ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !panel.contains(p) && !buttons.is_some_and(|b| b.contains(p)));
        if pressed_outside || ctx.input(|i| i.key_pressed(Key::Escape)) {
            self.close_expression();
        }
    }

    // ---- GIFs -------------------------------------------------------------

    fn gif_tab(&mut self, ui: &mut Ui, t: &Theme, r: &PanelRects, focus: bool) {
        let Some((channel, page)) = self.compose.expression.as_ref().map(|p| (p.channel, p.gif_page)) else { return };
        self.start_gif_search(channel);
        if !self.demo {
            self.api_get_once("expr:gifcats", GIF_CATEGORIES_PATH);
        }
        let frecency_busy = self.api_busy("expr:frecency");
        let cats: Vec<(String, String)> = match self.api_result("expr:gifcats") {
            Some(Ok(v)) => v["categories"]
                .as_array()
                .into_iter()
                .flatten()
                .filter_map(|c| Some((c["name"].as_str()?.to_string(), c["src"].as_str()?.to_string())))
                .filter(|(n, s)| !n.is_empty() && !s.is_empty())
                .collect(),
            _ => Vec::new(),
        };
        // (A real still, or the clip's first frame: never the whole animation.)
        let trending_bg = self.gif_trending.as_ref().and_then(|l| l.first()).map(|g| {
            let tile = Tile::from_gif(g);
            (tile.still, tile.moving)
        });
        // Discord's "Play GIFs when Discord is focused" (and RustCord focused,
        // reduced motion off: `playing` checks those).
        let autoplay = self.discord_setting("gif_auto_play", true);
        let mut action = None;
        let mut played = Vec::new();
        {
            let (Some(g), Some(p)) = (self.gif_picker.as_mut(), self.compose.expression.as_mut()) else { return };
            let favs = self.compose.frecency.as_ref();
            let searching = page != GifPage::Favourites && (!g.search.trim().is_empty() || g.query.is_some());

            // Search row: a back arrow and the page's name off the first page.
            let mut row = r.search;
            if searching || page != GifPage::Home {
                let br = Rect::from_min_size(row.min, vec2(30.0, row.height()));
                let b = ui.interact(br, egui::Id::new("gif_back"), Sense::click());
                ui.painter().text(br.center(), Align2::CENTER_CENTER, icon::BACK, icon_font(16.0), if b.hovered() { t.interactive_hover } else { t.interactive_normal });
                if b.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                    action = Some(GifAction::Back);
                }
                row.min.x = br.right() + 6.0;
                if !searching {
                    let title = if page == GifPage::Favourites { "Favourites" } else { "Trending GIFs" };
                    let tr = ui.painter().text(pos2(row.left(), row.center().y), Align2::LEFT_CENTER, title, strong(15.0), t.header_primary);
                    row.min.x = tr.right() + 12.0;
                }
            }
            let mut sui = ui.new_child(UiBuilder::new().max_rect(row));
            if page == GifPage::Favourites {
                search_field(&mut sui, t, &mut p.favourites_search, "Search Favourites", "gif_favourites", focus);
            } else {
                let (_, changed) = search_field(&mut sui, t, &mut g.search, "Search Tenor", "gifs", focus);
                if changed {
                    g.edited = Some(Instant::now());
                }
            }

            let body = Rect::from_min_max(pos2(r.body.left() + PAD - 4.0, r.body.top() + 8.0), pos2(r.body.right() - 6.0, r.body.bottom() - 6.0));
            let mut bui = ui.new_child(UiBuilder::new().max_rect(body));
            if page == GifPage::Favourites {
                match favs {
                    None if frecency_busy => spinner_in(&mut bui, body),
                    None => centred_note(ui, t, body, "Couldn't load your favourite GIFs."),
                    Some(f) => {
                        let q = p.favourites_search.trim().to_lowercase();
                        let tiles: Vec<Tile> = f
                            .favorite_gifs
                            .iter()
                            .filter(|g| q.is_empty() || g.url.to_lowercase().contains(&q) || g.src.to_lowercase().contains(&q))
                            .map(Tile::from_favourite)
                            .collect();
                        if tiles.is_empty() {
                            let note = if q.is_empty() { "No favourites yet: hover a GIF and click its star." } else { "No favourites match that search." };
                            centred_note(ui, t, body, note);
                        } else {
                            masonry(&mut bui, t, "favourites", &tiles, favs, autoplay, &mut action, &mut played);
                        }
                    }
                }
            } else if searching || page == GifPage::Trending {
                match &g.results {
                    None => spinner_in(&mut bui, body),
                    Some(Err(e)) => centred_note(ui, t, body, e),
                    Some(Ok(list)) if list.is_empty() => centred_note(ui, t, body, "No GIFs found. Try another search."),
                    Some(Ok(list)) => {
                        let tiles: Vec<Tile> = list.iter().map(Tile::from_gif).collect();
                        let salt = if searching { "results" } else { "trending" };
                        masonry(&mut bui, t, salt, &tiles, favs, autoplay, &mut action, &mut played);
                    }
                }
            } else {
                let fav_bg = favs.and_then(|f| f.favorite_gifs.first()).map(|g| (poster(&g.src), format!("{}#anim", g.src)));
                gif_home(&mut bui, t, fav_bg, trending_bg, &cats, autoplay, &mut action, &mut played);
            }
        }

        // Remember what was shown, to let it all go when the picker closes
        // (clips that scroll away give their frames back by themselves).
        if let Some(g) = self.gif_picker.as_mut() {
            g.shown.extend(played);
        }
        let frame = self.ctx.cumulative_pass_nr();
        match action {
            Some(GifAction::Send(url)) => self.send_gif(url),
            Some(GifAction::Favourite(gif)) => self.toggle_favorite_gif(gif),
            Some(GifAction::Page(next)) => {
                if let Some(p) = self.compose.expression.as_mut() {
                    p.gif_page = next;
                    p.tab_frame = frame;
                }
                if next == GifPage::Favourites {
                    self.want_frecency();
                }
            }
            Some(GifAction::Category(name)) => {
                if let Some(g) = self.gif_picker.as_mut() {
                    g.search = name.clone();
                    g.query = Some(name.clone());
                    g.results = None;
                    g.edited = None;
                    self.backend.send(Command::FetchGifs(Some(name)));
                }
            }
            Some(GifAction::Back) => {
                let trending = self.gif_trending.clone();
                if let Some(g) = self.gif_picker.as_mut().filter(|g| page != GifPage::Favourites && (g.query.is_some() || !g.search.is_empty())) {
                    g.search.clear();
                    g.edited = None;
                    if g.query.take().is_some() {
                        g.results = trending.map(Ok);
                    }
                }
                if let Some(p) = self.compose.expression.as_mut() {
                    p.gif_page = GifPage::Home;
                    p.favourites_search.clear();
                    p.tab_frame = frame;
                }
            }
            None => {}
        }
    }

    // ---- stickers ---------------------------------------------------------

    /// Every server's stickers you can see (this server first, then in your
    /// server list's order), with Frequently Used on top: Discord's ranking
    /// plus stickers sent from RustCord.
    fn sticker_sections(&self, channel: Id, query: &str) -> Sections<StickerItem> {
        let q = query.trim().to_lowercase();
        let here = self.store.channels.get(&channel).and_then(|c| c.guild_id);
        let total: usize = self.store.guilds.values().map(|g| g.guild.stickers.len()).sum();
        let frecency = self.compose.frecency.as_ref().map(|f| (f.version, f.stickers.len()));
        let recent: &[Id] = self.compose.recent_stickers.as_deref().unwrap_or(&[]);
        let sig = signature((&q, here, self.store.guilds.len(), self.store.guild_order.len(), total, frecency, recent));
        cached(&self.ctx, "stickers", sig, || {
            let mut order: Vec<Id> = Vec::with_capacity(self.store.guilds.len());
            order.extend(here);
            let mut seen: HashSet<Id> = order.iter().copied().collect();
            for g in self.store.guild_order.iter().chain(self.store.guilds.keys()) {
                if seen.insert(*g) {
                    order.push(*g);
                }
            }
            let mut by_id: HashMap<Id, StickerItem> = HashMap::new();
            let mut sections = Vec::new();
            for gid in order {
                let Some(g) = self.store.guilds.get(&gid) else { continue };
                let mut items = Vec::new();
                for s in g.guild.stickers.iter().filter(|s| s.available != Some(false)) {
                    let item = StickerItem { id: s.id, name: s.name.clone(), format: s.format_type, guild: gid };
                    if q.is_empty() || s.name.to_lowercase().contains(&q) || s.tags.to_lowercase().contains(&q) {
                        items.push(item.clone());
                    }
                    by_id.insert(s.id, item);
                }
                if !items.is_empty() {
                    sections.push(Section { key: gid.0, title: g.guild.name.clone(), badge: guild_badge(&g.guild), guild: Some(gid), locked: false, items });
                }
            }
            if q.is_empty() {
                let mut seen = HashSet::new();
                let discord = self.compose.frecency.as_ref().map(|f| f.stickers.as_slice()).unwrap_or(&[]);
                let items: Vec<StickerItem> = recent
                    .iter()
                    .chain(discord)
                    .filter(|id| seen.insert(**id))
                    .filter_map(|id| by_id.get(id).cloned())
                    .take(FREQUENT_STICKERS)
                    .collect();
                if !items.is_empty() {
                    sections.insert(0, Section { key: 0, title: "Frequently Used".into(), badge: Badge::Recent, guild: None, locked: false, items });
                }
            }
            sections
        })
    }

    fn sticker_tab(&mut self, ui: &mut Ui, t: &Theme, r: &PanelRects, focus: bool) {
        let Some(p) = self.compose.expression.as_mut() else { return };
        let channel = p.channel;
        let mut search = std::mem::take(&mut p.sticker_search);
        let mut shown = p.sticker_hovered;
        let mut sui = ui.new_child(UiBuilder::new().max_rect(r.search));
        let (resp, _) = search_field(&mut sui, t, &mut search, "Find the perfect sticker", "stickers", focus);
        let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));

        let sections = self.sticker_sections(channel, &search);
        let here = self.store.channels.get(&channel).and_then(|c| c.guild_id);
        let nitro = self.store.me.as_ref().and_then(|m| m.premium_type).unwrap_or(0) > 0;
        let locked = |s: &StickerItem| !nitro && Some(s.guild) != here;
        // Discord's "Sticker animation" setting: 2 = never.
        let animate = super::sticker_animation() != 2;
        let (mut send, mut hovered) = (None, None);
        if sections.is_empty() {
            let msg = if search.trim().is_empty() { "No stickers here yet" } else { "No stickers match that search" };
            centred_note(ui, t, r.body, msg);
        } else {
            let (rail_r, grid_r) = split_body(r.body);
            ui.painter().rect_filled(rail_r, 0.0, sunken(t));
            let mem = egui::Id::new("expr_stickers");
            let mut collapsed: HashSet<u64> = ui.ctx().data(|d| d.get_temp(mem.with("collapsed"))).unwrap_or_default();
            let active: usize = ui.ctx().data(|d| d.get_temp(mem.with("active"))).unwrap_or(0);
            let mut rui = ui.new_child(UiBuilder::new().max_rect(rail_r));
            let jump = rail(&mut rui, t, mem.with("rail"), &sections, active);
            let layout = grid_layout(&sections, grid_r.width(), 4, &collapsed);
            let mut gui = ui.new_child(UiBuilder::new().max_rect(grid_r));
            let (active, toggled) = section_grid(&mut gui, t, mem.with("grid"), &sections, &layout, &collapsed, jump, |ui, cell, si, i| {
                let s = &sections[si].items[i];
                let lock = locked(s);
                let resp = ui.interact(cell, mem.with(("cell", si, i)), if lock { Sense::hover() } else { Sense::click() });
                let hot = resp.hovered();
                if hot {
                    hovered = Some(s.id);
                    if !lock {
                        ui.painter().rect_filled(cell.shrink(2.0), 8.0, overlay(0.1));
                    }
                }
                let inner = cell.shrink(8.0);
                // Discord's picker plays a sticker while it's hovered (unless
                // sticker animation is off).
                paint_sticker(ui, inner, s.id, s.format, hot && animate, lock.then(|| crate::style::rgba(255, 255, 255, 90)));
                if resp.on_hover_cursor(if lock { CursorIcon::NotAllowed } else { CursorIcon::PointingHand }).clicked() {
                    send = Some(s.id);
                }
            });
            ui.ctx().data_mut(|d| d.insert_temp(mem.with("active"), active));
            if let Some(k) = toggled {
                if !collapsed.remove(&k) {
                    collapsed.insert(k);
                }
                ui.ctx().data_mut(|d| d.insert_temp(mem.with("collapsed"), collapsed));
            }
            if enter && !search.trim().is_empty() {
                send = sections.iter().flat_map(|s| s.items.iter()).find(|s| !locked(s)).map(|s| s.id);
            }
        }
        // Footer: the hovered sticker (else the last one, else the first).
        if hovered.is_some() {
            shown = hovered;
        }
        let all = || sections.iter().flat_map(|s| s.items.iter());
        let item = shown.and_then(|id| all().find(|s| s.id == id)).or_else(|| all().next());
        match item {
            Some(s) => {
                let g = self.store.guilds.get(&s.guild);
                let sub = if locked(s) {
                    "Get Nitro to use stickers from other servers".to_string()
                } else {
                    format!("from {}", g.map(|g| g.guild.name.as_str()).unwrap_or("a server"))
                };
                let picture = sticker_uri(ui.ctx(), s.id, s.format, 28.0, false);
                let badge = g.map(|g| guild_badge(&g.guild));
                footer(ui, t, r.footer, picture.as_deref(), &s.name, &sub, badge.as_ref());
            }
            None => footer(ui, t, r.footer, None, "", "", None),
        }

        if let Some(p) = self.compose.expression.as_mut() {
            p.sticker_search = search;
            p.sticker_hovered = shown;
        }
        if let Some(id) = send {
            self.send_sticker(channel, id);
        }
    }

    fn send_sticker(&mut self, channel: Id, id: Id) {
        let mut body = json!({ "content": "", "sticker_ids": [id.to_string()], "nonce": Id::from_timestamp_ms(crate::app::now_ms()).0.to_string() });
        // Replying: the sticker is the reply, like a GIF or text would be.
        if let Some(r) = self.reply.take_if(|r| r.channel == channel) {
            body["message_reference"] = json!({ "message_id": r.msg.to_string(), "channel_id": channel.to_string() });
            if !r.mention {
                body["allowed_mentions"] = json!({ "parse": ["users", "roles", "everyone"], "replied_user": false });
            }
        }
        self.api("sticker:send", Method::POST, format!("/channels/{channel}/messages"), Some(body));
        // Discord only learns what you use from the client: remember it here.
        let list = self.compose.recent_stickers.get_or_insert_with(Vec::new);
        list.retain(|s| *s != id);
        list.insert(0, id);
        list.truncate(FREQUENT_STICKERS);
        crate::features::save_recent_stickers(self.config_dir.as_deref(), list);
        self.close_expression();
    }

    // ---- emoji ------------------------------------------------------------

    /// Frequently Used, every server's emoji (the channel's server first)
    /// and the Unicode categories, filtered by `query`. Other servers' are
    /// left out where `rules` hide them.
    /// Like Discord's: Favourites, Top Emoji in this server (one row), then
    /// Frequently Used from your frecency settings (emoji you send, or for
    /// `reacting` the reactions you give), server emoji included.
    fn emoji_sections(&self, query: &str, rules: EmojiRules, reacting: bool) -> Sections<EmojiItem> {
        let q = query.trim().trim_matches(':').to_lowercase();
        let total: usize = self.store.guilds.values().map(|g| g.guild.emojis.len()).sum();
        let tone = crate::emoji::skin_tone();
        let first = rules.here.or(self.current_guild);
        let frecency = self.compose.frecency.as_ref();
        let top = first.map(|g| self.top_emoji(g)).unwrap_or_default();
        // (The minute: rankings age with the clock.)
        let minute = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() / 60);
        let used = (frecency.map(|f| f.version), self.compose.emoji_pending.len(), top.len(), minute);
        let sig = signature((&q, first, rules, self.store.guilds.len(), self.store.guild_order.len(), total, &self.frequent, tone, reacting, used));
        cached(&self.ctx, "emoji", sig, || {
            let mut sections = Vec::new();
            if q.is_empty() {
                // Server emoji by ID, wherever you share a server with them.
                let custom = |id: Id| -> Option<EmojiItem> {
                    self.store.guilds.iter().find_map(|(gid, g)| {
                        let e = g.guild.emojis.iter().find(|e| e.id == Some(id) && e.available != Some(false))?;
                        let locked = match rules.access(*gid, e.animated, e.managed) {
                            EmojiAccess::Usable => false,
                            EmojiAccess::Locked => true,
                            EmojiAccess::Hidden => return None,
                        };
                        Some(EmojiItem::Custom { id, name: e.name.clone()?, animated: e.animated, locked })
                    })
                };
                // A key from Discord's lists: a server emoji's ID or a Unicode name.
                let item = |key: &str| -> Option<EmojiItem> {
                    match key.parse::<u64>() {
                        Ok(id) if id > 1 << 32 => custom(Id(id)),
                        _ => {
                            let e = super::emoji_frecency::unicode_from_key(key)?;
                            Some(EmojiItem::Unicode { emoji: Cow::Owned(e), name: Cow::Owned(key.to_string()) })
                        }
                    }
                };
                if let Some(f) = frecency.filter(|f| !f.favorite_emoji.is_empty()) {
                    let items: Vec<EmojiItem> = f.favorite_emoji.iter().filter_map(|k| item(k)).collect();
                    if !items.is_empty() {
                        sections.push(Section { key: 1 << 62, title: "Favourites".into(), badge: Badge::Favourite, guild: None, locked: false, items });
                    }
                }
                if let Some(g) = first.and_then(|g| self.store.guilds.get(&g)).filter(|_| !reacting || !top.is_empty()) {
                    // (One row, as Discord shows: nine.)
                    let items: Vec<EmojiItem> = top.iter().filter_map(|id| custom(*id)).take(9).collect();
                    if !items.is_empty() {
                        sections.push(Section { key: (1 << 62) + 1, title: format!("Top Emoji in {}", g.guild.name), badge: guild_badge(&g.guild), guild: Some(g.guild.id), locked: false, items });
                    }
                }
                let items: Vec<EmojiItem> = match frecency {
                    Some(f) => {
                        let now = minute * 60_000;
                        let keys = if reacting { f.frequent_reactions(now) } else { f.frequent_emoji(now) };
                        keys.iter().filter_map(|k| item(k)).collect()
                    }
                    // (Until Discord's lists arrive, or in the demo: the local one.)
                    None => self.frequent.iter().map(|e| EmojiItem::Unicode { emoji: Cow::Owned(e.clone()), name: Cow::Borrowed(unicode_name(e)) }).collect(),
                };
                if !items.is_empty() {
                    sections.push(Section { key: 0, title: "Frequently Used".into(), badge: Badge::Recent, guild: None, locked: false, items });
                }
            }
            let mut guilds = self.store.guild_order.clone();
            if let Some(g) = first {
                guilds.retain(|x| *x != g);
                guilds.insert(0, g);
            }
            for gid in guilds {
                let Some(g) = self.store.guilds.get(&gid) else { continue };
                let items: Vec<EmojiItem> = g
                    .guild
                    .emojis
                    .iter()
                    .filter(|e| e.available != Some(false))
                    .filter_map(|e| {
                        let (id, name) = (e.id?, e.name.as_ref()?);
                        let locked = match rules.access(gid, e.animated, e.managed) {
                            EmojiAccess::Usable => false,
                            EmojiAccess::Locked => true,
                            EmojiAccess::Hidden => return None,
                        };
                        (q.is_empty() || name.to_lowercase().contains(&q)).then(|| EmojiItem::Custom { id, name: name.clone(), animated: e.animated, locked })
                    })
                    .collect();
                if !items.is_empty() {
                    let locked = items.iter().all(EmojiItem::locked);
                    sections.push(Section { key: gid.0, title: g.guild.name.clone(), badge: guild_badge(&g.guild), guild: Some(gid), locked, items });
                }
            }
            for (ci, (cat, list)) in CATEGORIES.iter().enumerate() {
                let items: Vec<EmojiItem> = list
                    .iter()
                    // (By name, another shortcode, or a describing word.)
                    .filter(|(e, n)| q.is_empty() || crate::emoji::search_rank(e, n, &q).is_some())
                    // (In the picker's skin tone, where the emoji has tones.)
                    .map(|(e, n)| EmojiItem::Unicode { emoji: Cow::Borrowed(crate::emoji::toned(e, tone).unwrap_or(*e)), name: Cow::Borrowed(*n) })
                    .collect();
                if let Some((first, _)) = list.first().filter(|_| !items.is_empty()) {
                    sections.push(Section { key: ci as u64 + 1, title: cat.to_string(), badge: Badge::Emoji(twemoji_url(first)), guild: None, locked: false, items });
                }
            }
            sections
        })
    }

    /// The emoji picker's search box, rail, grid and footer in `r` (the
    /// Emoji tab, and the reaction picker on its own) for an emoji going to
    /// `channel`. Returns a pick, and whether Shift was held (pick several).
    /// Emoji that need Nitro there show a lock and can't be picked (Discord
    /// opens a Nitro ad instead; RustCord doesn't copy that).
    #[allow(clippy::too_many_arguments)]
    pub(super) fn emoji_panel(
        &self,
        ui: &mut Ui,
        t: &Theme,
        r: &PanelRects,
        salt: &str,
        channel: Option<Id>,
        search: &mut String,
        shown: &mut Option<(String, String, Option<Id>)>,
        hint: &str,
        focus: bool,
    ) -> Option<(PickedEmoji, bool)> {
        // Discord's skin tone button: 38 px, 12 px right of the search box.
        let tone_button = Rect::from_center_size(pos2(r.search.right() - 19.0, r.search.center().y), vec2(38.0, 38.0));
        let mut sui = ui.new_child(UiBuilder::new().max_rect(r.search.with_max_x(tone_button.left() - 12.0)));
        let (resp, _) = search_field(&mut sui, t, search, hint, salt, focus);
        let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));
        let sections = self.emoji_sections(search, self.emoji_rules(channel), salt == "react");
        let (mut picked, mut hovered, mut anim_now) = (None, None, None);
        if sections.is_empty() {
            centred_note(ui, t, r.body, "No emoji match that search.");
        } else {
            let (rail_r, grid_r) = split_body(r.body);
            ui.painter().rect_filled(rail_r, 0.0, sunken(t));
            let mem = egui::Id::new(("expr_emoji", salt));
            let mut collapsed: HashSet<u64> = ui.ctx().data(|d| d.get_temp(mem.with("collapsed"))).unwrap_or_default();
            let active: usize = ui.ctx().data(|d| d.get_temp(mem.with("active"))).unwrap_or(0);
            let mut rui = ui.new_child(UiBuilder::new().max_rect(rail_r));
            // (The "standard emoji" button below the rail was pressed last frame.)
            let pending: Option<usize> = ui.ctx().data_mut(|d| d.remove_temp(mem.with("jump")));
            let jump = rail(&mut rui, t, mem.with("rail"), &sections, active).or(pending);
            let cols = ((grid_r.width() / CELL).floor() as usize).max(6);
            let layout = grid_layout(&sections, grid_r.width(), cols, &collapsed);
            let mut gui = ui.new_child(UiBuilder::new().max_rect(grid_r));
            let (active, toggled) = section_grid(&mut gui, t, mem.with("grid"), &sections, &layout, &collapsed, jump, |ui, cell, si, i| {
                let section = &sections[si];
                let e = &section.items[i];
                let lock = e.locked();
                let resp = ui.interact(cell, mem.with(("cell", si, i)), if lock { Sense::hover() } else { Sense::click() });
                let mut uri = e.still();
                if resp.hovered() {
                    ui.painter().rect_filled(cell, 4.0, t.bg_hover);
                    hovered = Some((uri.clone(), e.label(), section.guild));
                    if let Some(key) = e.moving() {
                        if let Some(f) = playing(ui, &key) {
                            uri = f;
                        }
                        anim_now = Some(key);
                    }
                }
                let size = (cell.width() - 8.0).clamp(20.0, 40.0);
                let pic = Rect::from_center_size(cell.center(), vec2(size, size));
                egui::Image::new(uri).show_loading_spinner(false).paint_at(ui, pic);
                if lock {
                    // Discord's locked emoji: 60 % black over it, a 16 px lock.
                    ui.painter().rect_filled(pic, 2.0, Color32::from_black_alpha(153));
                    ui.painter().text(pic.center(), Align2::CENTER_CENTER, icon::LOCK, icon_font(16.0), t.interactive_normal);
                    resp.on_hover_cursor(CursorIcon::NotAllowed);
                } else if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                    picked = Some((e.picked(), ui.input(|i| i.modifiers.shift)));
                }
            });
            ui.ctx().data_mut(|d| d.insert_temp(mem.with("active"), active));
            if let Some(k) = toggled {
                if !collapsed.remove(&k) {
                    collapsed.insert(k);
                }
                ui.ctx().data_mut(|d| d.insert_temp(mem.with("collapsed"), collapsed));
            }
            if enter && !search.trim().is_empty() {
                picked = sections.iter().flat_map(|s| s.items.iter()).find(|e| !e.locked()).map(|e| (e.picked(), false));
            }
        }
        track_animation(ui.ctx(), salt, anim_now);
        if hovered.is_some() {
            *shown = hovered;
        }
        match shown.as_ref() {
            Some((url, name, guild)) => {
                let g = guild.and_then(|g| self.store.guilds.get(&g));
                let sub = g.map(|g| format!("from {}", g.guild.name)).unwrap_or_default();
                let badge = g.map(|g| guild_badge(&g.guild));
                footer(ui, t, r.footer, Some(url), name, &sub, badge.as_ref());
            }
            None => footer(ui, t, r.footer, None, "Shift-click to pick several.", "", None),
        }
        skin_tone_selector(ui, t, tone_button, salt);
        // Discord's button under the rail: straight to the standard emoji,
        // however many servers' emoji come before them.
        let standard = sections.iter().position(|s| s.guild.is_none() && s.key != 0);
        if let Some(first) = standard {
            let br = Rect::from_min_size(pos2(r.footer.left(), r.footer.top()), vec2(RAIL - 1.0, r.footer.height()));
            let resp = ui.interact(br, egui::Id::new(("expr_emoji_standard", salt)), Sense::click());
            let c = if resp.hovered() { t.interactive_hover } else { t.header_secondary };
            ui.painter().text(br.center(), Align2::CENTER_CENTER, icon::EMOJI, icon_font(22.0), c);
            if resp.on_hover_text("Scroll to standard emoji").on_hover_cursor(CursorIcon::PointingHand).clicked() {
                ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new(("expr_emoji", salt)).with("jump"), first));
                ui.ctx().request_repaint();
            }
        }
        picked
    }

    fn emoji_tab(&mut self, ui: &mut Ui, t: &Theme, r: &PanelRects, focus: bool) {
        let Some(p) = self.compose.expression.as_mut() else { return };
        let channel = p.channel;
        let mut search = std::mem::take(&mut p.emoji_search);
        let mut shown = p.emoji_hovered.take();
        let picked = self.emoji_panel(ui, t, r, "expr", Some(channel), &mut search, &mut shown, "Find the perfect emoji", focus);
        if let Some(p) = self.compose.expression.as_mut() {
            p.emoji_search = search;
            p.emoji_hovered = shown;
        }
        if let Some((value, keep)) = picked {
            // The composer path of `pick_emoji` (draft text, Frequently Used).
            self.emoji_picker = Some(EmojiPicker { target: PickerTarget::Insert { channel }, pos: Pos2::ZERO, search: String::new(), opened_frame: 0, hovered: None });
            self.pick_emoji(value, false);
            self.emoji_picker = None;
            if !keep {
                self.close_expression();
                self.compose.focus_composer = true;
            }
        }
    }
}