oarust 0.14.1

GPU-first semantic computing engine written in Rust
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
//! `oa::Viewer` — windowed and headless media inspection application.
//!
//! Donor: `oa/ui/viewer.h`, `oa/ui/viewer.cpp`,
//!        `oa/ui/viewerApplication.cpp`, `oa/ui/viewerPresentation.cpp`
//!
//! The Viewer owns an SDL3 window, swapchain `Presenter`, `Ui` compositor,
//! `Navigation`, and optional media sources.  It borrows (or creates) one
//! `Engine` and drives a per-frame compose → direct-present loop until the
//! user closes the window or calls `quit()`.
//!
//! Entry points:
//! ```rust,ignore
//! // Static file path (creates its own engine):
//! Viewer::preview("path/to/image.png")?;
//!
//! // Borrowed engine:
//! Viewer::preview_with_engine(&engine, "path/to/video.mp4")?;
//!
//! // Existing GPU texture:
//! Viewer::show(&engine, &texture)?;
//!
//! // Custom live source:
//! let mut viewer = Viewer::new(ViewerConfig { mode: ViewerMode::Live, .. });
//! viewer.set_live_source(&mut my_source);
//! viewer.run(&engine)?;
//! ```

mod audio_mode;
mod audio_view;
mod decoration;
mod image_mode;
mod live_mode;
mod overlay;
mod timeline;
mod training_source;
mod video_mode;
mod workspace;

#[cfg(test)]
#[path = "../../../test/rs/render/viewer_canvas_unit.rs"]
mod canvas_tests;

pub use config::{ViewerAudioView, ViewerCanvasBackground, ViewerMode};
pub use live_source::ViewerLiveSource;
pub use training_source::{TrainingPreviewFrame, TrainingViewerSource};
pub use types::{TrainingViewerConfig, ViewerConfig, ViewerLiveCapabilities};
pub use workspace::{SharedItem, Workspace, WorkspaceItem, WorkspaceNode};

mod config;
mod live_source;
#[path = "viewer/type.gen.rs"]
mod types;

use std::time::Instant;

use crate::input::{
	InputEventKind, Key, Navigation,
	sdl_events::{convert_sdl_event, window_pixel_scale},
};
use crate::runtime::{Presenter, SdlWindow};
use crate::ui::{Ui, types::PixelRect};
use crate::{Engine, Error, Result, Texture, render::Renderer};

// ── Viewer ────────────────────────────────────────────────────────────────────

/// Windowed / headless media inspection session. Donor: `oa::Viewer`.
pub struct Viewer<'src> {
	config: ViewerConfig,
	live_source: Option<&'src mut dyn ViewerLiveSource>,
}

impl<'src> Viewer<'src> {
	pub fn new(config: ViewerConfig) -> Self {
		Self {
			config,
			live_source: None,
		}
	}

	pub fn new_with_path(path: impl Into<String>) -> Self {
		Self::new(ViewerConfig {
			path: path.into(),
			..ViewerConfig::default()
		})
	}

	pub fn set_live_source(&mut self, source: &'src mut dyn ViewerLiveSource) {
		self.live_source = Some(source);
		self.config.mode = ViewerMode::Live;
	}

	/// Attach a `Workspace` dock host; equivalent to `set_live_source` but
	/// selects `ViewerMode::Workspace` for the dock-window presentation.
	pub fn set_workspace(&mut self, workspace: &'src mut Workspace) {
		self.live_source = Some(workspace);
		self.config.mode = ViewerMode::Workspace;
	}

	// ── Blocking entry points ─────────────────────────────────────────────────

	/// Open `path` in a new window, creating a presentation-capable engine.
	pub fn preview(path: &str) -> Result<()> {
		Self::preview_with_config(path, ViewerConfig::default())
	}

	pub fn preview_with_config(path: &str, config: ViewerConfig) -> Result<()> {
		if path.is_empty() {
			return Err(Error::invalid_argument(
				"Viewer::preview requires a non-empty path",
			));
		}
		let full_config = ViewerConfig {
			path: path.to_owned(),
			..config
		};
		Viewer::new(full_config).run_owned()
	}

	/// Open `path` borrowing `engine`.
	pub fn preview_with_engine(engine: &Engine, path: &str) -> Result<()> {
		Self::preview_with_engine_and_config(engine, path, ViewerConfig::default())
	}

	pub fn preview_with_engine_and_config(
		engine: &Engine,
		path: &str,
		config: ViewerConfig,
	) -> Result<()> {
		if path.is_empty() {
			return Err(Error::invalid_argument(
				"Viewer::preview requires a non-empty path",
			));
		}
		let full_config = ViewerConfig {
			path: path.to_owned(),
			..config
		};
		Viewer::new(full_config).run_borrowed(engine)
	}

	/// Display `texture` in a blocking window using `engine`.
	pub fn show(engine: &Engine, texture: &Texture) -> Result<()> {
		Self::show_with_config(engine, texture, ViewerConfig::default())
	}

	pub fn show_with_config(engine: &Engine, texture: &Texture, config: ViewerConfig) -> Result<()> {
		if !texture.engine_handle().same_as(&engine.handle()) {
			return Err(Error::invalid_argument(
				"Viewer::show: Texture does not belong to this Engine",
			));
		}
		let app_config = ViewerConfig {
			mode: ViewerMode::Image,
			path: String::new(),
			..config
		};
		Viewer::new(app_config).run_with_texture(engine, texture)
	}

	/// Display a headless `RenderFrame` in a blocking window.
	///
	/// Waits for the frame's producer event before presenting, then returns
	/// once the window is closed.  A second `begin_frame` / `cancel_frame`
	/// cycle is recordable immediately after this call returns, proving that
	/// the ring slot was released.
	///
	/// Donor: `oa::Viewer::show(*engine, *renderer, *frame, cfg)`.
	pub fn show_render_frame(
		engine: &Engine,
		renderer: &Renderer<'_>,
		frame: crate::render::RenderFrame,
		config: ViewerConfig,
	) -> Result<()> {
		if !renderer.owns_frame(&frame) {
			return Err(Error::invalid_argument(
				"Viewer::show_render_frame requires a frame produced by the supplied Renderer and Engine",
			));
		}
		// Wait for the GPU producer before any readback or blit.
		frame.producer().wait()?;
		let texture = frame.color().clone();
		let app_config = ViewerConfig {
			mode: ViewerMode::Image,
			path: String::new(),
			..config
		};
		// `frame` must stay alive until the Viewer exits so the ring slot
		// is not recycled before the present completes.
		let result = Viewer::new(app_config).run_with_texture(engine, &texture);
		drop(texture);
		drop(frame);
		let collect_result = renderer.collect().map(|_| ());
		match (result, collect_result) {
			(Err(error), _) | (Ok(()), Err(error)) => Err(error),
			(Ok(()), Ok(())) => Ok(()),
		}
	}

	/// Run the viewer session borrowing `engine`.
	pub fn run(self, engine: &Engine) -> Result<()> {
		self.run_borrowed(engine)
	}

	// ── Private run ───────────────────────────────────────────────────────────

	/// Create a presentation-capable engine and run.
	///
	/// Use this when `Viewer::new(config).run_standalone()` — the viewer
	/// owns its own engine lifecycle.  Equivalent to the C++ `viewer.run()`
	/// one-liner when no engine is passed.
	pub fn run_standalone(self) -> Result<()> {
		self.run_owned()
	}

	fn run_owned(mut self) -> Result<()> {
		// Create the SDL3 window first — its extensions are required before
		// the Vulkan instance is created inside Engine::builder().build().
		let window = SdlWindow::with_client_frame(
			&self.config.title,
			self.config.width,
			self.config.height,
			true,
		)?;
		let extensions = window.required_instance_extensions()?;
		let engine = Engine::builder()
			.requirements(crate::EngineRequirements::default().presentation())
			.instance_extensions(extensions)
			.build()?;
		self.application_loop(&engine, window, None)
	}

	/// Run on a borrowed engine (creates its own window).
	fn run_borrowed(mut self, engine: &Engine) -> Result<()> {
		let window = SdlWindow::with_client_frame(
			&self.config.title,
			self.config.width,
			self.config.height,
			true,
		)?;
		self.application_loop(engine, window, None)
	}

	/// Run displaying a borrowed GPU texture.
	fn run_with_texture(mut self, engine: &Engine, texture: &Texture) -> Result<()> {
		let window = SdlWindow::with_client_frame(
			&self.config.title,
			self.config.width,
			self.config.height,
			texture.render_target_image().is_none(),
		)?;
		self.application_loop(engine, window, Some(texture))
	}

	/// Inner application loop. Donor: `oa::Viewer::runApplication`.
	fn application_loop(
		&mut self,
		engine: &Engine,
		window: SdlWindow,
		borrowed_texture: Option<&Texture>,
	) -> Result<()> {
		if self.config.show_help {
			engine.log(crate::LogLevel::Info, crate::LogComponent::UI, "Viewer: wheel/drag pan, Ctrl+wheel or right-drag zoom, +/- zoom, 0 fit, 9 actual size, 1–5 channels, B background, G grid, Ctrl+O open file, F11 fullscreen, Space play/pause, arrows seek, W/S/M audio views, Q/Esc close")?;
		}
		// Resolve initial drawable extent.
		let [w, h] = window.drawable_extent();
		if w == 0 || h == 0 {
			return Err(Error::invalid_argument(
				"Viewer window has zero drawable extent",
			));
		}

		// Build Presenter + swapchain.
		let mut presenter = Presenter::new(engine, &window)?;
		if !presenter.supports_swapchain() {
			return Err(Error::missing_capability(
				"Viewer requires a swapchain-capable device (VK_KHR_swapchain)",
			));
		}
		if !presenter.has_present() {
			return Err(Error::missing_capability(
				"Viewer requires a queue family that can present to the window surface",
			));
		}
		presenter.init_swapchain(&window)?;

		// Open the UI compositor.
		let style = self.config.style.clone();
		let mut ui = Ui::init_with_style(engine, w, h, style)?;

		// Open the media source.
		let mut media = MediaState::open(engine, &self.config, borrowed_texture)?;

		// Navigation — fitted to content.
		let mut nav = Navigation::new();
		if let Some((cw, ch)) = media.content_size() {
			nav.set_content_size(cw as f32, ch as f32)?;
		}
		nav.set_viewport_size(w as f32, h as f32)?;
		nav.fit_to_window()?;

		let mut source_opened = false;
		let mut run_result = (|| -> Result<()> {
			if let Some(source) = self.live_source.as_deref_mut() {
				source.open(engine)?;
				source_opened = true;
			}

			// Event pump.
			let mut event_pump = window
				.event_pump()
				.map_err(|e| Error::backend_failure("SDL3", "Viewer event pump", e))?;

			let mut running = true;
			let mut timeline_state = timeline::TransportState::default();
			let (mut open_files, open_rx) = OpenFileRequest::new();
			// Connected gamepads — handles stay alive until removal.
			let mut gamepads: Vec<sdl3::gamepad::Gamepad> = window
				.connected_gamepads()
				.into_iter()
				.filter_map(|id| window.open_gamepad(id).ok())
				.collect();
			let mut pointer_inside = true;
			let mut ime_active = false;
			let mut controls_idle_ms = 0.0_f32;
			let mut last_instant = Instant::now();
			let (mut sx, mut sy) = window_pixel_scale(&window.window);

			while running {
				let now = Instant::now();
				let delta_ms = now.duration_since(last_instant).as_secs_f32() * 1000.0;
				last_instant = now;
				controls_idle_ms += delta_ms;

				// Handle SDL events.
				for sdl_ev in event_pump.poll_iter() {
					match &sdl_ev {
						sdl3::event::Event::Quit { .. } => {
							running = false;
						}
						sdl3::event::Event::Window {
							win_event: sdl3::event::WindowEvent::PixelSizeChanged(pw, ph),
							..
						} => {
							let pw = *pw as u32;
							let ph = *ph as u32;
							if pw > 0 && ph > 0 {
								presenter.notify_pixel_size_changed(pw, ph);
								ui.resize(pw, ph)?;
								nav.set_viewport_size(pw as f32, ph as f32)?;
								(sx, sy) = window_pixel_scale(&window.window);
							}
						}
						sdl3::event::Event::Window {
							win_event: sdl3::event::WindowEvent::MouseEnter,
							..
						} => {
							pointer_inside = true;
							controls_idle_ms = 0.0;
						}
						sdl3::event::Event::Window {
							win_event: sdl3::event::WindowEvent::MouseLeave,
							..
						} => {
							pointer_inside = false;
						}
						sdl3::event::Event::GamepadAdded { which, .. } => {
							if let Ok(pad) = window.open_gamepad(which.raw()) {
								gamepads.push(pad);
							}
						}
						sdl3::event::Event::GamepadRemoved { which, .. } => {
							gamepads.retain(|pad| pad.id().is_ok_and(|id| id != *which));
						}
						_ => {}
					}
					if let Some(ui_ev) = convert_sdl_event(&sdl_ev, sx, sy) {
						controls_idle_ms = 0.0;
						// Quit shortcut.
						if ui_ev.kind == InputEventKind::KeyDown
							&& (ui_ev.key == self.config.key_quit || ui_ev.key == self.config.key_quit_q)
						{
							running = false;
							continue;
						}

						// Window shortcuts.
						if ui_ev.kind == InputEventKind::KeyDown && !ui_ev.key_repeat {
							if ui_ev.key == Key::F11 {
								window.toggle_fullscreen()?;
								continue;
							}
							if ui_ev.key == Key::O && ui_ev.ctrl() && self.live_source.is_none() {
								open_files.request(&window)?;
								continue;
							}
						}

						// Donor temporal step shortcuts permit keyboard repeat.
						if ui_ev.kind == InputEventKind::KeyDown
							&& media.has_timeline()
							&& matches!(ui_ev.key, Key::Left | Key::Right | Key::Up | Key::Down)
						{
							let steps = match ui_ev.key {
								Key::Left => -1,
								Key::Right => 1,
								Key::Up => 5,
								_ => -5,
							};
							media.step_temporal(steps)?;
							continue;
						}

						if ui_ev.kind == InputEventKind::KeyDown && !ui_ev.key_repeat {
							if matches!(media, MediaState::Audio { .. }) {
								match ui_ev.key {
									Key::W => self.config.audio_view = ViewerAudioView::Waveform,
									Key::S => self.config.audio_view = ViewerAudioView::Spectrum,
									Key::M => self.config.audio_view = ViewerAudioView::Mel,
									_ => {}
								}
							}

							if ui_ev.key == Key::L && media.has_timeline() {
								self.config.loop_media = !self.config.loop_media;
								match &mut media {
									MediaState::Audio { player, .. } => {
										if let Some(player) = player.as_ref() {
											player.set_loop(self.config.loop_media);
										}
									}
									MediaState::Video { player } => {
										if let Some(player) = player.as_mut() {
											player.set_looping(self.config.loop_media);
										}
									}
									_ => {}
								}
								continue;
							}
							if ui_ev.key == self.config.key_canvas_background {
								self.config.canvas_background = match self.config.canvas_background {
									ViewerCanvasBackground::Dark => ViewerCanvasBackground::Gradient,
									ViewerCanvasBackground::Gradient => ViewerCanvasBackground::Dark,
								};
								continue;
							}
							if ui_ev.key == self.config.key_canvas_grid {
								self.config.show_canvas_grid = !self.config.show_canvas_grid;
								continue;
							}
						}

						// Live source raw events (before navigation).
						if let Some(source) = self.live_source.as_deref_mut()
							&& source.capabilities().receives_events
						{
							source.on_event(&ui_ev)?;
						}

						// Chrome owns gesture starts, not motion/releases from an
						// existing canvas drag crossing into the controls.
						let pointer_event = matches!(
							ui_ev.kind,
							InputEventKind::MouseDown | InputEventKind::MouseScroll
						);
						let chrome_pointer = pointer_event
							&& (ui_ev.mouse_y < 43.0 * sy
								|| (self.config.show_timeline && media.has_timeline() && {
									let [cw, ch] = ui.compose_extent().unwrap_or([w, h]);
									let scale = (sx + sy) * 0.5;
									timeline::owns_pointer(PixelRect::new(0, 0, cw, ch), scale, ui_ev.mouse_y)
								}) || ui.is_popup_open("viewer-window-menu"));
						let source_controls = pointer_event
							&& self.live_source.as_deref().is_some_and(|source| {
								let [cw, ch] = ui.compose_extent().unwrap_or([w, h]);
								source
									.canvas_controls_rect(cw, ch, (sx + sy) * 0.5)
									.is_some_and(|rect| rect.contains(ui_ev.mouse_x, ui_ev.mouse_y))
							});
						let nav_consumed = !chrome_pointer && !source_controls && nav.handle_event(&ui_ev);

						// Image view shortcuts.
						if !nav_consumed {
							media.handle_event(&ui_ev, &self.config)?;
						}

						// Route to UI widgets.
						ui.route_event(&ui_ev);
					}
				}

				// Apply the file-dialog result from the previous frame.
				while let Ok(result) = open_rx.try_recv() {
					open_files.active = false;
					match result {
						Ok(paths) => {
							if let Some(path) = paths.into_iter().next() {
								self.open_media_path(engine, &mut media, &mut nav, &mut timeline_state, &path)?;
							}
						}
						Err(sdl3::dialog::DialogError::Canceled) => {}
						Err(error) => {
							engine.log(
								crate::LogLevel::Warn,
								crate::LogComponent::UI,
								format!("Viewer: open file dialog failed: {error}"),
							)?;
						}
					}
				}

				// Recreate the swapchain after a resize.
				if presenter.needs_swapchain_recreate() {
					presenter.wait_presentation_idle()?;
					presenter.recreate_swapchain(&window)?;
				}

				// Per-frame update.
				nav.set_motion_speed(self.config.motion_speed);
				nav.update(delta_ms);
				media.update()?;
				if let Some(source) = self.live_source.as_deref_mut() {
					source.update(delta_ms)?;
					media.update_live_texture(source.canvas_texture(), &mut nav)?;
				}

				// Build frame.
				let [compose_w, compose_h] = ui.compose_extent().unwrap_or([w, h]);
				ui.set_content_scale((sx + sy) * 0.5)?;
				ui.set_motion_speed(self.config.motion_speed)?;
				ui.begin_frame(delta_ms);
				let chrome_visible = !media.has_timeline()
					|| !self.config.auto_hide_controls
					|| !media.is_playing()
					|| (pointer_inside && controls_idle_ms < self.config.controls_hide_delay_ms as f32)
					|| ui.is_popup_open("viewer-window-menu");
				render_frame(
					&mut ui,
					&mut media,
					&mut nav,
					&self.config,
					compose_w,
					compose_h,
					(sx + sy) * 0.5,
					chrome_visible,
					&mut timeline_state,
				)?;
				if matches!(media, MediaState::Live { .. } | MediaState::Workspace)
					&& let Some(source) = self.live_source.as_deref_mut()
				{
					source.render(&mut ui, compose_w, compose_h)?;
				}
				if chrome_visible {
					running &= decoration::render(
						&mut ui,
						&window,
						&mut media,
						&mut nav,
						&mut self.config,
						[compose_w, compose_h],
						[sx, sy],
						&mut open_files,
					)?;
				}
				if window.client_frame
					&& presenter.has_transparent_composition()
					&& !window.window.is_maximized()
					&& window.window.fullscreen_state() == sdl3::video::FullscreenType::Off
				{
					// Compositors draw no frame for undecorated surfaces; the
					// client frame supplies its own GNOME-style edge outline
					// in the scrubber track's dark grey.
					ui.rect_outline_rounded_at(
						PixelRect::new(0, 0, compose_w, compose_h),
						crate::Color {
							a: 1.0,
							..self.config.style.surface
						},
						(1.0 * (sx + sy) * 0.5).round().max(1.0) as u32,
						PixelRect::new(0, 0, compose_w, compose_h),
						crate::runtime::window_decoration::CORNER_RADIUS * (sx + sy) * 0.5,
					);
					ui.mask_rounded_rect(
						PixelRect::new(0, 0, compose_w, compose_h),
						crate::runtime::window_decoration::CORNER_RADIUS * (sx + sy) * 0.5,
						crate::Color::new(0.0, 0.0, 0.0, 0.0),
					)?;
				}
				ui.end_frame();

				// IME: enable platform text input and anchor the candidate
				// window while a text widget holds focus.
				match ui.text_input_rect() {
					Some(rect) => {
						if !ime_active {
							window.set_text_input_active(true);
							ime_active = true;
						}
						window.set_text_input_area(rect.x, rect.y, rect.w, rect.h, 0);
					}
					None if ime_active => {
						window.set_text_input_active(false);
						ime_active = false;
					}
					None => {}
				}

				// Renderer targets already contain the complete frame. Present them
				// directly so the image-backed target never takes a host detour.
				if presenter.has_swapchain() {
					let suboptimal = if let Some(texture) = borrowed_texture
						&& texture.render_target_image().is_some()
					{
						presenter.present_texture(texture)?
					} else {
						ui.present_to(&mut presenter)?
					};
					if suboptimal {
						let [dw, dh] = window.drawable_extent();
						presenter.notify_pixel_size_changed(dw, dh);
					}
				}
			}
			Ok(())
		})();

		// Close every initialized session even when rendering or event handling
		// fails. Preserve the first error while still attempting later cleanup.
		preserve_first(&mut run_result, presenter.wait_presentation_idle());
		if source_opened && let Some(source) = self.live_source.as_deref_mut() {
			preserve_first(&mut run_result, source.close());
		}
		preserve_first(&mut run_result, media.close());
		preserve_first(&mut run_result, ui.close());
		run_result
	}

	/// Replace the open media with the file at `path`, keeping the window,
	/// engine, and presenter alive. A failed open keeps the current media and
	/// is logged rather than propagated.
	fn open_media_path(
		&mut self,
		engine: &Engine,
		media: &mut MediaState,
		nav: &mut Navigation,
		timeline_state: &mut timeline::TransportState,
		path: &std::path::Path,
	) -> Result<()> {
		let config = ViewerConfig {
			path: path.to_string_lossy().into_owned(),
			..self.config.clone()
		};
		let new_media = match MediaState::open(engine, &config, None) {
			Ok(media) => media,
			Err(error) => {
				engine.log(
					crate::LogLevel::Warn,
					crate::LogComponent::UI,
					format!("Viewer: could not open {}: {error}", path.display()),
				)?;
				return Ok(());
			}
		};
		let mut previous = std::mem::replace(media, new_media);
		previous.close()?;
		self.config = config;
		let (cw, ch) = media.content_size().unwrap_or((0, 0));
		nav.set_content_size(cw as f32, ch as f32)?;
		nav.fit_to_window()?;
		*timeline_state = timeline::TransportState::default();
		Ok(())
	}
}

fn preserve_first(result: &mut Result<()>, next: Result<()>) {
	if result.is_ok() {
		*result = next;
	}
}

// ── Open-file dialog ──────────────────────────────────────────────────────────

type OpenFileResult = std::result::Result<Vec<std::path::PathBuf>, sdl3::dialog::DialogError>;

/// Pending OS file-dialog request. The SDL dialog completes asynchronously;
/// the chosen path arrives on the channel and is applied on the next frame.
pub(super) struct OpenFileRequest {
	tx: std::sync::mpsc::Sender<OpenFileResult>,
	active: bool,
}

impl OpenFileRequest {
	fn new() -> (Self, std::sync::mpsc::Receiver<OpenFileResult>) {
		let (tx, rx) = std::sync::mpsc::channel();
		(Self { tx, active: false }, rx)
	}

	/// Show the OS open-file dialog unless one is already pending.
	pub(super) fn request(&mut self, window: &SdlWindow) -> Result<()> {
		if self.active {
			return Ok(());
		}
		const FILTERS: &[sdl3::dialog::DialogFileFilter<'_>] = &[
			sdl3::dialog::DialogFileFilter {
				name: "Media",
				pattern: "png;jpg;jpeg;bmp;tga;gif;webp;mp4;mkv;webm;avi;mov;mpg;mpeg;mp3;wav;flac;ogg;opus;m4a",
			},
			sdl3::dialog::DialogFileFilter {
				name: "All files",
				pattern: "*",
			},
		];
		let tx = self.tx.clone();
		sdl3::dialog::show_open_file_dialog(
			FILTERS,
			None::<&std::path::Path>,
			false,
			&window.window,
			Box::new(move |result, _filter| {
				let _ = tx.send(result);
			}),
		)
		.map_err(|e| {
			Error::backend_failure(
				"SDL3",
				"open file dialog",
				std::io::Error::other(e.to_string()),
			)
		})?;
		self.active = true;
		Ok(())
	}
}

// ── Frame render ──────────────────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
fn render_frame(
	ui: &mut Ui<'_>,
	media: &mut MediaState,
	nav: &mut Navigation,
	config: &ViewerConfig,
	w: u32,
	h: u32,
	content_scale: f32,
	chrome_visible: bool,
	timeline_state: &mut timeline::TransportState,
) -> Result<()> {
	let full_rect = PixelRect::new(0, 0, w, h);

	// Canvas background.
	if media.has_visual_content() || matches!(media, MediaState::Audio { .. }) {
		let (cw, ch) = media.content_size().unwrap_or((w, h));
		let destination = PixelRect::new(
			nav.pan_x() as i32,
			nav.pan_y() as i32,
			(cw as f32 * nav.zoom()).max(1.0) as u32,
			(ch as f32 * nav.zoom()).max(1.0) as u32,
		);
		overlay::draw_canvas_background(
			ui,
			full_rect,
			destination,
			nav,
			content_scale,
			media.has_visual_content(),
			config,
		)?;
	}

	// Media content area.
	match media {
		MediaState::Image {
			texture,
			channel_mode,
		} => {
			let tex_ref: Option<&Texture> = texture.as_ref().as_ref();
			image_mode::render(ui, tex_ref, nav, channel_mode, full_rect, config)?;
		}
		MediaState::Video { player } => {
			video_mode::render(ui, player.as_mut().as_mut(), nav)?;
		}
		MediaState::Audio { player, analysis } => {
			let p: Option<&mut crate::AudioPlayer> = player.as_mut().as_mut();
			let a: Option<&audio_view::AudioAnalysis> = analysis.as_ref();
			audio_mode::render(ui, p, a, full_rect, config)?;
		}
		MediaState::Live {
			texture,
			channel_mode,
		} => {
			image_mode::render(
				ui,
				texture.as_ref().as_ref(),
				nav,
				channel_mode,
				full_rect,
				config,
			)?;
		}
		MediaState::Workspace => {}
		MediaState::Empty => {}
	}

	// Timeline (temporal modes).
	let mut hud_inset = 0.0;
	if chrome_visible && config.show_timeline && media.has_timeline() {
		timeline::render(ui, media, config, full_rect, timeline_state)?;
		// Transport block top = title row above the scrubber bar.
		let bar = timeline::geometry(full_rect, ui.content_scale());
		let title_top = bar.y - (34.0 * ui.content_scale()).round().max(1.0) as i32;
		hud_inset = (full_rect.h as i32 - title_top).max(0) as f32;
	}
	overlay::draw_hud(ui, full_rect, nav, media.mode_name(), hud_inset, config)?;

	Ok(())
}

// ── Media state ───────────────────────────────────────────────────────────────

#[allow(dead_code)]
pub(crate) enum MediaState {
	Image {
		texture: Box<Option<Texture>>,
		channel_mode: image_mode::ChannelMode,
	},
	Video {
		player: Box<Option<crate::MediaPlayer>>,
	},
	Audio {
		player: Box<Option<crate::AudioPlayer>>,
		analysis: Option<audio_view::AudioAnalysis>,
	},
	Live {
		texture: Box<Option<Texture>>,
		channel_mode: image_mode::ChannelMode,
	},
	Workspace,
	Empty,
}

impl MediaState {
	fn open(engine: &Engine, config: &ViewerConfig, borrowed: Option<&Texture>) -> Result<Self> {
		match config.mode {
			ViewerMode::Image => {
				let texture = if let Some(t) = borrowed {
					Some(t.clone())
				} else if !config.path.is_empty() {
					Some(image_mode::load_texture(engine, &config.path)?)
				} else {
					None
				};
				Ok(Self::Image {
					texture: Box::new(texture),
					channel_mode: image_mode::ChannelMode::Rgb,
				})
			}
			ViewerMode::Video => {
				let player = if !config.path.is_empty() {
					Some(video_mode::open(engine, config)?)
				} else {
					None
				};
				Ok(Self::Video {
					player: Box::new(player),
				})
			}
			ViewerMode::Audio => {
				let (player, analysis) = if !config.path.is_empty() {
					let a = audio_view::analyze(engine, &config.path, config)?;
					let p = audio_mode::open(engine, config)?;
					(Some(p), a)
				} else {
					(None, None)
				};
				Ok(Self::Audio {
					player: Box::new(player),
					analysis,
				})
			}
			ViewerMode::Live => Ok(Self::Live {
				texture: Box::new(None),
				channel_mode: image_mode::ChannelMode::Rgb,
			}),
			ViewerMode::Workspace => Ok(Self::Workspace),
			ViewerMode::Auto => {
				// Try image → video → audio in donor order.
				if let Ok(texture) = image_mode::load_texture(engine, &config.path) {
					return Ok(Self::Image {
						texture: Box::new(Some(texture)),
						channel_mode: image_mode::ChannelMode::Rgb,
					});
				}
				let video_error = match video_mode::open(engine, config) {
					Ok(player) => {
						return Ok(Self::Video {
							player: Box::new(Some(player)),
						});
					}
					Err(error) => error,
				};
				let audio_error = match audio_mode::open(engine, config) {
					Ok(mut player) => {
						let analysis = match audio_view::analyze(engine, &config.path, config) {
							Ok(analysis) => analysis,
							Err(error) => {
								let _ = player.close();
								return Err(error);
							}
						};
						return Ok(Self::Audio {
							player: Box::new(Some(player)),
							analysis,
						});
					}
					Err(error) => error,
				};
				Err(Error::with_kind(
					video_error.kind(),
					format!("Viewer could not open media (video: {video_error}, audio: {audio_error})"),
				))
			}
		}
	}

	fn has_visual_content(&self) -> bool {
		matches!(
			self,
			Self::Image { .. } | Self::Video { .. } | Self::Live { .. } | Self::Workspace
		)
	}

	fn mode_name(&self) -> &'static str {
		match self {
			Self::Image { .. } => "Image",
			Self::Video { .. } => "Video",
			Self::Audio { .. } => "Audio",
			Self::Live { .. } => "Live",
			Self::Workspace => "Workspace",
			Self::Empty => "Empty",
		}
	}

	fn has_timeline(&self) -> bool {
		matches!(self, Self::Video { .. } | Self::Audio { .. })
	}

	fn content_size(&self) -> Option<(u32, u32)> {
		match self {
			Self::Image { texture, .. } | Self::Live { texture, .. } => texture
				.as_ref()
				.as_ref()
				.map(|t| (t.width() as u32, t.height() as u32)),
			Self::Video { player } => player
				.as_ref()
				.as_ref()
				.and_then(|p| p.info().map(|info| (info.width(), info.height()))),
			_ => None,
		}
	}

	fn update(&mut self) -> Result<()> {
		match self {
			Self::Video { player } => {
				if let Some(player) = player.as_mut() {
					// Bound catch-up after seeks, window stalls, or resize.
					player.tick(4)?;
				}
			}
			Self::Audio { player, .. } => {
				if let Some(player) = player.as_ref() {
					player.check_playback()?;
				}
			}
			_ => {}
		}
		Ok(())
	}

	fn update_live_texture(&mut self, source: Option<&Texture>, nav: &mut Navigation) -> Result<()> {
		let previous = self.content_size();
		if let Self::Live { texture, .. } = self {
			**texture = source.cloned();
			if let Some((width, height)) = self.content_size()
				&& previous != Some((width, height))
			{
				nav.set_content_size(width as f32, height as f32)?;
				nav.fit_to_window()?;
			}
		}
		Ok(())
	}

	fn handle_event(
		&mut self,
		ev: &crate::input::types::InputEvent,
		config: &ViewerConfig,
	) -> Result<()> {
		if ev.kind != InputEventKind::KeyDown || ev.key_repeat {
			return Ok(());
		}
		match self {
			Self::Image { channel_mode, .. } | Self::Live { channel_mode, .. } => {
				image_mode::handle_event(ev, channel_mode, config);
			}
			Self::Video { .. } | Self::Audio { .. } if ev.key == Key::Space => {
				self.toggle_play()?;
			}
			_ => {}
		}
		Ok(())
	}

	fn close(&mut self) -> Result<()> {
		match self {
			Self::Video { player } => player
				.as_mut()
				.as_mut()
				.map_or(Ok(()), |player| player.close()),
			Self::Audio { player, .. } => {
				if let Some(player) = player.as_mut().as_mut() {
					player.close()?;
				}
				Ok(())
			}
			Self::Image { .. } | Self::Live { .. } | Self::Workspace | Self::Empty => Ok(()),
		}
	}

	fn audio_player(&self) -> Option<&crate::AudioPlayer> {
		match self {
			Self::Video { player } => player.as_ref().as_ref().and_then(|player| player.audio()),
			Self::Audio { player, .. } => player.as_ref().as_ref(),
			_ => None,
		}
	}

	fn pause_playback(&mut self) -> Result<()> {
		match self {
			Self::Video { player } => player
				.as_mut()
				.as_mut()
				.map_or(Ok(()), |player| player.pause()),
			Self::Audio { player, .. } => {
				if let Some(player) = player.as_ref() {
					player.pause();
				}
				Ok(())
			}
			_ => Ok(()),
		}
	}

	pub(crate) fn position_us(&self) -> u64 {
		match self {
			Self::Video { player } => player
				.as_ref()
				.as_ref()
				.and_then(|player| player.position_us().ok())
				.unwrap_or(0),
			Self::Audio { player, .. } => player.as_ref().as_ref().map_or(0, |p| p.position_us()),
			_ => 0,
		}
	}

	pub(crate) fn duration_us(&self) -> u64 {
		match self {
			Self::Video { player } => player.as_ref().as_ref().map_or(0, |p| p.duration_us()),
			Self::Audio { player, .. } => player.as_ref().as_ref().map_or(0, |p| p.duration_us()),
			_ => 0,
		}
	}

	#[allow(dead_code)]
	pub(crate) fn is_playing(&self) -> bool {
		match self {
			Self::Video { player } => player.as_ref().as_ref().is_some_and(|p| p.is_playing()),
			Self::Audio { player, .. } => player.as_ref().as_ref().is_some_and(|p| p.is_playing()),
			_ => false,
		}
	}

	#[allow(dead_code)]
	pub(crate) fn toggle_play(&mut self) -> Result<()> {
		match self {
			Self::Video { player } => {
				if let Some(p) = player.as_mut().as_mut() {
					if p.is_playing() { p.pause() } else { p.play() }
				} else {
					Ok(())
				}
			}
			Self::Audio { player, .. } => {
				if let Some(p) = player.as_mut().as_mut() {
					if p.is_playing() {
						p.pause();
						Ok(())
					} else {
						p.play()
					}
				} else {
					Ok(())
				}
			}
			_ => Ok(()),
		}
	}

	/// Donor temporal step: one video frame or five seconds of audio, paused.
	pub(crate) fn step_temporal(&mut self, steps: i32) -> Result<()> {
		match self {
			Self::Video { player } => {
				if let Some(player) = player.as_mut() {
					player.step_frames(steps)?;
				}
			}
			Self::Audio { player, .. } => {
				if let Some(player) = player.as_mut() {
					player.pause();
					let target = (i128::from(player.position_us()) + i128::from(steps) * 5_000_000)
						.clamp(0, i128::from(player.duration_us())) as u64;
					player.seek(target)?;
				}
			}
			_ => {}
		}
		Ok(())
	}

	pub(crate) fn seek_fraction(&mut self, fraction: f32) -> Result<()> {
		let fraction = fraction.clamp(0.0, 1.0);
		let dur = self.duration_us();
		if dur == 0 {
			return Ok(());
		}
		let target = (dur as f64 * fraction as f64) as u64;
		match self {
			Self::Video { player } => {
				player
					.as_mut()
					.as_mut()
					.map_or(Ok(()), |p| match p.seek_us(target) {
						Err(error) if p.current_frame().is_ok() => {
							crate::log_warn!(crate::LogComponent::VIDEO, "Viewer seek failed: {error}");
							Ok(())
						}
						result => result,
					})
			}
			Self::Audio { player, .. } => {
				if let Some(p) = player.as_mut().as_mut() {
					p.seek(target)
				} else {
					Ok(())
				}
			}
			_ => Ok(()),
		}
	}
}