1use std::{
5 sync::Arc,
6 time::{Duration, Instant},
7};
8
9use idevice::{
10 ReadWrite, RsdService,
11 core_device::{
12 AppListEntry, AppServiceClient, ImageFormat, PasteboardServiceClient,
13 ScreenCaptureServiceClient,
14 },
15};
16
17use crate::{
18 ax::{
19 dump::Dump,
20 tree::{BuildOptions, Screen},
21 },
22 config::Config,
23 device::{
24 ax::{ANSWER_AT_LEAST, AxSub},
25 conn::{self, Tunnel},
26 input::InputSession,
27 },
28 i18n::t,
29 reply::{Fail, Res},
30};
31
32const APP_SERVICE: &str = "com.apple.coredevice.appservice";
33
34#[derive(Debug, Clone, Copy)]
36pub enum Gesture {
37 Tap { x: u16, y: u16, hold: Duration },
38 DoubleTap { x: u16, y: u16 },
39 Drag { from: (u16, u16), to: (u16, u16), duration: Duration, motion: crate::device::input::Motion },
40 Button { page: u64, usage: u64, hold: Duration },
41}
42
43#[derive(Debug, Clone, Copy, PartialEq)]
45pub enum Fresh {
46 Force,
48 MaxAge(Duration),
50}
51
52pub const REUSE: Duration = Duration::from_millis(1500);
55
56pub fn reuse() -> Duration {
58 std::env::var("IPH_REUSE_MS")
59 .ok()
60 .and_then(|v| v.parse().ok())
61 .map(Duration::from_millis)
62 .unwrap_or(REUSE)
63}
64const ASK_AGAIN: Duration = Duration::from_millis(6500);
70const READ_TIMEOUT: Duration = Duration::from_secs(14);
71const AX_RESTART_GAP: Duration = Duration::from_secs(120);
73const REOPEN_GAP: Duration = Duration::from_millis(2000);
76const SECOND_PASS_WAIT: Duration = Duration::from_millis(2500);
77
78#[derive(Debug, PartialEq, Clone, Copy)]
81pub(crate) enum AxStall {
82 Silent,
84 EmptyOnly,
89}
90
91pub(crate) fn ax_stall(empty: u64, unparsed: u64) -> Option<AxStall> {
94 match (empty, unparsed) {
95 (0, 0) => Some(AxStall::Silent),
96 (_, 0) => Some(AxStall::EmptyOnly),
97 _ => None,
98 }
99}
100
101pub struct Session {
102 pub udid: String,
103 pub config: Config,
104 pub tunnel: Option<Tunnel>,
105 pub ax: Option<AxSub>,
106 pub input: Option<InputSession>,
107 pub(crate) input_used: Instant,
108 input_closed_at: Option<Instant>,
110 pub(crate) input_suspect: bool,
115 abandoned: Vec<(InputSession, Option<Tunnel>)>,
119 apps: Option<Vec<AppListEntry>>,
120 pub(crate) screen_size: Option<(f64, f64)>,
122 stale_before: Option<Instant>,
125 pub connects: u64,
127 pub ax_restarts: u64,
130 ax_restarted_at: Option<Instant>,
131 ax_restart_unhelpful: bool,
137 system_in_front: bool,
143 pub dnd: crate::dnd::State,
145}
146
147fn plain_path(s: &str) -> String {
149 let s = s.strip_prefix("file://").unwrap_or(s);
150 let raw = s.as_bytes();
151 let mut bytes = Vec::with_capacity(raw.len());
152 let mut i = 0;
153 while i < raw.len() {
154 if raw[i] == b'%' && i + 2 < raw.len() {
155 let hex = std::str::from_utf8(&raw[i + 1..i + 3]).unwrap_or("");
156 if let Ok(v) = u8::from_str_radix(hex, 16) {
157 bytes.push(v);
158 i += 3;
159 continue;
160 }
161 }
162 bytes.push(raw[i]);
163 i += 1;
164 }
165 let mut path = String::from_utf8_lossy(&bytes).into_owned();
166 while path.len() > 1 && path.ends_with('/') {
167 path.pop();
168 }
169 path.strip_prefix("/private").map(String::from).unwrap_or(path)
171}
172
173fn is_transport_error(msg: &str) -> bool {
174 let m = msg.to_lowercase();
175 [
176 "adapter closed",
177 "broken pipe",
178 "channel recv timeout",
179 "connection reset",
180 "not connected",
181 "timed out",
182 "closed",
183 "unreachable",
184 "eof",
185 ]
186 .iter()
187 .any(|needle| m.contains(needle))
188}
189
190async fn bounded<T, E: std::fmt::Debug>(
192 what: &str,
193 secs: u64,
194 fut: impl std::future::Future<Output = Result<T, E>>,
195) -> Result<T, String> {
196 match tokio::time::timeout(Duration::from_secs(secs), fut).await {
197 Ok(Ok(v)) => Ok(v),
198 Ok(Err(e)) => Err(format!("{what}: {e:?}")),
199 Err(_) => Err(format!("{what}: no answer within {secs} s")),
200 }
201}
202
203impl Session {
204 pub fn new(udid: String, config: Config) -> Self {
205 let dnd = crate::dnd::State::load(&udid);
206 Self {
207 udid,
208 config,
209 tunnel: None,
210 ax: None,
211 input: None,
212 input_used: Instant::now(),
213 input_closed_at: None,
214 input_suspect: false,
215 abandoned: Vec::new(),
216 apps: None,
217 screen_size: None,
218 stale_before: None,
219 connects: 0,
220 ax_restarts: 0,
221 ax_restarted_at: None,
222 ax_restart_unhelpful: false,
223 system_in_front: false,
224 dnd,
225 }
226 }
227
228 pub(crate) fn reading_age(&self) -> Option<Duration> {
231 let arrived = self.ax.as_ref()?.latest_arrival()?;
232 if self.stale_before.is_some_and(|limit| arrived < limit) {
233 return None;
234 }
235 Some(arrived.elapsed())
236 }
237
238 pub fn invalidate_readings(&mut self) {
239 self.stale_before = Some(Instant::now());
240 }
241
242 pub async fn service_port(&mut self, name: &str) -> Res<(crate::tcp::handle::AdapterHandle, u16)> {
244 let tunnel = self.ensure_tunnel().await?;
245 let port = tunnel
246 .rsd
247 .services
248 .get(name)
249 .map(|s| s.port)
250 .ok_or_else(|| Fail::not_sent("service_unavailable", format!("{name} is not on offer")))?;
251 Ok((tunnel.adapter.clone(), port))
252 }
253
254 pub fn drop_input(&mut self) {
256 if let Some(input) = self.input.take() {
257 self.input_closed_at = Some(Instant::now());
258 self.abandoned.push((input, None));
259 }
260 }
261
262 pub fn reset(&mut self) {
264 let tunnel = self.tunnel.take();
265 if let Some(input) = self.input.take() {
266 self.input_closed_at = Some(Instant::now());
267 self.abandoned.push((input, tunnel));
269 }
270 self.ax = None;
271 }
272
273 pub async fn sweep(&mut self) {
277 for (input, tunnel) in std::mem::take(&mut self.abandoned) {
278 input.abandon().await;
279 drop(tunnel);
280 }
281 }
282
283 pub fn connection(&self) -> Option<&str> {
284 self.tunnel.as_ref().map(|t| t.connection.as_str())
285 }
286
287 pub(crate) fn refresh_connection(&mut self) {
290 if self.tunnel.as_ref().is_some_and(Tunnel::is_closed) {
291 crate::events::record("connection", "closed", 0, serde_json::json!({ "udid": self.udid, "reason": "heartbeat ended" }));
292 self.reset();
293 }
294 }
295
296 pub async fn ensure_tunnel(&mut self) -> Res<&mut Tunnel> {
297 self.refresh_connection();
298 if self.tunnel.is_none() {
299 self.sweep().await;
301 let tunnel = conn::open_tunnel(&self.udid).await.map_err(|e| {
302 Fail::not_sent("tunnel_failed", format!("{e:#}")).hint(t(
303 "폰이 같은 Wi-Fi에 있거나 USB로 연결되어 있고 잠금이 풀려 있는지 확인하세요. `iph doctor`로 점검할 수 있습니다.",
304 "Check that the phone is on the same Wi-Fi or plugged in, and unlocked. Run `iph doctor`.",
305 ))
306 })?;
307 self.connects += 1;
308 self.tunnel = Some(tunnel);
309 }
310 Ok(self.tunnel.as_mut().unwrap())
311 }
312
313 async fn ensure_ax(&mut self) -> Res<()> {
314 self.refresh_connection();
315 if self.ax.as_ref().is_some_and(|a| a.is_closed()) {
316 self.reset();
318 }
319 if self.ax.is_none() {
320 let mut last = None;
321 for attempt in 0..2 {
322 let tunnel = self.ensure_tunnel().await?;
323 let mut adapter = tunnel.adapter.clone();
324 match bounded("accessibility service", 12, AxSub::open(&mut adapter, &tunnel.rsd)).await {
325 Ok(ax) => {
326 self.ax = Some(ax);
327 return Ok(());
328 }
329 Err(e) => {
330 last = Some(e);
331 if attempt == 0 {
332 self.reset();
333 }
334 }
335 }
336 }
337 return Err(Fail::not_sent(
338 "ax_unavailable",
339 last.unwrap_or_else(|| "accessibility service unavailable".into()),
340 )
341 .hint(t(
342 "개발자 모드가 켜져 있고 개발자 디스크 이미지가 연결되어 있어야 합니다. `iph doctor`로 확인하세요.",
343 "Developer Mode must be on and the developer disk image mounted. Run `iph doctor`.",
344 )));
345 }
346 Ok(())
347 }
348
349 async fn restart_ax_daemon(&mut self) -> Result<u32, String> {
357 let mut svc = self.app_service().await.map_err(|f| f.message)?;
358 let processes = bounded("list processes", 10, svc.list_processes()).await?;
359 let pid = processes
360 .iter()
361 .find(|p| {
362 p.executable_url
363 .as_ref()
364 .is_some_and(|u| plain_path(&u.relative).ends_with("/axauditd"))
365 })
366 .map(|p| p.pid)
367 .ok_or("axauditd is not among the phone's processes")?;
368 const SIGABRT: u32 = 6;
374 const SIGKILL: u32 = 9;
375 bounded("signal", 10, svc.send_signal(pid, SIGABRT)).await?;
376 tokio::time::sleep(Duration::from_millis(1500)).await;
377 let _ = bounded("signal", 5, svc.send_signal(pid, SIGKILL)).await;
378 Ok(pid)
379 }
380
381 pub async fn dump(&mut self, fresh: Fresh, full: bool) -> Res<(u64, Arc<Dump>)> {
384 let mut started = Instant::now();
385 let mut restarted = false;
386 let mut reconnects = 0;
387 let mut second_pass_retries = 0;
388 let mut fresh = fresh;
389 let mut base: Option<(Instant, u64, u64)> = None;
393 loop {
394 self.ensure_ax().await?;
395 let ax = self.ax.as_mut().unwrap();
396 if base.is_none_or(|(opened, _, _)| opened != ax.opened) {
397 base = Some((ax.opened, ax.empty_count(), ax.unparsed_count()));
398 }
399 let usable = match (self.stale_before, ax.latest_arrival()) {
400 (Some(limit), Some(arrived)) => arrived >= limit,
401 _ => true,
402 };
403 let cached = match fresh {
404 Fresh::MaxAge(max) if usable => ax
405 .latest()
406 .filter(|(_, _, age)| *age <= max)
407 .map(|(seq, dump, _)| (seq, dump)),
408 _ => None,
409 };
410 let got = match cached {
411 Some(c) => Some(c),
412 None => {
413 let mut asked_at = if ax.latest().is_none() && ax.opened.elapsed() < ASK_AGAIN {
416 Some(ax.opened)
417 } else {
418 ax.request().ok()
419 };
420 let mut got = None;
421 while let Some(at) = asked_at {
422 if let Some(x) = ax.wait_arrived(at + ANSWER_AT_LEAST, ASK_AGAIN).await {
426 crate::device::ax::trace(|| {
427 let ms = ax
428 .latest_arrival()
429 .map(|t| t.saturating_duration_since(at).as_millis())
430 .unwrap_or(0);
431 format!("answer accepted {ms} ms after the request")
432 });
433 got = Some(x);
434 break;
435 }
436 if ax.is_closed() || started.elapsed() >= READ_TIMEOUT {
437 break;
438 }
439 asked_at = ax.request().ok();
440 }
441 got
442 }
443 };
444 let Some((seq, dump)) = got else {
445 if self.ax.as_ref().is_some_and(|a| a.is_closed()) && reconnects < 2 {
446 reconnects += 1;
447 self.reset();
448 continue;
449 }
450 let (empty, unparsed) = match (self.ax.as_ref(), base) {
451 (Some(a), Some((_, e0, u0))) => {
452 (a.empty_count().saturating_sub(e0), a.unparsed_count().saturating_sub(u0))
453 }
454 _ => (0, 0),
455 };
456 let up = self.ax.as_ref().is_some_and(|a| !a.is_closed());
457 let stall = if up { ax_stall(empty, unparsed) } else { None };
458 let locked = match stall {
461 Some(AxStall::EmptyOnly) => match conn::route(&self.udid).await {
462 Ok(r) => conn::passcode_locked(&*r.provider).await,
463 Err(_) => None,
464 },
465 _ => None,
466 };
467 let lately = self.ax_restarted_at.is_some_and(|at| at.elapsed() < AX_RESTART_GAP);
468 let mut why_not = "";
469 if restarted {
470 self.ax_restart_unhelpful = true;
473 }
474 if stall.is_some() && locked != Some(true) {
475 if restarted {
476 why_not = "it was already ended once during this reading";
477 } else if self.system_in_front {
478 why_not = "the home screen or a system panel was in front";
479 } else if self.ax_restart_unhelpful {
480 why_not = "ending it last time did not help";
481 } else if lately {
482 why_not = "it was ended less than 2 minutes ago";
483 } else if !self.config.daemon.restart_accessibility {
484 why_not = "[daemon] restart_accessibility = false";
485 }
486 }
487 if stall.is_some() && locked != Some(true) && why_not.is_empty() {
488 restarted = true;
489 let waited = started.elapsed().as_secs();
490 let how = match stall {
491 Some(AxStall::EmptyOnly) => format!("sent only empty answers ({empty})"),
492 _ => "gave no answer".to_string(),
493 };
494 match self.restart_ax_daemon().await {
495 Ok(pid) => {
496 eprintln!(
497 "[{}] the phone's accessibility daemon {how} for {waited} s; ended it (pid {pid}) so the phone starts a new one",
498 crate::clock::now_utc()
499 );
500 self.ax_restarted_at = Some(Instant::now());
501 self.ax_restarts += 1;
502 self.ax = None;
503 tokio::time::sleep(Duration::from_millis(500)).await;
504 started = Instant::now();
505 continue;
506 }
507 Err(e) => {
508 eprintln!(
509 "[{}] the phone's accessibility daemon {how} for {waited} s and could not be restarted: {e}",
510 crate::clock::now_utc()
511 );
512 why_not = "ending it failed";
513 self.ax_restart_unhelpful = true;
514 }
515 }
516 }
517 let fail = Fail::not_sent(
518 "ax_timeout",
519 format!(
520 "no accessibility tree within {} ms ({empty} empty, {unparsed} not understood)",
521 started.elapsed().as_millis(),
522 ),
523 )
524 .with("phone_locked", locked.map(serde_json::Value::Bool).unwrap_or(serde_json::Value::Null));
525 return Err(if locked == Some(true) {
526 fail.hint(t("폰이 잠겨 있습니다. 잠금을 풀어 주세요.", "The phone is locked. Unlock it."))
527 } else if stall.is_some() && self.system_in_front {
528 fail.with("ax_restart_skipped", why_not).hint(t(
529 "폰의 화면 읽기 서비스가 응답하지 않습니다. 홈 화면이나 제어 센터 같은 시스템 화면이 앞에 있습니다. 화면 기록 중에는 제어 센터가 읽히지 않습니다. `iph button home`으로 닫거나 `iph launch`로 앱을 띄운 뒤 다시 읽으세요. 이 두 명령은 화면을 못 읽어도 나갑니다.",
530 "The phone's screen-reading service is not answering, and the home screen or a system panel such as Control Center is in front. Control Center cannot be read while the screen is being recorded. Close it with `iph button home` or bring an app up with `iph launch`, then read again; both go out without a reading.",
531 ))
532 } else if stall.is_some() && self.ax_restart_unhelpful {
533 fail.with("ax_restart_skipped", why_not).hint(t(
534 "폰의 화면 읽기 서비스를 다시 띄워도 응답이 없습니다. 폰을 잠갔다가 다시 풀어 주세요.",
535 "The phone's screen-reading service did not answer after a restart either. Lock the phone and unlock it again.",
536 ))
537 } else if stall.is_some() {
538 fail.with("ax_restart_skipped", why_not).hint(t(
539 "폰의 화면 읽기 서비스(axauditd)가 응답하지 않습니다. 폰이 잠긴 것은 아닙니다. 잠시 뒤 다시 시도하세요. iph가 2분에 한 번까지 그 서비스를 다시 띄웁니다.",
540 "The phone's screen-reading service (axauditd) is not answering. The phone is not locked. Try again shortly; iph restarts that service at most every 2 minutes.",
541 ))
542 } else {
543 fail.hint(t(
544 "화면 읽기 응답을 이해하지 못했습니다. `iph read --raw`로 확인하세요.",
545 "The screen-reading answers were not understood. Look with `iph read --raw`.",
546 ))
547 });
548 };
549 if !full {
550 return Ok((seq, dump));
551 }
552 let ax = self.ax.as_mut().unwrap();
553 if let Some(merged) = ax.full(seq) {
554 return Ok((seq, merged));
555 }
556 match ax.wait_full(seq, SECOND_PASS_WAIT).await {
557 Some(merged) => return Ok((seq, merged)),
558 None => {
559 if ax.seq() > seq && started.elapsed() < READ_TIMEOUT {
561 fresh = Fresh::MaxAge(Duration::from_secs(5));
562 continue;
563 }
564 if second_pass_retries < 1 && started.elapsed() < READ_TIMEOUT {
568 second_pass_retries += 1;
569 fresh = Fresh::Force;
570 continue;
571 }
572 return Ok((seq, dump));
573 }
574 }
575 }
576 }
577
578 pub async fn screen(&mut self, fresh: Fresh, full: bool, opts: BuildOptions) -> Res<(u64, Screen)> {
579 let mut fresh = fresh;
580 let mut last = None;
581 for _ in 0..3 {
585 let (seq, dump) = Box::pin(self.dump(fresh, full)).await?;
586 let screen = Screen::build(&dump, opts);
587 self.ax_restart_unhelpful = false;
588 self.system_in_front = crate::dnd::system_ui(&screen);
589 if screen.width > 0.0 && screen.height > 0.0 {
590 self.screen_size = Some((screen.width, screen.height));
591 return Ok((seq, screen));
592 }
593 last = Some((seq, screen));
594 fresh = Fresh::Force;
595 }
596 let (seq, mut screen) = last.unwrap();
597 if let Some((w, h)) = self.screen_size {
598 screen.width = w;
599 screen.height = h;
600 }
601 Ok((seq, screen))
602 }
603
604 pub async fn ensure_input(&mut self) -> Res<&mut InputSession> {
607 self.refresh_connection();
610 let stale = self
611 .input
612 .as_ref()
613 .is_some_and(|i| i.media_idle_ms().is_none_or(|ms| ms > 2500));
614 if (stale || self.input_suspect)
615 && let Some(old) = self.input.take() {
616 old.close().await;
617 self.input_closed_at = Some(Instant::now());
618 }
619 self.input_suspect = false;
620 if self.input.is_none() {
621 self.sweep().await;
622 if let Some(closed) = self.input_closed_at {
628 let gap = std::env::var("IPH_REOPEN_GAP_MS")
629 .ok()
630 .and_then(|v| v.parse().ok())
631 .map(Duration::from_millis)
632 .unwrap_or(REOPEN_GAP);
633 let since = closed.elapsed();
634 if since < gap {
635 tokio::time::sleep(gap - since).await;
636 }
637 }
638 let mut last = String::new();
639 for attempt in 0..2 {
640 let video = self.config.daemon.screen_video;
641 let tunnel = self.ensure_tunnel().await?;
642 let mut adapter = tunnel.adapter.clone();
643 match bounded("input session", 20, InputSession::open(&mut adapter, &mut tunnel.rsd, video)).await {
644 Ok(s) => {
645 self.input = Some(s);
646 break;
647 }
648 Err(e) => {
649 last = e;
650 if attempt == 0 && is_transport_error(&last) {
651 self.reset();
652 } else {
653 break;
654 }
655 }
656 }
657 }
658 if self.input.is_none() {
659 return Err(Fail::not_sent("input_unavailable", last).hint(t(
660 "터치 입력에는 개발자 디스크 이미지의 display service가 필요합니다. `iph doctor`로 확인하세요.",
661 "Touch input needs the display service from the developer disk image. Run `iph doctor`.",
662 )));
663 }
664 }
665 self.input_used = Instant::now();
666 Ok(self.input.as_mut().unwrap())
667 }
668
669 pub async fn send_gesture(&mut self, gesture: Gesture) -> Res<()> {
676 for attempt in 0..2 {
677 let input = self.ensure_input().await?;
678 let before = input.reports_sent();
679 let sent = match gesture {
680 Gesture::Tap { x, y, hold } => input.tap(x, y, hold).await,
681 Gesture::DoubleTap { x, y } => input.double_tap(x, y).await,
682 Gesture::Drag { from, to, duration, motion } => input.drag(from, to, duration, motion).await,
683 Gesture::Button { page, usage, hold } => input.button(page, usage, hold).await,
684 };
685 let Err(e) = sent else {
686 return Ok(());
687 };
688 let untouched = input.reports_sent() == before;
689 self.drop_input();
690 if attempt == 0 && untouched {
691 crate::device::ax::trace(|| format!("gesture not sent ({e:#}); trying once on a new session"));
692 eprintln!("[{}] input connection was closed ({e:#}); sending again on a new session", crate::clock::now_utc());
693 continue;
694 }
695 return Err(Fail::unknown("input_failed", format!("{e:#}")).hint(t(
696 "입력이 나갔을 수 있습니다. 다시 보내지 말고 `iph read`로 화면을 확인하세요.",
697 "The input may have gone out. Do not resend; check the screen with `iph read`.",
698 )));
699 }
700 unreachable!("the loop returns on its second pass")
701 }
702
703 pub async fn close_idle_input(&mut self) {
706 let idle = Duration::from_secs(self.config.daemon.input_idle_secs);
707 if self.input.is_some() && self.input_used.elapsed() > idle
708 && let Some(s) = self.input.take() {
709 s.close().await;
710 self.input_closed_at = Some(Instant::now());
711 }
712 }
713
714 pub async fn close_input(&mut self) {
716 if let Some(s) = self.input.take() {
717 s.close().await;
718 self.input_closed_at = Some(Instant::now());
719 }
720 }
721
722 pub async fn close_input_if_unheld(&mut self) {
727 if self.config.daemon.input_idle_secs == 0
728 && let Some(s) = self.input.take() {
729 s.close().await;
730 self.input_closed_at = Some(Instant::now());
731 }
732 }
733
734 pub async fn shutdown(&mut self) {
735 if let Some(s) = self.input.take() {
736 s.close().await;
737 }
738 self.sweep().await;
739 self.reset();
740 }
741
742 async fn rsd_client<T>(&mut self) -> Res<T>
743 where
744 T: RsdService,
745 {
746 let mut last = String::new();
747 for attempt in 0..2 {
748 let tunnel = self.ensure_tunnel().await?;
749 let mut adapter = tunnel.adapter.clone();
750 match bounded("connect", 12, T::connect_rsd(&mut adapter, &mut tunnel.rsd)).await {
751 Ok(c) => return Ok(c),
752 Err(e) => {
753 last = e;
754 if attempt == 0 && is_transport_error(&last) {
755 self.reset();
756 } else {
757 break;
758 }
759 }
760 }
761 }
762 Err(Fail::not_sent(
763 "service_unavailable",
764 format!("{}: {last}", T::rsd_service_name()),
765 ))
766 }
767
768 pub async fn app_service(&mut self) -> Res<AppServiceClient<Box<dyn ReadWrite>>> {
769 self.rsd_client().await
770 }
771
772 pub async fn pasteboard(&mut self) -> Res<PasteboardServiceClient<Box<dyn ReadWrite>>> {
773 self.rsd_client().await
774 }
775
776 pub async fn list_apps(&mut self, refresh: bool) -> Res<Vec<AppListEntry>> {
777 if refresh || self.apps.is_none() {
778 let streams = self.ensure_tunnel().await?.rsd.services.get(APP_SERVICE).is_some_and(|svc| {
781 svc.features
782 .as_ref()
783 .is_some_and(|f| f.iter().any(|x| x == "com.apple.coredevice.feature.streamapplist"))
784 });
785 let mut svc = self.app_service().await?;
786 let apps: Vec<AppListEntry> = if streams {
787 use futures_util::TryStreamExt;
788 bounded(
789 "stream app list",
790 30,
791 svc.stream_apps(true, true, false, false, true).try_collect(),
792 )
793 .await
794 } else {
795 bounded("list apps", 30, svc.list_apps(true, true, false, false, true)).await
796 }
797 .map_err(|e| Fail::not_sent("apps_failed", e))?;
798 self.apps = Some(apps);
799 }
800 Ok(self.apps.clone().unwrap_or_default())
801 }
802
803 pub async fn screenshot_png(&mut self) -> Res<Vec<u8>> {
804 let mut svc: ScreenCaptureServiceClient<Box<dyn ReadWrite>> = self.rsd_client().await?;
805 bounded("screenshot", 20, svc.take_screenshot(None, ImageFormat::Png))
806 .await
807 .map_err(|e| Fail::not_sent("screenshot_failed", e))
808 }
809}
810
811#[cfg(test)]
812mod tests {
813 use super::{AxStall, ax_stall, plain_path};
814
815 #[test]
816 fn paths_compare_across_spellings() {
817 assert_eq!(
818 plain_path("file:///private/var/containers/Bundle/Application/AB/My%20App.app/"),
819 "/var/containers/Bundle/Application/AB/My App.app"
820 );
821 assert_eq!(plain_path("/Applications/Preferences.app"), "/Applications/Preferences.app");
822 assert_eq!(plain_path("file:///Applications/%EB%A9%94%EB%AA%A8.app/x"), "/Applications/메모.app/x");
823 }
824
825 #[test]
826 fn a_daemon_that_sends_only_empty_answers_is_restarted_too() {
827 assert_eq!(ax_stall(0, 0), Some(AxStall::Silent));
830 assert_eq!(ax_stall(3, 0), Some(AxStall::EmptyOnly));
831 assert_eq!(ax_stall(0, 1), None);
833 assert_eq!(ax_stall(2, 1), None);
834 }
835}