Skip to main content

hypersig_desktop/
item.rs

1//! The items of the menus the application builds, in the menu bar and in
2//! the tray, whose clicks reach the code that holds them.
3
4use std::fmt;
5
6use tokio::sync::broadcast;
7use tray_icon::menu::MenuId;
8
9/// An item of a menu, whose [`clicks`](Self::clicks) the application waits on.
10///
11/// It goes in a [`Menu`](crate::Menu) of the menu bar or in a
12/// [`Tray`](crate::Tray)'s menu, and its clicks reach only the code that
13/// holds it, since no item is named by a string.
14#[derive(Clone)]
15pub struct MenuItem {
16    pub(crate) id: MenuId,
17    pub(crate) label: String,
18    pub(crate) clicked: broadcast::Sender<()>,
19}
20
21impl fmt::Debug for MenuItem {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        f.debug_struct("MenuItem")
24            .field("label", &self.label)
25            .finish_non_exhaustive()
26    }
27}
28
29impl MenuItem {
30    /// An item labeled `label`.
31    pub fn new(label: impl Into<String>) -> Self {
32        Self {
33            id: MenuId::new(format!("hypersig-desktop-item-{}", next_id())),
34            label: label.into(),
35            clicked: broadcast::channel(16).0,
36        }
37    }
38
39    /// The clicks on this item that come after this call.
40    #[must_use]
41    pub fn clicks(&self) -> Clicks {
42        Clicks {
43            receiver: self.clicked.subscribe(),
44        }
45    }
46}
47
48/// The clicks on a [`MenuItem`], from [`MenuItem::clicks`].
49#[derive(Debug)]
50pub struct Clicks {
51    receiver: broadcast::Receiver<()>,
52}
53
54impl Clicks {
55    /// Waits for the next click, and returns `false` once the item is gone.
56    pub async fn next(&mut self) -> bool {
57        loop {
58            match self.receiver.recv().await {
59                Ok(()) => return true,
60                Err(broadcast::error::RecvError::Lagged(_)) => {}
61                Err(broadcast::error::RecvError::Closed) => return false,
62            }
63        }
64    }
65}
66
67/// A number no other item of this run has, for its menu id.
68fn next_id() -> u64 {
69    use std::sync::atomic::{AtomicU64, Ordering};
70    static NEXT: AtomicU64 = AtomicU64::new(0);
71    NEXT.fetch_add(1, Ordering::Relaxed)
72}