Skip to content

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

32.3 KB
Raw Blame
//! Keyboard shortcuts: RustCord's list of them (User Settings → Keybinds and
//! Discord's "Keyboard Combos" dialog, Ctrl + / or ⌘ / on macOS) and the
//! app-wide keys themselves. Ctrl on Windows and Linux is ⌘ on macOS.

use crate::app::{RustCord, Screen};
use crate::style::{overlay, Theme};
use eframe::egui::{
    self, load::Bytes, pos2, vec2, Align2, Color32, CursorIcon, FontId, ImageSource, Key, Modifiers, Order, Rect, Rounding, Sense, Stroke, Ui,
};
use std::time::{Duration, Instant};

pub const MAC: bool = cfg!(target_os = "macos");

/// One key of a combination.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeyToken {
    /// Ctrl, or ⌘ on macOS (Discord's "mod").
    Mod,
    Alt,
    Shift,
    Enter,
    Esc,
    Tab,
    Up,
    Down,
    Left,
    Right,
    Text(&'static str),
}
use KeyToken as K;

#[derive(Clone, Copy, PartialEq, Eq)]
enum Platforms {
    All,
    Mac,
    NotMac,
}

pub struct Shortcut {
    pub label: &'static str,
    /// Each combination on its own line (back, then forward).
    pub combos: &'static [&'static [KeyToken]],
    on: Platforms,
}

const fn all(label: &'static str, combos: &'static [&'static [KeyToken]]) -> Shortcut {
    Shortcut { label, combos, on: Platforms::All }
}

const fn mac(label: &'static str, combos: &'static [&'static [KeyToken]]) -> Shortcut {
    Shortcut { label, combos, on: Platforms::Mac }
}

const fn not_mac(label: &'static str, combos: &'static [&'static [KeyToken]]) -> Shortcut {
    Shortcut { label, combos, on: Platforms::NotMac }
}

/// What RustCord answers to, in Discord's groups and, where Discord has the
/// same shortcut, with its wording.
const GROUPS: &[(&str, &[Shortcut])] = &[
    (
        "Messages",
        &[
            all("Edit your last message (empty box)", &[&[K::Up]]),
            all("Save an edit", &[&[K::Enter]]),
            all("Cancel an edit", &[&[K::Esc]]),
            all("Select messages (MessageSelect plugin)", &[&[K::Mod, K::Shift, K::Text("CLICK")]]),
            all("Copy the selected messages", &[&[K::Mod, K::Text("C")]]),
        ],
    ),
    (
        "Navigation",
        &[
            not_mac("Navigate forward and backward in page history", &[&[K::Alt, K::Left], &[K::Alt, K::Right]]),
            mac("Navigate forward and backward in page history", &[&[K::Mod, K::Text("[")], &[K::Mod, K::Text("]")]]),
            all("Toggle QuickSwitcher", &[&[K::Mod, K::Text("K")]]),
        ],
    ),
    (
        "Voice and Video",
        &[all("Toggle mute", &[&[K::Mod, K::Shift, K::Text("M")]]), all("Toggle deafen", &[&[K::Mod, K::Shift, K::Text("D")]])],
    ),
    (
        "Chat",
        &[
            all("Send message", &[&[K::Enter]]),
            all("New line", &[&[K::Shift, K::Enter]]),
            all("Mark channel as read or cancel a reply", &[&[K::Esc]]),
            all("Pick from a mention, emoji or command list", &[&[K::Tab]]),
            all("Move in a mention, emoji or command list", &[&[K::Up], &[K::Down]]),
        ],
    ),
    (
        "Miscellaneous",
        &[
            all("Search", &[&[K::Mod, K::Text("F")]]),
            all("Open User Settings", &[&[K::Mod, K::Text(",")]]),
            all("Zoom in or out", &[&[K::Mod, K::Text("+")], &[K::Mod, K::Text("-")]]),
            all("Reset zoom", &[&[K::Mod, K::Text("0")]]),
            all("Reload RustCord", &[&[K::Mod, K::Text("R")]]),
            all("Close a window or menu", &[&[K::Esc]]),
            mac("Close the window", &[&[K::Mod, K::Text("W")]]),
        ],
    ),
];

/// The groups as this platform has them.
pub fn groups(mac: bool) -> impl Iterator<Item = (&'static str, Vec<&'static Shortcut>)> {
    GROUPS
        .iter()
        .map(move |(name, list)| {
            let shown = list.iter().filter(|s| match s.on {
                Platforms::All => true,
                Platforms::Mac => mac,
                Platforms::NotMac => !mac,
            });
            (*name, shown.collect::<Vec<_>>())
        })
        .filter(|(_, list)| !list.is_empty())
}

/// A key's text, as Discord's key combos write it (upper case; macOS gets its
/// symbols).
pub fn key_text(k: KeyToken, mac: bool) -> &'static str {
    match (k, mac) {
        (K::Mod, false) => "CTRL",
        (K::Mod, true) => "⌘",
        (K::Alt, false) => "ALT",
        (K::Alt, true) => "⌥",
        (K::Shift, false) => "SHIFT",
        (K::Shift, true) => "⇧",
        (K::Enter, false) => "ENTER",
        (K::Enter, true) => "⏎",
        (K::Esc, _) => "ESC",
        (K::Tab, _) => "TAB",
        (K::Up, false) => "↑",
        (K::Up, true) => "▲",
        (K::Down, false) => "↓",
        (K::Down, true) => "▼",
        (K::Left, false) => "←",
        (K::Left, true) => "◀",
        (K::Right, false) => "→",
        (K::Right, true) => "▶",
        (K::Text(s), _) => s,
    }
}

/// A combination written inline: "Ctrl+/" (macOS: "⌘/").
pub fn hint(combo: &[KeyToken], mac: bool) -> String {
    let word = |k: KeyToken| match (k, mac) {
        (K::Mod, false) => "Ctrl",
        (K::Alt, false) => "Alt",
        (K::Shift, false) => "Shift",
        (K::Enter, false) => "Enter",
        (K::Esc, _) => "Esc",
        (K::Tab, _) => "Tab",
        _ => key_text(k, mac),
    };
    combo.iter().map(|&k| word(k)).collect::<Vec<_>>().join(if mac { "" } else { "+" })
}

/// The combination that opens and closes the Keyboard Combos dialog.
pub const COMBOS_TOGGLE: &[KeyToken] = &[K::Mod, K::Text("/")];

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Action {
    Reload,
    QuickSwitcher,
    Settings,
    Combos,
    Search,
    Back,
    Forward,
    ZoomIn,
    ZoomOut,
    ZoomReset,
    Mute,
    Deafen,
    CloseWindow,
}

impl Action {
    /// Zoom and closing the window also work before you're signed in.
    const fn signed_in_only(self) -> bool {
        !matches!(self, Self::ZoomIn | Self::ZoomOut | Self::ZoomReset | Self::CloseWindow)
    }

    /// Holding the keys repeats it.
    const fn repeats(self) -> bool {
        matches!(self, Self::ZoomIn | Self::ZoomOut)
    }
}

/// The app-wide action for a key press, if any. Never with Alt held (except
/// Discord's Alt + ← / → off macOS), so AltGr letters still type and the
/// text box keeps Ctrl's text-editing keys on macOS.
pub(crate) fn action(key: Key, m: Modifiers, mac: bool) -> Option<Action> {
    if !mac && m.alt && !m.ctrl && !m.shift {
        return match key {
            Key::ArrowLeft => Some(Action::Back),
            Key::ArrowRight => Some(Action::Forward),
            _ => None,
        };
    }
    if !m.command || m.alt {
        return None;
    }
    let plain = !m.shift;
    Some(match key {
        Key::R => Action::Reload,
        Key::K if plain => Action::QuickSwitcher,
        Key::Comma if plain => Action::Settings,
        Key::Slash | Key::Questionmark => Action::Combos,
        Key::F if plain => Action::Search,
        Key::OpenBracket if mac && plain => Action::Back,
        Key::CloseBracket if mac && plain => Action::Forward,
        Key::Plus | Key::Equals => Action::ZoomIn,
        Key::Minus => Action::ZoomOut,
        Key::Num0 => Action::ZoomReset,
        Key::M if m.shift => Action::Mute,
        Key::D if m.shift => Action::Deafen,
        Key::W if mac && plain => Action::CloseWindow,
        _ => return None,
    })
}

/// One zoom step, in tenths, within Settings → Appearance's 50–200%.
pub fn zoom_step(current: f32, delta: f32) -> f32 {
    (((current + delta) * 10.0).round() / 10.0).clamp(0.5, 2.0)
}

/// A keyboard zoom goes to prefs.json once the keys have rested this long
/// (held keys repeat).
const ZOOM_SAVE_DELAY: Duration = Duration::from_millis(500);

const COMBOS_DIM: &str = "keyboard_combos_dim";

/// Whether a dialog other than Keyboard Combos is up. Every RustCord dialog
/// dims the whole window with a layer of its own, so its covering layer
/// (as of the last frame) is enough: no list of dialogs to keep up to date.
fn other_dialog_up(ctx: &egui::Context) -> bool {
    let screen = ctx.screen_rect().shrink(1.0);
    let combos_dim = egui::Id::new(COMBOS_DIM);
    ctx.memory(|m| {
        m.layer_ids().any(|l| {
            matches!(l.order, Order::Foreground | Order::Tooltip)
                && l.id != combos_dim
                && m.areas().visible_last_frame(&l)
                && m.area_rect(l.id).is_some_and(|r| r.contains_rect(screen))
        })
    })
}

/// The dance arrows' keys, left to right.
const ARROW_KEYS: [Key; 4] = [Key::ArrowLeft, Key::ArrowDown, Key::ArrowUp, Key::ArrowRight];

impl RustCord {
    fn focus_search(&self, ctx: &egui::Context) {
        if self.settings_open {
            if !super::connections::dialog_open(ctx) {
                ctx.memory_mut(|m| m.request_focus(egui::Id::new("settings_search_edit")));
            }
            return;
        }
        if self.shortcuts_open || other_dialog_up(ctx) {
            return;
        }
        let home = self.current_guild.is_none() && (self.friends_open || self.current_channel.is_none());
        if home {
            if !self.requests_open && self.store_page.is_none() && self.friends_tab != crate::features::FriendsTab::AddFriend {
                ctx.memory_mut(|m| m.request_focus(egui::Id::new("friends_search_edit")));
            }
        } else if self.current_channel.is_some() && !self.guild_page_active() && !self.showing_call_view() {
            ctx.memory_mut(|m| m.request_focus(egui::Id::new("chat_search_input")));
        }
    }

    fn open_keyboard_combos(&mut self, ctx: &egui::Context) {
        self.shortcuts_open = true;
        self.switcher = None;
        // Keys belong to the dialog now, not to a text box behind it.
        ctx.memory_mut(|m| {
            if let Some(id) = m.focused() {
                m.surrender_focus(id);
            }
        });
    }

    fn zoom_to(&mut self, ctx: &egui::Context, zoom: f32) {
        if (zoom - self.prefs.zoom).abs() > 0.001 {
            self.prefs.zoom = zoom;
            crate::features::apply_zoom(ctx, zoom);
            self.zoom_unsaved = Some(Instant::now());
        }
    }

    /// The app-wide keys, taken before any widget sees them. While Keyboard
    /// Combos is up it also takes Esc and the arrow keys (its dance arrows).
    pub fn handle_shortcuts(&mut self, ctx: &egui::Context) {
        if let Some(since) = self.zoom_unsaved {
            let left = ZOOM_SAVE_DELAY.saturating_sub(since.elapsed());
            if left.is_zero() {
                self.zoom_unsaved = None;
                self.save_prefs();
            } else {
                ctx.request_repaint_after(left);
            }
        }
        let signed_in = self.screen == Screen::Main && self.captcha.is_none();
        let combos = self.shortcuts_open;
        let mut close_combos = false;
        let mut actions = Vec::new();
        ctx.input_mut(|i| {
            i.events.retain(|e| {
                let egui::Event::Key { key, pressed, repeat, modifiers, .. } = e else {
                    return true;
                };
                if combos && (*key == Key::Escape || (ARROW_KEYS.contains(key) && modifiers.is_none())) {
                    close_combos |= *pressed && *key == Key::Escape;
                    return false;
                }
                let Some(act) = action(*key, *modifiers, MAC).filter(|a| signed_in || !a.signed_in_only()) else {
                    return true;
                };
                if *pressed && (!*repeat || act.repeats()) {
                    actions.push(act);
                }
                false
            });
        });
        if close_combos {
            self.shortcuts_open = false;
        }
        for act in actions {
            match act {
                Action::Reload => self.refresh(ctx),
                Action::QuickSwitcher => {
                    if self.switcher.is_some() {
                        self.switcher = None;
                    } else if !other_dialog_up(ctx) {
                        self.shortcuts_open = false;
                        ctx.data_mut(|d| d.insert_temp(egui::Id::new("switcher_opened"), ctx.cumulative_pass_nr()));
                        self.switcher = Some(String::new());
                    }
                }
                Action::Settings => {
                    if self.settings_open {
                        self.close_settings(ctx);
                    } else if !other_dialog_up(ctx) {
                        self.shortcuts_open = false;
                        self.switcher = None;
                        self.settings_open = true;
                    }
                }
                Action::Combos => {
                    if self.shortcuts_open {
                        self.shortcuts_open = false;
                    } else {
                        self.open_keyboard_combos(ctx);
                    }
                }
                Action::Search => self.focus_search(ctx),
                Action::Back | Action::Forward => {
                    if !self.shortcuts_open && self.switcher.is_none() && !other_dialog_up(ctx) {
                        self.navigate_history(act == Action::Forward);
                    }
                }
                Action::ZoomIn => self.zoom_to(ctx, zoom_step(self.prefs.zoom, 0.1)),
                Action::ZoomOut => self.zoom_to(ctx, zoom_step(self.prefs.zoom, -0.1)),
                Action::ZoomReset => self.zoom_to(ctx, 1.0),
                Action::Mute => self.toggle_self_mute(),
                Action::Deafen => self.toggle_self_deaf(),
                Action::CloseWindow => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
            }
        }
        if self.zoom_unsaved.is_some() {
            ctx.request_repaint_after(ZOOM_SAVE_DELAY);
        }
    }

    /// Discord's "Keyboard Combos" dialog (web module 453244), measured on
    /// Discord web (2026-12-04): 80% of the window's width within 800–950 px
    /// and at most 80% of its height, on --background-base-lower with 12 px
    /// corners. The 26/34 title 40 px in with its toggle combo 20 px after
    /// it; the 16/20 subtitle under it, 20 px above a hairline; the four dance
    /// arrows (50 px sprites 8 px apart, 40 px from the right) light up while
    /// their arrow key is held, or for 0.5 s after a click. Below, scrolling,
    /// each group: a 20/24 semibold heading, then cards 24 px apart in
    /// Discord's grid of columns at least 180 px wide, each on
    /// --background-mod-muted with 8 px corners and 12 px padding: the 14/18
    /// label, 8 px, then each combination on its own 23 px line, 8 px apart.
    /// Groups are 24 px apart with a hairline between. Esc, the toggle combo
    /// or a click outside closes it.
    pub fn keyboard_combos_ui(&mut self, ctx: &egui::Context) {
        if !self.shortcuts_open {
            if ctx.data(|d| d.get_temp::<[f64; 4]>(egui::Id::new("keyboard_combos_arrows")).is_some()) {
                // Closed: its pictures go too.
                ctx.data_mut(|d| d.remove::<[f64; 4]>(egui::Id::new("keyboard_combos_arrows")));
                for (name, _) in SPRITES {
                    ctx.forget_image(&sprite_uri(name));
                }
                let key_arrow = super::add_server::tinted_svg(KEYCAP_ARROW_KEY, KEYCAP_ARROW, self.theme.interactive_active);
                if let ImageSource::Bytes { uri, .. } = key_arrow {
                    ctx.forget_image(&uri);
                }
            }
            return;
        }
        let t = self.theme.clone();
        let screen = ctx.screen_rect();
        let w = (screen.width() * 0.8).clamp(800.0, 950.0).min(screen.width() - 32.0);
        let max_h = screen.height() * 0.8;
        let page = ctx.input_mut(|i| i.count_and_consume_key(Modifiers::NONE, Key::PageDown) as f32 - i.count_and_consume_key(Modifiers::NONE, Key::PageUp) as f32);

        let dim = egui::Area::new(egui::Id::new(COMBOS_DIM)).order(Order::Tooltip).fixed_pos(screen.min).show(ctx, |ui| {
            let _ = ui.allocate_exact_size(screen.size(), Sense::click());
            ui.painter().rect_filled(screen, 0.0, Color32::from_black_alpha(170));
        });
        let area = egui::Area::new(egui::Id::new("keyboard_combos")).order(Order::Tooltip).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
            let shadow = egui::epaint::Shadow { offset: vec2(0.0, 4.0), blur: 8.0, spread: 0.0, color: Color32::from_black_alpha(41) };
            egui::Frame::none().fill(t.bg_primary).rounding(12.0).stroke(Stroke::new(1.0_f32, t.border_subtle)).shadow(shadow).show(ui, |ui| {
                ui.set_width(w);
                ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                let header_h = combos_header(ui, &t, w);
                let body = layout_groups(ui, &t, w);
                // Fixed, not "what's left": an area's first frame is laid out
                // in egui's small default size, which would otherwise stick.
                let list_h = body.1.min(max_h - header_h).max(120.0);
                egui::ScrollArea::vertical()
                    .id_salt("keyboard_combos_scroll")
                    .min_scrolled_height(list_h)
                    .max_height(list_h)
                    .auto_shrink([false, true])
                    .show(ui, |ui| {
                        if page != 0.0 {
                            ui.scroll_with_delta(vec2(0.0, -page * ui.clip_rect().height()));
                        }
                        paint_groups(ui, &t, w, body);
                    });
            });
        });
        ctx.set_sublayer(dim.response.layer_id, area.response.layer_id);
        if super::pressed_outside(ctx, area.response.rect) {
            self.shortcuts_open = false;
        }
    }
}

const SPRITES: [(&str, &[u8]); 4] = [
    ("left", include_bytes!("../../assets/keyboard-combos/arrow-left.svg")),
    ("down", include_bytes!("../../assets/keyboard-combos/arrow-down.svg")),
    ("up", include_bytes!("../../assets/keyboard-combos/arrow-up.svg")),
    ("right", include_bytes!("../../assets/keyboard-combos/arrow-right.svg")),
];
/// Discord's arrow in a key (pointing down; turned for the others).
const KEYCAP_ARROW: &[u8] = include_bytes!("../../assets/keyboard-combos/keycap-arrow.svg");
const KEYCAP_ARROW_KEY: &str = "keycap-arrow";

fn sprite_uri(name: &str) -> String {
    format!("bytes://keyboard-combos-{name}.svg")
}

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

/// Title, subtitle and dance arrows; returns their height.
fn combos_header(ui: &mut Ui, t: &Theme, w: f32) -> f32 {
    let sub = ui.fonts(|f| {
        let mut job = egui::text::LayoutJob::single_section(
            "Master these to be the greatest Discord Discord Revolution player".into(),
            egui::TextFormat { font_id: FontId::proportional(16.0), color: t.text_normal, line_height: Some(20.0), ..Default::default() },
        );
        job.wrap.max_width = w - 80.0;
        f.layout_job(job)
    });
    let h = 59.0 + sub.size().y + 21.0;
    let (r, _) = ui.allocate_exact_size(vec2(w, h), Sense::hover());
    let title = ui.painter().layout_no_wrap("Keyboard Combos".into(), FontId::proportional(26.0), t.header_primary);
    let title_w = title.size().x;
    ui.painter().galley(pos2(r.left() + 40.0, r.top() + 37.0 - title.size().y / 2.0), title, t.header_primary);
    paint_combo(ui, t, pos2(r.left() + 40.0 + title_w + 20.0, r.top() + 25.0), COMBOS_TOGGLE);
    ui.painter().galley(pos2(r.left() + 40.0, r.top() + 59.0), sub, t.text_normal);
    // --opacity-black-8 under the subtitle.
    ui.painter().hline(r.x_range(), r.bottom() - 0.5, Stroke::new(1.0_f32, Color32::from_black_alpha(20)));

    // The dance arrows: Discord's sprites, idle / flash (0.1 s) / lit.
    let now = ui.input(|i| i.time);
    let state_id = egui::Id::new("keyboard_combos_arrows");
    let mut lit_since: [f64; 4] = ui.data(|d| d.get_temp(state_id)).unwrap_or([f64::NAN; 4]);
    let clicked_until_id = egui::Id::new("keyboard_combos_clicked");
    let mut clicked_until: [f64; 4] = ui.data(|d| d.get_temp(clicked_until_id)).unwrap_or([0.0; 4]);
    for (i, (name, bytes)) in SPRITES.into_iter().enumerate() {
        let a = Rect::from_min_size(pos2(r.right() - 40.0 - 232.0 + 4.0 + i as f32 * 58.0, r.top() + 26.0), vec2(50.0, 50.0));
        let resp = ui.interact(a, state_id.with(i), Sense::click()).on_hover_cursor(CursorIcon::PointingHand);
        if resp.clicked() {
            clicked_until[i] = now + 0.5;
        }
        let lit = ui.input(|inp| inp.key_down(ARROW_KEYS[i])) || now < clicked_until[i];
        if !lit {
            lit_since[i] = f64::NAN;
        } else if lit_since[i].is_nan() {
            lit_since[i] = now;
        }
        let frame = match now - lit_since[i] {
            d if d.is_nan() => 0.0,
            d if d < 0.1 => {
                ui.ctx().request_repaint_after(Duration::from_secs_f64(0.1 - d));
                1.0
            }
            _ => 2.0,
        };
        if now < clicked_until[i] {
            ui.ctx().request_repaint_after(Duration::from_secs_f64(clicked_until[i] - now));
        }
        let src = ImageSource::Bytes { uri: sprite_uri(name).into(), bytes: Bytes::Static(bytes) };
        egui::Image::new(src)
            .fit_to_exact_size(vec2(50.0, 150.0))
            .uv(Rect::from_min_max(pos2(0.0, frame / 3.0), pos2(1.0, (frame + 1.0) / 3.0)))
            .paint_at(ui, a);
    }
    ui.data_mut(|d| {
        d.insert_temp(state_id, lit_since);
        d.insert_temp(clicked_until_id, clicked_until);
    });
    h
}

/// A key's width in Discord's key combos.
fn key_width(ui: &Ui, k: KeyToken) -> f32 {
    if is_arrow(k) && !MAC {
        return 24.0;
    }
    let text = ui.fonts(|f| f.layout_no_wrap(key_text(k, MAC).into(), semibold(12.0), Color32::WHITE).size().x);
    (text + 14.0).max(14.0)
}

fn is_arrow(k: KeyToken) -> bool {
    matches!(k, K::Up | K::Down | K::Left | K::Right)
}

fn combo_width(ui: &Ui, combo: &[KeyToken]) -> f32 {
    combo.iter().map(|&k| key_width(ui, k)).sum::<f32>() + 3.0 * combo.len().saturating_sub(1) as f32
}

/// Discord's key combo: 23 px keys 3 px apart on --background-mod-muted,
/// a 1 px --border-subtle edge, 4 px corners and a 4 px inset bottom edge;
/// 12 px semibold upper-case text.
fn paint_combo(ui: &Ui, t: &Theme, at: egui::Pos2, combo: &[KeyToken]) {
    let mut x = at.x;
    for &k in combo {
        let kw = key_width(ui, k);
        let r = Rect::from_min_size(pos2(x, at.y), vec2(kw, 23.0));
        let p = ui.painter();
        p.rect(r, 4.0, overlay(0.08), Stroke::new(1.0_f32, t.border_subtle));
        p.rect_filled(Rect::from_min_max(pos2(r.left() + 1.0, r.bottom() - 5.0), pos2(r.right() - 1.0, r.bottom() - 1.0)), Rounding { nw: 0.0, ne: 0.0, sw: 3.0, se: 3.0 }, overlay(0.08));
        if is_arrow(k) && !MAC {
            let turn = match k {
                K::Up => std::f32::consts::PI,
                K::Left => std::f32::consts::FRAC_PI_2,
                K::Right => -std::f32::consts::FRAC_PI_2,
                _ => 0.0,
            };
            egui::Image::new(super::add_server::tinted_svg(KEYCAP_ARROW_KEY, KEYCAP_ARROW, t.interactive_active))
                .fit_to_exact_size(vec2(10.0, 10.0))
                .rotate(turn, vec2(0.5, 0.5))
                .paint_at(ui, Rect::from_min_size(pos2(r.left() + 7.0, r.top() + 4.0), vec2(10.0, 10.0)));
        } else {
            p.text(pos2(r.center().x, r.top() + 10.0), Align2::CENTER_CENTER, key_text(k, MAC), semibold(12.0), t.interactive_active);
        }
        x += kw + 3.0;
    }
}

/// How many of Discord's `repeat(auto-fill, minmax(180px, max-content))`
/// columns (24 px apart) fit in `avail`.
fn grid_columns(avail: f32) -> usize {
    (((avail + 24.0) / (180.0 + 24.0)).floor() as usize).max(1)
}

/// Their widths: 180 px each, then the room left shared out evenly, each
/// stopping at its widest card (CSS grid's "maximize tracks").
fn grid_widths(avail: f32, widest: &[f32]) -> Vec<f32> {
    let n = widest.len();
    let limit: Vec<f32> = widest.iter().map(|w| w.max(180.0).min(avail)).collect();
    let mut widths = vec![180.0_f32.min(avail); n];
    let mut free = avail - widths.iter().sum::<f32>() - 24.0 * n.saturating_sub(1) as f32;
    while free > 0.01 {
        let growing: Vec<usize> = (0..n).filter(|&c| widths[c] < limit[c] - 0.01).collect();
        if growing.is_empty() {
            break;
        }
        let share = free / growing.len() as f32;
        for c in growing {
            let add = share.min(limit[c] - widths[c]);
            widths[c] += add;
            free -= add;
        }
    }
    widths
}

struct Card {
    label: std::sync::Arc<egui::Galley>,
    combos: &'static [&'static [KeyToken]],
    rect: Rect,
}

struct Group {
    heading: std::sync::Arc<egui::Galley>,
    top: f32,
    cards: Vec<Card>,
    bottom: f32,
}

/// Positions (from the list's top left) of every group and card, and the
/// list's height.
fn layout_groups(ui: &Ui, t: &Theme, w: f32) -> (Vec<Group>, f32) {
    let avail = w - 48.0;
    let label_job = |text: &str, wrap: f32| {
        let mut job = egui::text::LayoutJob::single_section(
            text.into(),
            egui::TextFormat { font_id: FontId::proportional(14.0), color: t.text_normal, line_height: Some(18.0), ..Default::default() },
        );
        job.wrap.max_width = wrap;
        job
    };
    let mut out = Vec::new();
    let mut y = 0.0;
    for (name, list) in groups(MAC) {
        let top = y;
        let heading = ui.painter().layout_no_wrap(name.into(), semibold(20.0), t.header_primary);
        y += 24.0 + 24.0 + 8.0 + 8.0;
        let n = grid_columns(avail);
        let widest: Vec<f32> = (0..n)
            .map(|c| {
                list.iter().skip(c).step_by(n).map(|s| {
                    let label = ui.fonts(|f| f.layout_job(label_job(s.label, f32::INFINITY)).size().x);
                    let keys = s.combos.iter().map(|combo| combo_width(ui, combo)).fold(0.0, f32::max);
                    label.max(keys) + 24.0
                })
                .fold(0.0, f32::max)
            })
            .collect();
        let widths = grid_widths(avail, &widest);
        let mut cards = Vec::new();
        for row in list.chunks(n) {
            let mut x = 24.0;
            let mut row_cards = Vec::new();
            for (c, s) in row.iter().enumerate() {
                let label = ui.fonts(|f| f.layout_job(label_job(s.label, widths[c] - 24.0)));
                let h = 12.0 + label.size().y + 8.0 + 31.0 * s.combos.len() as f32 + 12.0;
                row_cards.push(Card { label, combos: s.combos, rect: Rect::from_min_size(pos2(x, y), vec2(widths[c], h)) });
                x += widths[c] + 24.0;
            }
            // Grid rows stretch their cards to the tallest.
            let row_h = row_cards.iter().map(|c| c.rect.height()).fold(0.0, f32::max);
            for card in &mut row_cards {
                card.rect.set_height(row_h);
            }
            cards.extend(row_cards);
            y += row_h + 24.0;
        }
        // The last row's gap becomes the grid's 8 px padding, then the
        // group's 24 px.
        y += 8.0;
        out.push(Group { heading, top, cards, bottom: y });
        y += 1.0;
    }
    (out, y - 1.0)
}

fn paint_groups(ui: &mut Ui, t: &Theme, w: f32, (groups, h): (Vec<Group>, f32)) {
    let (r, _) = ui.allocate_exact_size(vec2(w, h), Sense::hover());
    let o = r.min.to_vec2();
    let last = groups.len().saturating_sub(1);
    for (i, g) in groups.into_iter().enumerate() {
        let heading_h = g.heading.size().y;
        ui.painter().galley(pos2(24.0, g.top + 36.0 - heading_h / 2.0) + o, g.heading, t.header_primary);
        for card in g.cards {
            let cr = card.rect.translate(o);
            ui.painter().rect_filled(cr, 8.0, overlay(0.08));
            let label_h = card.label.size().y;
            ui.painter().galley(cr.min + vec2(12.0, 12.0), card.label, t.text_normal);
            for (j, combo) in card.combos.iter().enumerate() {
                paint_combo(ui, t, cr.min + vec2(12.0, 12.0 + label_h + 8.0 + 31.0 * j as f32), combo);
            }
        }
        if i < last {
            ui.painter().hline((r.left() + 16.0)..=(r.right() - 16.0), r.top() + g.bottom + 0.5, Stroke::new(1.0_f32, t.border_subtle));
        }
    }
}

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

    #[test]
    fn keys_are_written_the_platform_way() {
        assert_eq!(key_text(K::Mod, false), "CTRL");
        assert_eq!(key_text(K::Mod, true), "⌘");
        assert_eq!(key_text(K::Enter, false), "ENTER");
        assert_eq!(key_text(K::Enter, true), "⏎");
        assert_eq!(hint(COMBOS_TOGGLE, false), "Ctrl+/");
        assert_eq!(hint(COMBOS_TOGGLE, true), "⌘/");
        assert_eq!(hint(&[K::Mod, K::Shift, K::Text("M")], false), "Ctrl+Shift+M");
        assert_eq!(hint(&[K::Mod, K::Shift, K::Text("M")], true), "⌘⇧M");
    }

    #[test]
    fn each_platform_lists_its_own_history_keys() {
        let label = "Navigate forward and backward in page history";
        let find = |mac: bool| groups(mac).flat_map(|(_, l)| l).filter(|s| s.label == label).map(|s| s.combos[0]).collect::<Vec<_>>();
        assert_eq!(find(false), [&[K::Alt, K::Left][..]]);
        assert_eq!(find(true), [&[K::Mod, K::Text("[")][..]]);
        assert!(groups(false).flat_map(|(_, l)| l).all(|s| s.label != "Close the window"));
    }

    #[test]
    fn shortcuts_leave_text_editing_and_altgr_alone() {
        let cmd_mac = Modifiers { command: true, mac_cmd: true, ..Default::default() };
        let ctrl_win = Modifiers { command: true, ctrl: true, ..Default::default() };
        for (m, mac) in [(cmd_mac, true), (ctrl_win, false)] {
            assert_eq!(action(Key::K, m, mac), Some(Action::QuickSwitcher));
            assert_eq!(action(Key::Comma, m, mac), Some(Action::Settings));
            assert_eq!(action(Key::Slash, m, mac), Some(Action::Combos));
            assert_eq!(action(Key::Questionmark, m, mac), Some(Action::Combos));
            assert_eq!(action(Key::F, m, mac), Some(Action::Search));
            assert_eq!(action(Key::R, m, mac), Some(Action::Reload));
            assert_eq!(action(Key::Equals, m, mac), Some(Action::ZoomIn));
            assert_eq!(action(Key::Minus, m, mac), Some(Action::ZoomOut));
            assert_eq!(action(Key::Num0, m, mac), Some(Action::ZoomReset));
            let shifted = Modifiers { shift: true, ..m };
            assert_eq!(action(Key::M, shifted, mac), Some(Action::Mute));
            assert_eq!(action(Key::D, shifted, mac), Some(Action::Deafen));
            // ⌘M (minimize on macOS) doesn't mute.
            assert_eq!(action(Key::M, m, mac), None);
            // The text box keeps copy, paste, cut, select all and undo.
            for k in [Key::A, Key::C, Key::V, Key::X, Key::Z] {
                assert_eq!(action(k, m, mac), None);
            }
        }
        // History: Alt + ← / → off macOS, ⌘ [ / ] on it (Alt + arrows move by word there).
        let alt = Modifiers { alt: true, ..Default::default() };
        assert_eq!(action(Key::ArrowLeft, alt, false), Some(Action::Back));
        assert_eq!(action(Key::ArrowRight, alt, false), Some(Action::Forward));
        assert_eq!(action(Key::ArrowLeft, alt, true), None);
        assert_eq!(action(Key::OpenBracket, cmd_mac, true), Some(Action::Back));
        assert_eq!(action(Key::OpenBracket, ctrl_win, false), None);
        // ⌘W closes the window on macOS only.
        assert_eq!(action(Key::W, cmd_mac, true), Some(Action::CloseWindow));
        assert_eq!(action(Key::W, ctrl_win, false), None);
        // macOS's Ctrl text-editing keys and AltGr (Ctrl + Alt) never count.
        let ctrl_mac = Modifiers { ctrl: true, ..Default::default() };
        let altgr = Modifiers { command: true, ctrl: true, alt: true, ..Default::default() };
        assert_eq!(action(Key::K, ctrl_mac, true), None);
        assert_eq!(action(Key::K, altgr, false), None);
        assert_eq!(action(Key::ArrowLeft, altgr, false), None);
    }

    #[test]
    fn zoom_steps_stay_in_the_settings_range() {
        assert_eq!(zoom_step(1.0, 0.1), 1.1);
        assert_eq!(zoom_step(1.0, -0.1), 0.9);
        assert_eq!(zoom_step(2.0, 0.1), 2.0);
        assert_eq!(zoom_step(0.5, -0.1), 0.5);
    }

    #[test]
    fn grid_matches_discords_columns() {
        // Measured on Discord web: 902 px holds 4 columns; Navigation's are
        // 214, 187 and 214 px wide (the second card's widest is 187).
        assert_eq!(grid_columns(902.0), 4);
        assert_eq!(grid_columns(150.0), 1);
        let w = grid_widths(902.0, &[400.0, 187.0, 400.0, 400.0]);
        assert!((w[0] - 214.33).abs() < 0.05 && (w[1] - 187.0).abs() < 0.01 && (w[3] - 214.33).abs() < 0.05);
        // Short cards keep 180 px and the room stays on the right.
        assert_eq!(grid_widths(902.0, &[100.0; 4]), vec![180.0; 4]);
    }
}