1use std::collections::VecDeque;
22use std::ffi::OsString;
23use std::path::PathBuf;
24use std::sync::{Arc, Mutex, PoisonError};
25
26use hypersig::{SafeUrl, Url};
27
28use crate::os::Os;
29
30#[derive(Debug, Clone, Default)]
32pub struct FakeOs {
33 fake: Arc<Mutex<Fake>>,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38#[non_exhaustive]
39pub struct Arranged {
40 pub placement: crate::Placement,
42 pub layer: crate::Layer,
44 pub position: Option<(i32, i32)>,
46 pub size: Option<(u32, u32)>,
48}
49
50impl Fake {
51 pub(crate) fn arrange(&mut self, index: usize, change: crate::arrange::Arrange) {
53 use crate::arrange::Arrange;
54 if !self.windows.get(index).is_some_and(Option::is_some) {
55 return;
56 }
57 let arranged = self.arranged.entry(index).or_default();
58 match change {
59 Arrange::Place(placement) => arranged.placement = placement,
60 Arrange::Layer(layer) => arranged.layer = layer,
61 Arrange::Move(x, y) => arranged.position = Some((x, y)),
62 Arrange::Resize(width, height) => arranged.size = Some((width, height)),
63 }
64 }
65}
66
67#[derive(Debug)]
69pub(crate) struct Fake {
70 pub(crate) answers: VecDeque<Option<Vec<PathBuf>>>,
71 pub(crate) choices: VecDeque<Choice>,
73 pub(crate) messages: Vec<ShownMessage>,
75 pub(crate) dialogs: Vec<ShownDialog>,
76 pub(crate) clipboard: Option<String>,
77 pub(crate) windows: Vec<Option<Url>>,
79 pub(crate) focused: Option<usize>,
81 pub(crate) arranged: std::collections::HashMap<usize, Arranged>,
83 pub(crate) external: Vec<SafeUrl>,
84 pub(crate) launches: tokio::sync::broadcast::Sender<crate::Launch>,
85 pub(crate) badge: u32,
86 pub(crate) autostart: bool,
88 pub(crate) tray: Option<crate::Tray>,
89 pub(crate) menus: Vec<crate::Menu>,
91 pub(crate) shortcuts:
93 std::collections::HashMap<crate::Shortcut, tokio::sync::broadcast::Sender<crate::Press>>,
94 pub(crate) notifications: Vec<(
96 crate::Notification,
97 Option<tokio::sync::oneshot::Sender<bool>>,
98 )>,
99}
100
101impl Default for Fake {
102 fn default() -> Self {
103 Self {
104 answers: VecDeque::new(),
105 choices: VecDeque::new(),
106 messages: Vec::new(),
107 dialogs: Vec::new(),
108 clipboard: None,
109 windows: Vec::new(),
110 focused: None,
111 arranged: std::collections::HashMap::new(),
112 external: Vec::new(),
113 launches: crate::handoff::channel(),
114 badge: 0,
115 autostart: false,
116 tray: None,
117 menus: Vec::new(),
118 shortcuts: std::collections::HashMap::new(),
119 notifications: Vec::new(),
120 }
121 }
122}
123
124impl Fake {
125 pub(crate) fn tell(&mut self, message: crate::Message) {
127 self.messages.push(ShownMessage {
128 kind: MessageKind::Tell,
129 message,
130 });
131 }
132
133 pub(crate) fn confirm(&mut self, message: crate::Message) -> bool {
135 match self.choice(MessageKind::Confirm, message) {
136 Choice::Ok => true,
137 Choice::Cancel => false,
138 other => panic!("a box of OK and Cancel was answered with Choice::{other:?}"),
139 }
140 }
141
142 pub(crate) fn ask(&mut self, message: crate::Message) -> crate::Answer {
144 match self.choice(MessageKind::Ask, message) {
145 Choice::Yes => crate::Answer::Yes,
146 Choice::No => crate::Answer::No,
147 Choice::Cancel => crate::Answer::Cancel,
148 Choice::Ok => panic!("a box of Yes, No, and Cancel was answered with Choice::Ok"),
149 }
150 }
151
152 fn choice(&mut self, kind: MessageKind, message: crate::Message) -> Choice {
158 let number = self.messages.len() + 1;
159 let choice = self.choices.pop_front().unwrap_or_else(|| {
160 panic!("message box {number} was shown, and the test chose no button for it with FakeOs::choose")
161 });
162 self.messages.push(ShownMessage { kind, message });
163 choice
164 }
165
166 pub(crate) fn answer_dialog(&mut self, dialog: ShownDialog) -> Option<Vec<PathBuf>> {
174 let number = self.dialogs.len() + 1;
175 let answer = self.answers.pop_front().unwrap_or_else(|| {
176 panic!(
177 "dialog {number} was shown, and the test gave FakeOs no answer for it with answer_dialog or cancel_dialog"
178 )
179 });
180 if let Some(paths) = &answer
181 && dialog.kind != DialogKind::OpenFiles
182 && paths.len() != 1
183 {
184 panic!(
185 "dialog {number} was shown with DialogKind::{:?}, which chooses one path, and the test answered it with {} paths",
186 dialog.kind,
187 paths.len()
188 );
189 }
190 self.dialogs.push(dialog);
191 answer
192 }
193}
194
195#[derive(Debug, Clone, PartialEq, Eq)]
197#[non_exhaustive]
198pub struct ShownDialog {
199 pub kind: DialogKind,
201 pub title: Option<String>,
203 pub filters: Vec<(String, Vec<String>)>,
205 pub directory: Option<PathBuf>,
207 pub file_name: Option<String>,
209}
210
211#[derive(Debug, Clone, PartialEq, Eq)]
213#[non_exhaustive]
214pub struct ShownMessage {
215 pub kind: MessageKind,
217 pub message: crate::Message,
219}
220
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223#[non_exhaustive]
224pub enum MessageKind {
225 Tell,
227 Confirm,
229 Ask,
231}
232
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235#[non_exhaustive]
236pub enum Choice {
237 Ok,
239 Yes,
241 No,
243 Cancel,
245}
246
247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249#[non_exhaustive]
250pub enum DialogKind {
251 OpenFile,
253 OpenFiles,
255 PickFolder,
257 SaveFile,
259}
260
261impl FakeOs {
262 #[must_use]
264 pub fn new() -> Self {
265 Self::default()
266 }
267
268 #[must_use]
270 pub fn os(&self) -> Os {
271 Os::fake(Arc::clone(&self.fake))
272 }
273
274 pub fn answer_dialog(&self, paths: impl IntoIterator<Item = PathBuf>) {
280 self.lock()
281 .answers
282 .push_back(Some(paths.into_iter().collect()));
283 }
284
285 pub fn choose(&self, choice: Choice) {
290 self.lock().choices.push_back(choice);
291 }
292
293 #[must_use]
295 pub fn messages(&self) -> Vec<ShownMessage> {
296 self.lock().messages.clone()
297 }
298
299 pub fn cancel_dialog(&self) {
301 self.lock().answers.push_back(None);
302 }
303
304 #[must_use]
306 pub fn dialogs(&self) -> Vec<ShownDialog> {
307 self.lock().dialogs.clone()
308 }
309
310 #[must_use]
312 pub fn clipboard_text(&self) -> Option<String> {
313 self.lock().clipboard.clone()
314 }
315
316 pub fn set_clipboard_text(&self, text: impl Into<String>) {
318 self.lock().clipboard = Some(text.into());
319 }
320
321 #[must_use]
323 pub fn open_windows(&self) -> Vec<Url> {
324 self.lock().windows.iter().flatten().cloned().collect()
325 }
326
327 #[must_use]
329 pub fn window(&self, window: &crate::Window) -> Option<Arranged> {
330 let fake = self.lock();
331 let index = window.fake_index()?;
332 fake.windows.get(index)?.as_ref()?;
333 Some(fake.arranged.get(&index).copied().unwrap_or_default())
334 }
335
336 #[must_use]
338 pub fn focused_window(&self) -> Option<Url> {
339 let fake = self.lock();
340 fake.windows.get(fake.focused?)?.clone()
341 }
342
343 #[cfg(feature = "updater")]
347 #[must_use]
348 pub fn updater(&self) -> crate::Updater {
349 crate::Updater::fake()
350 }
351
352 pub fn launch(&self, dir: impl Into<PathBuf>, args: impl IntoIterator<Item = OsString>) {
356 let launch = crate::Launch::new(dir.into(), args.into_iter().collect());
357 let _ = self.lock().launches.send(launch);
359 }
360
361 #[must_use]
364 pub fn badge(&self) -> u32 {
365 self.lock().badge
366 }
367
368 #[must_use]
370 pub fn notifications(&self) -> Vec<crate::Notification> {
371 self.lock()
372 .notifications
373 .iter()
374 .map(|(shown, _)| shown.clone())
375 .collect()
376 }
377
378 pub fn click_notification(&self, index: usize) {
388 let mut fake = self.lock();
389 let clicked = fake
390 .notifications
391 .get_mut(index)
392 .and_then(|(_, clicked)| clicked.take())
393 .unwrap_or_else(|| panic!("no notification {index} is waiting to be clicked"));
394 let _ = clicked.send(true);
395 }
396
397 #[must_use]
399 pub fn has_shortcut(&self, shortcut: crate::Shortcut) -> bool {
400 self.lock().shortcuts.contains_key(&shortcut)
401 }
402
403 pub fn press_shortcut(&self, shortcut: crate::Shortcut, press: crate::Press) {
410 let fake = self.lock();
411 let presses = fake
412 .shortcuts
413 .get(&shortcut)
414 .unwrap_or_else(|| panic!("no handler registered the shortcut {shortcut:?}"));
415 let _ = presses.send(press);
416 }
417
418 #[must_use]
420 pub fn tray(&self) -> Option<crate::Tray> {
421 self.lock().tray.clone()
422 }
423
424 pub fn click_tray_item(&self, item: &crate::TrayItem) {
430 let shown = self
431 .lock()
432 .tray
433 .as_ref()
434 .is_some_and(|tray| tray.items.iter().any(|shown| shown.id == item.id));
435 assert!(shown, "the tray shown has no item labeled {:?}", item.label);
436 let _ = item.clicked.send(());
437 }
438
439 #[must_use]
441 pub fn menus(&self) -> Vec<crate::Menu> {
442 self.lock().menus.clone()
443 }
444
445 pub fn click_menu_item(&self, item: &crate::MenuItem) {
451 let shown = self
452 .lock()
453 .menus
454 .iter()
455 .any(|menu| menu.items().any(|shown| shown.id == item.id));
456 assert!(
457 shown,
458 "no menu of the menu bar has an item labeled {:?}",
459 item.label
460 );
461 let _ = item.clicked.send(());
462 }
463
464 #[must_use]
466 pub fn opened_externally(&self) -> Vec<SafeUrl> {
467 self.lock().external.clone()
468 }
469
470 fn lock(&self) -> std::sync::MutexGuard<'_, Fake> {
471 self.fake.lock().unwrap_or_else(PoisonError::into_inner)
472 }
473}
474
475#[cfg(test)]
476mod tests {
477 use std::path::PathBuf;
478
479 use axum::Router;
480 use hypersig::Route;
481
482 use super::{DialogKind, FakeOs, ShownDialog};
483
484 fn block_on<F: Future>(future: F) -> F::Output {
485 tokio::runtime::Builder::new_current_thread()
486 .build()
487 .unwrap_or_else(|error| panic!("no runtime: {error}"))
488 .block_on(future)
489 }
490
491 #[test]
492 fn a_dialog_is_recorded_with_its_kind_and_setup() {
493 let fake = FakeOs::new();
494 fake.answer_dialog([PathBuf::from("/notes/today.md")]);
495 let saved = block_on(
496 fake.os()
497 .dialog()
498 .title("Save the note")
499 .filter("Markdown", &["md"])
500 .directory("/notes")
501 .file_name("today.md")
502 .save_file(),
503 );
504 assert_eq!(saved, Some(PathBuf::from("/notes/today.md")));
505 assert_eq!(
506 fake.dialogs(),
507 [ShownDialog {
508 kind: DialogKind::SaveFile,
509 title: Some("Save the note".to_owned()),
510 filters: vec![("Markdown".to_owned(), vec!["md".to_owned()])],
511 directory: Some(PathBuf::from("/notes")),
512 file_name: Some("today.md".to_owned()),
513 }]
514 );
515 }
516
517 #[test]
518 fn open_files_takes_an_empty_answer() {
519 let fake = FakeOs::new();
520 fake.answer_dialog([]);
521 assert_eq!(block_on(fake.os().dialog().open_files()), Some(vec![]));
522 }
523
524 #[test]
525 #[should_panic(
526 expected = "dialog 1 was shown with DialogKind::OpenFile, which chooses one path, and the test answered it with 0 paths"
527 )]
528 fn a_dialog_of_one_path_refuses_an_empty_answer() {
529 let fake = FakeOs::new();
530 fake.answer_dialog([]);
531 let _ = block_on(fake.os().dialog().open_file());
532 }
533
534 #[test]
535 fn an_unanswered_dialog_is_not_recorded() {
536 let fake = FakeOs::new();
537 let os = fake.os();
538 let shown = std::thread::spawn(move || block_on(os.dialog().pick_folder())).join();
539 assert!(shown.is_err(), "the unanswered dialog panics");
540 assert_eq!(fake.dialogs(), []);
541 }
542
543 #[derive(hypersig::Signals, serde::Serialize, serde::Deserialize)]
544 struct NotePage {
545 id: u64,
546 }
547
548 hypersig::routes! {
549 fn pages(Router<()>);
550 const NOTE: Route<u64> = "/notes/{id}" => note;
551 }
552
553 async fn note((): (), id: u64) -> hypersig::Page<NotePage> {
554 hypersig::Page::new("Note", NotePage { id })
555 }
556
557 fn ok<T>(result: Result<T, crate::Error>) -> T {
558 result.unwrap_or_else(|error| panic!("{error}"))
559 }
560
561 #[test]
562 fn the_window_opened_or_focused_last_is_focused() {
563 let _ = pages(Router::new());
564 let fake = FakeOs::new();
565 let os = fake.os();
566 let first = ok(block_on(os.windows().open(&NOTE.url(1))));
567 let second = ok(block_on(os.windows().open(&NOTE.url(2))));
568 assert_eq!(fake.focused_window(), Some(NOTE.url(2)));
569 ok(first.focus());
570 assert_eq!(fake.focused_window(), Some(NOTE.url(1)));
571 ok(first.close());
572 assert_eq!(fake.focused_window(), None);
573 ok(second.focus());
574 ok(first.focus());
575 assert_eq!(fake.focused_window(), Some(NOTE.url(2)));
576 }
577
578 #[test]
579 fn the_badge_keeps_the_count_set_last() {
580 let fake = FakeOs::new();
581 assert_eq!(fake.badge(), 0);
582 ok(fake.os().badge(3));
583 ok(fake.os().badge(0));
584 ok(fake.os().badge(5));
585 assert_eq!(fake.badge(), 5);
586 }
587
588 #[test]
589 fn a_message_box_is_recorded_and_answered_by_the_test() {
590 use super::{Choice, MessageKind};
591 use crate::{Answer, Level, Message};
592 let fake = FakeOs::new();
593 let os = fake.os();
594 block_on(os.tell(Message::new(Level::Info, "Saved")));
595 fake.choose(Choice::Ok);
596 fake.choose(Choice::No);
597 assert!(block_on(os.confirm(Message::new(Level::Warning, "Quit?"))));
598 let answer = block_on(
599 os.ask(Message::new(Level::Warning, "Save?").body("Changes are lost otherwise.")),
600 );
601 assert_eq!(answer, Answer::No);
602 let kinds: Vec<_> = fake.messages().iter().map(|shown| shown.kind).collect();
603 assert_eq!(
604 kinds,
605 [MessageKind::Tell, MessageKind::Confirm, MessageKind::Ask]
606 );
607 assert_eq!(
608 fake.messages()[2].message.text(),
609 Some("Changes are lost otherwise.")
610 );
611 }
612
613 #[test]
614 fn a_window_is_found_focused_and_arranged() {
615 use crate::{Layer, Placement};
616 let fake = FakeOs::new();
617 let os = fake.os();
618 let window = ok(block_on(os.windows().open(&NOTE.url(1))));
619 let focused = ok(block_on(os.windows().focused())).expect("the window opened last");
620 assert_eq!(focused, window);
621 ok(window.place(Placement::Maximized));
622 ok(window.layer(Layer::AlwaysOnTop));
623 ok(window.move_to(10, -20));
624 ok(window.resize(800, 600));
625 let arranged = fake.window(&window).expect("the window is open");
626 assert_eq!(arranged.placement, Placement::Maximized);
627 assert_eq!(arranged.layer, Layer::AlwaysOnTop);
628 assert_eq!(arranged.position, Some((10, -20)));
629 assert_eq!(arranged.size, Some((800, 600)));
630 ok(window.close());
631 assert!(fake.window(&window).is_none());
632 assert!(ok(block_on(os.windows().focused())).is_none());
633 }
634
635 #[test]
636 fn a_menu_bar_is_recorded_and_its_item_clicked_by_the_test() {
637 use crate::{Menu, MenuItem};
638 let fake = FakeOs::new();
639 let open = MenuItem::new("Open");
640 let mut clicks = open.clicks();
641 ok(fake.os().menus([Menu::new("File").item(&open)]));
642 assert_eq!(fake.menus()[0].labels(), ["Open"]);
643 fake.click_menu_item(&open);
644 assert!(block_on(clicks.next()));
645 }
646
647 #[test]
648 fn the_start_at_login_is_kept_by_the_fake_system() {
649 let fake = FakeOs::new();
650 let os = fake.os();
651 assert!(!ok(block_on(os.autostart().is_enabled())));
652 ok(block_on(os.autostart().enable()));
653 assert!(ok(block_on(os.autostart().is_enabled())));
654 ok(block_on(os.autostart().disable()));
655 assert!(!ok(block_on(os.autostart().is_enabled())));
656 }
657
658 #[test]
659 fn a_shortcut_is_registered_and_pressed_by_the_test() {
660 use crate::{Key, Modifiers, Press, Shortcut};
661 const TALK: Shortcut = Shortcut::new(Modifiers::CONTROL, Key::Space);
662 let fake = FakeOs::new();
663 let os = fake.os();
664 assert!(!fake.has_shortcut(TALK));
665 let mut first = ok(block_on(os.shortcut(TALK)));
666 let mut second = ok(block_on(os.shortcut(TALK)));
667 assert!(fake.has_shortcut(TALK));
668 fake.press_shortcut(TALK, Press::Pressed);
669 fake.press_shortcut(TALK, Press::Released);
670 assert_eq!(block_on(first.next()), Some(Press::Pressed));
671 assert_eq!(block_on(first.next()), Some(Press::Released));
672 assert_eq!(block_on(second.next()), Some(Press::Pressed));
673 }
674
675 #[test]
676 fn a_notification_is_recorded_and_clicked_by_the_test() {
677 let fake = FakeOs::new();
678 let os = fake.os();
679 let (clicked, left) = block_on(async {
680 let first = ok(os
681 .notify(crate::Notification::new("Ada").body("Lunch?"))
682 .await);
683 let second = ok(os.notify(crate::Notification::new("Grace")).await);
684 fake.click_notification(0);
685 (first, second)
686 });
687 assert_eq!(fake.notifications()[0].title(), "Ada");
688 assert_eq!(fake.notifications()[0].text(), Some("Lunch?"));
689 assert_eq!(fake.notifications()[1].text(), None);
690 assert!(block_on(clicked.clicked()));
691 drop((fake, os));
692 assert!(!block_on(left.clicked()));
693 }
694}