#![allow(clippy::result_large_err)]
use std::{io::Read, time::Instant};
use clap::{Parser, Subcommand};
use iphone_cli::{
client, clock, connect, daemon, devices, diagnose, events, fields, human,
mcp,
reply::{Fail, envelope},
script, setup,
};
use serde_json::{Map, Value, json};
#[derive(Parser)]
#[command(
name = "iph",
version,
about = "Read and operate any app on a real iPhone through its accessibility tree",
long_about = "Read and operate any app on a real iPhone through its accessibility tree.\n\
No XCUITest, WebDriverAgent or Xcode signing. Output is JSON; add --human for people.\n\
Exit codes: 0 ok, 1 nothing was sent, 2 outcome unknown (check the screen)."
)]
struct Cli {
#[arg(long, global = true)]
udid: Option<String>,
#[arg(long, global = true)]
human: bool,
#[arg(long, global = true, hide = true)]
json: bool,
#[command(subcommand)]
command: Cmd,
}
#[derive(Subcommand)]
enum Cmd {
Devices,
Connect(connect::Args),
Diagnose(diagnose::Args),
Setup {
#[arg(long)]
fix_wifi: bool,
},
Doctor {
#[arg(long)]
no_touch_test: bool,
#[arg(long)]
fix_wifi: bool,
},
Read {
#[arg(long)]
app: bool,
#[arg(long)]
all: bool,
#[arg(long)]
full: bool,
#[arg(long)]
raw: bool,
#[arg(long)]
max_age: Option<u64>,
},
Find {
selector: String,
#[arg(long)]
all: bool,
},
Tap {
target: String,
#[arg(long)]
long: Option<u64>,
#[arg(long)]
double: bool,
#[arg(long)]
no_wait: bool,
},
Swipe {
direction: String,
#[arg(long)]
duration: Option<u64>,
#[arg(long)]
drag: bool,
},
Pinch {
direction: Option<String>,
#[arg(long)]
scale: Option<f64>,
#[arg(long, allow_negative_numbers = true)]
rotate: Option<f64>,
#[arg(long)]
at: Option<String>,
#[arg(long)]
duration: Option<u64>,
},
Scroll {
direction: String,
#[arg(long)]
until: Option<String>,
#[arg(long)]
max: Option<u32>,
},
Type {
text: String,
#[arg(long)]
clear: bool,
#[arg(long)]
submit: bool,
},
Key { key: String },
Button { button: String },
Launch {
app: String,
#[arg(long)]
restart: bool,
#[arg(long = "env", value_name = "K=V")]
env: Vec<String>,
#[arg(last = true)]
arguments: Vec<String>,
},
Apps,
Screenshot {
#[arg(short, long)]
output: Option<String>,
},
Batch { file: String },
Script {
file: String,
#[arg(long = "arg", value_name = "K=V")]
args: Vec<String>,
},
Run {
name: String,
#[arg(long = "arg", value_name = "K=V")]
args: Vec<String>,
},
Scripts,
Mcp {
#[arg(long, value_delimiter = ',')]
tools: Vec<String>,
},
Dnd { action: String },
Stop,
#[command(hide = true)]
Daemon,
#[command(hide = true)]
Debug { command: String },
}
fn print(value: &Value, human_out: bool, cmd: &str) {
if human_out {
println!("{}", human::render(cmd, value));
} else if std::io::IsTerminal::is_terminal(&std::io::stdout()) {
println!("{}", serde_json::to_string_pretty(value).unwrap());
} else {
println!("{value}");
}
}
fn exit_code(value: &Value) -> i32 {
if value["ok"] == true {
return 0;
}
match value["outcome"].as_str() {
Some("unknown") => 2,
_ => 1,
}
}
fn script_args(pairs: &[String]) -> Result<Map<String, Value>, Fail> {
let mut map = Map::new();
for pair in pairs {
let Some((k, v)) = pair.split_once('=') else {
return Err(Fail::invalid(format!("--arg expects name=value, got `{pair}`")));
};
map.insert(k.to_string(), json!(v));
}
Ok(map)
}
fn swipe_args(direction: &str, duration: Option<u64>, drag: bool) -> Result<Value, Fail> {
let nums: Vec<f64> = direction
.split(',')
.filter_map(|p| p.trim().parse::<f64>().ok())
.collect();
let mut v = if direction.contains(',') {
if nums.len() != 4 {
return Err(Fail::invalid("swipe takes a direction or x1,y1,x2,y2"));
}
json!({ "from": [nums[0], nums[1]], "to": [nums[2], nums[3]] })
} else {
json!({ "direction": direction })
};
if let Some(d) = duration {
v["duration_ms"] = json!(d);
}
v["drag"] = json!(drag);
Ok(v)
}
fn launch_args(app: &str, restart: bool, env: &[String], arguments: &[String]) -> Result<Value, Fail> {
let mut environment = serde_json::Map::new();
for pair in env {
let (name, value) = pair
.split_once('=')
.filter(|(name, _)| !name.is_empty())
.ok_or_else(|| Fail::invalid(format!("--env takes NAME=value, got \"{pair}\"")))?;
environment.insert(name.to_string(), json!(value));
}
Ok(json!({ "app": app, "restart": restart, "arguments": arguments, "environment": environment }))
}
fn main() {
let cli = Cli::parse();
events::init_tracing();
let worker = std::thread::Builder::new()
.name("iph-main".into())
.stack_size(64 << 20)
.spawn(move || {
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.thread_stack_size(16 << 20)
.build()
.expect("tokio runtime");
let code = runtime.block_on(run(cli));
runtime.shutdown_background();
code
})
.expect("spawn main thread");
std::process::exit(worker.join().unwrap_or(1));
}
async fn run(cli: Cli) -> i32 {
let started = Instant::now();
let human_out = cli.human;
match &cli.command {
Cmd::Diagnose(args) => {
if !args.command.is_empty() {
let child = Cli::try_parse_from(std::iter::once("iph".to_string()).chain(args.command.iter().cloned()));
if child.is_ok_and(|c| matches!(c.command, Cmd::Diagnose(_) | Cmd::Daemon | Cmd::Mcp { .. } | Cmd::Setup { .. })) {
let v = envelope(Err(Fail::invalid("diagnose can capture a finite iph command; diagnose, daemon, mcp and setup cannot be nested")), started);
print(&v, human_out, "diagnose");
return 1;
}
}
let v = envelope(diagnose::run(args.clone(), cli.udid.clone()).await, started);
print(&v, human_out, "diagnose");
return exit_code(&v);
}
Cmd::Scripts => {
let v = envelope(script::cmd_scripts(), started);
print(&v, human_out, "scripts");
return exit_code(&v);
}
Cmd::Devices => {
let v = envelope(devices::cmd_devices(cli.udid.clone()).await, started);
print(&v, human_out, "devices");
return exit_code(&v);
}
_ => {}
}
let udid = match client::resolve_udid(cli.udid.clone()).await {
Ok(u) => u,
Err(f) => {
let v = envelope(Err(f), started);
print(&v, human_out, "error");
return exit_code(&v);
}
};
let (cmd, args): (&str, Value) = match cli.command {
Cmd::Connect(args) => {
let v = envelope(connect::run(&udid, args).await, started);
print(&v, human_out, "connect");
return exit_code(&v);
}
Cmd::Daemon => {
return match daemon::run(udid).await {
Ok(()) => 0,
Err(e) => {
eprintln!("iph daemon: {e:#}");
1
}
};
}
Cmd::Mcp { tools } => {
return match mcp::serve(udid, tools).await {
Ok(()) => 0,
Err(e) => {
eprintln!("iph mcp: {e:#}");
1
}
};
}
Cmd::Setup { fix_wifi } => return setup::run(&udid, fix_wifi).await,
Cmd::Stop => {
let last = client::stop_daemon(&udid).await;
let v = envelope(Ok(fields! { "stopped": last.is_some() }), started);
print(&v, human_out, "stop");
return 0;
}
Cmd::Debug { command } => {
let v = client::request(&udid, &command, Value::Null).await;
print(&v, human_out, "debug");
return exit_code(&v);
}
Cmd::Doctor { no_touch_test, fix_wifi } => ("doctor", json!({ "no_touch_test": no_touch_test, "fix_wifi": fix_wifi })),
Cmd::Read { app, all, full, raw, max_age } => (
"read",
json!({ "app": app, "all": all, "full": full, "raw": raw, "max_age_ms": max_age }),
),
Cmd::Find { selector, all } => ("find", json!({ "selector": selector, "all": all })),
Cmd::Tap { target, long, double, no_wait } => {
("tap", json!({ "target": target, "long_ms": long, "double": double, "no_wait": no_wait }))
}
Cmd::Swipe { direction, duration, drag } => match swipe_args(&direction, duration, drag) {
Ok(v) => ("swipe", v),
Err(f) => {
let v = envelope(Err(f), started);
print(&v, human_out, "swipe");
return exit_code(&v);
}
},
Cmd::Pinch { direction, scale, rotate, at, duration } => (
"pinch",
json!({ "direction": direction, "scale": scale, "rotate": rotate, "at": at, "duration_ms": duration }),
),
Cmd::Scroll { direction, until, max } => (
"scroll",
json!({ "direction": direction, "until": until, "max": max }),
),
Cmd::Type { text, clear, submit } => {
("type", json!({ "text": text, "clear": clear, "submit": submit }))
}
Cmd::Key { key } => ("key", json!({ "key": key })),
Cmd::Button { button } => ("button", json!({ "button": button })),
Cmd::Dnd { action } => ("dnd", json!({ "action": action })),
Cmd::Launch { app, restart, env, arguments } => match launch_args(&app, restart, &env, &arguments) {
Ok(v) => ("launch", v),
Err(f) => {
let v = envelope(Err(f), started);
print(&v, human_out, "launch");
return exit_code(&v);
}
},
Cmd::Apps => ("apps", Value::Null),
Cmd::Screenshot { output } => {
let name = output.unwrap_or_else(|| {
format!("iph-screenshot-{}.png", clock::now_utc().replace([':', '-'], ""))
});
let path = std::path::absolute(&name)
.map(|p| p.display().to_string())
.unwrap_or(name);
("screenshot", json!({ "path": path }))
}
Cmd::Batch { file } => {
let text = if file == "-" {
let mut s = String::new();
std::io::stdin().read_to_string(&mut s).map(|_| s)
} else {
std::fs::read_to_string(&file)
};
let steps = text
.map_err(|e| Fail::invalid(format!("{file}: {e}")))
.and_then(|t| {
serde_json::from_str::<Value>(&t)
.map_err(|e| Fail::invalid(format!("{file}: not JSON: {e}")))
})
.and_then(|v| match v {
Value::Array(_) => Ok(v),
_ => Err(Fail::invalid("batch needs a JSON array of steps")),
});
match steps {
Ok(steps) => ("batch", json!({ "steps": steps })),
Err(f) => {
let v = envelope(Err(f), started);
print(&v, human_out, "batch");
return exit_code(&v);
}
}
}
Cmd::Script { file, args } => {
let code = if file == "-" {
let mut s = String::new();
std::io::stdin().read_to_string(&mut s).map(|_| s)
} else {
std::fs::read_to_string(&file)
};
let request = code
.map_err(|e| Fail::invalid(format!("{file}: {e}")))
.and_then(|code| Ok(script::request(&code, &script_args(&args)?, None)));
match request {
Ok(request) => ("script", request),
Err(f) => {
let v = envelope(Err(f), started);
print(&v, human_out, "script");
return exit_code(&v);
}
}
}
Cmd::Run { name, args } => {
let request = script::load(&name).and_then(|(code, source)| {
Ok(script::request(&code, &script_args(&args)?, Some((&name, &source))))
});
match request {
Ok(request) => ("script", request),
Err(f) => {
let v = envelope(Err(f), started);
print(&v, human_out, "script");
return exit_code(&v);
}
}
}
Cmd::Scripts | Cmd::Devices | Cmd::Diagnose(_) => unreachable!(),
};
let value = client::request(&udid, cmd, args).await;
print(&value, human_out, cmd);
exit_code(&value)
}
#[cfg(test)]
mod tests {
use super::*;
fn strings(v: &[&str]) -> Vec<String> {
v.iter().map(|s| s.to_string()).collect()
}
#[test]
fn launch_env_splits_at_the_first_equals() {
let v = launch_args("a", false, &strings(&["TZ=UTC", "TOKEN=a=b", "EMPTY="]), &strings(&["-k", "v"])).unwrap();
assert_eq!(v["environment"], json!({"TZ": "UTC", "TOKEN": "a=b", "EMPTY": ""}));
assert_eq!(v["arguments"], json!(["-k", "v"]));
}
#[test]
fn launch_env_without_a_name_or_equals_is_not_sent() {
for bad in ["NOEQUALS", "=v", ""] {
let f = launch_args("a", false, &strings(&[bad]), &[]).unwrap_err();
assert_eq!(f.code, "invalid_argument");
}
}
}