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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ What changed in each release, one line per change. Versions follow [Semantic Ver

## [Unreleased]

### 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.

### Improvements

- An action that had to unlock the phone first says so, and how long it took (#135).
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@

## [Unreleased]

### 新功能

- `iphone_tap` 加 `count`(1~10):在一个手势里连点,每下间隔约 0.1 秒,双击、短时间内连点几下的入口都能点到;分开调用每下约隔 0.5 秒。旧版本守护进程不认这个参数,只点一下。

### 改进

- 操作前先自动解锁了的话,结果里会说明,并写明用了多久(#135)。
Expand Down
4 changes: 2 additions & 2 deletions apps/iphone-control/src/viewer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1333,7 +1333,7 @@ fn action(name: &str, b: &Value) -> Option<Request> {
let num = |k: &str| b.get(k).and_then(Value::as_f64).filter(|v| v.is_finite());
let text = |k: &str| b.get(k).and_then(Value::as_str).map(str::to_owned);
Some(match name {
"tap" => Request::Tap { x: num("x")?, y: num("y")? },
"tap" => Request::Tap { x: num("x")?, y: num("y")?, count: 1 },
"long_press" => Request::LongPress { x: num("x")?, y: num("y")?, seconds: num("seconds")?.clamp(0.3, 5.0) },
"swipe" => Request::Swipe {
from: (num("x1")?, num("y1")?),
Expand Down Expand Up @@ -2010,7 +2010,7 @@ mod tests {

#[test]
fn page_actions_map_to_daemon_requests() {
assert_eq!(action("tap", &json!({"x": 10.0, "y": 20.5})), Some(Request::Tap { x: 10.0, y: 20.5 }));
assert_eq!(action("tap", &json!({"x": 10.0, "y": 20.5})), Some(Request::Tap { x: 10.0, y: 20.5, count: 1 }));
assert_eq!(
action("swipe", &json!({"x1": 1, "y1": 2, "x2": 3, "y2": 4, "seconds": 9})),
Some(Request::Swipe { from: (1.0, 2.0), to: (3.0, 4.0), seconds: 3.0 })
Expand Down
4 changes: 2 additions & 2 deletions crates/ictl-daemon/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1213,7 +1213,7 @@ impl Daemon {
data = Some(crate::protocol::Data::Elements { elements });
text
}),
Request::Tap { x, y } => self.tap(g, x, y, view).await,
Request::Tap { x, y, count } => self.tap(g, x, y, count, view).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 @@ -1691,7 +1691,7 @@ pub(crate) mod tests {
async fn coordinate_from_a_previous_view_is_rejected_before_dispatch() {
let (d, dir) = test_daemon("previous-view");
let ctx = CallCtx { expect_view: Some("old-view".into()), ..Default::default() };
let r = d.handle(Request::Tap { x: 3.0, y: 4.0 }, Instant::now(), ctx).await;
let r = d.handle(Request::Tap { x: 3.0, y: 4.0, count: 1 }, Instant::now(), ctx).await;
assert!(matches!(r, Response::Error { message, retry_as_gesture: false } if message.contains("画面")));
std::fs::remove_dir_all(dir).unwrap();
}
Expand Down
4 changes: 2 additions & 2 deletions crates/ictl-daemon/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ mod tests {
assert_eq!(events.next().await.unwrap().event, "task");
assert!(protocol::open_task(&socket, "又一个", "test", &[]).await.is_err(), "one at a time");

let tap = Request::Tap { x: 1.0, y: 2.0 };
let tap = Request::Tap { x: 1.0, y: 2.0, count: 1 };
let r = protocol::call(&socket, &tap, None).await.unwrap();
assert!(matches!(&r, Response::Error { message, .. } if message.contains(&opened.id)), "{r:?}");
// the task's own request gets past the task (and then finds no phone in this test)
Expand Down Expand Up @@ -420,7 +420,7 @@ mod tests {
br#"{"op":"tap","x":1.0,"y":2.0,"cancel_on_close":true,"expect_udid":"U1","expect_view":"V1","lang":"en"}"#,
)
.unwrap();
assert_eq!(req, protocol::Request::Tap { x: 1.0, y: 2.0 });
assert_eq!(req, protocol::Request::Tap { x: 1.0, y: 2.0, count: 1 });
assert!(cancel);
assert_eq!(expect.expect_udid.as_deref(), Some("U1"));
assert_eq!(expect.expect_view.as_deref(), Some("V1"));
Expand Down
4 changes: 2 additions & 2 deletions crates/ictl-daemon/src/tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1187,7 +1187,7 @@ fn gesture(tool: &str, args: &Value, result: &str) -> Option<Value> {
/// [`gesture`] for a request that no tool call announced
fn request_gesture(req: &Request) -> Option<Value> {
match req {
Request::Tap { x, y } => Some(json!({"kind": "tap", "x": x, "y": y})),
Request::Tap { x, y, .. } => Some(json!({"kind": "tap", "x": x, "y": y})),
Request::LongPress { x, y, .. } => Some(json!({"kind": "long_press", "x": x, "y": y})),
Request::Swipe { from, to, .. } => {
Some(json!({"kind": "swipe", "x": from.0, "y": from.1, "x2": to.0, "y2": to.1}))
Expand Down Expand Up @@ -1219,7 +1219,7 @@ mod tests {
}

fn tap() -> Request {
Request::Tap { x: 1.0, y: 2.0 }
Request::Tap { x: 1.0, y: 2.0, count: 1 }
}

async fn admit(ts: &Tasks, req: &Request, token: Option<&str>) -> Result<(Admission, bool), Response> {
Expand Down
44 changes: 34 additions & 10 deletions crates/ictl-daemon/src/tools/input.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Acting at a point or on an element: taps, touches, long presses, swipes, typing

use super::*;
use crate::protocol::MAX_TAP_COUNT;

impl Daemon {
/// A stale pointer must neither unlock nor act on a new display. Unlock can itself
Expand Down Expand Up @@ -37,34 +38,57 @@ impl Daemon {
Ok(rotation)
}

pub(crate) async fn tap(&self, g: &mut Inner, x: f64, y: f64, view: Option<&str>) -> crate::error::Result<String> {
/// 点击 `count` 下(1 = 普通点击)。连点时 WDA 发一个手势([`WdaClient::multi_tap`]),HID 在同一个会话里连发
pub(crate) async fn tap(
&self,
g: &mut Inner,
x: f64,
y: f64,
count: u32,
view: Option<&str>,
) -> crate::error::Result<String> {
if !(1..=MAX_TAP_COUNT).contains(&count) {
return Err(ictl_l10n::trf!(
"count 要是 1 到 {MAX_TAP_COUNT} 的整数",
"count must be a whole number from 1 to {MAX_TAP_COUNT}"
)
.into());
}
self.prepare_coordinates(g, view, true).await?;
let pos = format!("({},{})", fmt_g(x), fmt_g(y));
let times = if count > 1 { ictl_l10n::trf!(",连点 {count} 下", ", {count} times") } else { String::new() };
if let Some(w) = self.wda(g) {
// 只有连不上才退到 HID;超时说明请求已发出,再用 HID 做一遍可能点两次
match w.tap(x, y).await {
Ok(()) => return Ok(ictl_l10n::trf!("已点击 {pos}", "Tapped {pos}")),
let r = if count > 1 { w.multi_tap(x, y, count).await } else { w.tap(x, y).await };
match r {
Ok(()) => return Ok(ictl_l10n::trf!("已点击 {pos}{times}", "Tapped {pos}{times}")),
Err(WdaError::Unavailable(_)) if view.is_none() => {}
Err(e) => return Err(e.into()),
}
}
// natively HID is the way, not a fallback: the page's view was checked above as through WDA
if self.native(g) {
Box::pin(self.native_tap(g, x, y)).await?;
return Ok(ictl_l10n::trf!("已点击 {pos}", "Tapped {pos}"));
}
if view.is_some() {
let native = self.native(g);
if !native && view.is_some() {
return Err(wda_down(&g.state, g.info.as_ref()).into());
}
let rot = self.hid_touch_rotation(g).await?;
self.hid_do(g, move |h| {
Box::pin(async move {
h.rotation = rot;
h.tap(x, y).await
for i in 0..count {
if i > 0 {
tokio::time::sleep(Duration::from_millis(ictl_wda::MULTI_TAP_GAP_MS)).await;
}
h.tap(x, y).await?;
}
Ok(())
})
})
.await?;
Ok(ictl_l10n::trf!("已点击 {pos}(经 HID)", "Tapped {pos} (via HID)"))
if native {
return Ok(ictl_l10n::trf!("已点击 {pos}{times}", "Tapped {pos}{times}"));
}
Ok(ictl_l10n::trf!("已点击 {pos}{times}(经 HID)", "Tapped {pos}{times} (via HID)"))
}

/// Follow the viewer pointer with one HID report per call. The first event prepares the device.
Expand Down
2 changes: 1 addition & 1 deletion crates/ictl-daemon/src/tools/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ mod tests {
g.info = Some(ictl_device::DeviceInfo { product_version: "26.7.3".into(), ..Default::default() });
g.state = crate::machine::DeviceState::WdaStarting { last_error: None };
let down = |e: &str| e.contains("没有 HID 后备路线") || e.contains("no HID fallback");
let tap = d.tap(&mut g, 20., 50., None).await.unwrap_err().to_string();
let tap = d.tap(&mut g, 20., 50., 1, None).await.unwrap_err().to_string();
assert!(down(&tap), "{tap}");
let swipe = d.swipe(&mut g, (20., 50.), (20., 300.), 0.3, None, false).await.unwrap_err().to_string();
assert!(down(&swipe), "{swipe}");
Expand Down
43 changes: 38 additions & 5 deletions crates/ictl-mcp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use std::path::PathBuf;
use std::time::Duration;

use ictl_protocol::{self as protocol, Request, Response};
use ictl_protocol::{self as protocol, MAX_TAP_COUNT, Request, Response};
use rmcp::{
ErrorData, RoleServer, ServerHandler, ServiceExt,
model::{
Expand Down Expand Up @@ -329,12 +329,20 @@ WDA 不可用时会说明哪些功能受影响(读元素、按名字点击、启
ictl_l10n::tr!("点击屏幕上的一个坐标(单位是点,与 iphone_screenshot 全屏图的像素一致,左上角为原点)。\n\n\
何时用:目标没有文字(图标、图片)、在游戏或地图里,或 iphone_list_elements 里找不到它时。\
带文字的按钮、列表项优先用 iphone_tap_element,界面布局变了也点得准。按住用 iphone_long_press,滚动用 iphone_swipe。\n\n\
行为:单指按下约 0.05 秒后抬起,点一次。不检查坐标上是什么,点之前先截图确认位置。\
WDA 不可用时改用 CoreDevice HID(iOS 27 起;结果里注明「经 HID」)。", "Tap a point on the screen (in points, the same as the pixels of a full-screen iphone_screenshot, origin at the top left).\n\nWhen to use: the target has no text (icon, image), is in a game or map, or can't be found with iphone_list_elements. For buttons and list items with text prefer iphone_tap_element, which keeps working when the layout changes. Use iphone_long_press to hold and iphone_swipe to scroll.\n\nBehavior: one finger down for about 0.05 s, then up; a single tap. It doesn't check what is at that point, so look at a screenshot first. If WDA is unavailable it uses CoreDevice HID instead (iOS 27+; the result says “via HID”)."),
行为:单指按下约 0.05 秒后抬起,点一次(count 大于 1 时在同一点连点)。不检查坐标上是什么,点之前先截图确认位置。\
WDA 不可用时改用 CoreDevice HID(iOS 27 起;结果里注明「经 HID」)。", "Tap a point on the screen (in points, the same as the pixels of a full-screen iphone_screenshot, origin at the top left).\n\nWhen to use: the target has no text (icon, image), is in a game or map, or can't be found with iphone_list_elements. For buttons and list items with text prefer iphone_tap_element, which keeps working when the layout changes. Use iphone_long_press to hold and iphone_swipe to scroll.\n\nBehavior: one finger down for about 0.05 s, then up; a single tap (several at the same point with count above 1). It doesn't check what is at that point, so look at a screenshot first. If WDA is unavailable it uses CoreDevice HID instead (iOS 27+; the result says “via HID”)."),
ictl_l10n::tr!("已点击 (120,300)", "Tapped (120,300)"),
true,
),
schema(with_then(json!({"x": num(ictl_l10n::tr!("x(点)", "x (points)")), "y": num(ictl_l10n::tr!("y(点)", "y (points)"))})), &["x", "y"]),
schema(
with_then(json!({
"x": num(ictl_l10n::tr!("x(点)", "x (points)")),
"y": num(ictl_l10n::tr!("y(点)", "y (points)")),
"count": {"type": "integer", "default": 1, "minimum": 1, "maximum": MAX_TAP_COUNT,
"description": ictl_l10n::tr!("在这一点连点几下,一个手势里点完(每下间隔约 0.1 秒):2 是双击;也用于要在短时间内连点几下的入口。分开调用赶不上这类时间窗", "how many times to tap this point, all in one gesture (about 0.1 s apart): 2 is a double tap; also for entries that need several taps in a short time, which separate calls are too slow for")}
})),
&["x", "y"],
),
acting(ictl_l10n::tr!("点击坐标", "Tap point"), true, false),
),
t(
Expand Down Expand Up @@ -604,6 +612,16 @@ impl Args<'_> {
}),
}
}
/// 连点次数:不给是 1,给了要是 1 到 [`MAX_TAP_COUNT`] 的整数
fn count(&self, k: &str) -> Result<u32, String> {
match self.u_or(k, 1)? {
n @ 1.. if n <= MAX_TAP_COUNT as usize => Ok(n as u32),
_ => Err(ictl_l10n::trf!(
"参数 {k} 要是 1 到 {MAX_TAP_COUNT} 的整数",
"parameter {k} must be a whole number from 1 to {MAX_TAP_COUNT}"
)),
}
}
fn b_or(&self, k: &str, d: bool) -> Result<bool, String> {
match self.get(k) {
None => Ok(d),
Expand Down Expand Up @@ -641,7 +659,7 @@ pub fn to_request(name: &str, args: &Map<String, Value>) -> Result<Request, Stri
max_age_ms: 0,
keep_locked: false,
},
"iphone_tap" => Request::Tap { x: a.f("x")?, y: a.f("y")? },
"iphone_tap" => Request::Tap { x: a.f("x")?, y: a.f("y")?, count: a.count("count")? },
"iphone_tap_element" => Request::TapElement { text: a.s("text")?, index: a.u_or("index", 0)?, max_age_ms: 0 },
"iphone_long_press" => Request::LongPress { x: a.f("x")?, y: a.f("y")?, seconds: a.f_or("seconds", 1.0)? },
"iphone_swipe" => Request::Swipe {
Expand Down Expand Up @@ -1203,6 +1221,21 @@ mod tests {
with_lang(Lang::Zh, || assert!(has_cjk(instructions())));
}

/// iphone_tap 不带 count 是点一下;count 要是 1 到 MAX_TAP_COUNT 的整数,给错了报错、不点,不悄悄改成 1
#[test]
fn tap_count_defaults_to_one_and_rejects_out_of_range() {
let tap = |v: Value| to_request("iphone_tap", &args(v));
assert_eq!(tap(json!({"x": 1, "y": 2})), Ok(Request::Tap { x: 1.0, y: 2.0, count: 1 }));
assert_eq!(tap(json!({"x": 1, "y": 2, "count": 5})), Ok(Request::Tap { x: 1.0, y: 2.0, count: 5 }));
for bad in [json!(0), json!(11), json!(2.5), json!(-1), json!("two")] {
assert!(tap(json!({"x": 1, "y": 2, "count": bad})).is_err(), "{bad}");
}
// a batch step takes it too
let steps = batch_steps(&args(json!({"steps": [{"tool": "iphone_tap", "x": 1, "y": 2, "count": 2}]})));
let req = Request::Tap { x: 1.0, y: 2.0, count: 2 };
assert_eq!(steps, Ok(vec![Step::Request { tool: "iphone_tap".into(), req }]));
}

#[test]
fn alert_check_after_actions_but_not_buttons_or_reads() {
assert!(wants_alert_check(&Request::Swipe { from: (0.0, 0.0), to: (1.0, 1.0), seconds: 0.3 }));
Expand Down
24 changes: 24 additions & 0 deletions crates/ictl-protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ pub fn default_socket() -> PathBuf {
}
}

/// [`Request::Tap`] 一次最多连点几下
pub const MAX_TAP_COUNT: u32 = 10;

fn one() -> u32 {
1
}

fn is_one(n: &u32) -> bool {
*n == 1
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TouchPhase {
Expand Down Expand Up @@ -80,6 +91,9 @@ pub enum Request {
Tap {
x: f64,
y: f64,
/// 在这一点连点几下(一个手势),1 = 普通点击。旧版本客户端不带,按 1;为 1 时不写进请求,旧版本守护进程照常认
#[serde(default = "one", skip_serializing_if = "is_one")]
count: u32,
},
TapElement {
text: String,
Expand Down Expand Up @@ -872,6 +886,16 @@ pub async fn task_list(socket: &std::path::Path) -> Result<Vec<TaskInfo>, String
mod tests {
use super::*;

/// 不带 count 的点击(旧版本客户端)按 1 下;count 为 1 时不写进请求,旧版本守护进程收到的和以前一样
#[test]
fn a_tap_without_count_is_one_tap_on_the_wire() {
let old: Request = serde_json::from_str(r#"{"op":"tap","x":1.0,"y":2.0}"#).unwrap();
assert_eq!(old, Request::Tap { x: 1.0, y: 2.0, count: 1 });
assert_eq!(serde_json::to_string(&old).unwrap(), r#"{"op":"tap","x":1.0,"y":2.0}"#);
let five = Request::Tap { x: 1.0, y: 2.0, count: 5 };
assert_eq!(serde_json::to_string(&five).unwrap(), r#"{"op":"tap","x":1.0,"y":2.0,"count":5}"#);
}

/// A daemon that is restarting (it left the marker just now) is waited for; one that isn't running is reported
/// at once
#[tokio::test]
Expand Down
Loading
Loading