1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
37#[non_exhaustive]
38pub enum Button {
39 #[default]
41 Left,
42 Middle,
44 Right,
46}
47
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
50#[allow(clippy::struct_excessive_bools)]
51pub struct Modifiers {
52 pub shift: bool,
54 pub ctrl: bool,
56 pub alt: bool,
58 pub meta: bool,
60}
61
62#[derive(Clone, Copy, Debug, PartialEq)]
64pub enum WheelDelta {
65 Lines {
67 x: f32,
69 y: f32,
71 },
72 Pixels {
74 x: Css,
76 y: Css,
78 },
79}
80
81#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
83pub enum GesturePhase {
84 Start,
86 Update,
88 End,
90}
91
92#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
94#[non_exhaustive]
95pub enum Key {
96 ArrowLeft,
98 ArrowRight,
100 ArrowUp,
102 ArrowDown,
104 Home,
106 End,
108 Escape,
110 Delete,
112 Enter,
114 Char(char),
116}
117
118#[derive(Clone, Copy, Debug, PartialEq)]
121#[non_exhaustive]
122pub enum InputEvent {
123 PointerDown {
125 id: u64,
127 pos: PointCss,
129 button: Button,
131 mods: Modifiers,
133 time_ms: f64,
135 },
136 PointerMove {
138 id: u64,
140 pos: PointCss,
142 mods: Modifiers,
144 time_ms: f64,
146 },
147 PointerUp {
149 id: u64,
151 pos: PointCss,
153 button: Button,
155 mods: Modifiers,
157 time_ms: f64,
159 },
160 PointerLeave,
162 Wheel {
164 pos: PointCss,
166 delta: WheelDelta,
168 mods: Modifiers,
170 },
171 Pinch {
173 phase: GesturePhase,
175 center: PointCss,
177 scale: f32,
179 },
180 Key {
182 key: Key,
184 pressed: bool,
186 mods: Modifiers,
188 },
189 DoubleClick {
191 pos: PointCss,
193 button: Button,
195 },
196}
197
198#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
200#[non_exhaustive]
201pub enum CursorIcon {
202 #[default]
204 Default,
205 Crosshair,
207 Grab,
209 Grabbing,
211 EwResize,
213 NsResize,
215 Pointer,
217 Move,
219}
220
221#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
223pub struct InputResult {
224 pub consumed: bool,
227 pub cursor: CursorIcon,
229}
230
231#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
233#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
234pub enum CrosshairMode {
235 #[default]
237 Normal,
238 Magnet,
240 Hidden,
242}
243
244const DRAG_THRESHOLD: f32 = 3.0;
246pub const KINETIC_TAU_MS: f64 = 325.0;
249pub const KINETIC_MIN_SPEED: f64 = 0.05;
251const VELOCITY_WINDOW_MS: f64 = 100.0;
253const RELEASE_PAUSE_MS: f64 = 50.0;
255const LINE_PX: f32 = 40.0;
257const WHEEL_ZOOM: f64 = 0.002;
259const AXIS_DRAG_ZOOM: f64 = 0.005;
261
262#[derive(Clone, Copy, Debug, PartialEq, Eq)]
264pub(crate) enum Region {
265 Plot(PaneId),
266 PriceAxis(PaneId),
267 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#[derive(Clone, Copy, Debug, Default)]
294pub struct VelocityTracker {
295 samples: [Sample; 8],
296 n_samples: usize,
297}
298
299impl VelocityTracker {
300 pub fn clear(&mut self) {
302 self.n_samples = 0;
303 }
304
305 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 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#[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 ResizingPanes {
361 id: u64,
362 upper: PaneId,
363 lower: PaneId,
364 top: f32,
365 bottom: f32,
366 },
367 EditingDrawing {
369 id: u64,
370 drawing: DrawingId,
371 part: HitPart,
372 start: PointPx,
373 pane: PaneId,
374 },
375}
376
377impl Drag {
378 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 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#[derive(Clone, Copy, Debug)]
401pub(crate) struct Interaction {
402 pub(crate) drag: Drag,
403 pub(crate) kinetic: Option<(f64, Option<f64>)>,
406 velocity: VelocityTracker,
407 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 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 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 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 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 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 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 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 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 pub fn crosshair_mode(&self) -> CrosshairMode {
737 self.input.crosshair
738 }
739
740 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 pub fn is_animating(&self) -> bool {
748 self.input.kinetic.is_some()
749 }
750
751 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 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 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 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 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 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 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 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 assert!(s.release_velocity(200.0).abs() < 1e-12);
1218 }
1219}