Skip to main content

iced_winit/
lib.rs

1//! A windowing shell for Iced, on top of [`winit`].
2//!
3//! ![The native path of the Iced ecosystem](https://github.com/iced-rs/iced/blob/0525d76ff94e828b7b21634fa94a747022001c83/docs/graphs/native.png?raw=true)
4//!
5//! `iced_winit` offers some convenient abstractions on top of [`iced_runtime`]
6//! to quickstart development when using [`winit`].
7//!
8//! It exposes a renderer-agnostic [`Program`] trait that can be implemented
9//! and then run with a simple call. The use of this trait is optional.
10//!
11//! Additionally, a [`conversion`] module is available for users that decide to
12//! implement a custom event loop.
13//!
14//! [`iced_runtime`]: https://github.com/iced-rs/iced/tree/master/runtime
15//! [`winit`]: https://github.com/rust-windowing/winit
16//! [`conversion`]: crate::conversion
17#![doc(
18    html_logo_url = "https://raw.githubusercontent.com/iced-rs/iced/9ab6923e943f784985e9ef9ca28b10278297225d/docs/logo.svg"
19)]
20#![cfg_attr(docsrs, feature(doc_cfg))]
21pub use iced_debug as debug;
22pub use iced_program as program;
23pub use iced_runtime as runtime;
24pub use program::core;
25pub use program::graphics;
26pub use runtime::futures;
27pub use winit;
28
29pub mod clipboard;
30pub mod conversion;
31
32mod error;
33mod proxy;
34mod window;
35
36pub use clipboard::Clipboard;
37pub use error::Error;
38pub use proxy::Proxy;
39
40use crate::core::backend;
41use crate::core::mouse;
42use crate::core::renderer;
43use crate::core::shell;
44use crate::core::theme;
45use crate::core::time::{Duration, Instant};
46use crate::core::widget::operation::{self, Operation};
47use crate::core::{Point, Renderer, Size};
48use crate::futures::futures::channel::mpsc;
49use crate::futures::futures::channel::oneshot;
50use crate::futures::futures::task;
51use crate::futures::futures::{Future, StreamExt};
52use crate::futures::subscription;
53use crate::futures::{Executor, Runtime};
54use crate::graphics::{Compositor, Shell, compositor};
55use crate::runtime::font;
56use crate::runtime::image;
57use crate::runtime::system;
58use crate::runtime::user_interface::{self, UserInterface};
59use crate::runtime::{Action, Task};
60
61use program::Program;
62
63use rustc_hash::FxHashMap;
64use std::borrow::Cow;
65use std::mem::ManuallyDrop;
66use std::slice;
67use std::sync::Arc;
68
69/// Runs a [`Program`] with the provided settings.
70pub fn run<P>(program: P) -> Result<(), Error>
71where
72    P: Program + 'static,
73    P::Theme: theme::Base,
74{
75    use winit::event_loop::EventLoop;
76
77    let boot_span = debug::boot();
78    let settings = program.settings();
79    let window_settings = program.window();
80
81    let event_loop = EventLoop::with_user_event()
82        .build()
83        .expect("Create event loop");
84
85    let backend_settings = backend::Settings::from(&settings);
86    let renderer_settings = renderer::Settings::from(&settings);
87    let display_handle = event_loop.owned_display_handle();
88
89    let (proxy, worker) = Proxy::new(event_loop.create_proxy());
90
91    #[cfg(feature = "debug")]
92    {
93        let proxy = proxy.clone();
94
95        debug::on_hotpatch(move || {
96            proxy.send_action(Action::Reload);
97        });
98    }
99
100    let mut runtime = {
101        let executor = P::Executor::new().map_err(Error::ExecutorCreationFailed)?;
102        executor.spawn(worker);
103
104        Runtime::new(executor, proxy.clone())
105    };
106
107    let (program, task) = runtime.enter(|| program::Instance::new(program));
108    let is_daemon = window_settings.is_none();
109
110    let task = if let Some(window_settings) = window_settings {
111        let mut task = Some(task);
112
113        let (_id, open) = runtime::window::open(window_settings);
114
115        open.then(move |_| task.take().unwrap_or_else(Task::none))
116    } else {
117        task
118    };
119
120    if let Some(stream) = runtime::task::into_stream(task) {
121        runtime.run(stream);
122    }
123
124    runtime.track(subscription::into_recipes(
125        runtime.enter(|| program.subscription().map(Action::Output)),
126    ));
127
128    let (event_sender, event_receiver) = mpsc::unbounded();
129    let (control_sender, control_receiver) = mpsc::unbounded();
130    let (system_theme_sender, system_theme_receiver) = oneshot::channel();
131
132    let instance: std::pin::Pin<Box<dyn Future<Output = ()>>> = Box::pin(run_instance::<P>(
133        program,
134        runtime,
135        proxy.clone(),
136        event_receiver,
137        control_sender,
138        display_handle,
139        is_daemon,
140        backend_settings,
141        renderer_settings,
142        settings.fonts,
143        system_theme_receiver,
144    ));
145
146    let context = task::Context::from_waker(task::noop_waker_ref());
147
148    struct Runner<Message: 'static> {
149        instance: std::pin::Pin<Box<dyn Future<Output = ()>>>,
150        context: task::Context<'static>,
151        id: Option<String>,
152        sender: mpsc::UnboundedSender<Event<Action<Message>>>,
153        receiver: mpsc::UnboundedReceiver<Control>,
154        error: Option<Error>,
155        system_theme: Option<oneshot::Sender<theme::Mode>>,
156
157        #[cfg(target_arch = "wasm32")]
158        canvas: Option<web_sys::HtmlCanvasElement>,
159    }
160
161    let runner = Runner {
162        instance,
163        context,
164        id: settings.id,
165        sender: event_sender,
166        receiver: control_receiver,
167        error: None,
168        system_theme: Some(system_theme_sender),
169
170        #[cfg(target_arch = "wasm32")]
171        canvas: None,
172    };
173
174    boot_span.finish();
175
176    impl<Message> winit::application::ApplicationHandler<Action<Message>> for Runner<Message> {
177        fn resumed(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
178            if let Some(sender) = self.system_theme.take() {
179                let _ = sender.send(
180                    event_loop
181                        .system_theme()
182                        .map(conversion::theme_mode)
183                        .unwrap_or_default(),
184                );
185            }
186        }
187
188        fn new_events(
189            &mut self,
190            event_loop: &winit::event_loop::ActiveEventLoop,
191            cause: winit::event::StartCause,
192        ) {
193            self.process_event(
194                event_loop,
195                Event::EventLoopAwakened(winit::event::Event::NewEvents(cause)),
196            );
197        }
198
199        fn window_event(
200            &mut self,
201            event_loop: &winit::event_loop::ActiveEventLoop,
202            window_id: winit::window::WindowId,
203            event: winit::event::WindowEvent,
204        ) {
205            #[cfg(target_os = "windows")]
206            let is_move_or_resize = matches!(
207                event,
208                winit::event::WindowEvent::Resized(_) | winit::event::WindowEvent::Moved(_)
209            );
210
211            self.process_event(
212                event_loop,
213                Event::EventLoopAwakened(winit::event::Event::WindowEvent { window_id, event }),
214            );
215
216            // TODO: Remove when unnecessary
217            // On Windows, we emulate an `AboutToWait` event after every `Resized` event
218            // since the event loop does not resume during resize interaction.
219            // More details: https://github.com/rust-windowing/winit/issues/3272
220            #[cfg(target_os = "windows")]
221            {
222                if is_move_or_resize {
223                    self.process_event(
224                        event_loop,
225                        Event::EventLoopAwakened(winit::event::Event::AboutToWait),
226                    );
227                }
228            }
229        }
230
231        fn user_event(
232            &mut self,
233            event_loop: &winit::event_loop::ActiveEventLoop,
234            action: Action<Message>,
235        ) {
236            self.process_event(
237                event_loop,
238                Event::EventLoopAwakened(winit::event::Event::UserEvent(action)),
239            );
240        }
241
242        fn received_url(&mut self, event_loop: &winit::event_loop::ActiveEventLoop, url: String) {
243            self.process_event(
244                event_loop,
245                Event::EventLoopAwakened(winit::event::Event::PlatformSpecific(
246                    winit::event::PlatformSpecific::MacOS(winit::event::MacOS::ReceivedUrl(url)),
247                )),
248            );
249        }
250
251        fn about_to_wait(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
252            self.process_event(
253                event_loop,
254                Event::EventLoopAwakened(winit::event::Event::AboutToWait),
255            );
256        }
257    }
258
259    impl<Message> Runner<Message> {
260        fn process_event(
261            &mut self,
262            event_loop: &winit::event_loop::ActiveEventLoop,
263            event: Event<Action<Message>>,
264        ) {
265            if event_loop.exiting() {
266                return;
267            }
268
269            self.sender.start_send(event).expect("Send event");
270
271            loop {
272                let poll = self.instance.as_mut().poll(&mut self.context);
273
274                match poll {
275                    task::Poll::Pending => match self.receiver.try_recv() {
276                        Ok(control) => match control {
277                            Control::ChangeFlow(flow) => {
278                                use winit::event_loop::ControlFlow;
279
280                                match (event_loop.control_flow(), flow) {
281                                    (
282                                        ControlFlow::WaitUntil(current),
283                                        ControlFlow::WaitUntil(new),
284                                    ) if current > Instant::now() && current < new => {}
285                                    (ControlFlow::WaitUntil(current), ControlFlow::Wait)
286                                        if current > Instant::now() => {}
287                                    _ => {
288                                        event_loop.set_control_flow(flow);
289                                    }
290                                }
291                            }
292                            Control::CreateWindow {
293                                id,
294                                settings,
295                                title,
296                                scale_factor,
297                                monitor,
298                                on_open,
299                            } => {
300                                let exit_on_close_request = settings.exit_on_close_request;
301
302                                let visible = settings.visible;
303
304                                #[cfg(target_arch = "wasm32")]
305                                let target = settings.platform_specific.target.clone();
306
307                                let window_attributes = conversion::window_attributes(
308                                    settings,
309                                    &title,
310                                    scale_factor,
311                                    monitor.or(event_loop.primary_monitor()),
312                                    self.id.clone(),
313                                )
314                                .with_visible(false);
315
316                                #[cfg(target_arch = "wasm32")]
317                                let window_attributes = {
318                                    use winit::platform::web::WindowAttributesExtWebSys;
319                                    window_attributes.with_canvas(self.canvas.take())
320                                };
321
322                                log::info!(
323                                    "Window attributes for id `{id:#?}`: {window_attributes:#?}"
324                                );
325
326                                // On macOS, the `position` in `WindowAttributes` represents the "inner"
327                                // position of the window; while on other platforms it's the "outer" position.
328                                // We fix the inconsistency on macOS by positioning the window after creation.
329                                #[cfg(target_os = "macos")]
330                                let mut window_attributes = window_attributes;
331
332                                #[cfg(target_os = "macos")]
333                                let position = window_attributes.position.take();
334
335                                let window = event_loop
336                                    .create_window(window_attributes)
337                                    .expect("Create window");
338
339                                #[cfg(target_os = "macos")]
340                                if let Some(position) = position {
341                                    window.set_outer_position(position);
342                                }
343
344                                #[cfg(target_arch = "wasm32")]
345                                {
346                                    use winit::platform::web::WindowExtWebSys;
347
348                                    let canvas = window.canvas().expect("Get window canvas");
349
350                                    let _ = canvas.set_attribute(
351                                        "style",
352                                        "display: block; width: 100%; height: 100%",
353                                    );
354
355                                    let window = web_sys::window().unwrap();
356                                    let document = window.document().unwrap();
357                                    let body = document.body().unwrap();
358
359                                    let target = target.and_then(|target| {
360                                        body.query_selector(&format!("#{target}"))
361                                            .ok()
362                                            .unwrap_or(None)
363                                    });
364
365                                    match target {
366                                        Some(node) => {
367                                            let _ = node.replace_with_with_node_1(&canvas).expect(
368                                                &format!("Could not replace #{}", node.id()),
369                                            );
370                                        }
371                                        None => {
372                                            let _ = body
373                                                .append_child(&canvas)
374                                                .expect("Append canvas to HTML body");
375                                        }
376                                    };
377                                }
378
379                                self.process_event(
380                                    event_loop,
381                                    Event::WindowCreated {
382                                        id,
383                                        window: Arc::new(window),
384                                        exit_on_close_request,
385                                        make_visible: visible,
386                                        on_open,
387                                    },
388                                );
389                            }
390                            Control::Exit => {
391                                self.process_event(event_loop, Event::Exit);
392                                event_loop.exit();
393                                break;
394                            }
395                            Control::Crash(error) => {
396                                self.error = Some(error);
397                                event_loop.exit();
398                            }
399                            Control::SetAutomaticWindowTabbing(_enabled) => {
400                                #[cfg(target_os = "macos")]
401                                {
402                                    use winit::platform::macos::ActiveEventLoopExtMacOS;
403                                    event_loop.set_allows_automatic_window_tabbing(_enabled);
404                                }
405                            }
406                        },
407                        _ => {
408                            break;
409                        }
410                    },
411                    task::Poll::Ready(_) => {
412                        event_loop.exit();
413                        break;
414                    }
415                };
416            }
417        }
418    }
419
420    #[cfg(not(target_arch = "wasm32"))]
421    {
422        let mut runner = runner;
423        let _ = event_loop.run_app(&mut runner);
424
425        runner.error.map(Err).unwrap_or(Ok(()))
426    }
427
428    #[cfg(target_arch = "wasm32")]
429    {
430        use winit::platform::web::EventLoopExtWebSys;
431        let _ = event_loop.spawn_app(runner);
432
433        Ok(())
434    }
435}
436
437#[derive(Debug)]
438enum Event<Message: 'static> {
439    WindowCreated {
440        id: window::Id,
441        window: Arc<winit::window::Window>,
442        exit_on_close_request: bool,
443        make_visible: bool,
444        on_open: oneshot::Sender<window::Id>,
445    },
446    EventLoopAwakened(winit::event::Event<Message>),
447    Exit,
448}
449
450#[derive(Debug)]
451enum Control {
452    ChangeFlow(winit::event_loop::ControlFlow),
453    Exit,
454    Crash(Error),
455    CreateWindow {
456        id: window::Id,
457        settings: window::Settings,
458        title: String,
459        monitor: Option<winit::monitor::MonitorHandle>,
460        on_open: oneshot::Sender<window::Id>,
461        scale_factor: f32,
462    },
463    SetAutomaticWindowTabbing(bool),
464}
465
466async fn run_instance<P>(
467    mut program: program::Instance<P>,
468    mut runtime: Runtime<P::Executor, Proxy<P::Message>, Action<P::Message>>,
469    mut proxy: Proxy<P::Message>,
470    mut event_receiver: mpsc::UnboundedReceiver<Event<Action<P::Message>>>,
471    mut control_sender: mpsc::UnboundedSender<Control>,
472    display_handle: winit::event_loop::OwnedDisplayHandle,
473    is_daemon: bool,
474    backend_settings: backend::Settings,
475    mut renderer_settings: renderer::Settings,
476    default_fonts: Vec<Cow<'static, [u8]>>,
477    mut _system_theme: oneshot::Receiver<theme::Mode>,
478) where
479    P: Program + 'static,
480    P::Theme: theme::Base,
481{
482    use winit::event;
483    use winit::event_loop::ControlFlow;
484
485    let mut window_manager = window::Manager::new();
486    let mut is_window_opening = !is_daemon;
487
488    let mut compositor = None;
489    let mut events = Vec::new();
490    let mut messages = shell::Bus::new();
491    let mut actions = 0;
492
493    let mut ui_caches = FxHashMap::default();
494    let mut user_interfaces = ManuallyDrop::new(FxHashMap::default());
495    let mut clipboard = Clipboard::new();
496
497    #[cfg(all(feature = "linux-theme-detection", target_os = "linux"))]
498    let mut system_theme = {
499        let to_mode = |color_scheme| match color_scheme {
500            mundy::ColorScheme::NoPreference => theme::Mode::None,
501            mundy::ColorScheme::Light => theme::Mode::Light,
502            mundy::ColorScheme::Dark => theme::Mode::Dark,
503        };
504
505        runtime.run(
506            mundy::Preferences::stream(mundy::Interest::ColorScheme)
507                .map(move |preferences| {
508                    Action::System(system::Action::NotifyTheme(to_mode(
509                        preferences.color_scheme,
510                    )))
511                })
512                .boxed(),
513        );
514
515        runtime
516            .enter(|| {
517                mundy::Preferences::once_blocking(
518                    mundy::Interest::ColorScheme,
519                    core::time::Duration::from_millis(200),
520                )
521            })
522            .map(|preferences| to_mode(preferences.color_scheme))
523            .unwrap_or_default()
524    };
525
526    #[cfg(not(all(feature = "linux-theme-detection", target_os = "linux")))]
527    let mut system_theme = _system_theme.try_recv().ok().flatten().unwrap_or_default();
528
529    log::info!("System theme: {system_theme:?}");
530
531    'next_event: loop {
532        // Empty the queue if possible
533        let event = if let Ok(event) = event_receiver.try_recv() {
534            Some(event)
535        } else {
536            event_receiver.next().await
537        };
538
539        let Some(event) = event else {
540            break;
541        };
542
543        match event {
544            Event::WindowCreated {
545                id,
546                window,
547                exit_on_close_request,
548                make_visible,
549                on_open,
550            } => {
551                if compositor.is_none() {
552                    let (compositor_sender, compositor_receiver) = oneshot::channel();
553
554                    let create_compositor = {
555                        let window = window.clone();
556                        let backend_settings = backend_settings.clone();
557                        let display_handle = display_handle.clone();
558                        let proxy = proxy.clone();
559                        let default_fonts = default_fonts.clone();
560
561                        async move {
562                            let shell = Shell::new(proxy.clone());
563
564                            let mut compositor =
565                                <P::Renderer as compositor::Default>::Compositor::new(
566                                    backend_settings,
567                                    display_handle,
568                                    window,
569                                    shell,
570                                )
571                                .await;
572
573                            if let Ok(compositor) = &mut compositor {
574                                for font in default_fonts {
575                                    compositor.load_font(font.clone());
576                                }
577                            }
578
579                            compositor_sender
580                                .send(compositor)
581                                .ok()
582                                .expect("Send compositor");
583
584                            // HACK! Send a proxy event on completion to trigger
585                            // a runtime re-poll
586                            // TODO: Send compositor through proxy (?)
587                            {
588                                let (sender, _receiver) = oneshot::channel();
589
590                                proxy.send_action(Action::Window(
591                                    runtime::window::Action::GetLatest(sender),
592                                ));
593                            }
594                        }
595                    };
596
597                    #[cfg(target_arch = "wasm32")]
598                    wasm_bindgen_futures::spawn_local(create_compositor);
599
600                    #[cfg(not(target_arch = "wasm32"))]
601                    runtime.block_on(create_compositor);
602
603                    match compositor_receiver.await.expect("Wait for compositor") {
604                        Ok(new_compositor) => {
605                            compositor = Some(new_compositor);
606                        }
607                        Err(error) => {
608                            let _ = control_sender.start_send(Control::Crash(error.into()));
609                            continue;
610                        }
611                    }
612                }
613
614                let window_theme = window
615                    .theme()
616                    .map(conversion::theme_mode)
617                    .unwrap_or_default();
618
619                if system_theme != window_theme {
620                    system_theme = window_theme;
621
622                    runtime.broadcast(subscription::Event::SystemThemeChanged(window_theme));
623                }
624
625                let is_first = window_manager.is_empty();
626                let window = window_manager.insert(
627                    id,
628                    window,
629                    &program,
630                    compositor.as_mut().expect("Compositor must be initialized"),
631                    proxy.clone(),
632                    renderer_settings,
633                    exit_on_close_request,
634                    system_theme,
635                );
636
637                window
638                    .raw
639                    .set_theme(conversion::window_theme(window.state.theme_mode()));
640
641                debug::theme_changed(|| {
642                    if is_first {
643                        theme::Base::seed(window.state.theme())
644                    } else {
645                        None
646                    }
647                });
648
649                let logical_size = window.state.logical_size();
650
651                window.renderer.hint(window.state.scale());
652
653                let _ = user_interfaces.insert(
654                    id,
655                    build_user_interface(
656                        &program,
657                        user_interface::Cache::default(),
658                        &mut window.renderer,
659                        logical_size,
660                        id,
661                    ),
662                );
663                let _ = ui_caches.insert(id, user_interface::Cache::default());
664
665                if make_visible {
666                    window.raw.set_visible(true);
667                }
668
669                events.push((
670                    id,
671                    core::Event::Window(window::Event::Opened {
672                        position: window.position(),
673                        size: window.state.logical_size(),
674                        scale_factor: window.raw.scale_factor() as f32,
675                    }),
676                ));
677
678                let _ = on_open.send(id);
679                is_window_opening = false;
680            }
681            Event::EventLoopAwakened(event) => {
682                match event {
683                    event::Event::NewEvents(event::StartCause::Init) => {
684                        for (_id, window) in window_manager.iter_mut() {
685                            window.raw.request_redraw();
686                        }
687                    }
688                    event::Event::NewEvents(event::StartCause::ResumeTimeReached { .. }) => {
689                        let now = Instant::now();
690
691                        for (_id, window) in window_manager.iter_mut() {
692                            if let Some(redraw_at) = window.redraw_at
693                                && redraw_at <= now
694                            {
695                                window.raw.request_redraw();
696                                window.redraw_at = None;
697                            }
698                        }
699
700                        if let Some(redraw_at) = window_manager.redraw_at() {
701                            let _ = control_sender
702                                .start_send(Control::ChangeFlow(ControlFlow::WaitUntil(redraw_at)));
703                        } else {
704                            let _ =
705                                control_sender.start_send(Control::ChangeFlow(ControlFlow::Wait));
706                        }
707                    }
708                    event::Event::PlatformSpecific(event::PlatformSpecific::MacOS(
709                        event::MacOS::ReceivedUrl(url),
710                    )) => {
711                        runtime.broadcast(subscription::Event::PlatformSpecific(
712                            subscription::PlatformSpecific::MacOS(
713                                subscription::MacOS::ReceivedUrl(url),
714                            ),
715                        ));
716                    }
717                    event::Event::UserEvent(action) => {
718                        run_action(
719                            action,
720                            &program,
721                            &proxy,
722                            &mut runtime,
723                            &mut compositor,
724                            &mut events,
725                            &mut messages,
726                            &mut clipboard,
727                            &mut control_sender,
728                            &mut user_interfaces,
729                            &mut window_manager,
730                            &mut ui_caches,
731                            &mut is_window_opening,
732                            &mut system_theme,
733                            &mut renderer_settings,
734                        );
735                        actions += 1;
736                    }
737                    event::Event::WindowEvent {
738                        window_id: id,
739                        event: event::WindowEvent::RedrawRequested,
740                        ..
741                    } => {
742                        let Some(mut current_compositor) = compositor.as_mut() else {
743                            continue;
744                        };
745
746                        let Some((id, mut window)) = window_manager.get_mut_alias(id) else {
747                            continue;
748                        };
749
750                        let physical_size = window.state.physical_size();
751                        let mut logical_size = window.state.logical_size();
752
753                        if physical_size.width == 0 || physical_size.height == 0 {
754                            continue;
755                        }
756
757                        let frame_time = Instant::now();
758
759                        // Window was resized between redraws
760                        if window.surface_version != window.state.surface_version() {
761                            window.configure_surface(current_compositor);
762                            window.reanchor(frame_time);
763
764                            let ui = user_interfaces.remove(&id).expect("Remove user interface");
765
766                            let layout_span = debug::layout(id);
767                            let _ = user_interfaces
768                                .insert(id, ui.relayout(logical_size, &mut window.renderer));
769                            layout_span.finish();
770                        }
771
772                        let redraw_event = core::Event::Window(window::Event::RedrawRequested(
773                            window.tick(frame_time),
774                        ));
775
776                        let cursor = window.state.cursor();
777
778                        let mut interface =
779                            user_interfaces.get_mut(&id).expect("Get user interface");
780
781                        let interact_span = debug::interact(id);
782                        let mut redraw_count = 0;
783
784                        let state = loop {
785                            let message_count = messages.len();
786                            let (state, _) = interface.update(
787                                &window.raw,
788                                &window.waker,
789                                slice::from_ref(&redraw_event),
790                                cursor,
791                                &mut window.renderer,
792                                &mut messages,
793                            );
794
795                            if redraw_count >= 2 {
796                                log::warn!(
797                                    "3 consecutive RedrawRequested events produced invalidation"
798                                );
799
800                                break state;
801                            }
802
803                            if message_count == messages.len() {
804                                match state {
805                                    user_interface::State::Outdated => {}
806                                    user_interface::State::Updated { change, .. } => match change {
807                                        user_interface::Change::None => break state,
808                                        user_interface::Change::Overlay => {
809                                            redraw_count += 1;
810                                            continue;
811                                        }
812                                        user_interface::Change::Layout => {}
813                                    },
814                                }
815                            }
816
817                            redraw_count += 1;
818
819                            if !messages.is_empty()
820                                || matches!(state, user_interface::State::Outdated)
821                            {
822                                let caches: FxHashMap<_, _> =
823                                    ManuallyDrop::into_inner(user_interfaces)
824                                        .into_iter()
825                                        .map(|(id, interface)| (id, interface.into_cache()))
826                                        .collect();
827
828                                let actions = update(&mut program, &mut runtime, &mut messages);
829
830                                user_interfaces = ManuallyDrop::new(build_user_interfaces(
831                                    &program,
832                                    &mut window_manager,
833                                    caches,
834                                    &mut proxy,
835                                ));
836
837                                for action in actions {
838                                    // Defer all window actions to avoid compositor
839                                    // race conditions while redrawing
840                                    if let Action::Window(_) = action {
841                                        proxy.send_action(action);
842                                        continue;
843                                    }
844
845                                    run_action(
846                                        action,
847                                        &program,
848                                        &proxy,
849                                        &mut runtime,
850                                        &mut compositor,
851                                        &mut events,
852                                        &mut messages,
853                                        &mut clipboard,
854                                        &mut control_sender,
855                                        &mut user_interfaces,
856                                        &mut window_manager,
857                                        &mut ui_caches,
858                                        &mut is_window_opening,
859                                        &mut system_theme,
860                                        &mut renderer_settings,
861                                    );
862                                }
863
864                                for (window_id, window) in window_manager.iter_mut() {
865                                    // We are already redrawing this window
866                                    if window_id == id {
867                                        continue;
868                                    }
869
870                                    window.raw.request_redraw();
871                                }
872
873                                let Some(next_compositor) = compositor.as_mut() else {
874                                    continue 'next_event;
875                                };
876
877                                current_compositor = next_compositor;
878                                window = window_manager.get_mut(id).unwrap();
879
880                                // Window scale factor changed during a redraw request
881                                if logical_size != window.state.logical_size() {
882                                    logical_size = window.state.logical_size();
883
884                                    log::debug!(
885                                        "Window scale factor changed during a redraw request"
886                                    );
887
888                                    let ui =
889                                        user_interfaces.remove(&id).expect("Remove user interface");
890
891                                    let layout_span = debug::layout(id);
892                                    let _ = user_interfaces.insert(
893                                        id,
894                                        ui.relayout(logical_size, &mut window.renderer),
895                                    );
896                                    layout_span.finish();
897                                }
898
899                                interface = user_interfaces.get_mut(&id).unwrap();
900                            }
901                        };
902                        interact_span.finish();
903
904                        let draw_span = debug::draw(id);
905                        interface.draw(
906                            &mut window.renderer,
907                            window.state.theme(),
908                            &renderer::Style {
909                                text_color: window.state.text_color(),
910                            },
911                            cursor,
912                        );
913                        draw_span.finish();
914
915                        if let user_interface::State::Updated {
916                            redraw_request,
917                            input_method,
918                            mouse_interaction,
919                            clipboard: clipboard_requests,
920                            ..
921                        } = state
922                        {
923                            window.request_redraw(redraw_request);
924                            window.request_input_method(input_method);
925                            window.update_mouse(mouse_interaction);
926
927                            run_clipboard(&mut proxy, &mut clipboard, clipboard_requests, id);
928                        }
929
930                        runtime.broadcast(subscription::Event::Interaction {
931                            window: id,
932                            event: redraw_event,
933                            status: core::event::Status::Ignored,
934                        });
935
936                        window.draw_preedit();
937
938                        let present_span = debug::present(id);
939                        match current_compositor.present(
940                            &mut window.renderer,
941                            &mut window.surface,
942                            window.state.viewport(),
943                            window.state.background_color(),
944                            || window.raw.pre_present_notify(),
945                        ) {
946                            Ok(()) => {
947                                present_span.finish();
948                            }
949                            Err(error) => match error {
950                                compositor::SurfaceError::OutOfMemory => {
951                                    // This is an unrecoverable error.
952                                    panic!("{error:?}");
953                                }
954                                compositor::SurfaceError::Occluded => {
955                                    present_span.finish();
956
957                                    // Do nothing and wait for window to become visible again
958                                }
959                                compositor::SurfaceError::Timeout => {
960                                    present_span.finish();
961
962                                    window.raw.request_redraw();
963                                }
964                                compositor::SurfaceError::Lost
965                                | compositor::SurfaceError::Outdated
966                                | compositor::SurfaceError::Other => {
967                                    present_span.finish();
968
969                                    // Recreate at most once a second, and do not request a redraw in
970                                    // between, so a surface that keeps failing cannot spin the loop.
971                                    let due = matches!(error, compositor::SurfaceError::Outdated)
972                                        || window
973                                            .surface_error_at
974                                            .is_none_or(|at| at.elapsed() > Duration::from_secs(1));
975
976                                    if due {
977                                        window.surface_error_at = Some(Instant::now());
978
979                                        log::warn!(
980                                            "Error {error:?} when presenting surface. Recovering it."
981                                        );
982
983                                        if matches!(error, compositor::SurfaceError::Lost) {
984                                            window.surface = current_compositor
985                                                .create_surface(window.raw.clone());
986                                        }
987
988                                        window.configure_surface(current_compositor);
989                                        window.raw.request_redraw();
990                                    }
991                                }
992                            },
993                        }
994                    }
995                    event::Event::WindowEvent {
996                        event: window_event,
997                        window_id,
998                    } => {
999                        if !is_daemon
1000                            && matches!(window_event, winit::event::WindowEvent::Destroyed)
1001                            && !is_window_opening
1002                            && window_manager.is_empty()
1003                        {
1004                            control_sender
1005                                .start_send(Control::Exit)
1006                                .expect("Send control action");
1007
1008                            continue;
1009                        }
1010
1011                        let Some((id, window)) = window_manager.get_mut_alias(window_id) else {
1012                            continue;
1013                        };
1014
1015                        match window_event {
1016                            winit::event::WindowEvent::Resized(_)
1017                            | winit::event::WindowEvent::Occluded(false) => {
1018                                window.raw.request_redraw();
1019                            }
1020                            winit::event::WindowEvent::ThemeChanged(theme) => {
1021                                let mode = conversion::theme_mode(theme);
1022
1023                                if mode != system_theme {
1024                                    system_theme = mode;
1025
1026                                    runtime
1027                                        .broadcast(subscription::Event::SystemThemeChanged(mode));
1028                                }
1029                            }
1030                            _ => {}
1031                        }
1032
1033                        if matches!(window_event, winit::event::WindowEvent::CloseRequested)
1034                            && window.exit_on_close_request
1035                        {
1036                            run_action(
1037                                Action::Window(runtime::window::Action::Close(id)),
1038                                &program,
1039                                &proxy,
1040                                &mut runtime,
1041                                &mut compositor,
1042                                &mut events,
1043                                &mut messages,
1044                                &mut clipboard,
1045                                &mut control_sender,
1046                                &mut user_interfaces,
1047                                &mut window_manager,
1048                                &mut ui_caches,
1049                                &mut is_window_opening,
1050                                &mut system_theme,
1051                                &mut renderer_settings,
1052                            );
1053                        } else {
1054                            window.state.update(&program, &window.raw, &window_event);
1055
1056                            if let Some(event) = conversion::window_event(
1057                                window_event,
1058                                window.state.scale_factor(),
1059                                window.state.modifiers(),
1060                            ) {
1061                                events.push((id, event));
1062                            }
1063                        }
1064                    }
1065                    event::Event::AboutToWait => {
1066                        if actions > 0 {
1067                            proxy.free_slots(actions);
1068                            actions = 0;
1069                        }
1070
1071                        if events.is_empty() && messages.is_empty() && window_manager.is_idle() {
1072                            continue;
1073                        }
1074
1075                        let mut uis_stale = false;
1076
1077                        for (id, window) in window_manager.iter_mut() {
1078                            let interact_span = debug::interact(id);
1079                            let mut window_events = vec![];
1080
1081                            events.retain(|(window_id, event)| {
1082                                if *window_id == id {
1083                                    window_events.push(event.clone());
1084                                    false
1085                                } else {
1086                                    true
1087                                }
1088                            });
1089
1090                            if window_events.is_empty() {
1091                                continue;
1092                            }
1093
1094                            let (ui_state, statuses) = user_interfaces
1095                                .get_mut(&id)
1096                                .expect("Get user interface")
1097                                .update(
1098                                    &window.raw,
1099                                    &window.waker,
1100                                    &window_events,
1101                                    window.state.cursor(),
1102                                    &mut window.renderer,
1103                                    &mut messages,
1104                                );
1105
1106                            #[cfg(feature = "unconditional-rendering")]
1107                            window.request_redraw(window::RedrawRequest::NextFrame);
1108
1109                            match ui_state {
1110                                user_interface::State::Updated {
1111                                    redraw_request: _redraw_request,
1112                                    mouse_interaction,
1113                                    clipboard: clipboard_requests,
1114                                    ..
1115                                } => {
1116                                    window.update_mouse(mouse_interaction);
1117
1118                                    #[cfg(not(feature = "unconditional-rendering"))]
1119                                    window.request_redraw(_redraw_request);
1120
1121                                    run_clipboard(
1122                                        &mut proxy,
1123                                        &mut clipboard,
1124                                        clipboard_requests,
1125                                        id,
1126                                    );
1127                                }
1128                                user_interface::State::Outdated => {
1129                                    uis_stale = true;
1130                                }
1131                            }
1132
1133                            for (event, status) in window_events.into_iter().zip(statuses) {
1134                                runtime.broadcast(subscription::Event::Interaction {
1135                                    window: id,
1136                                    event,
1137                                    status,
1138                                });
1139                            }
1140
1141                            interact_span.finish();
1142                        }
1143
1144                        for (id, event) in events.drain(..) {
1145                            runtime.broadcast(subscription::Event::Interaction {
1146                                window: id,
1147                                event,
1148                                status: core::event::Status::Ignored,
1149                            });
1150                        }
1151
1152                        if !messages.is_empty() || uis_stale {
1153                            let cached_interfaces: FxHashMap<_, _> =
1154                                ManuallyDrop::into_inner(user_interfaces)
1155                                    .into_iter()
1156                                    .map(|(id, ui)| (id, ui.into_cache()))
1157                                    .collect();
1158
1159                            let actions = update(&mut program, &mut runtime, &mut messages);
1160
1161                            user_interfaces = ManuallyDrop::new(build_user_interfaces(
1162                                &program,
1163                                &mut window_manager,
1164                                cached_interfaces,
1165                                &mut proxy,
1166                            ));
1167
1168                            for action in actions {
1169                                run_action(
1170                                    action,
1171                                    &program,
1172                                    &proxy,
1173                                    &mut runtime,
1174                                    &mut compositor,
1175                                    &mut events,
1176                                    &mut messages,
1177                                    &mut clipboard,
1178                                    &mut control_sender,
1179                                    &mut user_interfaces,
1180                                    &mut window_manager,
1181                                    &mut ui_caches,
1182                                    &mut is_window_opening,
1183                                    &mut system_theme,
1184                                    &mut renderer_settings,
1185                                );
1186                            }
1187
1188                            for (_id, window) in window_manager.iter_mut() {
1189                                window.raw.request_redraw();
1190                            }
1191                        }
1192
1193                        if let Some(redraw_at) = window_manager.redraw_at() {
1194                            let _ = control_sender
1195                                .start_send(Control::ChangeFlow(ControlFlow::WaitUntil(redraw_at)));
1196                        } else {
1197                            let _ =
1198                                control_sender.start_send(Control::ChangeFlow(ControlFlow::Wait));
1199                        }
1200                    }
1201                    _ => {}
1202                }
1203            }
1204            Event::Exit => break,
1205        }
1206    }
1207
1208    let _ = ManuallyDrop::into_inner(user_interfaces);
1209}
1210
1211/// Builds a window's [`UserInterface`] for the [`Program`].
1212fn build_user_interface<'a, P: Program>(
1213    program: &'a program::Instance<P>,
1214    cache: user_interface::Cache,
1215    renderer: &mut P::Renderer,
1216    size: Size,
1217    id: window::Id,
1218) -> UserInterface<'a, P::Message, P::Theme, P::Renderer>
1219where
1220    P::Theme: theme::Base,
1221{
1222    let view_span = debug::view(id);
1223    let view = program.view(id);
1224    view_span.finish();
1225
1226    let layout_span = debug::layout(id);
1227    let user_interface = UserInterface::build(view, size, cache, renderer);
1228    layout_span.finish();
1229
1230    user_interface
1231}
1232
1233fn update<P: Program, E: Executor>(
1234    program: &mut program::Instance<P>,
1235    runtime: &mut Runtime<E, Proxy<P::Message>, Action<P::Message>>,
1236    messages: &mut shell::Bus<P::Message>,
1237) -> Vec<Action<P::Message>>
1238where
1239    P::Theme: theme::Base,
1240{
1241    use futures::futures;
1242
1243    let mut actions = Vec::new();
1244    let mut outputs = Vec::new();
1245
1246    while !messages.is_empty() {
1247        for (message, _receipt) in messages.drain() {
1248            let task = runtime.enter(|| program.update(message));
1249
1250            if let Some(mut stream) = runtime::task::into_stream(task) {
1251                let waker = futures::task::noop_waker_ref();
1252                let mut context = futures::task::Context::from_waker(waker);
1253
1254                // Run immediately available actions synchronously (e.g. widget operations)
1255                loop {
1256                    match runtime.enter(|| stream.poll_next_unpin(&mut context)) {
1257                        futures::task::Poll::Ready(Some(Action::Output(output))) => {
1258                            outputs.push(output);
1259                        }
1260                        futures::task::Poll::Ready(Some(action)) => {
1261                            actions.push(action);
1262                        }
1263                        futures::task::Poll::Ready(None) => {
1264                            break;
1265                        }
1266                        futures::task::Poll::Pending => {
1267                            runtime.run(stream);
1268                            break;
1269                        }
1270                    }
1271                }
1272            }
1273        }
1274
1275        for output in outputs.drain(..) {
1276            let _ = messages.push(output);
1277        }
1278    }
1279
1280    let subscription = runtime.enter(|| program.subscription());
1281    let recipes = subscription::into_recipes(subscription.map(Action::Output));
1282
1283    runtime.track(recipes);
1284
1285    actions
1286}
1287
1288fn run_action<'a, P, C>(
1289    action: Action<P::Message>,
1290    program: &'a program::Instance<P>,
1291    _proxy: &Proxy<P::Message>,
1292    runtime: &mut Runtime<P::Executor, Proxy<P::Message>, Action<P::Message>>,
1293    compositor: &mut Option<C>,
1294    events: &mut Vec<(window::Id, core::Event)>,
1295    messages: &mut shell::Bus<P::Message>,
1296    clipboard: &mut Clipboard,
1297    control_sender: &mut mpsc::UnboundedSender<Control>,
1298    interfaces: &mut FxHashMap<window::Id, UserInterface<'a, P::Message, P::Theme, P::Renderer>>,
1299    window_manager: &mut window::Manager<P, C>,
1300    ui_caches: &mut FxHashMap<window::Id, user_interface::Cache>,
1301    is_window_opening: &mut bool,
1302    system_theme: &mut theme::Mode,
1303    renderer_settings: &mut renderer::Settings,
1304) where
1305    P: Program,
1306    C: Compositor<Renderer = P::Renderer> + 'static,
1307    P::Theme: theme::Base,
1308{
1309    use crate::core::Renderer as _;
1310    use crate::runtime::backend;
1311    use crate::runtime::clipboard;
1312    use crate::runtime::window;
1313
1314    match action {
1315        Action::Output(message) => {
1316            let _ = messages.push(message);
1317        }
1318        Action::Clipboard(action) => match action {
1319            clipboard::Action::Read { kind, channel } => {
1320                clipboard.read(kind, move |result| {
1321                    let _ = channel.send(result);
1322                });
1323            }
1324            clipboard::Action::Write { content, channel } => {
1325                clipboard.write(content, move |result| {
1326                    let _ = channel.send(result);
1327                });
1328            }
1329        },
1330        Action::Window(action) => match action {
1331            window::Action::Open(id, settings, channel) => {
1332                let monitor = window_manager.last_monitor();
1333
1334                control_sender
1335                    .start_send(Control::CreateWindow {
1336                        id,
1337                        settings,
1338                        title: program.title(id),
1339                        scale_factor: program.scale_factor(id),
1340                        monitor,
1341                        on_open: channel,
1342                    })
1343                    .expect("Send control action");
1344
1345                *is_window_opening = true;
1346            }
1347            window::Action::Close(id) => {
1348                let _ = ui_caches.remove(&id);
1349                let _ = interfaces.remove(&id);
1350
1351                if window_manager.remove(id).is_some() {
1352                    events.push((id, core::Event::Window(core::window::Event::Closed)));
1353                }
1354
1355                if window_manager.is_empty() {
1356                    *compositor = None;
1357                }
1358            }
1359            window::Action::GetOldest(channel) => {
1360                let id = window_manager.iter_mut().next().map(|(id, _window)| id);
1361
1362                let _ = channel.send(id);
1363            }
1364            window::Action::GetLatest(channel) => {
1365                let id = window_manager.iter_mut().last().map(|(id, _window)| id);
1366
1367                let _ = channel.send(id);
1368            }
1369            window::Action::Drag(id) => {
1370                if let Some(window) = window_manager.get_mut(id) {
1371                    let _ = window.raw.drag_window();
1372                }
1373            }
1374            window::Action::DragResize(id, direction) => {
1375                if let Some(window) = window_manager.get_mut(id) {
1376                    let _ = window
1377                        .raw
1378                        .drag_resize_window(conversion::resize_direction(direction));
1379                }
1380            }
1381            window::Action::Resize(id, size) => {
1382                if let Some(window) = window_manager.get_mut(id) {
1383                    let _ = window.raw.request_inner_size(
1384                        winit::dpi::LogicalSize {
1385                            width: size.width,
1386                            height: size.height,
1387                        }
1388                        .to_physical::<f32>(f64::from(window.state.scale_factor())),
1389                    );
1390                }
1391            }
1392            window::Action::SetMinSize(id, size) => {
1393                if let Some(window) = window_manager.get_mut(id) {
1394                    window.raw.set_min_inner_size(size.map(|size| {
1395                        winit::dpi::LogicalSize {
1396                            width: size.width,
1397                            height: size.height,
1398                        }
1399                        .to_physical::<f32>(f64::from(window.state.scale_factor()))
1400                    }));
1401                }
1402            }
1403            window::Action::SetMaxSize(id, size) => {
1404                if let Some(window) = window_manager.get_mut(id) {
1405                    window.raw.set_max_inner_size(size.map(|size| {
1406                        winit::dpi::LogicalSize {
1407                            width: size.width,
1408                            height: size.height,
1409                        }
1410                        .to_physical::<f32>(f64::from(window.state.scale_factor()))
1411                    }));
1412                }
1413            }
1414            window::Action::SetResizeIncrements(id, increments) => {
1415                if let Some(window) = window_manager.get_mut(id) {
1416                    window.raw.set_resize_increments(increments.map(|size| {
1417                        winit::dpi::LogicalSize {
1418                            width: size.width,
1419                            height: size.height,
1420                        }
1421                        .to_physical::<f32>(f64::from(window.state.scale_factor()))
1422                    }));
1423                }
1424            }
1425            window::Action::SetResizable(id, resizable) => {
1426                if let Some(window) = window_manager.get_mut(id) {
1427                    window.raw.set_resizable(resizable);
1428                }
1429            }
1430            window::Action::GetSize(id, channel) => {
1431                if let Some(window) = window_manager.get_mut(id) {
1432                    let size = window.state.logical_size();
1433                    let _ = channel.send(Size::new(size.width, size.height));
1434                }
1435            }
1436            window::Action::GetMaximized(id, channel) => {
1437                if let Some(window) = window_manager.get_mut(id) {
1438                    let _ = channel.send(window.raw.is_maximized());
1439                }
1440            }
1441            window::Action::Maximize(id, maximized) => {
1442                if let Some(window) = window_manager.get_mut(id) {
1443                    window.raw.set_maximized(maximized);
1444                }
1445            }
1446            window::Action::GetMinimized(id, channel) => {
1447                if let Some(window) = window_manager.get_mut(id) {
1448                    let _ = channel.send(window.raw.is_minimized());
1449                }
1450            }
1451            window::Action::Minimize(id, minimized) => {
1452                if let Some(window) = window_manager.get_mut(id) {
1453                    window.raw.set_minimized(minimized);
1454                }
1455            }
1456            window::Action::GetPosition(id, channel) => {
1457                if let Some(window) = window_manager.get(id) {
1458                    let position = window
1459                        .raw
1460                        .outer_position()
1461                        .map(|position| {
1462                            let position = position.to_logical::<f32>(window.raw.scale_factor());
1463
1464                            Point::new(position.x, position.y)
1465                        })
1466                        .ok();
1467
1468                    let _ = channel.send(position);
1469                }
1470            }
1471            window::Action::GetScaleFactor(id, channel) => {
1472                if let Some(window) = window_manager.get_mut(id) {
1473                    let scale_factor = window.raw.scale_factor();
1474
1475                    let _ = channel.send(scale_factor as f32);
1476                }
1477            }
1478            window::Action::Move(id, position) => {
1479                if let Some(window) = window_manager.get_mut(id) {
1480                    window.raw.set_outer_position(winit::dpi::LogicalPosition {
1481                        x: position.x,
1482                        y: position.y,
1483                    });
1484                }
1485            }
1486            window::Action::SetMode(id, mode) => {
1487                if let Some(window) = window_manager.get_mut(id) {
1488                    window.raw.set_visible(conversion::visible(mode));
1489                    window
1490                        .raw
1491                        .set_fullscreen(conversion::fullscreen(window.raw.current_monitor(), mode));
1492                }
1493            }
1494            window::Action::SetIcon(id, icon) => {
1495                if let Some(window) = window_manager.get_mut(id) {
1496                    window.raw.set_window_icon(conversion::icon(icon));
1497                }
1498            }
1499            window::Action::GetMode(id, channel) => {
1500                if let Some(window) = window_manager.get_mut(id) {
1501                    let mode = if window.raw.is_visible().unwrap_or(true) {
1502                        conversion::mode(window.raw.fullscreen())
1503                    } else {
1504                        core::window::Mode::Hidden
1505                    };
1506
1507                    let _ = channel.send(mode);
1508                }
1509            }
1510            window::Action::ToggleMaximize(id) => {
1511                if let Some(window) = window_manager.get_mut(id) {
1512                    window.raw.set_maximized(!window.raw.is_maximized());
1513                }
1514            }
1515            window::Action::ToggleDecorations(id) => {
1516                if let Some(window) = window_manager.get_mut(id) {
1517                    window.raw.set_decorations(!window.raw.is_decorated());
1518                }
1519            }
1520            window::Action::RequestUserAttention(id, attention_type) => {
1521                if let Some(window) = window_manager.get_mut(id) {
1522                    window
1523                        .raw
1524                        .request_user_attention(attention_type.map(conversion::user_attention));
1525                }
1526            }
1527            window::Action::GainFocus(id) => {
1528                if let Some(window) = window_manager.get_mut(id) {
1529                    window.raw.focus_window();
1530                }
1531            }
1532            window::Action::SetLevel(id, level) => {
1533                if let Some(window) = window_manager.get_mut(id) {
1534                    window.raw.set_window_level(conversion::window_level(level));
1535                }
1536            }
1537            window::Action::ShowSystemMenu(id) => {
1538                if let Some(window) = window_manager.get_mut(id)
1539                    && let mouse::Cursor::Available(point) = window.state.cursor()
1540                {
1541                    window.raw.show_window_menu(winit::dpi::LogicalPosition {
1542                        x: point.x,
1543                        y: point.y,
1544                    });
1545                }
1546            }
1547            window::Action::GetRawId(id, channel) => {
1548                if let Some(window) = window_manager.get_mut(id) {
1549                    let _ = channel.send(window.raw.id().into());
1550                }
1551            }
1552            window::Action::Run(id, f) => {
1553                if let Some(window) = window_manager.get_mut(id) {
1554                    f(&window.raw);
1555                }
1556            }
1557            window::Action::Screenshot(id, channel) => {
1558                if let Some(window) = window_manager.get_mut(id)
1559                    && let Some(compositor) = compositor
1560                {
1561                    let bytes = compositor.screenshot(
1562                        &mut window.renderer,
1563                        window.state.viewport(),
1564                        window.state.background_color(),
1565                    );
1566
1567                    let _ = channel.send(core::window::Screenshot::new(
1568                        bytes,
1569                        window.state.physical_size(),
1570                        window.state.scale_factor(),
1571                    ));
1572                }
1573            }
1574            window::Action::EnableMousePassthrough(id) => {
1575                if let Some(window) = window_manager.get_mut(id) {
1576                    let _ = window.raw.set_cursor_hittest(false);
1577                }
1578            }
1579            window::Action::DisableMousePassthrough(id) => {
1580                if let Some(window) = window_manager.get_mut(id) {
1581                    let _ = window.raw.set_cursor_hittest(true);
1582                }
1583            }
1584            window::Action::GetMonitorSize(id, channel) => {
1585                if let Some(window) = window_manager.get(id) {
1586                    let size = window.raw.current_monitor().map(|monitor| {
1587                        let scale = window.state.scale_factor();
1588                        let size = monitor.size().to_logical(f64::from(scale));
1589
1590                        Size::new(size.width, size.height)
1591                    });
1592
1593                    let _ = channel.send(size);
1594                }
1595            }
1596            window::Action::SetAllowAutomaticTabbing(enabled) => {
1597                control_sender
1598                    .start_send(Control::SetAutomaticWindowTabbing(enabled))
1599                    .expect("Send control action");
1600            }
1601            window::Action::RedrawAll => {
1602                for (_id, window) in window_manager.iter_mut() {
1603                    window.raw.request_redraw();
1604                }
1605            }
1606            window::Action::RelayoutAll => {
1607                for (id, window) in window_manager.iter_mut() {
1608                    if let Some(ui) = interfaces.remove(&id) {
1609                        let _ = interfaces.insert(
1610                            id,
1611                            ui.relayout(window.state.logical_size(), &mut window.renderer),
1612                        );
1613                    }
1614
1615                    window.raw.request_redraw();
1616                }
1617            }
1618        },
1619        Action::System(action) => match action {
1620            system::Action::GetInformation(_channel) => {
1621                #[cfg(feature = "sysinfo")]
1622                {
1623                    if let Some(compositor) = compositor {
1624                        let graphics_info = compositor.information();
1625
1626                        let _ = std::thread::spawn(move || {
1627                            let information = system_information(graphics_info);
1628
1629                            let _ = _channel.send(information);
1630                        });
1631                    }
1632                }
1633            }
1634            system::Action::GetTheme(channel) => {
1635                let _ = channel.send(*system_theme);
1636            }
1637            system::Action::NotifyTheme(mode) => {
1638                if mode != *system_theme {
1639                    *system_theme = mode;
1640
1641                    runtime.broadcast(subscription::Event::SystemThemeChanged(mode));
1642                }
1643
1644                let Some(theme) = conversion::window_theme(mode) else {
1645                    return;
1646                };
1647
1648                for (_id, window) in window_manager.iter_mut() {
1649                    window.state.update(
1650                        program,
1651                        &window.raw,
1652                        &winit::event::WindowEvent::ThemeChanged(theme),
1653                    );
1654                }
1655            }
1656        },
1657        Action::Font(action) => match action {
1658            font::Action::Load { bytes, channel } => {
1659                if let Some(compositor) = compositor {
1660                    let result = compositor.load_font(bytes.clone());
1661                    let _ = channel.send(result);
1662                }
1663            }
1664            font::Action::List { channel } => {
1665                if let Some(compositor) = compositor {
1666                    let fonts = compositor.list_fonts();
1667                    let _ = channel.send(fonts);
1668                }
1669            }
1670            font::Action::SetDefaults { font, text_size } => {
1671                renderer_settings.font = font;
1672                renderer_settings.text_size = text_size;
1673
1674                let Some(compositor) = compositor else {
1675                    return;
1676                };
1677
1678                // Recreate renderers and relayout all windows
1679                for (id, window) in window_manager.iter_mut() {
1680                    window.renderer = compositor.create_renderer(*renderer_settings);
1681
1682                    let Some(ui) = interfaces.remove(&id) else {
1683                        continue;
1684                    };
1685
1686                    let size = window.state.logical_size();
1687                    let ui = ui.relayout(size, &mut window.renderer);
1688                    let _ = interfaces.insert(id, ui);
1689
1690                    window.raw.request_redraw();
1691                }
1692            }
1693        },
1694        Action::Widget(operation) => {
1695            let mut current_operation = Some(operation);
1696
1697            while let Some(mut operation) = current_operation.take() {
1698                for (id, ui) in interfaces.iter_mut() {
1699                    if let Some(window) = window_manager.get_mut(*id) {
1700                        ui.operate(&window.renderer, operation.as_mut());
1701                    }
1702                }
1703
1704                match operation.finish() {
1705                    operation::Outcome::None => {}
1706                    operation::Outcome::Some(()) => {}
1707                    operation::Outcome::Chain(next) => {
1708                        current_operation = Some(next);
1709                    }
1710                }
1711            }
1712
1713            // Redraw all windows
1714            for (_, window) in window_manager.iter_mut() {
1715                window.raw.request_redraw();
1716            }
1717        }
1718        Action::Image(action) => match action {
1719            image::Action::Allocate(handle, sender) => {
1720                // TODO: Shared image cache in compositor
1721                if let Some((_id, window)) = window_manager.iter_mut().next() {
1722                    window.renderer.allocate_image(&handle, move |allocation| {
1723                        let _ = sender.send(allocation);
1724                    });
1725                }
1726            }
1727        },
1728        Action::Backend(action) => match action {
1729            #[cfg(not(target_arch = "wasm32"))]
1730            backend::Action::Configure(settings, sender) => {
1731                let shell = Shell::new(_proxy.clone());
1732
1733                let mut new_compositor = if let Some(window) = window_manager.first() {
1734                    match runtime.block_on(C::new(
1735                        settings,
1736                        window.raw.clone(),
1737                        window.raw.clone(),
1738                        shell,
1739                    )) {
1740                        Ok(compositor) => compositor,
1741                        Err(error) => {
1742                            let _ = sender.send(Err(error));
1743                            return;
1744                        }
1745                    }
1746                } else {
1747                    return;
1748                };
1749
1750                graphics::cache::invalidate_all();
1751
1752                window_manager.replace_with(|mut window| {
1753                    drop(window.renderer);
1754                    drop(window.surface);
1755
1756                    window.renderer = new_compositor.create_renderer(*renderer_settings);
1757                    window.surface = new_compositor.create_surface(window.raw.clone());
1758                    window.configure_surface(&mut new_compositor);
1759
1760                    window
1761                });
1762
1763                *compositor = Some(new_compositor);
1764
1765                let _ = sender.send(Ok(()));
1766            }
1767            #[cfg(target_arch = "wasm32")]
1768            backend::Action::Configure(_, _) => {}
1769        },
1770        Action::Event { window, event } => {
1771            events.push((window, event));
1772        }
1773        Action::Tick => {
1774            for (_id, window) in window_manager.iter_mut() {
1775                window.renderer.tick();
1776            }
1777        }
1778        Action::Reload => {
1779            for (id, window) in window_manager.iter_mut() {
1780                let Some(ui) = interfaces.remove(&id) else {
1781                    continue;
1782                };
1783
1784                let cache = ui.into_cache();
1785                let size = window.state.logical_size();
1786
1787                let _ = interfaces.insert(
1788                    id,
1789                    build_user_interface(program, cache, &mut window.renderer, size, id),
1790                );
1791
1792                window.raw.request_redraw();
1793            }
1794        }
1795        Action::Exit => {
1796            control_sender
1797                .start_send(Control::Exit)
1798                .expect("Send control action");
1799        }
1800    }
1801}
1802
1803/// Build the user interface for every window.
1804pub fn build_user_interfaces<'a, P: Program, C>(
1805    program: &'a program::Instance<P>,
1806    window_manager: &mut window::Manager<P, C>,
1807    mut cached_user_interfaces: FxHashMap<window::Id, user_interface::Cache>,
1808    proxy: &mut Proxy<P::Message>,
1809) -> FxHashMap<window::Id, UserInterface<'a, P::Message, P::Theme, P::Renderer>>
1810where
1811    C: Compositor<Renderer = P::Renderer>,
1812    P::Theme: theme::Base,
1813{
1814    for (id, window) in window_manager.iter_mut() {
1815        let old_size = window.state.logical_size();
1816
1817        window.state.synchronize(program, id, &window.raw);
1818
1819        let new_size = window.state.logical_size();
1820
1821        if old_size != new_size {
1822            proxy.send_action(Action::Event {
1823                window: id,
1824                event: core::Event::Window(window::Event::Resized(new_size)),
1825            });
1826        }
1827
1828        window.renderer.hint(window.state.scale());
1829    }
1830
1831    debug::theme_changed(|| {
1832        window_manager
1833            .first()
1834            .and_then(|window| theme::Base::seed(window.state.theme()))
1835    });
1836
1837    cached_user_interfaces
1838        .drain()
1839        .filter_map(|(id, cache)| {
1840            let window = window_manager.get_mut(id)?;
1841
1842            Some((
1843                id,
1844                build_user_interface(
1845                    program,
1846                    cache,
1847                    &mut window.renderer,
1848                    window.state.logical_size(),
1849                    id,
1850                ),
1851            ))
1852        })
1853        .collect()
1854}
1855
1856/// Returns true if the provided event should cause a [`Program`] to
1857/// exit.
1858pub fn user_force_quit(
1859    event: &winit::event::WindowEvent,
1860    _modifiers: winit::keyboard::ModifiersState,
1861) -> bool {
1862    match event {
1863        #[cfg(target_os = "macos")]
1864        winit::event::WindowEvent::KeyboardInput {
1865            event:
1866                winit::event::KeyEvent {
1867                    logical_key: winit::keyboard::Key::Character(c),
1868                    state: winit::event::ElementState::Pressed,
1869                    ..
1870                },
1871            ..
1872        } if c == "q" && _modifiers.super_key() => true,
1873        _ => false,
1874    }
1875}
1876
1877#[cfg(feature = "sysinfo")]
1878fn system_information(graphics: compositor::Information) -> system::Information {
1879    use sysinfo::{Process, System};
1880
1881    let mut system = System::new_all();
1882    system.refresh_all();
1883
1884    let cpu_brand = system
1885        .cpus()
1886        .first()
1887        .map(|cpu| cpu.brand().to_string())
1888        .unwrap_or_default();
1889
1890    let memory_used = sysinfo::get_current_pid()
1891        .and_then(|pid| system.process(pid).ok_or("Process not found"))
1892        .map(Process::memory)
1893        .ok();
1894
1895    system::Information {
1896        system_name: System::name(),
1897        system_kernel: System::kernel_version(),
1898        system_version: System::long_os_version(),
1899        system_short_version: System::os_version(),
1900        cpu_brand,
1901        cpu_cores: system.physical_core_count(),
1902        memory_total: system.total_memory(),
1903        memory_used,
1904        graphics_adapter: graphics.adapter,
1905        graphics_backend: graphics.backend,
1906    }
1907}
1908
1909fn run_clipboard<Message: Send>(
1910    proxy: &mut Proxy<Message>,
1911    clipboard: &mut Clipboard,
1912    requests: core::Clipboard,
1913    window: window::Id,
1914) {
1915    for kind in requests.reads {
1916        let proxy = proxy.clone();
1917
1918        clipboard.read(kind, move |result| {
1919            proxy.send_action(Action::Event {
1920                window,
1921                event: core::Event::Clipboard(core::clipboard::Event::Read(result.map(Arc::new))),
1922            });
1923        });
1924    }
1925
1926    if let Some(content) = requests.write {
1927        let proxy = proxy.clone();
1928
1929        clipboard.write(content, move |result| {
1930            proxy.send_action(Action::Event {
1931                window,
1932                event: core::Event::Clipboard(core::clipboard::Event::Written(result)),
1933            });
1934        });
1935    }
1936}