handle.rs 32 KB

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