mod.rs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. use crate::server::Platform;
  2. use crate::{
  3. cfg::ConfigOptsServe,
  4. server::{
  5. output::{print_console_info, PrettierOptions},
  6. setup_file_watcher,
  7. },
  8. BuildResult, Result,
  9. };
  10. use dioxus_cli_config::CrateConfig;
  11. use dioxus_cli_config::ExecutableType;
  12. use dioxus_hot_reload::HotReloadMsg;
  13. use dioxus_html::HtmlCtx;
  14. use dioxus_rsx::hot_reload::*;
  15. use interprocess_docfix::local_socket::LocalSocketListener;
  16. use std::{
  17. process::{Child, Command},
  18. sync::{Arc, Mutex, RwLock},
  19. };
  20. use tokio::sync::broadcast::{self};
  21. #[cfg(feature = "plugin")]
  22. use plugin::PluginManager;
  23. use super::HotReloadState;
  24. pub async fn startup(config: CrateConfig, serve: &ConfigOptsServe) -> Result<()> {
  25. startup_with_platform::<DesktopPlatform>(config, serve).await
  26. }
  27. pub(crate) async fn startup_with_platform<P: Platform + Send + 'static>(
  28. config: CrateConfig,
  29. serve_cfg: &ConfigOptsServe,
  30. ) -> Result<()> {
  31. // ctrl-c shutdown checker
  32. let _crate_config = config.clone();
  33. let _ = ctrlc::set_handler(move || {
  34. #[cfg(feature = "plugin")]
  35. let _ = PluginManager::on_serve_shutdown(&_crate_config);
  36. std::process::exit(0);
  37. });
  38. let hot_reload_state = match config.hot_reload {
  39. true => {
  40. let FileMapBuildResult { map, errors } =
  41. FileMap::<HtmlCtx>::create(config.crate_dir.clone()).unwrap();
  42. for err in errors {
  43. log::error!("{}", err);
  44. }
  45. let file_map = Arc::new(Mutex::new(map));
  46. let hot_reload_tx = broadcast::channel(100).0;
  47. Some(HotReloadState {
  48. messages: hot_reload_tx.clone(),
  49. file_map: file_map.clone(),
  50. })
  51. }
  52. false => None,
  53. };
  54. serve::<P>(config, serve_cfg, hot_reload_state).await?;
  55. Ok(())
  56. }
  57. /// Start the server without hot reload
  58. async fn serve<P: Platform + Send + 'static>(
  59. config: CrateConfig,
  60. serve: &ConfigOptsServe,
  61. hot_reload_state: Option<HotReloadState>,
  62. ) -> Result<()> {
  63. let platform = RwLock::new(P::start(&config, serve)?);
  64. log::info!("🚀 Starting development server...");
  65. // We got to own watcher so that it exists for the duration of serve
  66. // Otherwise full reload won't work.
  67. let _watcher = setup_file_watcher(
  68. {
  69. let config = config.clone();
  70. move || platform.write().unwrap().rebuild(&config)
  71. },
  72. &config,
  73. None,
  74. hot_reload_state.clone(),
  75. )
  76. .await?;
  77. match hot_reload_state {
  78. Some(hot_reload_state) => {
  79. // The open interprocess sockets
  80. start_desktop_hot_reload(hot_reload_state).await?;
  81. }
  82. None => {
  83. std::future::pending::<()>().await;
  84. }
  85. }
  86. Ok(())
  87. }
  88. async fn start_desktop_hot_reload(hot_reload_state: HotReloadState) -> Result<()> {
  89. let metadata = cargo_metadata::MetadataCommand::new()
  90. .no_deps()
  91. .exec()
  92. .unwrap();
  93. let target_dir = metadata.target_directory.as_std_path();
  94. let path = target_dir.join("dioxusin");
  95. clear_paths(&path);
  96. match LocalSocketListener::bind(path) {
  97. Ok(local_socket_stream) => {
  98. let aborted = Arc::new(Mutex::new(false));
  99. // States
  100. // The open interprocess sockets
  101. let channels = Arc::new(Mutex::new(Vec::new()));
  102. // listen for connections
  103. std::thread::spawn({
  104. let file_map = hot_reload_state.file_map.clone();
  105. let channels = channels.clone();
  106. let aborted = aborted.clone();
  107. move || {
  108. loop {
  109. //accept() will block the thread when local_socket_stream is in blocking mode (default)
  110. match local_socket_stream.accept() {
  111. Ok(mut connection) => {
  112. // send any templates than have changed before the socket connected
  113. let templates: Vec<_> = {
  114. file_map
  115. .lock()
  116. .unwrap()
  117. .map
  118. .values()
  119. .filter_map(|(_, template_slot)| *template_slot)
  120. .collect()
  121. };
  122. for template in templates {
  123. if !send_msg(
  124. HotReloadMsg::UpdateTemplate(template),
  125. &mut connection,
  126. ) {
  127. continue;
  128. }
  129. }
  130. channels.lock().unwrap().push(connection);
  131. println!("Connected to hot reloading 🚀");
  132. }
  133. Err(err) => {
  134. let error_string = err.to_string();
  135. // Filter out any error messages about a operation that may block and an error message that triggers on some operating systems that says "Waiting for a process to open the other end of the pipe" without WouldBlock being set
  136. let display_error = err.kind() != std::io::ErrorKind::WouldBlock
  137. && !error_string.contains("Waiting for a process");
  138. if display_error {
  139. 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);
  140. }
  141. }
  142. }
  143. if *aborted.lock().unwrap() {
  144. break;
  145. }
  146. }
  147. }
  148. });
  149. let mut hot_reload_rx = hot_reload_state.messages.subscribe();
  150. while let Ok(template) = hot_reload_rx.recv().await {
  151. let channels = &mut *channels.lock().unwrap();
  152. let mut i = 0;
  153. while i < channels.len() {
  154. let channel = &mut channels[i];
  155. if send_msg(HotReloadMsg::UpdateTemplate(template), channel) {
  156. i += 1;
  157. } else {
  158. channels.remove(i);
  159. }
  160. }
  161. }
  162. }
  163. Err(error) => println!("failed to connect to hot reloading\n{error}"),
  164. }
  165. Ok(())
  166. }
  167. fn clear_paths(file_socket_path: &std::path::Path) {
  168. if cfg!(unix) {
  169. // On unix, if you force quit the application, it can leave the file socket open
  170. // This will cause the local socket listener to fail to open
  171. // We check if the file socket is already open from an old session and then delete it
  172. if file_socket_path.exists() {
  173. let _ = std::fs::remove_file(file_socket_path);
  174. }
  175. }
  176. }
  177. fn send_msg(msg: HotReloadMsg, channel: &mut impl std::io::Write) -> bool {
  178. if let Ok(msg) = serde_json::to_string(&msg) {
  179. if channel.write_all(msg.as_bytes()).is_err() {
  180. return false;
  181. }
  182. if channel.write_all(&[b'\n']).is_err() {
  183. return false;
  184. }
  185. true
  186. } else {
  187. false
  188. }
  189. }
  190. fn start_desktop(config: &CrateConfig, skip_assets: bool) -> Result<(RAIIChild, BuildResult)> {
  191. // Run the desktop application
  192. let result = crate::builder::build_desktop(config, true, skip_assets)?;
  193. match &config.executable {
  194. ExecutableType::Binary(name)
  195. | ExecutableType::Lib(name)
  196. | ExecutableType::Example(name) => {
  197. let mut file = config.out_dir().join(name);
  198. if cfg!(windows) {
  199. file.set_extension("exe");
  200. }
  201. let active = "DIOXUS_ACTIVE";
  202. let child = RAIIChild(
  203. Command::new(file.to_str().unwrap())
  204. .env(active, "true")
  205. .spawn()?,
  206. );
  207. Ok((child, result))
  208. }
  209. }
  210. }
  211. pub(crate) struct DesktopPlatform {
  212. currently_running_child: RAIIChild,
  213. skip_assets: bool,
  214. }
  215. impl Platform for DesktopPlatform {
  216. fn start(config: &CrateConfig, serve: &ConfigOptsServe) -> Result<Self> {
  217. let (child, first_build_result) = start_desktop(config, serve.skip_assets)?;
  218. log::info!("🚀 Starting development server...");
  219. // Print serve info
  220. print_console_info(
  221. config,
  222. PrettierOptions {
  223. changed: vec![],
  224. warnings: first_build_result.warnings,
  225. elapsed_time: first_build_result.elapsed_time,
  226. },
  227. None,
  228. );
  229. Ok(Self {
  230. currently_running_child: child,
  231. skip_assets: serve.skip_assets,
  232. })
  233. }
  234. fn rebuild(&mut self, config: &CrateConfig) -> Result<BuildResult> {
  235. self.currently_running_child.0.kill()?;
  236. let (child, result) = start_desktop(config, self.skip_assets)?;
  237. self.currently_running_child = child;
  238. Ok(result)
  239. }
  240. }
  241. struct RAIIChild(Child);
  242. impl Drop for RAIIChild {
  243. fn drop(&mut self) {
  244. let _ = self.0.kill();
  245. }
  246. }