Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ What changed in each release, one line per change. Versions follow [Semantic Ver
### New

- `iphone_tap` takes `count` (1–10): the taps go in one gesture, about 0.1 s apart, so a double tap or several quick taps work; separate calls are about 0.5 s apart. An older daemon ignores it and taps once.
- `iphone_batch` takes `one_gesture`: a batch of coordinate taps runs as one gesture, about twice as fast for pressing keys on a keyboard.

### Improvements

Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
### 新功能

- `iphone_tap` 加 `count`(1~10):在一个手势里连点,每下间隔约 0.1 秒,双击、短时间内连点几下的入口都能点到;分开调用每下约隔 0.5 秒。旧版本守护进程不认这个参数,只点一下。
- `iphone_batch` 新增 `one_gesture`:全是坐标点击的一批步骤放进一个手势里点完,在键盘上逐个按键快一倍左右。

### 改进

Expand Down
2 changes: 2 additions & 0 deletions crates/ictl-daemon/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1214,6 +1214,7 @@ impl Daemon {
text
}),
Request::Tap { x, y, count } => self.tap(g, x, y, count, view).await,
Request::TapSequence { points } => self.tap_sequence(g, &points).await,
Request::TapElement { text, index, max_age_ms } => {
self.tap_element(g, &text, index, Duration::from_millis(max_age_ms)).await.map(|(t, missed)| {
outcome.tapped_nothing = missed;
Expand Down Expand Up @@ -1337,6 +1338,7 @@ fn lane(req: &Request) -> Lane {
| Request::Screenshot { .. }
| Request::ListElements { .. }
| Request::Tap { .. }
| Request::TapSequence { .. }
| Request::TapElement { .. }
| Request::LongPress { .. }
| Request::Swipe { .. }
Expand Down
1 change: 1 addition & 0 deletions crates/ictl-daemon/src/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ pub fn scope_check(req: &Request) -> Option<Check> {
Request::LaunchApp { app } => Some(Check::Launch(app.clone())),
Request::OpenUrl { url } => Some(Check::Url(url.clone())),
Request::Tap { .. }
| Request::TapSequence { .. }
| Request::TapElement { .. }
| Request::LongPress { .. }
| Request::Swipe { .. }
Expand Down
49 changes: 49 additions & 0 deletions crates/ictl-daemon/src/tools/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,55 @@ impl Daemon {
Ok(ictl_l10n::trf!("已点击 {pos}{times}(经 HID)", "Tapped {pos}{times} (via HID)"))
}

/// 依次点几个点(`iphone_batch` 的 `one_gesture`):WDA 发一个手势([`WdaClient::tap_sequence`]),HID 在同一个会话里连发。
/// 和 [`Self::tap`] 一样只有连不上 WDA 才退到 HID
pub(crate) async fn tap_sequence(&self, g: &mut Inner, points: &[(f64, f64)]) -> crate::error::Result<String> {
if points.is_empty() || points.len() > crate::protocol::MAX_SEQUENCE_POINTS {
return Err(ictl_l10n::trf!(
"一个手势要点 1 到 {} 个点",
"a gesture takes 1 to {} points",
crate::protocol::MAX_SEQUENCE_POINTS
)
.into());
}
self.prepare_coordinates(g, None, true).await?;
let n = points.len();
let list: Vec<String> = points.iter().map(|(x, y)| format!("({},{})", fmt_g(*x), fmt_g(*y))).collect();
let list = list.join(" ");
if let Some(w) = self.wda(g) {
match w.tap_sequence(points).await {
Ok(()) => {
return Ok(ictl_l10n::trf!(
"在一个手势里依次点了 {n} 个点:{list}",
"Tapped {n} points in one gesture: {list}"
));
}
Err(WdaError::Unavailable(_)) => {}
Err(e) => return Err(e.into()),
}
}
let native = self.native(g);
let rot = self.hid_touch_rotation(g).await?;
let pts = points.to_vec();
self.hid_do(g, move |h| {
Box::pin(async move {
h.rotation = rot;
for (i, (x, y)) in pts.into_iter().enumerate() {
if i > 0 {
tokio::time::sleep(Duration::from_millis(ictl_wda::SEQUENCE_GAP_MS)).await;
}
h.tap(x, y).await?;
}
Ok(())
})
})
.await?;
if native {
return Ok(ictl_l10n::trf!("依次点了 {n} 个点:{list}", "Tapped {n} points: {list}"));
}
Ok(ictl_l10n::trf!("依次点了 {n} 个点(经 HID):{list}", "Tapped {n} points (via HID): {list}"))
}

/// Follow the viewer pointer with one HID report per call. The first event prepares the device.
/// Later events reuse the open HID session and reject a change in display orientation.
pub(crate) async fn touch(
Expand Down
63 changes: 60 additions & 3 deletions crates/ictl-mcp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -557,7 +557,9 @@ then 在全部做完(或停下)后返回一次界面。", "Run several steps in
"steps": {"type": "array", "items": {"type": "object"},
"description": ictl_l10n::tr!("要执行的步骤,1 到 20 个,例如 [{\"tool\": \"iphone_tap_element\", \"text\": \"通用\"}]", "the steps to run, 1 to 20, e.g. [{\"tool\": \"iphone_tap_element\", \"text\": \"General\"}]")},
"reuse_elements": {"type": "boolean", "default": false,
"description": ictl_l10n::tr!("这批操作不改变界面布局时(例如在同一个键盘上连按)设为 true:按名字点击复用最近读到的元素树,每步省 0.3~0.8 秒。会跳转页面的不要用,否则可能点到旧位置", "Set to true when the steps don't change the layout (e.g. pressing keys on the same keypad): tapping by text reuses the most recent element tree, saving 0.3-0.8 s per step. Don't use it for steps that navigate, or it may tap where things used to be")}
"description": ictl_l10n::tr!("这批操作不改变界面布局时(例如在同一个键盘上连按)设为 true:按名字点击复用最近读到的元素树,每步省 0.3~0.8 秒。会跳转页面的不要用,否则可能点到旧位置", "Set to true when the steps don't change the layout (e.g. pressing keys on the same keypad): tapping by text reuses the most recent element tree, saving 0.3-0.8 s per step. Don't use it for steps that navigate, or it may tap where things used to be")},
"one_gesture": {"type": "boolean", "default": false,
"description": ictl_l10n::tr!("步骤全是 iphone_tap 时可设为 true:这些点在一个手势里依次点完(每个点一根手指,间隔约 0.04 秒),中间不等界面空闲。用于在同一个键盘上连按,例如输入框不接受 iphone_type_text 时逐个点数字键:7 个键约 1.9 秒,分开点约 3.6 秒。点的过程中不看界面,中途跳了页面后面的点也照样点下去;点完截图或读元素核对", "Only when every step is iphone_tap: set to true to tap the points one after another in a single gesture (one finger per point, about 0.04 s apart) without waiting for the interface in between. For pressing keys on the same keyboard, e.g. digit keys one by one when a field doesn't take iphone_type_text: 7 keys in about 1.9 s instead of about 3.6 s. Nothing is checked while it taps, so if a tap navigates, the remaining points still land; check the result with a screenshot or elements afterwards")}
})),
&["steps"],
),
Expand Down Expand Up @@ -780,13 +782,14 @@ pub fn batch_steps(args: &Map<String, Value>) -> Result<Vec<Step>, String> {
.and_then(Value::as_array)
.ok_or(ictl_l10n::tr!("缺少 steps(数组)", "missing steps (array)"))?;
let reuse = Args(args).b_or("reuse_elements", false)?;
let one_gesture = Args(args).b_or("one_gesture", false)?;
if steps.is_empty() || steps.len() > BATCH_MAX_STEPS {
return Err(ictl_l10n::trf!(
"steps 要有 1 到 {BATCH_MAX_STEPS} 步",
"steps must have 1 to {BATCH_MAX_STEPS} steps"
));
}
steps
let steps: Vec<Step> = steps
.iter()
.enumerate()
.map(|(i, s)| {
Expand Down Expand Up @@ -823,7 +826,32 @@ pub fn batch_steps(args: &Map<String, Value>) -> Result<Vec<Step>, String> {
};
Ok(Step::Request { tool: tool.to_owned(), req })
})
.collect()
.collect::<Result<_, String>>()?;
if !one_gesture {
return Ok(steps);
}
// 全是坐标点击才能并成一个手势:别的步骤(按名字点、等待、输入)都要在点之间看界面或花时间
let points = steps
.iter()
.map(|s| match s {
Step::Request { req: Request::Tap { x, y, count }, .. } => Some((*x, *y, *count)),
_ => None,
})
.collect::<Option<Vec<_>>>()
.ok_or(ictl_l10n::tr!(
"one_gesture 只能用于步骤全是 iphone_tap(按坐标点)的批量",
"one_gesture only works when every step is iphone_tap (tap by coordinates)"
))?;
// 一个手势里每个点只点一下;要连点用 iphone_tap 的 count,不悄悄当成点一下
if points.iter().any(|p| p.2 != 1) {
return Err(ictl_l10n::tr!(
"one_gesture 里的 iphone_tap 不能带 count;要在一个点连点,单独调用 iphone_tap 并给 count",
"iphone_tap steps under one_gesture can't take count; to tap one point several times, call iphone_tap on its own with count"
)
.into());
}
let points = points.into_iter().map(|(x, y, _)| (x, y)).collect();
Ok(vec![Step::Request { tool: "iphone_tap".into(), req: Request::TapSequence { points } }])
}

/// tap_element 的结果是不是「没点到」(没找到、index 超出匹配个数、或整个被别的东西盖住)
Expand All @@ -837,6 +865,7 @@ pub fn tap_missed(text: &str, outcome: Option<protocol::Outcome>) -> bool {
pub fn wants_alert_check(req: &Request) -> bool {
match req {
Request::Tap { .. }
| Request::TapSequence { .. }
| Request::TapElement { .. }
| Request::LongPress { .. }
| Request::Swipe { .. }
Expand Down Expand Up @@ -1221,6 +1250,34 @@ mod tests {
with_lang(Lang::Zh, || assert!(has_cjk(instructions())));
}

/// one_gesture 把全是坐标点击的批量并成一个 TapSequence;混了别的步骤就报错,一步都不执行
#[test]
fn one_gesture_turns_taps_into_one_sequence() {
let steps = batch_steps(&args(json!({"one_gesture": true, "steps": [
{"tool": "iphone_tap", "x": 60, "y": 548},
{"tool": "iphone_tap", "x": 23, "y": 548.5}
]})));
let req = Request::TapSequence { points: vec![(60.0, 548.0), (23.0, 548.5)] };
assert_eq!(steps, Ok(vec![Step::Request { tool: "iphone_tap".into(), req }]));
for other in [
json!({"tool": "iphone_tap_element", "text": "1"}),
json!({"tool": "wait", "seconds": 0.1}),
json!({"tool": "iphone_type_text", "text": "1"}),
] {
let steps = json!({"one_gesture": true, "steps": [{"tool": "iphone_tap", "x": 1, "y": 2}, other]});
assert!(batch_steps(&args(steps)).is_err());
}
// without it a batch of taps stays step by step
let steps = batch_steps(&args(json!({"steps": [{"tool": "iphone_tap", "x": 1, "y": 2}]}))).unwrap();
assert_eq!(
steps,
vec![Step::Request { tool: "iphone_tap".into(), req: Request::Tap { x: 1.0, y: 2.0, count: 1 } }]
);
// a step's count can't go into one gesture: an error, not one tap
let steps = json!({"one_gesture": true, "steps": [{"tool": "iphone_tap", "x": 1, "y": 2, "count": 2}]});
assert!(batch_steps(&args(steps)).is_err());
}

/// iphone_tap 不带 count 是点一下;count 要是 1 到 MAX_TAP_COUNT 的整数,给错了报错、不点,不悄悄改成 1
#[test]
fn tap_count_defaults_to_one_and_rejects_out_of_range() {
Expand Down
11 changes: 11 additions & 0 deletions crates/ictl-protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ fn one() -> u32 {
fn is_one(n: &u32) -> bool {
*n == 1
}
/// [`Request::TapSequence`] 一个手势最多点几个点(同 `iphone_batch` 最多几步)
pub const MAX_SEQUENCE_POINTS: usize = 20;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
Expand Down Expand Up @@ -95,6 +97,10 @@ pub enum Request {
#[serde(default = "one", skip_serializing_if = "is_one")]
count: u32,
},
/// 依次点几个点,一个手势(`iphone_batch` 的 `one_gesture`):同一个键盘上连按。旧版本守护进程不认识,报错,不会只点一部分
TapSequence {
points: Vec<(f64, f64)>,
},
TapElement {
text: String,
index: usize,
Expand Down Expand Up @@ -431,6 +437,7 @@ impl Request {
match self {
Self::Tap { .. }
| Self::TapElement { .. }
| Self::TapSequence { .. }
| Self::LongPress { .. }
| Self::Swipe { .. }
| Self::TypeText { .. }
Expand Down Expand Up @@ -931,6 +938,10 @@ mod tests {
let s = serde_json::to_string(&r).unwrap();
assert!(s.starts_with(r#"{"op":"swipe""#), "{s}");
assert_eq!(serde_json::from_str::<Request>(&s).unwrap(), r);
let r = Request::TapSequence { points: vec![(60.0, 548.0), (23.0, 548.0)] };
let s = serde_json::to_string(&r).unwrap();
assert_eq!(s, r#"{"op":"tap_sequence","points":[[60.0,548.0],[23.0,548.0]]}"#);
assert_eq!(serde_json::from_str::<Request>(&s).unwrap(), r);
let e: Response = serde_json::from_str(r#"{"kind":"error","message":"x"}"#).unwrap();
assert_eq!(e, Response::error("x"));
}
Expand Down
64 changes: 63 additions & 1 deletion crates/ictl-wda/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ impl StallReason {
const SCREEN_RECHECK: Duration = Duration::from_secs(60);
/// 普通点击按下的时长(毫秒)。太短可能不被识别成点击;解锁按键另有自己的时长
const TAP_PRESS_MS: u64 = 50;
/// 一个手势里依次点几个点时,前一个抬起到后一个按下停多久(毫秒)。真机上 20、40、60 都没有漏键、多键
pub const SEQUENCE_GAP_MS: u64 = 40;
/// 连点时两下之间停多久(毫秒):双击要在约 250 毫秒内,「800 毫秒内点 5 下」要每下不到 160 毫秒
pub const MULTI_TAP_GAP_MS: u64 = 100;

Expand Down Expand Up @@ -88,6 +90,32 @@ pub fn swipe_steps(from: (f64, f64), to: (f64, f64), ms: u64) -> Vec<PointerStep
]
}

/// 一个 actions 请求里依次点几个点,每个点一根手指:第 k 根手指先空等前面 k 个点按完(每个点占 5 个节拍:移动、按下、
/// 按住 `press_ms`、抬起、停 `gap_ms`),再移过去按下抬起。W3C 按节拍对齐各手指,所以这些点一个接一个、不重叠。
/// 不用一根手指移来移去:iPhone 17(iOS 26.5.2)上一根手指在一个手势里移到别的点再按,每个点都被识别两次
/// (数字键盘上点 7 个键输出 14 位)
pub fn tap_sequence_body(points: &[(f64, f64)], press_ms: u64, gap_ms: u64) -> Value {
let pause = |ms: u64| json!({"type": "pause", "duration": ms});
let fingers: Vec<Value> = points
.iter()
.enumerate()
.map(|(k, &(x, y))| {
let mut actions = Vec::with_capacity(5 * k + 4);
for _ in 0..k {
actions.extend([pause(0), pause(0), pause(press_ms), pause(0), pause(gap_ms)]);
}
actions.extend([
json!({"type": "pointerMove", "duration": 0, "x": x, "y": y}),
json!({"type": "pointerDown", "button": 0}),
pause(press_ms),
json!({"type": "pointerUp", "button": 0}),
]);
json!({"type": "pointer", "id": format!("finger{}", k + 1), "parameters": {"pointerType": "touch"}, "actions": actions})
})
.collect();
json!({"actions": fingers})
}

/// `POST /session/{id}/actions` 的请求体
pub fn actions_body(steps: &[PointerStep]) -> Value {
let actions: Vec<Value> = steps
Expand Down Expand Up @@ -795,6 +823,14 @@ impl<T: Transport> WdaClient<T> {
self.quick_gesture(&tap_steps(x, y, TAP_PRESS_MS), IdleSettings::NO_COOL_OFF).await
}

/// 依次点几个点,一个手势([`tap_sequence_body`]):同一个键盘、键盘上连按时用。分开点每下都要等界面空闲,
/// 数字键盘上点 7 个键约 3.6 秒,一个手势约 1.9 秒。点的过程中界面变了(跳了页面)后面的点也照样点下去,
/// 所以只给点的时候布局不变的一串点用
pub async fn tap_sequence(&mut self, points: &[(f64, f64)]) -> Result<()> {
let body = tap_sequence_body(points, TAP_PRESS_MS, SEQUENCE_GAP_MS);
self.quick_actions(body, IdleSettings::NO_COOL_OFF).await
}

/// 同一点连点 `count` 下(双击、「短时间内连点 N 下」的隐藏入口),一个 actions 手势,每下之间停
/// [`MULTI_TAP_GAP_MS`]。分开点每下都要等界面空闲(约 0.6 秒),`iphone_batch` 连点 5 下约 2.9 秒,赶不上这类入口的时间窗
pub async fn multi_tap(&mut self, x: f64, y: f64, count: u32) -> Result<()> {
Expand Down Expand Up @@ -872,9 +908,13 @@ impl<T: Transport> WdaClient<T> {

/// 发一个手势,期间把等待设置临时换成 `during`(见 [`Self::tap`]),做完恢复
async fn quick_gesture(&mut self, steps: &[PointerStep], during: IdleSettings) -> Result<()> {
self.quick_actions(actions_body(steps), during).await
}

async fn quick_actions(&mut self, body: Value, during: IdleSettings) -> Result<()> {
let baseline = self.baseline().await?;
self.set_idle_settings(during).await?;
let r = self.actions(steps).await;
let r = self.post("/actions", body).await.map(drop);
if let Err(e) = self.set_idle_settings(baseline).await {
tracing::warn!(
"{}",
Expand Down Expand Up @@ -1260,6 +1300,28 @@ mod tests {
assert_eq!(steps.iter().filter(|s| s["type"] == "pointerDown").count(), 1);
}

/// 依次点几个点:每个点一根手指,第 k 根先空等前面的点按完;各手指的节拍数对得上,按下抬起一个接一个、不重叠
#[test]
fn a_sequence_is_one_finger_per_point_in_turn() {
let body = tap_sequence_body(&[(10.0, 20.0), (30.0, 40.0), (50.0, 60.0)], 50, 40);
let fingers = body["actions"].as_array().unwrap();
assert_eq!(fingers.len(), 3);
for (k, f) in fingers.iter().enumerate() {
let a = f["actions"].as_array().unwrap();
assert_eq!(a.len(), 5 * k + 4, "finger {k}");
// pauses only until its own turn, then move, down, hold, up at its point
assert!(a[..5 * k].iter().all(|s| s["type"] == "pause"));
assert_eq!(a[5 * k]["type"], "pointerMove");
assert_eq!(a[5 * k]["x"].as_f64(), Some(10.0 + 20.0 * k as f64));
assert_eq!(a[5 * k + 1]["type"], "pointerDown");
assert_eq!(a[5 * k + 3]["type"], "pointerUp");
assert_ne!(fingers[0]["id"], fingers[k.max(1)]["id"]);
}
// finger k waits 5 ticks per earlier point: move, down, hold, up, gap
assert_eq!(fingers[1]["actions"][2]["duration"], 50);
assert_eq!(fingers[1]["actions"][4]["duration"], 40);
}

/// 连点是一个 actions 请求:一根手指只移动一次,在同一点按下抬起 N 次,两下之间停 MULTI_TAP_GAP_MS;
/// 5 下在 0.8 秒内点完
#[tokio::test]
Expand Down
5 changes: 4 additions & 1 deletion crates/ictl-wda/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ pub mod elements;
pub mod http;
pub mod runner;

pub use client::{IdleSettings, Launch, MULTI_TAP_GAP_MS, WdaClient, multi_tap_steps, swipe_steps, tap_steps};
pub use client::{
IdleSettings, Launch, MULTI_TAP_GAP_MS, SEQUENCE_GAP_MS, WdaClient, multi_tap_steps, swipe_steps,
tap_sequence_body, tap_steps,
};
pub use runner::WdaRunner;

#[derive(Debug, thiserror::Error)]
Expand Down
Loading
Loading