protocol.rs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. use dioxus_interpreter_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"), 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>
  40. {js}
  41. let rootname = "{root_name}";
  42. let root = window.document.getElementById(rootname);
  43. if (root != null) {{
  44. window.interpreter = new Interpreter(root);
  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. }
  81. // Else, try to serve a file from the filesystem.
  82. let path = PathBuf::from(request.uri().path().trim_start_matches('/'));
  83. // If the path is relative, we'll try to serve it from the assets directory.
  84. let mut asset = get_asset_root()
  85. .unwrap_or_else(|| Path::new(".").to_path_buf())
  86. .join(&path);
  87. if !asset.exists() {
  88. asset = PathBuf::from("/").join(path);
  89. }
  90. if asset.exists() {
  91. return Response::builder()
  92. .header("Content-Type", get_mime_from_path(&asset)?)
  93. .body(Cow::from(std::fs::read(asset)?))
  94. .map_err(From::from);
  95. }
  96. Response::builder()
  97. .status(StatusCode::NOT_FOUND)
  98. .body(Cow::from(String::from("Not Found").into_bytes()))
  99. .map_err(From::from)
  100. }
  101. #[allow(unreachable_code)]
  102. fn get_asset_root() -> Option<PathBuf> {
  103. /*
  104. We're matching exactly how cargo-bundle works.
  105. - [x] macOS
  106. - [ ] Windows
  107. - [ ] Linux (rpm)
  108. - [ ] Linux (deb)
  109. - [ ] iOS
  110. - [ ] Android
  111. */
  112. if std::env::var_os("CARGO").is_some() {
  113. return None;
  114. }
  115. // TODO: support for other platforms
  116. #[cfg(target_os = "macos")]
  117. {
  118. let bundle = core_foundation::bundle::CFBundle::main_bundle();
  119. let bundle_path = bundle.path()?;
  120. let resources_path = bundle.resources_path()?;
  121. let absolute_resources_root = bundle_path.join(resources_path);
  122. let canonical_resources_root = dunce::canonicalize(absolute_resources_root).ok()?;
  123. return Some(canonical_resources_root);
  124. }
  125. None
  126. }
  127. /// Get the mime type from a path-like string
  128. fn get_mime_from_path(trimmed: &Path) -> Result<&'static str> {
  129. if trimmed.ends_with(".svg") {
  130. return Ok("image/svg+xml");
  131. }
  132. let res = match infer::get_from_path(trimmed)?.map(|f| f.mime_type()) {
  133. Some(t) if t == "text/plain" => get_mime_by_ext(trimmed),
  134. Some(f) => f,
  135. None => get_mime_by_ext(trimmed),
  136. };
  137. Ok(res)
  138. }
  139. /// Get the mime type from a URI using its extension
  140. fn get_mime_by_ext(trimmed: &Path) -> &'static str {
  141. match trimmed.extension().and_then(|e| e.to_str()) {
  142. Some("bin") => "application/octet-stream",
  143. Some("css") => "text/css",
  144. Some("csv") => "text/csv",
  145. Some("html") => "text/html",
  146. Some("ico") => "image/vnd.microsoft.icon",
  147. Some("js") => "text/javascript",
  148. Some("json") => "application/json",
  149. Some("jsonld") => "application/ld+json",
  150. Some("mjs") => "text/javascript",
  151. Some("rtf") => "application/rtf",
  152. Some("svg") => "image/svg+xml",
  153. Some("mp4") => "video/mp4",
  154. // Assume HTML when a TLD is found for eg. `dioxus:://dioxuslabs.app` | `dioxus://hello.com`
  155. Some(_) => "text/html",
  156. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
  157. // using octet stream according to this:
  158. None => "application/octet-stream",
  159. }
  160. }