Skip to content

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

12.1 KB
Raw Blame
//! Opening and closing motion for everything that floats: popouts, menus,
//! tooltips, dialogs and their dimmed backdrops.
//!
//! One pass at the end of each frame ([`end_frame`]) eases in every floating
//! layer that has just appeared and, from the copy it keeps of each open
//! layer's last frame, eases out the ones that have gone. Surfaces don't opt
//! in; one whose motion Discord defines says which with [`tag`], and one that
//! is always on screen opts out with [`Motion::Still`].
//!
//! Discord's own numbers (web client, read 2026-12-01):
//! - popouts slide 10 px into place in 0.2 s, CSS `ease-out`, without fading;
//! - modals fade in while growing from 70 % in 0.2 s, ease-out quad, and
//!   leave the same way;
//! - the backdrop fades.
//!
//! Nothing here runs while nothing floats, and frames are only asked for
//! while something is mid-motion. Settings → Accessibility switches it off,
//! and so does Reduced Motion.

use eframe::egui::{
    self,
    emath::TSTransform,
    epaint::{shape_transform::adjust_colors, ClippedShape},
    layers::ShapeIdx,
    Color32, LayerId, Order, Rect, Vec2,
};
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};

/// Settings → Accessibility → "Open and close animations".
pub static ENABLED: AtomicBool = AtomicBool::new(true);

/// A layer with more shapes than this isn't copied for a closing animation
/// (a whole settings page): it opens with motion and closes at once.
const MAX_KEPT: usize = 3000;

/// How a floating layer arrives and leaves.
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Motion {
    /// Chosen from the layer: a backdrop fades, a tooltip or menu fades in
    /// growing slightly.
    Auto,
    /// Discord's popout: slides in from this offset.
    Slide(Vec2),
    /// Discord's modal: fades in growing from 70 %.
    Modal,
    /// Always on screen (a floating panel, a drag ghost): left alone.
    Still,
}

/// The numbers behind a [`Motion`].
struct Spec {
    secs_in: f32,
    secs_out: f32,
    /// Size it grows from (and, for modals, shrinks back to).
    scale: f32,
    slide: Vec2,
    fade_in: bool,
    shrink_out: bool,
    quad: bool,
}

impl Spec {
    fn of(motion: Motion, order: Order, rect: Rect, screen: Rect) -> Self {
        let plain = Self { secs_in: 0.14, secs_out: 0.1, scale: 0.96, slide: Vec2::ZERO, fade_in: true, shrink_out: false, quad: false };
        match motion {
            Motion::Slide(slide) => Self { secs_in: 0.2, scale: 1.0, slide, fade_in: false, ..plain },
            Motion::Modal => Self { secs_in: 0.2, secs_out: 0.2, scale: 0.7, shrink_out: true, quad: true, ..plain },
            // A backdrop (or a page as big as the window): no growing.
            _ if rect.width() >= screen.width() * 0.9 && rect.height() >= screen.height() * 0.9 => Self { secs_in: 0.2, secs_out: 0.15, scale: 1.0, ..plain },
            _ if order == Order::Tooltip => Self { secs_in: 0.1, secs_out: 0.08, ..plain },
            _ => plain,
        }
    }

    fn ease(&self, x: f32) -> f32 {
        if self.quad {
            1.0 - (1.0 - x) * (1.0 - x)
        } else {
            ease_out(x)
        }
    }

    /// The layer `e` of the way in (1 = in place): its transform and opacity.
    fn at(&self, e: f32, rect: Rect, arriving: bool) -> (TSTransform, f32) {
        let scale = if arriving || self.shrink_out { self.scale + (1.0 - self.scale) * e } else { 1.0 };
        let slide = if arriving { self.slide * (1.0 - e) } else { Vec2::ZERO };
        let alpha = if arriving && !self.fade_in { 1.0 } else { e };
        (TSTransform::new(rect.center().to_vec2() * (1.0 - scale) + slide, scale), alpha)
    }
}

/// CSS `ease-out`: cubic-bezier(0, 0, 0.58, 1).
pub fn ease_out(x: f32) -> f32 {
    let x = x.clamp(0.0, 1.0);
    let bez = |t: f32, a: f32, b: f32| 3.0 * (1.0 - t) * (1.0 - t) * t * a + 3.0 * (1.0 - t) * t * t * b + t * t * t;
    let (mut lo, mut hi, mut t) = (0.0, 1.0, x);
    for _ in 0..16 {
        let cx = bez(t, 0.0, 0.58);
        if (cx - x).abs() < 1e-4 {
            break;
        }
        if cx < x {
            lo = t;
        } else {
            hi = t;
        }
        t = (lo + hi) / 2.0;
    }
    bez(t, 0.0, 1.0)
}

struct Open {
    motion: Motion,
    key: u64,
    since: f64,
    rect: Rect,
    /// Its shapes as last painted, for the way out.
    last: Vec<ClippedShape>,
    pass: u64,
}

struct Ghost {
    layer: LayerId,
    motion: Motion,
    rect: Rect,
    since: f64,
    shapes: Vec<ClippedShape>,
}

#[derive(Default)]
struct State {
    open: HashMap<LayerId, Open>,
    ghosts: Vec<Ghost>,
    /// This frame's [`tag`]s.
    tags: HashMap<LayerId, (Motion, u64)>,
}

thread_local! {
    static STATE: RefCell<State> = RefCell::new(State::default());
}

pub fn enabled() -> bool {
    ENABLED.load(Relaxed) && !super::REDUCED_MOTION.load(Relaxed)
}

/// Say how the layer `ui` paints into moves (each frame it's shown). When
/// `key` changes, it arrives again: a popout reused for someone else.
pub fn tag(ui: &egui::Ui, motion: Motion, key: u64) {
    if enabled() {
        let layer = ui.layer_id();
        STATE.with(|s| s.borrow_mut().tags.insert(layer, (motion, key)));
    }
}

fn fade(shape: &mut egui::Shape, alpha: f32) {
    if alpha < 1.0 {
        adjust_colors(shape, move |c| *c = faded(*c, alpha));
    }
}

/// `c` at `alpha` of its strength. Text laid out without a colour carries
/// egui's placeholder, which is swapped for the shape's own (already faded)
/// colour when drawn: changing it would paint the marker itself, in green.
fn faded(c: Color32, alpha: f32) -> Color32 {
    if c == Color32::PLACEHOLDER {
        c
    } else {
        c.gamma_multiply(alpha)
    }
}

/// Run once per frame, after everything is drawn.
pub fn end_frame(ctx: &egui::Context) {
    if !enabled() {
        STATE.with(|s| {
            let mut s = s.borrow_mut();
            if !s.open.is_empty() || !s.ghosts.is_empty() || !s.tags.is_empty() {
                *s = State::default();
            }
        });
        return;
    }
    let (now, screen, pass) = (ctx.input(|i| i.time), ctx.screen_rect(), ctx.cumulative_pass_nr());
    // Floating layers drawn this frame or the last, with where they are.
    // (Layers something else is already moving, a drag ghost, are left out.)
    let floating: Vec<(LayerId, Option<Rect>)> = ctx.memory(|m| {
        m.areas()
            .visible_layer_ids()
            .into_iter()
            .filter(|l| matches!(l.order, Order::Middle | Order::Foreground | Order::Tooltip) && !m.layer_transforms.contains_key(l))
            .map(|l| (l, m.area_rect(l.id)))
            .collect()
    });
    let moving = STATE.with(|s| {
        let mut s = s.borrow_mut();
        let s = &mut *s;
        if floating.is_empty() && s.open.is_empty() && s.ghosts.is_empty() {
            s.tags.clear();
            return false;
        }
        let mut moving = false;
        ctx.graphics_mut(|g| {
            for (layer, rect) in floating {
                let Some(list) = g.get_mut(layer).filter(|l| !l.is_empty()) else { continue };
                let (motion, key) = s.tags.get(&layer).copied().unwrap_or((Motion::Auto, 0));
                if motion == Motion::Still {
                    s.open.remove(&layer);
                    continue;
                }
                let rect = rect.unwrap_or(screen);
                let open = s.open.entry(layer).or_insert_with(|| Open { motion, key, since: now, rect, last: Vec::new(), pass });
                if open.key != key {
                    open.since = now;
                }
                (open.motion, open.key, open.rect, open.pass) = (motion, key, rect, pass);
                s.ghosts.retain(|gh| gh.layer != layer);
                let count = list.next_idx().0;
                open.last.clear();
                if count <= MAX_KEPT {
                    open.last.extend(list.all_entries().cloned());
                }
                let spec = Spec::of(motion, layer.order, rect, screen);
                let x = ((now - open.since) as f32 / spec.secs_in).clamp(0.0, 1.0);
                if x < 1.0 {
                    let (transform, alpha) = spec.at(spec.ease(x), rect, true);
                    for i in 0..count {
                        list.mutate_shape(ShapeIdx(i), |c| fade(&mut c.shape, alpha));
                    }
                    list.transform(transform);
                    moving = true;
                }
            }
            // The ones that weren't drawn this frame: on their way out.
            let gone: Vec<LayerId> = s.open.iter().filter(|(_, o)| o.pass != pass).map(|(l, _)| *l).collect();
            for layer in gone {
                if let Some(o) = s.open.remove(&layer).filter(|o| !o.last.is_empty()) {
                    s.ghosts.push(Ghost { layer, motion: o.motion, rect: o.rect, since: now, shapes: o.last });
                }
            }
            s.ghosts.retain(|gh| {
                let spec = Spec::of(gh.motion, gh.layer.order, gh.rect, screen);
                let x = ((now - gh.since) as f32 / spec.secs_out).clamp(0.0, 1.0);
                if x >= 1.0 {
                    return false;
                }
                let (transform, alpha) = spec.at(1.0 - spec.ease(x), gh.rect, false);
                let list = g.entry(gh.layer);
                for c in &gh.shapes {
                    let mut shape = c.shape.clone();
                    fade(&mut shape, alpha);
                    shape.transform(transform);
                    list.add(transform.mul_rect(c.clip_rect), shape);
                }
                moving = true;
                true
            });
        });
        s.tags.clear();
        moving
    });
    if moving {
        ctx.request_repaint();
    }
}

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

    #[test]
    fn ease_out_matches_css() {
        assert_eq!(ease_out(0.0), 0.0);
        assert_eq!(ease_out(1.0), 1.0);
        // cubic-bezier(0, 0, 0.58, 1) at x = 0.5 is 0.6845 (Chrome).
        assert!((ease_out(0.5) - 0.6845).abs() < 0.005, "{}", ease_out(0.5));
        assert!(ease_out(0.25) < ease_out(0.5) && ease_out(0.5) < ease_out(0.75));
    }

    #[test]
    fn fading_keeps_uncoloured_text_uncoloured() {
        // A label painted with `painter.galley(pos, galley, colour)`: its
        // glyphs hold the placeholder until they're drawn.
        let ctx = egui::Context::default();
        let mut galley = None;
        let _ = ctx.run(Default::default(), |ctx| {
            galley = Some(ctx.fonts(|f| f.layout_no_wrap("Activity".into(), egui::FontId::default(), Color32::PLACEHOLDER)));
        });
        let mut shape = egui::Shape::galley(egui::Pos2::ZERO, galley.unwrap(), Color32::WHITE);
        fade(&mut shape, 0.5);
        let egui::Shape::Text(text) = &shape else { panic!("a text shape") };
        assert_eq!(text.fallback_color, Color32::WHITE.gamma_multiply(0.5));
        let glyphs: Vec<Color32> = text.galley.rows.iter().flat_map(|r| r.visuals.mesh.vertices.iter().map(|v| v.color)).collect();
        assert!(!glyphs.is_empty() && glyphs.iter().all(|c| *c == Color32::PLACEHOLDER), "{:?}", glyphs.first());
    }

    #[test]
    fn popout_slides_without_fading() {
        let rect = Rect::from_min_size(egui::pos2(100.0, 100.0), egui::vec2(300.0, 400.0));
        let spec = Spec::of(Motion::Slide(egui::vec2(10.0, 0.0)), Order::Foreground, rect, Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 720.0)));
        let (t, alpha) = spec.at(0.0, rect, true);
        assert_eq!((t.translation, t.scaling, alpha), (egui::vec2(10.0, 0.0), 1.0, 1.0));
        let (t, _) = spec.at(1.0, rect, true);
        assert_eq!(t, TSTransform::IDENTITY);
    }

    #[test]
    fn modal_grows_from_its_centre() {
        let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 720.0));
        let rect = Rect::from_center_size(screen.center(), egui::vec2(600.0, 400.0));
        let spec = Spec::of(Motion::Modal, Order::Foreground, rect, screen);
        let (t, alpha) = spec.at(0.0, rect, true);
        assert_eq!((t.scaling, alpha), (0.7, 0.0));
        // The centre stays where it is.
        assert!((t * rect.center() - rect.center()).length() < 0.001);
        // On the way out it shrinks back.
        assert_eq!(spec.at(0.0, rect, false).0.scaling, 0.7);
    }
}