1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
//! Host-agnostic interaction tools: wheel zoom, drag pan, hover, home reset.
//!
//! [`Interactor`] owns a [`Figure`] and consumes [`Event`]s, mutating axes
//! limits through the same public API (`set_xlim`/`set_ylim`) a user would
//! call. It contains no DOM or backend types, so every behavior is testable
//! natively by synthesizing events.
//!
//! Pan and zoom operate in **scale-transformed space** (via each axes' data
//! scale), so log/symlog/asinh/logit axes pan and zoom the way the eye
//! expects — a fixed pixel drag shifts a fixed number of decades on a log
//! axis — with no per-scale special cases here.
use crate::figure::Figure;
use crate::figure::event::{Event, MouseButton};
/// Per-wheel-detent zoom factor: one line of scroll scales the view by 1.1.
const ZOOM_BASE: f64 = 1.1;
/// Clamp on the per-event zoom factor so a trackpad momentum burst cannot
/// teleport the view.
const ZOOM_FACTOR_RANGE: (f64, f64) = (0.5, 2.0);
/// What an event did, so the host knows whether to repaint.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Outcome {
/// Nothing changed; no repaint needed.
Unchanged,
/// Axes limits (or the canvas) changed; schedule a repaint.
NeedsRedraw,
/// The cursor is over axes `axes` at data coordinates `(x, y)`.
Hover {
/// Index of the hovered axes.
axes: usize,
/// Cursor x in data coordinates.
x: f64,
/// Cursor y in data coordinates.
y: f64,
},
}
/// One axes' explicit `(xlim, ylim)` limit pairs.
type AxesLimits = ((f64, f64), (f64, f64));
/// An in-progress left-button pan drag.
#[derive(Clone, Copy)]
struct Drag {
/// The axes being panned.
axes: usize,
/// The grabbed point in **scale-transformed** coordinates; kept under the
/// cursor for the duration of the drag.
anchor: (f64, f64),
}
/// Interaction state machine over an owned [`Figure`].
pub struct Interactor {
/// The figure being interacted with.
fig: Figure,
/// Per-axes `(xlim, ylim)` captured before the first limit-changing
/// interaction, restored by double-click.
home: Option<Vec<AxesLimits>>,
/// The active pan drag, if any.
drag: Option<Drag>,
/// Axes whose view the user has taken over by panning or zooming. While an
/// axes is held, a timeline's view tracks ([`seek`](Interactor::seek))
/// leave its limits alone; double-click hands the view back.
user_view: std::collections::HashSet<usize>,
}
impl Interactor {
/// Wrap `fig` for interaction.
#[must_use]
pub fn new(fig: Figure) -> Self {
Self {
fig,
home: None,
drag: None,
user_view: std::collections::HashSet::new(),
}
}
/// A shared reference to the wrapped figure (for rendering and readouts).
#[must_use]
pub fn figure(&self) -> &Figure {
&self.fig
}
/// A mutable reference to the wrapped figure.
///
/// The captured home limits are kept; if you restructure the axes, the
/// next double-click restores the limits captured before the change.
pub fn figure_mut(&mut self) -> &mut Figure {
&mut self.fig
}
/// Unwrap back into the figure.
#[must_use]
pub fn into_figure(self) -> Figure {
self.fig
}
/// Consume one event, returning what the host should do next.
pub fn handle(&mut self, ev: Event) -> Outcome {
match ev {
Event::MouseDown {
x,
y,
button: MouseButton::Left,
} => self.begin_pan(x, y),
Event::MouseDown { .. } => Outcome::Unchanged,
Event::MouseMove { x, y } => match self.drag {
Some(_) => self.continue_pan(x, y),
None => self.hover(x, y),
},
Event::MouseUp {
button: MouseButton::Left,
..
}
| Event::Leave => {
self.drag = None;
Outcome::Unchanged
}
Event::MouseUp { .. } => Outcome::Unchanged,
Event::Wheel { x, y, dy } => self.zoom(x, y, dy),
Event::DoubleClick { x, y } => self.go_home(x, y),
// The figure's size in inches is fixed; a host resize just needs a
// repaint at the (unchanged) figure size.
Event::Resize { .. } => Outcome::NeedsRedraw,
}
}
/// The cursor position in scale-transformed coordinates for `axes`,
/// **without** the inside-the-axes check (a captured drag may leave the
/// axes rectangle).
fn pixel_to_scaled(&self, axes: usize, px: f64, py: f64) -> Option<(f64, f64)> {
let ax = self.fig.axes().get(axes)?;
let (fig_w, fig_h) = self.fig.size_px();
let (_rect, td) = ax.pixel_rect_and_trans_data_in(
fig_w,
fig_h,
self.fig.xlim_override_for(axes),
self.fig.layout_rect_for(axes, fig_w, fig_h),
);
let inv = td.inverted()?;
Some(inv.transform_point((px, fig_h - py)))
}
/// The current effective limits of `axes` in scale-transformed space, as
/// `((sx_lo, sx_hi), (sy_lo, sy_hi))`.
///
/// Reads the *scale-limited* limits (the draw-time values), so stored
/// limits that sit outside the scale's domain — e.g. a log axis whose raw
/// limits went non-positive — are repaired before being transformed,
/// instead of mapping to non-finite scaled coordinates. Linked x-limits
/// (twins, [`sharex`](Figure::sharex)) resolve through their leader, the
/// same values the axes draws with.
fn scaled_limits(&self, axes: usize) -> Option<((f64, f64), (f64, f64))> {
let ax = self.fig.axes().get(axes)?;
let ((xlo, xhi), (ylo, yhi)) = ax.limits_with_override(self.fig.xlim_override_for(axes));
let t = ax.data_to_scaled();
let [sx_lo, sy_lo] = t.map_point(xlo, ylo);
let [sx_hi, sy_hi] = t.map_point(xhi, yhi);
Some(((sx_lo, sx_hi), (sy_lo, sy_hi)))
}
/// The axes whose stored x-limits actually drive `axes`' x mapping: its
/// link leader when one is set (twins, [`sharex`](Figure::sharex)),
/// otherwise itself. Writing x changes there keeps a linked group in
/// lockstep — the followers re-resolve from the leader at draw time.
fn x_link_target(&self, axes: usize) -> usize {
match self.fig.axes()[axes].xlim_link {
Some(leader) if leader != axes && leader < self.fig.axes().len() => leader,
_ => axes,
}
}
/// Apply scale-transformed limits back to `axes` as explicit data limits,
/// returning whether they were stored.
///
/// The inverse transform can saturate at the scale's domain edges — a
/// logit inverse rounding to exactly `0.0`/`1.0`, a log inverse
/// underflowing to `0.0` or overflowing to `inf` — so candidates are
/// rejected when non-finite and clamped to the scale's domain before
/// `set_xlim`/`set_ylim`. One extreme wheel or drag therefore cannot
/// poison the axes for every later interaction.
///
/// The x-limits are stored on the axes' link leader (see
/// [`Interactor::x_link_target`]); the y-limits always land on `axes`
/// itself, so linked groups zoom together in x while y stays per-axes.
fn set_scaled_limits(&mut self, axes: usize, sx: (f64, f64), sy: (f64, f64)) -> bool {
let x_target = self.x_link_target(axes);
let (xlim, ylim) = {
let ax = &self.fig.axes()[axes];
let t = ax.data_to_scaled();
let [xlo, ylo] = t.inverse_point(sx.0, sy.0);
let [xhi, yhi] = t.inverse_point(sx.1, sy.1);
if ![xlo, xhi, ylo, yhi].iter().all(|v| v.is_finite()) {
return false;
}
ax.clamp_limits_to_scale((xlo, xhi), (ylo, yhi))
};
if x_target != axes {
self.fig.axes_mut()[x_target].set_xlim(xlim.0, xlim.1);
} else {
self.fig.axes_mut()[axes].set_xlim(xlim.0, xlim.1);
}
self.fig.axes_mut()[axes].set_ylim(ylim.0, ylim.1);
// The user now owns this view (and the leader's x, when linked):
// timeline view tracks yield to it until double-click hands it back.
self.user_view.insert(axes);
self.user_view.insert(x_target);
true
}
/// Capture every axes' current effective limits as "home", once.
fn capture_home(&mut self) {
if self.home.is_none() {
self.home = Some(
self.fig
.axes()
.iter()
.map(|ax| ax.effective_limits())
.collect(),
);
}
}
fn begin_pan(&mut self, x: f64, y: f64) -> Outcome {
let Some(axes) = self.fig.axes_at(x, y) else {
return Outcome::Unchanged;
};
let Some(anchor) = self.pixel_to_scaled(axes, x, y) else {
return Outcome::Unchanged;
};
self.capture_home();
self.drag = Some(Drag { axes, anchor });
Outcome::Unchanged
}
fn continue_pan(&mut self, x: f64, y: f64) -> Outcome {
let Some(Drag { axes, anchor }) = self.drag else {
return Outcome::Unchanged;
};
let Some(under) = self.pixel_to_scaled(axes, x, y) else {
return Outcome::Unchanged;
};
let Some((sx, sy)) = self.scaled_limits(axes) else {
return Outcome::Unchanged;
};
// Shift limits so the grabbed point lands back under the cursor.
let (dx, dy) = (anchor.0 - under.0, anchor.1 - under.1);
if dx == 0.0 && dy == 0.0 {
return Outcome::Unchanged;
}
if self.set_scaled_limits(axes, (sx.0 + dx, sx.1 + dx), (sy.0 + dy, sy.1 + dy)) {
Outcome::NeedsRedraw
} else {
Outcome::Unchanged
}
}
fn zoom(&mut self, x: f64, y: f64, dy: f64) -> Outcome {
let Some(axes) = self.fig.axes_at(x, y) else {
return Outcome::Unchanged;
};
let Some((cx, cy)) = self.pixel_to_scaled(axes, x, y) else {
return Outcome::Unchanged;
};
let Some((sx, sy)) = self.scaled_limits(axes) else {
return Outcome::Unchanged;
};
let k = ZOOM_BASE
.powf(dy)
.clamp(ZOOM_FACTOR_RANGE.0, ZOOM_FACTOR_RANGE.1);
if k == 1.0 {
return Outcome::Unchanged;
}
self.capture_home();
// Scale each limit about the cursor's scaled coordinate, so the data
// point under the cursor stays under the cursor.
let nx = (cx - (cx - sx.0) * k, cx + (sx.1 - cx) * k);
let ny = (cy - (cy - sy.0) * k, cy + (sy.1 - cy) * k);
if self.set_scaled_limits(axes, nx, ny) {
Outcome::NeedsRedraw
} else {
Outcome::Unchanged
}
}
fn go_home(&mut self, x: f64, y: f64) -> Outcome {
let Some(axes) = self.fig.axes_at(x, y) else {
return Outcome::Unchanged;
};
let Some(limits) = self.home.as_ref().and_then(|h| h.get(axes).copied()) else {
return Outcome::Unchanged;
};
let ((xlo, xhi), (ylo, yhi)) = limits;
let ax = &mut self.fig.axes_mut()[axes];
ax.set_xlim(xlo, xhi);
ax.set_ylim(ylo, yhi);
// A linked axes draws its x from its leader: restore the leader's
// captured home too, so double-click resets the whole shared group.
let x_target = self.x_link_target(axes);
if x_target != axes {
if let Some(((lxlo, lxhi), _)) = self.home.as_ref().and_then(|h| h.get(x_target)) {
let (lxlo, lxhi) = (*lxlo, *lxhi);
self.fig.axes_mut()[x_target].set_xlim(lxlo, lxhi);
}
}
// Double-click hands the view back: an animated axes' camera tracks
// resume on the next seek.
self.user_view.remove(&axes);
self.user_view.remove(&x_target);
Outcome::NeedsRedraw
}
/// Advance the figure's animation to time `t`, preserving any view the
/// user has taken over.
///
/// Data tracks (line samples, scatter offsets, image data) always apply —
/// they are the animation's content. **View tracks (`xlim`/`ylim`) yield
/// to a user-held view**: once someone has panned or zoomed an axes, an
/// authored camera move fighting them every frame would make interaction
/// pointless, so the timeline's camera is suspended for that axes until
/// double-click hands the view back. This is the interactive counterpart
/// of `design/10` §5's data/view orthogonality.
///
/// # Errors
///
/// As [`Figure::seek`]: a track addressing a missing artist, or handing it
/// the wrong number of values.
#[cfg(feature = "portable")]
pub fn seek(&mut self, t: f64) -> Result<(), crate::portable::PortableError> {
self.holding_user_view(|fig| fig.seek(t))
}
/// Move control `index` to `value` under the same view policy as
/// [`Interactor::seek`]: controls may drive `xlim`/`ylim` exactly as
/// timelines may, and a view the user has taken over wins against both
/// through one code path (design/12 §4). Returns the position actually
/// applied, as [`Figure::set_control`] does.
///
/// # Errors
///
/// As [`Figure::set_control`].
#[cfg(feature = "portable")]
pub fn set_control(
&mut self,
index: usize,
value: f64,
) -> Result<f64, crate::portable::PortableError> {
self.holding_user_view(|fig| fig.set_control(index, value))
}
/// Run `f` and re-impose the user's limits on every axes they have taken
/// over — snapshot-and-restore rather than filtered evaluation, so the
/// track machinery keeps exactly one code path and the policy lives here,
/// next to the state that defines it.
#[cfg(feature = "portable")]
fn holding_user_view<R>(
&mut self,
f: impl FnOnce(&mut Figure) -> Result<R, crate::portable::PortableError>,
) -> Result<R, crate::portable::PortableError> {
let held: Vec<(usize, AxesLimits)> = self
.user_view
.iter()
.filter(|&&i| i < self.fig.axes().len())
.map(|&i| (i, self.fig.axes()[i].effective_limits()))
.collect();
let out = f(&mut self.fig)?;
for (i, (xlim, ylim)) in held {
let ax = &mut self.fig.axes_mut()[i];
ax.set_xlim(xlim.0, xlim.1);
ax.set_ylim(ylim.0, ylim.1);
}
Ok(out)
}
fn hover(&self, x: f64, y: f64) -> Outcome {
let Some(axes) = self.fig.axes_at(x, y) else {
return Outcome::Unchanged;
};
match self.fig.pixel_to_data(axes, x, y) {
Some((dx, dy)) => Outcome::Hover { axes, x: dx, y: dy },
None => Outcome::Unchanged,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A 4x3 in @ 100 dpi figure with one axes and a line, explicit limits.
fn fixture() -> Interactor {
let mut fig = Figure::new(4.0, 3.0);
let ax = fig.add_axes(0.1, 0.1, 0.8, 0.8);
ax.plot(&[0.0, 5.0, 10.0], &[0.0, 5.0, 10.0]);
ax.set_xlim(0.0, 10.0);
ax.set_ylim(0.0, 10.0);
Interactor::new(fig)
}
fn limits(it: &Interactor) -> ((f64, f64), (f64, f64)) {
it.figure().axes()[0].effective_limits()
}
fn assert_close(a: f64, b: f64, tol: f64, what: &str) {
assert!((a - b).abs() < tol, "{what}: expected {b}, got {a}");
}
#[test]
fn wheel_zoom_keeps_cursor_data_point_fixed() {
let mut it = fixture();
let (px, py) = (150.0, 120.0);
let before = it.figure().pixel_to_data(0, px, py).expect("inside axes");
assert_eq!(
it.handle(Event::Wheel {
x: px,
y: py,
dy: -1.0
}),
Outcome::NeedsRedraw
);
let after = it.figure().pixel_to_data(0, px, py).expect("still inside");
assert_close(after.0, before.0, 1e-9, "x under cursor");
assert_close(after.1, before.1, 1e-9, "y under cursor");
// And the view actually zoomed in (span shrank).
let ((xlo, xhi), _) = limits(&it);
assert!(xhi - xlo < 10.0, "zoom in must shrink the x span");
}
#[test]
fn wheel_zoom_on_log_axes_keeps_cursor_point_fixed() {
let mut fig = Figure::new(4.0, 3.0);
let ax = fig.add_axes(0.1, 0.1, 0.8, 0.8);
ax.set_xscale_log(10.0);
ax.plot(&[1.0, 10.0, 1000.0], &[0.0, 5.0, 10.0]);
ax.set_xlim(1.0, 1000.0);
ax.set_ylim(0.0, 10.0);
let mut it = Interactor::new(fig);
let (px, py) = (200.0, 150.0);
let before = it.figure().pixel_to_data(0, px, py).expect("inside axes");
it.handle(Event::Wheel {
x: px,
y: py,
dy: 2.0,
});
let after = it.figure().pixel_to_data(0, px, py).expect("still inside");
assert_close(
after.0,
before.0,
1e-9 * before.0.abs(),
"log x under cursor",
);
assert_close(after.1, before.1, 1e-9, "y under cursor");
// Limits stay positive on the log axis.
let ((xlo, _), _) = limits(&it);
assert!(xlo > 0.0, "log axis lower limit must stay positive");
}
#[test]
fn pan_roundtrip_restores_limits() {
let mut it = fixture();
let start = limits(&it);
it.handle(Event::MouseDown {
x: 200.0,
y: 150.0,
button: MouseButton::Left,
});
assert_eq!(
it.handle(Event::MouseMove { x: 240.0, y: 130.0 }),
Outcome::NeedsRedraw
);
it.handle(Event::MouseMove { x: 200.0, y: 150.0 });
it.handle(Event::MouseUp {
x: 200.0,
y: 150.0,
button: MouseButton::Left,
});
let end = limits(&it);
assert_close(end.0.0, start.0.0, 1e-9, "xlo");
assert_close(end.0.1, start.0.1, 1e-9, "xhi");
assert_close(end.1.0, start.1.0, 1e-9, "ylo");
assert_close(end.1.1, start.1.1, 1e-9, "yhi");
}
#[test]
fn pan_on_log_axis_shifts_decades_not_data_units() {
let mut fig = Figure::new(4.0, 3.0);
let ax = fig.add_axes(0.1, 0.1, 0.8, 0.8);
ax.set_xscale_log(10.0);
ax.plot(&[1.0, 10.0, 100.0], &[0.0, 1.0, 2.0]);
ax.set_xlim(1.0, 100.0);
ax.set_ylim(0.0, 2.0);
let mut it = Interactor::new(fig);
it.handle(Event::MouseDown {
x: 200.0,
y: 150.0,
button: MouseButton::Left,
});
it.handle(Event::MouseMove { x: 100.0, y: 150.0 });
// A pure-x pixel shift on a log axis multiplies both limits by the
// same factor: the ratio (decade span) is preserved.
let ((xlo, xhi), _) = limits(&it);
assert!(xlo > 0.0 && xhi > xlo);
assert_close(xhi / xlo, 100.0, 1e-6, "decade span preserved");
assert!(xlo > 1.0, "dragging left pans toward larger x");
}
#[test]
fn double_click_restores_home_after_zoom_and_pan() {
let mut it = fixture();
let home = limits(&it);
it.handle(Event::Wheel {
x: 150.0,
y: 120.0,
dy: -3.0,
});
it.handle(Event::MouseDown {
x: 200.0,
y: 150.0,
button: MouseButton::Left,
});
it.handle(Event::MouseMove { x: 260.0, y: 90.0 });
it.handle(Event::MouseUp {
x: 260.0,
y: 90.0,
button: MouseButton::Left,
});
assert_ne!(limits(&it), home, "interaction must have changed the view");
assert_eq!(
it.handle(Event::DoubleClick { x: 200.0, y: 150.0 }),
Outcome::NeedsRedraw
);
let end = limits(&it);
assert_close(end.0.0, home.0.0, 1e-9, "xlo home");
assert_close(end.0.1, home.0.1, 1e-9, "xhi home");
assert_close(end.1.0, home.1.0, 1e-9, "ylo home");
assert_close(end.1.1, home.1.1, 1e-9, "yhi home");
}
#[test]
fn events_outside_all_axes_are_unchanged() {
let mut it = fixture();
let start = limits(&it);
// (5, 5) is in the figure margin, outside the axes rect.
assert_eq!(
it.handle(Event::Wheel {
x: 5.0,
y: 5.0,
dy: -1.0
}),
Outcome::Unchanged
);
assert_eq!(
it.handle(Event::MouseDown {
x: 5.0,
y: 5.0,
button: MouseButton::Left
}),
Outcome::Unchanged
);
assert_eq!(
it.handle(Event::MouseMove { x: 6.0, y: 6.0 }),
Outcome::Unchanged
);
assert_eq!(
it.handle(Event::DoubleClick { x: 5.0, y: 5.0 }),
Outcome::Unchanged
);
assert_eq!(limits(&it), start);
}
#[test]
fn hover_reports_data_coordinates() {
let mut it = fixture();
let (px, py) = it
.figure()
.data_to_pixel(0, 5.0, 5.0)
.expect("axes 0 exists");
match it.handle(Event::MouseMove { x: px, y: py }) {
Outcome::Hover { axes, x, y } => {
assert_eq!(axes, 0);
assert_close(x, 5.0, 1e-9, "hover x");
assert_close(y, 5.0, 1e-9, "hover y");
}
other => panic!("expected Hover, got {other:?}"),
}
}
#[test]
fn repeated_extreme_logit_interaction_keeps_limits_in_domain() {
let mut fig = Figure::new(4.0, 3.0);
let ax = fig.add_axes(0.1, 0.1, 0.8, 0.8);
let x: Vec<f64> = (0..50).map(|i| f64::from(i) * 0.2 - 5.0).collect();
let p: Vec<f64> = x.iter().map(|v| 1.0 / (1.0 + (-v).exp())).collect();
ax.logity(&x, &p);
ax.set_xlim(-5.0, 5.0);
ax.set_ylim(0.001, 0.999);
let mut it = Interactor::new(fig);
// Hammer the view: repeated max-rate zoom-outs toward the saturating
// tails, interleaved with hard pans up and down.
for round in 0..60 {
it.handle(Event::Wheel {
x: 200.0,
y: 40.0,
dy: 8.0,
});
it.handle(Event::MouseDown {
x: 200.0,
y: 150.0,
button: MouseButton::Left,
});
let target_y = if round % 2 == 0 { -400.0 } else { 700.0 };
it.handle(Event::MouseMove {
x: 200.0,
y: target_y,
});
it.handle(Event::MouseUp {
x: 200.0,
y: target_y,
button: MouseButton::Left,
});
let (_, (ylo, yhi)) = limits(&it);
assert!(
ylo.is_finite() && yhi.is_finite(),
"round {round}: logit limits went non-finite: ({ylo}, {yhi})"
);
assert!(
ylo > 0.0 && yhi < 1.0 && ylo < yhi,
"round {round}: logit limits left (0, 1): ({ylo}, {yhi})"
);
}
// The view must still respond to interaction afterwards.
assert_eq!(
it.handle(Event::Wheel {
x: 200.0,
y: 150.0,
dy: -1.0
}),
Outcome::NeedsRedraw
);
}
#[test]
fn repeated_extreme_log_interaction_keeps_limits_positive() {
let mut fig = Figure::new(4.0, 3.0);
let ax = fig.add_axes(0.1, 0.1, 0.8, 0.8);
ax.set_xscale_log(10.0);
ax.plot(&[1.0, 10.0, 100.0], &[0.0, 1.0, 2.0]);
ax.set_xlim(1.0, 100.0);
ax.set_ylim(0.0, 2.0);
let mut it = Interactor::new(fig);
for round in 0..80 {
// Zoom out hard at the left edge, then drag far right — both push
// the lower limit toward log-underflow territory.
it.handle(Event::Wheel {
x: 45.0,
y: 150.0,
dy: 8.0,
});
it.handle(Event::MouseDown {
x: 100.0,
y: 150.0,
button: MouseButton::Left,
});
it.handle(Event::MouseMove { x: 900.0, y: 150.0 });
it.handle(Event::MouseUp {
x: 900.0,
y: 150.0,
button: MouseButton::Left,
});
let ((xlo, xhi), _) = limits(&it);
assert!(
xlo.is_finite() && xhi.is_finite(),
"round {round}: log limits went non-finite: ({xlo}, {xhi})"
);
assert!(
xlo > 0.0 && xlo < xhi,
"round {round}: log limits left the domain: ({xlo}, {xhi})"
);
}
assert_eq!(
it.handle(Event::Wheel {
x: 200.0,
y: 150.0,
dy: -1.0
}),
Outcome::NeedsRedraw
);
}
/// A 4x3 in figure with two stacked axes sharing x: leader on top
/// (index 0), follower below (index 1). Event rows: top ≈ (200, 90),
/// bottom ≈ (200, 220).
fn sharex_fixture() -> Interactor {
let mut fig = Figure::new(4.0, 3.0);
let top = fig.add_axes(0.1, 0.55, 0.8, 0.35);
top.plot(&[0.0, 5.0, 10.0], &[0.0, 5.0, 10.0]);
top.set_xlim(0.0, 10.0);
top.set_ylim(0.0, 10.0);
let bottom = fig.add_axes(0.1, 0.1, 0.8, 0.35);
bottom.plot(&[0.0, 5.0, 10.0], &[20.0, 25.0, 30.0]);
bottom.set_xlim(0.0, 10.0);
bottom.set_ylim(20.0, 30.0);
fig.sharex(1, 0);
Interactor::new(fig)
}
#[test]
fn sharex_zoom_on_the_follower_moves_the_shared_x() {
let mut it = sharex_fixture();
// Wheel in over the bottom (follower) axes.
assert_eq!(
it.handle(Event::Wheel {
x: 200.0,
y: 220.0,
dy: -2.0
}),
Outcome::NeedsRedraw
);
// The shared x (stored on the leader) shrank...
let ((lxlo, lxhi), (lylo, lyhi)) = it.figure().axes()[0].effective_limits();
assert!(lxhi - lxlo < 10.0, "leader x must zoom: ({lxlo}, {lxhi})");
// ...the leader's y is untouched...
assert_close(lylo, 0.0, 1e-9, "leader ylo");
assert_close(lyhi, 10.0, 1e-9, "leader yhi");
// ...and only the follower's y zoomed.
let (_, (fylo, fyhi)) = it.figure().axes()[1].effective_limits();
assert!(fyhi - fylo < 10.0, "follower y must zoom: ({fylo}, {fyhi})");
// The follower draws with the leader's x.
let over = it.figure().xlim_override_for(1).expect("linked");
assert_close(over.0, lxlo, 1e-9, "follower drawn xlo");
assert_close(over.1, lxhi, 1e-9, "follower drawn xhi");
}
#[test]
fn sharex_zoom_on_the_leader_carries_the_follower() {
let mut it = sharex_fixture();
it.handle(Event::Wheel {
x: 200.0,
y: 90.0,
dy: -2.0,
});
let ((lxlo, lxhi), _) = it.figure().axes()[0].effective_limits();
assert!(lxhi - lxlo < 10.0, "leader x must zoom");
let over = it.figure().xlim_override_for(1).expect("linked");
assert_close(over.0, lxlo, 1e-9, "follower follows xlo");
assert_close(over.1, lxhi, 1e-9, "follower follows xhi");
}
#[test]
fn sharex_double_click_on_the_follower_restores_the_group() {
let mut it = sharex_fixture();
it.handle(Event::Wheel {
x: 200.0,
y: 220.0,
dy: -3.0,
});
let ((zxlo, zxhi), _) = it.figure().axes()[0].effective_limits();
assert!(zxhi - zxlo < 10.0, "precondition: zoomed in");
it.handle(Event::DoubleClick { x: 200.0, y: 220.0 });
let ((xlo, xhi), _) = it.figure().axes()[0].effective_limits();
assert_close(xlo, 0.0, 1e-9, "shared x home lo");
assert_close(xhi, 10.0, 1e-9, "shared x home hi");
let (_, (fylo, fyhi)) = it.figure().axes()[1].effective_limits();
assert_close(fylo, 20.0, 1e-9, "follower y home lo");
assert_close(fyhi, 30.0, 1e-9, "follower y home hi");
}
#[test]
fn drag_survives_leaving_the_axes_rect() {
let mut it = fixture();
it.handle(Event::MouseDown {
x: 100.0,
y: 150.0,
button: MouseButton::Left,
});
// Drag far outside the axes (pointer capture keeps events flowing).
assert_eq!(
it.handle(Event::MouseMove { x: 500.0, y: 150.0 }),
Outcome::NeedsRedraw
);
// Leave cancels the drag; further moves are hover/unchanged.
it.handle(Event::Leave);
assert_eq!(
it.handle(Event::MouseMove { x: 500.0, y: 150.0 }),
Outcome::Unchanged
);
}
}