1use std::cell::{Cell, RefCell};
10use std::rc::Rc;
11use std::sync::Arc;
12use std::time::Instant;
13
14use agg_gui::{winit_adapter, App, Modifiers};
15use agg_gui_wgpu::{Gpu, GpuConfig};
16use winit::event::{ElementState, Event, StartCause, WindowEvent};
17use winit::event_loop::{ActiveEventLoop, ControlFlow};
18use winit::window::{Fullscreen, Window};
19
20use crate::bounds::{BoundsAutoSave, SavedBounds, WindowBoundsStore, WindowedSizeTracker};
21use crate::config::{RedrawPolicy, ScreenshotConfig};
22use crate::host::{ExitAction, ShellControl, ShellHost, WindowGeometry};
23use crate::input::{dispatch_touch, shift_held, wheel_delta};
24use crate::paint::{PaintRequest, Painter};
25use crate::screenshot::capture_exhausted;
26use crate::waker::HostWakerGuard;
27use crate::ShellError;
28
29pub(crate) struct ShellLoop<H: ShellHost> {
32 pub(crate) window: Arc<Window>,
33 pub(crate) gpu: Option<Gpu>,
38 pub(crate) gpu_config: GpuConfig,
39 pub(crate) painter: Painter,
40 pub(crate) app: App,
41 pub(crate) host: H,
42 pub(crate) policy: RedrawPolicy,
43 pub(crate) screenshot: Option<ScreenshotConfig>,
44 pub(crate) screenshot_done: bool,
45 pub(crate) screenshot_last_paint: Instant,
49 pub(crate) cursor: (f64, f64),
50 pub(crate) mods: Modifiers,
51 pub(crate) mouse_buttons_down: u32,
52 pub(crate) input_since_frame: bool,
53 pub(crate) pending_resize: Option<(u32, u32)>,
54 pub(crate) bounds_store: Option<Box<dyn WindowBoundsStore>>,
55 pub(crate) bounds_auto: BoundsAutoSave,
56 pub(crate) windowed_size: WindowedSizeTracker,
60 pub(crate) maximized: bool,
61 pub(crate) exit: Rc<Cell<Option<ExitAction>>>,
62 pub(crate) error: Rc<RefCell<Option<ShellError>>>,
63 pub(crate) finished: bool,
64 pub(crate) _waker_guard: HostWakerGuard,
67}
68
69impl<H: ShellHost> ShellLoop<H> {
70 pub(crate) fn handle(&mut self, event: Event<()>, elwt: &ActiveEventLoop) {
71 match event {
72 Event::WindowEvent { event, .. } => self.window_event(event, elwt),
73
74 Event::NewEvents(StartCause::ResumeTimeReached { .. }) => {
80 self.window.request_redraw();
81 }
82
83 Event::UserEvent(()) => {
91 agg_gui::animation::request_draw();
92 }
93
94 Event::AboutToWait => self.about_to_wait(elwt),
95
96 Event::LoopExiting => self.finish(),
97
98 _ => {}
99 }
100 }
101
102 fn window_event(&mut self, event: WindowEvent, elwt: &ActiveEventLoop) {
103 match event {
104 WindowEvent::CloseRequested => {
105 elwt.exit();
106 }
107
108 WindowEvent::Resized(size) if size.width > 0 && size.height > 0 => {
109 self.pending_resize = Some((size.width, size.height));
114 self.maximized = self.window.is_maximized();
115 self.windowed_size.note_resize(
120 (size.width, size.height),
121 self.maximized,
122 self.window.fullscreen().is_some(),
123 );
124 self.notify_geometry();
125 self.window.request_redraw();
126 }
127
128 WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
129 agg_gui::set_device_scale(scale_factor);
130 self.notify_geometry();
131 self.window.request_redraw();
132 }
133
134 WindowEvent::CursorMoved { position, .. } => {
135 self.cursor = (position.x, position.y);
136 self.input_since_frame = true;
137 self.app.on_mouse_move(self.cursor.0, self.cursor.1);
138 winit_adapter::apply_cursor(&self.window, agg_gui::current_cursor_icon());
139 }
140
141 WindowEvent::CursorLeft { .. } => {
142 self.app.on_mouse_leave();
143 }
144
145 WindowEvent::ModifiersChanged(state) => {
146 self.mods = winit_adapter::modifiers(state.state());
147 }
148
149 WindowEvent::MouseInput { state, button, .. } => {
150 let btn = winit_adapter::mouse_button(button);
151 self.input_since_frame = true;
152 let (x, y) = self.cursor;
153 match state {
154 ElementState::Pressed => {
155 self.mouse_buttons_down = self.mouse_buttons_down.saturating_add(1);
156 self.app.on_mouse_down(x, y, btn, self.mods);
157 }
158 ElementState::Released => {
159 self.mouse_buttons_down = self.mouse_buttons_down.saturating_sub(1);
160 self.app.on_mouse_up(x, y, btn, self.mods);
161 }
162 }
163 }
164
165 WindowEvent::MouseWheel { delta, .. } => {
166 self.input_since_frame = true;
167 let (dx, dy) = wheel_delta(delta, shift_held(self.mods));
168 let (x, y) = self.cursor;
169 self.app.on_mouse_wheel_xy_mods(x, y, dx, dy, self.mods);
170 }
171
172 WindowEvent::KeyboardInput {
173 event: key_event, ..
174 } => {
175 self.input_since_frame = true;
176 let Some(key) = winit_adapter::key_event(&key_event, self.mods) else {
177 return;
178 };
179 match key_event.state {
180 ElementState::Pressed => self.app.on_key_down(key, self.mods),
181 ElementState::Released => self.app.on_key_up(key, self.mods),
185 }
186 }
187
188 WindowEvent::Touch(touch) => {
189 self.input_since_frame = true;
190 dispatch_touch(&mut self.app, touch);
191 self.window.request_redraw();
194 }
195
196 WindowEvent::RedrawRequested => {
197 self.paint(elwt);
198 }
199
200 _ => {}
201 }
202 }
203
204 fn about_to_wait(&mut self, elwt: &ActiveEventLoop) {
205 if agg_gui::fullscreen::take_request() {
207 let now_fullscreen = self.window.fullscreen().is_none();
208 self.window
209 .set_fullscreen(now_fullscreen.then_some(Fullscreen::Borderless(None)));
210 agg_gui::fullscreen::set_active(now_fullscreen);
211 self.notify_geometry();
212 self.window.request_redraw();
213 }
214
215 let capture_pending = self.screenshot.is_some() && !self.screenshot_done;
216 let continuous = self.policy == RedrawPolicy::Continuous;
217 let mut painted = false;
218 if capture_pending {
219 painted = self.paint(elwt);
223 if !self.screenshot_done && capture_exhausted(self.screenshot_last_paint.elapsed()) {
224 self.fail(
225 ShellError::Screenshot(format!(
226 "gave up after {:.0}s without a presentable surface",
227 self.screenshot_last_paint.elapsed().as_secs_f64()
228 )),
229 elwt,
230 );
231 }
232 } else if continuous || self.app.wants_draw() {
233 painted = self.paint(elwt);
234 }
235
236 {
237 let mut exit = self.exit.get();
238 let mut control = ShellControl {
239 policy: &mut self.policy,
240 exit: &mut exit,
241 painted,
242 pointer_idle: self.mouse_buttons_down == 0,
243 };
244 self.host.on_idle(&mut self.app, &mut control);
245 self.exit.set(exit);
246 }
247
248 self.save_bounds_if_changed();
249
250 let poll = capture_pending || self.policy == RedrawPolicy::Continuous;
260 if poll || self.app.wants_draw() {
261 elwt.set_control_flow(ControlFlow::Poll);
262 } else if let Some(t) = self.app.next_draw_deadline() {
263 elwt.set_control_flow(ControlFlow::WaitUntil(t));
264 } else {
265 elwt.set_control_flow(ControlFlow::Wait);
266 }
267
268 if self.exit.get().is_some() {
269 elwt.exit();
270 }
271 }
272
273 pub(crate) fn paint(&mut self, elwt: &ActiveEventLoop) -> bool {
276 if let Err(e) = self.recover_lost_device() {
277 self.fail(e, elwt);
278 return false;
279 }
280 let Some(gpu) = self.gpu.as_mut() else {
281 return false;
282 };
283 let capture = self
284 .screenshot
285 .as_ref()
286 .filter(|_| !self.screenshot_done)
287 .cloned();
288 let outcome = self.painter.paint(
289 gpu,
290 &self.window,
291 &mut self.app,
292 &mut self.host,
293 PaintRequest {
294 pending_resize: &mut self.pending_resize,
295 input_since_last_frame: self.input_since_frame,
296 capture: capture.as_ref(),
297 },
298 );
299 match outcome {
300 Ok(outcome) => {
301 if outcome.painted {
302 self.input_since_frame = false;
303 self.screenshot_last_paint = Instant::now();
304 }
305 if outcome.captured {
306 self.screenshot_done = true;
307 elwt.exit();
308 }
309 outcome.painted
310 }
311 Err(e) => {
312 self.fail(e, elwt);
313 false
314 }
315 }
316 }
317
318 fn recover_lost_device(&mut self) -> Result<(), ShellError> {
327 if !self.gpu.as_ref().is_some_and(|g| g.device_lost()) {
328 return Ok(());
329 }
330 log::warn!("agg-gui-shell: wgpu device lost — rebuilding device and surface");
331 drop(self.gpu.take());
334 let size = self.window.inner_size();
335 let gpu = Gpu::new(
336 Arc::clone(&self.window),
337 (size.width.max(1), size.height.max(1)),
338 self.gpu_config,
339 )
340 .map_err(ShellError::Gpu)?;
341 self.painter.rebuild(&gpu);
342 self.host.on_gpu_rebuilt(&mut self.app, &gpu);
343 self.gpu = Some(gpu);
344 agg_gui::animation::request_draw();
347 Ok(())
348 }
349
350 fn fail(&mut self, error: ShellError, elwt: &ActiveEventLoop) {
353 if let Ok(mut slot) = self.error.try_borrow_mut() {
354 if slot.is_none() {
355 *slot = Some(error);
356 }
357 }
358 elwt.exit();
359 }
360
361 fn geometry(&self) -> WindowGeometry {
362 let size = self.window.inner_size();
363 WindowGeometry {
364 width: size.width,
365 height: size.height,
366 maximized: self.maximized,
367 fullscreen: self.window.fullscreen().is_some(),
368 scale_factor: self.window.scale_factor(),
369 }
370 }
371
372 fn notify_geometry(&mut self) {
373 let geometry = self.geometry();
374 self.host.on_geometry_changed(geometry);
375 }
376
377 fn current_bounds(&self) -> SavedBounds {
378 let (width, height) = self.windowed_size.size();
379 SavedBounds {
380 width,
381 height,
382 maximized: self.maximized,
383 }
384 }
385
386 fn save_bounds_if_changed(&mut self) {
390 let Some(store) = self.bounds_store.as_ref() else {
391 return;
392 };
393 let bounds = self.current_bounds();
394 if self
395 .bounds_auto
396 .should_save(self.mouse_buttons_down == 0, bounds)
397 {
398 store.save(bounds);
399 }
400 }
401
402 fn finish(&mut self) {
404 if self.finished {
405 return;
406 }
407 self.finished = true;
408 if let Some(store) = self.bounds_store.as_ref() {
409 store.save(self.current_bounds());
414 }
415 self.host.on_exit(&mut self.app);
416 }
417}
418
419pub struct ShellInit<'a> {
423 pub(crate) window: &'a Arc<Window>,
424 pub(crate) gpu: &'a Gpu,
425 pub(crate) restored_bounds: Option<SavedBounds>,
426}
427
428impl ShellInit<'_> {
429 pub fn window(&self) -> &Arc<Window> {
432 self.window
433 }
434
435 pub fn gpu(&self) -> &Gpu {
438 self.gpu
439 }
440
441 pub fn size(&self) -> (u32, u32) {
443 (self.gpu.config().width, self.gpu.config().height)
444 }
445
446 pub fn restored_bounds(&self) -> Option<SavedBounds> {
450 self.restored_bounds
451 }
452
453 pub fn device_scale(&self) -> f64 {
455 agg_gui::device_scale()
456 }
457}