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