dioxus_native/
dioxus_application.rs

1use blitz_shell::{BlitzApplication, View};
2use dioxus_core::{provide_context, ScopeId};
3use dioxus_history::{History, MemoryHistory};
4use std::rc::Rc;
5use winit::application::ApplicationHandler;
6use winit::event::{StartCause, WindowEvent};
7use winit::event_loop::{ActiveEventLoop, EventLoopProxy};
8use winit::window::WindowId;
9
10use crate::DioxusNativeWindowRenderer;
11use crate::{contexts::DioxusNativeDocument, BlitzShellEvent, DioxusDocument, WindowConfig};
12
13/// Dioxus-native specific event type
14pub enum DioxusNativeEvent {
15    /// A hotreload event, basically telling us to update our templates.
16    #[cfg(all(
17        feature = "hot-reload",
18        debug_assertions,
19        not(target_os = "android"),
20        not(target_os = "ios")
21    ))]
22    DevserverEvent(dioxus_devtools::DevserverMsg),
23
24    /// Create a new head element from the Link and Title elements
25    ///
26    /// todo(jon): these should probabkly be synchronous somehow
27    CreateHeadElement {
28        window: WindowId,
29        name: String,
30        attributes: Vec<(String, String)>,
31        contents: Option<String>,
32    },
33}
34
35pub struct DioxusNativeApplication {
36    pending_window: Option<WindowConfig<DioxusNativeWindowRenderer>>,
37    inner: BlitzApplication<DioxusNativeWindowRenderer>,
38    proxy: EventLoopProxy<BlitzShellEvent>,
39}
40
41impl DioxusNativeApplication {
42    pub fn new(
43        proxy: EventLoopProxy<BlitzShellEvent>,
44        config: WindowConfig<DioxusNativeWindowRenderer>,
45    ) -> Self {
46        Self {
47            pending_window: Some(config),
48            inner: BlitzApplication::new(proxy.clone()),
49            proxy,
50        }
51    }
52
53    pub fn add_window(&mut self, window_config: WindowConfig<DioxusNativeWindowRenderer>) {
54        self.inner.add_window(window_config);
55    }
56
57    fn handle_blitz_shell_event(
58        &mut self,
59        event_loop: &ActiveEventLoop,
60        event: &DioxusNativeEvent,
61    ) {
62        match event {
63            #[cfg(all(
64                feature = "hot-reload",
65                debug_assertions,
66                not(target_os = "android"),
67                not(target_os = "ios")
68            ))]
69            DioxusNativeEvent::DevserverEvent(event) => match event {
70                dioxus_devtools::DevserverMsg::HotReload(hotreload_message) => {
71                    for window in self.inner.windows.values_mut() {
72                        let doc = window.downcast_doc_mut::<DioxusDocument>();
73                        dioxus_devtools::apply_changes(&doc.vdom, hotreload_message);
74                        window.poll();
75                    }
76                }
77                dioxus_devtools::DevserverMsg::Shutdown => event_loop.exit(),
78                dioxus_devtools::DevserverMsg::FullReloadStart => {}
79                dioxus_devtools::DevserverMsg::FullReloadFailed => {}
80                dioxus_devtools::DevserverMsg::FullReloadCommand => {}
81                _ => {}
82            },
83
84            DioxusNativeEvent::CreateHeadElement {
85                name,
86                attributes,
87                contents,
88                window,
89            } => {
90                if let Some(window) = self.inner.windows.get_mut(window) {
91                    let doc = window.downcast_doc_mut::<DioxusDocument>();
92                    doc.create_head_element(name, attributes, contents);
93                    window.poll();
94                }
95            }
96
97            // Suppress unused variable warning
98            #[cfg(not(all(
99                feature = "hot-reload",
100                debug_assertions,
101                not(target_os = "android"),
102                not(target_os = "ios")
103            )))]
104            _ => {
105                let _ = event_loop;
106                let _ = event;
107            }
108        }
109    }
110}
111
112impl ApplicationHandler<BlitzShellEvent> for DioxusNativeApplication {
113    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
114        #[cfg(feature = "tracing")]
115        tracing::debug!("Injecting document provider into all windows");
116
117        if let Some(config) = self.pending_window.take() {
118            let mut window = View::init(config, event_loop, &self.proxy);
119            let renderer = window.renderer.clone();
120            let window_id = window.window_id();
121            let doc = window.downcast_doc_mut::<DioxusDocument>();
122
123            doc.vdom.in_scope(ScopeId::ROOT, || {
124                let shared: Rc<dyn dioxus_document::Document> =
125                    Rc::new(DioxusNativeDocument::new(self.proxy.clone(), window_id));
126                provide_context(shared);
127            });
128
129            // Add history
130            let history_provider: Rc<dyn History> = Rc::new(MemoryHistory::default());
131            doc.vdom
132                .in_scope(ScopeId::ROOT, move || provide_context(history_provider));
133
134            // Add renderer
135            doc.vdom
136                .in_scope(ScopeId::ROOT, move || provide_context(renderer));
137
138            // Queue rebuild
139            doc.initial_build();
140
141            // And then request redraw
142            window.request_redraw();
143
144            // todo(jon): we should actually mess with the pending windows instead of passing along the contexts
145            self.inner.windows.insert(window_id, window);
146        }
147
148        self.inner.resumed(event_loop);
149    }
150
151    fn suspended(&mut self, event_loop: &ActiveEventLoop) {
152        self.inner.suspended(event_loop);
153    }
154
155    fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
156        self.inner.new_events(event_loop, cause);
157    }
158
159    fn window_event(
160        &mut self,
161        event_loop: &ActiveEventLoop,
162        window_id: WindowId,
163        event: WindowEvent,
164    ) {
165        self.inner.window_event(event_loop, window_id, event);
166    }
167
168    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: BlitzShellEvent) {
169        match event {
170            BlitzShellEvent::Embedder(event) => {
171                if let Some(event) = event.downcast_ref::<DioxusNativeEvent>() {
172                    self.handle_blitz_shell_event(event_loop, event);
173                }
174            }
175            event => self.inner.user_event(event_loop, event),
176        }
177    }
178}