Skip to content

Control a real USB-connected iPhone from Linux (no Mac, no paid developer account) and expose it to AI agents as MCP tools

阶段 2/4:WDA 客户端 ictl-wda 与自动解锁 ictl-unlock

Derrorse28196fa3456
diff --git a/Cargo.lock b/Cargo.lock
index d813af5..57d28cd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2062,19 +2062,22 @@ name = "ictl-unlock"
version = "0.1.0"
dependencies = [
"ictl-wda",
+ "serde_json",
"thiserror 2.0.21",
"tokio",
"tracing",
+ "uuid",
]
[[package]]
name = "ictl-wda"
version = "0.1.0"
dependencies = [
+ "base64 0.23.1",
"ictl-device",
"idevice",
"quick-xml 0.42.0",
- "serde",
+ "regex",
"serde_json",
"thiserror 2.0.21",
"tokio",
@@ -3675,9 +3678,9 @@ dependencies = [
[[package]]
name = "regex"
-version = "1.13.1"
+version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
+checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
dependencies = [
"aho-corasick",
"memchr",
diff --git a/crates/ictl-unlock/Cargo.toml b/crates/ictl-unlock/Cargo.toml
index 1306a32..d109060 100644
--- a/crates/ictl-unlock/Cargo.toml
+++ b/crates/ictl-unlock/Cargo.toml
@@ -12,3 +12,7 @@ ictl-wda.workspace = true
tokio.workspace = true
thiserror.workspace = true
tracing.workspace = true
+
+[dev-dependencies]
+serde_json.workspace = true
+uuid.workspace = true
diff --git a/crates/ictl-unlock/src/fake.rs b/crates/ictl-unlock/src/fake.rs
new file mode 100644
index 0000000..e3464dd
--- /dev/null
+++ b/crates/ictl-unlock/src/fake.rs
@@ -0,0 +1,140 @@
+//! 单测用的假锁屏:按 toolkit 实测到的 WDA 行为模拟锁屏界面。
+//!
+//! - 键盘元素一直在元素树里(不管是否显示)
+//! - 只有「按 Home 后上滑」之后键盘才真正显示,显示前按键落空
+//! - 整串输完:对了就解锁,错了算一次输错并清空
+
+use std::sync::Mutex;
+use std::time::Duration;
+
+use ictl_wda::http::Transport;
+use serde_json::{Value, json};
+
+const LOCK_XML: &str = include_str!("../../ictl-wda/tests/fixtures/lockscreen.xml");
+/// 与 lockscreen.xml 里各键的中心点一致
+const KEYS: [(i64, i64); 10] = [
+ (215, 695),
+ (103, 371),
+ (215, 371),
+ (327, 371),
+ (103, 479),
+ (215, 479),
+ (327, 479),
+ (103, 587),
+ (215, 587),
+ (327, 587),
+];
+
+#[derive(Debug, Clone, Default)]
+pub struct State {
+ pub locked: bool,
+ pub shown: bool,
+ pub entered: Vec<u8>,
+ pub idle: (f64, f64),
+ pub idle_during_unlock: Vec<(f64, f64)>,
+ pub presses_per_action_max: usize,
+ pub requests_to_actions: usize,
+ pub failed_attempts: u32,
+ pub digits_typed: u32,
+ swipes_to_ignore: u32,
+ press_count: u32,
+ drop_press: Option<u32>,
+}
+
+pub struct FakeLockScreen {
+ code: Vec<u8>,
+ st: Mutex<State>,
+}
+
+impl FakeLockScreen {
+ pub fn new(code: &str) -> Self {
+ let st = State { locked: true, idle: (10.0, 2.0), ..Default::default() };
+ Self { code: code.bytes().map(|b| b - b'0').collect(), st: Mutex::new(st) }
+ }
+
+ pub fn state(&self) -> State {
+ self.st.lock().unwrap().clone()
+ }
+
+ pub fn unlock_now(&self) {
+ self.st.lock().unwrap().locked = false;
+ }
+
+ pub fn swipes_ignored(&self, n: u32) {
+ self.st.lock().unwrap().swipes_to_ignore = n;
+ }
+
+ /// 第 n 次有效按键(从 1 数)被键盘吞掉
+ pub fn drop_press(&self, n: u32) {
+ self.st.lock().unwrap().drop_press = Some(n);
+ }
+
+ fn handle(&self, method: &str, path: &str, body: Option<Value>) -> (u16, Value) {
+ let mut s = self.st.lock().unwrap();
+ let path = path.strip_prefix("/session/S").unwrap_or(path);
+ let v = match (method, path) {
+ ("GET", "/wda/locked") => json!(s.locked),
+ ("GET", "/wda/screen") => json!({"screenSize": {"width": 430, "height": 932}, "scale": 3}),
+ ("POST", "/session") => return (200, json!({"sessionId": "S", "value": {}})),
+ ("GET", "/appium/settings") => json!({"waitForIdleTimeout": s.idle.0, "animationCoolOffTimeout": s.idle.1}),
+ ("POST", "/appium/settings") => {
+ let b = &body.unwrap()["settings"];
+ s.idle = (b["waitForIdleTimeout"].as_f64().unwrap(), b["animationCoolOffTimeout"].as_f64().unwrap());
+ Value::Null
+ }
+ ("POST", "/wda/pressButton") => {
+ s.shown = false;
+ s.entered.clear();
+ Value::Null
+ }
+ ("POST", "/actions") => {
+ s.requests_to_actions += 1;
+ let idle = s.idle;
+ s.idle_during_unlock.push(idle);
+ let steps = body.unwrap()["actions"][0]["actions"].as_array().unwrap().clone();
+ let downs = steps.iter().filter(|a| a["type"] == "pointerDown").count();
+ let is_swipe = steps.iter().any(|a| a["type"] == "pointerMove" && a["duration"].as_u64().unwrap_or(0) > 0);
+ if is_swipe {
+ if s.swipes_to_ignore > 0 {
+ s.swipes_to_ignore -= 1;
+ } else {
+ s.shown = true;
+ }
+ } else {
+ s.presses_per_action_max = s.presses_per_action_max.max(downs);
+ let (x, y) = (steps[0]["x"].as_f64().unwrap() as i64, steps[0]["y"].as_f64().unwrap() as i64);
+ let digit = KEYS.iter().position(|k| *k == (x, y)).expect("按在键盘以外") as u8;
+ if s.shown {
+ s.press_count += 1;
+ if s.drop_press != Some(s.press_count) {
+ s.entered.push(digit);
+ s.digits_typed += 1;
+ }
+ if s.entered.len() == self.code.len() {
+ if s.entered == self.code {
+ s.locked = false;
+ } else {
+ s.failed_attempts += 1;
+ }
+ s.entered.clear();
+ }
+ }
+ }
+ Value::Null
+ }
+ ("GET", p) if p.starts_with("/source") => json!(LOCK_XML),
+ ("POST", "/elements") => json!([{"ELEMENT": "E1"}]),
+ ("GET", "/element/E1/attribute/value") => json!(format!("共{}位数,已输入{}位", self.code.len(), s.entered.len())),
+ _ => return (404, json!({"value": {"error": "unknown command", "message": path}})),
+ };
+ (200, json!({"value": v, "sessionId": "S"}))
+ }
+}
+
+impl Transport for &FakeLockScreen {
+ async fn send(&self, method: &str, path: &str, body: Option<Vec<u8>>, _: Duration) -> std::io::Result<(u16, Vec<u8>)> {
+ let body = body.and_then(|b| serde_json::from_slice(&b).ok());
+ let (status, v) = self.handle(method, path, body);
+ Ok((status, v.to_string().into_bytes()))
+ }
+}
diff --git a/crates/ictl-unlock/src/lib.rs b/crates/ictl-unlock/src/lib.rs
index 7167d2f..929e572 100644
--- a/crates/ictl-unlock/src/lib.rs
+++ b/crates/ictl-unlock/src/lib.rs
@@ -1,47 +1,311 @@
-//! 锁屏自动解锁(默认关闭,需显式开启并配置密码文件)。
+//! 锁屏自动解锁(默认关闭,需显式配置密码文件)。
//!
-//! 必须遵守的规则(toolkit 实测,见 docs/capability-matrix.md §5):
-//! 1. 唤醒固定为:Home → 等 1.0s → 底部上滑 → 等 1.5s;不以"树里有键盘"作判断
-//! 2. 先读密码栏「共N位数,已输入M位」,总位数不符一位都不输
-//! 3. 每位一个独立 W3C 手势(按下 80ms),按完核对已输入位数 +1,不符立即停
-//! 4. 期间 waitForIdleTimeout=1、animationCoolOffTimeout=0.2,结束后恢复(0 会唤醒失败)
-//! 5. 第一位没生效可重来(最多 3 轮);整串输完仍锁着才算输错:写停用标记 + 通知
-//! 6. 只支持纯数字;开机后首次解锁(BFU)永远需要人工
+//! 规则全部来自 toolkit 实测(docs/capability-matrix.md §5):
+//! 1. 先读 `/wda/locked`,没锁直接返回;WDA 不可用也直接返回(交给后面的调用去报错)
+//! 2. 每轮固定:按 Home → 等 1.0s → 底部上滑 → 等 1.5s。不以「树里有键盘」判断:键盘收起时按键元素也常驻树中
+//! 3. 读密码栏「共N位数,已输入M位」:总位数和配置不符一位都不输;有残留输入就下一轮(Home 会清空)
+//! 4. 每位一个独立 W3C 手势(按下 80ms),按完核对已输入位数正好 +1,不符立即停——输入不完整不算输错。
+//! 多位合成一个手势会漏键;`/wda/tap` 在锁屏上每次约 2.9 秒,太慢
+//! 5. 解锁期间 waitForIdleTimeout=1、animationCoolOffTimeout=0.2(0 会唤醒失败),结束后恢复
+//! 6. 第一位没生效可以重来(最多 3 轮);整串输完仍锁着才算真正输错一次:写停用标记,之后拒绝自动解锁直到人工清除
+//! 7. 只支持纯数字;开机后首次解锁(BFU)永远需要人工
use std::path::PathBuf;
+use std::time::Duration;
-pub const WAKE_SETTLE_MS: u64 = 1000;
-pub const SWIPE_SETTLE_MS: u64 = 1500;
-pub const KEY_PRESS_MS: u64 = 80;
-pub const FIRST_DIGIT_ROUNDS: u32 = 3;
+use ictl_wda::{IdleSettings, WdaClient, WdaError, elements, http::Transport, swipe_steps, tap_steps};
#[derive(Debug, thiserror::Error)]
pub enum UnlockError {
- #[error("没有配置锁屏密码,需要人工解锁")]
+ #[error("手机已锁屏,且没有配置锁屏密码,需要人工解锁")]
NoPasscode,
- #[error("自动解锁之前失败过已停用,请人工解锁并检查配置后清除停用标记")]
+ #[error("自动解锁只支持纯数字锁屏密码")]
+ NotDigits,
+ #[error("手机已锁屏;自动解锁之前失败过已停用,请人工解锁、核对密码后运行 iphone-control unlock-reset")]
Disabled,
- #[error("调不出密码键盘(一位都没输)")]
+ #[error("调不出锁屏密码键盘(一位都没输进去),请截图看看锁屏界面")]
NoKeypad,
/// 输入不完整,不算输错
- #[error("第 {0} 位没按上,已停止(输入不完整不算输错)")]
+ #[error("第 {0} 位没按上,已停止(输入不完整不算输错),稍后再试")]
Incomplete(u32),
#[error("手机要求 {expected} 位密码,配置的是 {configured} 位,一位都没输")]
LengthMismatch { expected: u32, configured: u32 },
/// 整串输完仍锁着:已写停用标记
- #[error("整串密码输完手机仍锁着,自动解锁已停用")]
+ #[error("整串密码输完手机仍锁着,自动解锁已停用(防止输错次数累计)")]
WrongPasscode,
#[error(transparent)]
- Wda(#[from] ictl_wda::WdaError),
+ Wda(#[from] WdaError),
+ #[error("{0}")]
+ Io(#[from] std::io::Error),
}
+pub type Result<T> = std::result::Result<T, UnlockError>;
+
+/// 各步等待时长。默认值是实测可靠的;单测里设为 0
+#[derive(Debug, Clone, Copy)]
+pub struct Timing {
+ pub wake_settle: Duration,
+ pub swipe_settle: Duration,
+ pub key_press_ms: u64,
+ pub key_confirm: Duration,
+ pub unlock_confirm: Duration,
+ pub poll: Duration,
+}
+
+impl Default for Timing {
+ fn default() -> Self {
+ Self {
+ wake_settle: Duration::from_millis(1000),
+ swipe_settle: Duration::from_millis(1500),
+ key_press_ms: 80,
+ key_confirm: Duration::from_millis(1500),
+ unlock_confirm: Duration::from_secs(5),
+ poll: Duration::from_millis(300),
+ }
+ }
+}
+
+pub const FIRST_DIGIT_ROUNDS: u32 = 3;
+/// 解锁期间的等待上限(不能是 0:唤醒会失败)
+pub const UNLOCK_IDLE: IdleSettings = IdleSettings { wait_for_idle_timeout: 1.0, animation_cool_off_timeout: 0.2 };
+
pub struct UnlockConfig {
pub passcode_file: PathBuf,
pub disabled_flag: PathBuf,
+ pub timing: Timing,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Outcome {
+ /// 本来就没锁,或 WDA 不可用(不处理)
+ NotLocked,
+ Unlocked,
+}
+
+impl UnlockConfig {
+ pub fn enabled(&self) -> bool {
+ self.passcode_file.is_file()
+ }
+
+ pub fn disabled_by_failure(&self) -> bool {
+ self.disabled_flag.exists()
+ }
+}
+
+/// 未锁屏直接返回;否则按规则解锁
+pub async fn ensure_unlocked<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig) -> Result<Outcome> {
+ match wda.locked().await {
+ Ok(false) | Err(WdaError::Unavailable(_)) => return Ok(Outcome::NotLocked),
+ Ok(true) => {}
+ Err(e) => return Err(e.into()),
+ }
+ if cfg.disabled_by_failure() {
+ return Err(UnlockError::Disabled);
+ }
+ let code = std::fs::read_to_string(&cfg.passcode_file).map_err(|_| UnlockError::NoPasscode)?.trim().to_owned();
+ if code.is_empty() || !code.bytes().all(|b| b.is_ascii_digit()) {
+ return Err(UnlockError::NotDigits);
+ }
+ let saved = wda.idle_settings().await?;
+ wda.set_idle_settings(UNLOCK_IDLE).await?;
+ let r = unlock(wda, cfg, code.as_bytes()).await;
+ if let Err(e) = wda.set_idle_settings(saved).await {
+ tracing::warn!("恢复 WDA 等待设置失败:{e}");
+ }
+ r
+}
+
+async fn press<T: Transport>(wda: &mut WdaClient<T>, at: (i64, i64), t: &Timing) -> Result<()> {
+ Ok(wda.actions(&tap_steps(at.0 as f64, at.1 as f64, t.key_press_ms)).await?)
}
-/// 未锁屏直接返回 Ok;否则按规则解锁
-pub async fn ensure_unlocked(wda: &mut ictl_wda::WdaClient, cfg: &UnlockConfig) -> Result<(), UnlockError> {
- let _ = (wda, cfg);
- todo!()
+/// 按一个数字键,等密码栏已输入位数变成 `expect`;返回实际位数(读不到密码栏为 -1)
+async fn tap_key<T: Transport>(wda: &mut WdaClient<T>, at: (i64, i64), expect: u32, t: &Timing) -> Result<i64> {
+ press(wda, at, t).await?;
+ let deadline = tokio::time::Instant::now() + t.key_confirm;
+ loop {
+ let got = wda.passcode_field().await?.map(|f| f.1 as i64).unwrap_or(-1);
+ if got >= expect as i64 || tokio::time::Instant::now() >= deadline {
+ return Ok(got);
+ }
+ tokio::time::sleep(t.poll.min(Duration::from_millis(150))).await;
+ }
+}
+
+async fn unlock<T: Transport>(wda: &mut WdaClient<T>, cfg: &UnlockConfig, code: &[u8]) -> Result<Outcome> {
+ let t = &cfg.timing;
+ let screen = wda.screen_size().await?;
+ let digit = |i: usize| (code[i] - b'0') as usize;
+ let len = code.len() as u32;
+
+ let mut keys = None;
+ for _ in 0..FIRST_DIGIT_ROUNDS {
+ // Home 唤醒;键盘已打开时会收起并清空半截输入
+ wda.press_button("home").await?;
+ tokio::time::sleep(t.wake_settle).await;
+ let (cx, h) = (screen.width / 2.0, screen.height);
+ wda.actions(&swipe_steps((cx, h - 8.0), (cx, h * 0.45), 250)).await?;
+ tokio::time::sleep(t.swipe_settle).await;
+ if !wda.locked().await? {
+ return Ok(Outcome::Unlocked);
+ }
+ let (Some(pad), Some((total, entered))) = (elements::keypad(&wda.elements().await?), wda.passcode_field().await?) else {
+ continue;
+ };
+ if entered != 0 {
+ continue;
+ }
+ if total != len {
+ return Err(UnlockError::LengthMismatch { expected: total, configured: len });
+ }
+ match tap_key(wda, pad[digit(0)], 1, t).await? {
+ 1 => {
+ keys = Some(pad);
+ break;
+ }
+ n if n > 1 => return Err(UnlockError::Incomplete(1)),
+ _ => continue,
+ }
+ }
+ let pad = keys.ok_or(UnlockError::NoKeypad)?;
+
+ for n in 2..len {
+ if tap_key(wda, pad[digit(n as usize - 1)], n, t).await? != n as i64 {
+ return Err(UnlockError::Incomplete(n));
+ }
+ }
+
+ press(wda, pad[digit(code.len() - 1)], t).await?;
+ let deadline = tokio::time::Instant::now() + t.unlock_confirm;
+ loop {
+ tokio::time::sleep(t.poll).await;
+ if !wda.locked().await? {
+ return Ok(Outcome::Unlocked);
+ }
+ if tokio::time::Instant::now() >= deadline {
+ break;
+ }
+ }
+ let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs();
+ std::fs::write(&cfg.disabled_flag, format!("{now} 整串密码输完仍是锁屏状态\n"))?;
+ Err(UnlockError::WrongPasscode)
+}
+
+#[cfg(test)]
+mod fake;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use fake::FakeLockScreen;
+
+ fn cfg(passcode: Option<&str>) -> (UnlockConfig, PathBuf) {
+ let dir = std::env::temp_dir().join(format!("ictl-unlock-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ if let Some(p) = passcode {
+ std::fs::write(dir.join("passcode"), p).unwrap();
+ }
+ let timing = Timing {
+ wake_settle: Duration::ZERO,
+ swipe_settle: Duration::ZERO,
+ key_press_ms: 80,
+ key_confirm: Duration::from_millis(20),
+ unlock_confirm: Duration::from_millis(20),
+ poll: Duration::from_millis(1),
+ };
+ (UnlockConfig { passcode_file: dir.join("passcode"), disabled_flag: dir.join("UNLOCK-DISABLED"), timing }, dir)
+ }
+
+ #[tokio::test]
+ async fn correct_passcode_unlocks_and_restores_idle_settings() {
+ let fake = FakeLockScreen::new("123456");
+ let (cfg, dir) = cfg(Some("123456\n"));
+ let mut wda = WdaClient::new(&fake);
+ assert_eq!(ensure_unlocked(&mut wda, &cfg).await.unwrap(), Outcome::Unlocked);
+ let s = fake.state();
+ assert!(!s.locked);
+ assert_eq!(s.idle, (10.0, 2.0), "结束后要恢复原来的等待设置");
+ assert!(s.idle_during_unlock.iter().all(|i| *i == (1.0, 0.2)));
+ assert_eq!(s.presses_per_action_max, 1, "每位一个独立手势");
+ assert!(!cfg.disabled_flag.exists());
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
+ #[tokio::test]
+ async fn not_locked_does_nothing() {
+ let fake = FakeLockScreen::new("123456");
+ fake.unlock_now();
+ let (cfg, dir) = cfg(None);
+ assert_eq!(ensure_unlocked(&mut WdaClient::new(&fake), &cfg).await.unwrap(), Outcome::NotLocked);
+ assert_eq!(fake.state().requests_to_actions, 0);
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
+ #[tokio::test]
+ async fn wrong_passcode_counts_once_and_disables() {
+ let fake = FakeLockScreen::new("123456");
+ let (cfg, dir) = cfg(Some("654321"));
+ let mut wda = WdaClient::new(&fake);
+ assert!(matches!(ensure_unlocked(&mut wda, &cfg).await, Err(UnlockError::WrongPasscode)));
+ assert_eq!(fake.state().failed_attempts, 1);
+ assert!(cfg.disabled_flag.exists());
+ // 停用后不再尝试
+ assert!(matches!(ensure_unlocked(&mut wda, &cfg).await, Err(UnlockError::Disabled)));
+ assert_eq!(fake.state().failed_attempts, 1);
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
+ #[tokio::test]
+ async fn length_mismatch_types_nothing() {
+ let fake = FakeLockScreen::new("123456");
+ let (cfg, dir) = cfg(Some("1234"));
+ let r = ensure_unlocked(&mut WdaClient::new(&fake), &cfg).await;
+ assert!(matches!(r, Err(UnlockError::LengthMismatch { expected: 6, configured: 4 })), "{r:?}");
+ assert_eq!(fake.state().digits_typed, 0);
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
+ /// 回归用例 #1:键盘收起时按键仍在树里。第一次上滑没调出键盘(按键落空),不算输错,下一轮重来
+ #[tokio::test]
+ async fn keypad_in_tree_but_not_shown_retries_without_counting() {
+ let fake = FakeLockScreen::new("123456");
+ fake.swipes_ignored(1);
+ let (cfg, dir) = cfg(Some("123456"));
+ assert_eq!(ensure_unlocked(&mut WdaClient::new(&fake), &cfg).await.unwrap(), Outcome::Unlocked);
+ assert_eq!(fake.state().failed_attempts, 0);
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
+ #[tokio::test]
+ async fn keypad_never_shows_is_no_keypad_not_wrong() {
+ let fake = FakeLockScreen::new("123456");
+ fake.swipes_ignored(99);
+ let (cfg, dir) = cfg(Some("123456"));
+ assert!(matches!(ensure_unlocked(&mut WdaClient::new(&fake), &cfg).await, Err(UnlockError::NoKeypad)));
+ assert!(!cfg.disabled_flag.exists());
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
+ /// 回归用例 #4:中间某位被吞(键盘没接住),立即停止,不提交、不算输错
+ #[tokio::test]
+ async fn dropped_middle_digit_stops_without_submitting() {
+ let fake = FakeLockScreen::new("123456");
+ fake.drop_press(3);
+ let (cfg, dir) = cfg(Some("123456"));
+ assert!(matches!(ensure_unlocked(&mut WdaClient::new(&fake), &cfg).await, Err(UnlockError::Incomplete(3))));
+ assert_eq!(fake.state().failed_attempts, 0);
+ assert!(!cfg.disabled_flag.exists());
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
+ #[tokio::test]
+ async fn missing_or_non_digit_passcode() {
+ let fake = FakeLockScreen::new("123456");
+ let (cfg_none, d1) = cfg(None);
+ assert!(matches!(ensure_unlocked(&mut WdaClient::new(&fake), &cfg_none).await, Err(UnlockError::NoPasscode)));
+ let (cfg_alpha, d2) = cfg(Some("abc123"));
+ assert!(matches!(ensure_unlocked(&mut WdaClient::new(&fake), &cfg_alpha).await, Err(UnlockError::NotDigits)));
+ std::fs::remove_dir_all(d1).unwrap();
+ std::fs::remove_dir_all(d2).unwrap();
+ }
}
diff --git a/crates/ictl-wda/Cargo.toml b/crates/ictl-wda/Cargo.toml
index 5fdbd37..f1075d0 100644
--- a/crates/ictl-wda/Cargo.toml
+++ b/crates/ictl-wda/Cargo.toml
@@ -12,7 +12,8 @@ ictl-device.workspace = true
idevice.workspace = true
tokio.workspace = true
quick-xml.workspace = true
-serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
tracing.workspace = true
+base64.workspace = true
+regex.workspace = true
diff --git a/crates/ictl-wda/src/client.rs b/crates/ictl-wda/src/client.rs
new file mode 100644
index 0000000..61ad23e
--- /dev/null
+++ b/crates/ictl-wda/src/client.rs
@@ -0,0 +1,349 @@
+//! WDA HTTP 客户端。会话失效(WDA 重启后)自动重建一次。
+
+use std::time::Duration;
+
+use base64::Engine;
+use ictl_device::ScreenSize;
+use serde_json::{Value, json};
+
+use crate::http::Transport;
+use crate::{Result, WdaError, elements};
+
+const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
+
+/// W3C pointer 动作的一步
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub enum PointerStep {
+ Move { x: f64, y: f64, ms: u64 },
+ Down,
+ Up,
+ Pause { ms: u64 },
+}
+
+/// 单指点一下:按下停 `press_ms` 再抬起
+pub fn tap_steps(x: f64, y: f64, press_ms: u64) -> Vec<PointerStep> {
+ vec![PointerStep::Move { x, y, ms: 0 }, PointerStep::Down, PointerStep::Pause { ms: press_ms }, PointerStep::Up]
+}
+
+/// 滑动:按下、停 50ms、在 `ms` 毫秒内移到终点、抬起(与 toolkit 一致)
+pub fn swipe_steps(from: (f64, f64), to: (f64, f64), ms: u64) -> Vec<PointerStep> {
+ vec![
+ PointerStep::Move { x: from.0, y: from.1, ms: 0 },
+ PointerStep::Down,
+ PointerStep::Pause { ms: 50 },
+ PointerStep::Move { x: to.0, y: to.1, ms },
+ PointerStep::Up,
+ ]
+}
+
+/// `POST /session/{id}/actions` 的请求体
+pub fn actions_body(steps: &[PointerStep]) -> Value {
+ let actions: Vec<Value> = steps
+ .iter()
+ .map(|s| match *s {
+ PointerStep::Move { x, y, ms } => json!({"type": "pointerMove", "duration": ms, "x": x, "y": y}),
+ PointerStep::Down => json!({"type": "pointerDown", "button": 0}),
+ PointerStep::Up => json!({"type": "pointerUp", "button": 0}),
+ PointerStep::Pause { ms } => json!({"type": "pause", "duration": ms}),
+ })
+ .collect();
+ json!({"actions": [{"type": "pointer", "id": "finger1", "parameters": {"pointerType": "touch"}, "actions": actions}]})
+}
+
+/// appium settings 中与等待有关的两项。锁屏解锁期间要临时调小。
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct IdleSettings {
+ pub wait_for_idle_timeout: f64,
+ pub animation_cool_off_timeout: f64,
+}
+
+pub struct WdaClient<T> {
+ transport: T,
+ session: Option<String>,
+ screen: Option<ScreenSize>,
+}
+
+impl<T: Transport> WdaClient<T> {
+ pub fn new(transport: T) -> Self {
+ Self { transport, session: None, screen: None }
+ }
+
+ async fn call(&self, method: &str, path: &str, body: Option<Value>, timeout: Duration) -> Result<Value> {
+ let body = body.map(|b| b.to_string().into_bytes());
+ let (status, raw) = self
+ .transport
+ .send(method, path, body, timeout)
+ .await
+ .map_err(|e| WdaError::Unavailable(e.to_string()))?;
+ let v: Value = match serde_json::from_slice(&raw) {
+ Ok(v) => v,
+ Err(_) if status >= 400 => return Err(WdaError::Remote { kind: "http".into(), message: status.to_string() }),
+ Err(e) => return Err(WdaError::Unavailable(format!("响应不是 JSON:{e}"))),
+ };
+ if let Some(err) = v.get("value").and_then(|x| x.get("error")).and_then(|e| e.as_str()) {
+ let msg = v["value"].get("message").and_then(|m| m.as_str()).unwrap_or_default();
+ return Err(WdaError::Remote { kind: err.to_owned(), message: msg.lines().next().unwrap_or_default().to_owned() });
+ }
+ Ok(v)
+ }
+
+ async fn get(&self, path: &str) -> Result<Value> {
+ Ok(self.call("GET", path, None, DEFAULT_TIMEOUT).await?["value"].take())
+ }
+
+ async fn session_id(&mut self) -> Result<String> {
+ if let Some(s) = &self.session {
+ return Ok(s.clone());
+ }
+ let r = self
+ .call("POST", "/session", Some(json!({"capabilities": {"alwaysMatch": {}}})), DEFAULT_TIMEOUT)
+ .await?;
+ let id = r
+ .get("sessionId")
+ .and_then(|s| s.as_str())
+ .or_else(|| r["value"].get("sessionId").and_then(|s| s.as_str()))
+ .ok_or_else(|| WdaError::Unavailable("创建会话没有返回 sessionId".into()))?
+ .to_owned();
+ self.session = Some(id.clone());
+ Ok(id)
+ }
+
+ /// 带会话的请求;会话失效时重建一次再试
+ pub async fn in_session(&mut self, method: &str, path: &str, body: Option<Value>, timeout: Duration) -> Result<Value> {
+ for attempt in 0..2 {
+ let sid = self.session_id().await?;
+ match self.call(method, &format!("/session/{sid}{path}"), body.clone(), timeout).await {
+ Err(WdaError::Remote { kind, .. }) if attempt == 0 && kind.contains("session") => self.session = None,
+ other => return other.map(|mut v| v["value"].take()),
+ }
+ }
+ unreachable!()
+ }
+
+ async fn post(&mut self, path: &str, body: Value) -> Result<Value> {
+ self.in_session("POST", path, Some(body), DEFAULT_TIMEOUT).await
+ }
+
+ pub async fn status(&self) -> Result<Value> {
+ self.get("/status").await
+ }
+
+ pub async fn ready(&self) -> Result<bool> {
+ Ok(self.call("GET", "/status", None, Duration::from_secs(5)).await?["value"]["ready"] == true)
+ }
+
+ /// 屏幕点尺寸,拿到后缓存
+ pub async fn screen_size(&mut self) -> Result<ScreenSize> {
+ if let Some(s) = self.screen {
+ return Ok(s);
+ }
+ let v = self.get("/wda/screen").await?;
+ let s = &v["screenSize"];
+ let size = match (s["width"].as_f64(), s["height"].as_f64()) {
+ (Some(width), Some(height)) => ScreenSize { width, height },
+ _ => return Err(WdaError::Unavailable("/wda/screen 没有 screenSize".into())),
+ };
+ self.screen = Some(size);
+ Ok(size)
+ }
+
+ pub async fn locked(&self) -> Result<bool> {
+ Ok(self.call("GET", "/wda/locked", None, Duration::from_secs(10)).await?["value"] == true)
+ }
+
+ pub async fn active_app(&self) -> Result<String> {
+ Ok(self.get("/wda/activeAppInfo").await?["bundleId"].as_str().unwrap_or_default().to_owned())
+ }
+
+ pub async fn screenshot_png(&self) -> Result<Vec<u8>> {
+ let v = self.get("/screenshot").await?;
+ let b64: String = v.as_str().unwrap_or_default().chars().filter(|c| !c.is_whitespace()).collect();
+ base64::engine::general_purpose::STANDARD
+ .decode(b64)
+ .map_err(|e| WdaError::Unavailable(format!("截图不是有效的 base64:{e}")))
+ }
+
+ /// 元素树 XML,排除可见性等慢属性(完整树 7~8 秒,排除后约 0.3 秒)
+ pub async fn source_xml(&self) -> Result<String> {
+ let path = format!("/source?format=xml&excluded_attributes={}", elements::SOURCE_EXCLUDED);
+ let v = self.call("GET", &path, None, Duration::from_secs(60)).await?;
+ Ok(v["value"].as_str().unwrap_or_default().to_owned())
+ }
+
+ pub async fn elements(&mut self) -> Result<Vec<elements::Element>> {
+ let screen = self.screen_size().await?;
+ Ok(elements::parse(&self.source_xml().await?, screen))
+ }
+
+ pub async fn tap(&mut self, x: f64, y: f64) -> Result<()> {
+ self.post("/wda/tap", json!({"x": x, "y": y})).await.map(drop)
+ }
+
+ pub async fn touch_and_hold(&mut self, x: f64, y: f64, seconds: f64) -> Result<()> {
+ self.post("/wda/touchAndHold", json!({"x": x, "y": y, "duration": seconds})).await.map(drop)
+ }
+
+ /// 一次 W3C actions 请求。注意:多次点击合并成一个请求会漏键,解锁时每位单独发
+ pub async fn actions(&mut self, steps: &[PointerStep]) -> Result<()> {
+ self.post("/actions", actions_body(steps)).await.map(drop)
+ }
+
+ pub async fn keys(&mut self, text: &str) -> Result<()> {
+ let chars: Vec<String> = text.chars().map(String::from).collect();
+ self.in_session("POST", "/wda/keys", Some(json!({"value": chars})), Duration::from_secs(120)).await.map(drop)
+ }
+
+ /// home / volumeUp / volumeDown
+ pub async fn press_button(&mut self, name: &str) -> Result<()> {
+ self.post("/wda/pressButton", json!({"name": name})).await.map(drop)
+ }
+
+ pub async fn lock(&mut self) -> Result<()> {
+ self.post("/wda/lock", json!({})).await.map(drop)
+ }
+
+ /// 启动并等到前台后再停 1 秒(冷启动后立即点击会被吞)
+ pub async fn launch_app(&mut self, bundle_id: &str) -> Result<()> {
+ self.in_session("POST", "/wda/apps/launch", Some(json!({"bundleId": bundle_id})), Duration::from_secs(60)).await?;
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(8);
+ while tokio::time::Instant::now() < deadline && self.active_app().await? != bundle_id {
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ Ok(())
+ }
+
+ pub async fn terminate_app(&mut self, bundle_id: &str) -> Result<()> {
+ self.post("/wda/apps/terminate", json!({"bundleId": bundle_id})).await.map(drop)
+ }
+
+ pub async fn open_url(&mut self, url: &str) -> Result<()> {
+ self.in_session("POST", "/url", Some(json!({"url": url})), Duration::from_secs(60)).await.map(drop)
+ }
+
+ pub async fn idle_settings(&mut self) -> Result<IdleSettings> {
+ let v = self.in_session("GET", "/appium/settings", None, DEFAULT_TIMEOUT).await?;
+ Ok(IdleSettings {
+ wait_for_idle_timeout: v["waitForIdleTimeout"].as_f64().unwrap_or(10.0),
+ animation_cool_off_timeout: v["animationCoolOffTimeout"].as_f64().unwrap_or(2.0),
+ })
+ }
+
+ pub async fn set_idle_settings(&mut self, s: IdleSettings) -> Result<()> {
+ let body = json!({"settings": {"waitForIdleTimeout": s.wait_for_idle_timeout, "animationCoolOffTimeout": s.animation_cool_off_timeout}});
+ self.post("/appium/settings", body).await.map(drop)
+ }
+
+ /// 锁屏密码栏的 (总位数, 已输入位数);找不到密码栏返回 None
+ pub async fn passcode_field(&mut self) -> Result<Option<(u32, u32)>> {
+ let els = self
+ .post("/elements", json!({"using": "class name", "value": "XCUIElementTypeSecureTextField"}))
+ .await?;
+ for e in els.as_array().into_iter().flatten() {
+ let Some(eid) = e.as_object().and_then(|o| o.values().next()).and_then(|v| v.as_str()) else { continue };
+ let v = self.in_session("GET", &format!("/element/{eid}/attribute/value"), None, DEFAULT_TIMEOUT).await?;
+ if let Some(p) = v.as_str().and_then(elements::parse_passcode_value) {
+ return Ok(Some(p));
+ }
+ }
+ Ok(None)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::VecDeque;
+ use std::sync::Mutex;
+
+ /// 按顺序返回预设响应,并记录收到的请求
+ #[derive(Default)]
+ struct Mock {
+ replies: Mutex<VecDeque<(u16, String)>>,
+ seen: Mutex<Vec<(String, String, Option<String>)>>,
+ }
+
+ impl Mock {
+ fn with(replies: &[(u16, &str)]) -> Self {
+ Self { replies: Mutex::new(replies.iter().map(|(s, b)| (*s, b.to_string())).collect()), ..Default::default() }
+ }
+ }
+
+ impl Transport for &Mock {
+ async fn send(&self, method: &str, path: &str, body: Option<Vec<u8>>, _: Duration) -> std::io::Result<(u16, Vec<u8>)> {
+ self.seen.lock().unwrap().push((method.into(), path.into(), body.map(|b| String::from_utf8(b).unwrap())));
+ let (s, b) = self.replies.lock().unwrap().pop_front().ok_or_else(|| std::io::Error::other("连接被拒绝"))?;
+ Ok((s, b.into_bytes()))
+ }
+ }
+
+ #[tokio::test]
+ async fn session_is_recreated_once_after_invalid_session() {
+ let m = Mock::with(&[
+ (200, r#"{"sessionId":"A","value":{}}"#),
+ (404, r#"{"value":{"error":"invalid session id","message":"gone\nmore"}}"#),
+ (200, r#"{"value":{"sessionId":"B"}}"#),
+ (200, r#"{"value":null}"#),
+ ]);
+ let mut c = WdaClient::new(&m);
+ c.tap(10.0, 20.0).await.unwrap();
+ let paths: Vec<_> = m.seen.lock().unwrap().iter().map(|s| s.1.clone()).collect();
+ assert_eq!(paths, ["/session", "/session/A/wda/tap", "/session", "/session/B/wda/tap"]);
+ }
+
+ #[tokio::test]
+ async fn remote_error_keeps_first_line_and_unreachable_maps_to_unavailable() {
+ let m = Mock::with(&[(200, r#"{"sessionId":"A"}"#), (500, r#"{"value":{"error":"unknown error","message":"boom\nstack"}}"#)]);
+ let mut c = WdaClient::new(&m);
+ match c.tap(1.0, 1.0).await {
+ Err(WdaError::Remote { kind, message }) => assert_eq!((kind.as_str(), message.as_str()), ("unknown error", "boom")),
+ other => panic!("{other:?}"),
+ }
+ assert!(matches!(c.status().await, Err(WdaError::Unavailable(_))));
+ }
+
+ #[tokio::test]
+ async fn screen_size_is_cached_and_status_ready() {
+ let m = Mock::with(&[
+ (200, r#"{"value":{"screenSize":{"width":430,"height":932},"scale":3}}"#),
+ (200, r#"{"value":{"ready":true}}"#),
+ ]);
+ let mut c = WdaClient::new(&m);
+ assert_eq!(c.screen_size().await.unwrap(), ScreenSize { width: 430.0, height: 932.0 });
+ assert_eq!(c.screen_size().await.unwrap().width, 430.0);
+ assert!(c.ready().await.unwrap());
+ }
+
+ #[tokio::test]
+ async fn source_request_excludes_slow_attributes() {
+ let m = Mock::with(&[(200, r#"{"value":"<x/>"}"#)]);
+ let c = WdaClient::new(&m);
+ c.source_xml().await.unwrap();
+ let path = m.seen.lock().unwrap()[0].1.clone();
+ assert!(path.starts_with("/source?format=xml&excluded_attributes=visible,"), "{path}");
+ }
+
+ #[tokio::test]
+ async fn passcode_field_reads_secure_text_field_value() {
+ let m = Mock::with(&[
+ (200, r#"{"sessionId":"S"}"#),
+ (200, r#"{"value":[{"ELEMENT":"E1","element-6066-11e4-a52e-4f735466cecf":"E1"}]}"#),
+ (200, r#"{"value":"共6位数,已输入2位"}"#),
+ ]);
+ let mut c = WdaClient::new(&m);
+ assert_eq!(c.passcode_field().await.unwrap(), Some((6, 2)));
+ assert_eq!(m.seen.lock().unwrap()[2].1, "/session/S/element/E1/attribute/value");
+ }
+
+ #[test]
+ fn actions_body_is_one_pointer_with_steps() {
+ let b = actions_body(&tap_steps(10.0, 20.0, 80));
+ let a = &b["actions"][0];
+ assert_eq!(a["parameters"]["pointerType"], "touch");
+ let types: Vec<_> = a["actions"].as_array().unwrap().iter().map(|s| s["type"].as_str().unwrap()).collect();
+ assert_eq!(types, ["pointerMove", "pointerDown", "pause", "pointerUp"]);
+ assert_eq!(a["actions"][2]["duration"], 80);
+ let s = swipe_steps((1.0, 2.0), (3.0, 4.0), 300);
+ assert_eq!(s[3], PointerStep::Move { x: 3.0, y: 4.0, ms: 300 });
+ }
+}
diff --git a/crates/ictl-wda/src/elements.rs b/crates/ictl-wda/src/elements.rs
index 62f1d5e..f070a21 100644
--- a/crates/ictl-wda/src/elements.rs
+++ b/crates/ictl-wda/src/elements.rs
@@ -1,13 +1,17 @@
-//! 元素树解析(纯函数,单测用脱敏 XML 样本)。
+//! 元素树解析(纯函数)。行为与 toolkit 的 `src/iphone_mcp/elements.py` 一致:
//!
-//! 规则(来自 toolkit):
//! - 只保留有 label/name/value 的元素
-//! - 按坐标判断是否在屏幕内;铺满全屏的 Application/Window/Toolbar 之类去掉
-//! - 父子重复(同文字同位置)去重
+//! - 按坐标判断是否在屏幕内(请求时排除了 WDA 的可见性计算:完整树 7~8 秒,排除后约 0.3 秒)
+//! - 铺满全屏的 Application/Window 之类去掉;父子重复(同文字同位置)去重
//! - 点击中心取元素在屏幕内的部分
//! - 锁屏密码键盘的 `Key` 元素不显示时也在树里,**不能**据此判断键盘已出现
use ictl_device::ScreenSize;
+use quick_xml::{XmlVersion, events::Event};
+
+/// `/source?format=xml&excluded_attributes=` 要排除的属性
+pub const SOURCE_EXCLUDED: &str =
+ "visible,accessible,focused,enabled,selected,index,traits,placeholderValue,hittable,customActions,nativeFrame";
#[derive(Debug, Clone, PartialEq)]
pub struct Element {
@@ -19,50 +23,251 @@ pub struct Element {
pub size: (i64, i64),
}
+impl Element {
+ fn haystack(&self) -> String {
+ format!("{} {} {}", self.label, self.name, self.value).to_lowercase()
+ }
+
+ /// 与 toolkit 相同的一行描述:`Button "显示与亮度" id="..." @(215,676) 390x53`
+ pub fn describe(&self) -> String {
+ let text = [&self.label, &self.name, &self.value].into_iter().find(|s| !s.is_empty()).cloned().unwrap_or_default();
+ let mut s = format!("{} \"{}\"", self.kind, text);
+ if !self.name.is_empty() && !self.label.is_empty() && self.name != self.label {
+ s += &format!(" id=\"{}\"", self.name);
+ }
+ if !self.value.is_empty() && self.value != self.label && self.value != self.name {
+ let v: String = self.value.chars().take(60).collect();
+ s += &format!(" value=\"{v}\"");
+ }
+ s + &format!(" @({},{}) {}x{}", self.center.0, self.center.1, self.size.0, self.size.1)
+ }
+}
+
+/// Python `round()` 是银行家舍入;坐标这里差半点无所谓,但为了与 toolkit 输出逐字一致,照它来
+fn py_round(v: f64) -> i64 {
+ let r = v.round();
+ if (v - v.trunc()).abs() == 0.5 && (r as i64) % 2 != 0 { (r - v.signum()) as i64 } else { r as i64 }
+}
+
pub fn parse(xml: &str, screen: ScreenSize) -> Vec<Element> {
- let _ = (xml, screen);
- todo!("quick-xml 遍历")
+ let (sw, sh) = (screen.width, screen.height);
+ let mut reader = quick_xml::Reader::from_str(xml);
+ let mut seen = std::collections::HashSet::new();
+ let mut out = Vec::new();
+ loop {
+ let e = match reader.read_event() {
+ Ok(Event::Start(e)) | Ok(Event::Empty(e)) => e,
+ Ok(Event::Eof) | Err(_) => break,
+ Ok(_) => continue,
+ };
+ let tag = e.name().as_ref().to_owned();
+ let mut attr = std::collections::HashMap::new();
+ for a in e.attributes().flatten() {
+ let k = a.key.as_ref().to_owned();
+ let v = a.normalized_value(XmlVersion::Implicit1_0).map(|c| c.into_owned()).unwrap_or_default();
+ attr.insert(k, v);
+ }
+ let get = |k: &str| attr.get(k).map(|s| s.trim().to_owned()).unwrap_or_default();
+ let (label, name, value) = (get("label"), get("name"), get("value"));
+ let text = [&label, &name, &value].into_iter().find(|s| !s.is_empty()).cloned();
+ let Some(text) = text else { continue };
+ let num = |k: &str| attr.get(k).and_then(|s| s.parse::<f64>().ok()).unwrap_or(0.0);
+ let (x, y, w, h) = (num("x"), num("y"), num("width"), num("height"));
+ if w <= 0.0 || h <= 0.0 || x >= sw || y >= sh || x + w <= 0.0 || y + h <= 0.0 {
+ continue;
+ }
+ if w >= sw && h >= sh {
+ continue;
+ }
+ if !seen.insert((text, py_round(x), py_round(y), py_round(w), py_round(h))) {
+ continue;
+ }
+ let (vx1, vy1, vx2, vy2) = (x.max(0.0), y.max(0.0), (x + w).min(sw), (y + h).min(sh));
+ let kind = attr.get("type").cloned().unwrap_or(tag);
+ out.push(Element {
+ kind: kind.strip_prefix("XCUIElementType").unwrap_or(&kind).to_owned(),
+ label,
+ name,
+ value,
+ center: (py_round((vx1 + vx2) / 2.0), py_round((vy1 + vy2) / 2.0)),
+ size: (py_round(w), py_round(h)),
+ });
+ }
+ out
+}
+
+/// 标签/名字/值里包含 `text` 的元素(不区分大小写)
+pub fn filter<'a>(elements: &'a [Element], text: &str) -> Vec<&'a Element> {
+ let t = text.to_lowercase();
+ elements.iter().filter(|e| e.haystack().contains(&t)).collect()
}
-/// 按文字找元素:先完全相同,再包含(不区分大小写)
+/// 按文字找元素:先找标签或名字完全相同的,没有再找包含该文字的
pub fn find<'a>(elements: &'a [Element], text: &str) -> Vec<&'a Element> {
- let _ = (elements, text);
- todo!()
+ let exact: Vec<_> = elements.iter().filter(|e| e.label == text || e.name == text).collect();
+ if exact.is_empty() { filter(elements, text) } else { exact }
}
-/// 锁屏键盘 0~9 的中心点;没找齐 10 个返回 None
+/// 锁屏密码键盘上 0~9 各键的中心点;没找齐 10 个返回 None。
+/// 找到了也不代表键盘在屏幕上——按键后要核对密码栏的已输入位数。
pub fn keypad(elements: &[Element]) -> Option<[(i64, i64); 10]> {
- let _ = elements;
- todo!()
+ let mut keys: [Option<(i64, i64)>; 10] = [None; 10];
+ for e in elements.iter().filter(|e| e.kind == "Button" || e.kind == "Key") {
+ for t in [e.label.trim(), e.name.trim()] {
+ let mut chars = t.chars();
+ let (Some(first), second) = (chars.next(), chars.next()) else { continue };
+ // 键的标签可能是 "2" 或 "2 ABC",但不能是 "10"
+ if let Some(d) = first.to_digit(10)
+ && !second.is_some_and(|c| c.is_ascii_digit())
+ {
+ keys[d as usize].get_or_insert(e.center);
+ break;
+ }
+ }
+ }
+ let mut out = [(0, 0); 10];
+ for (i, k) in keys.into_iter().enumerate() {
+ out[i] = k?;
+ }
+ Some(out)
}
-/// 解析密码栏的值「共6位数,已输入2位」→ (6, 2)。只认恰好两个整数。
-pub fn parse_passcode_field(value: &str) -> Option<(u32, u32)> {
- let nums: Vec<u32> = value
- .split(|c: char| !c.is_ascii_digit())
- .filter(|s| !s.is_empty())
- .filter_map(|s| s.parse().ok())
- .collect();
+/// 锁屏密码栏的值形如「共6位数,已输入2位」或英文「6-digit passcode, 2 entered」,返回 (总位数, 已输入位数)
+pub fn parse_passcode_value(value: &str) -> Option<(u32, u32)> {
+ let nums: Vec<u32> = regex::Regex::new(r"\d+").ok()?.find_iter(value).filter_map(|m| m.as_str().parse().ok()).collect();
match nums[..] {
[total, entered] => Some((total, entered)),
_ => None,
}
}
-/// 元素一行描述,格式与 toolkit 一致:`Button "秒表" @(261,880) 106x54`
-pub fn describe(e: &Element) -> String {
- let text = [&e.label, &e.name, &e.value].into_iter().find(|s| !s.is_empty()).cloned().unwrap_or_default();
- format!("{} \"{}\" @({},{}) {}x{}", e.kind, text, e.center.0, e.center.1, e.size.0, e.size.1)
-}
-
#[cfg(test)]
mod tests {
use super::*;
+ const SCREEN: ScreenSize = ScreenSize { width: 430.0, height: 932.0 };
+ const HOME: &str = include_str!("../tests/fixtures/home.xml");
+ const LOCK: &str = include_str!("../tests/fixtures/lockscreen.xml");
+
+ fn labels(els: &[Element]) -> Vec<String> {
+ els.iter().map(|e| if e.label.is_empty() { e.name.clone() } else { e.label.clone() }).collect()
+ }
+
+ fn home() -> Vec<Element> {
+ parse(HOME, SCREEN)
+ }
+
+ #[test]
+ fn full_screen_containers_are_dropped() {
+ let h = home();
+ assert!(!labels(&h).contains(&"Home screen icons".to_owned()));
+ assert!(h.iter().all(|e| e.kind != "Application" && e.kind != "Window"));
+ }
+
+ #[test]
+ fn child_repeating_parent_label_and_rect_is_deduped() {
+ let h = home();
+ let l = labels(&h);
+ assert_eq!(l.iter().filter(|s| *s == "设置").count(), 1);
+ assert_eq!(h[l.iter().position(|s| s == "设置").unwrap()].kind, "Icon");
+ }
+
+ #[test]
+ fn offscreen_page_and_degenerate_elements_are_dropped() {
+ let l = labels(&home());
+ assert!(!l.contains(&"第二页的 App".to_owned()));
+ assert!(!l.contains(&"零宽".to_owned()));
+ }
+
+ #[test]
+ fn unlabeled_elements_are_dropped() {
+ assert!(home().iter().all(|e| !(e.label.is_empty() && e.name.is_empty() && e.value.is_empty())));
+ }
+
+ #[test]
+ fn center_is_clipped_to_visible_part() {
+ let h = home();
+ assert_eq!(h.iter().find(|e| e.label == "被顶出屏幕一半").unwrap().center, (150, 10));
+ assert_eq!(h.iter().find(|e| e.label.starts_with("垂直滚动条")).unwrap().center.0, 421);
+ }
+
+ #[test]
+ fn type_prefix_is_removed() {
+ let kinds: Vec<_> = home().iter().map(|e| e.kind.clone()).collect();
+ for k in ["Icon", "Button", "StaticText"] {
+ assert!(kinds.contains(&k.to_owned()));
+ }
+ }
+
+ #[test]
+ fn describe_matches_toolkit_format() {
+ let h = home();
+ let d = |l: &str| h.iter().find(|e| e.label == l).unwrap().describe();
+ assert_eq!(d("显示与亮度"), r#"Button "显示与亮度" id="com.apple.settings.displayAndBrightness" @(215,676) 390x53"#);
+ assert!(d("设置").contains(r#"value="1个新项目""#));
+ }
+
+ #[test]
+ fn find_prefers_exact_over_substring() {
+ let h = home();
+ let names = |v: Vec<&Element>| v.into_iter().map(|e| e.label.clone()).collect::<Vec<_>>();
+ assert_eq!(names(find(&h, "时钟")), ["时钟"]);
+ assert_eq!(names(find(&h, "亮度")), ["显示与亮度"]);
+ assert!(find(&h, "不存在").is_empty());
+ assert_eq!(names(find(&h, "com.apple.settings.displayAndBrightness")), ["显示与亮度"]);
+ }
+
+ #[test]
+ fn filter_is_case_insensitive_and_checks_value() {
+ let h = home();
+ assert_eq!(filter(&h, "新项目").iter().map(|e| e.label.as_str()).collect::<Vec<_>>(), ["设置"]);
+ }
+
+ fn key(label: &str, x: i64, kind: &str) -> Element {
+ Element { kind: kind.into(), label: label.into(), name: label.into(), value: String::new(), center: (x, 100), size: (80, 80) }
+ }
+
+ #[test]
+ fn keypad_needs_all_ten_digits() {
+ let keys: Vec<_> = (0..10).map(|d| key(&d.to_string(), d * 10, "Key")).collect();
+ let pad = keypad(&keys).unwrap();
+ assert_eq!(pad[0], (0, 100));
+ assert_eq!(pad[9], (90, 100));
+ assert!(keypad(&keys[..9]).is_none());
+ }
+
+ #[test]
+ fn keypad_accepts_letters_after_digit_but_not_multi_digit_labels() {
+ let keys: Vec<_> = (0..10).map(|d| key(&format!("{d} ABC"), d, "Button")).collect();
+ assert!(keypad(&keys).is_some());
+ let mut keys: Vec<_> = (0..9).map(|d| key(&d.to_string(), d, "Key")).collect();
+ keys.push(key("10", 0, "Key"));
+ assert!(keypad(&keys).is_none());
+ }
+
+ #[test]
+ fn keypad_ignores_non_key_types() {
+ let keys: Vec<_> = (0..10).map(|d| key(&d.to_string(), d, "StaticText")).collect();
+ assert!(keypad(&keys).is_none());
+ }
+
+ /// 回归用例 #1:键盘收起时 Key 元素仍在树里。只能证明"树里有",解锁逻辑不能拿它判断键盘已显示
+ #[test]
+ fn hidden_keypad_still_present_in_tree() {
+ let els = parse(LOCK, SCREEN);
+ let pad = keypad(&els).expect("隐藏的键盘仍能解析出 10 个键");
+ assert_eq!(pad[1], (103, 371));
+ assert_eq!(pad[0], (215, 695));
+ let field = els.iter().find(|e| e.kind == "SecureTextField").unwrap();
+ assert_eq!(parse_passcode_value(&field.value), Some((6, 0)));
+ }
+
#[test]
- fn passcode_field() {
- assert_eq!(parse_passcode_field("共6位数,已输入0位"), Some((6, 0)));
- assert_eq!(parse_passcode_field("共6位数,已输入5位"), Some((6, 5)));
- assert_eq!(parse_passcode_field("密码栏"), None);
+ fn passcode_value_variants() {
+ assert_eq!(parse_passcode_value("共6位数,已输入0位"), Some((6, 0)));
+ assert_eq!(parse_passcode_value("共6位数,已输入2位"), Some((6, 2)));
+ assert_eq!(parse_passcode_value("6-digit passcode, 3 entered"), Some((6, 3)));
+ assert_eq!(parse_passcode_value("共4位数"), None);
+ assert_eq!(parse_passcode_value(""), None);
}
}
diff --git a/crates/ictl-wda/src/http.rs b/crates/ictl-wda/src/http.rs
new file mode 100644
index 0000000..6d4e3ac
--- /dev/null
+++ b/crates/ictl-wda/src/http.rs
@@ -0,0 +1,149 @@
+//! 发往 WDA 的极简 HTTP/1.1。
+//!
+//! WDA 直接经 usbmuxd 连手机上的端口,本机不监听任何端口(docs/decisions.md D3)。
+//! idevice 自带的 `WdaClient` 不支持 `excluded_attributes`、appium settings、W3C actions 等,
+//! 所以这里自己发请求:每个请求一条新连接、`Connection: close`,读到 EOF 为止。
+
+use std::future::Future;
+use std::sync::Arc;
+use std::time::Duration;
+
+use idevice::provider::IdeviceProvider;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+/// 一次 HTTP 请求的传输。抽象出来便于单测里换成假的
+pub trait Transport: Send + Sync {
+ fn send(
+ &self,
+ method: &str,
+ path: &str,
+ body: Option<Vec<u8>>,
+ timeout: Duration,
+ ) -> impl Future<Output = std::io::Result<(u16, Vec<u8>)>> + Send;
+}
+
+/// 经 usbmuxd 直连手机上 WDA 端口
+#[derive(Clone)]
+pub struct DeviceTransport {
+ provider: Arc<dyn IdeviceProvider>,
+ port: u16,
+}
+
+impl DeviceTransport {
+ pub fn new(provider: Arc<dyn IdeviceProvider>, port: u16) -> Self {
+ Self { provider, port }
+ }
+}
+
+impl Transport for DeviceTransport {
+ async fn send(&self, method: &str, path: &str, body: Option<Vec<u8>>, timeout: Duration) -> std::io::Result<(u16, Vec<u8>)> {
+ let req = build_request(method, path, body.as_deref());
+ let fut = async {
+ let idevice = self.provider.connect(self.port).await.map_err(std::io::Error::other)?;
+ let mut sock = idevice.get_socket().ok_or_else(|| std::io::Error::other("连接没有套接字"))?;
+ sock.write_all(&req).await?;
+ sock.flush().await?;
+ let mut buf = Vec::new();
+ sock.read_to_end(&mut buf).await?;
+ parse_response(&buf)
+ };
+ tokio::time::timeout(timeout, fut)
+ .await
+ .map_err(|_| std::io::Error::new(std::io::ErrorKind::TimedOut, format!("请求超时({} 秒)", timeout.as_secs())))?
+ }
+}
+
+pub fn build_request(method: &str, path: &str, body: Option<&[u8]>) -> Vec<u8> {
+ let body = body.unwrap_or_default();
+ let mut req = format!(
+ "{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nAccept: application/json\r\n"
+ );
+ if method != "GET" || !body.is_empty() {
+ req.push_str(&format!("Content-Type: application/json\r\nContent-Length: {}\r\n", body.len()));
+ }
+ req.push_str("\r\n");
+ let mut out = req.into_bytes();
+ out.extend_from_slice(body);
+ out
+}
+
+/// 解析完整的 HTTP 响应:状态码和正文。支持 Content-Length、chunked 和读到 EOF 三种正文
+pub fn parse_response(raw: &[u8]) -> std::io::Result<(u16, Vec<u8>)> {
+ let bad = |m: &str| std::io::Error::new(std::io::ErrorKind::InvalidData, m.to_owned());
+ let split = raw.windows(4).position(|w| w == b"\r\n\r\n").ok_or_else(|| bad("HTTP 响应没有头部结束标记"))?;
+ let head = std::str::from_utf8(&raw[..split]).map_err(|_| bad("HTTP 头不是 UTF-8"))?;
+ let body = &raw[split + 4..];
+ let mut lines = head.split("\r\n");
+ let status: u16 = lines
+ .next()
+ .and_then(|l| l.split_whitespace().nth(1))
+ .and_then(|s| s.parse().ok())
+ .ok_or_else(|| bad("HTTP 状态行无效"))?;
+ let mut length = None;
+ let mut chunked = false;
+ for l in lines {
+ let Some((k, v)) = l.split_once(':') else { continue };
+ let (k, v) = (k.trim().to_ascii_lowercase(), v.trim());
+ if k == "content-length" {
+ length = v.parse::<usize>().ok();
+ } else if k == "transfer-encoding" && v.eq_ignore_ascii_case("chunked") {
+ chunked = true;
+ }
+ }
+ if chunked {
+ return Ok((status, dechunk(body).ok_or_else(|| bad("chunked 正文不完整"))?));
+ }
+ match length {
+ Some(n) if body.len() < n => Err(bad("正文比 Content-Length 短,连接提前断了")),
+ Some(n) => Ok((status, body[..n].to_vec())),
+ None => Ok((status, body.to_vec())),
+ }
+}
+
+fn dechunk(mut body: &[u8]) -> Option<Vec<u8>> {
+ let mut out = Vec::new();
+ loop {
+ let line_end = body.windows(2).position(|w| w == b"\r\n")?;
+ let size_str = std::str::from_utf8(&body[..line_end]).ok()?;
+ let size = usize::from_str_radix(size_str.split(';').next()?.trim(), 16).ok()?;
+ body = &body[line_end + 2..];
+ if size == 0 {
+ return Some(out);
+ }
+ out.extend_from_slice(body.get(..size)?);
+ body = body.get(size + 2..)?;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn request_has_length_only_with_body() {
+ let get = String::from_utf8(build_request("GET", "/status", None)).unwrap();
+ assert!(get.starts_with("GET /status HTTP/1.1\r\n"));
+ assert!(!get.contains("Content-Length"));
+ let post = String::from_utf8(build_request("POST", "/session", Some(b"{}"))).unwrap();
+ assert!(post.contains("Content-Length: 2\r\n") && post.ends_with("\r\n\r\n{}"));
+ }
+
+ #[test]
+ fn parses_content_length_body() {
+ let raw = b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nServer: x\r\n\r\nhelloEXTRA";
+ assert_eq!(parse_response(raw).unwrap(), (200, b"hello".to_vec()));
+ }
+
+ #[test]
+ fn parses_chunked_body() {
+ let raw = b"HTTP/1.1 404 Not Found\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n";
+ assert_eq!(parse_response(raw).unwrap(), (404, b"abcde".to_vec()));
+ }
+
+ #[test]
+ fn body_until_eof_and_truncated_body() {
+ assert_eq!(parse_response(b"HTTP/1.1 200 OK\r\n\r\n{}").unwrap(), (200, b"{}".to_vec()));
+ assert!(parse_response(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nshort").is_err());
+ assert!(parse_response(b"garbage").is_err());
+ }
+}
diff --git a/crates/ictl-wda/src/lib.rs b/crates/ictl-wda/src/lib.rs
index d61e4a0..0b87cba 100644
--- a/crates/ictl-wda/src/lib.rs
+++ b/crates/ictl-wda/src/lib.rs
@@ -1,13 +1,17 @@
-//! WebDriverAgent:启动、HTTP 客户端、元素树解析。
+//! WebDriverAgent:启动 runner、HTTP 客户端、元素树解析。
//!
-//! - 启动:idevice `XCUITestService::run_until_wda_ready`,就绪判定 = 本进程持有的 XCTest 会话存活 **且** `/status` ready
-//! (手机上残留的 WDA 在 runner 退出后还会响应几十秒)
-//! - 访问:经 idevice provider 直连设备 8100 端口,本机不监听任何端口
-//! - 元素树:`/source?format=xml&excluded_attributes=visible,...`(约 0.3 秒;完整树 7~8 秒),可见性按坐标自己判断
-
-use std::time::Duration;
+//! - 启动:[`runner::WdaRunner`],就绪判定 = 本进程持有的 runner 任务存活 **且** `/status` ready
+//! - 访问:[`http::DeviceTransport`] 经 usbmuxd 直连设备 8100 端口,本机不监听任何端口
+//! - 元素树:[`elements`],纯函数,可见性按坐标判断
+pub mod client;
pub mod elements;
+pub mod http;
+pub mod runner;
+
+pub use client::{IdleSettings, PointerStep, WdaClient, actions_body, swipe_steps, tap_steps};
+pub use elements::Element;
+pub use runner::WdaRunner;
#[derive(Debug, thiserror::Error)]
pub enum WdaError {
@@ -16,88 +20,28 @@ pub enum WdaError {
/// 手机重启后首次启用 UI 自动化,需要用户在手机上输入锁屏密码
#[error("WDA 卡在「Enable UI Automation」密码框,请在手机上输入锁屏密码")]
NeedsAutomationPin,
- #[error("WDA 返回错误 {kind}: {message}")]
+ #[error("手机上没有安装 WDA({0}),先运行 iphone-control sign")]
+ NotInstalled(String),
+ #[error("WDA 启动失败:{0}")]
+ StartFailed(String),
+ #[error("{kind}: {message}")]
Remote { kind: String, message: String },
}
pub type Result<T> = std::result::Result<T, WdaError>;
-/// 识别 XCTest 启动失败是否是"等待自动化密码"
+/// 识别 XCTest 启动失败是否是「等待自动化密码」(toolkit 实测的报错文字)
pub fn is_automation_pin_error(message: &str) -> bool {
message.contains("enabling automation mode")
}
-/// 一个运行中的 WDA runner
-pub struct WdaRunner {
- pub bundle_id: String,
-}
-
-impl WdaRunner {
- pub async fn start(tunnel: &mut ictl_device::Tunnel, bundle_id: &str, timeout: Duration) -> Result<Self> {
- let _ = (tunnel, bundle_id, timeout);
- todo!("TestConfig::from_installation_proxy + XCUITestService::run_until_wda_ready")
- }
-
- pub fn alive(&self) -> bool {
- todo!("WdaRunHandle 任务是否仍在运行")
- }
-
- pub async fn stop(self) -> Result<()> {
- todo!("WdaRunHandle::abort")
- }
-}
-
-/// W3C pointer 动作的一步
-#[derive(Debug, Clone)]
-pub enum PointerStep {
- Move { x: f64, y: f64, ms: u64 },
- Down,
- Up,
- Pause { ms: u64 },
-}
-
-/// appium settings 中与等待有关的两项。锁屏解锁期间要临时调小。
-#[derive(Debug, Clone, Copy)]
-pub struct IdleSettings {
- pub wait_for_idle_timeout: f64,
- pub animation_cool_off_timeout: f64,
-}
-
-/// WDA HTTP 客户端,会话失效时自动重建一次
-pub struct WdaClient {
- session: Option<String>,
-}
-
-impl WdaClient {
- pub fn new() -> Self {
- Self { session: None }
- }
-
- pub async fn ready(&mut self) -> Result<bool> { todo!("GET /status") }
- pub async fn screen_size(&mut self) -> Result<ictl_device::ScreenSize> { todo!("GET /wda/screen") }
- pub async fn locked(&mut self) -> Result<bool> { todo!("GET /wda/locked") }
- pub async fn active_app(&mut self) -> Result<String> { todo!("GET /wda/activeAppInfo") }
- pub async fn screenshot_png(&mut self) -> Result<Vec<u8>> { todo!("GET /screenshot") }
- pub async fn source_xml(&mut self) -> Result<String> { todo!("GET /source?format=xml&excluded_attributes=...") }
- pub async fn tap(&mut self, x: f64, y: f64) -> Result<()> { let _ = (x, y); todo!("POST /session/{{id}}/wda/tap") }
- pub async fn touch_and_hold(&mut self, x: f64, y: f64, seconds: f64) -> Result<()> { let _ = (x, y, seconds); todo!() }
- /// 一次 W3C actions 请求。注意:多次点击合并成一个请求会漏键,解锁时每位单独发
- pub async fn actions(&mut self, steps: &[PointerStep]) -> Result<()> { let _ = steps; todo!("POST /session/{{id}}/actions") }
- pub async fn keys(&mut self, text: &str) -> Result<()> { let _ = text; todo!("POST /session/{{id}}/wda/keys") }
- pub async fn press_button(&mut self, name: &str) -> Result<()> { let _ = name; todo!() }
- pub async fn lock(&mut self) -> Result<()> { todo!("POST /session/{{id}}/wda/lock") }
- /// 启动并等到前台后再停 1 秒(冷启动立即点击会被吞)
- pub async fn launch_app(&mut self, bundle_id: &str) -> Result<()> { let _ = bundle_id; todo!() }
- pub async fn terminate_app(&mut self, bundle_id: &str) -> Result<()> { let _ = bundle_id; todo!() }
- pub async fn open_url(&mut self, url: &str) -> Result<()> { let _ = url; todo!("POST /session/{{id}}/url") }
- pub async fn idle_settings(&mut self) -> Result<IdleSettings> { todo!("GET /session/{{id}}/appium/settings") }
- pub async fn set_idle_settings(&mut self, s: IdleSettings) -> Result<()> { let _ = s; todo!() }
- /// 锁屏密码栏的值(形如「共6位数,已输入2位」)
- pub async fn passcode_field_value(&mut self) -> Result<Option<String>> { todo!("查 XCUIElementTypeSecureTextField 的 value") }
-}
-
-impl Default for WdaClient {
- fn default() -> Self {
- Self::new()
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn automation_pin_error_detection() {
+ assert!(super::is_automation_pin_error(
+ "Timed out while enabling automation mode. (Error code: 1000, Domain: com.apple.dt.XCTest.XCTFuture)"
+ ));
+ assert!(!super::is_automation_pin_error("Failed to load the test bundle (Error code: 103)"));
}
}
diff --git a/crates/ictl-wda/src/runner.rs b/crates/ictl-wda/src/runner.rs
new file mode 100644
index 0000000..2440c5e
--- /dev/null
+++ b/crates/ictl-wda/src/runner.rs
@@ -0,0 +1,102 @@
+//! 启动手机上的 WebDriverAgent(XCTest runner)。
+//!
+//! 用 idevice 的 `XCUITestService` 跑测试计划;它自己经 usbmuxd 建 CoreDeviceProxy 隧道,和设备层的隧道互不影响。
+//! 就绪判定 = 本进程持有的 runner 任务还活着 **且** `/status` ready(手机上残留的 WDA 在 runner 退出后还会响应几十秒)。
+
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use idevice::{
+ IdeviceError, IdeviceService,
+ dvt::xctest::{TestConfig, XCUITestService, listener::XCUITestListener},
+ installation_proxy::InstallationProxyClient,
+ provider::IdeviceProvider,
+};
+use tokio::task::JoinHandle;
+
+use crate::http::DeviceTransport;
+use crate::{Result, WdaClient, WdaError, is_automation_pin_error};
+
+pub const WDA_PORT: u16 = 8100;
+
+/// 记下 XCTest 过程中报告的错误文字,用来识别「Enable UI Automation」密码框超时
+struct ErrorListener(Arc<Mutex<Vec<String>>>);
+
+impl ErrorListener {
+ fn push(&self, s: &str) {
+ self.0.lock().unwrap().push(s.to_owned());
+ }
+}
+
+impl XCUITestListener for ErrorListener {
+ async fn initialization_for_ui_testing_did_fail(&mut self, description: &str) -> std::result::Result<(), IdeviceError> {
+ self.push(description);
+ Ok(())
+ }
+
+ async fn did_fail_to_bootstrap(&mut self, description: &str) -> std::result::Result<(), IdeviceError> {
+ self.push(description);
+ Err(IdeviceError::UnexpectedResponse(format!("test runner failed to bootstrap: {description}")))
+ }
+}
+
+pub struct WdaRunner {
+ pub bundle_id: String,
+ task: JoinHandle<std::result::Result<(), IdeviceError>>,
+}
+
+impl WdaRunner {
+ /// 启动 runner 并等到 `/status` ready。`bundle_id` 是签名后带团队 ID 的 xctrunner Bundle ID。
+ pub async fn start(provider: Arc<dyn IdeviceProvider>, bundle_id: &str, timeout: Duration) -> Result<(Self, WdaClient<DeviceTransport>)> {
+ let mut ip = InstallationProxyClient::connect(&*provider).await.map_err(|e| WdaError::Unavailable(e.to_string()))?;
+ let cfg = TestConfig::from_installation_proxy(&mut ip, bundle_id, None).await.map_err(|e| match e {
+ IdeviceError::AppNotInstalled => WdaError::NotInstalled(bundle_id.to_owned()),
+ other => WdaError::StartFailed(other.to_string()),
+ })?;
+
+ let errors = Arc::new(Mutex::new(Vec::new()));
+ let task = {
+ let (provider, errors) = (provider.clone(), errors.clone());
+ tokio::spawn(async move { XCUITestService::new(provider).run(cfg, &mut ErrorListener(errors), None).await })
+ };
+ let runner = Self { bundle_id: bundle_id.to_owned(), task };
+ let client = WdaClient::new(DeviceTransport::new(provider, WDA_PORT));
+
+ let failure = |extra: Option<String>| {
+ let mut text: Vec<String> = errors.lock().unwrap().clone();
+ text.extend(extra);
+ let joined = text.join("; ");
+ if is_automation_pin_error(&joined) { WdaError::NeedsAutomationPin } else { WdaError::StartFailed(joined) }
+ };
+
+ let deadline = tokio::time::Instant::now() + timeout;
+ loop {
+ if runner.task.is_finished() {
+ let r = runner.task.await;
+ let msg = match r {
+ Ok(Ok(())) => "runner 提前结束".to_owned(),
+ Ok(Err(e)) => e.to_string(),
+ Err(e) => e.to_string(),
+ };
+ return Err(failure(Some(msg)));
+ }
+ if client.ready().await.unwrap_or(false) {
+ return Ok((runner, client));
+ }
+ if tokio::time::Instant::now() >= deadline {
+ runner.task.abort();
+ return Err(failure(Some(format!("{} 秒内 WDA 没有就绪", timeout.as_secs()))));
+ }
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ }
+ }
+
+ /// runner 任务是否还活着。死了就算手机上的 WDA 还在响应也不能用
+ pub fn alive(&self) -> bool {
+ !self.task.is_finished()
+ }
+
+ pub fn stop(self) {
+ self.task.abort();
+ }
+}
diff --git a/crates/ictl-wda/tests/fixtures/home.xml b/crates/ictl-wda/tests/fixtures/home.xml
new file mode 100644
index 0000000..6e70d46
--- /dev/null
+++ b/crates/ictl-wda/tests/fixtures/home.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<XCUIElementTypeApplication type="XCUIElementTypeApplication" name=" " label=" " x="0" y="0" width="430" height="932">
+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" x="0" y="0" width="430" height="932">
+ <XCUIElementTypeOther type="XCUIElementTypeOther" name="Home screen icons" x="0" y="0" width="430" height="932">
+ <XCUIElementTypeIcon type="XCUIElementTypeIcon" name="设置" label="设置" value="1个新项目" x="129" y="604" width="84" height="106">
+ <XCUIElementTypeOther type="XCUIElementTypeOther" name="设置" label="设置" x="129" y="604" width="84" height="106"/>
+ </XCUIElementTypeIcon>
+ <XCUIElementTypeIcon type="XCUIElementTypeIcon" name="时钟" label="时钟" x="228" y="402" width="73" height="95"/>
+ <XCUIElementTypeIcon type="XCUIElementTypeIcon" name="第二页的 App" label="第二页的 App" x="890" y="402" width="73" height="95"/>
+ <XCUIElementTypeButton type="XCUIElementTypeButton" name="com.apple.settings.displayAndBrightness" label="显示与亮度" x="20" y="650" width="390" height="53"/>
+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" label="被顶出屏幕一半" x="100" y="-20" width="100" height="40"/>
+ <XCUIElementTypeOther type="XCUIElementTypeOther" x="10" y="10" width="50" height="50"/>
+ <XCUIElementTypeOther type="XCUIElementTypeOther" label="零宽" x="10" y="10" width="0" height="50"/>
+ <XCUIElementTypeOther type="XCUIElementTypeOther" label="垂直滚动条, 1页" value="0%" x="412" y="113" width="30" height="736"/>
+ </XCUIElementTypeOther>
+ </XCUIElementTypeWindow>
+</XCUIElementTypeApplication>
diff --git a/crates/ictl-wda/tests/fixtures/lockscreen.xml b/crates/ictl-wda/tests/fixtures/lockscreen.xml
new file mode 100644
index 0000000..f732d4a
--- /dev/null
+++ b/crates/ictl-wda/tests/fixtures/lockscreen.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- 锁屏界面(自造样本):密码键盘已收起,但 Key 元素仍留在树里 -->
+<XCUIElementTypeApplication type="XCUIElementTypeApplication" name=" " label=" " x="0" y="0" width="430" height="932">
+ <XCUIElementTypeWindow type="XCUIElementTypeWindow" name="SBCoverSheetWindow" x="0" y="0" width="430" height="932">
+ <XCUIElementTypeOther type="XCUIElementTypeOther" label="向上轻扫以解锁" x="128" y="11" width="174" height="37"/>
+ <XCUIElementTypeOther type="XCUIElementTypeOther" name="passcode-view" x="0" y="0" width="430" height="932">
+ <XCUIElementTypeStaticText type="XCUIElementTypeStaticText" label="输入密码" x="173" y="175" width="84" height="24"/>
+ <XCUIElementTypeSecureTextField type="XCUIElementTypeSecureTextField" label="密码栏" value="共6位数,已输入0位" x="0" y="220" width="430" height="14"/>
+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="1" x="47" y="317" width="112" height="108"/>
+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="2" x="159" y="317" width="112" height="108"/>
+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="3" x="271" y="317" width="112" height="108"/>
+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="4" x="47" y="425" width="112" height="108"/>
+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="5" x="159" y="425" width="112" height="108"/>
+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="6" x="271" y="425" width="112" height="108"/>
+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="7" x="47" y="533" width="112" height="108"/>
+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="8" x="159" y="533" width="112" height="108"/>
+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="9" x="271" y="533" width="112" height="108"/>
+ <XCUIElementTypeKey type="XCUIElementTypeKey" label="0" x="159" y="641" width="112" height="108"/>
+ </XCUIElementTypeOther>
+ </XCUIElementTypeWindow>
+</XCUIElementTypeApplication>