zaxis 0.0.1

An event-driven immediate mode GUI for desktop tools
Documentation
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
//! Single-window desktop runner. The low-level Context and Renderer remain available.

use crate::{Context, PresentationMode, RenderError, RenderStatus, Renderer};
use std::{
    error::Error,
    fmt,
    sync::Arc,
    time::{Duration, Instant},
};
use winit::{
    application::ApplicationHandler,
    dpi::LogicalSize,
    event::WindowEvent,
    event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
    window::{CursorIcon, Window, WindowAttributes, WindowId},
};

/// Application state lives here, independently of the native window and GPU.
pub trait App {
    /// Build the UI on each redraw. Do not call `Context::run` yourself.
    /// Widgets request follow-up frames automatically. For timers and animations,
    /// use `Context::request_repaint_after`; the runner sleeps between redraws.
    fn update(&mut self, context: &mut Context, frame: &mut Frame<'_>);
}

/// Native window access and application shutdown during an update.
pub struct Frame<'a> {
    window: &'a Arc<Window>,
    close_requested: &'a mut bool,
}

impl Frame<'_> {
    /// Native window for changing the title, requesting redraws, or cloning its
    /// Arc into a background worker that needs to wake the sleeping event loop.
    pub fn window(&self) -> &Arc<Window> {
        self.window
    }

    /// Exit after the current frame has been presented successfully.
    pub fn close(&mut self) {
        *self.close_requested = true;
    }
}

/// Native window configuration. Sizes in `WindowAttributes` may be logical or physical.
/// On macOS the runner always enables system decorations for native controls and resizing.
#[derive(Debug, Clone)]
pub struct RunOptions {
    pub window_attributes: WindowAttributes,
    pub presentation_mode: PresentationMode,
}

impl Default for RunOptions {
    fn default() -> Self {
        Self {
            window_attributes: Window::default_attributes()
                .with_title("zaxis")
                .with_inner_size(LogicalSize::new(860.0, 560.0)),
            presentation_mode: PresentationMode::default(),
        }
    }
}

impl RunOptions {
    /// Request native rounded corners and the system shadow on Windows 11.
    /// Applies to undecorated windows as well. Maximized/snapped windows follow
    /// the OS policy. On other platforms this leaves window attributes unchanged.
    /// Call after setting `window_attributes`.
    pub fn with_rounded_corners(mut self, rounded: bool) -> Self {
        #[cfg(target_os = "windows")]
        {
            use winit::platform::windows::{CornerPreference, WindowAttributesExtWindows};
            self.window_attributes = self
                .window_attributes
                .with_undecorated_shadow(rounded)
                .with_corner_preference(if rounded {
                    CornerPreference::Round
                } else {
                    CornerPreference::DoNotRound
                });
        }
        #[cfg(not(target_os = "windows"))]
        let _ = rounded;
        self
    }
}

/// Open a desktop window and run an application on the main thread until closed.
/// Returns event-loop, window creation, and unrecoverable renderer errors.
/// winit generally permits only one event loop per process.
///
/// ```no_run
/// use zaxis::{App, Context, Frame, Window};
/// struct MyApp;
/// impl App for MyApp {
///     fn update(&mut self, context: &mut Context, _frame: &mut Frame<'_>) {
///         Window::new("Tools").show(context, |ui| { ui.label("Hello"); });
///     }
/// }
/// fn main() -> Result<(), zaxis::RunError> {
///     zaxis::run(MyApp)
/// }
/// ```
pub fn run(app: impl App) -> Result<(), RunError> {
    run_with_options(app, RunOptions::default())
}

/// Run with explicit window attributes and presentation mode. See [`run`].
pub fn run_with_options(app: impl App, options: RunOptions) -> Result<(), RunError> {
    let event_loop = EventLoop::<()>::with_user_event()
        .build()
        .map_err(RunError::EventLoop)?;
    event_loop.set_control_flow(ControlFlow::Wait);
    let proxy = event_loop.create_proxy();
    let mut context = Context::new();
    context.set_image_waker(move || {
        let _ = proxy.send_event(());
    });
    let mut runner = Runner {
        app,
        options,
        context,
        state: None,
        error: None,
        close_requested: false,
    };
    let result = event_loop.run_app(&mut runner).map_err(RunError::EventLoop);
    runner.error.map_or(result, Err)
}

/// An unrecoverable desktop runner failure.
#[derive(Debug)]
pub enum RunError {
    EventLoop(winit::error::EventLoopError),
    Window(winit::error::OsError),
    Render(RenderError),
}

impl fmt::Display for RunError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EventLoop(error) => write!(f, "running the event loop: {error}"),
            Self::Window(error) => write!(f, "creating the window: {error}"),
            Self::Render(error) => error.fmt(f),
        }
    }
}

impl Error for RunError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(match self {
            Self::EventLoop(error) => error,
            Self::Window(error) => error,
            Self::Render(error) => error,
        })
    }
}

struct State {
    window: Arc<Window>,
    renderer: Renderer,
    occluded: bool,
    retry_at: Option<Instant>,
    cursor: CursorIcon,
}

impl State {
    fn visible(&self) -> bool {
        let size = self.window.inner_size();
        !self.occluded
            && self.window.is_minimized() != Some(true)
            && size.width > 0
            && size.height > 0
    }
}

struct Runner<A> {
    app: A,
    options: RunOptions,
    context: Context,
    state: Option<State>,
    error: Option<RunError>,
    close_requested: bool,
}

impl<A: App> Runner<A> {
    fn fail(&mut self, event_loop: &ActiveEventLoop, error: RunError) {
        self.error = Some(error);
        event_loop.exit();
    }

    fn create_state(&mut self, event_loop: &ActiveEventLoop) -> Result<State, RunError> {
        let window = Arc::new(
            event_loop
                .create_window(self.options.window_attributes.clone().with_decorations(
                    cfg!(target_os = "macos") || self.options.window_attributes.decorations,
                ))
                .map_err(RunError::Window)?,
        );
        let renderer = pollster::block_on(Renderer::new_with_presentation_mode(
            Arc::clone(&window),
            self.options.presentation_mode,
        ))
        .map_err(RunError::Render)?;
        let mut limits = self.context.image_limits().clone();
        limits.max_dimension = limits
            .max_dimension
            .min(renderer.max_texture_dimension_2d());
        if limits.max_dimension != self.context.image_limits().max_dimension {
            self.context.set_image_limits(limits);
        }
        self.context
            .set_viewport(window.inner_size(), window.scale_factor());
        window.request_redraw();
        Ok(State {
            window,
            renderer,
            occluded: false,
            retry_at: None,
            cursor: CursorIcon::Default,
        })
    }

    fn handle_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        event: WindowEvent,
    ) -> Result<(), RenderError> {
        let state = self.state.as_mut().unwrap();
        if self.context.native_chrome_press(&event, &state.window) {
            state.window.request_redraw();
            return Ok(());
        }
        let response = self.context.on_window_event(&event);
        match event {
            WindowEvent::CloseRequested => event_loop.exit(),
            WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } => {
                let size = state.window.inner_size();
                self.context.set_viewport(size, state.window.scale_factor());
                state.renderer.resize(size)?;
            }
            WindowEvent::Occluded(value) => {
                state.occluded = value;
                if !value {
                    state.window.request_redraw();
                }
            }
            WindowEvent::RedrawRequested if state.visible() => {
                state.retry_at = None;
                let mut frame = Frame {
                    window: &state.window,
                    close_requested: &mut self.close_requested,
                };
                self.context
                    .run(|context| self.app.update(context, &mut frame));
                self.context.sync_ime(&state.window);
                match state
                    .renderer
                    .render(self.context.draw_data(), self.context.style().background)
                {
                    Ok(RenderStatus::Presented) => {
                        if self.close_requested {
                            event_loop.exit();
                        }
                    }
                    Ok(RenderStatus::Dormant) => {}
                    Ok(RenderStatus::Retry) => {
                        state.retry_at = Some(Instant::now() + Duration::from_millis(16))
                    }
                    Err(RenderError::DeviceLost(_)) => {
                        state.renderer = pollster::block_on(Renderer::new_with_presentation_mode(
                            Arc::clone(&state.window),
                            state.renderer.presentation_mode(),
                        ))?;
                        let mut limits = self.context.image_limits().clone();
                        limits.max_dimension = limits
                            .max_dimension
                            .min(state.renderer.max_texture_dimension_2d());
                        if limits.max_dimension != self.context.image_limits().max_dimension {
                            self.context.set_image_limits(limits);
                        }
                        state.window.request_redraw();
                    }
                    Err(error) => return Err(error),
                }
            }
            _ => {}
        }
        if response.repaint && state.visible() {
            state.window.request_redraw();
        }
        let cursor = self.context.cursor_icon();
        if cursor != state.cursor {
            state.window.set_cursor(cursor);
            state.cursor = cursor;
        }
        Ok(())
    }
}

impl<A: App> ApplicationHandler for Runner<A> {
    fn user_event(&mut self, _event_loop: &ActiveEventLoop, _: ()) {
        if let Some(state) = &self.state {
            if state.visible() {
                state.window.request_redraw();
            }
        }
    }
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if let Some(state) = &mut self.state {
            state.occluded = false;
            self.context.request_repaint();
            state.window.request_redraw();
        } else {
            match self.create_state(event_loop) {
                Ok(state) => self.state = Some(state),
                Err(error) => self.fail(event_loop, error),
            }
        }
    }

    fn suspended(&mut self, event_loop: &ActiveEventLoop) {
        // Drop the surface on platforms that invalidate it on suspension, while
        // preserving both application state and retained UI state.
        self.state = None;
        self.context.on_window_event(&WindowEvent::Focused(false));
        event_loop.set_control_flow(ControlFlow::Wait);
    }

    fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
        if !self
            .state
            .as_ref()
            .is_some_and(|state| state.window.id() == id)
        {
            return;
        }
        if let Err(error) = self.handle_event(event_loop, event) {
            self.fail(event_loop, RunError::Render(error));
        }
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        let Some(state) = &mut self.state else {
            event_loop.set_control_flow(ControlFlow::Wait);
            return;
        };
        let now = Instant::now();
        let moving = state.renderer.presentation_mode() == PresentationMode::Vsync
            && self.context.wants_animation_frame();
        let (redraw, control_flow) = repaint_schedule(
            now,
            state.visible(),
            self.context.needs_repaint_at(now) || moving,
            self.context.next_repaint(),
            state.retry_at,
        );
        if redraw {
            state.window.request_redraw();
        }
        event_loop.set_control_flow(control_flow);
    }
}

fn repaint_schedule(
    now: Instant,
    visible: bool,
    needs_repaint: bool,
    next_repaint: Option<Instant>,
    retry_at: Option<Instant>,
) -> (bool, ControlFlow) {
    if !visible {
        return (false, ControlFlow::Wait);
    }
    // Back off transient surface failures even when the UI requests another frame.
    let redraw = retry_at.map_or(needs_repaint, |deadline| deadline <= now);
    let deadline = retry_at
        .or(next_repaint)
        .filter(|time| !redraw && *time > now);
    (
        redraw,
        deadline.map_or(ControlFlow::Wait, ControlFlow::WaitUntil),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn idle_input_and_animation_schedule_without_polling() {
        let now = Instant::now();
        let later = now + Duration::from_millis(50);
        assert_eq!(
            repaint_schedule(now, true, false, None, None),
            (false, ControlFlow::Wait)
        );
        assert_eq!(
            repaint_schedule(now, true, true, None, None),
            (true, ControlFlow::Wait)
        );
        assert_eq!(
            repaint_schedule(now, true, false, Some(later), None),
            (false, ControlFlow::WaitUntil(later))
        );
        assert_eq!(
            repaint_schedule(later, true, true, Some(later), None),
            (true, ControlFlow::Wait)
        );
    }

    #[test]
    fn retry_backs_off_even_with_dirty_ui_and_expired_animation() {
        let now = Instant::now();
        let retry = now + Duration::from_millis(16);
        assert_eq!(
            repaint_schedule(now, true, true, Some(now), Some(retry)),
            (false, ControlFlow::WaitUntil(retry))
        );
        assert_eq!(
            repaint_schedule(retry, true, false, None, Some(retry)),
            (true, ControlFlow::Wait)
        );
    }

    #[test]
    fn hidden_windows_sleep_even_with_active_motion_and_expired_retry() {
        let now = Instant::now();
        assert_eq!(
            repaint_schedule(now, false, true, Some(now), Some(now)),
            (false, ControlFlow::Wait)
        );
    }

    #[test]
    fn vsync_motion_requests_the_next_present_without_a_second_timer() {
        let now = Instant::now();
        assert_eq!(
            repaint_schedule(now, true, true, Some(now + Duration::from_millis(16)), None),
            (true, ControlFlow::Wait)
        );
    }
}