Skip to content

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

9.7 KB
Raw Blame
//! The grey stand-in messages Discord shows where history hasn't loaded yet:
//! above the oldest message while there is more, and in a channel opening
//! for the first time. Discord web draws them (modules 114212 and 730276,
//! read 2026-12-02) as random groups of one to four lines, each group with
//! a round avatar, a name blob and a line blob per message, and a few groups
//! carrying an attachment box. The block's height is decided up front, so
//! the list doesn't move when it's replaced by real messages.
//!
//! RustCord adds a soft shine sweeping across the blobs while they show
//! (Discord web's are still; off with Reduced Motion).

use eframe::egui::{self, epaint, pos2, vec2, Color32, Pos2, Rect, Shape, Ui};

/// Discord's default chat text size, which its placeholder sizes are for.
const FONT_DEFAULT: f32 = 16.0;

/// One group of placeholder messages.
#[derive(Clone, Debug)]
struct Group {
    /// Width of each message's line blob (rem × 16, before scaling).
    lines: Vec<f32>,
    /// The name blob's width (the same units) and strength.
    name_w: f32,
    name_alpha: f32,
    /// An attachment box under one of the messages: (which, size in px).
    attachment: Option<(usize, egui::Vec2)>,
}

/// A block of placeholder messages and the height it takes.
#[derive(Clone, Debug)]
pub struct Placeholder {
    groups: Vec<Group>,
    /// The chat text size and group spacing it was made for.
    font: f32,
    spacing: f32,
    pub height: f32,
}

/// A small, fast, seeded random source (SplitMix64): the same channel gets
/// the same stand-ins every time it's drawn.
struct Rng(u64);

impl Rng {
    fn next(&mut self) -> u64 {
        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut z = self.0;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        z ^ (z >> 31)
    }

    /// A whole number in `lo..=hi`, as lodash's `random(lo, hi)`.
    fn int(&mut self, lo: u32, hi: u32) -> u32 {
        lo + (self.next() % u64::from(hi - lo + 1)) as u32
    }

    /// A number in `lo..hi`.
    fn float(&mut self, lo: f32, hi: f32) -> f32 {
        lo + (self.next() >> 40) as f32 / (1u64 << 24) as f32 * (hi - lo)
    }
}

impl Placeholder {
    /// Discord's `generateMessageSpecs` for a window `window_h` tall, at
    /// chat text size `font` and group spacing `spacing` (cozy messages):
    /// 10 to 30 groups for the window's height (87 % of them in cozy mode),
    /// one to four messages each, and an attachment for about every fourth
    /// group.
    pub fn generate(seed: u64, window_h: f32, font: f32, spacing: f32) -> Self {
        let mut rng = Rng(seed);
        let r = font / FONT_DEFAULT;
        let room = (window_h - 145.0).max(400.0);
        let per_screen = ((1.05 * (room / (91.0 * r)).ceil()).ceil()).clamp(10.0, 30.0);
        let count = (0.87 * per_screen).round().max(1.0) as usize;
        let attachments = ((count as f32 / 30.0 * 8.0).round() as usize).clamp(1, count);
        let mut height = 0.0;
        let mut groups: Vec<Group> = (0..count)
            .map(|_| {
                let n = rng.int(1, 4) as usize;
                height += spacing * r + 44.0 * r + (n - 1) as f32 * 22.0 * r;
                Group::with_lines(n)
            })
            .collect();
        // Attachments go to groups picked at random, one each.
        let mut free: Vec<usize> = (0..count).collect();
        for _ in 0..attachments {
            let size = vec2(rng.int(140, 400) as f32, rng.int(100, 320) as f32);
            let g = free.remove(rng.int(0, free.len() as u32 - 1) as usize);
            let n = groups[g].lines.len();
            groups[g].attachment = Some((rng.int(0, n as u32 - 1) as usize, size));
            height += size.y + 6.0 * r;
        }
        for g in &mut groups {
            g.name_w = rng.int(80, 120) as f32;
            g.name_alpha = rng.float(0.1, 0.2);
            for w in &mut g.lines {
                *w = rng.int(120, 320) as f32;
            }
        }
        Self { groups, font, spacing, height }
    }

    /// Whether it was made for this text size and spacing.
    pub fn fits(&self, font: f32, spacing: f32) -> bool {
        self.font == font && self.spacing == spacing
    }

    /// Paints it with its top-left at `at`, in the chat's text colour
    /// `ink`; only what's inside the painter's clip. `shine` is the time,
    /// for the sweeping highlight (None: still). Returns whether any of it
    /// was on screen.
    pub fn paint(&self, ui: &Ui, at: Pos2, width: f32, ink: Color32, shine: Option<f64>) -> bool {
        let r = self.font / FONT_DEFAULT;
        let clip = ui.clip_rect();
        let mut shapes = Vec::new();
        let tint = |alpha: f32| ink.gamma_multiply(alpha);
        let blob = |x: f32, y: f32, w: f32, alpha: f32| Shape::rect_filled(Rect::from_min_size(pos2(x, y + 3.0 * r), vec2(w * r, 16.0 * r)), 8.0 * r, tint(alpha));
        let mut y = at.y;
        let left = at.x + 72.0 * r;
        for g in &self.groups {
            y += self.spacing * r;
            let group_top = y;
            let group_h = 44.0 * r + (g.lines.len() - 1) as f32 * 22.0 * r + g.attachment.map_or(0.0, |(_, s)| s.y + 6.0 * r);
            if group_top > clip.bottom() {
                break;
            }
            if group_top + group_h < clip.top() {
                y += group_h;
                continue;
            }
            // The avatar (40 px at most) and the name, then a line per message.
            let avatar = (40.0 * r).min(40.0);
            shapes.push(Shape::circle_filled(pos2(at.x + 16.0 * r + avatar / 2.0, y + 4.0 * r + avatar / 2.0), avatar / 2.0, tint(0.08)));
            shapes.push(blob(left, y, g.name_w, g.name_alpha));
            y += 22.0 * r;
            for (i, w) in g.lines.iter().enumerate() {
                shapes.push(blob(left, y, w.min((width - 88.0 * r).max(40.0) / r), 0.06));
                y += 22.0 * r;
                if let Some((_, size)) = g.attachment.filter(|(at_line, _)| *at_line == i) {
                    let w = size.x.min((width - 88.0 * r).max(40.0));
                    shapes.push(Shape::rect_filled(Rect::from_min_size(pos2(left, y + 4.0 * r), vec2(w, size.y)), 6.0, tint(0.03)));
                    y += size.y + 6.0 * r;
                }
            }
        }
        if shapes.is_empty() {
            return false;
        }
        match shine {
            None => ui.painter().extend(shapes),
            Some(time) => {
                ui.painter().add(shine_mesh(ui, shapes, at.x, width, time));
            }
        }
        true
    }
}

impl Group {
    fn with_lines(n: usize) -> Self {
        Self { lines: vec![0.0; n], name_w: 0.0, name_alpha: 0.0, attachment: None }
    }
}

/// How long one sweep of the shine takes, and how wide its bright part is.
const SHINE_PERIOD: f64 = 1.8;
const SHINE_WIDTH: f32 = 110.0;
/// How much brighter the blobs get at the shine's middle.
const SHINE_GAIN: f32 = 1.6;

/// The shapes as one mesh whose corners are brightened where the shine
/// passes: a soft band moving left to right.
fn shine_mesh(ui: &Ui, shapes: Vec<Shape>, left: f32, width: f32, time: f64) -> Shape {
    let ctx = ui.ctx();
    let options = ctx.tessellation_options(|o| *o);
    let mut tessellator = epaint::Tessellator::new(ctx.pixels_per_point(), options, ctx.fonts(|f| f.font_image_size()), Vec::new());
    let mut mesh = epaint::Mesh::default();
    for shape in shapes {
        tessellator.tessellate_shape(shape, &mut mesh);
    }
    let span = width + 4.0 * SHINE_WIDTH;
    let centre = left - 2.0 * SHINE_WIDTH + (time.rem_euclid(SHINE_PERIOD) / SHINE_PERIOD) as f32 * span;
    for v in &mut mesh.vertices {
        let d = (v.pos.x - centre) / SHINE_WIDTH;
        let gain = 1.0 + SHINE_GAIN * (-d * d).exp();
        let c = v.color;
        let lift = |x: u8| (x as f32 * gain).min(255.0) as u8;
        // (Premultiplied: colour and alpha scale together.)
        v.color = Color32::from_rgba_premultiplied(lift(c.r()), lift(c.g()), lift(c.b()), lift(c.a()));
    }
    Shape::mesh(mesh)
}

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

    #[test]
    fn same_channel_same_stand_ins() {
        let a = Placeholder::generate(42, 900.0, 16.0, 16.0);
        let b = Placeholder::generate(42, 900.0, 16.0, 16.0);
        assert_eq!(a.height, b.height);
        assert_eq!(a.groups.len(), b.groups.len());
    }

    #[test]
    fn sized_like_discords() {
        // A 900 px window: ceil(755 / 91) = 9 → ceil(9.45) = 10 groups, 87 %
        // of them (9), and one attachment for every ~4 groups (2).
        let p = Placeholder::generate(7, 900.0, 16.0, 16.0);
        assert_eq!(p.groups.len(), 9);
        assert_eq!(p.groups.iter().filter(|g| g.attachment.is_some()).count(), 2);
        assert!(p.groups.iter().all(|g| (1..=4).contains(&g.lines.len())));
        // Height: each group's spacing, first message (44) and the rest (22),
        // plus each attachment and its 6 px.
        let expect: f32 = p.groups.iter().map(|g| 16.0 + 44.0 + (g.lines.len() - 1) as f32 * 22.0 + g.attachment.map_or(0.0, |(_, s)| s.y + 6.0)).sum();
        assert!((p.height - expect).abs() < 0.01, "{} vs {expect}", p.height);
        // A tall window gets more, up to 30 × 87 %.
        assert_eq!(Placeholder::generate(7, 5000.0, 16.0, 16.0).groups.len(), 26);
    }

    #[test]
    fn widths_stay_in_discords_ranges() {
        let p = Placeholder::generate(99, 1200.0, 16.0, 16.0);
        for g in &p.groups {
            assert!((80.0..=120.0).contains(&g.name_w));
            assert!((0.1..0.2).contains(&g.name_alpha));
            assert!(g.lines.iter().all(|w| (120.0..=320.0).contains(w)));
            if let Some((i, s)) = g.attachment {
                assert!(i < g.lines.len() && (140.0..=400.0).contains(&s.x) && (100.0..=320.0).contains(&s.y));
            }
        }
    }
}