mod.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. use crate::{
  2. server::{
  3. output::{print_console_info, PrettierOptions},
  4. setup_file_watcher,
  5. },
  6. BuildResult, CrateConfig, Result,
  7. };
  8. use dioxus_hot_reload::HotReloadMsg;
  9. use dioxus_html::HtmlCtx;
  10. use dioxus_rsx::hot_reload::*;
  11. use interprocess_docfix::local_socket::LocalSocketListener;
  12. use std::{
  13. process::{Child, Command},
  14. sync::{Arc, Mutex, RwLock},
  15. };
  16. use tokio::sync::broadcast::{self};
  17. #[cfg(feature = "plugin")]
  18. use plugin::PluginManager;
  19. use super::HotReloadState;
  20. pub async fn startup(config: CrateConfig) -> Result<()> {
  21. // ctrl-c shutdown checker
  22. let _crate_config = config.clone();
  23. let _ = ctrlc::set_handler(move || {
  24. #[cfg(feature = "plugin")]
  25. let _ = PluginManager::on_serve_shutdown(&_crate_config);
  26. std::process::exit(0);
  27. });
  28. let hot_reload_state = match config.hot_reload {
  29. true => {
  30. let FileMapBuildResult { map, errors } =
  31. FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
  32. for err in errors {
  33. log::error!("{}", err);
  34. }
  35. let file_map = Arc::new(Mutex::new(map));
  36. let hot_reload_tx = broadcast::channel(100).0;
  37. clear_paths();
  38. Some(HotReloadState {
  39. messages: hot_reload_tx.clone(),
  40. file_map: file_map.clone(),
  41. })
  42. }
  43. false => None,
  44. };
  45. serve(config, hot_reload_state).await?;
  46. Ok(())
  47. }
  48. /// Start the server without hot reload
  49. pub async fn serve(config: CrateConfig, hot_reload_state: Option<HotReloadState>) -> Result<()> {
  50. let (child, first_build_result) = start_desktop(&config)?;
  51. let currently_running_child: RwLock<Child> = RwLock::new(child);
  52. log::info!("🚀 Starting development server...");
  53. // We got to own watcher so that it exists for the duration of serve
  54. // Otherwise full reload won't work.
  55. let _watcher = setup_file_watcher(
  56. {
  57. let config = config.clone();
  58. move || {
  59. let mut current_child = currently_running_child.write().unwrap();
  60. current_child.kill()?;
  61. let (child, result) = start_desktop(&config)?;
  62. *current_child = child;
  63. Ok(result)
  64. }
  65. },
  66. &config,
  67. None,
  68. hot_reload_state.clone(),
  69. )
  70. .await?;
  71. // Print serve info
  72. print_console_info(
  73. &config,
  74. PrettierOptions {
  75. changed: vec![],
  76. warnings: first_build_result.warnings,
  77. elapsed_time: first_build_result.elapsed_time,
  78. },
  79. None,
  80. );
  81. match hot_reload_state {
  82. Some(hot_reload_state) => {
  83. start_desktop_hot_reload(hot_reload_state).await?;
  84. }
  85. None => {
  86. std::future::pending::<()>().await;
  87. }
  88. }
  89. Ok(())
  90. }
  91. async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()> {
  92. match LocalSocketListener::bind("@dioxusin") {
  93. Ok(local_socket_stream) => {
  94. let aborted = Arc::new(Mutex::new(false));
  95. // States
  96. // The open interprocess sockets
  97. let channels = Arc::new(Mutex::new(Vec::new()));
  98. // listen for connections
  99. std::thread::spawn({
  100. let file_map = hot_reload_state.file_map.clone();
  101. let channels = channels.clone();
  102. let aborted = aborted.clone();
  103. move || {
  104. loop {
  105. //accept() will block the thread when local_socket_stream is in blocking mode (default)
  106. match local_socket_stream.accept() {
  107. Ok(mut connection) => {
  108. // send any templates than have changed before the socket connected
  109. let templates: Vec<_> = {
  110. file_map
  111. .lock()
  112. .unwrap()
  113. .map
  114. .values()
  115. .filter_map(|(_, template_slot)| *template_slot)
  116. .collect()
  117. };
  118. for template in templates {
  119. if !send_msg(
  120. HotReloadMsg::UpdateTemplate(template),
  121. &mut connection,
  122. ) {
  123. continue;
  124. }
  125. }
  126. channels.lock().unwrap().push(connection);
  127. println!("Connected to hot reloading 🚀");
  128. }
  129. Err(err) => {
  130. if err.kind() != std::io::ErrorKind::WouldBlock {
  131. println!("Error connecting to hot reloading: {} (Hot reloading is a feature of the dioxus-cli. If you are not using the CLI, this error can be ignored)", err);
  132. }
  133. }
  134. }
  135. if *aborted.lock().unwrap() {
  136. break;
  137. }
  138. }
  139. }
  140. });
  141. let mut hot_reload_rx = hot_reload_state.messages.subscribe();
  142. while let Ok(template) = hot_reload_rx.recv().await {
  143. let channels = &mut *channels.lock().unwrap();
  144. let mut i = 0;
  145. while i < channels.len() {
  146. let channel = &mut channels[i];
  147. if send_msg(HotReloadMsg::UpdateTemplate(template), channel) {
  148. i += 1;
  149. } else {
  150. channels.remove(i);
  151. }
  152. }
  153. }
  154. }
  155. Err(error) => println!("failed to connect to hot reloading\n{error}"),
  156. }
  157. Ok(())
  158. }
  159. fn clear_paths() {
  160. if cfg!(target_os = "macos") {
  161. // On unix, if you force quit the application, it can leave the file socket open
  162. // This will cause the local socket listener to fail to open
  163. // We check if the file socket is already open from an old session and then delete it
  164. let paths = ["./dioxusin", "./@dioxusin"];
  165. for path in paths {
  166. let path = std::path::PathBuf::from(path);
  167. if path.exists() {
  168. let _ = std::fs::remove_file(path);
  169. }
  170. }
  171. }
  172. }
  173. fn send_msg(msg: HotReloadMsg, channel: &mut impl std::io::Write) -> bool {
  174. if let Ok(msg) = serde_json::to_string(&msg) {
  175. if channel.write_all(msg.as_bytes()).is_err() {
  176. return false;
  177. }
  178. if channel.write_all(&[b'\n']).is_err() {
  179. return false;
  180. }
  181. true
  182. } else {
  183. false
  184. }
  185. }
  186. pub fn start_desktop(config: &CrateConfig) -> Result<(Child, BuildResult)> {
  187. // Run the desktop application
  188. let result = crate::builder::build_desktop(config, true)?;
  189. match &config.executable {
  190. crate::ExecutableType::Binary(name)
  191. | crate::ExecutableType::Lib(name)
  192. | crate::ExecutableType::Example(name) => {
  193. let mut file = config.out_dir.join(name);
  194. if cfg!(windows) {
  195. file.set_extension("exe");
  196. }
  197. let child = Command::new(file.to_str().unwrap()).spawn()?;
  198. Ok((child, result))
  199. }
  200. }
  201. }