Skip to main content

oa/input/
navigation.rs

1//! 2-D viewer navigation (pan / zoom) state machine.
2//!
3//! Donor: `oa/ui/navigation.h`, `oa/ui/navigation.cpp`.
4//!
5//! The camera lives in "content space": +X right, +Y down, Z = zoom level.
6//! `pan_x` / `pan_y` are screen-pixel offsets from the viewport origin to
7//! the top-left corner of the content image.  `zoom` is the scale factor
8//! applied to the content before those offsets.
9
10pub use super::type_gen::NavigationConfig;
11use super::types::{InputEvent, InputEventKind, Key, PinchPhase, ScrollGesture};
12use crate::{Error, Result};
13
14// ── Config ────────────────────────────────────────────────────────────────────
15
16impl Default for NavigationConfig {
17	fn default() -> Self {
18		Self {
19			zoom_min: 0.01,
20			zoom_max: 50.0,
21			mouse_wheel_sensitivity: 0.001,
22			wheel_pan_scale: 50.0,
23			ctrl_scroll_dolly_scale: 0.35,
24			rmb_zoom_drag_scale: 0.005,
25			keyboard_pan_step: 0.5,
26			touchpad_pan_scale: 40.0,
27			pinch_gesture_scale: 0.5,
28			keyboard_zoom_step: 1.05,
29			animation_duration_ms: 200.0,
30		}
31	}
32}
33
34// ── Navigation ────────────────────────────────────────────────────────────────
35
36/// 2-D viewport navigation session. Donor: `oa::Navigation`.
37pub struct Navigation {
38	config: NavigationConfig,
39	// Current state (screen pixels).
40	pan_x: f32,
41	pan_y: f32,
42	zoom: f32,
43	// Content and viewport dimensions.
44	content_w: f32,
45	content_h: f32,
46	viewport_w: f32,
47	viewport_h: f32,
48	// Drag state.
49	dragging_pan: bool,
50	last_drag_x: f32,
51	last_drag_y: f32,
52	dragging_rmb: bool,
53	last_rmb_x: f32,
54	// Zoom anchors: pointer position and the RMB-drag press point.
55	pointer_x: f32,
56	pointer_y: f32,
57	rmb_anchor_x: f32,
58	rmb_anchor_y: f32,
59	// Animation.
60	animating: bool,
61	anim_elapsed_ms: f32,
62	anim_duration_ms: f32,
63	anim_start_pan_x: f32,
64	anim_start_pan_y: f32,
65	anim_start_zoom: f32,
66	anim_target_pan_x: f32,
67	anim_target_pan_y: f32,
68	anim_target_zoom: f32,
69	// Pinch state.
70	pinch_active: bool,
71}
72
73impl Navigation {
74	/// Create with default config.
75	pub fn new() -> Self {
76		Self::new_with_config(NavigationConfig::default())
77	}
78
79	/// Apply the shared donor motion preset to subsequent viewport transitions.
80	pub fn set_motion_speed(&mut self, speed: crate::input::MotionSpeed) {
81		self.config.animation_duration_ms = speed.duration_ms(200.0);
82	}
83
84	pub fn new_with_config(config: NavigationConfig) -> Self {
85		Self {
86			config,
87			pan_x: 0.0,
88			pan_y: 0.0,
89			zoom: 1.0,
90			content_w: 0.0,
91			content_h: 0.0,
92			viewport_w: 0.0,
93			viewport_h: 0.0,
94			dragging_pan: false,
95			last_drag_x: 0.0,
96			last_drag_y: 0.0,
97			dragging_rmb: false,
98			last_rmb_x: 0.0,
99			pointer_x: 0.0,
100			pointer_y: 0.0,
101			rmb_anchor_x: 0.0,
102			rmb_anchor_y: 0.0,
103			animating: false,
104			anim_elapsed_ms: 0.0,
105			anim_duration_ms: 0.0,
106			anim_start_pan_x: 0.0,
107			anim_start_pan_y: 0.0,
108			anim_start_zoom: 1.0,
109			anim_target_pan_x: 0.0,
110			anim_target_pan_y: 0.0,
111			anim_target_zoom: 1.0,
112			pinch_active: false,
113		}
114	}
115
116	/// Set the content (source image) size.
117	pub fn set_content_size(&mut self, w: f32, h: f32) -> Result<()> {
118		if !w.is_finite() || !h.is_finite() || w < 0.0 || h < 0.0 {
119			return Err(Error::invalid_argument(
120				"Navigation content size must be finite and non-negative",
121			));
122		}
123		self.content_w = w;
124		self.content_h = h;
125		Ok(())
126	}
127
128	/// Set the viewport (window) size.
129	pub fn set_viewport_size(&mut self, w: f32, h: f32) -> Result<()> {
130		if !w.is_finite() || !h.is_finite() || w < 0.0 || h < 0.0 {
131			return Err(Error::invalid_argument(
132				"Navigation viewport size must be finite and non-negative",
133			));
134		}
135		self.viewport_w = w;
136		self.viewport_h = h;
137		Ok(())
138	}
139
140	// ── Read-back ─────────────────────────────────────────────────────────────
141
142	pub fn pan_x(&self) -> f32 {
143		self.pan_x
144	}
145	pub fn pan_y(&self) -> f32 {
146		self.pan_y
147	}
148	pub fn zoom(&self) -> f32 {
149		self.zoom
150	}
151
152	// ── Mutations ─────────────────────────────────────────────────────────────
153
154	/// Fit content to the viewport with no animation.
155	pub fn fit_to_window(&mut self) -> Result<()> {
156		self.fit_to_window_animated(false)
157	}
158
159	pub fn fit_to_window_animated(&mut self, animate: bool) -> Result<()> {
160		if self.content_w <= 0.0
161			|| self.content_h <= 0.0
162			|| self.viewport_w <= 0.0
163			|| self.viewport_h <= 0.0
164		{
165			return Ok(());
166		}
167		let scale = (self.viewport_w / self.content_w)
168			.min(self.viewport_h / self.content_h)
169			.max(self.config.zoom_min);
170		let target_pan_x = (self.viewport_w - self.content_w * scale) * 0.5;
171		let target_pan_y = (self.viewport_h - self.content_h * scale) * 0.5;
172		if animate {
173			self.begin_animation(target_pan_x, target_pan_y, scale);
174		} else {
175			self.pan_x = target_pan_x;
176			self.pan_y = target_pan_y;
177			self.zoom = scale;
178			self.animating = false;
179		}
180		Ok(())
181	}
182
183	/// Zoom to 1:1 pixel (100%).
184	pub fn zoom_to_100(&mut self) {
185		let center_x = self.viewport_w * 0.5;
186		let center_y = self.viewport_h * 0.5;
187		self.zoom_at(1.0, center_x, center_y, false);
188	}
189
190	/// Pan by screen-pixel delta.
191	pub fn pan_by(&mut self, dx: f32, dy: f32) {
192		self.pan_x += dx;
193		self.pan_y += dy;
194		self.animating = false;
195	}
196
197	/// Keyboard directional pan.
198	pub fn keyboard_pan(&mut self, dir_x: f32, dir_y: f32) {
199		let step = self.config.keyboard_pan_step * self.viewport_w.max(1.0);
200		self.pan_by(dir_x * step, dir_y * step);
201	}
202
203	/// Keyboard zoom in.
204	pub fn keyboard_zoom_in(&mut self) {
205		let center_x = self.viewport_w * 0.5;
206		let center_y = self.viewport_h * 0.5;
207		let new_zoom = (self.zoom * self.config.keyboard_zoom_step)
208			.clamp(self.zoom_min_limit(), self.zoom_max_limit());
209		self.zoom_at(new_zoom, center_x, center_y, false);
210	}
211
212	/// Keyboard zoom out.
213	pub fn keyboard_zoom_out(&mut self) {
214		let center_x = self.viewport_w * 0.5;
215		let center_y = self.viewport_h * 0.5;
216		let new_zoom = (self.zoom / self.config.keyboard_zoom_step)
217			.clamp(self.zoom_min_limit(), self.zoom_max_limit());
218		self.zoom_at(new_zoom, center_x, center_y, false);
219	}
220
221	// ── Per-frame ─────────────────────────────────────────────────────────────
222
223	/// Advance animation by `delta_ms` milliseconds.
224	pub fn update(&mut self, delta_ms: f32) {
225		if !self.animating {
226			return;
227		}
228		self.anim_elapsed_ms = (self.anim_elapsed_ms + delta_ms).min(self.anim_duration_ms);
229		let t = if self.anim_duration_ms > 0.0 {
230			Self::ease_out_cubic(self.anim_elapsed_ms / self.anim_duration_ms)
231		} else {
232			1.0
233		};
234		self.pan_x = lerp(self.anim_start_pan_x, self.anim_target_pan_x, t);
235		self.pan_y = lerp(self.anim_start_pan_y, self.anim_target_pan_y, t);
236		self.zoom = lerp(self.anim_start_zoom, self.anim_target_zoom, t);
237		if self.anim_elapsed_ms >= self.anim_duration_ms {
238			self.animating = false;
239		}
240	}
241
242	/// Route one InputEvent to the navigation logic.
243	///
244	/// Returns `true` when the event was consumed.
245	pub fn handle_event(&mut self, ev: &InputEvent) -> bool {
246		if matches!(
247			ev.kind,
248			InputEventKind::MouseMove
249				| InputEventKind::MouseDown
250				| InputEventKind::MouseUp
251				| InputEventKind::MouseScroll
252		) {
253			self.pointer_x = ev.mouse_x;
254			self.pointer_y = ev.mouse_y;
255		}
256		match ev.kind {
257			InputEventKind::MouseDown => {
258				if ev.button == 1 || ev.button == 2 {
259					// LMB or MMB → begin pan drag.
260					self.dragging_pan = true;
261					self.last_drag_x = ev.mouse_x;
262					self.last_drag_y = ev.mouse_y;
263					self.animating = false;
264					return true;
265				}
266				if ev.button == 3 {
267					// RMB → begin zoom drag, anchored at the press point.
268					self.dragging_rmb = true;
269					self.last_rmb_x = ev.mouse_x;
270					self.rmb_anchor_x = ev.mouse_x;
271					self.rmb_anchor_y = ev.mouse_y;
272					self.animating = false;
273					return true;
274				}
275			}
276			InputEventKind::MouseUp => {
277				if ev.button == 1 || ev.button == 2 {
278					self.dragging_pan = false;
279					return false;
280				}
281				if ev.button == 3 {
282					self.dragging_rmb = false;
283					return false;
284				}
285			}
286			InputEventKind::MouseMove => {
287				if self.dragging_pan {
288					let dx = ev.mouse_x - self.last_drag_x;
289					let dy = ev.mouse_y - self.last_drag_y;
290					self.last_drag_x = ev.mouse_x;
291					self.last_drag_y = ev.mouse_y;
292					self.pan_by(dx, dy);
293					return true;
294				}
295				if self.dragging_rmb {
296					let dx = ev.mouse_x - self.last_rmb_x;
297					self.last_rmb_x = ev.mouse_x;
298					let factor = 1.0 + dx * self.config.rmb_zoom_drag_scale;
299					let new_zoom = (self.zoom * factor).clamp(self.zoom_min_limit(), self.zoom_max_limit());
300					self.zoom_at(new_zoom, self.rmb_anchor_x, self.rmb_anchor_y, false);
301					return true;
302				}
303			}
304			InputEventKind::MouseScroll => {
305				match ev.scroll_gesture {
306					ScrollGesture::MouseWheel => {
307						if ev.ctrl() {
308							// ctrl+wheel → zoom at cursor.
309							let delta = ev.scroll_y * self.config.ctrl_scroll_dolly_scale;
310							let factor = 1.0 + delta;
311							let new_zoom =
312								(self.zoom * factor).clamp(self.zoom_min_limit(), self.zoom_max_limit());
313							self.zoom_at(new_zoom, ev.mouse_x, ev.mouse_y, false);
314						} else {
315							// wheel → pan (view follows the scroll direction,
316							// eog-style).
317							let step = self.config.wheel_pan_scale;
318							self.pan_by(ev.scroll_x * step, ev.scroll_y * step);
319						}
320						return true;
321					}
322					ScrollGesture::TouchpadPan => {
323						// Touchpad two-finger pan: content follows the fingers
324						// (natural scrolling, like browsers). Deltas arrive in
325						// traditional units — +x = gesture right, +y = gesture
326						// up — so content-following is +x / -y in screen space.
327						let scale = self.config.touchpad_pan_scale;
328						self.pan_by(ev.scroll_x * scale, -ev.scroll_y * scale);
329						return true;
330					}
331					ScrollGesture::PinchScroll => {
332						let delta = ev.scroll_y * self.config.ctrl_scroll_dolly_scale;
333						let factor = 1.0 + delta;
334						let new_zoom = (self.zoom * factor).clamp(self.zoom_min_limit(), self.zoom_max_limit());
335						self.zoom_at(new_zoom, ev.mouse_x, ev.mouse_y, false);
336						return true;
337					}
338					ScrollGesture::None => {}
339				}
340			}
341			InputEventKind::Pinch => {
342				match ev.pinch_phase {
343					PinchPhase::Begin => {
344						self.pinch_active = true;
345					}
346					PinchPhase::Update => {
347						// gesture_scale is the ratio since the last update;
348						// apply it incrementally, anchored at the pointer.
349						// Updates are applied without requiring Begin —
350						// MultiGesture backends have no phase signal.
351						let factor = 1.0 + (ev.gesture_scale - 1.0) * self.config.pinch_gesture_scale;
352						let new_zoom = (self.zoom * factor).clamp(self.zoom_min_limit(), self.zoom_max_limit());
353						self.zoom_at(new_zoom, self.pointer_x, self.pointer_y, false);
354					}
355					PinchPhase::End | PinchPhase::None => {
356						self.pinch_active = false;
357					}
358				}
359				return true;
360			}
361			InputEventKind::KeyDown => {
362				if ev.key == Key::Equals && !ev.ctrl() {
363					self.keyboard_zoom_in();
364					return true;
365				}
366				if ev.key == Key::Minus && !ev.ctrl() {
367					self.keyboard_zoom_out();
368					return true;
369				}
370				if ev.key == Key::Num0 || ev.key == Key::F {
371					let _ = self.fit_to_window();
372					return true;
373				}
374				if ev.key == Key::Num9 {
375					self.zoom_to_100();
376					return true;
377				}
378				if ev.key == Key::Kp8 {
379					self.keyboard_pan(0.0, -1.0);
380					return true;
381				}
382				if ev.key == Key::Kp2 {
383					self.keyboard_pan(0.0, 1.0);
384					return true;
385				}
386				if ev.key == Key::Kp4 {
387					self.keyboard_pan(-1.0, 0.0);
388					return true;
389				}
390				if ev.key == Key::Kp6 {
391					self.keyboard_pan(1.0, 0.0);
392					return true;
393				}
394			}
395			_ => {}
396		}
397		false
398	}
399
400	// ── Private ───────────────────────────────────────────────────────────────
401
402	fn zoom_at(&mut self, new_zoom: f32, anchor_x: f32, anchor_y: f32, animate: bool) {
403		let clamped = new_zoom.clamp(self.zoom_min_limit(), self.zoom_max_limit());
404		let ratio = clamped / self.zoom;
405		let new_pan_x = anchor_x - (anchor_x - self.pan_x) * ratio;
406		let new_pan_y = anchor_y - (anchor_y - self.pan_y) * ratio;
407		if animate {
408			self.begin_animation(new_pan_x, new_pan_y, clamped);
409		} else {
410			self.pan_x = new_pan_x;
411			self.pan_y = new_pan_y;
412			self.zoom = clamped;
413			self.animating = false;
414		}
415	}
416
417	/// Fit-to-window scale for the current content and viewport.
418	fn fit_zoom(&self) -> f32 {
419		if self.content_w <= 0.0
420			|| self.content_h <= 0.0
421			|| self.viewport_w <= 0.0
422			|| self.viewport_h <= 0.0
423		{
424			return self.config.zoom_min;
425		}
426		(self.viewport_w / self.content_w).min(self.viewport_h / self.content_h)
427	}
428
429	/// Maximum zoom-out: a 10% margin below the fit scale (or below actual
430	/// size for content smaller than the viewport), floored by `zoom_min`.
431	fn zoom_min_limit(&self) -> f32 {
432		(self.fit_zoom().min(1.0) * 0.1).max(self.config.zoom_min)
433	}
434
435	/// Maximum zoom-in: `zoom_max`, raised to the fit scale so small content
436	/// fitted above it stays reachable and zoom-out does not jump-clamp.
437	fn zoom_max_limit(&self) -> f32 {
438		self.config.zoom_max.max(self.fit_zoom())
439	}
440
441	fn begin_animation(&mut self, target_pan_x: f32, target_pan_y: f32, target_zoom: f32) {
442		self.anim_start_pan_x = self.pan_x;
443		self.anim_start_pan_y = self.pan_y;
444		self.anim_start_zoom = self.zoom;
445		self.anim_target_pan_x = target_pan_x;
446		self.anim_target_pan_y = target_pan_y;
447		self.anim_target_zoom = target_zoom;
448		self.anim_elapsed_ms = 0.0;
449		self.anim_duration_ms = self.config.animation_duration_ms;
450		self.animating = true;
451	}
452
453	fn ease_out_cubic(t: f32) -> f32 {
454		let t = t.clamp(0.0, 1.0);
455		1.0 - (1.0 - t).powi(3)
456	}
457}
458
459impl Default for Navigation {
460	fn default() -> Self {
461		Self::new()
462	}
463}
464
465fn lerp(a: f32, b: f32, t: f32) -> f32 {
466	a + (b - a) * t
467}