config.rs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. use std::borrow::Cow;
  2. use std::path::PathBuf;
  3. use dioxus_core::prelude::Component;
  4. use tao::window::{Icon, WindowBuilder, WindowId};
  5. use wry::{
  6. http::{Request as HttpRequest, Response as HttpResponse},
  7. FileDropEvent,
  8. };
  9. /// The behaviour of the application when the last window is closed.
  10. #[derive(Copy, Clone, Eq, PartialEq)]
  11. pub enum WindowCloseBehaviour {
  12. /// Default behaviour, closing the last window exits the app
  13. LastWindowExitsApp,
  14. /// Closing the last window will not actually close it, just hide it
  15. LastWindowHides,
  16. /// Closing the last window will close it but the app will keep running so that new windows can be opened
  17. CloseWindow,
  18. }
  19. /// The configuration for the desktop application.
  20. pub struct Config {
  21. pub(crate) window: WindowBuilder,
  22. pub(crate) file_drop_handler: Option<DropHandler>,
  23. pub(crate) protocols: Vec<WryProtocol>,
  24. pub(crate) pre_rendered: Option<String>,
  25. pub(crate) disable_context_menu: bool,
  26. pub(crate) resource_dir: Option<PathBuf>,
  27. pub(crate) data_dir: Option<PathBuf>,
  28. pub(crate) custom_head: Option<String>,
  29. pub(crate) custom_index: Option<String>,
  30. pub(crate) root_name: String,
  31. pub(crate) background_color: Option<(u8, u8, u8, u8)>,
  32. pub(crate) last_window_close_behaviour: WindowCloseBehaviour,
  33. pub(crate) enable_default_menu_bar: bool,
  34. }
  35. type DropHandler = Box<dyn Fn(WindowId, FileDropEvent) -> bool>;
  36. pub(crate) type WryProtocol = (
  37. String,
  38. Box<dyn Fn(HttpRequest<Vec<u8>>) -> HttpResponse<Cow<'static, [u8]>> + 'static>,
  39. );
  40. impl Config {
  41. /// Initializes a new `WindowBuilder` with default values.
  42. #[inline]
  43. pub fn new() -> Self {
  44. let window = WindowBuilder::new().with_title(
  45. dioxus_cli_config::CURRENT_CONFIG
  46. .as_ref()
  47. .map(|c| c.dioxus_config.application.name.clone())
  48. .unwrap_or("Dioxus App".to_string()),
  49. );
  50. Self {
  51. // event_handler: None,
  52. window,
  53. protocols: Vec::new(),
  54. file_drop_handler: None,
  55. pre_rendered: None,
  56. disable_context_menu: !cfg!(debug_assertions),
  57. resource_dir: None,
  58. data_dir: None,
  59. custom_head: None,
  60. custom_index: None,
  61. root_name: "main".to_string(),
  62. background_color: None,
  63. last_window_close_behaviour: WindowCloseBehaviour::LastWindowExitsApp,
  64. enable_default_menu_bar: true,
  65. }
  66. }
  67. /// Launch a Dioxus app using the given component and config
  68. ///
  69. /// See the [`crate::launch::launch`] function for more details.
  70. pub fn launch(self, root: Component<()>) {
  71. crate::launch::launch_cfg(root, self)
  72. }
  73. /// Launch a Dioxus app using the given component, config, and props
  74. ///
  75. /// See the [`crate::launch::launch_with_props`] function for more details.
  76. pub fn launch_with_props<P: 'static + Clone>(self, root: Component<P>, props: P) {
  77. crate::launch::launch_with_props(root, props, self)
  78. }
  79. /// Set whether the default menu bar should be enabled.
  80. ///
  81. /// > Note: `enable` is `true` by default. To disable the default menu bar pass `false`.
  82. pub fn with_default_menu_bar(mut self, enable: bool) -> Self {
  83. self.enable_default_menu_bar = enable;
  84. self
  85. }
  86. /// set the directory from which assets will be searched in release mode
  87. pub fn with_resource_directory(mut self, path: impl Into<PathBuf>) -> Self {
  88. self.resource_dir = Some(path.into());
  89. self
  90. }
  91. /// set the directory where data will be stored in release mode.
  92. ///
  93. /// > Note: This **must** be set when bundling on Windows.
  94. pub fn with_data_directory(mut self, path: impl Into<PathBuf>) -> Self {
  95. self.data_dir = Some(path.into());
  96. self
  97. }
  98. /// Set whether or not the right-click context menu should be disabled.
  99. pub fn with_disable_context_menu(mut self, disable: bool) -> Self {
  100. self.disable_context_menu = disable;
  101. self
  102. }
  103. /// Set the pre-rendered HTML content
  104. pub fn with_prerendered(mut self, content: String) -> Self {
  105. self.pre_rendered = Some(content);
  106. self
  107. }
  108. /// Set the configuration for the window.
  109. pub fn with_window(mut self, window: WindowBuilder) -> Self {
  110. // gots to do a swap because the window builder only takes itself as muy self
  111. // I wish more people knew about returning &mut Self
  112. self.window = window;
  113. self
  114. }
  115. /// Sets the behaviour of the application when the last window is closed.
  116. pub fn with_close_behaviour(mut self, behaviour: WindowCloseBehaviour) -> Self {
  117. self.last_window_close_behaviour = behaviour;
  118. self
  119. }
  120. /// Set a file drop handler. If this is enabled, html drag events will be disabled.
  121. pub fn with_file_drop_handler(
  122. mut self,
  123. handler: impl Fn(WindowId, FileDropEvent) -> bool + 'static,
  124. ) -> Self {
  125. self.file_drop_handler = Some(Box::new(handler));
  126. self
  127. }
  128. /// Set a custom protocol
  129. pub fn with_custom_protocol<F>(mut self, name: String, handler: F) -> Self
  130. where
  131. F: Fn(HttpRequest<Vec<u8>>) -> HttpResponse<Cow<'static, [u8]>> + 'static,
  132. {
  133. self.protocols.push((name, Box::new(handler)));
  134. self
  135. }
  136. /// Set a custom icon for this application
  137. pub fn with_icon(mut self, icon: Icon) -> Self {
  138. self.window.window.window_icon = Some(icon);
  139. self
  140. }
  141. /// Inject additional content into the document's HEAD.
  142. ///
  143. /// This is useful for loading CSS libraries, JS libraries, etc.
  144. pub fn with_custom_head(mut self, head: String) -> Self {
  145. self.custom_head = Some(head);
  146. self
  147. }
  148. /// Use a custom index.html instead of the default Dioxus one.
  149. ///
  150. /// Make sure your index.html is valid HTML.
  151. ///
  152. /// Dioxus injects some loader code into the closing body tag. Your document
  153. /// must include a body element!
  154. pub fn with_custom_index(mut self, index: String) -> Self {
  155. self.custom_index = Some(index);
  156. self
  157. }
  158. /// Set the name of the element that Dioxus will use as the root.
  159. ///
  160. /// This is akint to calling React.render() on the element with the specified name.
  161. pub fn with_root_name(mut self, name: impl Into<String>) -> Self {
  162. self.root_name = name.into();
  163. self
  164. }
  165. /// Sets the background color of the WebView.
  166. /// This will be set before the HTML is rendered and can be used to prevent flashing when the page loads.
  167. /// Accepts a color in RGBA format
  168. pub fn with_background_color(mut self, color: (u8, u8, u8, u8)) -> Self {
  169. self.background_color = Some(color);
  170. self
  171. }
  172. }
  173. impl Default for Config {
  174. fn default() -> Self {
  175. Self::new()
  176. }
  177. }
  178. // dirty trick, avoid introducing `image` at runtime
  179. // TODO: use serde when `Icon` impl serde
  180. //
  181. // This function should only be enabled when generating new icons.
  182. //
  183. // #[test]
  184. // #[ignore]
  185. // fn prepare_default_icon() {
  186. // use image::io::Reader as ImageReader;
  187. // use image::ImageFormat;
  188. // use std::fs::File;
  189. // use std::io::Cursor;
  190. // use std::io::Write;
  191. // use std::path::PathBuf;
  192. // let png: &[u8] = include_bytes!("default_icon.png");
  193. // let mut reader = ImageReader::new(Cursor::new(png));
  194. // reader.set_format(ImageFormat::Png);
  195. // let icon = reader.decode().unwrap();
  196. // let bin = PathBuf::from(file!())
  197. // .parent()
  198. // .unwrap()
  199. // .join("default_icon.bin");
  200. // println!("{:?}", bin);
  201. // let mut file = File::create(bin).unwrap();
  202. // file.write_all(icon.as_bytes()).unwrap();
  203. // println!("({}, {})", icon.width(), icon.height())
  204. // }