Skip to main content

ferrochart_core/
interaction.rs

1//! Platform-independent input events and the interaction state machine:
2//! panning with kinetic scrolling, wheel and pinch zoom, axis dragging,
3//! keyboard navigation and the crosshair.
4//!
5//! Bindings (winit, DOM, native) translate their events into [`InputEvent`]s
6//! in CSS pixels; the chart multiplies by the device pixel ratio. Input never
7//! allocates: the state machine keeps a fixed-size velocity history.
8//!
9//! **Clock**: kinetic scrolling compares `time_ms` of pointer events with the
10//! `now_ms` passed to `Chart::build_frame`, so both must come from the same
11//! clock (e.g. `performance.now()` or `Instant` since start).
12//!
13//! With several panes, price-axis drags, wheel zoom over the axis and vertical
14//! panning act on the pane under the pointer; dragging a separator resizes
15//! the two panes next to it.
16//!
17//! Drawings: with a tool armed, clicks create a drawing
18//! (click per anchor, or press-drag-release for the first two); otherwise a
19//! press on a drawing selects it and drags it (or the handle under the
20//! pointer) unless it is locked. Escape cancels, Delete removes the
21//! selection, Ctrl/โŒ˜+Z undoes, Ctrl/โŒ˜+Shift+Z and Ctrl/โŒ˜+Y redo.
22//!
23
24use smallvec::SmallVec;
25
26use crate::chart::{Chart, HANDLE_CSS};
27use crate::data::{DrawingId, PaneId};
28use crate::drawing::{
29    Anchor, AnchorCount, FREEHAND_STEP_CSS, HitPart, index_of_time, time_of_index,
30};
31use crate::frame::Invalidation;
32use crate::geom::{Css, PointCss, PointPx, Px};
33use crate::pane::{MIN_PANE_CSS, SEPARATOR_HIT_CSS, SEPARATOR_PX, split_stretch};
34
35/// Mouse button.
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
37#[non_exhaustive]
38pub enum Button {
39    /// Primary button (also touch and pen contact).
40    #[default]
41    Left,
42    /// Middle button.
43    Middle,
44    /// Secondary button.
45    Right,
46}
47
48/// Keyboard modifiers. Plain flags mirror the DOM/winit events they come from.
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
50#[allow(clippy::struct_excessive_bools)]
51pub struct Modifiers {
52    /// Shift.
53    pub shift: bool,
54    /// Control.
55    pub ctrl: bool,
56    /// Alt / Option.
57    pub alt: bool,
58    /// Meta / Command / Windows.
59    pub meta: bool,
60}
61
62/// Scroll amount of a wheel event.
63#[derive(Clone, Copy, Debug, PartialEq)]
64pub enum WheelDelta {
65    /// Lines (mouse wheel notches). Positive `y` scrolls down.
66    Lines {
67        /// Horizontal lines.
68        x: f32,
69        /// Vertical lines.
70        y: f32,
71    },
72    /// Pixels (touchpads, precise wheels). Positive `y` scrolls down.
73    Pixels {
74        /// Horizontal distance.
75        x: Css,
76        /// Vertical distance.
77        y: Css,
78    },
79}
80
81/// Phase of a continuous gesture.
82#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
83pub enum GesturePhase {
84    /// The gesture begins.
85    Start,
86    /// The gesture continues.
87    Update,
88    /// The gesture ends.
89    End,
90}
91
92/// Keys the chart reacts to.
93#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
94#[non_exhaustive]
95pub enum Key {
96    /// Left arrow: pan towards earlier bars.
97    ArrowLeft,
98    /// Right arrow: pan towards later bars.
99    ArrowRight,
100    /// Up arrow: zoom in.
101    ArrowUp,
102    /// Down arrow: zoom out.
103    ArrowDown,
104    /// Home: scroll to the first bar.
105    Home,
106    /// End: scroll to the latest bar.
107    End,
108    /// Escape: cancel the current drag or the drawing being created.
109    Escape,
110    /// Delete: delete the selected drawing.
111    Delete,
112    /// Enter: finish a drawing with an open number of anchors (a path).
113    Enter,
114    /// Any other key, by character.
115    Char(char),
116}
117
118/// A platform-independent input event. Positions are in CSS pixels relative to
119/// the chart's top-left corner.
120#[derive(Clone, Copy, Debug, PartialEq)]
121#[non_exhaustive]
122pub enum InputEvent {
123    /// A button was pressed or a touch began.
124    PointerDown {
125        /// Pointer id (mouse = 0).
126        id: u64,
127        /// Position.
128        pos: PointCss,
129        /// Button.
130        button: Button,
131        /// Modifiers.
132        mods: Modifiers,
133        /// Event time, same clock as `build_frame`'s `now_ms`.
134        time_ms: f64,
135    },
136    /// The pointer moved.
137    PointerMove {
138        /// Pointer id.
139        id: u64,
140        /// Position.
141        pos: PointCss,
142        /// Modifiers.
143        mods: Modifiers,
144        /// Event time.
145        time_ms: f64,
146    },
147    /// A button was released or a touch ended.
148    PointerUp {
149        /// Pointer id.
150        id: u64,
151        /// Position.
152        pos: PointCss,
153        /// Button.
154        button: Button,
155        /// Modifiers.
156        mods: Modifiers,
157        /// Event time.
158        time_ms: f64,
159    },
160    /// The pointer left the chart.
161    PointerLeave,
162    /// Wheel or touchpad scroll.
163    Wheel {
164        /// Pointer position.
165        pos: PointCss,
166        /// Scroll amount.
167        delta: WheelDelta,
168        /// Modifiers.
169        mods: Modifiers,
170    },
171    /// Touchpad or touch-screen pinch. `scale` is relative to the previous event.
172    Pinch {
173        /// Phase.
174        phase: GesturePhase,
175        /// Center of the gesture.
176        center: PointCss,
177        /// Scale factor since the previous event (> 1 zooms in).
178        scale: f32,
179    },
180    /// A key was pressed or released.
181    Key {
182        /// The key.
183        key: Key,
184        /// Pressed (`true`) or released.
185        pressed: bool,
186        /// Modifiers.
187        mods: Modifiers,
188    },
189    /// Double click / double tap.
190    DoubleClick {
191        /// Position.
192        pos: PointCss,
193        /// Button.
194        button: Button,
195    },
196}
197
198/// Mouse cursor the host should show.
199#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
200#[non_exhaustive]
201pub enum CursorIcon {
202    /// Arrow.
203    #[default]
204    Default,
205    /// Crosshair (over the plot).
206    Crosshair,
207    /// Open hand.
208    Grab,
209    /// Closed hand (panning).
210    Grabbing,
211    /// Horizontal resize (time axis).
212    EwResize,
213    /// Vertical resize (price axis).
214    NsResize,
215    /// Pointing hand (over a drawing).
216    Pointer,
217    /// Move (over a drawing's handle, or dragging a drawing).
218    Move,
219}
220
221/// Result of [`Chart::handle_input`].
222#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
223pub struct InputResult {
224    /// The chart used the event; the host should not handle it further (e.g.
225    /// prevent page scrolling on the web).
226    pub consumed: bool,
227    /// Cursor to show.
228    pub cursor: CursorIcon,
229}
230
231/// Crosshair behavior.
232#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
233#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
234pub enum CrosshairMode {
235    /// Follows the pointer; x snaps to bar centers.
236    #[default]
237    Normal,
238    /// y snaps to the nearest of the bar's open, high, low and close.
239    Magnet,
240    /// No crosshair.
241    Hidden,
242}
243
244/// Pointer movement (CSS px) before a press becomes a pan.
245const DRAG_THRESHOLD: f32 = 3.0;
246/// Kinetic velocity decay time constant: after a release at speed `v`, the
247/// speed is `v ยท exp(-t / KINETIC_TAU_MS)`.
248pub const KINETIC_TAU_MS: f64 = 325.0;
249/// Kinetic scrolling starts above / stops below this speed (physical px per ms).
250pub const KINETIC_MIN_SPEED: f64 = 0.05;
251/// Velocity is measured over the pointer moves of the last ... ms.
252const VELOCITY_WINDOW_MS: f64 = 100.0;
253/// A pan released after a pause longer than this has no kinetic phase.
254const RELEASE_PAUSE_MS: f64 = 50.0;
255/// CSS px per wheel line.
256const LINE_PX: f32 = 40.0;
257/// Zoom factor per CSS px of wheel scroll.
258const WHEEL_ZOOM: f64 = 0.002;
259/// Zoom factor per CSS px of axis drag.
260const AXIS_DRAG_ZOOM: f64 = 0.005;
261
262/// Where a pointer is.
263#[derive(Clone, Copy, Debug, PartialEq, Eq)]
264pub(crate) enum Region {
265    Plot(PaneId),
266    PriceAxis(PaneId),
267    /// The separator above pane `k` (an index, `k >= 1`).
268    Separator(usize),
269    TimeAxis,
270    Outside,
271}
272
273#[derive(Clone, Copy, Debug, Default)]
274struct Sample {
275    t: f64,
276    x: f32,
277}
278
279/// Release velocity of a drag along one axis, from a fixed number of recent
280/// pointer samples (no allocation). Used by the chart's kinetic panning and
281/// by `ferrochart-plot`.
282///
283/// ```
284/// use ferrochart_core::interaction::VelocityTracker;
285///
286/// let mut v = VelocityTracker::default();
287/// for i in 0..10 {
288///     v.record(f64::from(i) * 10.0, i as f32 * 5.0); // 5 px every 10 ms
289/// }
290/// assert!((v.release_velocity(95.0) - 0.5).abs() < 1e-9);
291/// assert_eq!(v.release_velocity(200.0), 0.0); // paused before release
292/// ```
293#[derive(Clone, Copy, Debug, Default)]
294pub struct VelocityTracker {
295    samples: [Sample; 8],
296    n_samples: usize,
297}
298
299impl VelocityTracker {
300    /// Forgets all samples (a new drag).
301    pub fn clear(&mut self) {
302        self.n_samples = 0;
303    }
304
305    /// Records the pointer position `x` (px) at time `t` (ms).
306    pub fn record(&mut self, t: f64, x: f32) {
307        self.samples.copy_within(1.., 0);
308        let last = self.samples.len() - 1;
309        self.samples[last] = Sample { t, x };
310        self.n_samples = (self.n_samples + 1).min(self.samples.len());
311    }
312
313    /// Release velocity in px/ms from the samples of the last 100 ms; 0 if
314    /// the pointer paused for more than 50 ms before `now`.
315    pub fn release_velocity(&self, now: f64) -> f64 {
316        let recent = &self.samples[self.samples.len() - self.n_samples..];
317        let Some(last) = recent.last() else {
318            return 0.0;
319        };
320        if now - last.t > RELEASE_PAUSE_MS {
321            return 0.0;
322        }
323        let Some(first) = recent.iter().find(|s| last.t - s.t <= VELOCITY_WINDOW_MS) else {
324            return 0.0;
325        };
326        let dt = last.t - first.t;
327        if dt <= 0.0 {
328            return 0.0;
329        }
330        f64::from(last.x - first.x) / dt
331    }
332}
333
334/// Interaction state.
335#[derive(Clone, Copy, Debug, Default)]
336pub(crate) enum Drag {
337    #[default]
338    Idle,
339    PressPending {
340        id: u64,
341        start: PointPx,
342        pane: PaneId,
343    },
344    Panning {
345        id: u64,
346        last: PointPx,
347        pane: PaneId,
348    },
349    ScalingPrice {
350        id: u64,
351        last_y: f32,
352        pane: PaneId,
353    },
354    ScalingTime {
355        id: u64,
356        last_x: f32,
357    },
358    /// Dragging the separator between `upper` and `lower`, which together span
359    /// `top..bottom` (separator included) when the drag started.
360    ResizingPanes {
361        id: u64,
362        upper: PaneId,
363        lower: PaneId,
364        top: f32,
365        bottom: f32,
366    },
367    /// Dragging a drawing or one of its handles from `start`.
368    EditingDrawing {
369        id: u64,
370        drawing: DrawingId,
371        part: HitPart,
372        start: PointPx,
373        pane: PaneId,
374    },
375}
376
377impl Drag {
378    /// The pane the drag acts on, if any.
379    pub(crate) fn pane(self) -> Option<PaneId> {
380        match self {
381            Self::PressPending { pane, .. }
382            | Self::Panning { pane, .. }
383            | Self::ScalingPrice { pane, .. }
384            | Self::EditingDrawing { pane, .. } => Some(pane),
385            Self::ResizingPanes { upper, .. } => Some(upper),
386            Self::Idle | Self::ScalingTime { .. } => None,
387        }
388    }
389
390    /// Whether the drag involves `pane`.
391    pub(crate) fn involves(self, pane: PaneId) -> bool {
392        match self {
393            Self::ResizingPanes { upper, lower, .. } => upper == pane || lower == pane,
394            _ => self.pane() == Some(pane),
395        }
396    }
397}
398
399/// State machine data stored in the chart.
400#[derive(Clone, Copy, Debug)]
401pub(crate) struct Interaction {
402    pub(crate) drag: Drag,
403    /// Kinetic scrolling velocity (physical px per ms) and the time of the last
404    /// step (`None` until the first frame after release).
405    pub(crate) kinetic: Option<(f64, Option<f64>)>,
406    velocity: VelocityTracker,
407    /// Pointer position in physical px, `None` when outside.
408    pub(crate) pointer: Option<PointPx>,
409    pub(crate) crosshair: CrosshairMode,
410}
411
412impl Default for Interaction {
413    fn default() -> Self {
414        Self {
415            drag: Drag::Idle,
416            kinetic: None,
417            velocity: VelocityTracker::default(),
418            pointer: None,
419            crosshair: CrosshairMode::Normal,
420        }
421    }
422}
423
424impl Chart {
425    pub(crate) fn region(&self, p: PointPx) -> Region {
426        let l = self.layout;
427        let in_width = p.x >= 0.0 && p.x < l.time_axis.right();
428        if in_width && p.y < l.time_axis.y {
429            let hit = SEPARATOR_HIT_CSS * self.dpr;
430            for k in 1..self.panes.len() {
431                let center = self.panes[k].plot.y - SEPARATOR_PX * 0.5;
432                if (p.y - center).abs() <= hit {
433                    return Region::Separator(k);
434                }
435            }
436        }
437        if let Some(i) = self.pane_at(p) {
438            return Region::Plot(self.panes[i].id);
439        }
440        if l.price_axis.contains(p) {
441            return self
442                .panes
443                .iter()
444                .find(|pane| p.y >= pane.plot.y && p.y < pane.plot.bottom())
445                .map_or(Region::Outside, |pane| Region::PriceAxis(pane.id));
446        }
447        if l.time_axis.contains(p) {
448            Region::TimeAxis
449        } else {
450            Region::Outside
451        }
452    }
453
454    fn hover_cursor(&self, p: PointPx) -> CursorIcon {
455        match self.region(p) {
456            Region::Plot(pane) => {
457                if self.drawings.armed.is_some() || self.drawings.creating.is_some() {
458                    return CursorIcon::Crosshair;
459                }
460                match self.hit_drawing(pane, p) {
461                    Some((_, HitPart::Handle(_))) => CursorIcon::Move,
462                    Some((_, HitPart::Body)) => CursorIcon::Pointer,
463                    None => CursorIcon::Crosshair,
464                }
465            }
466            Region::PriceAxis(_) | Region::Separator(_) => CursorIcon::NsResize,
467            Region::TimeAxis => CursorIcon::EwResize,
468            Region::Outside => CursorIcon::Default,
469        }
470    }
471
472    fn set_pointer(&mut self, p: Option<PointPx>) {
473        if self.input.pointer != p {
474            self.input.pointer = p;
475            if self.input.crosshair != CrosshairMode::Hidden {
476                self.invalidation = self.invalidation.max(Invalidation::Cursor);
477            }
478        }
479    }
480
481    /// Plot-relative x of a physical point.
482    fn plot_x(&self, p: PointPx) -> f32 {
483        p.x - self.layout.plot.x
484    }
485
486    fn zoom_time(&mut self, anchor_x: f32, factor: f64) {
487        self.time_scale.zoom(Px(anchor_x), factor);
488    }
489
490    fn zoom_price_at(&mut self, pane: PaneId, y: f32, factor: f64) {
491        let Some(pane) = self.pane_mut(pane) else {
492            return;
493        };
494        let plot = pane.plot;
495        let center =
496            pane.price_scale
497                .y_to_price(f64::from(y), f64::from(plot.y), f64::from(plot.h));
498        pane.price_scale.zoom_around(factor, center);
499    }
500
501    /// Moves the separator of a `ResizingPanes` drag to `y`.
502    fn resize_panes(&mut self, y: f32) {
503        let Drag::ResizingPanes {
504            upper,
505            lower,
506            top,
507            bottom,
508            ..
509        } = self.input.drag
510        else {
511            return;
512        };
513        let min = MIN_PANE_CSS * self.dpr;
514        let (lo, hi) = (top + min, bottom - min - SEPARATOR_PX);
515        if lo > hi {
516            return;
517        }
518        let y = y.round().clamp(lo, hi);
519        let (Some(su), Some(sl)) = (self.pane_stretch(upper), self.pane_stretch(lower)) else {
520            return;
521        };
522        if let Some((a, b)) = split_stretch(su + sl, y - top, bottom - y - SEPARATOR_PX) {
523            for (id, s) in [(upper, a), (lower, b)] {
524                if let Some(p) = self.pane_mut(id) {
525                    p.stretch = s;
526                }
527            }
528            self.invalidation = Invalidation::Full;
529        }
530    }
531
532    /// The anchor under `p` on `pane`: x snaps to the nearest bar (times
533    /// past the data are extrapolated), y snaps to the bar's OHLC in magnet
534    /// mode. `None` without data.
535    pub(crate) fn anchor_at(&self, pane: PaneId, p: PointPx) -> Option<Anchor> {
536        let i = self.pane_index(pane)?;
537        let ctx = self.drawing_ctx(i, &self.text_cache)?;
538        let plot = ctx.plot;
539        let idx = self.time_scale.x_to_index(Px(p.x - plot.x)).round();
540        let time = time_of_index(&self.time_index, idx)?;
541        let mut y = p.y;
542        if self.input.crosshair == CrosshairMode::Magnet
543            && let Some(bar) = self.magnet_bar(pane, idx as i64)
544        {
545            let mut best = f32::INFINITY;
546            for v in bar {
547                if let Some(vy) = ctx.y_of(v)
548                    && (vy - p.y).abs() < (best - p.y).abs()
549                {
550                    best = vy;
551                }
552            }
553            if best.is_finite() {
554                y = best;
555            }
556        }
557        let price = ctx.price_at(y);
558        price.is_finite().then_some(Anchor { time, price })
559    }
560
561    /// The anchor exactly at `p` (no snapping to bars or the magnet): for
562    /// freehand drawings.
563    pub(crate) fn free_anchor_at(&self, pane: PaneId, p: PointPx) -> Option<Anchor> {
564        let i = self.pane_index(pane)?;
565        let ctx = self.drawing_ctx(i, &self.text_cache)?;
566        let time = ctx.time_at(p.x)?;
567        let price = ctx.price_at(p.y);
568        price.is_finite().then_some(Anchor { time, price })
569    }
570
571    /// What `p` hits among the drawings of `pane`: the selected drawing's
572    /// handles first, then the selected drawing, then the others from the
573    /// top.
574    pub(crate) fn hit_drawing(&self, pane: PaneId, p: PointPx) -> Option<(DrawingId, HitPart)> {
575        let i = self.pane_index(pane)?;
576        let ctx = self.drawing_ctx(i, &self.text_cache)?;
577        let tol = ctx.hit_tolerance();
578        let entries = &self.drawings.entries;
579        let selected = self
580            .drawings
581            .selected()
582            .and_then(|s| self.drawings.entry(s))
583            .filter(|e| e.pane == pane && e.visible);
584        if let Some(e) = selected {
585            let r = HANDLE_CSS * 0.5 * self.dpr + tol * 0.5;
586            let hit = self
587                .handle_buf
588                .try_borrow_mut()
589                .ok()
590                .and_then(|mut handles| {
591                    handles.clear();
592                    e.tool.handles(&ctx, &mut handles);
593                    handles
594                        .iter()
595                        .position(|h| (p.x - h.x).hypot(p.y - h.y) <= r)
596                });
597            if let Some(k) = hit {
598                return Some((e.id, HitPart::Handle(k)));
599            }
600            if let Some(part) = e.tool.hit_test(&ctx, p) {
601                return Some((e.id, part));
602            }
603        }
604        entries.iter().rev().find_map(|e| {
605            let b = e.bbox;
606            let near = b.w + b.h > 0.0
607                && p.x >= b.x - tol
608                && p.x <= b.right() + tol
609                && p.y >= b.y - tol
610                && p.y <= b.bottom() + tol;
611            if e.pane != pane || !e.visible || !near {
612                return None;
613            }
614            Some((e.id, e.tool.hit_test(&ctx, p)?))
615        })
616    }
617
618    /// A press on the plot of `pane` when drawings are involved: creating
619    /// one, or selecting and starting to drag one. `None` lets the press pan.
620    fn drawing_press(&mut self, id: u64, pane: PaneId, p: PointPx) -> Option<InputResult> {
621        let take = |cursor| {
622            Some(InputResult {
623                consumed: true,
624                cursor,
625            })
626        };
627        if let Some(c) = self.drawings.creating {
628            if let Some(a) = self.anchor_at(c.pane, p) {
629                self.drawings.creation_click(a, Some(p));
630            }
631            return take(CursorIcon::Crosshair);
632        }
633        if self.drawings.armed.is_some() {
634            if let Some(a) = self.anchor_at(pane, p) {
635                self.drawings.begin_creation(pane, a, p);
636            }
637            // A freehand drawing starts exactly under the pointer.
638            if self.drawings.creating_count() == Some(AnchorCount::Freehand)
639                && let Some(a) = self.free_anchor_at(pane, p)
640                && let Some(c) = self.drawings.creating
641                && let Some(e) = self.drawings.entry_mut(c.id)
642                && let Some(first) = e.tool.anchors_mut().first_mut()
643            {
644                *first = a;
645            }
646            return take(CursorIcon::Crosshair);
647        }
648        let Some((drawing, part)) = self.hit_drawing(pane, p) else {
649            let _ = self.drawings.select(None);
650            return None;
651        };
652        let _ = self.drawings.select(Some(drawing));
653        let e = self.drawings.entry(drawing)?;
654        if e.locked {
655            return None;
656        }
657        let before = e.tool.anchors().to_vec();
658        self.drawings.edit_before = before;
659        self.input.drag = Drag::EditingDrawing {
660            id,
661            drawing,
662            part,
663            start: p,
664            pane,
665        };
666        take(CursorIcon::Move)
667    }
668
669    /// Moves the dragged drawing (or its handle) to follow the pointer: the
670    /// body moves by whole bars and by the pointer's y in display space.
671    fn drag_drawing(&mut self, p: PointPx) {
672        let Drag::EditingDrawing {
673            drawing,
674            part,
675            start,
676            pane,
677            ..
678        } = self.input.drag
679        else {
680            return;
681        };
682        match part {
683            HitPart::Handle(k) => {
684                let Some(a) = self.anchor_at(pane, p) else {
685                    return;
686                };
687                if let Some(e) = self.drawings.entry_mut(drawing) {
688                    e.tool.move_handle(k, a);
689                }
690            }
691            HitPart::Body => {
692                let Some(i) = self.pane_index(pane) else {
693                    return;
694                };
695                let Some(ctx) = self.drawing_ctx(i, &self.text_cache) else {
696                    return;
697                };
698                let spacing = self.time_scale.bar_spacing();
699                let di = if spacing > 0.0 {
700                    (f64::from(p.x - start.x) / spacing).round()
701                } else {
702                    0.0
703                };
704                let dy = p.y - start.y;
705                let moved: SmallVec<[Anchor; 4]> = self
706                    .drawings
707                    .edit_before
708                    .iter()
709                    .map(|a| {
710                        let time = if di == 0.0 {
711                            Some(a.time)
712                        } else {
713                            index_of_time(&self.time_index, a.time)
714                                .and_then(|j| time_of_index(&self.time_index, j + di))
715                        };
716                        let price = ctx.y_of(a.price).map(|y| ctx.price_at(y + dy));
717                        match (time, price) {
718                            (Some(time), Some(price)) if price.is_finite() => {
719                                Anchor { time, price }
720                            }
721                            _ => *a,
722                        }
723                    })
724                    .collect();
725                if let Some(e) = self.drawings.entry_mut(drawing) {
726                    let anchors = e.tool.anchors_mut();
727                    anchors.clear();
728                    anchors.extend_from_slice(&moved);
729                }
730            }
731        }
732        self.drawings.dirty = true;
733    }
734
735    /// The current crosshair mode.
736    pub fn crosshair_mode(&self) -> CrosshairMode {
737        self.input.crosshair
738    }
739
740    /// Sets the crosshair mode.
741    pub fn set_crosshair_mode(&mut self, mode: CrosshairMode) {
742        self.input.crosshair = mode;
743        self.invalidation = self.invalidation.max(Invalidation::Cursor);
744    }
745
746    /// Whether kinetic scrolling is running (the host keeps requesting frames).
747    pub fn is_animating(&self) -> bool {
748        self.input.kinetic.is_some()
749    }
750
751    /// Advances kinetic scrolling to `now_ms` (called by `build_frame`).
752    pub(crate) fn step_kinetic(&mut self, now_ms: f64) {
753        let Some((v, last)) = self.input.kinetic else {
754            return;
755        };
756        let Some(last) = last else {
757            self.input.kinetic = Some((v, Some(now_ms)));
758            self.time_scale.changed = true;
759            return;
760        };
761        let dt = now_ms - last;
762        if !(dt.is_finite() && dt > 0.0) {
763            self.input.kinetic = Some((v, Some(now_ms)));
764            return;
765        }
766        let decay = (-dt / KINETIC_TAU_MS).exp();
767        let distance = v * KINETIC_TAU_MS * (1.0 - decay);
768        let before = self.time_scale.right_offset();
769        self.time_scale.scroll_by(Px(distance as f32));
770        let v = v * decay;
771        let stuck = (self.time_scale.right_offset() - before).abs() < 1e-9;
772        self.input.kinetic = (v.abs() >= KINETIC_MIN_SPEED && !stuck).then_some((v, Some(now_ms)));
773    }
774
775    /// Handles an input event. Coordinates are CSS pixels; regions refer
776    /// to the layout of the last built frame.
777    ///
778    /// # Examples
779    ///
780    /// ```
781    /// use ferrochart_core::chart::{SeriesData, SeriesOptions};
782    /// use ferrochart_core::frame::SeriesKind;
783    /// use ferrochart_core::geom::{PointCss, SizeCss};
784    /// use ferrochart_core::interaction::{Button, InputEvent, Modifiers};
785    /// use ferrochart_core::testing::{random_walk, MonoMeasurer};
786    /// use ferrochart_core::{Chart, ChartOptions};
787    ///
788    /// let mut chart = Chart::new(ChartOptions::default());
789    /// chart.resize(SizeCss { w: 800.0, h: 400.0 }, 1.0);
790    /// let id = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
791    /// chart.set_data(id, SeriesData::Ohlc(random_walk(1, 1000, 0, 60_000)?))?;
792    /// chart.build_frame(0.0, &MonoMeasurer);
793    ///
794    /// let before = chart.time_scale().visible_range();
795    /// let mods = Modifiers::default();
796    /// let at = |x| PointCss { x, y: 200.0 };
797    /// chart.handle_input(InputEvent::PointerDown { id: 0, pos: at(400.0), button: Button::Left, mods, time_ms: 0.0 });
798    /// chart.handle_input(InputEvent::PointerMove { id: 0, pos: at(460.0), mods, time_ms: 16.0 });
799    /// chart.handle_input(InputEvent::PointerUp { id: 0, pos: at(460.0), button: Button::Left, mods, time_ms: 500.0 });
800    /// // Dragging right by 60 px shows bars 10 bars earlier (6 px spacing).
801    /// let after = chart.time_scale().visible_range();
802    /// assert!((before.0 - after.0 - 10.0).abs() < 1e-9);
803    /// # Ok::<(), ferrochart_core::Error>(())
804    /// ```
805    pub fn handle_input(&mut self, event: InputEvent) -> InputResult {
806        let dpr = self.dpr;
807        let consumed = |cursor| InputResult {
808            consumed: true,
809            cursor,
810        };
811        match event {
812            InputEvent::PointerDown {
813                id,
814                pos,
815                button,
816                time_ms,
817                ..
818            } => {
819                let p = pos.to_px(dpr);
820                self.input.kinetic = None;
821                if button != Button::Left || !matches!(self.input.drag, Drag::Idle) {
822                    return InputResult {
823                        consumed: false,
824                        cursor: self.hover_cursor(p),
825                    };
826                }
827                match self.region(p) {
828                    Region::Plot(pane) => {
829                        if let Some(result) = self.drawing_press(id, pane, p) {
830                            self.set_pointer(Some(p));
831                            return result;
832                        }
833                        self.input.drag = Drag::PressPending { id, start: p, pane };
834                        self.input.velocity.clear();
835                        self.input.velocity.record(time_ms, p.x);
836                        self.set_pointer(Some(p));
837                        consumed(CursorIcon::Crosshair)
838                    }
839                    Region::PriceAxis(pane) => {
840                        self.input.drag = Drag::ScalingPrice {
841                            id,
842                            last_y: p.y,
843                            pane,
844                        };
845                        consumed(CursorIcon::NsResize)
846                    }
847                    Region::Separator(k) => {
848                        let (Some(up), Some(down)) = (self.panes.get(k - 1), self.panes.get(k))
849                        else {
850                            return InputResult::default();
851                        };
852                        self.input.drag = Drag::ResizingPanes {
853                            id,
854                            upper: up.id,
855                            lower: down.id,
856                            top: up.plot.y,
857                            bottom: down.plot.bottom(),
858                        };
859                        consumed(CursorIcon::NsResize)
860                    }
861                    Region::TimeAxis => {
862                        self.input.drag = Drag::ScalingTime { id, last_x: p.x };
863                        consumed(CursorIcon::EwResize)
864                    }
865                    Region::Outside => InputResult::default(),
866                }
867            }
868            InputEvent::PointerMove {
869                id, pos, time_ms, ..
870            } => {
871                let p = pos.to_px(dpr);
872                let in_plot = matches!(self.region(p), Region::Plot(_));
873                match self.input.drag {
874                    Drag::Idle if self.drawings.creating.is_some() => {
875                        if let Some(c) = self.drawings.creating {
876                            if c.count == AnchorCount::Freehand {
877                                if let Some(a) = self.free_anchor_at(c.pane, p) {
878                                    let step = FREEHAND_STEP_CSS * dpr;
879                                    self.drawings.freehand_move(a, p, step);
880                                }
881                            } else if let Some(a) = self.anchor_at(c.pane, p) {
882                                self.drawings.creation_move(a);
883                            }
884                        }
885                        self.set_pointer(in_plot.then_some(p));
886                        consumed(CursorIcon::Crosshair)
887                    }
888                    Drag::EditingDrawing { id: d, .. } if d == id => {
889                        self.drag_drawing(p);
890                        self.set_pointer(in_plot.then_some(p));
891                        consumed(CursorIcon::Move)
892                    }
893                    Drag::Idle => {
894                        self.set_pointer(in_plot.then_some(p));
895                        InputResult {
896                            consumed: false,
897                            cursor: self.hover_cursor(p),
898                        }
899                    }
900                    Drag::PressPending {
901                        id: d, start, pane, ..
902                    } if d == id => {
903                        let moved = (p.x - start.x).hypot(p.y - start.y);
904                        if moved > DRAG_THRESHOLD * dpr {
905                            self.input.drag = Drag::Panning {
906                                id,
907                                last: start,
908                                pane,
909                            };
910                            return self.pan_to(p, time_ms);
911                        }
912                        self.set_pointer(in_plot.then_some(p));
913                        consumed(CursorIcon::Crosshair)
914                    }
915                    Drag::Panning { id: d, .. } if d == id => self.pan_to(p, time_ms),
916                    Drag::ScalingPrice {
917                        id: d,
918                        last_y,
919                        pane,
920                    } if d == id => {
921                        let dy = f64::from((p.y - last_y) / dpr);
922                        if let Some(scale) = self.pane_mut(pane).map(|p| &mut p.price_scale) {
923                            let center = scale.center_price();
924                            scale.zoom_around((dy * AXIS_DRAG_ZOOM).exp(), center);
925                        }
926                        self.input.drag = Drag::ScalingPrice {
927                            id,
928                            last_y: p.y,
929                            pane,
930                        };
931                        consumed(CursorIcon::NsResize)
932                    }
933                    Drag::ResizingPanes { id: d, .. } if d == id => {
934                        self.resize_panes(p.y);
935                        consumed(CursorIcon::NsResize)
936                    }
937                    Drag::ScalingTime { id: d, last_x } if d == id => {
938                        let dx = f64::from((p.x - last_x) / dpr);
939                        let right = self.layout.plot.w;
940                        self.zoom_time(right, (dx * AXIS_DRAG_ZOOM).exp());
941                        self.input.drag = Drag::ScalingTime { id, last_x: p.x };
942                        consumed(CursorIcon::EwResize)
943                    }
944                    _ => InputResult::default(),
945                }
946            }
947            InputEvent::PointerUp {
948                id, pos, time_ms, ..
949            } => {
950                let p = pos.to_px(dpr);
951                let drag = self.input.drag;
952                if let Some(c) = self.drawings.creating
953                    && matches!(drag, Drag::Idle)
954                {
955                    // Releasing far from the press is a click (drag creation).
956                    let far = c
957                        .down
958                        .is_some_and(|d| (p.x - d.x).hypot(p.y - d.y) > DRAG_THRESHOLD * dpr);
959                    if c.count == AnchorCount::Freehand {
960                        if let Some(a) = self.free_anchor_at(c.pane, p) {
961                            // The release point, unless the last anchor is close.
962                            self.drawings.freehand_move(a, p, 1.0);
963                        }
964                        self.drawings.freehand_release();
965                        return consumed(self.hover_cursor(p));
966                    }
967                    if let Some(c) = self.drawings.creating.as_mut() {
968                        c.down = None;
969                    }
970                    if far && let Some(a) = self.anchor_at(c.pane, p) {
971                        self.drawings.creation_click(a, None);
972                    }
973                    return consumed(CursorIcon::Crosshair);
974                }
975                if let Drag::EditingDrawing {
976                    id: d,
977                    drawing,
978                    start,
979                    pane,
980                    ..
981                } = drag
982                {
983                    if d != id {
984                        return InputResult::default();
985                    }
986                    self.input.drag = Drag::Idle;
987                    let before = core::mem::take(&mut self.drawings.edit_before);
988                    self.drawings.moved(drawing, before);
989                    // A press on a drawing that did not move it is a click.
990                    if (p.x - start.x).hypot(p.y - start.y) <= DRAG_THRESHOLD * dpr {
991                        self.emit_click(pane, p, Some(drawing));
992                    }
993                    return consumed(self.hover_cursor(p));
994                }
995                let (Drag::PressPending { id: d, .. }
996                | Drag::Panning { id: d, .. }
997                | Drag::ScalingPrice { id: d, .. }
998                | Drag::ScalingTime { id: d, .. }
999                | Drag::ResizingPanes { id: d, .. }) = drag
1000                else {
1001                    return InputResult {
1002                        consumed: false,
1003                        cursor: self.hover_cursor(p),
1004                    };
1005                };
1006                if d != id {
1007                    return InputResult::default();
1008                }
1009                self.input.drag = Drag::Idle;
1010                if let Drag::PressPending { pane, .. } = drag {
1011                    self.emit_click(pane, p, None);
1012                }
1013                if let Drag::Panning { .. } = drag {
1014                    let v = self.input.velocity.release_velocity(time_ms);
1015                    if v.abs() >= KINETIC_MIN_SPEED {
1016                        // Start counting from the release.
1017                        self.input.kinetic = Some((v, Some(time_ms)));
1018                        self.time_scale.changed = true;
1019                    }
1020                }
1021                consumed(self.hover_cursor(p))
1022            }
1023            InputEvent::PointerLeave => {
1024                self.set_pointer(None);
1025                InputResult::default()
1026            }
1027            InputEvent::Wheel { pos, delta, mods } => self.wheel(pos.to_px(dpr), delta, mods),
1028            InputEvent::Pinch {
1029                phase,
1030                center,
1031                scale,
1032            } => {
1033                if phase == GesturePhase::Start {
1034                    self.input.kinetic = None;
1035                }
1036                let p = center.to_px(dpr);
1037                if scale.is_finite() && scale > 0.0 {
1038                    let x = self.plot_x(p);
1039                    self.zoom_time(x, f64::from(scale));
1040                }
1041                consumed(self.hover_cursor(p))
1042            }
1043            InputEvent::Key { key, pressed, mods } => {
1044                if !pressed {
1045                    return InputResult::default();
1046                }
1047                self.key(key, mods)
1048            }
1049            InputEvent::DoubleClick { pos, button } => {
1050                let p = pos.to_px(dpr);
1051                if button != Button::Left {
1052                    return InputResult::default();
1053                }
1054                if self.drawings.finish_open() {
1055                    return consumed(self.hover_cursor(p));
1056                }
1057                match self.region(p) {
1058                    Region::PriceAxis(pane) => {
1059                        if let Some(pane) = self.pane_mut(pane) {
1060                            pane.price_scale.set_auto_scale(true);
1061                        }
1062                        consumed(CursorIcon::NsResize)
1063                    }
1064                    Region::TimeAxis => {
1065                        let spacing = self.default_bar_spacing.to_px(dpr).0;
1066                        self.time_scale.set_bar_spacing(f64::from(spacing));
1067                        consumed(CursorIcon::EwResize)
1068                    }
1069                    _ => InputResult::default(),
1070                }
1071            }
1072        }
1073    }
1074
1075    fn pan_to(&mut self, p: PointPx, time_ms: f64) -> InputResult {
1076        let Drag::Panning { id, last, pane } = self.input.drag else {
1077            return InputResult::default();
1078        };
1079        self.time_scale.scroll_by(Px(p.x - last.x));
1080        if let Some(pane) = self.pane_mut(pane)
1081            && !pane.price_scale.auto_scale()
1082        {
1083            let h = f64::from(pane.plot.h);
1084            pane.price_scale.pan_px(f64::from(p.y - last.y), h);
1085        }
1086        self.input.velocity.record(time_ms, p.x);
1087        self.input.drag = Drag::Panning { id, last: p, pane };
1088        let in_plot = matches!(self.region(p), Region::Plot(_));
1089        self.set_pointer(in_plot.then_some(p));
1090        InputResult {
1091            consumed: true,
1092            cursor: CursorIcon::Grabbing,
1093        }
1094    }
1095
1096    fn wheel(&mut self, p: PointPx, delta: WheelDelta, mods: Modifiers) -> InputResult {
1097        let (dx, dy) = match delta {
1098            WheelDelta::Lines { x, y } => (x * LINE_PX, y * LINE_PX),
1099            WheelDelta::Pixels { x, y } => (x.0, y.0),
1100        };
1101        if !(dx.is_finite() && dy.is_finite()) {
1102            return InputResult::default();
1103        }
1104        let region = self.region(p);
1105        if region == Region::Outside {
1106            return InputResult::default();
1107        }
1108        self.input.kinetic = None;
1109        let dpr = self.dpr;
1110        if mods.shift {
1111            // Shift + wheel pans; vertical wheels pan horizontally.
1112            let d = if dx.abs() > dy.abs() { dx } else { dy };
1113            self.time_scale.scroll_by(Px(-d * dpr));
1114        } else if let (Region::PriceAxis(pane), _) | (Region::Plot(pane), true) = (region, mods.alt)
1115        {
1116            self.zoom_price_at(pane, p.y, (f64::from(dy) * WHEEL_ZOOM).exp());
1117        } else if dx.abs() > dy.abs() {
1118            // Horizontal touchpad scroll pans.
1119            self.time_scale.scroll_by(Px(-dx * dpr));
1120        } else {
1121            let anchor = if region == Region::TimeAxis {
1122                self.layout.plot.w
1123            } else {
1124                self.plot_x(p)
1125            };
1126            self.zoom_time(anchor, (-f64::from(dy) * WHEEL_ZOOM).exp());
1127        }
1128        InputResult {
1129            consumed: true,
1130            cursor: self.hover_cursor(p),
1131        }
1132    }
1133
1134    fn key(&mut self, key: Key, mods: Modifiers) -> InputResult {
1135        let w = self.layout.plot.w;
1136        let command = mods.ctrl || mods.meta;
1137        let done = |consumed| InputResult {
1138            consumed,
1139            cursor: CursorIcon::Default,
1140        };
1141        match key {
1142            Key::Char('z' | 'Z') if command => {
1143                return done(if mods.shift {
1144                    self.drawings.redo()
1145                } else {
1146                    self.drawings.undo()
1147                });
1148            }
1149            Key::Char('y' | 'Y') if command => return done(self.drawings.redo()),
1150            Key::Escape if self.drawings.creating.is_some() => {
1151                self.drawings.escape_creation();
1152                return done(true);
1153            }
1154            Key::Escape if self.drawings.armed.is_some() => {
1155                self.drawings.cancel_tool();
1156                return done(true);
1157            }
1158            Key::Enter => return done(self.drawings.finish_open()),
1159            Key::Escape if matches!(self.input.drag, Drag::EditingDrawing { .. }) => {
1160                let before = core::mem::take(&mut self.drawings.edit_before);
1161                if let Drag::EditingDrawing { drawing, .. } = self.input.drag
1162                    && let Some(e) = self.drawings.entry_mut(drawing)
1163                {
1164                    let anchors = e.tool.anchors_mut();
1165                    anchors.clear();
1166                    anchors.extend_from_slice(&before);
1167                }
1168                self.drawings.dirty = true;
1169                self.input.drag = Drag::Idle;
1170                return done(true);
1171            }
1172            Key::Delete => {
1173                let Some(sel) = self.drawings.selected() else {
1174                    return done(false);
1175                };
1176                if matches!(self.input.drag, Drag::EditingDrawing { .. }) {
1177                    self.input.drag = Drag::Idle;
1178                }
1179                return done(self.drawings.remove(sel).is_ok());
1180            }
1181            Key::ArrowLeft => self.time_scale.scroll_by(Px(w * 0.1)),
1182            Key::ArrowRight => self.time_scale.scroll_by(Px(-w * 0.1)),
1183            Key::ArrowUp => self.zoom_time(w, 1.25),
1184            Key::ArrowDown => self.zoom_time(w, 0.8),
1185            Key::Home => self.time_scale.scroll_to_first(),
1186            Key::End => self.scroll_to_realtime(),
1187            Key::Escape => {
1188                let was_dragging = !matches!(self.input.drag, Drag::Idle);
1189                self.input.drag = Drag::Idle;
1190                self.input.kinetic = None;
1191                return InputResult {
1192                    consumed: was_dragging,
1193                    cursor: CursorIcon::Default,
1194                };
1195            }
1196            Key::Char(_) => return InputResult::default(),
1197        }
1198        InputResult {
1199            consumed: true,
1200            cursor: CursorIcon::Default,
1201        }
1202    }
1203}
1204
1205#[cfg(test)]
1206mod tests {
1207    use super::*;
1208
1209    #[test]
1210    fn velocity_uses_recent_samples() {
1211        let mut s = VelocityTracker::default();
1212        for i in 0..10 {
1213            s.record(f64::from(i) * 10.0, i as f32 * 5.0);
1214        }
1215        assert!((s.release_velocity(95.0) - 0.5).abs() < 1e-9);
1216        // A pause before release: no kinetic phase.
1217        assert!(s.release_velocity(200.0).abs() < 1e-12);
1218    }
1219}