1use std::fmt;
4use std::path::PathBuf;
5#[cfg(feature = "testing")]
6use std::sync::{Arc, Mutex, PoisonError};
7
8use hypersig::{SafeUrl, Url};
9use tao::event_loop::EventLoopProxy;
10use tao::window::WindowId;
11use tokio::sync::{broadcast, oneshot};
12
13use crate::arrange::{Arrange, Layer, Placement};
14use crate::clipboard;
15use crate::error::Error;
16use crate::handoff::{Launch, Launches};
17use crate::menu::Menu;
18use crate::message::{Answer, Message};
19use crate::notification::{Notification, Notified};
20use crate::run::Event;
21use crate::shortcut::{Presses, Shortcut};
22#[cfg(feature = "testing")]
23use crate::testing::Fake;
24use crate::tray::Tray;
25
26#[derive(Clone)]
33pub struct Os {
34 inner: Inner,
35 launches: broadcast::Sender<Launch>,
36 id: &'static str,
38}
39
40#[derive(Clone)]
41enum Inner {
42 System(EventLoopProxy<Event>),
43 #[cfg(feature = "testing")]
44 Fake(Arc<Mutex<Fake>>),
45}
46
47impl fmt::Debug for Os {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 f.debug_struct("Os").finish_non_exhaustive()
50 }
51}
52
53impl Os {
54 pub(crate) fn new(
55 proxy: EventLoopProxy<Event>,
56 launches: broadcast::Sender<Launch>,
57 id: &'static str,
58 ) -> Self {
59 Self {
60 inner: Inner::System(proxy),
61 launches,
62 id,
63 }
64 }
65
66 #[cfg(feature = "testing")]
67 pub(crate) fn fake(fake: Arc<Mutex<Fake>>) -> Self {
68 let launches = lock(&fake).launches.clone();
69 Self {
70 inner: Inner::Fake(fake),
71 launches,
72 id: "dev.hypersig.fake",
73 }
74 }
75
76 #[must_use]
87 pub fn launches(&self) -> Launches {
88 Launches::new(self.launches.subscribe())
89 }
90
91 pub async fn notify(&self, notification: Notification) -> Result<Notified, Error> {
104 match &self.inner {
105 Inner::System(_) => {
106 tokio::task::spawn_blocking(move || crate::notification::show(¬ification))
107 .await
108 .map_err(Error::notification)?
109 }
110 #[cfg(feature = "testing")]
111 Inner::Fake(fake) => {
112 let (clicked, heard) = oneshot::channel();
113 lock(fake).notifications.push((notification, Some(clicked)));
114 Ok(Notified { clicked: heard })
115 }
116 }
117 }
118
119 pub async fn shortcut(&self, shortcut: Shortcut) -> Result<Presses, Error> {
134 match &self.inner {
135 Inner::System(proxy) => {
136 let (answer, answered) = oneshot::channel();
137 Os::send(proxy, Event::Shortcut { shortcut, answer })?;
138 answered.await.map_err(|_closed| Error::closed())?
139 }
140 #[cfg(feature = "testing")]
141 Inner::Fake(fake) => Ok(Presses::new(
142 lock(fake)
143 .shortcuts
144 .entry(shortcut)
145 .or_insert_with(crate::shortcut::channel)
146 .subscribe(),
147 )),
148 }
149 }
150
151 pub async fn tray(&self, tray: Tray) -> Result<(), Error> {
162 match &self.inner {
163 Inner::System(proxy) => {
164 let (answer, answered) = oneshot::channel();
165 Os::send(proxy, Event::Tray { tray, answer })?;
166 answered.await.map_err(|_closed| Error::closed())?
167 }
168 #[cfg(feature = "testing")]
169 Inner::Fake(fake) => {
170 lock(fake).tray = Some(tray);
171 Ok(())
172 }
173 }
174 }
175
176 pub fn menus(&self, menus: impl IntoIterator<Item = Menu>) -> Result<(), Error> {
189 let menus = menus.into_iter().collect();
190 match &self.inner {
191 Inner::System(proxy) => Os::send(proxy, Event::Menus(menus)),
192 #[cfg(feature = "testing")]
193 Inner::Fake(fake) => {
194 lock(fake).menus = menus;
195 Ok(())
196 }
197 }
198 }
199
200 pub fn badge(&self, count: u32) -> Result<(), Error> {
212 match &self.inner {
213 Inner::System(proxy) => Os::send(proxy, Event::Badge(count)),
214 #[cfg(feature = "testing")]
215 Inner::Fake(fake) => {
216 lock(fake).badge = count;
217 Ok(())
218 }
219 }
220 }
221
222 #[must_use]
224 pub fn windows(&self) -> Windows<'_> {
225 Windows { os: self }
226 }
227
228 pub fn dialog(&self) -> Dialog {
230 Dialog {
231 #[cfg(feature = "testing")]
232 os: self.clone(),
233 title: None,
234 filters: Vec::new(),
235 directory: None,
236 file_name: None,
237 }
238 }
239
240 pub async fn tell(&self, message: Message) {
243 match &self.inner {
244 Inner::System(_) => {
245 message.system(rfd::MessageButtons::Ok).show().await;
246 }
247 #[cfg(feature = "testing")]
248 Inner::Fake(fake) => lock(fake).tell(message),
249 }
250 }
251
252 pub async fn confirm(&self, message: Message) -> bool {
255 match &self.inner {
256 Inner::System(_) => {
257 let chosen = message.system(rfd::MessageButtons::OkCancel).show().await;
258 chosen == rfd::MessageDialogResult::Ok
259 }
260 #[cfg(feature = "testing")]
261 Inner::Fake(fake) => lock(fake).confirm(message),
262 }
263 }
264
265 pub async fn ask(&self, message: Message) -> Answer {
268 match &self.inner {
269 Inner::System(_) => {
270 let chosen = message
271 .system(rfd::MessageButtons::YesNoCancel)
272 .show()
273 .await;
274 Answer::from_system(&chosen)
275 }
276 #[cfg(feature = "testing")]
277 Inner::Fake(fake) => lock(fake).ask(message),
278 }
279 }
280
281 #[must_use]
283 pub fn autostart(&self) -> Autostart<'_> {
284 Autostart { os: self }
285 }
286
287 #[must_use]
289 pub fn clipboard(&self) -> Clipboard<'_> {
290 Clipboard { os: self }
291 }
292
293 pub fn open_external(&self, url: &SafeUrl) -> Result<(), Error> {
302 if !is_external(url.as_str()) {
303 return Err(Error::not_external());
304 }
305 match &self.inner {
306 Inner::System(_) => open::that_detached(url.as_str()).map_err(Error::from),
307 #[cfg(feature = "testing")]
308 Inner::Fake(fake) => {
309 lock(fake).external.push(url.clone());
310 Ok(())
311 }
312 }
313 }
314
315 fn send(proxy: &EventLoopProxy<Event>, event: Event) -> Result<(), Error> {
317 proxy.send_event(event).map_err(|_closed| Error::closed())
318 }
319}
320
321pub(crate) fn is_external(url: &str) -> bool {
325 ["http://", "https://", "mailto:"].iter().any(|scheme| {
326 url.get(..scheme.len())
327 .is_some_and(|start| start.eq_ignore_ascii_case(scheme))
328 })
329}
330
331#[cfg(feature = "testing")]
332fn lock(fake: &Mutex<Fake>) -> std::sync::MutexGuard<'_, Fake> {
333 fake.lock().unwrap_or_else(PoisonError::into_inner)
334}
335
336#[derive(Debug, Clone, Copy)]
338pub struct Windows<'a> {
339 os: &'a Os,
340}
341
342impl Windows<'_> {
343 pub async fn open(&self, page: &Url) -> Result<Window, Error> {
350 let key = match &self.os.inner {
351 Inner::System(proxy) => {
352 let (answer, answered) = oneshot::channel();
353 Os::send(
354 proxy,
355 Event::Open {
356 url: page.as_str().to_owned(),
357 answer: Some(answer),
358 },
359 )?;
360 Key::System(answered.await.map_err(|_closed| Error::closed())??)
361 }
362 #[cfg(feature = "testing")]
363 Inner::Fake(fake) => {
364 let mut fake = lock(fake);
365 fake.windows.push(Some(page.clone()));
366 let index = fake.windows.len() - 1;
367 fake.focused = Some(index);
369 Key::Fake(index)
370 }
371 };
372 Ok(Window {
373 key,
374 os: self.os.clone(),
375 })
376 }
377
378 pub async fn focused(&self) -> Result<Option<Window>, Error> {
389 let key = match &self.os.inner {
390 Inner::System(proxy) => {
391 let (answer, answered) = oneshot::channel();
392 Os::send(proxy, Event::Focused(answer))?;
393 answered
394 .await
395 .map_err(|_closed| Error::closed())?
396 .map(Key::System)
397 }
398 #[cfg(feature = "testing")]
399 Inner::Fake(fake) => {
400 let fake = lock(fake);
401 fake.focused
402 .filter(|&index| fake.windows.get(index).is_some_and(Option::is_some))
403 .map(Key::Fake)
404 }
405 };
406 Ok(key.map(|key| Window {
407 key,
408 os: self.os.clone(),
409 }))
410 }
411}
412
413#[derive(Debug, Clone)]
415pub struct Window {
416 key: Key,
417 os: Os,
418}
419
420#[derive(Debug, Clone, Copy, PartialEq, Eq)]
421enum Key {
422 System(WindowId),
423 #[cfg(feature = "testing")]
424 Fake(usize),
425}
426
427impl Window {
428 pub fn close(&self) -> Result<(), Error> {
437 match (&self.os.inner, self.key) {
438 (Inner::System(proxy), Key::System(id)) => Os::send(proxy, Event::Close(id)),
439 #[cfg(feature = "testing")]
440 (Inner::Fake(fake), Key::Fake(index)) => {
441 if let Some(window) = lock(fake).windows.get_mut(index) {
442 *window = None;
443 }
444 Ok(())
445 }
446 #[cfg(feature = "testing")]
447 _ => Ok(()),
448 }
449 }
450
451 pub fn focus(&self) -> Result<(), Error> {
460 match (&self.os.inner, self.key) {
461 (Inner::System(proxy), Key::System(id)) => Os::send(proxy, Event::Focus(id)),
462 #[cfg(feature = "testing")]
463 (Inner::Fake(fake), Key::Fake(index)) => {
464 let mut fake = lock(fake);
465 if fake.windows.get(index).is_some_and(Option::is_some) {
466 fake.focused = Some(index);
467 }
468 Ok(())
469 }
470 #[cfg(feature = "testing")]
471 _ => Ok(()),
472 }
473 }
474}
475
476impl Window {
477 pub fn place(&self, placement: Placement) -> Result<(), Error> {
487 self.arrange(Arrange::Place(placement))
488 }
489
490 pub fn layer(&self, layer: Layer) -> Result<(), Error> {
497 self.arrange(Arrange::Layer(layer))
498 }
499
500 pub fn move_to(&self, x: i32, y: i32) -> Result<(), Error> {
510 self.arrange(Arrange::Move(x, y))
511 }
512
513 pub fn resize(&self, width: u32, height: u32) -> Result<(), Error> {
520 self.arrange(Arrange::Resize(width, height))
521 }
522
523 fn arrange(&self, change: Arrange) -> Result<(), Error> {
524 match (&self.os.inner, self.key) {
525 (Inner::System(proxy), Key::System(id)) => Os::send(proxy, Event::Arrange(id, change)),
526 #[cfg(feature = "testing")]
527 (Inner::Fake(fake), Key::Fake(index)) => {
528 lock(fake).arrange(index, change);
529 Ok(())
530 }
531 #[cfg(feature = "testing")]
532 _ => Ok(()),
533 }
534 }
535
536 #[cfg(feature = "testing")]
538 pub(crate) fn fake_index(&self) -> Option<usize> {
539 match self.key {
540 Key::Fake(index) => Some(index),
541 Key::System(_) => None,
542 }
543 }
544}
545
546impl PartialEq for Window {
547 fn eq(&self, other: &Self) -> bool {
548 self.key == other.key
549 }
550}
551
552impl Eq for Window {}
553
554#[derive(Debug, Clone)]
556#[must_use = "a dialog shows only when one of its async methods is awaited"]
557pub struct Dialog {
558 #[cfg(feature = "testing")]
560 os: Os,
561 title: Option<String>,
562 filters: Vec<(String, Vec<String>)>,
563 directory: Option<PathBuf>,
564 file_name: Option<String>,
565}
566
567impl Dialog {
568 pub fn title(mut self, title: impl Into<String>) -> Self {
570 self.title = Some(title.into());
571 self
572 }
573
574 pub fn filter(mut self, name: impl Into<String>, extensions: &[&str]) -> Self {
576 self.filters.push((
577 name.into(),
578 extensions
579 .iter()
580 .map(|&extension| extension.to_owned())
581 .collect(),
582 ));
583 self
584 }
585
586 pub fn directory(mut self, directory: impl Into<PathBuf>) -> Self {
588 self.directory = Some(directory.into());
589 self
590 }
591
592 pub fn file_name(mut self, name: impl Into<String>) -> Self {
594 self.file_name = Some(name.into());
595 self
596 }
597
598 pub async fn open_file(self) -> Option<PathBuf> {
600 #[cfg(feature = "testing")]
601 if let Some(paths) = self.fake_answer(crate::testing::DialogKind::OpenFile) {
602 return paths?.into_iter().next();
603 }
604 self.system()
605 .pick_file()
606 .await
607 .map(|file| file.path().to_owned())
608 }
609
610 pub async fn open_files(self) -> Option<Vec<PathBuf>> {
612 #[cfg(feature = "testing")]
613 if let Some(paths) = self.fake_answer(crate::testing::DialogKind::OpenFiles) {
614 return paths;
615 }
616 self.system()
617 .pick_files()
618 .await
619 .map(|files| files.iter().map(|file| file.path().to_owned()).collect())
620 }
621
622 pub async fn pick_folder(self) -> Option<PathBuf> {
624 #[cfg(feature = "testing")]
625 if let Some(paths) = self.fake_answer(crate::testing::DialogKind::PickFolder) {
626 return paths?.into_iter().next();
627 }
628 self.system()
629 .pick_folder()
630 .await
631 .map(|folder| folder.path().to_owned())
632 }
633
634 pub async fn save_file(self) -> Option<PathBuf> {
637 #[cfg(feature = "testing")]
638 if let Some(paths) = self.fake_answer(crate::testing::DialogKind::SaveFile) {
639 return paths?.into_iter().next();
640 }
641 self.system()
642 .save_file()
643 .await
644 .map(|file| file.path().to_owned())
645 }
646
647 #[cfg(feature = "testing")]
651 #[expect(
652 clippy::option_option,
653 reason = "the outer layer is who answers and the inner one is the answer"
654 )]
655 fn fake_answer(&self, kind: crate::testing::DialogKind) -> Option<Option<Vec<PathBuf>>> {
656 match &self.os.inner {
657 Inner::System(_) => None,
658 Inner::Fake(fake) => Some(lock(fake).answer_dialog(crate::testing::ShownDialog {
659 kind,
660 title: self.title.clone(),
661 filters: self.filters.clone(),
662 directory: self.directory.clone(),
663 file_name: self.file_name.clone(),
664 })),
665 }
666 }
667
668 fn system(self) -> rfd::AsyncFileDialog {
669 let mut dialog = rfd::AsyncFileDialog::new();
670 if let Some(title) = self.title {
671 dialog = dialog.set_title(title);
672 }
673 for (name, extensions) in self.filters {
674 dialog = dialog.add_filter(name, &extensions);
675 }
676 if let Some(directory) = self.directory {
677 dialog = dialog.set_directory(directory);
678 }
679 if let Some(name) = self.file_name {
680 dialog = dialog.set_file_name(name);
681 }
682 dialog
683 }
684}
685
686#[derive(Debug, Clone, Copy)]
693pub struct Autostart<'a> {
694 os: &'a Os,
695}
696
697impl Autostart<'_> {
698 pub async fn enable(&self) -> Result<(), Error> {
705 match &self.os.inner {
706 Inner::System(_) => {
707 crate::autostart::with_entry(self.os.id, auto_launch::AutoLaunch::enable).await
708 }
709 #[cfg(feature = "testing")]
710 Inner::Fake(fake) => {
711 lock(fake).autostart = true;
712 Ok(())
713 }
714 }
715 }
716
717 pub async fn disable(&self) -> Result<(), Error> {
724 match &self.os.inner {
725 Inner::System(_) => {
726 crate::autostart::with_entry(self.os.id, auto_launch::AutoLaunch::disable).await
727 }
728 #[cfg(feature = "testing")]
729 Inner::Fake(fake) => {
730 lock(fake).autostart = false;
731 Ok(())
732 }
733 }
734 }
735
736 pub async fn is_enabled(&self) -> Result<bool, Error> {
743 match &self.os.inner {
744 Inner::System(_) => {
745 crate::autostart::with_entry(self.os.id, auto_launch::AutoLaunch::is_enabled).await
746 }
747 #[cfg(feature = "testing")]
748 Inner::Fake(fake) => Ok(lock(fake).autostart),
749 }
750 }
751}
752
753#[derive(Debug, Clone, Copy)]
755pub struct Clipboard<'a> {
756 os: &'a Os,
757}
758
759impl Clipboard<'_> {
760 pub async fn read_text(&self) -> Result<Option<String>, Error> {
766 match &self.os.inner {
767 Inner::System(_) => clipboard::read().await,
768 #[cfg(feature = "testing")]
769 Inner::Fake(fake) => Ok(lock(fake).clipboard.clone()),
770 }
771 }
772
773 pub async fn write_text(&self, text: impl Into<String>) -> Result<(), Error> {
779 match &self.os.inner {
780 Inner::System(_) => clipboard::write(text.into()).await,
781 #[cfg(feature = "testing")]
782 Inner::Fake(fake) => {
783 lock(fake).clipboard = Some(text.into());
784 Ok(())
785 }
786 }
787 }
788}
789
790#[cfg(test)]
791mod tests {
792 use super::is_external;
793
794 #[test]
795 fn only_an_absolute_url_is_external() {
796 for url in [
797 "https://example.com",
798 "HTTP://example.com/a",
799 "mailto:a@example.com",
800 ] {
801 assert!(is_external(url), "{url}");
802 }
803 for url in ["/notes", "notes", "//example.com", "file:///etc", ""] {
804 assert!(!is_external(url), "{url}");
805 }
806 }
807}