skenion_runtime/
visual.rs1use std::{
2 error::Error,
3 path::Path,
4 process::{Child, Command},
5 time::{Duration, Instant},
6};
7
8use winit::{
9 application::ApplicationHandler,
10 event::WindowEvent,
11 event_loop::{ActiveEventLoop, EventLoop},
12 window::{Window, WindowAttributes, WindowId},
13};
14
15use crate::{
16 ExecutionPlan,
17 preview_manager::{PreviewHandle, PreviewSpawn},
18 render::{PreviewDocument, write_preview_document},
19};
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum PreviewFrameLimit {
23 Frames(usize),
24 UntilClose,
25}
26
27pub fn run_preview_window(
28 plan: ExecutionPlan,
29 frame_limit: PreviewFrameLimit,
30) -> Result<(), Box<dyn Error>> {
31 let event_loop = EventLoop::new()?;
32 let mut app = PreviewApp::new(plan, frame_limit);
33 event_loop.run_app(&mut app)?;
34 Ok(())
35}
36
37pub(crate) fn spawn_preview_document_handle(
38 document: &PreviewDocument,
39 telemetry_path: &Path,
40 control_state_path: &Path,
41) -> Result<PreviewSpawn, String> {
42 let document_path = write_preview_document(document)?;
43 let child = Command::new(std::env::current_exe().map_err(|error| error.to_string())?)
44 .arg("preview-document")
45 .arg("--document")
46 .arg(&document_path)
47 .arg("--until-close")
48 .arg("--telemetry")
49 .arg(telemetry_path)
50 .arg("--control-state")
51 .arg(control_state_path)
52 .spawn()
53 .map_err(|error| error.to_string())?;
54 Ok(PreviewSpawn::new(
55 Box::new(ChildPreviewHandle { child }),
56 Some(document_path),
57 ))
58}
59
60struct PreviewApp {
61 plan: ExecutionPlan,
62 window: Option<Window>,
63 frame_index: usize,
64 frame_limit: PreviewFrameLimit,
65 last_tick: Instant,
66}
67
68impl PreviewApp {
69 fn new(plan: ExecutionPlan, frame_limit: PreviewFrameLimit) -> Self {
70 Self {
71 plan,
72 window: None,
73 frame_index: 0,
74 frame_limit,
75 last_tick: Instant::now(),
76 }
77 }
78
79 fn window_title(&self) -> String {
80 format!(
81 "Skenion Preview - {} frame {}{} nodes {}",
82 self.plan.graph_id,
83 self.frame_index,
84 self.frame_limit_label(),
85 self.plan.nodes.len()
86 )
87 }
88
89 fn frame_limit_label(&self) -> String {
90 match self.frame_limit {
91 PreviewFrameLimit::Frames(frame_count) => format!("/{frame_count}"),
92 PreviewFrameLimit::UntilClose => " until close".to_owned(),
93 }
94 }
95
96 fn request_redraw(&self) {
97 if let Some(window) = &self.window {
98 window.request_redraw();
99 }
100 }
101
102 fn should_exit_after_redraw(&self) -> bool {
103 match self.frame_limit {
104 PreviewFrameLimit::Frames(frame_count) => self.frame_index >= frame_count.max(1),
105 PreviewFrameLimit::UntilClose => false,
106 }
107 }
108}
109
110impl ApplicationHandler for PreviewApp {
111 fn resumed(&mut self, event_loop: &ActiveEventLoop) {
112 if self.window.is_some() {
113 return;
114 }
115
116 let attributes = WindowAttributes::default()
117 .with_title(self.window_title())
118 .with_inner_size(winit::dpi::LogicalSize::new(960.0, 540.0));
119 match event_loop.create_window(attributes) {
120 Ok(window) => {
121 self.window = Some(window);
122 self.request_redraw();
123 }
124 Err(error) => {
125 eprintln!("failed to create preview window: {error}");
126 event_loop.exit();
127 }
128 }
129 }
130
131 fn window_event(
132 &mut self,
133 event_loop: &ActiveEventLoop,
134 window_id: WindowId,
135 event: WindowEvent,
136 ) {
137 let Some(window) = &self.window else {
138 return;
139 };
140 if window.id() != window_id {
141 return;
142 }
143
144 match event {
145 WindowEvent::CloseRequested => event_loop.exit(),
146 WindowEvent::RedrawRequested => {
147 window.set_title(&self.window_title());
148 self.frame_index += 1;
149 if self.should_exit_after_redraw() {
150 event_loop.exit();
151 } else {
152 self.last_tick = Instant::now();
153 window.request_redraw();
154 }
155 }
156 _ => {}
157 }
158 }
159
160 fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
161 if self.last_tick.elapsed() >= Duration::from_millis(16) {
162 self.request_redraw();
163 }
164 }
165}
166
167struct ChildPreviewHandle {
168 child: Child,
169}
170
171impl PreviewHandle for ChildPreviewHandle {
172 fn pid(&self) -> Option<u32> {
173 Some(self.child.id())
174 }
175
176 fn try_wait(&mut self) -> Result<Option<i32>, String> {
177 self.child
178 .try_wait()
179 .map(|status| status.map(exit_code))
180 .map_err(|error| error.to_string())
181 }
182
183 fn stop(&mut self) -> Result<Option<i32>, String> {
184 self.child.kill().map_err(|error| error.to_string())?;
185 self.child
186 .wait()
187 .map(|status| Some(exit_code(status)))
188 .map_err(|error| error.to_string())
189 }
190}
191
192fn exit_code(status: std::process::ExitStatus) -> i32 {
193 status.code().unwrap_or(-1)
194}