handle.rs 33 KB

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