Skip to main content

oa/plot/
view.rs

1//! `oa::plot::FigureView` — interactive `ViewerLiveSource` for a retained
2//! `Figure`.
3//!
4//! The view borrows only the bounded input/UI capabilities every
5//! `ViewerLiveSource` receives:
6//!
7//! - wheel scroll zooms about the pointer's data position;
8//! - left-drag pans the axes under the press;
9//! - Shift+left-drag box-zooms into the selection;
10//! - double-click or `R` restores the limits recorded before interaction;
11//! - clicking a legend row toggles that artist's visibility;
12//! - the crosshair reports data coordinates and snaps a tooltip to the
13//!   nearest recorded sample.
14//!
15//! View transitions animate over `Ui`'s motion speed.  All view math runs in
16//! display space — logarithmic axes pan and zoom on transformed values and
17//! write back through the axis scale.
18
19use crate::input::{InputEvent, InputEventKind, Key};
20use crate::ui::{PixelRect, TextLayoutConfig, Ui};
21use crate::viewer::{ViewerLiveCapabilities, ViewerLiveSource};
22use crate::{Color, Error, Result, Runtime};
23
24use super::Figure;
25use super::axes::{ArtistKind, legend_row_rect, scale_value, unscale_value};
26
27/// Zoom multiplier applied per wheel step.
28const SCROLL_ZOOM_STEP: f32 = 1.15;
29/// Minimum box-zoom selection edge before the zoom applies.
30const BOX_ZOOM_MIN_PX: f32 = 4.0;
31/// Nearest-sample tooltip pick radius, in pixels.
32const TOOLTIP_PICK_PX: f32 = 24.0;
33/// Base view-transition length in milliseconds, scaled by `Ui` motion speed.
34const VIEW_ANIM_MS: f32 = 160.0;
35
36/// Left-drag pan state captured at pointer press.
37struct DragState {
38	/// Flattened `(row * cols + col)` cell index under the press.
39	cell: usize,
40	press: [f32; 2],
41	/// Effective display-space limits when the drag started.
42	limits: [f32; 4],
43}
44
45/// In-flight animated view transition for one cell.
46struct ViewAnim {
47	from: [f32; 4],
48	to: [f32; 4],
49	elapsed_ms: f32,
50	duration_ms: f32,
51	/// Restore automatic data limits once the transition lands.
52	clear_on_finish: bool,
53}
54
55/// Shift+drag box-zoom selection in progress.
56struct BoxSelect {
57	cell: usize,
58	start: [f32; 2],
59	current: [f32; 2],
60}
61
62/// Serializable snapshot of a `FigureView`'s per-axes view overrides.
63///
64/// Limits live in display space (post-scale); `restore` writes them back
65/// through the axes' scale transforms.  The vector is flattened row-major
66/// over the figure grid.
67#[derive(Clone, Debug, Default)]
68pub struct FigureViewState {
69	/// Per-cell view override; `None` leaves the recorded limits.
70	pub limits: Vec<Option<[f32; 4]>>,
71}
72
73/// Interactive `Figure` presentation through `Viewer` live mode.
74///
75/// Attach with `Viewer::set_live_source`, which switches the viewer to live
76/// mode; the figure keeps its recorded theme and artists while the view owns
77/// only per-axes limit overrides.
78pub struct FigureView {
79	figure: Figure,
80	/// Display-space limits recorded on each axes before interaction, so `R`
81	/// restores the caller's view instead of always auto-fitting.
82	base_limits: Vec<Option<[f32; 4]>>,
83	/// Active per-axes view overrides in display space; `None` leaves the
84	/// recorded limits.
85	view_limits: Vec<Option<[f32; 4]>>,
86	view_anims: Vec<Option<ViewAnim>>,
87	drag: Option<DragState>,
88	box_select: Option<BoxSelect>,
89	/// Hovered legend entry, as `(cell, drawn row, artist index)`.
90	legend_hover: Option<(usize, usize, usize)>,
91	pointer: [f32; 2],
92	pointer_valid: bool,
93	scroll_pos: [f32; 2],
94	scroll_delta: f32,
95	reset_pending: bool,
96	extent: [u32; 2],
97	/// UI-space origin of the last rendered frame; `[0, 0]` when rendered
98	/// full-window. Hit-testing and overlays offset by this origin so pointer
99	/// coordinates stay in UI space.
100	origin: [i32; 2],
101	/// Pane identity used when hosted as a `WorkspaceItem`.
102	name: String,
103	show_crosshair: bool,
104	/// Cached transition duration resolved from `Ui`'s motion speed.
105	motion_ms: f32,
106}
107
108impl FigureView {
109	/// Wrap `figure` for interactive presentation.
110	pub fn new(figure: Figure) -> Self {
111		let mut figure = figure;
112		let rows = figure.rows().max(1);
113		let cols = figure.cols().max(1);
114		let mut base_limits = Vec::with_capacity((rows * cols) as usize);
115		for row in 0..rows {
116			for col in 0..cols {
117				let axes = figure.ax(row, col);
118				base_limits.push(
119					axes
120						.explicit_limits()
121						.map(|_| axes.scaled_limits())
122						.map(|l| [l.x_min, l.x_max, l.y_min, l.y_max]),
123				);
124			}
125		}
126		let cells = base_limits.len();
127		Self {
128			figure,
129			base_limits,
130			view_limits: vec![None; cells],
131			view_anims: (0..cells).map(|_| None).collect(),
132			drag: None,
133			box_select: None,
134			legend_hover: None,
135			pointer: [0.0; 2],
136			pointer_valid: false,
137			scroll_pos: [0.0; 2],
138			scroll_delta: 0.0,
139			reset_pending: false,
140			extent: [0; 2],
141			origin: [0; 2],
142			name: String::new(),
143			show_crosshair: true,
144			motion_ms: VIEW_ANIM_MS,
145		}
146	}
147
148	/// The wrapped figure.
149	pub fn figure(&self) -> &Figure {
150		&self.figure
151	}
152
153	/// Mutable figure access for streaming series updates between frames.
154	///
155	/// Recorded `limits` only take effect while the axes has no active view
156	/// override; `R` restores the limits present at attach time.
157	pub fn figure_mut(&mut self) -> &mut Figure {
158		&mut self.figure
159	}
160
161	/// Toggle the pointer crosshair and data-coordinate readout (default on).
162	pub fn crosshair(&mut self, visible: bool) {
163		self.show_crosshair = visible;
164	}
165
166	/// Set the pane identity shown when the view is hosted as a
167	/// `WorkspaceItem` (tab id and label).
168	pub fn set_name(&mut self, name: impl Into<String>) {
169		self.name = name.into();
170	}
171
172	/// The pane identity assigned by `set_name` (empty until set).
173	pub fn name(&self) -> &str {
174		&self.name
175	}
176
177	/// Render the figure into `rect` of the current `Ui` frame instead of
178	/// filling the window — the `WorkspaceItem` pane path.
179	pub fn render_at(&mut self, ui: &mut Ui<'_>, rect: PixelRect) -> Result<()> {
180		if rect.w == 0 || rect.h == 0 {
181			return Ok(());
182		}
183		self.extent = [rect.w, rect.h];
184		self.origin = [rect.x, rect.y];
185		self.motion_ms = ui.motion_speed().duration_ms(VIEW_ANIM_MS);
186		self.apply_interactions();
187		self.apply_legend_highlight();
188		self.figure.render_frame_at(rect, ui)?;
189		self.render_overlay(ui, rect.w, rect.h)?;
190		Ok(())
191	}
192
193	/// Restore every axes to the limits recorded at attach time.
194	pub fn reset_view(&mut self) {
195		self.reset_pending = true;
196	}
197
198	/// Snapshot the active view overrides for later `restore`.
199	pub fn state(&self) -> FigureViewState {
200		FigureViewState {
201			limits: self.view_limits.clone(),
202		}
203	}
204
205	/// Restore a snapshot taken by `state`, dropping in-flight transitions.
206	pub fn restore(&mut self, state: &FigureViewState) {
207		for (cell, limits) in state.limits.iter().enumerate() {
208			if cell >= self.cell_count() {
209				break;
210			}
211			self.view_limits[cell] = *limits;
212			self.view_anims[cell] = None;
213		}
214	}
215
216	// ── Interaction helpers ─────────────────────────────────────────────────
217
218	fn cell_count(&self) -> usize {
219		self.base_limits.len()
220	}
221
222	fn cols(&self) -> usize {
223		self.figure.cols().max(1) as usize
224	}
225
226	/// Flattened index of the data viewport under a pointer, if any.
227	fn cell_at(&self, px: f32, py: f32) -> Option<usize> {
228		let [w, h] = self.extent;
229		if w == 0 || h == 0 {
230			return None;
231		}
232		(0..self.cell_count()).find(|&cell| self.plot_rect(cell).contains(px, py))
233	}
234
235	fn cell_rect(&self, cell: usize) -> PixelRect {
236		let (row, col) = (cell / self.cols(), cell % self.cols());
237		let rect = self
238			.figure
239			.cell_rect(row as i32, col as i32, self.extent[0], self.extent[1]);
240		PixelRect::new(
241			rect.x + self.origin[0],
242			rect.y + self.origin[1],
243			rect.w.max(0) as u32,
244			rect.h.max(0) as u32,
245		)
246	}
247
248	/// Data viewport with the label and colorbar gutters excluded.
249	fn plot_rect(&self, cell: usize) -> PixelRect {
250		self.figure.axes()[cell].layout(self.cell_rect(cell)).plot
251	}
252
253	/// Display-space limits a cell would show without a view override.
254	fn axes_limits(&self, cell: usize) -> [f32; 4] {
255		let limits = self.figure.axes()[cell].scaled_limits();
256		[limits.x_min, limits.x_max, limits.y_min, limits.y_max]
257	}
258
259	/// Effective display-space limits for a cell: override, else recorded.
260	fn effective_limits(&self, cell: usize) -> [f32; 4] {
261		self
262			.view_limits
263			.get(cell)
264			.copied()
265			.flatten()
266			.unwrap_or_else(|| self.axes_limits(cell))
267	}
268
269	/// Start an animated transition toward `target` display-space limits.
270	///
271	/// Instant under `MotionSpeed::Instant`; a zero-duration transition just
272	/// writes the override (and the optional auto-restore) directly.
273	fn animate_to(&mut self, cell: usize, target: [f32; 4], clear_on_finish: bool) {
274		if !target.iter().all(|v| v.is_finite()) || target[0] >= target[1] || target[2] >= target[3] {
275			return;
276		}
277		if self.motion_ms <= 0.0 {
278			self.view_anims[cell] = None;
279			if clear_on_finish {
280				self.view_limits[cell] = None;
281				let (row, col) = (cell / self.cols(), cell % self.cols());
282				self.figure.ax(row as i32, col as i32).auto_limits();
283			} else {
284				self.view_limits[cell] = Some(target);
285			}
286			return;
287		}
288		let from = self.effective_limits(cell);
289		self.view_limits[cell] = Some(from);
290		self.view_anims[cell] = Some(ViewAnim {
291			from,
292			to: target,
293			elapsed_ms: 0.0,
294			duration_ms: self.motion_ms,
295			clear_on_finish,
296		});
297	}
298
299	/// Legend row hit-test — returns `(drawn row, artist index, hidden)`.
300	fn legend_hit(&self, cell: usize, px: f32, py: f32) -> Option<(usize, usize, bool)> {
301		let axes = &self.figure.axes()[cell];
302		if !axes.cmds.show_legend {
303			return None;
304		}
305		let area = self.plot_rect(cell);
306		let palette = self.figure.config().theme.ui_style().data_palette;
307		for entry in axes.legend_entries(&palette) {
308			if entry.row == usize::MAX {
309				continue;
310			}
311			if legend_row_rect(area, entry.row).contains(px, py) {
312				return Some((entry.row, entry.artist, entry.hidden));
313			}
314		}
315		None
316	}
317
318	/// Write the legend-hover series emphasis into every axes. The flag lives
319	/// on `Axes`, so each frame clears it before setting the hovered cell's.
320	fn apply_legend_highlight(&mut self) {
321		for cell in 0..self.cell_count() {
322			let (row, col) = (cell / self.cols(), cell % self.cols());
323			let artist = match self.legend_hover {
324				Some((hover, _, artist)) if hover == cell => Some(artist),
325				_ => None,
326			};
327			self
328				.figure
329				.ax(row as i32, col as i32)
330				.set_series_highlight(artist);
331		}
332	}
333
334	/// Apply pending scroll/reset input, then write view overrides into the
335	/// figure's axes (unscaled back into recorded data limits).
336	fn apply_interactions(&mut self) {
337		if self.reset_pending {
338			self.reset_pending = false;
339			for cell in 0..self.cell_count() {
340				match self.base_limits[cell] {
341					Some(limits) => self.animate_to(cell, limits, false),
342					None => {
343						let target = self.axes_limits(cell);
344						self.animate_to(cell, target, true);
345					}
346				}
347			}
348		}
349		if self.scroll_delta != 0.0 {
350			let steps = self.scroll_delta;
351			self.scroll_delta = 0.0;
352			if let Some(cell) = self.cell_at(self.scroll_pos[0], self.scroll_pos[1]) {
353				let rect = self.plot_rect(cell);
354				let limits = self.effective_limits(cell);
355				self.animate_to(
356					cell,
357					zoom_limits(limits, rect, self.scroll_pos, steps),
358					false,
359				);
360			}
361		}
362		for cell in 0..self.cell_count() {
363			if let Some(limits) = self.view_limits[cell] {
364				let (row, col) = (cell / self.cols(), cell % self.cols());
365				let axes = self.figure.ax(row as i32, col as i32);
366				let (x_scale, y_scale) = (axes.cmds.x_scale, axes.cmds.y_scale);
367				axes.limits(
368					unscale_value(limits[0], x_scale),
369					unscale_value(limits[1], x_scale),
370					unscale_value(limits[2], y_scale),
371					unscale_value(limits[3], y_scale),
372				);
373			}
374		}
375	}
376
377	/// Nearest recorded sample to the pointer, in pixel space.
378	///
379	/// Only host-backed line and scatter artists participate — a
380	/// device-resident series has no host samples to inspect.  Returns the
381	/// resolved color, raw data value, and screen position of the hit.
382	fn nearest_sample(
383		&self,
384		cell: usize,
385		area: PixelRect,
386		limits: [f32; 4],
387		px: f32,
388		py: f32,
389	) -> Option<(String, Color, f32, f32, f32, f32)> {
390		let axes = &self.figure.axes()[cell];
391		let (x_scale, y_scale) = (axes.cmds.x_scale, axes.cmds.y_scale);
392		let palette = self.figure.config().theme.ui_style().data_palette;
393		let x_span = (limits[1] - limits[0]).max(f32::EPSILON);
394		let y_span = (limits[3] - limits[2]).max(f32::EPSILON);
395		let map = |x: f32, y: f32| -> Option<[f32; 2]> {
396			let sx = scale_value(x, x_scale);
397			let sy = scale_value(y, y_scale);
398			if !sx.is_finite() || !sy.is_finite() {
399				return None;
400			}
401			Some([
402				area.x as f32 + (sx - limits[0]) / x_span * area.w.saturating_sub(1) as f32,
403				area.y as f32 + (1.0 - (sy - limits[2]) / y_span) * area.h.saturating_sub(1) as f32,
404			])
405		};
406		let (mut line, mut scatter, mut bar, mut matrix, mut stream, mut band, mut bx) =
407			(0usize, 0usize, 0usize, 0usize, 0usize, 0usize, 0usize);
408		let mut palette_idx = 0usize;
409		let mut best: Option<(String, Color, f32, f32, f32, f32, f32)> = None;
410		for kind in &axes.cmds.artists {
411			let (samples, label, color, hidden): (&dyn SeriesPoints, &str, Color, bool) = match kind {
412				ArtistKind::Line => {
413					let Some(cmd) = axes.cmds.lines.get(line) else {
414						continue;
415					};
416					line += 1;
417					(cmd, &cmd.style.label, cmd.style.color, cmd.style.hidden)
418				}
419				ArtistKind::Scatter => {
420					let Some(cmd) = axes.cmds.scatters.get(scatter) else {
421						continue;
422					};
423					scatter += 1;
424					(cmd, &cmd.style.label, cmd.style.color, cmd.style.hidden)
425				}
426				ArtistKind::Bar => {
427					let Some(cmd) = axes.cmds.bars.get(bar) else {
428						continue;
429					};
430					bar += 1;
431					if cmd.style.color.a == 0.0 {
432						palette_idx += 1;
433					}
434					continue;
435				}
436				ArtistKind::LineMatrix => {
437					let Some(cmd) = axes.cmds.line_matrices.get(matrix) else {
438						continue;
439					};
440					matrix += 1;
441					if cmd.style.color.a == 0.0 {
442						palette_idx += 1;
443					}
444					continue;
445				}
446				ArtistKind::Stream => {
447					let Some(cmd) = axes.cmds.streams.get(stream) else {
448						continue;
449					};
450					stream += 1;
451					(cmd, &cmd.style.label, cmd.style.color, cmd.style.hidden)
452				}
453				ArtistKind::Band => {
454					let Some(cmd) = axes.cmds.bands.get(band) else {
455						continue;
456					};
457					band += 1;
458					if cmd.style.color.a == 0.0 {
459						palette_idx += 1;
460					}
461					continue;
462				}
463				ArtistKind::BoxPlot => {
464					let Some(cmd) = axes.cmds.boxes.get(bx) else {
465						continue;
466					};
467					bx += 1;
468					if cmd.style.color.a == 0.0 {
469						palette_idx += 1;
470					}
471					continue;
472				}
473			};
474			let color = if color.a == 0.0 {
475				let resolved = palette[palette_idx % palette.len()];
476				palette_idx += 1;
477				resolved
478			} else {
479				color
480			};
481			if hidden {
482				continue;
483			}
484			for index in 0..samples.len() {
485				let (x, y) = samples.point(index);
486				let Some(point) = map(x, y) else {
487					continue;
488				};
489				let dx = point[0] - px;
490				let dy = point[1] - py;
491				let dist = dx * dx + dy * dy;
492				let better = best.as_ref().is_none_or(|hit| dist < hit.6);
493				if better {
494					best = Some((label.to_owned(), color, x, y, point[0], point[1], dist));
495				}
496			}
497		}
498		best
499			.filter(|hit| hit.6 <= TOOLTIP_PICK_PX * TOOLTIP_PICK_PX)
500			.map(|(label, color, x, y, sx, sy, _)| (label, color, x, y, sx, sy))
501	}
502
503	/// Crosshair, nearest-sample tooltip, legend hover, and box-zoom overlay.
504	fn render_overlay(&mut self, ui: &mut Ui<'_>, w: u32, h: u32) -> Result<()> {
505		let style = self.figure.config().theme.ui_style();
506		let full = PixelRect::new(self.origin[0], self.origin[1], w, h);
507		let label_cfg = TextLayoutConfig {
508			size: 10.0,
509			..Default::default()
510		};
511
512		// Box-zoom selection rectangle.
513		if let Some(select) = &self.box_select {
514			let rect = selection_rect(select.start, select.current);
515			let accent = Color::new(style.accent.r, style.accent.g, style.accent.b, 0.12);
516			ui.rect_raw(rect, accent, full, 0.0);
517			ui.rect_outline_raw(rect, style.accent, 1, full);
518		}
519
520		// Hovered legend row highlight.
521		if let Some((cell, row, _)) = self.legend_hover {
522			let area = self.plot_rect(cell);
523			let band = legend_row_rect(area, row);
524			let hover = Color::new(style.text.r, style.text.g, style.text.b, 0.08);
525			ui.rect_raw(band, hover, self.cell_rect(cell), 0.0);
526		}
527
528		if !self.show_crosshair || !self.pointer_valid {
529			return Ok(());
530		}
531		let Some(cell) = self.cell_at(self.pointer[0], self.pointer[1]) else {
532			return Ok(());
533		};
534		let area = self.plot_rect(cell);
535		let limits = self.effective_limits(cell);
536		let axes = &self.figure.axes()[cell];
537		let (x_scale, y_scale) = (axes.cmds.x_scale, axes.cmds.y_scale);
538		let x_span = (limits[1] - limits[0]).max(f32::EPSILON);
539		let y_span = (limits[3] - limits[2]).max(f32::EPSILON);
540		let px = self.pointer[0].clamp(
541			area.x as f32,
542			(area.x + area.w.saturating_sub(1) as i32) as f32,
543		);
544		let py = self.pointer[1].clamp(
545			area.y as f32,
546			(area.y + area.h.saturating_sub(1) as i32) as f32,
547		);
548		let data_x = limits[0] + (px - area.x as f32) / area.w.max(1) as f32 * x_span;
549		let data_y = limits[3] - (py - area.y as f32) / area.h.max(1) as f32 * y_span;
550
551		let crosshair = Color::new(style.accent.r, style.accent.g, style.accent.b, 0.65);
552		let right = (area.x + area.w as i32) as f32;
553		let bottom = (area.y + area.h as i32) as f32;
554		ui.line_at([px, area.y as f32], [px, bottom], crosshair, 1.0, area)?;
555		ui.line_at([area.x as f32, py], [right, py], crosshair, 1.0, area)?;
556
557		if let Some((label, color, raw_x, raw_y, sx, sy)) =
558			self.nearest_sample(cell, area, limits, px, py)
559		{
560			ui.line_at([sx, sy], [sx, sy], color, 9.0, area)?;
561			let name = if label.is_empty() {
562				"series".to_owned()
563			} else {
564				label
565			};
566			ui.text_at(
567				&format!("{name} ({raw_x:.4}, {raw_y:.4})"),
568				[px + 8.0, py - 4.0],
569				label_cfg,
570				style.text,
571				full,
572			)?;
573		} else {
574			ui.text_at(
575				&format!(
576					"{:.4}, {:.4}",
577					unscale_value(data_x, x_scale),
578					unscale_value(data_y, y_scale),
579				),
580				[px + 8.0, py - 4.0],
581				label_cfg,
582				style.text,
583				full,
584			)?;
585		}
586		Ok(())
587	}
588}
589
590/// Point access shared by line and scatter commands during hit-testing.
591trait SeriesPoints {
592	fn len(&self) -> usize;
593	fn point(&self, index: usize) -> (f32, f32);
594}
595
596impl SeriesPoints for super::axes::LineCmd {
597	fn len(&self) -> usize {
598		self.x.len()
599	}
600	fn point(&self, index: usize) -> (f32, f32) {
601		(self.x[index], self.y[index])
602	}
603}
604
605impl SeriesPoints for super::axes::StreamCmd {
606	fn len(&self) -> usize {
607		self.len
608	}
609	fn point(&self, index: usize) -> (f32, f32) {
610		let capacity = self.values.len();
611		(index as f32, self.values[(self.head + index) % capacity])
612	}
613}
614
615impl SeriesPoints for super::axes::ScatterCmd {
616	fn len(&self) -> usize {
617		self.x.len()
618	}
619	fn point(&self, index: usize) -> (f32, f32) {
620		(self.x[index], self.y[index])
621	}
622}
623
624/// Zoom `limits` about the pointer's data position by `steps` wheel ticks.
625fn zoom_limits(limits: [f32; 4], rect: PixelRect, pos: [f32; 2], steps: f32) -> [f32; 4] {
626	// Positive scroll (up) shrinks the span — zoom in.
627	let factor = SCROLL_ZOOM_STEP.powf(-steps);
628	let w = rect.w.max(1) as f32;
629	let h = rect.h.max(1) as f32;
630	let fx = ((pos[0] - rect.x as f32) / w).clamp(0.0, 1.0);
631	// Data y increases upward; screen y increases downward.
632	let fy = 1.0 - ((pos[1] - rect.y as f32) / h).clamp(0.0, 1.0);
633	let [x_min, x_max, y_min, y_max] = limits;
634	let anchor_x = x_min + (x_max - x_min) * fx;
635	let anchor_y = y_min + (y_max - y_min) * fy;
636	let x_span = (x_max - x_min) * factor;
637	let y_span = (y_max - y_min) * factor;
638	[
639		anchor_x - x_span * fx,
640		anchor_x + x_span * (1.0 - fx),
641		anchor_y - y_span * fy,
642		anchor_y + y_span * (1.0 - fy),
643	]
644}
645
646/// Pan `limits` by the pixel delta between press and current pointer.
647fn pan_limits(limits: [f32; 4], rect: PixelRect, press: [f32; 2], pos: [f32; 2]) -> [f32; 4] {
648	let dx = (pos[0] - press[0]) / rect.w.max(1) as f32;
649	let dy = (pos[1] - press[1]) / rect.h.max(1) as f32;
650	let x_span = limits[1] - limits[0];
651	let y_span = limits[3] - limits[2];
652	[
653		limits[0] - dx * x_span,
654		limits[1] - dx * x_span,
655		limits[2] + dy * y_span,
656		limits[3] + dy * y_span,
657	]
658}
659
660/// Axis-aligned pixel rect spanned by two box-select corners.
661fn selection_rect(a: [f32; 2], b: [f32; 2]) -> PixelRect {
662	let x = a[0].min(b[0]);
663	let y = a[1].min(b[1]);
664	PixelRect::new(
665		x as i32,
666		y as i32,
667		(a[0] - b[0]).abs().max(1.0) as u32,
668		(a[1] - b[1]).abs().max(1.0) as u32,
669	)
670}
671
672/// Limits for the display-space span selected by a box-zoom gesture.
673fn box_zoom_limits(limits: [f32; 4], rect: PixelRect, a: [f32; 2], b: [f32; 2]) -> [f32; 4] {
674	let w = rect.w.max(1) as f32;
675	let h = rect.h.max(1) as f32;
676	let x_span = limits[1] - limits[0];
677	let y_span = limits[3] - limits[2];
678	let fx = |px: f32| limits[0] + ((px - rect.x as f32) / w).clamp(0.0, 1.0) * x_span;
679	let fy = |py: f32| limits[3] - ((py - rect.y as f32) / h).clamp(0.0, 1.0) * y_span;
680	let (x0, x1) = (fx(a[0]).min(fx(b[0])), fx(a[0]).max(fx(b[0])));
681	let (y0, y1) = (fy(a[1]).min(fy(b[1])), fy(a[1]).max(fy(b[1])));
682	[x0, x1, y0, y1]
683}
684
685/// Ease-out cubic interpolation between two limit boxes.
686fn lerp_limits(from: [f32; 4], to: [f32; 4], t: f32) -> [f32; 4] {
687	[
688		from[0] + (to[0] - from[0]) * t,
689		from[1] + (to[1] - from[1]) * t,
690		from[2] + (to[2] - from[2]) * t,
691		from[3] + (to[3] - from[3]) * t,
692	]
693}
694
695impl ViewerLiveSource for FigureView {
696	fn capabilities(&self) -> ViewerLiveCapabilities {
697		ViewerLiveCapabilities {
698			receives_events: true,
699			..ViewerLiveCapabilities::default()
700		}
701	}
702
703	fn open(&mut self, _runtime: &Runtime) -> Result<()> {
704		Ok(())
705	}
706
707	fn update(&mut self, delta_ms: f32) -> Result<()> {
708		if !delta_ms.is_finite() || delta_ms < 0.0 {
709			return Err(Error::invalid_argument(
710				"FigureView::update requires a finite non-negative delta",
711			));
712		}
713		for cell in 0..self.cell_count() {
714			let Some(anim) = &self.view_anims[cell] else {
715				continue;
716			};
717			let elapsed = anim.elapsed_ms + delta_ms;
718			let duration = anim.duration_ms.max(1.0);
719			let t = (elapsed / duration).min(1.0);
720			let eased = 1.0 - (1.0 - t).powi(3);
721			let value = lerp_limits(anim.from, anim.to, eased);
722			let done = t >= 1.0;
723			let clear = anim.clear_on_finish;
724			self.view_limits[cell] = Some(value);
725			if done {
726				self.view_anims[cell] = None;
727				if clear {
728					self.view_limits[cell] = None;
729					let (row, col) = (cell / self.cols(), cell % self.cols());
730					self.figure.ax(row as i32, col as i32).auto_limits();
731				}
732			} else if let Some(anim) = &mut self.view_anims[cell] {
733				anim.elapsed_ms = elapsed;
734			}
735		}
736		Ok(())
737	}
738
739	fn on_event(&mut self, event: &InputEvent) -> Result<()> {
740		match event.kind {
741			InputEventKind::MouseScroll => {
742				self.scroll_pos = [event.mouse_x, event.mouse_y];
743				self.scroll_delta += event.scroll_y;
744			}
745			InputEventKind::MouseDown if event.button == 1 => {
746				let Some(cell) = self.cell_at(event.mouse_x, event.mouse_y) else {
747					return Ok(());
748				};
749				// Plain legend clicks toggle the artist. Shift-drag can start
750				// anywhere inside the data viewport, including under the legend.
751				if !event.shift()
752					&& let Some((_, artist, hidden)) = self.legend_hit(cell, event.mouse_x, event.mouse_y)
753				{
754					let (row, col) = (cell / self.cols(), cell % self.cols());
755					self
756						.figure
757						.ax(row as i32, col as i32)
758						.set_artist_hidden(artist, !hidden);
759					return Ok(());
760				}
761				if event.click_count >= 2 {
762					// Double-click restores this cell's attach-time limits.
763					match self.base_limits[cell] {
764						Some(limits) => self.animate_to(cell, limits, false),
765						None => {
766							let target = self.axes_limits(cell);
767							self.animate_to(cell, target, true);
768						}
769					}
770					return Ok(());
771				}
772				if event.shift() {
773					self.box_select = Some(BoxSelect {
774						cell,
775						start: [event.mouse_x, event.mouse_y],
776						current: [event.mouse_x, event.mouse_y],
777					});
778					return Ok(());
779				}
780				self.view_anims[cell] = None;
781				self.drag = Some(DragState {
782					cell,
783					press: [event.mouse_x, event.mouse_y],
784					limits: self.effective_limits(cell),
785				});
786			}
787			InputEventKind::MouseMove => {
788				self.pointer = [event.mouse_x, event.mouse_y];
789				self.pointer_valid = true;
790				self.legend_hover = self.cell_at(event.mouse_x, event.mouse_y).and_then(|cell| {
791					self
792						.legend_hit(cell, event.mouse_x, event.mouse_y)
793						.map(|(row, artist, _)| (cell, row, artist))
794				});
795				if let Some(select) = &mut self.box_select {
796					select.current = [event.mouse_x, event.mouse_y];
797				}
798				// Pan applies immediately so a press/drag/release inside one
799				// frame still lands; render only publishes the overrides.
800				if let Some(drag) = &self.drag {
801					let pos = [event.mouse_x, event.mouse_y];
802					if drag.cell < self.cell_count() {
803						let rect = self.plot_rect(drag.cell);
804						if rect.w > 0 && rect.h > 0 {
805							self.view_limits[drag.cell] = Some(pan_limits(drag.limits, rect, drag.press, pos));
806						}
807					}
808				}
809			}
810			InputEventKind::MouseUp if event.button == 1 => {
811				if let Some(select) = self.box_select.take() {
812					let dx = (select.current[0] - select.start[0]).abs();
813					let dy = (select.current[1] - select.start[1]).abs();
814					if dx >= BOX_ZOOM_MIN_PX && dy >= BOX_ZOOM_MIN_PX {
815						let rect = self.plot_rect(select.cell);
816						let limits = self.effective_limits(select.cell);
817						let target = box_zoom_limits(limits, rect, select.start, select.current);
818						self.animate_to(select.cell, target, false);
819					}
820				}
821				self.drag = None;
822			}
823			InputEventKind::MouseLeave => {
824				self.pointer_valid = false;
825				self.drag = None;
826				self.box_select = None;
827				self.legend_hover = None;
828			}
829			InputEventKind::KeyDown if event.key == Key::R => {
830				self.reset_pending = true;
831			}
832			_ => {}
833		}
834		Ok(())
835	}
836
837	fn render(&mut self, ui: &mut Ui<'_>, width: u32, height: u32) -> Result<()> {
838		self.render_at(ui, PixelRect::new(0, 0, width, height))
839	}
840
841	fn close(&mut self) -> Result<()> {
842		Ok(())
843	}
844}
845
846impl crate::viewer::WorkspaceItem for FigureView {
847	fn id(&self) -> &str {
848		&self.name
849	}
850
851	fn title(&self) -> &str {
852		if self.name.is_empty() {
853			"figure"
854		} else {
855			&self.name
856		}
857	}
858
859	fn update(&mut self, delta_ms: f32) -> Result<()> {
860		ViewerLiveSource::update(self, delta_ms)
861	}
862
863	fn render(&mut self, ui: &mut Ui<'_>, rect: PixelRect) -> Result<()> {
864		self.render_at(ui, rect)
865	}
866
867	fn on_event(&mut self, event: &InputEvent) -> Result<()> {
868		ViewerLiveSource::on_event(self, event)
869	}
870}