dioxus_native/
dioxus_application.rs

1use blitz_shell::{BlitzApplication, View};
2use dioxus_core::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        tracing::debug!("Injecting document provider into all windows");
115
116        if let Some(config) = self.pending_window.take() {
117            let mut window = View::init(config, event_loop, &self.proxy);
118            let renderer = window.renderer.clone();
119            let window_id = window.window_id();
120            let doc = window.downcast_doc_mut::<DioxusDocument>();
121
122            doc.vdom.in_runtime(|| {
123                let shared: Rc<dyn dioxus_document::Document> =
124                    Rc::new(DioxusNativeDocument::new(self.proxy.clone(), window_id));
125                ScopeId::ROOT.provide_context(shared);
126            });
127
128            // Add history
129            let history_provider: Rc<dyn History> = Rc::new(MemoryHistory::default());
130            doc.vdom
131                .in_runtime(move || ScopeId::ROOT.provide_context(history_provider));
132
133            // Add renderer
134            doc.vdom
135                .in_runtime(move || ScopeId::ROOT.provide_context(renderer));
136
137            // Queue rebuild
138            doc.initial_build();
139
140            // And then request redraw
141            window.request_redraw();
142
143            // todo(jon): we should actually mess with the pending windows instead of passing along the contexts
144            self.inner.windows.insert(window_id, window);
145        }
146
147        self.inner.resumed(event_loop);
148    }
149
150    fn suspended(&mut self, event_loop: &ActiveEventLoop) {
151        self.inner.suspended(event_loop);
152    }
153
154    fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
155        self.inner.new_events(event_loop, cause);
156    }
157
158    fn window_event(
159        &mut self,
160        event_loop: &ActiveEventLoop,
161        window_id: WindowId,
162        event: WindowEvent,
163    ) {
164        self.inner.window_event(event_loop, window_id, event);
165    }
166
167    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: BlitzShellEvent) {
168        match event {
169            BlitzShellEvent::Embedder(event) => {
170                if let Some(event) = event.downcast_ref::<DioxusNativeEvent>() {
171                    self.handle_blitz_shell_event(event_loop, event);
172                }
173            }
174            event => self.inner.user_event(event_loop, event),
175        }
176    }
177}