дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 18:17:15 +02:00
The Xcode run destination chooser lists paired iPhones and iPads from devicectl under a Devices header, marking ones that are not connected or have Developer Mode off. Running on a device stops before building when the device is not ready or the app would be unsigned (CODE_SIGNING_ALLOWED = NO, or automatic signing without a team), and otherwise builds with -allowProvisioningUpdates, installs with devicectl and launches with --console so output shows in the Run console and Stop ends the app. Scheme environment goes through DEVICECTL_CHILD_*, and a failed launch adds an unlock hint after devicectl's error. Debugging on a device is not supported yet. Install and launch on real hardware were exercised with a stubbed xcrun only. Co-authored-by: wildcatDownstairs <[email protected]>
265 рядки
12 KiB
Rust
265 рядки
12 KiB
Rust
//! 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.
|
|
|
|
use ide_core::process::prepare;
|
|
use ide_core::{IdeError, IdeResult};
|
|
use serde::Serialize;
|
|
use serde_json::Value;
|
|
use specta::Type;
|
|
use std::path::Path;
|
|
use std::process::Command;
|
|
|
|
/// 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 {
|
|
pub udid: String,
|
|
pub name: String,
|
|
/// The runtime, as Xcode shows it: `iOS 27.0`.
|
|
pub runtime: String,
|
|
/// `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 {
|
|
if root.join("pubspec.yaml").is_file() {
|
|
return false;
|
|
}
|
|
let Ok(entries) = std::fs::read_dir(root) else { return false };
|
|
entries.flatten().any(|e| {
|
|
let name = e.file_name();
|
|
let name = name.to_string_lossy();
|
|
name.ends_with(".xcodeproj") || name.ends_with(".xcworkspace")
|
|
})
|
|
}
|
|
|
|
/// `com.apple.CoreSimulator.SimRuntime.iOS-27-0` → its version parts, for iOS runtimes only.
|
|
fn ios_version(runtime: &str) -> Option<Vec<u32>> {
|
|
let version = runtime.rsplit('.').next()?.strip_prefix("iOS-")?;
|
|
version.split('-').map(|p| p.parse().ok()).collect()
|
|
}
|
|
|
|
/// The iOS simulators in `simctl list devices available --json` output: booted first, then
|
|
/// newest runtime, then by name.
|
|
pub fn parse_list(json: &str) -> IdeResult<Vec<IosSimulator>> {
|
|
let value: Value = serde_json::from_str(json).map_err(|e| IdeError::internal(format!("simctl list: {e}")))?;
|
|
let mut devices: Vec<(Vec<u32>, IosSimulator)> = Vec::new();
|
|
for (runtime, list) in value.get("devices").and_then(Value::as_object).into_iter().flatten() {
|
|
let Some(version) = ios_version(runtime) else { continue };
|
|
let label = format!("iOS {}", version.iter().map(u32::to_string).collect::<Vec<_>>().join("."));
|
|
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, physical: false }));
|
|
}
|
|
}
|
|
devices.sort_by(|(va, a), (vb, b)| {
|
|
(a.state != "Booted")
|
|
.cmp(&(b.state != "Booted"))
|
|
.then_with(|| vb.cmp(va))
|
|
.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
|
|
.then_with(|| a.udid.cmp(&b.udid))
|
|
});
|
|
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<Vec<IosSimulator>> {
|
|
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<IosSimulator> {
|
|
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<String> {
|
|
let mut cmd = Command::new(program);
|
|
if let Some(dir) = dir {
|
|
cmd.current_dir(dir);
|
|
}
|
|
prepare(&mut cmd).args(args);
|
|
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("could not run {program}: {e}")))?;
|
|
if out.status.success() {
|
|
return Ok(String::from_utf8_lossy(&out.stdout).into_owned());
|
|
}
|
|
let stderr = String::from_utf8_lossy(&out.stderr);
|
|
Err(IdeError::unavailable(format!("{program} {} failed: {}", args.join(" "), stderr.trim())))
|
|
}
|
|
|
|
/// 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<Vec<IosSimulator>> {
|
|
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.
|
|
pub fn boot(udid: &str) -> IdeResult<()> {
|
|
run_in(None, "xcrun", &["simctl", "boot", udid]).map(drop)
|
|
}
|
|
|
|
pub fn shutdown(udid: &str) -> IdeResult<()> {
|
|
run_in(None, "xcrun", &["simctl", "shutdown", udid]).map(drop)
|
|
}
|
|
|
|
/// Brings Simulator.app to the front, which shows the booted simulators.
|
|
pub fn open_app() -> IdeResult<()> {
|
|
run_in(None, "open", &["-a", "Simulator"]).map(drop)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
const LIST: &str = r#"{"devices": {
|
|
"com.apple.CoreSimulator.SimRuntime.iOS-26-4": [
|
|
{"udid": "A1", "name": "iPhone 17", "state": "Shutdown", "isAvailable": true}
|
|
],
|
|
"com.apple.CoreSimulator.SimRuntime.watchOS-12-0": [
|
|
{"udid": "W1", "name": "Apple Watch", "state": "Booted", "isAvailable": true}
|
|
],
|
|
"com.apple.CoreSimulator.SimRuntime.iOS-27-0": [
|
|
{"udid": "B2", "name": "iPhone Air", "state": "Shutdown"},
|
|
{"udid": "B1", "name": "iPad Pro", "state": "Shutdown"},
|
|
{"udid": "B3", "name": "iPhone 18", "state": "Booted"},
|
|
{"name": "no udid", "state": "Shutdown"}
|
|
],
|
|
"com.apple.CoreSimulator.SimRuntime.iOS-26-10": [
|
|
{"udid": "C1", "name": "iPhone 17", "state": "Booted"}
|
|
]
|
|
}}"#;
|
|
|
|
#[test]
|
|
fn lists_ios_simulators_booted_then_newest_then_by_name() {
|
|
let devices = parse_list(LIST).unwrap();
|
|
let order: Vec<_> = devices.iter().map(|d| (d.udid.as_str(), d.runtime.as_str())).collect();
|
|
assert_eq!(
|
|
order,
|
|
[("B3", "iOS 27.0"), ("C1", "iOS 26.10"), ("B1", "iOS 27.0"), ("B2", "iOS 27.0"), ("A1", "iOS 26.4")]
|
|
);
|
|
assert_eq!(devices[0].name, "iPhone 18");
|
|
assert_eq!(devices[0].state, "Booted");
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_output_that_is_not_json() {
|
|
assert!(parse_list("xcrun: error").is_err());
|
|
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()));
|
|
std::fs::create_dir_all(dir.join("App.xcodeproj")).unwrap();
|
|
assert!(is_xcode_project(&dir));
|
|
std::fs::write(dir.join("pubspec.yaml"), "name: app\n").unwrap();
|
|
assert!(!is_xcode_project(&dir), "Flutter projects list their devices through Flutter");
|
|
std::fs::remove_dir_all(&dir).unwrap();
|
|
}
|
|
}
|