Skip to content

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

13.3 KB
Raw Blame
//! Middle-click autoscroll, as Chrome does it on Windows (so as Discord does
//! in the browser): press the middle button over something that scrolls and
//! move the pointer away from that point to scroll, faster the further away.
//! Letting go after moving stops it; a click without moving leaves it on
//! until the next click (which does nothing else) or Esc.
//!
//! It works below the widgets, so every list scrolls this way without
//! knowing about it. While it's on, egui is shown the pointer resting where
//! the button went down: the list under that point stays the hovered one and
//! nothing else lights up (Chrome doesn't hover either). Each frame then
//! feeds that list its distance as if a wheel had turned.

use eframe::egui::{self, Color32, Context, CursorIcon, Event, Key, PointerButton, Pos2, RawInput, Shape, Stroke, Vec2};

/// Chromium's dead zone around the click (`kNoMiddleClickAutoscrollRadius`),
/// per axis, in CSS pixels (egui points here).
const DEAD_ZONE: f32 = 15.0;

/// A scroll too small to move anything (it vanishes against any offset
/// above about 1e-23), asking whether the list under the click scrolls that
/// way: one that can takes it out of the frame's input.
const PROBE: f32 = 1e-30;

#[derive(Default)]
pub struct Autoscroll {
    on: Option<Active>,
    /// The button whose press ended autoscroll: its release is kept from egui too.
    swallow_release: Option<PointerButton>,
    /// Where the pointer really is, for egui's next frame, once autoscroll
    /// ended outside of the input (nothing under the click scrolled).
    give_back: Option<Event>,
}

struct Active {
    origin: Pos2,
    /// Where the pointer really is.
    pointer: Pos2,
    /// The pointer left the window (it carries on scrolling meanwhile).
    outside: bool,
    mode: Mode,
    /// Which ways (x, y) the list under the click scrolls; `None` while
    /// finding out.
    axes: Option<[bool; 2]>,
    /// Finding out: the ways found so far, this frame's probe, how many sent.
    found: [bool; 2],
    probe: Vec2,
    probes: u8,
    /// The last frame's time, while it was scrolling.
    scrolled_at: Option<f64>,
}

#[derive(Clone, Copy, PartialEq, Debug)]
enum Mode {
    /// Just pressed, still inside the dead zone.
    Initial,
    /// Moved out of the dead zone while held: letting go stops.
    Holding,
    /// Let go without moving: on until the next click.
    Toggled,
}

impl Active {
    /// Where the pointer is, for egui once autoscroll is over.
    fn pointer_event(&self) -> Event {
        if self.outside {
            Event::PointerGone
        } else {
            Event::PointerMoved(self.pointer)
        }
    }
}

impl Autoscroll {
    /// From `raw_input_hook`: starts and stops autoscroll and keeps from egui
    /// the input it uses. `enabled` is false while the middle button is the
    /// Push-to-Talk key (holding it to talk mustn't scroll anything).
    pub fn filter(&mut self, raw: &mut RawInput, enabled: bool) {
        let events = std::mem::take(&mut raw.events);
        raw.events.extend(self.give_back.take());
        for e in events {
            self.event(e, enabled, &mut raw.events);
        }
    }

    fn event(&mut self, e: Event, enabled: bool, out: &mut Vec<Event>) {
        let Some(a) = &mut self.on else {
            match e {
                // (RustCord has no other use for the middle button.)
                Event::PointerButton { button: PointerButton::Middle, pressed, pos, .. } if enabled => {
                    if pressed {
                        self.on = Some(Active { origin: pos, pointer: pos, outside: false, mode: Mode::Initial, axes: None, found: [false; 2], probe: Vec2::ZERO, probes: 0, scrolled_at: None });
                        out.push(Event::PointerMoved(pos));
                    }
                }
                Event::PointerButton { button, pressed: false, .. } if self.swallow_release == Some(button) => self.swallow_release = None,
                e => out.push(e),
            }
            return;
        };
        match e {
            Event::PointerMoved(p) => {
                (a.pointer, a.outside) = (p, false);
                let d = p - a.origin;
                if a.mode == Mode::Initial && (d.x.abs() > DEAD_ZONE || d.y.abs() > DEAD_ZONE) {
                    a.mode = Mode::Holding;
                }
            }
            // Out of the window it carries on, as in Chrome.
            Event::PointerGone => a.outside = true,
            // Any press stops it and does nothing else.
            Event::PointerButton { button, pressed: true, .. } => {
                if button != PointerButton::Middle {
                    self.swallow_release = Some(button);
                }
                self.stop(out);
            }
            Event::PointerButton { button, pressed: false, .. } => {
                match a.mode {
                    Mode::Initial if button == PointerButton::Middle => a.mode = Mode::Toggled,
                    Mode::Holding => self.stop(out),
                    _ => {}
                }
                // (A button held down from before still lets go in egui.)
                if button != PointerButton::Middle {
                    out.push(e);
                }
            }
            Event::Key { key: Key::Escape, pressed: true, .. } => self.stop(out),
            Event::WindowFocused(false) => {
                self.stop(out);
                out.push(e);
            }
            e => out.push(e),
        }
    }

    fn stop(&mut self, out: &mut Vec<Event>) {
        if let Some(a) = self.on.take() {
            out.push(a.pointer_event());
        }
    }

    /// Before the frame's UI: this frame's scroll, or while it's finding out
    /// whether anything under the click scrolls, the probe.
    pub fn before_ui(&mut self, ctx: &Context) {
        let Some(a) = &mut self.on else { return };
        let delta = match a.axes {
            None => {
                // Up and left first, then the other way for what didn't move
                // (a list at its top can't scroll up).
                let sign = if a.probes == 0 { PROBE } else { -PROBE };
                a.probes += 1;
                a.probe = Vec2::new(if a.found[0] { 0.0 } else { sign }, if a.found[1] { 0.0 } else { sign });
                ctx.request_repaint();
                a.probe
            }
            Some([x, y]) => {
                let v = velocity(a.pointer - a.origin);
                let v = Vec2::new(if x { v.x } else { 0.0 }, if y { v.y } else { 0.0 });
                let now = ctx.input(|i| i.time);
                // (From the frame before, but only if that one was scrolling
                // too: nothing redraws while the pointer rests near the click.)
                let dt = a.scrolled_at.map_or(0.0, |t| (now - t).clamp(0.0, 0.1) as f32);
                a.scrolled_at = (v != Vec2::ZERO).then_some(now);
                if v == Vec2::ZERO {
                    return;
                }
                ctx.request_repaint();
                // (A wheel's delta points the other way.)
                -v * dt
            }
        };
        ctx.input_mut(|i| i.smooth_scroll_delta += delta);
    }

    /// After the frame's UI: what the probe found, then the cursor and the
    /// mark where the click was.
    pub fn after_ui(&mut self, ctx: &Context) {
        let Some(a) = &mut self.on else { return };
        if a.axes.is_none() {
            let left = ctx.input(|i| i.smooth_scroll_delta);
            a.found[0] |= a.probe.x != 0.0 && left.x == 0.0;
            a.found[1] |= a.probe.y != 0.0 && left.y == 0.0;
            if a.found != [true; 2] && a.probes < 2 {
                return;
            }
            if a.found == [false; 2] {
                // Nothing there scrolls: as if the button had done nothing.
                self.give_back = Some(a.pointer_event());
                self.on = None;
                ctx.request_repaint();
                return;
            }
            a.axes = Some(a.found);
        }
        let Some(axes) = a.axes else { return };
        ctx.set_cursor_icon(cursor(a.pointer - a.origin, axes));
        paint_mark(ctx, a.origin, axes);
    }
}

/// Chromium's speed for the pointer `d` away from the click, per axis, in
/// points a second: |d|^2.2 × 0.000008 a millisecond, none inside the dead
/// zone (`AutoscrollController::HandleMouseMoveForMiddleClickAutoscroll`).
fn velocity(d: Vec2) -> Vec2 {
    let axis = |d: f32| if d.abs() <= DEAD_ZONE { 0.0 } else { d.signum() * d.abs().powf(2.2) * 0.008 };
    Vec2::new(axis(d.x), axis(d.y))
}

/// Chromium's cursor: the way it's scrolling (of the ways the list scrolls),
/// else the ways it can.
fn cursor(d: Vec2, [x, y]: [bool; 2]) -> CursorIcon {
    let (north, south) = (y && d.y < -DEAD_ZONE, y && d.y > DEAD_ZONE);
    let (east, west) = (x && d.x > DEAD_ZONE, x && d.x < -DEAD_ZONE);
    if north || south {
        match (north, east, west) {
            (true, true, _) => CursorIcon::ResizeNorthEast,
            (true, _, true) => CursorIcon::ResizeNorthWest,
            (true, ..) => CursorIcon::ResizeNorth,
            (false, true, _) => CursorIcon::ResizeSouthEast,
            (false, _, true) => CursorIcon::ResizeSouthWest,
            (false, ..) => CursorIcon::ResizeSouth,
        }
    } else if east {
        CursorIcon::ResizeEast
    } else if west {
        CursorIcon::ResizeWest
    } else {
        match (x, y) {
            (false, _) => CursorIcon::ResizeVertical,
            (_, false) => CursorIcon::ResizeHorizontal,
            _ => CursorIcon::AllScroll,
        }
    }
}

/// The mark Chrome leaves at the click: a white disc with a dot, and arrows
/// the ways the list scrolls.
fn paint_mark(ctx: &Context, at: Pos2, [x, y]: [bool; 2]) {
    let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("autoscroll_mark")));
    let ink = Color32::from_gray(64);
    painter.circle(at, 13.0, Color32::from_white_alpha(240), Stroke::new(1.0_f32, Color32::from_gray(150)));
    painter.circle_filled(at, 2.0, ink);
    let arrow = |dir: Vec2| {
        let (tip, base, side) = (at + dir * 10.0, at + dir * 5.5, dir.rot90() * 4.0);
        painter.add(Shape::convex_polygon(vec![tip, base + side, base - side], ink, Stroke::NONE));
    };
    if y {
        arrow(Vec2::UP);
        arrow(Vec2::DOWN);
    }
    if x {
        arrow(Vec2::LEFT);
        arrow(Vec2::RIGHT);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use eframe::egui::{pos2, vec2, Modifiers};

    fn button(button: PointerButton, pressed: bool, pos: Pos2) -> Event {
        Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE }
    }

    /// Runs events through the filter: what egui gets.
    fn feed(s: &mut Autoscroll, events: Vec<Event>) -> Vec<Event> {
        let mut raw = RawInput { events, ..Default::default() };
        s.filter(&mut raw, true);
        raw.events
    }

    #[test]
    fn speed_follows_chromium() {
        assert_eq!(velocity(vec2(15.0, -15.0)), Vec2::ZERO);
        let v = velocity(vec2(0.0, 100.0));
        assert!((v.y - 201.0).abs() < 1.0 && v.x == 0.0, "{v:?}");
        assert!(velocity(vec2(-300.0, 0.0)).x < -2000.0);
    }

    #[test]
    fn a_click_without_moving_stays_on_until_the_next_click() {
        let mut s = Autoscroll::default();
        let at = pos2(100.0, 100.0);
        assert_eq!(feed(&mut s, vec![button(PointerButton::Middle, true, at), button(PointerButton::Middle, false, at)]), vec![Event::PointerMoved(at)]);
        assert_eq!(s.on.as_ref().map(|a| a.mode), Some(Mode::Toggled));
        // Moving scrolls; egui keeps seeing the pointer at the click.
        assert!(feed(&mut s, vec![Event::PointerMoved(pos2(100.0, 300.0))]).is_empty());
        // The click that stops it reaches nothing, its release neither.
        let gone = feed(&mut s, vec![button(PointerButton::Primary, true, pos2(100.0, 300.0))]);
        assert_eq!(gone, vec![Event::PointerMoved(pos2(100.0, 300.0))]);
        assert!(s.on.is_none());
        assert!(feed(&mut s, vec![button(PointerButton::Primary, false, pos2(100.0, 300.0))]).is_empty());
        assert!(!feed(&mut s, vec![button(PointerButton::Primary, true, at)]).is_empty());
    }

    #[test]
    fn letting_go_after_moving_stops() {
        let mut s = Autoscroll::default();
        let at = pos2(50.0, 50.0);
        feed(&mut s, vec![button(PointerButton::Middle, true, at), Event::PointerMoved(pos2(50.0, 90.0))]);
        assert_eq!(s.on.as_ref().map(|a| a.mode), Some(Mode::Holding));
        assert_eq!(feed(&mut s, vec![button(PointerButton::Middle, false, pos2(50.0, 90.0))]), vec![Event::PointerMoved(pos2(50.0, 90.0))]);
        assert!(s.on.is_none());
    }

    #[test]
    fn push_to_talk_on_the_middle_button_keeps_it_off() {
        let mut s = Autoscroll::default();
        let press = button(PointerButton::Middle, true, pos2(1.0, 1.0));
        let mut raw = RawInput { events: vec![press.clone()], ..Default::default() };
        s.filter(&mut raw, false);
        assert_eq!(raw.events, vec![press]);
        assert!(s.on.is_none());
    }

    #[test]
    fn cursor_points_the_way_it_scrolls() {
        assert_eq!(cursor(vec2(0.0, 40.0), [false, true]), CursorIcon::ResizeSouth);
        assert_eq!(cursor(vec2(40.0, -40.0), [true, true]), CursorIcon::ResizeNorthEast);
        assert_eq!(cursor(vec2(40.0, 0.0), [false, true]), CursorIcon::ResizeVertical);
        assert_eq!(cursor(vec2(3.0, 3.0), [true, true]), CursorIcon::AllScroll);
    }
}