diff --git a/crates/ide-host/src/ops/ios.rs b/crates/ide-host/src/ops/ios.rs index 8fd9462e08..bbae5de3d1 100644 --- a/crates/ide-host/src/ops/ios.rs +++ b/crates/ide-host/src/ops/ios.rs @@ -8,9 +8,9 @@ async fn blocking(f: impl FnOnce() -> IdeResult + Send + ' tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))? } -/// The available iOS simulators, booted first; `None` outside macOS or when the project has no -/// Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has -/// no change feed, and one listing takes a fraction of a second. +/// The available iOS simulators, booted first, then the paired iPhones and iPads; `None` outside +/// macOS or when the project has no Xcode project or workspace at its root. Asked again whenever +/// the chooser opens: `simctl` has no change feed, and one listing takes a fraction of a second. #[command(trust = trusted)] pub async fn ios_simulators(host: &Host, window: &str) -> IdeResult>> { let root = host.project(window)?.root.clone(); diff --git a/crates/ide-run/src/simulator.rs b/crates/ide-run/src/simulator.rs index 05ef4316f3..2c2137e233 100644 --- a/crates/ide-run/src/simulator.rs +++ b/crates/ide-run/src/simulator.rs @@ -1,4 +1,5 @@ -//! iOS Simulators, through `xcrun simctl` (macOS only): the devices an Xcode project can run on. +//! iOS Simulators, through `xcrun simctl`, and connected iPhones and iPads, through +//! `xcrun devicectl` (macOS only): the devices an Xcode project can run on. //! //! Flutter projects get theirs from `flutter daemon` (`ide-flutter`), so only native Xcode //! projects use this. @@ -11,7 +12,8 @@ use specta::Type; use std::path::Path; use std::process::Command; -/// One simulator `simctl list devices available` reports. +/// One simulator `simctl list devices available` reports, or one physical device +/// `devicectl list devices` knows. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)] #[serde(rename_all = "camelCase")] pub struct IosSimulator { @@ -19,10 +21,18 @@ pub struct IosSimulator { pub name: String, /// The runtime, as Xcode shows it: `iOS 27.0`. pub runtime: String, - /// `Booted`, `Shutdown`, `Booting`, `Shutting Down`. + /// `Booted`, `Shutdown`, `Booting`, `Shutting Down`; for a physical device [`AVAILABLE`], + /// [`UNAVAILABLE`] (not connected) or [`DEVELOPER_MODE_OFF`]. pub state: String, + /// An iPhone or iPad rather than a simulator. + pub physical: bool, } +/// The states of a physical device. +pub const AVAILABLE: &str = "Available"; +pub const UNAVAILABLE: &str = "Unavailable"; +pub const DEVELOPER_MODE_OFF: &str = "Developer Mode Off"; + /// An Xcode project or workspace directly in `root`, outside a Flutter project (whose /// `ios/Runner.xcodeproj` sits one level down and whose devices come from Flutter). pub fn is_xcode_project(root: &Path) -> bool { @@ -54,7 +64,8 @@ pub fn parse_list(json: &str) -> IdeResult> { for d in list.as_array().into_iter().flatten() { let text = |key| d.get(key).and_then(Value::as_str).map(str::to_owned); let (Some(udid), Some(name), Some(state)) = (text("udid"), text("name"), text("state")) else { continue }; - devices.push((version.clone(), IosSimulator { udid, name, runtime: label.clone(), state })); + devices + .push((version.clone(), IosSimulator { udid, name, runtime: label.clone(), state, physical: false })); } } devices.sort_by(|(va, a), (vb, b)| { @@ -67,6 +78,67 @@ pub fn parse_list(json: &str) -> IdeResult> { Ok(devices.into_iter().map(|(_, d)| d).collect()) } +/// The physical iOS and iPadOS devices in `devicectl list devices --json-output` output, by name. +/// Reads the fields Xcode 15 and later write, falling back to the `properties` that replace them. +pub fn parse_devices(json: &str) -> IdeResult> { + let value: Value = serde_json::from_str(json).map_err(|e| IdeError::internal(format!("devicectl list: {e}")))?; + let mut devices = Vec::new(); + for d in value.pointer("/result/devices").and_then(Value::as_array).into_iter().flatten() { + let text = |old: &str, new: &str| { + d.pointer(old).or_else(|| d.pointer(new)).and_then(Value::as_str).unwrap_or_default().to_owned() + }; + let reality = text("/hardwareProperties/reality", "/properties/hardware/reality"); + let platform = text("/hardwareProperties/platform", "/properties/hardware/platform"); + let udid = text("/hardwareProperties/udid", "/properties/hardware/udid"); + if reality != "physical" || !matches!(&*platform, "iOS" | "iPadOS") || udid.is_empty() { + continue; + } + let version = d + .pointer("/deviceProperties/osVersionNumber") + .or_else(|| d.pointer("/properties/software/osVersionNumber/stringValue")) + .and_then(Value::as_str) + .unwrap_or_default(); + // `tunnelState` (`connected`, `disconnected`: reachable, connects on use) or `state`. + let connection = text("/connectionProperties/tunnelState", "/properties/connection/state"); + let developer_mode = d + .pointer("/deviceProperties/developerModeStatus") + .and_then(Value::as_str) + .map(str::to_owned) + .or_else(|| d.pointer("/properties/state/developerModeStatus")?.as_object()?.keys().next().cloned()); + let state = if connection == "unavailable" || connection.is_empty() { + UNAVAILABLE + } else if developer_mode.as_deref() == Some("disabled") { + DEVELOPER_MODE_OFF + } else { + AVAILABLE + }; + devices.push(IosSimulator { + udid, + name: text("/deviceProperties/name", "/properties/state/name"), + runtime: format!("{platform} {version}").trim().to_owned(), + state: state.to_owned(), + physical: true, + }); + } + devices.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.udid.cmp(&b.udid))); + Ok(devices) +} + +/// The physical devices paired with this Mac, as [`parse_devices`] reads them; none when +/// `devicectl` (Xcode 15 and later) is missing or fails. `dir` picks the project's Xcode. +pub fn devices(dir: &Path) -> Vec { + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos(); + let file = std::env::temp_dir().join(format!("openidea-devicectl-{}-{stamp}.json", std::process::id())); + let path = file.to_string_lossy().into_owned(); + let listed = run_in(Some(dir), "xcrun", &["devicectl", "list", "devices", "--quiet", "--json-output", &path]); + let json = std::fs::read_to_string(&file); + let _ = std::fs::remove_file(&file); + match (listed, json) { + (Ok(_), Ok(json)) => parse_devices(&json).unwrap_or_default(), + _ => Vec::new(), + } +} + /// `dir`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`). fn run_in(dir: Option<&Path>, program: &str, args: &[&str]) -> IdeResult { let mut cmd = Command::new(program); @@ -82,10 +154,12 @@ fn run_in(dir: Option<&Path>, program: &str, args: &[&str]) -> IdeResult Err(IdeError::unavailable(format!("{program} {} failed: {}", args.join(" "), stderr.trim()))) } -/// The available iOS simulators, sorted as [`parse_list`] does. -/// The available iOS simulators of the Xcode the project at `root` uses. +/// The available iOS simulators of the Xcode the project at `root` uses, sorted as +/// [`parse_list`] does, then the physical devices. pub fn list(root: &Path) -> IdeResult> { - parse_list(&run_in(Some(root), "xcrun", &["simctl", "list", "devices", "available", "--json"])?) + let mut list = parse_list(&run_in(Some(root), "xcrun", &["simctl", "list", "devices", "available", "--json"])?)?; + list.extend(devices(root)); + Ok(list) } /// Boots a simulator; returns once `simctl` has it booted. @@ -142,6 +216,42 @@ mod tests { assert_eq!(parse_list("{}").unwrap(), []); } + #[test] + fn lists_physical_devices_by_name_from_old_and_new_fields() { + // Trimmed `devicectl list devices --json-output` (Xcode 27): one device with the + // deprecated fields too, one with `properties` only, a simulator and a Mac. + let json = r#"{"info": {"outcome": "success"}, "result": {"devices": [ + {"hardwareProperties": {"reality": "physical", "platform": "iOS", "udid": "00008110-AAA"}, + "deviceProperties": {"name": "Work iPhone", "osVersionNumber": "27.3", "developerModeStatus": "enabled"}, + "connectionProperties": {"tunnelState": "disconnected"}, + "properties": {"hardware": {"reality": "physical", "platform": "iOS", "udid": "00008110-AAA"}, + "connection": {"state": "disconnected"}}}, + {"properties": {"hardware": {"reality": "physical", "platform": "iPadOS", "udid": "00008103-BBB"}, + "software": {"osVersionNumber": {"stringValue": "26.1"}}, + "state": {"name": "Test iPad", "developerModeStatus": {"disabled": {"mode": 0}}}, + "connection": {"state": "connected"}}}, + {"properties": {"hardware": {"reality": "physical", "platform": "iOS", "udid": "00008150-CCC"}, + "state": {"name": "Away iPhone", "developerModeStatus": {"enabled": {"mode": 1}}}, + "connection": {"state": "unavailable"}}}, + {"hardwareProperties": {"reality": "simulated", "platform": "iOS", "udid": "SIM"}, + "connectionProperties": {"tunnelState": "disconnected"}}, + {"hardwareProperties": {"reality": "physical", "platform": "macOS", "udid": "MAC"}, + "connectionProperties": {"tunnelState": "connected"}} + ]}}"#; + let devices = parse_devices(json).unwrap(); + let rows: Vec<_> = devices.iter().map(|d| (&*d.name, &*d.udid, &*d.runtime, &*d.state, d.physical)).collect(); + assert_eq!( + rows, + [ + ("Away iPhone", "00008150-CCC", "iOS", UNAVAILABLE, true), + ("Test iPad", "00008103-BBB", "iPadOS 26.1", DEVELOPER_MODE_OFF, true), + ("Work iPhone", "00008110-AAA", "iOS 27.3", AVAILABLE, true), + ] + ); + assert!(parse_devices("not json").is_err()); + assert_eq!(parse_devices(r#"{"info": {"outcome": "failed"}}"#).unwrap(), []); + } + #[test] fn finds_xcode_projects_at_the_root_only() { let dir = std::env::temp_dir().join(format!("ide-run-simulator-{}", std::process::id())); diff --git a/crates/ide-run/src/xcode.rs b/crates/ide-run/src/xcode.rs index d7a67d5c75..3ad97020af 100644 --- a/crates/ide-run/src/xcode.rs +++ b/crates/ide-run/src/xcode.rs @@ -3,7 +3,8 @@ //! projects without any, but it takes a second or two, too slow for detection. //! //! A scheme's run configuration builds it for the iOS Simulator and launches the app there with -//! `simctl`, or, for a macOS app, builds it for the Mac and runs its executable; +//! `simctl`, for a connected iPhone or iPad and launches it there with `devicectl`, or, for a +//! macOS app, builds it for the Mac and runs its executable; //! [`prepare`] turns the configuration into that process when it starts. use ide_core::{IdeError, IdeResult}; @@ -305,17 +306,32 @@ pub fn mac_executable(settings: &str) -> Result { } /// The built `.app` and its bundle id, from `xcodebuild -showBuildSettings -json`: the -/// scheme's first application target. -pub fn built_app(settings: &str) -> Result<(PathBuf, String), String> { +/// scheme's first application target for the iOS Simulator, or with `device` for an iPhone or +/// iPad, which runs only an app signed with a development team. +pub fn built_app(settings: &str, device: bool) -> Result<(PathBuf, String), String> { let apps = app_settings(settings)?; - let Some(app) = apps.iter().find(|b| b["PLATFORM_NAME"] == "iphonesimulator") else { + let (platform, target) = + if device { ("iphoneos", "an iOS device") } else { ("iphonesimulator", "the iOS Simulator") }; + let Some(app) = apps.iter().find(|b| b["PLATFORM_NAME"] == platform) else { return Err(match apps.first().and_then(|b| b["PLATFORM_NAME"].as_str()) { - Some(platform) => format!("The scheme builds an app for {platform}, not the iOS Simulator"), + Some(platform) => format!("The scheme builds an app for {platform}, not {target}"), None => "The scheme builds no application".to_owned(), }); }; let get = |key: &str| app[key].as_str().filter(|v| !v.is_empty()).ok_or(format!("The build settings have no {key}")); + if device && app["CODE_SIGNING_ALLOWED"] == "NO" { + return Err(format!( + "{} is built unsigned (CODE_SIGNING_ALLOWED = NO), and an iOS device runs only signed apps", + get("WRAPPER_NAME")? + )); + } + if device && app["CODE_SIGN_STYLE"] == "Automatic" && get("DEVELOPMENT_TEAM").is_err() { + return Err(format!( + "Signing {} for a device needs a development team: choose one under Signing & Capabilities in Xcode", + get("WRAPPER_NAME")? + )); + } Ok((Path::new(get("TARGET_BUILD_DIR")?).join(get("WRAPPER_NAME")?), get("PRODUCT_BUNDLE_IDENTIFIER")?.to_owned())) } @@ -372,6 +388,49 @@ fn announce_suspended(udid: &str, bundle_id: &str) -> String { ) } +/// The script a run on a physical device executes: build with the project's signing (letting +/// Xcode register the device and fetch profiles, as its own Run does), install, then launch with +/// the app's output on the console. The app's arguments follow the script as `$@`. A Stop's +/// SIGINT becomes a SIGTERM to `devicectl` (a background job ignores SIGINT), which passes it on +/// to the app. When `devicectl` itself fails to launch the app +/// (its JSON outcome is not `success`) and no Stop was asked for, a hint about a locked device +/// follows its error. +pub fn device_launch_script(build_args: &[String], udid: &str, name: &str, app: &Path, bundle_id: &str) -> String { + let build: Vec = build_args.iter().map(|a| sh_quote(a)).collect(); + let (udid, app, bundle_id) = (sh_quote(udid), sh_quote(&app.to_string_lossy()), sh_quote(bundle_id)); + let hint = sh_quote(&format!("Could not launch the app on {name}. If it is locked, unlock it and run again.")); + format!( + "set -e\n\ + xcodebuild {} -allowProvisioningUpdates build\n\ + xcrun devicectl device install app --device {udid} {app}\n\ + set +e\n\ + result=$(mktemp)\n\ + xcrun devicectl device process launch --console --terminate-existing --json-output \"$result\" --device {udid} {bundle_id} -- \"$@\" &\n\ + launch=$!\n\ + trap 'stopped=1; kill -TERM $launch 2>/dev/null' INT TERM\n\ + wait $launch; status=$?\n\ + while kill -0 $launch 2>/dev/null; do wait $launch; status=$?; done\n\ + if [ -z \"$stopped\" ] && ! grep -q '\"outcome\" *: *\"success\"' \"$result\" 2>/dev/null; then echo {hint} >&2; fi\n\ + rm -f \"$result\"\n\ + exit $status\n", + build.join(" "), + ) +} + +/// Why a run cannot start on `device`, a physical one [`crate::simulator::devices`] listed. +fn device_unready(device: &crate::simulator::IosSimulator) -> Option { + let name = &device.name; + match device.state.as_str() { + crate::simulator::UNAVAILABLE => Some(format!( + "{name} is not connected. Connect it with a cable or to this Mac's network, unlock it, and run again." + )), + crate::simulator::DEVELOPER_MODE_OFF => Some(format!( + "Developer Mode is off on {name}. Turn it on in Settings > Privacy & Security > Developer Mode, restart the device, and run again." + )), + _ => None, + } +} + /// The script a macOS run executes: build, then become the app's executable, so its output /// reaches the console and a Stop's SIGINT reaches the app. Its arguments follow as `$@`. pub fn mac_launch_script(build_args: &[String], executable: &Path) -> String { @@ -417,7 +476,7 @@ pub fn destination(dir: &Path, params: &BTreeMap, derived_data: } /// Turns a `kind = "xcode"` configuration into the process that builds, installs and launches -/// its scheme on the simulator. `dir` is the run's working directory; DerivedData goes under +/// its scheme on the simulator, or on the physical device whose UDID [`SIMULATOR_PARAM`] holds. `dir` is the run's working directory; DerivedData goes under /// `cache_dir`. The configuration's environment reaches a simulator app as `SIMCTL_CHILD_*`. /// A macOS app ([`runs_on_mac`]) is built for `platform=macOS` and run directly, with no simulator. pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> IdeResult<()> { @@ -443,11 +502,32 @@ pub fn prepare(dir: &Path, cache_dir: &Path, config: &mut crate::RunConfig) -> I return Ok(()); } let udid = destination.trim_start_matches("id=").to_owned(); + let device = crate::simulator::devices(dir).into_iter().find(|d| d.udid == udid); + if let Some(reason) = device.as_ref().and_then(device_unready) { + return Err(IdeError::unavailable(reason)); + } let args = build_args(params, Some(&destination), &derived_data).map_err(IdeError::invalid)?; let settings = show(&args)?; - let (app, bundle_id) = built_app(&settings).map_err(IdeError::invalid)?; + let (app, bundle_id) = built_app(&settings, device.is_some()).map_err(IdeError::invalid)?; let app_args = crate::import::split_args(params.get("arguments").map_or("", String::as_str)); let wait = params.get(WAIT_FOR_DEBUGGER_PARAM).is_some_and(|v| !v.trim().is_empty()); + if let Some(device) = device { + if wait { + return Err(IdeError::unavailable("Debugging an app on a physical device is not supported yet")); + } + config.command = "/bin/sh".into(); + config.args = [ + "-c".to_owned(), + device_launch_script(&args, &udid, &device.name, &app, &bundle_id), + "xcode-run".to_owned(), + ] + .into_iter() + .chain(app_args) + .collect(); + let env = std::mem::take(&mut config.env); + config.env = env.into_iter().map(|(k, v)| (format!("DEVICECTL_CHILD_{k}"), v)).collect(); + return Ok(()); + } config.command = "/bin/sh".into(); config.args = ["-c".to_owned(), launch_script(&args, &udid, &app, &bundle_id, wait), "xcode-run".to_owned()] .into_iter() @@ -625,14 +705,66 @@ mod tests { ) }; assert_eq!( - built_app(&settings("iphonesimulator")).unwrap(), + built_app(&settings("iphonesimulator"), false).unwrap(), (PathBuf::from("/dd/Build/Products/Debug-iphonesimulator/App.app"), "dev.example.App".to_owned()) ); assert_eq!( - built_app(&settings("macosx")).unwrap_err(), + built_app(&settings("macosx"), false).unwrap_err(), "The scheme builds an app for macosx, not the iOS Simulator" ); - assert_eq!(built_app("[]").unwrap_err(), "The scheme builds no application"); + assert_eq!(built_app("[]", false).unwrap_err(), "The scheme builds no application"); + assert_eq!( + built_app(&settings("iphonesimulator"), true).unwrap_err(), + "The scheme builds an app for iphonesimulator, not an iOS device" + ); + } + + #[test] + fn a_device_app_must_be_signed_with_a_team() { + let settings = |signing: &str| { + format!( + r#"[{{"target": "App", "buildSettings": {{"PRODUCT_TYPE": "com.apple.product-type.application", + "PLATFORM_NAME": "iphoneos", "TARGET_BUILD_DIR": "/dd/Debug-iphoneos", "WRAPPER_NAME": "App.app", + "PRODUCT_BUNDLE_IDENTIFIER": "dev.example.App", {signing}}}}}]"# + ) + }; + let signed = settings(r#""CODE_SIGN_STYLE": "Automatic", "DEVELOPMENT_TEAM": "ABCDE12345""#); + assert_eq!( + built_app(&signed, true).unwrap(), + (PathBuf::from("/dd/Debug-iphoneos/App.app"), "dev.example.App".to_owned()) + ); + let manual = settings(r#""CODE_SIGN_STYLE": "Manual", "DEVELOPMENT_TEAM": """#); + assert!(built_app(&manual, true).is_ok(), "manual signing names its profile; xcodebuild checks it"); + assert_eq!( + built_app(&settings(r#""CODE_SIGN_STYLE": "Automatic", "DEVELOPMENT_TEAM": """#), true).unwrap_err(), + "Signing App.app for a device needs a development team: choose one under Signing & Capabilities in Xcode" + ); + assert_eq!( + built_app(&settings(r#""CODE_SIGNING_ALLOWED": "NO""#), true).unwrap_err(), + "App.app is built unsigned (CODE_SIGNING_ALLOWED = NO), and an iOS device runs only signed apps" + ); + } + + #[test] + fn an_unready_device_says_what_to_do() { + let device = |state: &str| crate::simulator::IosSimulator { + udid: "U".into(), + name: "Test iPhone".into(), + runtime: "iOS 27.3".into(), + state: state.into(), + physical: true, + }; + assert_eq!(device_unready(&device(crate::simulator::AVAILABLE)), None); + assert!( + device_unready(&device(crate::simulator::UNAVAILABLE)) + .unwrap() + .starts_with("Test iPhone is not connected.") + ); + assert!( + device_unready(&device(crate::simulator::DEVELOPER_MODE_OFF)) + .unwrap() + .starts_with("Developer Mode is off on Test iPhone.") + ); } #[test] @@ -772,6 +904,82 @@ mod tests { ); } + /// The device script builds, installs and launches through devicectl, turns a Stop's SIGINT + /// into a SIGTERM to it, and adds the locked-device hint only when devicectl itself failed to launch. + #[cfg(unix)] + #[test] + fn device_launch_script_installs_launches_and_explains_a_failed_launch() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("log"); + let stub = |tool: &str, then: &str| { + let path = dir.path().join(tool); + let body = format!( + "#!/bin/sh\nprintf '{tool}' >> \"$LOG\"; printf ' [%s]' \"$@\" >> \"$LOG\"; echo >> \"$LOG\"\n{then}" + ); + fs::write(&path, body).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap(); + }; + stub("xcodebuild", ""); + // `launch` writes its JSON result to the path after `--json-output` ($8), then either + // fails at once or runs until a SIGINT reaches it. + stub( + "xcrun", + "[ \"$4\" = launch ] || exit 0\n\ + printf '{\"info\" : {\"outcome\" : \"%s\"}}' \"$OUTCOME\" > \"$8\"\n\ + [ \"$OUTCOME\" = success ] || { echo 'ERROR: the device was not unlocked' >&2; exit 1; }\n\ + trap 'echo terminated >> \"$LOG\"; exit 0' TERM\n\ + while :; do sleep 0.05; done\n", + ); + let build = ["-project".to_owned(), "App.xcodeproj".to_owned()]; + let script = + device_launch_script(&build, "00008110-AAA", "Test iPhone", Path::new("/dd/My App.app"), "dev.example.App"); + let run = |outcome: &str| { + let _ = fs::remove_file(&log); + std::process::Command::new("/bin/sh") + .args(["-c", &script, "xcode-run", "--greeting", "hi there"]) + .env("PATH", format!("{}:/usr/bin:/bin", dir.path().display())) + .env("LOG", &log) + .env("OUTCOME", outcome) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap() + }; + + let failed = run("failed").wait_with_output().unwrap(); + assert_eq!(failed.status.code(), Some(1)); + assert_eq!( + String::from_utf8_lossy(&failed.stderr), + "ERROR: the device was not unlocked\n\ + Could not launch the app on Test iPhone. If it is locked, unlock it and run again.\n" + ); + + let child = run("success"); + let launched = || fs::read_to_string(&log).unwrap_or_default().contains("[launch]"); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + while !launched() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + std::thread::sleep(std::time::Duration::from_millis(200)); + unsafe { libc::kill(child.id() as i32, libc::SIGINT) }; + let stopped = child.wait_with_output().unwrap(); + assert!(stopped.status.success()); + assert_eq!(String::from_utf8_lossy(&stopped.stderr), ""); + let log = fs::read_to_string(&log).unwrap(); + let json = log.split("[--json-output] [").nth(1).unwrap().split(']').next().unwrap().to_owned(); + assert_eq!( + log, + format!( + "xcodebuild [-project] [App.xcodeproj] [-allowProvisioningUpdates] [build]\n\ + xcrun [devicectl] [device] [install] [app] [--device] [00008110-AAA] [/dd/My App.app]\n\ + xcrun [devicectl] [device] [process] [launch] [--console] [--terminate-existing] [--json-output] [{json}] \ + [--device] [00008110-AAA] [dev.example.App] [--] [--greeting] [hi there]\n\ + terminated\n" + ) + ); + assert!(!Path::new(&json).exists(), "the launch result file is removed"); + } + /// A debug launch passes `--wait-for-debugger` and prints the pid of the suspended app (not of /// a running copy, nor of a process outside its bundle) right away, while simctl keeps running. #[cfg(unix)] diff --git a/src/bindings.ts b/src/bindings.ts index 5af2c02e76..25e744dc84 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -973,9 +973,9 @@ export const commands = { iosSimulatorOpenApp: () => typedError(__TAURI_INVOKE("ios_simulator_open_app")), iosSimulatorShutdown: (udid: string) => typedError(__TAURI_INVOKE("ios_simulator_shutdown", { udid })), /** - * The available iOS simulators, booted first; `None` outside macOS or when the project has no - * Xcode project or workspace at its root. Asked again whenever the chooser opens: `simctl` has - * no change feed, and one listing takes a fraction of a second. + * The available iOS simulators, booted first, then the paired iPhones and iPads; `None` outside + * macOS or when the project has no Xcode project or workspace at its root. Asked again whenever + * the chooser opens: `simctl` has no change feed, and one listing takes a fraction of a second. */ iosSimulators: () => typedError(__TAURI_INVOKE("ios_simulators")), /** Incremental build of the jdtls workspace serving `module` (e.g. before HotSwap). */ @@ -10044,14 +10044,22 @@ export type InvalidateCachesOptions = { buildCaches?: boolean, }; -/** One simulator `simctl list devices available` reports. */ +/** + * One simulator `simctl list devices available` reports, or one physical device + * `devicectl list devices` knows. + */ export type IosSimulator = { udid: string, name: string, /** The runtime, as Xcode shows it: `iOS 27.0`. */ runtime: string, - /** `Booted`, `Shutdown`, `Booting`, `Shutting Down`. */ + /** + * `Booted`, `Shutdown`, `Booting`, `Shutting Down`; for a physical device [`AVAILABLE`], + * [`UNAVAILABLE`] (not connected) or [`DEVELOPER_MODE_OFF`]. + */ state: string, + /** An iPhone or iPad rather than a simulator. */ + physical: boolean, }; /** A binary argument or result of an IPC command. */ diff --git a/src/features/run/IosSimulatorChooser.tsx b/src/features/run/IosSimulatorChooser.tsx index 9e5888984e..4f25f10fd6 100644 --- a/src/features/run/IosSimulatorChooser.tsx +++ b/src/features/run/IosSimulatorChooser.tsx @@ -15,7 +15,7 @@ import { } from "@/workbench/iosSimulators"; import styles from "./Run.module.css"; -/** Title bar: the simulator Xcode launches use, in projects with an Xcode project on macOS. */ +/** Title bar: the simulator or device Xcode launches use, in projects with an Xcode project on macOS. */ export function IosSimulatorChooser() { const root = useProject((s) => s.project?.root); useEffect(() => (root ? watchIosSimulators(root) : undefined), [root]); @@ -23,7 +23,7 @@ export function IosSimulatorChooser() { return shown ? : null; } -const booted = (s: IosSimulator) => s.state === "Booted"; +const booted = (s: IosSimulator) => !s.physical && s.state === "Booted"; function Chooser() { const tx = useTx(); @@ -48,11 +48,31 @@ function Chooser() { : { label: tx("Boot"), disabled: !!busy || s.state !== "Shutdown", run: () => void bootIosSimulator(s) }, ], }); + // A device's row is selectable in any state: the run explains what to do when it is not ready. + const device = (s: IosSimulator): MenuItem => { + const unready = + s.state === "Unavailable" + ? tx("Not connected") + : s.state === "Developer Mode Off" + ? tx("Developer Mode off") + : null; + return { + id: s.udid, + label: unready ? `${s.name} · ${s.runtime} · ${unready}` : `${s.name} · ${s.runtime}`, + verbatim: true, + checked: s.udid === current?.udid, + hint: s.udid, + performOnSelect: true, + run: () => selectIosSimulator(s.udid), + }; + }; const running = (list ?? []).filter(booted); - const idle = (list ?? []).filter((s) => !booted(s)); + const idle = (list ?? []).filter((s) => !s.physical && !booted(s)); + const devices = (list ?? []).filter((s) => s.physical); const items: MenuItem[] = [ ...(running.length ? [{ kind: "header", label: tx("Booted") } as const, ...running.map(row)] : []), ...(idle.length ? [{ kind: "header", label: tx("Available") } as const, ...idle.map(row)] : []), + ...(devices.length ? [{ kind: "header", label: tx("Devices") } as const, ...devices.map(device)] : []), ...(error ? [{ label: error, verbatim: true, disabled: true }] : []), ...(list && !list.length ? [{ label: tx("No simulators available"), disabled: true }] : []), { kind: "separator" }, @@ -66,8 +86,8 @@ function Chooser() { variant="title" className={styles.widgetDevice} data-toolbar-icon-dropdown="" - tooltip={tx("iOS Simulator")} - aria-label={tx`iOS Simulator: ${label}`} + tooltip={tx("Run Destination")} + aria-label={tx`Run Destination: ${label}`} aria-haspopup="menu" aria-expanded={open} onClick={() => { diff --git a/src/features/run/xcodeType.test.ts b/src/features/run/xcodeType.test.ts index 841c12e438..3cb7dd00c8 100644 --- a/src/features/run/xcodeType.test.ts +++ b/src/features/run/xcodeType.test.ts @@ -25,7 +25,7 @@ describe("Xcode run configurations", () => { kind: "xcode", params: { container: "App.xcodeproj", scheme: "App", ...(simulator ? { simulator } : {}) }, }) as unknown as RunConfig; - const sim = (udid: string) => ({ udid, name: udid, runtime: "iOS 27.0", state: "Shutdown" }); + const sim = (udid: string) => ({ udid, name: udid, runtime: "iOS 27.0", state: "Shutdown", physical: false }); it("runs an unpinned configuration on the toolbar's simulator", async () => { useIosSimulators.setState({ list: [sim("A"), sim("B")], preferred: "B" }); diff --git a/src/features/run/xcodeType.ts b/src/features/run/xcodeType.ts index 9dd18e9dc6..3dd30f1ffc 100644 --- a/src/features/run/xcodeType.ts +++ b/src/features/run/xcodeType.ts @@ -1,5 +1,5 @@ /** - * Xcode schemes run on the iOS Simulator, or on the Mac for a macOS app. The host builds, installs and launches the app at + * Xcode schemes run on the iOS Simulator or a connected iPhone or iPad, or on the Mac for a macOS app. The host builds, installs and launches the app at * launch (`ide_run::xcode::prepare`); the command line here names what is built. */ import type { RunConfigTypeContribution } from "@/workbench/contributions"; @@ -9,7 +9,7 @@ export const xcodeType: RunConfigTypeContribution = { id: "xcode", label: "Xcode App", icon: "file-swift", - description: "Build an Xcode scheme and run it on the iOS Simulator or the Mac", + description: "Build an Xcode scheme and run it on the iOS Simulator, a connected device or the Mac", // Debug launches the app suspended and attaches lldb-dap to it (`debugXcodeApp`). debugAdapter: "lldb-dap", fields: [ @@ -25,10 +25,10 @@ export const xcodeType: RunConfigTypeContribution = { { key: "configuration", label: "Build configuration", placeholder: "The scheme's" }, { key: "simulator", - label: "Simulator", + label: "Simulator or device", mono: true, placeholder: "A booted simulator, else the newest iPhone", - hint: "A simulator UDID (xcrun simctl list devices) pins this configuration to it; macos runs an app that also supports the Mac there", + hint: "A simulator or device UDID (xcrun simctl list devices, xcrun devicectl list devices) pins this configuration to it; macos runs an app that also supports the Mac there", }, { key: "arguments", label: "Launch arguments", mono: true }, ], diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index aee4578064..fb338faef4 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2373,8 +2373,11 @@ "Booted": "Booted", "No simulators available": "No simulators available", "Open Simulator": "Open Simulator", - "iOS Simulator": "iOS Simulator", - "iOS Simulator: {label}": "iOS Simulator: {label}", + "Run Destination": "Run Destination", + "Run Destination: {label}": "Run Destination: {label}", + "Devices": "Devices", + "Not connected": "Not connected", + "Developer Mode off": "Developer Mode off", "Could not boot {name}": "Could not boot {name}", "Could not shut down {name}": "Could not shut down {name}", "Could not open Simulator": "Could not open Simulator", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index f7a91798e8..2708787ba1 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -1,13 +1,13 @@ { "{name} ({runtime} Simulator)": "{name}({runtime} 模擬器)", "Xcode App": "Xcode 應用程式", - "Build an Xcode scheme and run it on the iOS Simulator or the Mac": "建置 Xcode 方案並在 iOS 模擬器或 Mac 上執行", + "Build an Xcode scheme and run it on the iOS Simulator, a connected device or the Mac": "建置 Xcode 方案並在 iOS 模擬器、已連接的裝置或 Mac 上執行", "Project or workspace": "專案或工作區", "Build configuration": "建置組態", "The scheme's": "方案自身的", - "Simulator": "模擬器", + "Simulator or device": "模擬器或裝置", "A booted simulator, else the newest iPhone": "已啟動的模擬器,否則為最新的 iPhone", - "A simulator UDID (xcrun simctl list devices) pins this configuration to it; macos runs an app that also supports the Mac there": "填寫模擬器 UDID(xcrun simctl list devices)可將此組態固定到該模擬器;填寫 macos 則讓同時支援 Mac 的 App 在 Mac 上執行", + "A simulator or device UDID (xcrun simctl list devices, xcrun devicectl list devices) pins this configuration to it; macos runs an app that also supports the Mac there": "填寫模擬器或裝置的 UDID(xcrun simctl list devices、xcrun devicectl list devices)可將此組態固定到它;填寫 macos 則讓同時支援 Mac 的 App 在 Mac 上執行", "Launch arguments": "啟動引數", "Quick Preview": "快速預覽", "Build and Run": "建置和執行", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index c055b30853..a7772592b4 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2,13 +2,13 @@ "{name} ({runtime} Simulator)": "{name}({runtime} 模拟器)", "App.xcodeproj": "App.xcodeproj", "Xcode App": "Xcode 应用", - "Build an Xcode scheme and run it on the iOS Simulator or the Mac": "构建 Xcode 方案并在 iOS 模拟器或 Mac 上运行", + "Build an Xcode scheme and run it on the iOS Simulator, a connected device or the Mac": "构建 Xcode 方案并在 iOS 模拟器、已连接的设备或 Mac 上运行", "Project or workspace": "项目或工作区", "Build configuration": "构建配置", "The scheme's": "方案自身的", - "Simulator": "模拟器", + "Simulator or device": "模拟器或设备", "A booted simulator, else the newest iPhone": "已启动的模拟器,否则为最新的 iPhone", - "A simulator UDID (xcrun simctl list devices) pins this configuration to it; macos runs an app that also supports the Mac there": "填写模拟器 UDID(xcrun simctl list devices)可将此配置固定到该模拟器;填写 macos 则让同时支持 Mac 的 App 在 Mac 上运行", + "A simulator or device UDID (xcrun simctl list devices, xcrun devicectl list devices) pins this configuration to it; macos runs an app that also supports the Mac there": "填写模拟器或设备的 UDID(xcrun simctl list devices、xcrun devicectl list devices)可将此配置固定到它;填写 macos 则让同时支持 Mac 的 App 在 Mac 上运行", "Launch arguments": "启动参数", "Enable Git integration": "启用 Git 集成", "Off, the IDE runs no git: repositories are not detected, and Git actions, menus and tool windows are hidden. Applies to all projects.": "关闭后 IDE 不运行 git:不检测仓库,并隐藏 Git 操作、菜单和工具窗口。对所有项目生效。", @@ -5708,8 +5708,11 @@ "Booted": "已启动", "No simulators available": "没有可用的模拟器", "Open Simulator": "打开 Simulator", - "iOS Simulator": "iOS 模拟器", - "iOS Simulator: {label}": "iOS 模拟器:{label}", + "Run Destination": "运行目标", + "Run Destination: {label}": "运行目标:{label}", + "Devices": "设备", + "Not connected": "未连接", + "Developer Mode off": "开发者模式未开启", "Could not boot {name}": "无法启动 {name}", "Could not shut down {name}": "无法关闭 {name}", "Could not open Simulator": "无法打开 Simulator", diff --git a/src/workbench/iosSimulators.test.ts b/src/workbench/iosSimulators.test.ts index b0ee851305..a2a1791bfb 100644 --- a/src/workbench/iosSimulators.test.ts +++ b/src/workbench/iosSimulators.test.ts @@ -10,7 +10,13 @@ vi.mock("@/platform/ipc", async (original) => ({ commands: { iosSimulators: () => iosSimulators() }, })); -const sim = (udid: string, state = "Shutdown"): IosSimulator => ({ udid, name: udid, runtime: "iOS 27.0", state }); +const sim = (udid: string, state = "Shutdown"): IosSimulator => ({ + udid, + name: udid, + runtime: "iOS 27.0", + state, + physical: false, +}); const config = (params?: Record) => ({ id: "xcode:App", kind: "xcode", params }) as unknown as RunConfig;