lib.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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, window::Fullscreen},
  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::Visible(state) => {
  276. for webview in desktop.webviews.values() {
  277. let window = webview.window();
  278. window.set_visible(state);
  279. }
  280. }
  281. UserWindowEvent::Minimize(state) => {
  282. // this loop just run once, because dioxus-desktop is unsupport multi-window.
  283. for webview in desktop.webviews.values() {
  284. let window = webview.window();
  285. // change window minimized state.
  286. window.set_minimized(state);
  287. }
  288. }
  289. UserWindowEvent::Maximize(state) => {
  290. // this loop just run once, because dioxus-desktop is unsupport multi-window.
  291. for webview in desktop.webviews.values() {
  292. let window = webview.window();
  293. // change window maximized state.
  294. window.set_maximized(state);
  295. }
  296. }
  297. UserWindowEvent::Fullscreen(fullscreen) => {
  298. for webview in desktop.webviews.values() {
  299. let window = webview.window();
  300. window.set_fullscreen(*fullscreen.clone());
  301. }
  302. }
  303. UserWindowEvent::FocusWindow => {
  304. for webview in desktop.webviews.values() {
  305. let window = webview.window();
  306. window.set_focus();
  307. }
  308. }
  309. UserWindowEvent::Resizable(state) => {
  310. for webview in desktop.webviews.values() {
  311. let window = webview.window();
  312. window.set_resizable(state);
  313. }
  314. }
  315. UserWindowEvent::AlwaysOnTop(state) => {
  316. for webview in desktop.webviews.values() {
  317. let window = webview.window();
  318. window.set_always_on_top(state);
  319. }
  320. }
  321. UserWindowEvent::CursorVisible(state) => {
  322. for webview in desktop.webviews.values() {
  323. let window = webview.window();
  324. window.set_cursor_visible(state);
  325. }
  326. }
  327. UserWindowEvent::SetTitle(content) => {
  328. for webview in desktop.webviews.values() {
  329. let window = webview.window();
  330. window.set_title(&content);
  331. }
  332. }
  333. UserWindowEvent::SetDecorations(state) => {
  334. for webview in desktop.webviews.values() {
  335. let window = webview.window();
  336. window.set_decorations(state);
  337. }
  338. }
  339. }
  340. }
  341. Event::MainEventsCleared => {}
  342. Event::Resumed => {}
  343. Event::Suspended => {}
  344. Event::LoopDestroyed => {}
  345. Event::RedrawRequested(_id) => {}
  346. _ => {}
  347. }
  348. })
  349. }
  350. pub enum UserWindowEvent {
  351. Update,
  352. DragWindow,
  353. CloseWindow,
  354. FocusWindow,
  355. Visible(bool),
  356. Minimize(bool),
  357. Maximize(bool),
  358. Resizable(bool),
  359. AlwaysOnTop(bool),
  360. Fullscreen(Box<Option<Fullscreen>>),
  361. CursorVisible(bool),
  362. SetTitle(String),
  363. SetDecorations(bool),
  364. }
  365. pub struct DesktopController {
  366. pub proxy: EventLoopProxy<UserWindowEvent>,
  367. pub webviews: HashMap<WindowId, WebView>,
  368. pub sender: futures_channel::mpsc::UnboundedSender<SchedulerMsg>,
  369. pub pending_edits: Arc<RwLock<VecDeque<String>>>,
  370. pub quit_app_on_close: bool,
  371. pub is_ready: Arc<AtomicBool>,
  372. }
  373. impl DesktopController {
  374. // Launch the virtualdom on its own thread managed by tokio
  375. // returns the desktop state
  376. pub fn new_on_tokio<P: Send + 'static>(
  377. root: Component<P>,
  378. props: P,
  379. evt: EventLoopProxy<UserWindowEvent>,
  380. ) -> Self {
  381. let edit_queue = Arc::new(RwLock::new(VecDeque::new()));
  382. let pending_edits = edit_queue.clone();
  383. let (sender, receiver) = futures_channel::mpsc::unbounded::<SchedulerMsg>();
  384. let return_sender = sender.clone();
  385. let proxy = evt.clone();
  386. let desktop_context_proxy = proxy.clone();
  387. std::thread::spawn(move || {
  388. // We create the runtime as multithreaded, so you can still "spawn" onto multiple threads
  389. let runtime = tokio::runtime::Builder::new_multi_thread()
  390. .enable_all()
  391. .build()
  392. .unwrap();
  393. runtime.block_on(async move {
  394. let mut dom =
  395. VirtualDom::new_with_props_and_scheduler(root, props, (sender, receiver));
  396. let window_context = DesktopContext::new(desktop_context_proxy);
  397. dom.base_scope().provide_context(window_context);
  398. let edits = dom.rebuild();
  399. edit_queue
  400. .write()
  401. .unwrap()
  402. .push_front(serde_json::to_string(&edits.edits).unwrap());
  403. loop {
  404. dom.wait_for_work().await;
  405. let mut muts = dom.work_with_deadline(|| false);
  406. while let Some(edit) = muts.pop() {
  407. edit_queue
  408. .write()
  409. .unwrap()
  410. .push_front(serde_json::to_string(&edit.edits).unwrap());
  411. }
  412. let _ = evt.send_event(UserWindowEvent::Update);
  413. }
  414. })
  415. });
  416. Self {
  417. pending_edits,
  418. sender: return_sender,
  419. proxy,
  420. webviews: HashMap::new(),
  421. is_ready: Arc::new(AtomicBool::new(false)),
  422. quit_app_on_close: true,
  423. }
  424. }
  425. pub fn close_window(&mut self, window_id: WindowId, control_flow: &mut ControlFlow) {
  426. self.webviews.remove(&window_id);
  427. if self.webviews.is_empty() && self.quit_app_on_close {
  428. *control_flow = ControlFlow::Exit;
  429. }
  430. }
  431. pub fn try_load_ready_webviews(&mut self) {
  432. if self.is_ready.load(std::sync::atomic::Ordering::Relaxed) {
  433. let mut queue = self.pending_edits.write().unwrap();
  434. let (_id, view) = self.webviews.iter_mut().next().unwrap();
  435. while let Some(edit) = queue.pop_back() {
  436. view.evaluate_script(&format!("window.interpreter.handleEdits({})", edit))
  437. .unwrap();
  438. }
  439. } else {
  440. println!("waiting for ready");
  441. }
  442. }
  443. }