dioxus_desktop/
config.rs

1use dioxus_core::{LaunchConfig, VirtualDom};
2use std::path::PathBuf;
3use std::{borrow::Cow, sync::Arc};
4use tao::window::{Icon, WindowBuilder};
5use tao::{
6    event_loop::{EventLoop, EventLoopWindowTarget},
7    window::Window,
8};
9use wry::http::{Request as HttpRequest, Response as HttpResponse};
10use wry::{RequestAsyncResponder, WebViewId};
11
12use crate::ipc::UserWindowEvent;
13use crate::menubar::{default_menu_bar, DioxusMenu};
14
15type CustomEventHandler = Box<
16    dyn 'static
17        + for<'a> FnMut(
18            &tao::event::Event<'a, UserWindowEvent>,
19            &EventLoopWindowTarget<UserWindowEvent>,
20        ),
21>;
22
23/// The closing behaviour of specific application window.
24#[derive(Debug, Copy, Clone, Eq, PartialEq)]
25#[non_exhaustive]
26pub enum WindowCloseBehaviour {
27    /// Window will hide instead of closing
28    WindowHides,
29
30    /// Window will close
31    WindowCloses,
32}
33
34/// The state of the menu builder. We need to keep track of if the state is default
35/// so we only swap out the default menu bar when decorations are disabled
36pub(crate) enum MenuBuilderState {
37    Unset,
38    Set(Option<DioxusMenu>),
39}
40
41impl From<MenuBuilderState> for Option<DioxusMenu> {
42    fn from(val: MenuBuilderState) -> Self {
43        match val {
44            MenuBuilderState::Unset => Some(default_menu_bar()),
45            MenuBuilderState::Set(menu) => menu,
46        }
47    }
48}
49
50/// The configuration for the desktop application.
51pub struct Config {
52    pub(crate) event_loop: Option<EventLoop<UserWindowEvent>>,
53    pub(crate) window: WindowBuilder,
54    pub(crate) as_child_window: bool,
55    pub(crate) menu: MenuBuilderState,
56    pub(crate) protocols: Vec<WryProtocol>,
57    pub(crate) asynchronous_protocols: Vec<AsyncWryProtocol>,
58    pub(crate) pre_rendered: Option<String>,
59    pub(crate) disable_context_menu: bool,
60    pub(crate) resource_dir: Option<PathBuf>,
61    pub(crate) data_dir: Option<PathBuf>,
62    pub(crate) custom_head: Option<String>,
63    pub(crate) custom_index: Option<String>,
64    pub(crate) root_name: String,
65    pub(crate) background_color: Option<(u8, u8, u8, u8)>,
66    pub(crate) exit_on_last_window_close: bool,
67    pub(crate) window_close_behavior: WindowCloseBehaviour,
68    pub(crate) custom_event_handler: Option<CustomEventHandler>,
69    pub(crate) disable_file_drop_handler: bool,
70
71    #[allow(clippy::type_complexity)]
72    pub(crate) on_window: Option<Box<dyn FnMut(Arc<Window>, &mut VirtualDom) + 'static>>,
73}
74
75impl LaunchConfig for Config {}
76
77pub(crate) type WryProtocol = (
78    String,
79    Box<dyn Fn(WebViewId, HttpRequest<Vec<u8>>) -> HttpResponse<Cow<'static, [u8]>> + 'static>,
80);
81
82pub(crate) type AsyncWryProtocol = (
83    String,
84    Box<dyn Fn(WebViewId, HttpRequest<Vec<u8>>, RequestAsyncResponder) + 'static>,
85);
86
87impl Config {
88    /// Initializes a new `WindowBuilder` with default values.
89    #[inline]
90    pub fn new() -> Self {
91        let mut window: WindowBuilder = WindowBuilder::new()
92            .with_title(dioxus_cli_config::app_title().unwrap_or_else(|| "Dioxus App".to_string()));
93
94        // During development we want the window to be on top so we can see it while we work
95        let always_on_top = dioxus_cli_config::always_on_top().unwrap_or(true);
96
97        if cfg!(debug_assertions) {
98            window = window.with_always_on_top(always_on_top);
99        }
100
101        Self {
102            window,
103            as_child_window: false,
104            event_loop: None,
105            menu: MenuBuilderState::Unset,
106            protocols: Vec::new(),
107            asynchronous_protocols: Vec::new(),
108            pre_rendered: None,
109            disable_context_menu: !cfg!(debug_assertions),
110            resource_dir: None,
111            data_dir: None,
112            custom_head: None,
113            custom_index: None,
114            root_name: "main".to_string(),
115            background_color: None,
116            exit_on_last_window_close: true,
117            window_close_behavior: WindowCloseBehaviour::WindowCloses,
118            custom_event_handler: None,
119            disable_file_drop_handler: false,
120            on_window: None,
121        }
122    }
123
124    /// set the directory from which assets will be searched in release mode
125    pub fn with_resource_directory(mut self, path: impl Into<PathBuf>) -> Self {
126        self.resource_dir = Some(path.into());
127        self
128    }
129
130    /// set the directory where data will be stored in release mode.
131    ///
132    /// > Note: This **must** be set when bundling on Windows.
133    pub fn with_data_directory(mut self, path: impl Into<PathBuf>) -> Self {
134        self.data_dir = Some(path.into());
135        self
136    }
137
138    /// Set whether or not the right-click context menu should be disabled.
139    pub fn with_disable_context_menu(mut self, disable: bool) -> Self {
140        self.disable_context_menu = disable;
141        self
142    }
143
144    /// Set whether or not the file drop handler should be disabled.
145    /// On Windows the drop handler must be disabled for HTML drag and drop APIs to work.
146    pub fn with_disable_drag_drop_handler(mut self, disable: bool) -> Self {
147        self.disable_file_drop_handler = disable;
148        self
149    }
150
151    /// Set the pre-rendered HTML content
152    pub fn with_prerendered(mut self, content: String) -> Self {
153        self.pre_rendered = Some(content);
154        self
155    }
156
157    /// Set the event loop to be used
158    pub fn with_event_loop(mut self, event_loop: EventLoop<UserWindowEvent>) -> Self {
159        self.event_loop = Some(event_loop);
160        self
161    }
162
163    /// Set the configuration for the window.
164    pub fn with_window(mut self, window: WindowBuilder) -> Self {
165        // We need to do a swap because the window builder only takes itself as muy self
166        self.window = window;
167        // If the decorations are off for the window, remove the menu as well
168        if !self.window.window.decorations && matches!(self.menu, MenuBuilderState::Unset) {
169            self.menu = MenuBuilderState::Set(None);
170        }
171        self
172    }
173
174    /// Set the window as child
175    pub fn with_as_child_window(mut self) -> Self {
176        self.as_child_window = true;
177        self
178    }
179
180    /// When the last window is closed, the application will exit.
181    ///
182    /// This is the default behaviour.
183    ///
184    /// If the last window is hidden, the application will not exit.
185    pub fn with_exits_when_last_window_closes(mut self, exit: bool) -> Self {
186        self.exit_on_last_window_close = exit;
187        self
188    }
189
190    /// Sets the behaviour of the application when the last window is closed.
191    pub fn with_close_behaviour(mut self, behaviour: WindowCloseBehaviour) -> Self {
192        self.window_close_behavior = behaviour;
193        self
194    }
195
196    /// Sets a custom callback to run whenever the event pool receives an event.
197    pub fn with_custom_event_handler(
198        mut self,
199        f: impl FnMut(&tao::event::Event<'_, UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>)
200            + 'static,
201    ) -> Self {
202        self.custom_event_handler = Some(Box::new(f));
203        self
204    }
205
206    /// Set a custom protocol
207    pub fn with_custom_protocol<F>(mut self, name: impl ToString, handler: F) -> Self
208    where
209        F: Fn(WebViewId, HttpRequest<Vec<u8>>) -> HttpResponse<Cow<'static, [u8]>> + 'static,
210    {
211        self.protocols.push((name.to_string(), Box::new(handler)));
212        self
213    }
214
215    /// Set an asynchronous custom protocol
216    ///
217    /// **Example Usage**
218    /// ```rust
219    /// # use wry::http::response::Response as HTTPResponse;
220    /// # use std::borrow::Cow;
221    /// # use dioxus_desktop::Config;
222    /// #
223    /// # fn main() {
224    /// let cfg = Config::new()
225    ///     .with_asynchronous_custom_protocol("asset", |_webview_id, request, responder| {
226    ///         tokio::spawn(async move {
227    ///             responder.respond(
228    ///                 HTTPResponse::builder()
229    ///                     .status(404)
230    ///                     .body(Cow::Borrowed("404 - Not Found".as_bytes()))
231    ///                     .unwrap()
232    ///             );
233    ///         });
234    ///     });
235    /// # }
236    /// ```
237    /// note a key difference between Dioxus and Wry, the protocol name doesn't explicitly need to be a
238    /// [`String`], but needs to implement [`ToString`].
239    ///
240    /// See [`wry`](wry::WebViewBuilder::with_asynchronous_custom_protocol) for more details on implementation
241    pub fn with_asynchronous_custom_protocol<F>(mut self, name: impl ToString, handler: F) -> Self
242    where
243        F: Fn(WebViewId, HttpRequest<Vec<u8>>, RequestAsyncResponder) + 'static,
244    {
245        self.asynchronous_protocols
246            .push((name.to_string(), Box::new(handler)));
247        self
248    }
249
250    /// Set a custom icon for this application
251    pub fn with_icon(mut self, icon: Icon) -> Self {
252        self.window.window.window_icon = Some(icon);
253        self
254    }
255
256    /// Inject additional content into the document's HEAD.
257    ///
258    /// This is useful for loading CSS libraries, JS libraries, etc.
259    pub fn with_custom_head(mut self, head: String) -> Self {
260        self.custom_head = Some(head);
261        self
262    }
263
264    /// Use a custom index.html instead of the default Dioxus one.
265    ///
266    /// Make sure your index.html is valid HTML.
267    ///
268    /// Dioxus injects some loader code into the closing body tag. Your document
269    /// must include a body element!
270    pub fn with_custom_index(mut self, index: String) -> Self {
271        self.custom_index = Some(index);
272        self
273    }
274
275    /// Set the name of the element that Dioxus will use as the root.
276    ///
277    /// This is akin to calling React.render() on the element with the specified name.
278    pub fn with_root_name(mut self, name: impl Into<String>) -> Self {
279        self.root_name = name.into();
280        self
281    }
282
283    /// Sets the background color of the WebView.
284    /// This will be set before the HTML is rendered and can be used to prevent flashing when the page loads.
285    /// Accepts a color in RGBA format
286    pub fn with_background_color(mut self, color: (u8, u8, u8, u8)) -> Self {
287        self.background_color = Some(color);
288        self
289    }
290
291    /// Sets the menu the window will use. This will override the default menu bar.
292    ///
293    /// > Note: Menu will be hidden if
294    /// > [`with_decorations`](tao::window::WindowBuilder::with_decorations)
295    /// > is set to false and passed into [`with_window`](Config::with_window)
296    #[allow(unused)]
297    pub fn with_menu(mut self, menu: impl Into<Option<DioxusMenu>>) -> Self {
298        #[cfg(not(any(target_os = "ios", target_os = "android")))]
299        {
300            if self.window.window.decorations {
301                self.menu = MenuBuilderState::Set(menu.into())
302            }
303        }
304        self
305    }
306
307    /// Allows modifying the window and virtual dom right after they are built, but before the webview is created.
308    ///
309    /// This is important for z-ordering textures in child windows. Note that this callback runs on
310    /// every window creation, so it's up to you to
311    pub fn with_on_window(mut self, f: impl FnMut(Arc<Window>, &mut VirtualDom) + 'static) -> Self {
312        self.on_window = Some(Box::new(f));
313        self
314    }
315}
316
317impl Default for Config {
318    fn default() -> Self {
319        Self::new()
320    }
321}
322
323// dirty trick, avoid introducing `image` at runtime
324// TODO: use serde when `Icon` impl serde
325//
326// This function should only be enabled when generating new icons.
327//
328// #[test]
329// #[ignore]
330// fn prepare_default_icon() {
331//     use image::io::Reader as ImageReader;
332//     use image::ImageFormat;
333//     use std::fs::File;
334//     use std::io::Cursor;
335//     use std::io::Write;
336//     use std::path::PathBuf;
337//     let png: &[u8] = include_bytes!("default_icon.png");
338//     let mut reader = ImageReader::new(Cursor::new(png));
339//     reader.set_format(ImageFormat::Png);
340//     let icon = reader.decode().unwrap();
341//     let bin = PathBuf::from(file!())
342//         .parent()
343//         .unwrap()
344//         .join("default_icon.bin");
345//     println!("{:?}", bin);
346//     let mut file = File::create(bin).unwrap();
347//     file.write_all(icon.as_bytes()).unwrap();
348//     println!("({}, {})", icon.width(), icon.height())
349// }