handle.rs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. use crate::{AppBundle, DioxusCrate, Platform, Result};
  2. use anyhow::Context;
  3. use dioxus_cli_opt::process_file_to;
  4. use std::{
  5. env,
  6. net::SocketAddr,
  7. path::{Path, PathBuf},
  8. process::Stdio,
  9. };
  10. use tokio::{
  11. io::{AsyncBufReadExt, BufReader, Lines},
  12. process::{Child, ChildStderr, ChildStdout, Command},
  13. };
  14. /// A handle to a running app.
  15. ///
  16. /// Also includes a handle to its server if it exists.
  17. /// The actual child processes might not be present (web) or running (died/killed).
  18. ///
  19. /// The purpose of this struct is to accumulate state about the running app and its server, like
  20. /// any runtime information needed to hotreload the app or send it messages.
  21. ///
  22. /// We might want to bring in websockets here too, so we know the exact channels the app is using to
  23. /// communicate with the devserver. Currently that's a broadcast-type system, so this struct isn't super
  24. /// duper useful.
  25. ///
  26. /// todo: restructure this such that "open" is a running task instead of blocking the main thread
  27. pub(crate) struct AppHandle {
  28. pub(crate) app: AppBundle,
  29. // These might be None if the app died or the user did not specify a server
  30. pub(crate) app_child: Option<Child>,
  31. pub(crate) server_child: Option<Child>,
  32. // stdio for the app so we can read its stdout/stderr
  33. // we don't map stdin today (todo) but most apps don't need it
  34. pub(crate) app_stdout: Option<Lines<BufReader<ChildStdout>>>,
  35. pub(crate) app_stderr: Option<Lines<BufReader<ChildStderr>>>,
  36. pub(crate) server_stdout: Option<Lines<BufReader<ChildStdout>>>,
  37. pub(crate) server_stderr: Option<Lines<BufReader<ChildStderr>>>,
  38. /// The executables but with some extra entropy in their name so we can run two instances of the
  39. /// same app without causing collisions on the filesystem.
  40. pub(crate) entropy_app_exe: Option<PathBuf>,
  41. pub(crate) entropy_server_exe: Option<PathBuf>,
  42. /// The virtual directory that assets will be served from
  43. /// Used mostly for apk/ipa builds since they live in simulator
  44. pub(crate) runtime_asst_dir: Option<PathBuf>,
  45. }
  46. impl AppHandle {
  47. pub async fn new(app: AppBundle) -> Result<Self> {
  48. Ok(AppHandle {
  49. app,
  50. runtime_asst_dir: None,
  51. app_child: None,
  52. app_stderr: None,
  53. app_stdout: None,
  54. server_child: None,
  55. server_stdout: None,
  56. server_stderr: None,
  57. entropy_app_exe: None,
  58. entropy_server_exe: None,
  59. })
  60. }
  61. pub(crate) async fn open(
  62. &mut self,
  63. devserver_ip: SocketAddr,
  64. open_address: Option<SocketAddr>,
  65. start_fullstack_on_address: Option<SocketAddr>,
  66. open_browser: bool,
  67. ) -> Result<()> {
  68. let krate = &self.app.build.krate;
  69. // Set the env vars that the clients will expect
  70. // These need to be stable within a release version (ie 0.6.0)
  71. let mut envs = vec![
  72. (dioxus_cli_config::CLI_ENABLED_ENV, "true".to_string()),
  73. (
  74. dioxus_cli_config::ALWAYS_ON_TOP_ENV,
  75. krate.settings.always_on_top.unwrap_or(true).to_string(),
  76. ),
  77. (
  78. dioxus_cli_config::APP_TITLE_ENV,
  79. krate.config.web.app.title.clone(),
  80. ),
  81. ("RUST_BACKTRACE", "1".to_string()),
  82. (
  83. dioxus_cli_config::DEVSERVER_IP_ENV,
  84. devserver_ip.ip().to_string(),
  85. ),
  86. (
  87. dioxus_cli_config::DEVSERVER_PORT_ENV,
  88. devserver_ip.port().to_string(),
  89. ),
  90. // unset the cargo dirs in the event we're running `dx` locally
  91. // since the child process will inherit the env vars, we don't want to confuse the downstream process
  92. ("CARGO_MANIFEST_DIR", "".to_string()),
  93. (
  94. dioxus_cli_config::SESSION_CACHE_DIR,
  95. self.app
  96. .build
  97. .krate
  98. .session_cache_dir()
  99. .display()
  100. .to_string(),
  101. ),
  102. ];
  103. if let Some(base_path) = &krate.config.web.app.base_path {
  104. envs.push((dioxus_cli_config::ASSET_ROOT_ENV, base_path.clone()));
  105. }
  106. if let Some(env_filter) = env::var_os("RUST_LOG").and_then(|e| e.into_string().ok()) {
  107. envs.push(("RUST_LOG", env_filter));
  108. }
  109. // Launch the server if we were given an address to start it on, and the build includes a server. After we
  110. // start the server, consume its stdout/stderr.
  111. if let (Some(addr), Some(server)) = (start_fullstack_on_address, self.server_exe()) {
  112. tracing::debug!("Proxying fullstack server from port {:?}", addr);
  113. envs.push((dioxus_cli_config::SERVER_IP_ENV, addr.ip().to_string()));
  114. envs.push((dioxus_cli_config::SERVER_PORT_ENV, addr.port().to_string()));
  115. tracing::debug!("Launching server from path: {server:?}");
  116. let mut child = Command::new(server)
  117. .envs(envs.clone())
  118. .stderr(Stdio::piped())
  119. .stdout(Stdio::piped())
  120. .kill_on_drop(true)
  121. .spawn()?;
  122. let stdout = BufReader::new(child.stdout.take().unwrap());
  123. let stderr = BufReader::new(child.stderr.take().unwrap());
  124. self.server_stdout = Some(stdout.lines());
  125. self.server_stderr = Some(stderr.lines());
  126. self.server_child = Some(child);
  127. }
  128. // We try to use stdin/stdout to communicate with the app
  129. let running_process = match self.app.build.build.platform() {
  130. // Unfortunately web won't let us get a proc handle to it (to read its stdout/stderr) so instead
  131. // use use the websocket to communicate with it. I wish we could merge the concepts here,
  132. // like say, opening the socket as a subprocess, but alas, it's simpler to do that somewhere else.
  133. Platform::Web => {
  134. // Only the first build we open the web app, after that the user knows it's running
  135. if open_browser {
  136. self.open_web(open_address.unwrap_or(devserver_ip));
  137. }
  138. None
  139. }
  140. Platform::Ios => Some(self.open_ios_sim(envs).await?),
  141. // https://developer.android.com/studio/run/emulator-commandline
  142. Platform::Android => {
  143. self.open_android_sim(devserver_ip, envs).await;
  144. None
  145. }
  146. // These are all just basically running the main exe, but with slightly different resource dir paths
  147. Platform::Server
  148. | Platform::MacOS
  149. | Platform::Windows
  150. | Platform::Linux
  151. | Platform::Liveview => Some(self.open_with_main_exe(envs)?),
  152. };
  153. // If we have a running process, we need to attach to it and wait for its outputs
  154. if let Some(mut child) = running_process {
  155. let stdout = BufReader::new(child.stdout.take().unwrap());
  156. let stderr = BufReader::new(child.stderr.take().unwrap());
  157. self.app_stdout = Some(stdout.lines());
  158. self.app_stderr = Some(stderr.lines());
  159. self.app_child = Some(child);
  160. }
  161. Ok(())
  162. }
  163. /// Gracefully kill the process and all of its children
  164. ///
  165. /// Uses the `SIGTERM` signal on unix and `taskkill` on windows.
  166. /// This complex logic is necessary for things like window state preservation to work properly.
  167. ///
  168. /// Also wipes away the entropy executables if they exist.
  169. pub(crate) async fn cleanup(&mut self) {
  170. // Soft-kill the process by sending a sigkill, allowing the process to clean up
  171. self.soft_kill().await;
  172. // Wipe out the entropy executables if they exist
  173. if let Some(entropy_app_exe) = self.entropy_app_exe.take() {
  174. _ = std::fs::remove_file(entropy_app_exe);
  175. }
  176. if let Some(entropy_server_exe) = self.entropy_server_exe.take() {
  177. _ = std::fs::remove_file(entropy_server_exe);
  178. }
  179. }
  180. /// Kill the app and server exes
  181. pub(crate) async fn soft_kill(&mut self) {
  182. use futures_util::FutureExt;
  183. // Kill any running executables on Windows
  184. let server_process = self.server_child.take();
  185. let client_process = self.app_child.take();
  186. let processes = [server_process, client_process]
  187. .into_iter()
  188. .flatten()
  189. .collect::<Vec<_>>();
  190. for mut process in processes {
  191. let Some(pid) = process.id() else {
  192. _ = process.kill().await;
  193. continue;
  194. };
  195. // on unix, we can send a signal to the process to shut down
  196. #[cfg(unix)]
  197. {
  198. _ = Command::new("kill")
  199. .args(["-s", "TERM", &pid.to_string()])
  200. .spawn();
  201. }
  202. // on windows, use the `taskkill` command
  203. #[cfg(windows)]
  204. {
  205. _ = Command::new("taskkill")
  206. .args(["/F", "/PID", &pid.to_string()])
  207. .spawn();
  208. }
  209. // join the wait with a 100ms timeout
  210. futures_util::select! {
  211. _ = process.wait().fuse() => {}
  212. _ = tokio::time::sleep(std::time::Duration::from_millis(1000)).fuse() => {}
  213. };
  214. }
  215. }
  216. /// Hotreload an asset in the running app.
  217. ///
  218. /// This will modify the build dir in place! Be careful! We generally assume you want all bundles
  219. /// to reflect the latest changes, so we will modify the bundle.
  220. ///
  221. /// However, not all platforms work like this, so we might also need to update a separate asset
  222. /// dir that the system simulator might be providing. We know this is the case for ios simulators
  223. /// and haven't yet checked for android.
  224. ///
  225. /// This will return the bundled name of the asset such that we can send it to the clients letting
  226. /// them know what to reload. It's not super important that this is robust since most clients will
  227. /// kick all stylsheets without necessarily checking the name.
  228. pub(crate) async fn hotreload_bundled_asset(&self, changed_file: &PathBuf) -> Option<PathBuf> {
  229. let mut bundled_name = None;
  230. // Use the build dir if there's no runtime asset dir as the override. For the case of ios apps,
  231. // we won't actually be using the build dir.
  232. let asset_dir = match self.runtime_asst_dir.as_ref() {
  233. Some(dir) => dir.to_path_buf().join("assets/"),
  234. None => self.app.build.asset_dir(),
  235. };
  236. tracing::debug!("Hotreloading asset {changed_file:?} in target {asset_dir:?}");
  237. // If the asset shares the same name in the bundle, reload that
  238. if let Some(legacy_asset_dir) = self.app.build.krate.legacy_asset_dir() {
  239. if changed_file.starts_with(&legacy_asset_dir) {
  240. tracing::debug!("Hotreloading legacy asset {changed_file:?}");
  241. let trimmed = changed_file.strip_prefix(legacy_asset_dir).unwrap();
  242. let res = std::fs::copy(changed_file, asset_dir.join(trimmed));
  243. bundled_name = Some(trimmed.to_path_buf());
  244. if let Err(e) = res {
  245. tracing::debug!("Failed to hotreload legacy asset {e}");
  246. }
  247. }
  248. }
  249. // Canonicalize the path as Windows may use long-form paths "\\\\?\\C:\\".
  250. let changed_file = dunce::canonicalize(changed_file)
  251. .inspect_err(|e| tracing::debug!("Failed to canonicalize hotreloaded asset: {e}"))
  252. .ok()?;
  253. // The asset might've been renamed thanks to the manifest, let's attempt to reload that too
  254. if let Some(resource) = self.app.app.assets.assets.get(&changed_file).as_ref() {
  255. let output_path = asset_dir.join(resource.bundled_path());
  256. // Remove the old asset if it exists
  257. _ = std::fs::remove_file(&output_path);
  258. // And then process the asset with the options into the **old** asset location. If we recompiled,
  259. // the asset would be in a new location because the contents and hash have changed. Since we are
  260. // hotreloading, we need to use the old asset location it was originally written to.
  261. let options = *resource.options();
  262. let res = process_file_to(&options, &changed_file, &output_path);
  263. bundled_name = Some(PathBuf::from(resource.bundled_path()));
  264. if let Err(e) = res {
  265. tracing::debug!("Failed to hotreload asset {e}");
  266. }
  267. }
  268. // If the emulator is android, we need to copy the asset to the device with `adb push asset /data/local/tmp/dx/assets/filename.ext`
  269. if self.app.build.build.platform() == Platform::Android {
  270. if let Some(bundled_name) = bundled_name.as_ref() {
  271. let target = dioxus_cli_config::android_session_cache_dir().join(bundled_name);
  272. tracing::debug!("Pushing asset to device: {target:?}");
  273. let res = tokio::process::Command::new(DioxusCrate::android_adb())
  274. .arg("push")
  275. .arg(&changed_file)
  276. .arg(target)
  277. .output()
  278. .await
  279. .context("Failed to push asset to device");
  280. if let Err(e) = res {
  281. tracing::debug!("Failed to push asset to device: {e}");
  282. }
  283. }
  284. }
  285. // Now we can return the bundled asset name to send to the hotreload engine
  286. bundled_name
  287. }
  288. /// Open the native app simply by running its main exe
  289. ///
  290. /// Eventually, for mac, we want to run the `.app` with `open` to fix issues with `dylib` paths,
  291. /// but for now, we just run the exe directly. Very few users should be caring about `dylib` search
  292. /// paths right now, but they will when we start to enable things like swift integration.
  293. ///
  294. /// Server/liveview/desktop are all basically the same, though
  295. fn open_with_main_exe(&mut self, envs: Vec<(&str, String)>) -> Result<Child> {
  296. // Create a new entropy app exe if we need to
  297. let main_exe = self.app_exe();
  298. let child = Command::new(main_exe)
  299. .envs(envs)
  300. .stderr(Stdio::piped())
  301. .stdout(Stdio::piped())
  302. .kill_on_drop(true)
  303. .spawn()?;
  304. Ok(child)
  305. }
  306. /// Open the web app by opening the browser to the given address.
  307. /// Check if we need to use https or not, and if so, add the protocol.
  308. /// Go to the basepath if that's set too.
  309. fn open_web(&self, address: SocketAddr) {
  310. let base_path = self.app.build.krate.config.web.app.base_path.clone();
  311. let https = self
  312. .app
  313. .build
  314. .krate
  315. .config
  316. .web
  317. .https
  318. .enabled
  319. .unwrap_or_default();
  320. let protocol = if https { "https" } else { "http" };
  321. let base_path = match base_path.as_deref() {
  322. Some(base_path) => format!("/{}", base_path.trim_matches('/')),
  323. None => "".to_owned(),
  324. };
  325. _ = open::that_detached(format!("{protocol}://{address}{base_path}"));
  326. }
  327. /// Use `xcrun` to install the app to the simulator
  328. /// With simulators, we're free to basically do anything, so we don't need to do any fancy codesigning
  329. /// or entitlements, or anything like that.
  330. ///
  331. /// However, if there's no simulator running, this *might* fail.
  332. ///
  333. /// TODO(jon): we should probably check if there's a simulator running before trying to install,
  334. /// and open the simulator if we have to.
  335. async fn open_ios_sim(&mut self, envs: Vec<(&str, String)>) -> Result<Child> {
  336. tracing::debug!(
  337. "Installing app to simulator {:?}",
  338. self.app.build.root_dir()
  339. );
  340. let res = Command::new("xcrun")
  341. .arg("simctl")
  342. .arg("install")
  343. .arg("booted")
  344. .arg(self.app.build.root_dir())
  345. .stderr(Stdio::piped())
  346. .stdout(Stdio::piped())
  347. .output()
  348. .await?;
  349. tracing::debug!("Installed app to simulator with exit code: {res:?}");
  350. // Remap the envs to the correct simctl env vars
  351. // iOS sim lets you pass env vars but they need to be in the format "SIMCTL_CHILD_XXX=XXX"
  352. let ios_envs = envs
  353. .iter()
  354. .map(|(k, v)| (format!("SIMCTL_CHILD_{k}"), v.clone()));
  355. let child = Command::new("xcrun")
  356. .arg("simctl")
  357. .arg("launch")
  358. .arg("--console")
  359. .arg("booted")
  360. .arg(self.app.build.krate.bundle_identifier())
  361. .envs(ios_envs)
  362. .stderr(Stdio::piped())
  363. .stdout(Stdio::piped())
  364. .kill_on_drop(true)
  365. .spawn()?;
  366. Ok(child)
  367. }
  368. /// We have this whole thing figured out, but we don't actually use it yet.
  369. ///
  370. /// Launching on devices is more complicated and requires us to codesign the app, which we don't
  371. /// currently do.
  372. ///
  373. /// Converting these commands shouldn't be too hard, but device support would imply we need
  374. /// better support for codesigning and entitlements.
  375. #[allow(unused)]
  376. async fn open_ios_device(&self) -> Result<()> {
  377. use serde_json::Value;
  378. let app_path = self.app.build.root_dir();
  379. install_app(&app_path).await?;
  380. // 2. Determine which device the app was installed to
  381. let device_uuid = get_device_uuid().await?;
  382. // 3. Get the installation URL of the app
  383. let installation_url = get_installation_url(&device_uuid, &app_path).await?;
  384. // 4. Launch the app into the background, paused
  385. launch_app_paused(&device_uuid, &installation_url).await?;
  386. // 5. Pick up the paused app and resume it
  387. resume_app(&device_uuid).await?;
  388. async fn install_app(app_path: &PathBuf) -> Result<()> {
  389. let output = Command::new("xcrun")
  390. .args(["simctl", "install", "booted"])
  391. .arg(app_path)
  392. .output()
  393. .await?;
  394. if !output.status.success() {
  395. return Err(format!("Failed to install app: {:?}", output).into());
  396. }
  397. Ok(())
  398. }
  399. async fn get_device_uuid() -> Result<String> {
  400. let output = Command::new("xcrun")
  401. .args([
  402. "devicectl",
  403. "list",
  404. "devices",
  405. "--json-output",
  406. "target/deviceid.json",
  407. ])
  408. .output()
  409. .await?;
  410. let json: Value =
  411. serde_json::from_str(&std::fs::read_to_string("target/deviceid.json")?)
  412. .context("Failed to parse xcrun output")?;
  413. let device_uuid = json["result"]["devices"][0]["identifier"]
  414. .as_str()
  415. .ok_or("Failed to extract device UUID")?
  416. .to_string();
  417. Ok(device_uuid)
  418. }
  419. async fn get_installation_url(device_uuid: &str, app_path: &Path) -> Result<String> {
  420. // xcrun devicectl device install app --device <uuid> --path <path> --json-output
  421. let output = Command::new("xcrun")
  422. .args([
  423. "devicectl",
  424. "device",
  425. "install",
  426. "app",
  427. "--device",
  428. device_uuid,
  429. &app_path.display().to_string(),
  430. "--json-output",
  431. "target/xcrun.json",
  432. ])
  433. .output()
  434. .await?;
  435. if !output.status.success() {
  436. return Err(format!("Failed to install app: {:?}", output).into());
  437. }
  438. let json: Value = serde_json::from_str(&std::fs::read_to_string("target/xcrun.json")?)
  439. .context("Failed to parse xcrun output")?;
  440. let installation_url = json["result"]["installedApplications"][0]["installationURL"]
  441. .as_str()
  442. .ok_or("Failed to extract installation URL")?
  443. .to_string();
  444. Ok(installation_url)
  445. }
  446. async fn launch_app_paused(device_uuid: &str, installation_url: &str) -> Result<()> {
  447. let output = Command::new("xcrun")
  448. .args([
  449. "devicectl",
  450. "device",
  451. "process",
  452. "launch",
  453. "--no-activate",
  454. "--verbose",
  455. "--device",
  456. device_uuid,
  457. installation_url,
  458. "--json-output",
  459. "target/launch.json",
  460. ])
  461. .output()
  462. .await?;
  463. if !output.status.success() {
  464. return Err(format!("Failed to launch app: {:?}", output).into());
  465. }
  466. Ok(())
  467. }
  468. async fn resume_app(device_uuid: &str) -> Result<()> {
  469. let json: Value = serde_json::from_str(&std::fs::read_to_string("target/launch.json")?)
  470. .context("Failed to parse xcrun output")?;
  471. let status_pid = json["result"]["process"]["processIdentifier"]
  472. .as_u64()
  473. .ok_or("Failed to extract process identifier")?;
  474. let output = Command::new("xcrun")
  475. .args([
  476. "devicectl",
  477. "device",
  478. "process",
  479. "resume",
  480. "--device",
  481. device_uuid,
  482. "--pid",
  483. &status_pid.to_string(),
  484. ])
  485. .output()
  486. .await?;
  487. if !output.status.success() {
  488. return Err(format!("Failed to resume app: {:?}", output).into());
  489. }
  490. Ok(())
  491. }
  492. unimplemented!("dioxus-cli doesn't support ios devices yet.")
  493. }
  494. #[allow(unused)]
  495. async fn codesign_ios(&self) -> Result<()> {
  496. const CODESIGN_ERROR: &str = r#"This is likely because you haven't
  497. - Created a provisioning profile before
  498. - Accepted the Apple Developer Program License Agreement
  499. The agreement changes frequently and might need to be accepted again.
  500. To accept the agreement, go to https://developer.apple.com/account
  501. To create a provisioning profile, follow the instructions here:
  502. https://developer.apple.com/documentation/xcode/sharing-your-teams-signing-certificates"#;
  503. let profiles_folder = dirs::home_dir()
  504. .context("Your machine has no home-dir")?
  505. .join("Library/MobileDevice/Provisioning Profiles");
  506. if !profiles_folder.exists() || profiles_folder.read_dir()?.next().is_none() {
  507. tracing::error!(
  508. r#"No provisioning profiles found when trying to codesign the app.
  509. We checked the folder: {}
  510. {CODESIGN_ERROR}
  511. "#,
  512. profiles_folder.display()
  513. )
  514. }
  515. let identities = Command::new("security")
  516. .args(["find-identity", "-v", "-p", "codesigning"])
  517. .output()
  518. .await
  519. .context("Failed to run `security find-identity -v -p codesigning`")
  520. .map(|e| {
  521. String::from_utf8(e.stdout)
  522. .context("Failed to parse `security find-identity -v -p codesigning`")
  523. })??;
  524. // Parsing this:
  525. // 51ADE4986E0033A5DB1C794E0D1473D74FD6F871 "Apple Development: jkelleyrtp@gmail.com (XYZYZY)"
  526. let app_dev_name = regex::Regex::new(r#""Apple Development: (.+)""#)
  527. .unwrap()
  528. .captures(&identities)
  529. .and_then(|caps| caps.get(1))
  530. .map(|m| m.as_str())
  531. .context(
  532. "Failed to find Apple Development in `security find-identity -v -p codesigning`",
  533. )?;
  534. // Acquire the provision file
  535. let provision_file = profiles_folder
  536. .read_dir()?
  537. .flatten()
  538. .find(|entry| {
  539. entry
  540. .file_name()
  541. .to_str()
  542. .map(|s| s.contains("mobileprovision"))
  543. .unwrap_or_default()
  544. })
  545. .context("Failed to find a provisioning profile. \n\n{CODESIGN_ERROR}")?;
  546. // The .mobileprovision file has some random binary thrown into into, but it's still basically a plist
  547. // Let's use the plist markers to find the start and end of the plist
  548. fn cut_plist(bytes: &[u8], byte_match: &[u8]) -> Option<usize> {
  549. bytes
  550. .windows(byte_match.len())
  551. .enumerate()
  552. .rev()
  553. .find(|(_, slice)| *slice == byte_match)
  554. .map(|(i, _)| i + byte_match.len())
  555. }
  556. let bytes = std::fs::read(provision_file.path())?;
  557. let cut1 = cut_plist(&bytes, b"<plist").context("Failed to parse .mobileprovision file")?;
  558. let cut2 = cut_plist(&bytes, r#"</dict>"#.as_bytes())
  559. .context("Failed to parse .mobileprovision file")?;
  560. let sub_bytes = &bytes[(cut1 - 6)..cut2];
  561. let mbfile: ProvisioningProfile =
  562. plist::from_bytes(sub_bytes).context("Failed to parse .mobileprovision file")?;
  563. #[derive(serde::Deserialize, Debug)]
  564. struct ProvisioningProfile {
  565. #[serde(rename = "TeamIdentifier")]
  566. team_identifier: Vec<String>,
  567. #[serde(rename = "ApplicationIdentifierPrefix")]
  568. application_identifier_prefix: Vec<String>,
  569. #[serde(rename = "Entitlements")]
  570. entitlements: Entitlements,
  571. }
  572. #[derive(serde::Deserialize, Debug)]
  573. struct Entitlements {
  574. #[serde(rename = "application-identifier")]
  575. application_identifier: String,
  576. #[serde(rename = "keychain-access-groups")]
  577. keychain_access_groups: Vec<String>,
  578. }
  579. let entielements_xml = format!(
  580. r#"
  581. <?xml version="1.0" encoding="UTF-8"?>
  582. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  583. <plist version="1.0"><dict>
  584. <key>application-identifier</key>
  585. <string>{APPLICATION_IDENTIFIER}</string>
  586. <key>keychain-access-groups</key>
  587. <array>
  588. <string>{APP_ID_ACCESS_GROUP}.*</string>
  589. </array>
  590. <key>get-task-allow</key>
  591. <true/>
  592. <key>com.apple.developer.team-identifier</key>
  593. <string>{TEAM_IDENTIFIER}</string>
  594. </dict></plist>
  595. "#,
  596. APPLICATION_IDENTIFIER = mbfile.entitlements.application_identifier,
  597. APP_ID_ACCESS_GROUP = mbfile.entitlements.keychain_access_groups[0],
  598. TEAM_IDENTIFIER = mbfile.team_identifier[0],
  599. );
  600. // write to a temp file
  601. let temp_file = tempfile::NamedTempFile::new()?;
  602. std::fs::write(temp_file.path(), entielements_xml)?;
  603. // codesign the app
  604. let output = Command::new("codesign")
  605. .args([
  606. "--force",
  607. "--entitlements",
  608. temp_file.path().to_str().unwrap(),
  609. "--sign",
  610. app_dev_name,
  611. ])
  612. .arg(self.app.build.root_dir())
  613. .output()
  614. .await
  615. .context("Failed to codesign the app")?;
  616. if !output.status.success() {
  617. let stderr = String::from_utf8(output.stderr).unwrap_or_default();
  618. return Err(format!("Failed to codesign the app: {stderr}").into());
  619. }
  620. Ok(())
  621. }
  622. async fn open_android_sim(
  623. &self,
  624. devserver_socket: SocketAddr,
  625. envs: Vec<(&'static str, String)>,
  626. ) {
  627. let apk_path = self.app.apk_path();
  628. let session_cache = self.app.build.krate.session_cache_dir();
  629. let full_mobile_app_name = self.app.build.krate.full_mobile_app_name();
  630. // Start backgrounded since .open() is called while in the arm of the top-level match
  631. tokio::task::spawn(async move {
  632. let port = devserver_socket.port();
  633. if let Err(e) = Command::new("adb")
  634. .arg("reverse")
  635. .arg(format!("tcp:{}", port))
  636. .arg(format!("tcp:{}", port))
  637. .stderr(Stdio::piped())
  638. .stdout(Stdio::piped())
  639. .output()
  640. .await
  641. {
  642. tracing::error!("failed to forward port {port}: {e}");
  643. }
  644. // Install
  645. // adb install -r app-debug.apk
  646. if let Err(e) = Command::new(DioxusCrate::android_adb())
  647. .arg("install")
  648. .arg("-r")
  649. .arg(apk_path)
  650. .stderr(Stdio::piped())
  651. .stdout(Stdio::piped())
  652. .output()
  653. .await
  654. {
  655. tracing::error!("Failed to install apk with `adb`: {e}");
  656. };
  657. // Write the env vars to a .env file in our session cache
  658. let env_file = session_cache.join(".env");
  659. let contents: String = envs
  660. .iter()
  661. .map(|(key, value)| format!("{key}={value}"))
  662. .collect::<Vec<_>>()
  663. .join("\n");
  664. _ = std::fs::write(&env_file, contents);
  665. // Push the env file to the device
  666. if let Err(e) = tokio::process::Command::new(DioxusCrate::android_adb())
  667. .arg("push")
  668. .arg(env_file)
  669. .arg(dioxus_cli_config::android_session_cache_dir().join(".env"))
  670. .output()
  671. .await
  672. .context("Failed to push asset to device")
  673. {
  674. tracing::error!("Failed to push .env file to device: {e}");
  675. }
  676. // eventually, use the user's MainActivity, not our MainActivity
  677. // adb shell am start -n dev.dioxus.main/dev.dioxus.main.MainActivity
  678. let activity_name = format!("{}/dev.dioxus.main.MainActivity", full_mobile_app_name,);
  679. if let Err(e) = Command::new(DioxusCrate::android_adb())
  680. .arg("shell")
  681. .arg("am")
  682. .arg("start")
  683. .arg("-n")
  684. .arg(activity_name)
  685. .stderr(Stdio::piped())
  686. .stdout(Stdio::piped())
  687. .output()
  688. .await
  689. {
  690. tracing::error!("Failed to start app with `adb`: {e}");
  691. };
  692. });
  693. }
  694. fn make_entropy_path(exe: &PathBuf) -> PathBuf {
  695. let id = uuid::Uuid::new_v4();
  696. let name = id.to_string();
  697. let some_entropy = name.split('-').next().unwrap();
  698. // Make a copy of the server exe with a new name
  699. let entropy_server_exe = exe.with_file_name(format!(
  700. "{}-{}",
  701. exe.file_name().unwrap().to_str().unwrap(),
  702. some_entropy
  703. ));
  704. std::fs::copy(exe, &entropy_server_exe).unwrap();
  705. entropy_server_exe
  706. }
  707. fn server_exe(&mut self) -> Option<PathBuf> {
  708. let mut server = self.app.server_exe()?;
  709. // Create a new entropy server exe if we need to
  710. if cfg!(target_os = "windows") || cfg!(target_os = "linux") {
  711. // If we already have an entropy server exe, return it - this is useful for re-opening the same app
  712. if let Some(existing_server) = self.entropy_server_exe.clone() {
  713. return Some(existing_server);
  714. }
  715. // Otherwise, create a new entropy server exe and save it for re-opning
  716. let entropy_server_exe = Self::make_entropy_path(&server);
  717. self.entropy_server_exe = Some(entropy_server_exe.clone());
  718. server = entropy_server_exe;
  719. }
  720. Some(server)
  721. }
  722. fn app_exe(&mut self) -> PathBuf {
  723. let mut main_exe = self.app.main_exe();
  724. // The requirement here is based on the platform, not necessarily our current architecture.
  725. let requires_entropy = match self.app.build.build.platform() {
  726. // When running "bundled", we don't need entropy
  727. Platform::Web => false,
  728. Platform::MacOS => false,
  729. Platform::Ios => false,
  730. Platform::Android => false,
  731. // But on platforms that aren't running as "bundled", we do.
  732. Platform::Windows => true,
  733. Platform::Linux => true,
  734. Platform::Server => true,
  735. Platform::Liveview => true,
  736. };
  737. if requires_entropy || std::env::var("DIOXUS_ENTROPY").is_ok() {
  738. // If we already have an entropy app exe, return it - this is useful for re-opening the same app
  739. if let Some(existing_app_exe) = self.entropy_app_exe.clone() {
  740. return existing_app_exe;
  741. }
  742. let entropy_app_exe = Self::make_entropy_path(&main_exe);
  743. self.entropy_app_exe = Some(entropy_app_exe.clone());
  744. main_exe = entropy_app_exe;
  745. }
  746. main_exe
  747. }
  748. }