lib.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. //! Dioxus Desktop Renderer
  2. //!
  3. //! Render the Dioxus VirtualDom using the platform's native WebView implementation.
  4. //!
  5. //! # Desktop
  6. //!
  7. //! One of Dioxus' killer features is the ability to quickly build a native desktop app that looks and feels the same across platforms. Apps built with Dioxus are typically <5mb in size and use existing system resources, so they won't hog extreme amounts of RAM or memory.
  8. //!
  9. //! Dioxus Desktop is built off Tauri. Right now there aren't any Dioxus abstractions over keyboard shortcuts, menubar, handling, etc, so you'll want to leverage Tauri - mostly [Wry](http://github.com/tauri-apps/wry/) and [Tao](http://github.com/tauri-apps/tao)) directly. The next major release of Dioxus-Desktop will include components and hooks for notifications, global shortcuts, menubar, etc.
  10. //!
  11. //!
  12. //! ## Getting Set up
  13. //!
  14. //! Getting Set up with Dioxus-Desktop is quite easy. Make sure you have Rust and Cargo installed, and then create a new project:
  15. //!
  16. //! ```shell
  17. //! $ cargo new --bin demo
  18. //! $ cd app
  19. //! ```
  20. //!
  21. //! Add Dioxus with the `desktop` feature:
  22. //!
  23. //! ```shell
  24. //! $ cargo add dioxus --features desktop
  25. //! ```
  26. //!
  27. //! Edit your `main.rs`:
  28. //!
  29. //! ```rust
  30. //! // main.rs
  31. //! use dioxus::prelude::*;
  32. //!
  33. //! fn main() {
  34. //! dioxus::desktop::launch(app);
  35. //! }
  36. //!
  37. //! fn app(cx: Scope) -> Element {
  38. //! cx.render(rsx!{
  39. //! div {
  40. //! "hello world!"
  41. //! }
  42. //! })
  43. //! }
  44. //! ```
  45. //!
  46. //!
  47. //! To configure the webview, menubar, and other important desktop-specific features, checkout out some of the launch configuration in the [API reference](https://docs.rs/dioxus-desktop/).
  48. //!
  49. //! ## Future Steps
  50. //!
  51. //! Make sure to read the [Dioxus Guide](https://dioxuslabs.com/guide) if you already haven't!
  52. pub mod cfg;
  53. pub mod desktop_context;
  54. pub mod escape;
  55. pub mod events;
  56. use cfg::DesktopConfig;
  57. pub use desktop_context::use_window;
  58. use desktop_context::DesktopContext;
  59. use dioxus_core::*;
  60. use std::{
  61. collections::{HashMap, VecDeque},
  62. sync::atomic::AtomicBool,
  63. sync::{Arc, RwLock},
  64. };
  65. use tao::{
  66. event::{Event, StartCause, WindowEvent},
  67. event_loop::{ControlFlow, EventLoop},
  68. window::{Window, WindowId},
  69. };
  70. pub use wry;
  71. pub use wry::application as tao;
  72. use wry::{
  73. application::event_loop::EventLoopProxy,
  74. webview::RpcRequest,
  75. webview::{WebView, WebViewBuilder},
  76. };
  77. /// Launch the WebView and run the event loop.
  78. ///
  79. /// This function will start a multithreaded Tokio runtime as well the WebView event loop.
  80. ///
  81. /// ```rust
  82. /// use dioxus::prelude::*;
  83. ///
  84. /// fn main() {
  85. /// dioxus::desktop::launch(app);
  86. /// }
  87. ///
  88. /// fn app(cx: Scope) -> Element {
  89. /// cx.render(rsx!{
  90. /// h1 {"hello world!"}
  91. /// })
  92. /// }
  93. /// ```
  94. pub fn launch(root: Component) {
  95. launch_with_props(root, (), |c| c)
  96. }
  97. /// Launch the WebView and run the event loop, with configuration.
  98. ///
  99. /// This function will start a multithreaded Tokio runtime as well the WebView event loop.
  100. ///
  101. /// You can configure the WebView window with a configuration closure
  102. ///
  103. /// ```rust
  104. /// use dioxus::prelude::*;
  105. ///
  106. /// fn main() {
  107. /// dioxus::desktop::launch_cfg(app, |c| c.with_window(|w| w.with_title("My App")));
  108. /// }
  109. ///
  110. /// fn app(cx: Scope) -> Element {
  111. /// cx.render(rsx!{
  112. /// h1 {"hello world!"}
  113. /// })
  114. /// }
  115. /// ```
  116. pub fn launch_cfg(
  117. root: Component,
  118. config_builder: impl FnOnce(&mut DesktopConfig) -> &mut DesktopConfig,
  119. ) {
  120. launch_with_props(root, (), config_builder)
  121. }
  122. /// Launch the WebView and run the event loop, with configuration and root props.
  123. ///
  124. /// This function will start a multithreaded Tokio runtime as well the WebView event loop.
  125. ///
  126. /// You can configure the WebView window with a configuration closure
  127. ///
  128. /// ```rust
  129. /// use dioxus::prelude::*;
  130. ///
  131. /// fn main() {
  132. /// dioxus::desktop::launch_cfg(app, AppProps { name: "asd" }, |c| c);
  133. /// }
  134. ///
  135. /// struct AppProps {
  136. /// name: &'static str
  137. /// }
  138. ///
  139. /// fn app(cx: Scope<AppProps>) -> Element {
  140. /// cx.render(rsx!{
  141. /// h1 {"hello {cx.props.name}!"}
  142. /// })
  143. /// }
  144. /// ```
  145. pub fn launch_with_props<P: 'static + Send>(
  146. root: Component<P>,
  147. props: P,
  148. builder: impl FnOnce(&mut DesktopConfig) -> &mut DesktopConfig,
  149. ) {
  150. let mut cfg = DesktopConfig::default();
  151. builder(&mut cfg);
  152. let event_loop = EventLoop::with_user_event();
  153. let mut desktop = DesktopController::new_on_tokio(root, props, event_loop.create_proxy());
  154. let proxy = event_loop.create_proxy();
  155. event_loop.run(move |window_event, event_loop, control_flow| {
  156. *control_flow = ControlFlow::Wait;
  157. match window_event {
  158. Event::NewEvents(StartCause::Init) => {
  159. let builder = cfg.window.clone();
  160. let window = builder.build(event_loop).unwrap();
  161. let window_id = window.id();
  162. let (is_ready, sender) = (desktop.is_ready.clone(), desktop.sender.clone());
  163. let proxy = proxy.clone();
  164. let file_handler = cfg.file_drop_handler.take();
  165. let mut webview = WebViewBuilder::new(window)
  166. .unwrap()
  167. .with_url("dioxus://index.html/")
  168. .unwrap()
  169. .with_rpc_handler(move |_window: &Window, req: RpcRequest| {
  170. match req.method.as_str() {
  171. "user_event" => {
  172. let event = events::trigger_from_serialized(req.params.unwrap());
  173. log::trace!("User event: {:?}", event);
  174. sender.unbounded_send(SchedulerMsg::Event(event)).unwrap();
  175. }
  176. "initialize" => {
  177. is_ready.store(true, std::sync::atomic::Ordering::Relaxed);
  178. let _ = proxy.send_event(UserWindowEvent::Update);
  179. }
  180. "browser_open" => {
  181. println!("browser_open");
  182. let data = req.params.unwrap();
  183. log::trace!("Open browser: {:?}", data);
  184. if let Some(arr) = data.as_array() {
  185. if let Some(temp) = arr[0].as_object() {
  186. if temp.contains_key("href") {
  187. let url = temp.get("href").unwrap().as_str().unwrap();
  188. if let Err(e) = webbrowser::open(url) {
  189. log::error!("Open Browser error: {:?}", e);
  190. }
  191. }
  192. }
  193. }
  194. }
  195. _ => {}
  196. }
  197. None
  198. })
  199. .with_custom_protocol(String::from("dioxus"), move |request| {
  200. // Any content that that uses the `dioxus://` scheme will be shuttled through this handler as a "special case"
  201. // For now, we only serve two pieces of content which get included as bytes into the final binary.
  202. let path = request.uri().replace("dioxus://", "");
  203. // all assets shouldbe called from index.html
  204. let trimmed = path.trim_start_matches("index.html/");
  205. if trimmed.is_empty() {
  206. wry::http::ResponseBuilder::new()
  207. .mimetype("text/html")
  208. .body(include_bytes!("./index.html").to_vec())
  209. } else if trimmed == "index.js" {
  210. wry::http::ResponseBuilder::new()
  211. .mimetype("text/javascript")
  212. .body(dioxus_interpreter_js::INTERPRTER_JS.as_bytes().to_vec())
  213. } else {
  214. // Read the file content from file path
  215. use std::fs::read;
  216. let path_buf = std::path::Path::new(trimmed).canonicalize()?;
  217. let cur_path = std::path::Path::new(".").canonicalize()?;
  218. if !path_buf.starts_with(cur_path) {
  219. return wry::http::ResponseBuilder::new()
  220. .status(wry::http::status::StatusCode::FORBIDDEN)
  221. .body(String::from("Forbidden").into_bytes());
  222. }
  223. if !path_buf.exists() {
  224. return wry::http::ResponseBuilder::new()
  225. .status(wry::http::status::StatusCode::NOT_FOUND)
  226. .body(String::from("Not Found").into_bytes());
  227. }
  228. let mime = mime_guess::from_path(&path_buf).first_or_octet_stream();
  229. // do not let path searching to go two layers beyond the caller level
  230. let data = read(path_buf)?;
  231. let meta = format!("{}", mime);
  232. wry::http::ResponseBuilder::new().mimetype(&meta).body(data)
  233. }
  234. })
  235. .with_file_drop_handler(move |window, evet| {
  236. file_handler
  237. .as_ref()
  238. .map(|handler| handler(window, evet))
  239. .unwrap_or_default()
  240. });
  241. for (name, handler) in cfg.protocos.drain(..) {
  242. webview = webview.with_custom_protocol(name, handler)
  243. }
  244. desktop.webviews.insert(window_id, webview.build().unwrap());
  245. }
  246. Event::WindowEvent {
  247. event, window_id, ..
  248. } => match event {
  249. WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
  250. WindowEvent::Destroyed { .. } => desktop.close_window(window_id, control_flow),
  251. WindowEvent::Resized(_) | WindowEvent::Moved(_) => {
  252. if let Some(view) = desktop.webviews.get_mut(&window_id) {
  253. let _ = view.resize();
  254. }
  255. }
  256. _ => {}
  257. },
  258. Event::UserEvent(_evt) => {
  259. //
  260. match _evt {
  261. UserWindowEvent::Update => desktop.try_load_ready_webviews(),
  262. UserWindowEvent::DragWindow => {
  263. // this loop just run once, because dioxus-desktop is unsupport multi-window.
  264. for webview in desktop.webviews.values() {
  265. let window = webview.window();
  266. // start to drag the window.
  267. // if the drag_window have any err. we don't do anything.
  268. let _ = window.drag_window();
  269. }
  270. }
  271. UserWindowEvent::CloseWindow => {
  272. // close window
  273. *control_flow = ControlFlow::Exit;
  274. }
  275. UserWindowEvent::Minimize(state) => {
  276. // this loop just run once, because dioxus-desktop is unsupport multi-window.
  277. for webview in desktop.webviews.values() {
  278. let window = webview.window();
  279. // change window minimized state.
  280. window.set_minimized(state);
  281. }
  282. }
  283. UserWindowEvent::Maximize(state) => {
  284. // this loop just run once, because dioxus-desktop is unsupport multi-window.
  285. for webview in desktop.webviews.values() {
  286. let window = webview.window();
  287. // change window maximized state.
  288. window.set_maximized(state);
  289. }
  290. }
  291. UserWindowEvent::FocusWindow => {
  292. for webview in desktop.webviews.values() {
  293. let window = webview.window();
  294. window.set_focus();
  295. }
  296. }
  297. }
  298. }
  299. Event::MainEventsCleared => {}
  300. Event::Resumed => {}
  301. Event::Suspended => {}
  302. Event::LoopDestroyed => {}
  303. Event::RedrawRequested(_id) => {}
  304. _ => {}
  305. }
  306. })
  307. }
  308. pub enum UserWindowEvent {
  309. Update,
  310. DragWindow,
  311. CloseWindow,
  312. FocusWindow,
  313. Minimize(bool),
  314. Maximize(bool),
  315. }
  316. pub struct DesktopController {
  317. pub proxy: EventLoopProxy<UserWindowEvent>,
  318. pub webviews: HashMap<WindowId, WebView>,
  319. pub sender: futures_channel::mpsc::UnboundedSender<SchedulerMsg>,
  320. pub pending_edits: Arc<RwLock<VecDeque<String>>>,
  321. pub quit_app_on_close: bool,
  322. pub is_ready: Arc<AtomicBool>,
  323. }
  324. impl DesktopController {
  325. // Launch the virtualdom on its own thread managed by tokio
  326. // returns the desktop state
  327. pub fn new_on_tokio<P: Send + 'static>(
  328. root: Component<P>,
  329. props: P,
  330. evt: EventLoopProxy<UserWindowEvent>,
  331. ) -> Self {
  332. let edit_queue = Arc::new(RwLock::new(VecDeque::new()));
  333. let pending_edits = edit_queue.clone();
  334. let (sender, receiver) = futures_channel::mpsc::unbounded::<SchedulerMsg>();
  335. let return_sender = sender.clone();
  336. let proxy = evt.clone();
  337. let desktop_context_proxy = proxy.clone();
  338. std::thread::spawn(move || {
  339. // We create the runtime as multithreaded, so you can still "spawn" onto multiple threads
  340. let runtime = tokio::runtime::Builder::new_multi_thread()
  341. .enable_all()
  342. .build()
  343. .unwrap();
  344. runtime.block_on(async move {
  345. let mut dom =
  346. VirtualDom::new_with_props_and_scheduler(root, props, (sender, receiver));
  347. let window_context = DesktopContext::new(desktop_context_proxy);
  348. dom.base_scope().provide_context(window_context);
  349. let edits = dom.rebuild();
  350. edit_queue
  351. .write()
  352. .unwrap()
  353. .push_front(serde_json::to_string(&edits.edits).unwrap());
  354. loop {
  355. dom.wait_for_work().await;
  356. let mut muts = dom.work_with_deadline(|| false);
  357. while let Some(edit) = muts.pop() {
  358. edit_queue
  359. .write()
  360. .unwrap()
  361. .push_front(serde_json::to_string(&edit.edits).unwrap());
  362. }
  363. let _ = evt.send_event(UserWindowEvent::Update);
  364. }
  365. })
  366. });
  367. Self {
  368. pending_edits,
  369. sender: return_sender,
  370. proxy,
  371. webviews: HashMap::new(),
  372. is_ready: Arc::new(AtomicBool::new(false)),
  373. quit_app_on_close: true,
  374. }
  375. }
  376. pub fn close_window(&mut self, window_id: WindowId, control_flow: &mut ControlFlow) {
  377. self.webviews.remove(&window_id);
  378. if self.webviews.is_empty() && self.quit_app_on_close {
  379. *control_flow = ControlFlow::Exit;
  380. }
  381. }
  382. pub fn try_load_ready_webviews(&mut self) {
  383. if self.is_ready.load(std::sync::atomic::Ordering::Relaxed) {
  384. let mut queue = self.pending_edits.write().unwrap();
  385. let (_id, view) = self.webviews.iter_mut().next().unwrap();
  386. while let Some(edit) = queue.pop_back() {
  387. view.evaluate_script(&format!("window.interpreter.handleEdits({})", edit))
  388. .unwrap();
  389. }
  390. } else {
  391. println!("waiting for ready");
  392. }
  393. }
  394. }