protocol.rs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. use dioxus_interpreter_js::{COMMON_JS, INTERPRETER_JS};
  2. use std::{
  3. borrow::Cow,
  4. path::{Path, PathBuf},
  5. };
  6. use wry::{
  7. http::{status::StatusCode, Request, Response},
  8. Result,
  9. };
  10. fn module_loader(root_name: &str) -> String {
  11. let js = INTERPRETER_JS.replace(
  12. "/*POST_HANDLE_EDITS*/",
  13. r#"// Prevent file inputs from opening the file dialog on click
  14. let inputs = document.querySelectorAll("input");
  15. for (let input of inputs) {
  16. if (!input.getAttribute("data-dioxus-file-listener")) {
  17. // prevent file inputs from opening the file dialog on click
  18. const type = input.getAttribute("type");
  19. if (type === "file") {
  20. input.setAttribute("data-dioxus-file-listener", true);
  21. input.addEventListener("click", (event) => {
  22. let target = event.target;
  23. let target_id = find_real_id(target);
  24. if (target_id !== null) {
  25. const send = (event_name) => {
  26. const message = serializeIpcMessage("file_diolog", { accept: target.getAttribute("accept"), directory: target.getAttribute("webkitdirectory") === "true", multiple: target.hasAttribute("multiple"), target: parseInt(target_id), bubbles: event_bubbles(event_name), event: event_name });
  27. window.ipc.postMessage(message);
  28. };
  29. send("change&input");
  30. }
  31. event.preventDefault();
  32. });
  33. }
  34. }
  35. }"#,
  36. );
  37. format!(
  38. r#"
  39. <script type="module">
  40. {js}
  41. let rootname = "{root_name}";
  42. let root = window.document.getElementById(rootname);
  43. if (root != null) {{
  44. window.interpreter = new Interpreter(root, new InterpreterConfig(true));
  45. window.ipc.postMessage(serializeIpcMessage("initialize"));
  46. }}
  47. </script>
  48. "#
  49. )
  50. }
  51. pub(super) fn desktop_handler(
  52. request: &Request<Vec<u8>>,
  53. custom_head: Option<String>,
  54. custom_index: Option<String>,
  55. root_name: &str,
  56. ) -> Result<Response<Cow<'static, [u8]>>> {
  57. // If the request is for the root, we'll serve the index.html file.
  58. if request.uri().path() == "/" {
  59. // If a custom index is provided, just defer to that, expecting the user to know what they're doing.
  60. // we'll look for the closing </body> tag and insert our little module loader there.
  61. let body = match custom_index {
  62. Some(custom_index) => custom_index
  63. .replace("</body>", &format!("{}</body>", module_loader(root_name)))
  64. .into_bytes(),
  65. None => {
  66. // Otherwise, we'll serve the default index.html and apply a custom head if that's specified.
  67. let mut template = include_str!("./index.html").to_string();
  68. if let Some(custom_head) = custom_head {
  69. template = template.replace("<!-- CUSTOM HEAD -->", &custom_head);
  70. }
  71. template
  72. .replace("<!-- MODULE LOADER -->", &module_loader(root_name))
  73. .into_bytes()
  74. }
  75. };
  76. return Response::builder()
  77. .header("Content-Type", "text/html")
  78. .body(Cow::from(body))
  79. .map_err(From::from);
  80. } else if request.uri().path() == "/common.js" {
  81. return Response::builder()
  82. .header("Content-Type", "text/javascript")
  83. .body(Cow::from(COMMON_JS.as_bytes()))
  84. .map_err(From::from);
  85. }
  86. // Else, try to serve a file from the filesystem.
  87. let decoded = urlencoding::decode(request.uri().path().trim_start_matches('/'))
  88. .expect("expected URL to be UTF-8 encoded");
  89. let path = PathBuf::from(&*decoded);
  90. // If the path is relative, we'll try to serve it from the assets directory.
  91. let mut asset = get_asset_root()
  92. .unwrap_or_else(|| Path::new(".").to_path_buf())
  93. .join(&path);
  94. if !asset.exists() {
  95. asset = PathBuf::from("/").join(path);
  96. }
  97. if asset.exists() {
  98. return Response::builder()
  99. .header("Content-Type", get_mime_from_path(&asset)?)
  100. .body(Cow::from(std::fs::read(asset)?))
  101. .map_err(From::from);
  102. }
  103. Response::builder()
  104. .status(StatusCode::NOT_FOUND)
  105. .body(Cow::from(String::from("Not Found").into_bytes()))
  106. .map_err(From::from)
  107. }
  108. #[allow(unreachable_code)]
  109. fn get_asset_root() -> Option<PathBuf> {
  110. /*
  111. We're matching exactly how cargo-bundle works.
  112. - [x] macOS
  113. - [ ] Windows
  114. - [ ] Linux (rpm)
  115. - [ ] Linux (deb)
  116. - [ ] iOS
  117. - [ ] Android
  118. */
  119. if std::env::var_os("CARGO").is_some() {
  120. return None;
  121. }
  122. // TODO: support for other platforms
  123. #[cfg(target_os = "macos")]
  124. {
  125. let bundle = core_foundation::bundle::CFBundle::main_bundle();
  126. let bundle_path = bundle.path()?;
  127. let resources_path = bundle.resources_path()?;
  128. let absolute_resources_root = bundle_path.join(resources_path);
  129. let canonical_resources_root = dunce::canonicalize(absolute_resources_root).ok()?;
  130. return Some(canonical_resources_root);
  131. }
  132. None
  133. }
  134. /// Get the mime type from a path-like string
  135. fn get_mime_from_path(trimmed: &Path) -> Result<&'static str> {
  136. if trimmed.extension().is_some_and(|ext| ext == "svg") {
  137. return Ok("image/svg+xml");
  138. }
  139. let res = match infer::get_from_path(trimmed)?.map(|f| f.mime_type()) {
  140. Some(f) => {
  141. if f == "text/plain" {
  142. get_mime_by_ext(trimmed)
  143. } else {
  144. f
  145. }
  146. }
  147. None => get_mime_by_ext(trimmed),
  148. };
  149. Ok(res)
  150. }
  151. /// Get the mime type from a URI using its extension
  152. fn get_mime_by_ext(trimmed: &Path) -> &'static str {
  153. match trimmed.extension().and_then(|e| e.to_str()) {
  154. Some("bin") => "application/octet-stream",
  155. Some("css") => "text/css",
  156. Some("csv") => "text/csv",
  157. Some("html") => "text/html",
  158. Some("ico") => "image/vnd.microsoft.icon",
  159. Some("js") => "text/javascript",
  160. Some("json") => "application/json",
  161. Some("jsonld") => "application/ld+json",
  162. Some("mjs") => "text/javascript",
  163. Some("rtf") => "application/rtf",
  164. Some("svg") => "image/svg+xml",
  165. Some("mp4") => "video/mp4",
  166. // Assume HTML when a TLD is found for eg. `dioxus:://dioxuslabs.app` | `dioxus://hello.com`
  167. Some(_) => "text/html",
  168. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
  169. // using octet stream according to this:
  170. None => "application/octet-stream",
  171. }
  172. }