1use std::time::{Duration, Instant};
15
16use serde::{Deserialize, Serialize};
17use unicode_normalization::UnicodeNormalization;
18
19use crate::{
20 actions::{AFTER_DRAG, AFTER_TAP},
21 ax::tree::{BuildOptions, Rect, Screen},
22 config::DndConfig,
23 device::{
24 ax::trace,
25 input::{Motion, normalize},
26 session::{Fresh, Gesture, Session},
27 },
28 fields,
29 i18n::t,
30 paths,
31 reply::{Fail, Res},
32 clock::now_utc,
33};
34
35const CONTROL_LABELS: [&str; 2] = ["집중 모드", "Focus"];
37const MODE_LABELS: [&str; 2] = ["방해금지 모드", "Do Not Disturb"];
39const HOLD: Duration = Duration::from_millis(800);
42const AFTER_HOME: Duration = Duration::from_millis(500);
43const BETWEEN_HOME: Duration = Duration::from_millis(600);
45const WAIT: Duration = Duration::from_secs(5);
47fn nfc(s: &str) -> String {
48 s.nfc().collect()
49}
50
51fn named(label: &str, name: &str) -> bool {
53 label == name || label.strip_prefix(name).is_some_and(|rest| rest.starts_with(", "))
54}
55
56#[derive(Debug, Clone)]
58pub struct Labels {
59 pub control: Vec<String>,
60 pub mode: Vec<String>,
61}
62
63impl Labels {
64 pub fn new(config: &DndConfig) -> Self {
65 let mut control: Vec<String> = CONTROL_LABELS.iter().map(|s| s.to_string()).collect();
66 control.extend(config.control.as_deref().map(nfc));
67 let mode = match &config.focus {
68 Some(name) => vec![nfc(name)],
69 None => MODE_LABELS.iter().map(|s| s.to_string()).collect(),
70 };
71 Self { control, mode }
72 }
73
74 fn is_mode(&self, name: &str) -> bool {
75 self.mode.iter().any(|m| m == name)
76 }
77}
78
79#[derive(Debug, Clone, PartialEq)]
80pub struct Row {
81 pub label: String,
82 pub selected: bool,
83 pub frame: Rect,
84}
85
86#[derive(Debug, Clone, PartialEq)]
88pub enum View {
89 Controls { control: Rect, active: Option<String> },
91 List { rows: Vec<Row> },
93 Other,
94}
95
96pub(crate) fn system_ui(screen: &Screen) -> bool {
99 screen.apps.first().is_some_and(|a| a.name.is_none())
100}
101
102pub fn view(screen: &Screen, labels: &Labels) -> View {
103 if !system_ui(screen) {
104 return View::Other;
105 }
106 let buttons: Vec<(Row, Option<String>)> = screen
107 .elements
108 .iter()
109 .filter(|e| e.role == "button" && e.on_screen)
110 .filter_map(|e| {
111 let row = Row { label: nfc(e.label.as_deref()?), selected: e.selected, frame: e.frame? };
112 Some((row, e.value.as_deref().map(nfc)))
113 })
114 .collect();
115 let mode = buttons
116 .iter()
117 .find(|(b, _)| labels.mode.iter().any(|m| named(&b.label, m)))
118 .map(|(b, _)| b.frame);
119 if let Some(mode) = mode {
120 let rows = buttons
122 .into_iter()
123 .map(|(b, _)| b)
124 .filter(|b| (b.frame.x - mode.x).abs() < 2.0 && (b.frame.w - mode.w).abs() < 2.0)
125 .collect();
126 return View::List { rows };
127 }
128 match buttons.into_iter().find(|(b, _)| labels.control.contains(&b.label)) {
129 Some((b, value)) => View::Controls { control: b.frame, active: value.filter(|_| b.selected) },
130 None => View::Other,
131 }
132}
133
134#[derive(Debug, Clone, PartialEq)]
135pub enum Want {
136 Status,
138 Quiet,
140 Back(Option<String>),
142}
143
144fn mode_row<'a>(rows: &'a [Row], labels: &Labels) -> Option<&'a Row> {
145 rows.iter().find(|r| labels.mode.iter().any(|m| named(&r.label, m)))
146}
147
148pub fn pick<'a>(rows: &'a [Row], labels: &Labels, want: &Want) -> Option<&'a Row> {
150 let mode = mode_row(rows, labels)?;
151 match want {
152 Want::Status => None,
153 Want::Quiet => (!mode.selected).then_some(mode),
154 Want::Back(_) if !mode.selected => None,
156 Want::Back(Some(name)) => {
157 let earlier = rows
158 .iter()
159 .find(|r| r.label == *name)
160 .or_else(|| rows.iter().find(|r| named(&r.label, name)))
161 .filter(|r| !std::ptr::eq(*r, mode));
162 Some(earlier.unwrap_or(mode))
164 }
165 Want::Back(None) => Some(mode),
166 }
167}
168
169pub fn reached(rows: &[Row], labels: &Labels, want: &Want) -> bool {
171 let quiet = mode_row(rows, labels).is_some_and(|m| m.selected);
172 match want {
173 Want::Status => true,
174 Want::Quiet => quiet,
175 Want::Back(_) => !quiet,
176 }
177}
178
179#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
182pub struct Record {
183 pub previous: Option<String>,
185 pub at: String,
186}
187
188impl Record {
189 pub fn load(udid: &str) -> Option<Record> {
190 let text = std::fs::read_to_string(paths::dnd_record(udid)).ok()?;
191 serde_json::from_str(&text).ok()
192 }
193
194 fn save(&self, udid: &str) -> std::io::Result<()> {
195 use std::io::Write;
196 paths::ensure_private_dir(&paths::state_dir())?;
197 let mut file = paths::private_file()
198 .create(true)
199 .write(true)
200 .truncate(true)
201 .open(paths::dnd_record(udid))?;
202 file.write_all(serde_json::to_string(self).unwrap_or_default().as_bytes())
203 }
204
205 fn clear(udid: &str) {
206 let _ = std::fs::remove_file(paths::dnd_record(udid));
207 }
208}
209
210#[derive(Debug, Default)]
212pub struct State {
213 pub record: Option<Record>,
214}
215
216impl State {
217 pub fn load(udid: &str) -> Self {
218 Self { record: Record::load(udid) }
219 }
220}
221
222#[derive(Debug, Clone, PartialEq)]
223pub struct Switch {
224 pub before: Option<String>,
226 pub after: Option<String>,
228 pub changed: bool,
229 pub app_changed: bool,
231}
232
233enum Touch {
234 Pull,
236 Hold(f64, f64),
237 Tap(f64, f64),
238 Home,
239}
240
241#[derive(Debug, Deserialize)]
242#[serde(deny_unknown_fields)]
243pub struct DndArgs {
244 pub action: String,
246}
247
248fn no_control() -> Fail {
249 Fail::unknown("control_center_unavailable", "Control Center did not show a Focus control").hint(t(
250 "제어 센터 첫 페이지에 '집중 모드' 항목이 있어야 하고, 앱을 쓰는 중에도 제어 센터가 열려야 합니다. 폰 언어가 한국어 · 영어가 아니면 config.toml의 [dnd] control에 그 항목의 이름을 적으세요.",
251 "Control Center's first page must hold the Focus control, and Control Center must open while an app is in front. For a phone in a language other than Korean or English, put the control's label in [dnd] control in config.toml.",
252 ))
253}
254
255fn no_list() -> Fail {
256 Fail::unknown("focus_list_unavailable", "the list of Focus modes did not show Do Not Disturb").hint(t(
257 "폰에 보이는 방해금지 모드의 이름을 config.toml의 [dnd] focus에 적으세요.",
258 "Put the name the phone shows for Do Not Disturb in [dnd] focus in config.toml.",
259 ))
260}
261
262impl Session {
263 async fn dnd_touch(&mut self, size: (f64, f64), touch: Touch) -> Res<()> {
264 let (w, h) = size;
265 let at = |x: f64, y: f64| (normalize(x, w), normalize(y, h));
266 let gesture = match touch {
267 Touch::Pull => {
270 let x = (w - 30.0).max(w * 0.9);
271 Gesture::Drag {
272 from: at(x, 2.0),
273 to: at(x, h * 0.32),
274 duration: Duration::from_millis(350),
275 motion: Motion::Place,
276 }
277 }
278 Touch::Hold(x, y) => {
279 let (x, y) = at(x, y);
280 Gesture::Tap { x, y, hold: HOLD }
281 }
282 Touch::Tap(x, y) => {
283 let (x, y) = at(x, y);
284 Gesture::Tap { x, y, hold: Duration::from_millis(50) }
285 }
286 Touch::Home => {
287 let (page, usage, hold) = crate::keys::button("home").map_err(Fail::invalid)?;
288 Gesture::Button { page, usage, hold: Duration::from_millis(hold) }
289 }
290 };
291 self.send_gesture(gesture).await
292 }
293
294 async fn dnd_look(&mut self, delay: Duration, labels: &Labels) -> Res<(Screen, View)> {
295 tokio::time::sleep(delay).await;
296 let (_, screen) = self.screen(Fresh::Force, false, BuildOptions::default()).await?;
297 let seen = view(&screen, labels);
298 trace(|| match &seen {
299 View::Controls { control, active } => format!("focus: control center, control at {control:?}, on: {active:?}"),
300 View::List { rows } => format!("focus: list of {} modes", rows.len()),
301 View::Other => format!("focus: something else ({} elements)", screen.elements.len()),
302 });
303 Ok((screen, seen))
304 }
305
306 async fn dnd_until(
308 &mut self,
309 delay: Duration,
310 labels: &Labels,
311 wanted: impl Fn(&View) -> bool,
312 ) -> Res<(bool, Screen, View)> {
313 let began = Instant::now();
314 let mut delay = delay;
315 loop {
316 let (screen, seen) = self.dnd_look(delay, labels).await?;
317 let ok = wanted(&seen);
318 if ok || began.elapsed() >= WAIT {
319 return Ok((ok, screen, seen));
320 }
321 delay = Duration::from_millis(200);
322 }
323 }
324
325 async fn dnd_close(
332 &mut self,
333 start: &Screen,
334 pulled: bool,
335 labels: &Labels,
336 mut seen: Option<(Screen, View)>,
337 ) -> Res<Screen> {
338 let size = (start.width, start.height);
339 let panels_of = |screen: &Screen, now: &View| match now {
343 View::List { .. } => 2,
344 View::Controls { .. } => 1,
345 View::Other if pulled
348 && system_ui(screen)
349 && (!system_ui(start) || screen.signature() != start.signature()) => 1,
350 View::Other => 0,
351 };
352 let mut presses = 0;
353 loop {
354 let (mut screen, mut now) = match seen.take() {
355 Some(x) => x,
356 None => self.dnd_look(AFTER_HOME, labels).await?,
357 };
358 let mut panels = panels_of(&screen, &now);
359 if panels > 0 && presses > 0 {
360 (screen, now) = self.dnd_look(Duration::from_millis(300), labels).await?;
364 panels = panels.min(panels_of(&screen, &now));
365 }
366 if panels == 0 || presses >= 4 {
367 return Ok(screen);
368 }
369 for i in 0..panels {
370 if i > 0 {
371 tokio::time::sleep(BETWEEN_HOME).await;
372 }
373 self.dnd_touch(size, Touch::Home).await?;
374 presses += 1;
375 }
376 }
377 }
378
379 pub(crate) async fn focus_switch(&mut self, want: Want) -> Res<Switch> {
385 let labels = Labels::new(&self.config.dnd);
386 let (_, mut start) = self.screen(Fresh::Force, false, BuildOptions::default()).await?;
387 if start.width <= 0.0 || start.height <= 0.0 {
388 return Err(Fail::not_sent("no_screen_size", "the reading has no application frame"));
389 }
390 self.ensure_input().await?;
392
393 let seen = view(&start, &labels);
395 if seen != View::Other {
396 let open = start.clone();
397 start = self.dnd_close(&open, false, &labels, Some((start, seen))).await?;
398 }
399 let result = self.focus_steps(&want, &labels, &start).await;
400 self.invalidate_readings();
402 let Err(fail) = result else {
403 return result;
404 };
405 match self.dnd_close(&start, true, &labels, None).await {
407 Ok(_) => Err(fail),
408 Err(_) => Err(fail.with("control_center", "may still be open")),
409 }
410 }
411
412 async fn focus_steps(&mut self, want: &Want, labels: &Labels, start: &Screen) -> Res<Switch> {
415 let size = (start.width, start.height);
416 let front = start.apps.first().map(|a| a.pid);
417 let already: Vec<Rect> = start
420 .elements
421 .iter()
422 .filter(|e| e.role == "button")
423 .filter(|e| e.label.as_deref().is_some_and(|l| labels.control.contains(&nfc(l))))
424 .filter_map(|e| e.frame)
425 .collect();
426 let control_of = |seen: &View| match seen {
427 View::Controls { control, active } if !already.contains(control) => Some((*control, active.clone())),
428 _ => None,
429 };
430
431 let mut last = None;
432 for attempt in 0..2 {
433 if attempt == 1 {
434 self.close_input().await;
438 }
439 self.dnd_touch(size, Touch::Pull).await?;
440 let (ok, screen, seen) = self
441 .dnd_until(AFTER_DRAG, labels, |v| control_of(v).is_some() || matches!(v, View::List { .. }))
442 .await?;
443 last = Some((screen, seen));
444 if ok {
445 break;
446 }
447 }
448 let (mut screen, mut seen) = last.expect("the loop ran");
449 if matches!(seen, View::List { .. }) {
450 self.dnd_touch(size, Touch::Home).await?;
452 (_, screen, seen) = self.dnd_until(AFTER_HOME, labels, |v| control_of(v).is_some()).await?;
453 }
454 let Some((control, active)) = control_of(&seen) else {
455 return Err(no_control());
456 };
457
458 let quiet = active.as_deref().is_some_and(|a| labels.is_mode(a));
459 let nothing_to_do = match want {
460 Want::Status => true,
461 Want::Quiet => quiet,
462 Want::Back(_) => !quiet,
463 };
464 let mut after = active.clone();
465 let mut changed = false;
466 if !nothing_to_do {
467 let (x, y) = control.center();
468 self.dnd_touch(size, Touch::Hold(x, y)).await?;
469 (_, screen, seen) = self
470 .dnd_until(AFTER_TAP, labels, |v| matches!(v, View::List { .. }))
471 .await?;
472 let View::List { rows } = &seen else {
473 return Err(no_list());
474 };
475 if let Some(row) = pick(rows, labels, want) {
476 after = match (want, mode_row(rows, labels)) {
477 (Want::Quiet, _) => labels.mode.iter().find(|m| named(&row.label, m)).cloned(),
478 (Want::Back(earlier), Some(mode)) if !std::ptr::eq(row, mode) => earlier.clone(),
479 _ => None,
480 };
481 let (x, y) = row.frame.center();
482 if *want == Want::Quiet {
483 let record = Record { previous: active.clone(), at: now_utc() };
486 record
487 .save(&self.udid)
488 .map_err(|e| Fail::unknown("state_write_failed", format!("{e}")))?;
489 self.dnd.record = Some(record);
490 }
491 self.dnd_touch(size, Touch::Tap(x, y)).await?;
492 let ok;
493 (ok, screen, seen) = self
494 .dnd_until(AFTER_TAP, labels, |v| {
495 matches!(v, View::List { rows } if reached(rows, labels, want))
496 })
497 .await?;
498 if !ok {
499 return Err(Fail::unknown(
500 "focus_not_changed",
501 "the tap in the list of modes did not change Focus",
502 ));
503 }
504 changed = true;
505 }
506 }
507 let end = self.dnd_close(start, true, labels, Some((screen, seen))).await?;
508 let app_changed = end.apps.first().map(|a| a.pid) != front;
509 trace(|| format!("focus: {active:?} -> {after:?} (changed {changed}, app changed {app_changed})"));
510 Ok(Switch { before: active, after, changed, app_changed })
511 }
512
513 pub async fn cmd_dnd(&mut self, args: DndArgs) -> Res {
514 let labels = Labels::new(&self.config.dnd);
515 match args.action.as_str() {
516 "on" => {
517 let switch = self.focus_switch(Want::Quiet).await?;
518 Ok(fields! {
519 "on": true,
520 "changed": switch.changed,
521 "focus": switch.after,
522 "previous": self.dnd.record.as_ref().and_then(|r| r.previous.clone()),
523 "set_by_iph": self.dnd.record.is_some(),
524 })
525 }
526 "off" => {
527 let earlier = self.dnd.record.as_ref().and_then(|r| r.previous.clone());
528 let switch = self.focus_switch(Want::Back(earlier)).await?;
529 Record::clear(&self.udid);
530 self.dnd = State::default();
531 Ok(fields! { "on": false, "changed": switch.changed, "focus": switch.after })
532 }
533 "status" => {
534 let switch = self.focus_switch(Want::Status).await?;
535 Ok(fields! {
536 "on": switch.before.as_deref().is_some_and(|f| labels.is_mode(f)),
537 "focus": switch.before,
538 "set_by_iph": self.dnd.record.is_some(),
539 "previous": self.dnd.record.as_ref().and_then(|r| r.previous.clone()),
540 })
541 }
542 other => Err(Fail::invalid(format!("unknown action `{other}` (on, off, status)"))),
543 }
544 }
545}
546
547#[cfg(test)]
548mod tests {
549 use super::*;
550 use serde_json::{Value, json};
551
552 fn labels() -> Labels {
553 Labels::new(&DndConfig::default())
554 }
555
556 fn button(label: &str, value: Option<&str>, selected: bool, frame: [f64; 4]) -> Value {
557 json!({
558 "id": format!("{label}{}", frame[1]), "role": "button", "label": label, "value": value,
559 "frame": { "x": frame[0], "y": frame[1], "w": frame[2], "h": frame[3] },
560 "traits": ["button"], "enabled": true, "selected": selected, "focused": false,
561 "depth": 1, "pid": 60, "on_screen": true,
562 })
563 }
564
565 fn screen(app: Option<&str>, elements: Vec<Value>) -> Screen {
566 serde_json::from_value(json!({
567 "width": 400.0, "height": 900.0,
568 "apps": [{ "pid": 60, "name": app }],
569 "elements": elements,
570 }))
571 .unwrap()
572 }
573
574 fn controls(active: Option<&str>) -> Screen {
575 screen(None, vec![
576 button("카메라", None, false, [220.0, 490.0, 73.0, 73.0]),
577 button("집중 모드", active, active.is_some(), [46.0, 490.0, 161.0, 73.0]),
578 ])
579 }
580
581 fn list(on: Option<&str>) -> Screen {
584 let names = ["방해금지 모드", "업무", "독서"];
585 let mut rows: Vec<Value> = names
586 .iter()
587 .enumerate()
588 .map(|(i, name)| {
589 let is_on = on == Some(*name);
590 let label = match (is_on, *name) {
591 (true, n) => format!("{n}, 켬"),
592 (false, "방해금지 모드") => "방해금지 모드, 모든 알림을 무음으로 설정".to_string(),
593 (false, n) => n.to_string(),
594 };
595 button(&label, None, is_on, [44.0, 190.0 + 70.0 * i as f64, 342.0, 58.0])
596 })
597 .collect();
598 rows.push(button("새로운 집중 모드", None, false, [178.0, 820.0, 73.0, 63.0]));
599 screen(None, rows)
600 }
601
602 fn rows(s: &Screen) -> Vec<Row> {
603 match view(s, &labels()) {
604 View::List { rows } => rows,
605 other => panic!("not a list: {other:?}"),
606 }
607 }
608
609 #[test]
610 fn control_center_shows_the_focus_that_is_on() {
611 assert_eq!(
612 view(&controls(Some("업무")), &labels()),
613 View::Controls { control: Rect { x: 46.0, y: 490.0, w: 161.0, h: 73.0 }, active: Some("업무".into()) }
614 );
615 assert!(matches!(view(&controls(None), &labels()), View::Controls { active: None, .. }));
616 }
617
618 #[test]
619 fn an_app_with_the_same_words_is_not_control_center() {
620 let settings = screen(Some("설정"), vec![
622 button("집중 모드", None, false, [20.0, 740.0, 390.0, 49.0]),
623 button("방해금지 모드", None, false, [20.0, 130.0, 390.0, 50.0]),
624 ]);
625 assert_eq!(view(&settings, &labels()), View::Other);
626 }
627
628 #[test]
629 fn the_list_leaves_out_the_button_under_it() {
630 let rows = rows(&list(Some("업무")));
631 assert_eq!(rows.len(), 3);
632 assert!(rows.iter().all(|r| r.label != "새로운 집중 모드"));
633 assert!(rows.iter().any(|r| r.label == "업무, 켬" && r.selected));
634 }
635
636 #[test]
637 fn going_quiet_taps_do_not_disturb_unless_it_is_on() {
638 let l = labels();
639 let off = rows(&list(Some("업무")));
640 assert!(named(&pick(&off, &l, &Want::Quiet).unwrap().label, "방해금지 모드"));
641 assert!(!reached(&off, &l, &Want::Quiet));
642 let on = rows(&list(Some("방해금지 모드")));
643 assert_eq!(pick(&on, &l, &Want::Quiet), None);
644 assert!(reached(&on, &l, &Want::Quiet));
645 }
646
647 #[test]
648 fn going_back_picks_the_earlier_focus() {
649 let l = labels();
650 let quiet = rows(&list(Some("방해금지 모드")));
651 let back = Want::Back(Some("업무".into()));
652 assert_eq!(pick(&quiet, &l, &back).unwrap().label, "업무");
653 assert!(!reached(&quiet, &l, &back));
654 assert!(reached(&rows(&list(Some("업무"))), &l, &back));
655 }
656
657 #[test]
658 fn going_back_to_no_focus_turns_do_not_disturb_off() {
659 let l = labels();
660 let quiet = rows(&list(Some("방해금지 모드")));
661 assert_eq!(pick(&quiet, &l, &Want::Back(None)).unwrap().label, "방해금지 모드, 켬");
662 assert_eq!(pick(&quiet, &l, &Want::Back(Some("없어진 모드".into()))).unwrap().label, "방해금지 모드, 켬");
664 assert!(reached(&rows(&list(None)), &l, &Want::Back(None)));
665 }
666
667 #[test]
668 fn a_focus_someone_else_chose_is_left_alone() {
669 let l = labels();
670 let theirs = rows(&list(Some("독서")));
671 assert_eq!(pick(&theirs, &l, &Want::Back(Some("업무".into()))), None);
672 assert_eq!(pick(&theirs, &l, &Want::Back(None)), None);
673 }
674
675 #[test]
676 fn another_focus_can_stand_in_for_do_not_disturb() {
677 let l = Labels::new(&DndConfig { focus: Some("독서".into()), ..Default::default() });
678 let View::List { rows } = view(&list(Some("업무")), &l) else { panic!("not a list") };
679 assert_eq!(pick(&rows, &l, &Want::Quiet).unwrap().label, "독서");
680 assert!(l.is_mode("독서") && !l.is_mode("방해금지 모드"));
681 }
682
683 #[test]
684 fn names_match_whole_or_before_a_comma() {
685 assert!(named("방해금지 모드", "방해금지 모드"));
686 assert!(named("방해금지 모드, 켬", "방해금지 모드"));
687 assert!(!named("방해금지 모드 2", "방해금지 모드"));
688 assert!(!named("업무", "방해금지 모드"));
689 }
690
691 #[test]
692 fn the_record_survives_a_restart() {
693 let dir = std::env::temp_dir().join(format!("iph-dnd-test-{}", std::process::id()));
694 unsafe { std::env::set_var("IPH_STATE_DIR", &dir) };
696 let record = Record { previous: Some("업무".into()), at: now_utc() };
697 record.save("TEST-PHONE").unwrap();
698 assert_eq!(State::load("TEST-PHONE").record, Some(record));
699 Record::clear("TEST-PHONE");
700 assert_eq!(Record::load("TEST-PHONE"), None);
701 let _ = std::fs::remove_dir_all(&dir);
702 }
703}