Skip to main content

rust_glass/
app.rs

1//! Window host: event loop, surface, clipboard, input method and the bridge
2//! to screen readers. Draws only when something changes; an idle window uses
3//! no CPU or GPU time.
4
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7
8use winit::application::ApplicationHandler;
9use winit::dpi::{LogicalPosition, LogicalSize, PhysicalSize};
10use winit::event::{ElementState, Ime, MouseButton, MouseScrollDelta, WindowEvent};
11use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy};
12use winit::keyboard::{Key as WKey, NamedKey};
13use winit::window::{CursorIcon, Window, WindowId};
14
15use crate::context::{Context, Cursor, HostCommand};
16use crate::geometry::{Rect, vec2};
17pub use crate::gpu::FrameStats;
18use crate::gpu::{Gpu, Renderer};
19use crate::input::{Event, Key, Modifiers};
20
21/// Timings of recent frames, passed to [`App::update`].
22#[derive(Clone, Copy, Debug, Default)]
23pub struct FrameInfo {
24    /// Time spent in UI code and building the draw list, in milliseconds.
25    pub ui_ms: f32,
26    /// Time spent sending the frame to the GPU, in milliseconds.
27    pub encode_ms: f32,
28    /// What the renderer did.
29    pub gpu: FrameStats,
30    /// Time between frames while animating, in milliseconds.
31    pub interval_ms: f32,
32}
33
34/// Your application. [`run`] calls it to draw each frame.
35pub trait App {
36    /// Called once, before the first frame. Load images here.
37    fn setup(&mut self, _ctx: &mut Context) {}
38    /// Describes the whole interface for this frame. Runs only when something
39    /// changed or an animation is running.
40    fn update(&mut self, ctx: &mut Context, info: &FrameInfo);
41    /// Called when a file is dropped on the window.
42    fn file_dropped(&mut self, _ctx: &mut Context, _path: &std::path::Path) {}
43}
44
45/// Settings of the window opened by [`run`].
46#[derive(Clone, Debug)]
47pub struct Options {
48    /// Window title.
49    pub title: String,
50    /// Initial size in points. The window is made smaller if the screen is.
51    pub size: (f32, f32),
52    /// Smallest size in points.
53    pub min_size: (f32, f32),
54    /// Wait for the display refresh before showing a frame.
55    pub vsync: bool,
56    /// Prefer the integrated GPU on machines with two.
57    pub low_power: bool,
58}
59
60impl Default for Options {
61    fn default() -> Self {
62        Self {
63            title: "rust-glass".into(),
64            size: (1180.0, 780.0),
65            min_size: (480.0, 360.0),
66            vsync: true,
67            low_power: true,
68        }
69    }
70}
71
72/// Runs one frame of UI code, again when sizes were guessed.
73pub(crate) fn run_ui(
74    ctx: &mut Context,
75    app: &mut dyn App,
76    info: &FrameInfo,
77    size: crate::geometry::Vec2,
78    ppp: f32,
79    time: f64,
80    events: &[Event],
81) {
82    ctx.begin_frame(size, ppp, time, events);
83    app.update(ctx, info);
84    ctx.end_frame();
85    let mut tries = 0;
86    while ctx.wants_relayout() && tries < 3 {
87        tries += 1;
88        ctx.begin_frame(size, ppp, time, &[]);
89        app.update(ctx, info);
90        ctx.end_frame();
91    }
92    if ctx.wants_relayout() {
93        ctx.request_repaint();
94    }
95}
96
97struct Live {
98    window: Arc<Window>,
99    gpu: Gpu,
100    surface: wgpu::Surface<'static>,
101    config: wgpu::SurfaceConfiguration,
102    renderer: Renderer,
103    cursor: Cursor,
104    access: accesskit_winit::Adapter,
105    /// Caret rectangle given to the input method, `None` while no field has focus.
106    ime: Option<Rect>,
107}
108
109struct Host<A: App> {
110    app: A,
111    ctx: Context,
112    options: Options,
113    live: Option<Live>,
114    proxy: EventLoopProxy<accesskit_winit::Event>,
115    events: Vec<Event>,
116    start: Instant,
117    last: Instant,
118    info: FrameInfo,
119    clipboard: Option<arboard::Clipboard>,
120    redraw: bool,
121    was_animating: bool,
122    error: Option<String>,
123}
124
125/// Opens a window and runs `app` until the window closes.
126///
127/// # Errors
128///
129/// Returns an error when the window or the GPU cannot be set up.
130pub fn run(options: Options, app: impl App + 'static) -> Result<(), String> {
131    let start = Instant::now();
132    let el = EventLoop::with_user_event().build().map_err(|e| e.to_string())?;
133    let mut host = Host {
134        app,
135        ctx: Context::new(),
136        options,
137        live: None,
138        proxy: el.create_proxy(),
139        events: Vec::new(),
140        start,
141        last: Instant::now(),
142        info: FrameInfo::default(),
143        clipboard: None,
144        redraw: true,
145        was_animating: false,
146        error: None,
147    };
148    el.run_app(&mut host).map_err(|e| e.to_string())?;
149    match host.error {
150        Some(e) => Err(e),
151        None => Ok(()),
152    }
153}
154
155impl<A: App> Host<A> {
156    fn create(&mut self, el: &ActiveEventLoop) -> Result<Live, String> {
157        let o = &self.options;
158        let attrs = Window::default_attributes()
159            .with_title(&o.title)
160            .with_inner_size(LogicalSize::new(o.size.0, o.size.1))
161            .with_min_inner_size(LogicalSize::new(o.min_size.0, o.min_size.1))
162            // Shown after the first frame, so there is no flash.
163            .with_visible(false);
164        let window = Arc::new(el.create_window(attrs).map_err(|e| e.to_string())?);
165        // Must exist before the window is shown.
166        let access = accesskit_winit::Adapter::with_event_loop_proxy(el, &window, self.proxy.clone());
167        fit_on_screen(&window);
168        let instance = Gpu::instance();
169        let surface = instance.create_surface(window.clone()).map_err(|e| e.to_string())?;
170        let gpu = Gpu::new(instance, Some(&surface), o.low_power)?;
171        let caps = surface.get_capabilities(&gpu.adapter);
172        let format = caps
173            .formats
174            .iter()
175            .copied()
176            .find(|f| matches!(f, wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Rgba8Unorm))
177            .unwrap_or(caps.formats[0]);
178        let size = window.inner_size();
179        let mut config = surface
180            .get_default_config(&gpu.adapter, size.width.max(1), size.height.max(1))
181            .ok_or("the surface is not supported by the adapter")?;
182        config.format = format;
183        config.present_mode =
184            if o.vsync { wgpu::PresentMode::AutoVsync } else { wgpu::PresentMode::AutoNoVsync };
185        config.desired_maximum_frame_latency = 1;
186        surface.configure(&gpu.device, &config);
187        let renderer = Renderer::new(&gpu, format);
188        log::info!("rendering on {}", gpu.describe());
189        Ok(Live { window, gpu, surface, config, renderer, cursor: Cursor::Default, access, ime: None })
190    }
191
192    fn frame(&mut self) {
193        let Some(live) = &mut self.live else { return };
194        let PhysicalSize { width, height } = live.window.inner_size();
195        if width == 0 || height == 0 {
196            return;
197        }
198        if (width, height) != (live.config.width, live.config.height) {
199            live.config.width = width;
200            live.config.height = height;
201            live.surface.configure(&live.gpu.device, &live.config);
202        }
203        let now = Instant::now();
204        if self.was_animating {
205            let iv = (now - self.last).as_secs_f32() * 1000.0;
206            self.info.interval_ms =
207                if self.info.interval_ms == 0.0 { iv } else { self.info.interval_ms * 0.9 + iv * 0.1 };
208        }
209        self.last = now;
210
211        let stats = live.renderer.poll_stats();
212        self.ctx.apply_stats(&stats);
213        let ppp = live.window.scale_factor() as f32;
214        let size = vec2(width as f32, height as f32) / ppp;
215        let events = std::mem::take(&mut self.events);
216        let time = (now - self.start).as_secs_f64();
217        run_ui(&mut self.ctx, &mut self.app, &self.info, size, ppp, time, &events);
218        if self.ctx.accessibility() {
219            let (ctx, title) = (&self.ctx, &self.options.title);
220            live.access.update_if_active(|| ctx.access_update(title));
221        }
222        if live.ime != self.ctx.ime_area {
223            match self.ctx.ime_area {
224                Some(r) => {
225                    if live.ime.is_none() {
226                        live.window.set_ime_allowed(true);
227                    }
228                    live.window.set_ime_cursor_area(
229                        LogicalPosition::new(r.min.x, r.min.y),
230                        LogicalSize::new(r.width().max(1.0), r.height().max(1.0)),
231                    );
232                }
233                None => live.window.set_ime_allowed(false),
234            }
235            live.ime = self.ctx.ime_area;
236        }
237        let ui_done = Instant::now();
238        let smooth = |old: f32, new: f32| if old == 0.0 { new } else { old * 0.9 + new * 0.1 };
239        self.info.ui_ms = smooth(self.info.ui_ms, (ui_done - now).as_secs_f32() * 1000.0);
240
241        for u in self.ctx.uploads.drain(..) {
242            let id = live.renderer.add_image(u.w, u.h, &u.rgba);
243            debug_assert_eq!(id, u.id);
244        }
245        for id in self.ctx.removed_images.drain(..) {
246            live.renderer.remove_image(id);
247        }
248        live.renderer.upload_atlas(&mut self.ctx.text.uploads);
249
250        use wgpu::CurrentSurfaceTexture as C;
251        let frame = match live.surface.get_current_texture() {
252            C::Success(t) => t,
253            C::Suboptimal(t) => {
254                // Use it now, reconfigure on the next frame.
255                live.config.width = 0;
256                t
257            }
258            C::Outdated | C::Lost => {
259                live.surface.configure(&live.gpu.device, &live.config);
260                self.redraw = true;
261                return;
262            }
263            _ => {
264                self.redraw = !live.window.is_minimized().unwrap_or(false);
265                return;
266            }
267        };
268        let enc = Instant::now();
269        let view = frame.texture.create_view(&Default::default());
270        live.renderer.render(&self.ctx.paint.data, &view, width, height);
271        live.window.pre_present_notify();
272        live.gpu.queue.present(frame);
273        self.info.encode_ms = smooth(self.info.encode_ms, enc.elapsed().as_secs_f32() * 1000.0);
274        self.info.gpu = live.renderer.frame_stats;
275
276        if live.cursor != self.ctx.cursor {
277            live.cursor = self.ctx.cursor;
278            live.window.set_cursor(match live.cursor {
279                Cursor::Default => CursorIcon::Default,
280                Cursor::Pointer => CursorIcon::Pointer,
281                Cursor::Text => CursorIcon::Text,
282                Cursor::Grab => CursorIcon::Default,
283                Cursor::ResizeHorizontal => CursorIcon::EwResize,
284                Cursor::NotAllowed => CursorIcon::NotAllowed,
285            });
286        }
287        self.was_animating = self.ctx.wants_repaint();
288        self.redraw |= self.was_animating;
289    }
290
291    fn key(&mut self, k: &WKey) -> Option<Key> {
292        Some(match k {
293            WKey::Named(n) => match n {
294                NamedKey::Enter => Key::Enter,
295                NamedKey::Escape => Key::Escape,
296                NamedKey::Tab => Key::Tab,
297                NamedKey::Space => Key::Space,
298                NamedKey::Backspace => Key::Backspace,
299                NamedKey::Delete => Key::Delete,
300                NamedKey::ArrowLeft => Key::Left,
301                NamedKey::ArrowRight => Key::Right,
302                NamedKey::ArrowUp => Key::Up,
303                NamedKey::ArrowDown => Key::Down,
304                NamedKey::Home => Key::Home,
305                NamedKey::End => Key::End,
306                NamedKey::PageUp => Key::PageUp,
307                NamedKey::PageDown => Key::PageDown,
308                _ => return None,
309            },
310            WKey::Character(s) => Key::Char(s.chars().next()?.to_ascii_lowercase()),
311            _ => return None,
312        })
313    }
314}
315
316impl<A: App> ApplicationHandler<accesskit_winit::Event> for Host<A> {
317    fn user_event(&mut self, _: &ActiveEventLoop, ev: accesskit_winit::Event) {
318        use accesskit_winit::WindowEvent as W;
319        match ev.window_event {
320            W::InitialTreeRequested => self.ctx.set_accessibility(true),
321            W::ActionRequested(req) => {
322                if let Some((id, a)) = crate::accessibility::from_accesskit(&req) {
323                    self.events.push(Event::Access(id, a));
324                }
325            }
326            W::AccessibilityDeactivated => self.ctx.set_accessibility(false),
327        }
328        self.redraw = true;
329    }
330
331    fn resumed(&mut self, el: &ActiveEventLoop) {
332        if self.live.is_some() {
333            return;
334        }
335        match self.create(el) {
336            Ok(l) => {
337                self.live = Some(l);
338                self.app.setup(&mut self.ctx);
339                self.frame();
340                if let Some(l) = &self.live {
341                    l.window.set_visible(true);
342                }
343                self.redraw = true;
344            }
345            Err(e) => {
346                self.error = Some(e);
347                el.exit();
348            }
349        }
350    }
351
352    fn window_event(&mut self, el: &ActiveEventLoop, _: WindowId, ev: WindowEvent) {
353        if let Some(l) = &mut self.live {
354            l.access.process_event(&l.window, &ev);
355        }
356        let ppp = self.live.as_ref().map_or(1.0, |l| l.window.scale_factor());
357        let mut dirty = true;
358        match ev {
359            WindowEvent::CloseRequested => {
360                el.exit();
361                return;
362            }
363            WindowEvent::RedrawRequested => {
364                self.redraw = false;
365                self.frame();
366                dirty = false;
367            }
368            WindowEvent::CursorMoved { position, .. } => {
369                let p = position.to_logical::<f32>(ppp);
370                self.events.push(Event::PointerMoved(vec2(p.x, p.y)));
371            }
372            WindowEvent::CursorLeft { .. } => self.events.push(Event::PointerLeft),
373            WindowEvent::MouseInput { state, button, .. } => match (state, button) {
374                (ElementState::Pressed, MouseButton::Left) => self.events.push(Event::PointerDown),
375                (ElementState::Released, MouseButton::Left) => self.events.push(Event::PointerUp),
376                (ElementState::Pressed, MouseButton::Right) => self.events.push(Event::SecondaryDown),
377                _ => dirty = false,
378            },
379            WindowEvent::Touch(t) => {
380                let p = t.location.to_logical::<f32>(ppp);
381                self.events.push(Event::PointerMoved(vec2(p.x, p.y)));
382                match t.phase {
383                    winit::event::TouchPhase::Started => self.events.push(Event::PointerDown),
384                    winit::event::TouchPhase::Moved => {}
385                    _ => {
386                        self.events.push(Event::PointerUp);
387                        self.events.push(Event::PointerLeft);
388                    }
389                }
390            }
391            WindowEvent::MouseWheel { delta, .. } => {
392                let d = match delta {
393                    MouseScrollDelta::LineDelta(x, y) => vec2(x, y) * 56.0,
394                    MouseScrollDelta::PixelDelta(p) => {
395                        let p = p.to_logical::<f32>(ppp);
396                        vec2(p.x, p.y)
397                    }
398                };
399                self.events.push(Event::Scroll(d));
400            }
401            WindowEvent::ModifiersChanged(m) => {
402                let s = m.state();
403                self.events.push(Event::Modifiers(Modifiers {
404                    shift: s.shift_key(),
405                    ctrl: s.control_key(),
406                    alt: s.alt_key(),
407                    command: if cfg!(target_os = "macos") { s.super_key() } else { s.control_key() },
408                }));
409            }
410            WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Pressed => {
411                let m = self.ctx.input.modifiers;
412                if let Some(k) = self.key(&event.logical_key) {
413                    if k == Key::Char('v') && m.command {
414                        if self.clipboard.is_none() {
415                            self.clipboard = arboard::Clipboard::new().ok();
416                        }
417                        if let Some(t) = self.clipboard.as_mut().and_then(|c| c.get_text().ok()) {
418                            self.events.push(Event::Paste(t));
419                        }
420                    } else {
421                        self.events.push(Event::Key(k));
422                    }
423                }
424                if !m.command
425                    && let Some(t) = &event.text
426                    && !t.chars().all(char::is_control)
427                {
428                    self.events.push(Event::Text(t.to_string()));
429                }
430            }
431            WindowEvent::Ime(Ime::Commit(t)) => {
432                self.events.push(Event::Preedit(String::new(), None));
433                self.events.push(Event::Text(t));
434            }
435            WindowEvent::Ime(Ime::Preedit(t, c)) => self.events.push(Event::Preedit(t, c)),
436            WindowEvent::Ime(Ime::Disabled) => self.events.push(Event::Preedit(String::new(), None)),
437            WindowEvent::Focused(f) => self.events.push(Event::Focus(f)),
438            WindowEvent::DroppedFile(p) => self.app.file_dropped(&mut self.ctx, &p),
439            WindowEvent::Resized(_) | WindowEvent::ScaleFactorChanged { .. } => {}
440            WindowEvent::Occluded(false) | WindowEvent::ThemeChanged(_) => {}
441            _ => dirty = false,
442        }
443        self.redraw |= dirty;
444        for c in std::mem::take(&mut self.ctx.host_commands) {
445            match c {
446                HostCommand::Copy(s) => {
447                    if self.clipboard.is_none() {
448                        self.clipboard = arboard::Clipboard::new().ok();
449                    }
450                    if let Some(cb) = &mut self.clipboard {
451                        let _ = cb.set_text(s);
452                    }
453                }
454                HostCommand::OpenUrl(u) => open_url(&u),
455                HostCommand::Close => el.exit(),
456            }
457        }
458    }
459
460    fn about_to_wait(&mut self, el: &ActiveEventLoop) {
461        let Some(live) = &mut self.live else { return };
462        if self.redraw {
463            live.window.request_redraw();
464            el.set_control_flow(ControlFlow::Wait);
465            return;
466        }
467        // Nothing to draw, but measurements may still be on their way.
468        if live.renderer.stats_pending() {
469            let stats = live.renderer.poll_stats();
470            if self.ctx.apply_stats(&stats) {
471                live.window.request_redraw();
472            }
473            el.set_control_flow(ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(8)));
474        } else {
475            el.set_control_flow(ControlFlow::Wait);
476        }
477    }
478}
479
480/// Center the window on its monitor, smaller if it would not fit.
481fn fit_on_screen(window: &Window) {
482    let Some(m) = window.current_monitor().or_else(|| window.primary_monitor()) else { return };
483    let (area, at) = (m.size(), m.position());
484    // Room for a taskbar or dock and the title bar.
485    let reserve = (96.0 * m.scale_factor()) as u32;
486    let size = window.inner_size();
487    let w = size.width.min(area.width.saturating_sub(reserve / 4));
488    let h = size.height.min(area.height.saturating_sub(reserve));
489    if (w, h) != (size.width, size.height) {
490        let _ = window.request_inner_size(PhysicalSize::new(w, h));
491    }
492    let x = at.x + (area.width.saturating_sub(w) / 2) as i32;
493    let y = at.y + (area.height.saturating_sub(h + reserve / 2) / 3) as i32;
494    window.set_outer_position(winit::dpi::PhysicalPosition::new(x, y));
495}
496
497fn open_url(u: &str) {
498    if !(u.starts_with("https://") || u.starts_with("http://")) {
499        return;
500    }
501    #[cfg(target_os = "windows")]
502    let r = std::process::Command::new("explorer").arg(u).spawn();
503    #[cfg(target_os = "macos")]
504    let r = std::process::Command::new("open").arg(u).spawn();
505    #[cfg(not(any(target_os = "windows", target_os = "macos")))]
506    let r = std::process::Command::new("xdg-open").arg(u).spawn();
507    if let Err(e) = r {
508        log::warn!("could not open {u}: {e}");
509    }
510}