trayicon/
trayiconbuilder.rs1use crate::{trayiconsender::TrayIconSender, Icon, MenuBuilder, TrayIcon};
2use std::fmt::{Display, Formatter};
3
4#[derive(Debug, Clone, Copy, PartialEq)]
5pub enum Error {
6 MenuItemNotFound,
7 IconLoadingFailed,
8 SenderMissing,
9 IconMissing,
10 OsError,
11}
12
13impl From<&Error> for Error {
15 fn from(e: &Error) -> Self {
16 *e
17 }
18}
19
20impl Display for Error {
21 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
22 write!(f, "{}", self)
23 }
24}
25
26impl std::error::Error for Error {}
27
28#[derive(Debug, Clone)]
32pub struct TrayIconBuilder<T>
33where
34 T: PartialEq + Clone + 'static,
35{
36 pub(crate) icon: Result<Icon, Error>,
37 pub(crate) menu: Option<MenuBuilder<T>>,
38 pub(crate) tooltip: Option<String>,
39 pub(crate) on_click: Option<T>,
40 pub(crate) on_double_click: Option<T>,
41 pub(crate) on_right_click: Option<T>,
42 pub(crate) sender: Option<TrayIconSender<T>>,
43}
44
45impl<T> TrayIconBuilder<T>
46where
47 T: PartialEq + Clone + 'static,
48{
49 #[allow(clippy::new_without_default)]
50 pub fn new() -> TrayIconBuilder<T> {
51 TrayIconBuilder {
52 icon: Err(Error::IconMissing),
53 menu: None,
54 tooltip: None,
55 on_click: None,
56 on_double_click: None,
57 on_right_click: None,
58 sender: None,
59 }
60 }
61
62 pub fn when<F>(self, f: F) -> Self
64 where
65 F: FnOnce(Self) -> Self,
66 {
67 f(self)
68 }
69
70 pub fn sender(mut self, cb: impl Fn(&T) + 'static) -> Self {
71 self.sender = Some(TrayIconSender::new(cb));
72 self
73 }
74
75 pub fn tooltip(mut self, tooltip: &str) -> Self {
76 self.tooltip = Some(tooltip.to_string());
77 self
78 }
79
80 pub fn on_click(mut self, id: T) -> Self {
81 self.on_click = Some(id);
82 self
83 }
84
85 pub fn on_double_click(mut self, id: T) -> Self {
86 self.on_double_click = Some(id);
87 self
88 }
89
90 pub fn on_right_click(mut self, id: T) -> Self {
91 self.on_right_click = Some(id);
92 self
93 }
94
95 pub fn icon(mut self, icon: Icon) -> Self {
96 self.icon = Ok(icon);
97 self
98 }
99
100 pub fn icon_from_buffer(mut self, buffer: &'static [u8]) -> Self {
101 self.icon = Icon::from_buffer(buffer, None, None);
102 self
103 }
104
105 pub fn menu(mut self, menu: MenuBuilder<T>) -> Self
106 where
107 T: PartialEq + Clone + 'static,
108 {
109 self.menu = Some(menu);
110 self
111 }
112
113 pub fn build(self) -> Result<TrayIcon<T>, Error> {
114 Ok(TrayIcon::new(crate::build_trayicon(&self)?, self))
115 }
116}