system_tray/item.rs
1use crate::dbus::DBusProps;
2use crate::error::{Error, Result};
3use serde::Deserialize;
4use std::fmt::{Debug, Formatter};
5use zbus::zvariant::{Array, Structure};
6
7/// Represents an item to display inside the tray.
8/// <https://www.freedesktop.org/wiki/Specifications/StatusNotifierItem/StatusNotifierItem/>
9#[derive(Deserialize, Debug, Clone)]
10pub struct StatusNotifierItem {
11 /// A name that should be unique for this application and consistent between sessions, such as the application name itself.
12 pub id: String,
13
14 /// The category of this item.
15 ///
16 /// The allowed values for the Category property are:
17 ///
18 /// - `ApplicationStatus`: The item describes the status of a generic application, for instance the current state of a media player.
19 /// In the case where the category of the item can not be known, such as when the item is being proxied from another incompatible or emulated system,
20 /// `ApplicationStatus` can be used a sensible default fallback.
21 /// - `Communications`: The item describes the status of communication oriented applications, like an instant messenger or an email client.
22 /// - `SystemServices`: The item describes services of the system not seen as a stand alone application by the user, such as an indicator for the activity of a disk indexing service.
23 /// - `Hardware`: The item describes the state and control of a particular hardware, such as an indicator of the battery charge or sound card volume control.
24 pub category: Category,
25
26 /// A name that describes the application, it can be more descriptive than Id.
27 pub title: Option<String>,
28
29 /// Describes the status of this item or of the associated application.
30 ///
31 /// The allowed values for the Status property are:
32 ///
33 /// - Passive: The item doesn't convey important information to the user, it can be considered an "idle" status and is likely that visualizations will chose to hide it.
34 /// - Active: The item is active, is more important that the item will be shown in some way to the user.
35 /// - `NeedsAttention`: The item carries really important information for the user, such as battery charge running out and is wants to incentive the direct user intervention.
36 /// Visualizations should emphasize in some way the items with `NeedsAttention` status.
37 pub status: Status,
38
39 /// The windowing-system dependent identifier for a window, the application can choose one of its windows to be available through this property or just set 0 if it's not interested.
40 pub window_id: u32,
41
42 pub icon_theme_path: Option<String>,
43
44 /// The `StatusNotifierItem` can carry an icon that can be used by the visualization to identify the item.
45 ///
46 /// An icon can either be identified by its Freedesktop-compliant icon name, carried by this property of by the icon data itself, carried by the property `IconPixmap`.
47 /// Visualizations are encouraged to prefer icon names over icon pixmaps if both are available
48 /// (still not very defined: could be the pixmap used as fallback if an icon name is not found?)
49 pub icon_name: Option<String>,
50
51 /// Carries an ARGB32 binary representation of the icon, the format of icon data used in this specification is described in Section Icons
52 ///
53 /// # Icons
54 ///
55 /// All the icons can be transferred over the bus by a particular serialization of their data,
56 /// capable of representing multiple resolutions of the same image or a brief aimation of images of the same size.
57 ///
58 /// Icons are transferred in an array of raw image data structures of signature a(iiay) whith each one describing the width, height, and image data respectively.
59 /// The data is represented in ARGB32 format and is in the network byte order, to make easy the communication over the network between little and big endian machines.
60 pub icon_pixmap: Option<Vec<IconPixmap>>,
61
62 /// The Freedesktop-compliant name of an icon.
63 /// This can be used by the visualization to indicate extra state information, for instance as an overlay for the main icon.
64 pub overlay_icon_name: Option<String>,
65
66 /// ARGB32 binary representation of the overlay icon described in the previous paragraph.
67 pub overlay_icon_pixmap: Option<Vec<IconPixmap>>,
68
69 /// The Freedesktop-compliant name of an icon. this can be used by the visualization to indicate that the item is in `RequestingAttention` state.
70 pub attention_icon_name: Option<String>,
71
72 /// ARGB32 binary representation of the requesting attention icon describe in the previous paragraph.
73 pub attention_icon_pixmap: Option<Vec<IconPixmap>>,
74
75 /// An item can also specify an animation associated to the `RequestingAttention` state.
76 /// This should be either a Freedesktop-compliant icon name or a full path.
77 /// The visualization can choose between the movie or `AttentionIconPixmap` (or using neither of those) at its discretion.
78 pub attention_movie_name: Option<String>,
79
80 /// Data structure that describes extra information associated to this item, that can be visualized for instance by a tooltip
81 /// (or by any other mean the visualization consider appropriate.
82 pub tool_tip: Option<Tooltip>,
83
84 /// The item only support the context menu, the visualization should prefer showing the menu or sending `ContextMenu()` instead of `Activate()`
85 pub item_is_menu: bool,
86
87 /// `DBus` path to an object which should implement the `com.canonical.dbusmenu` interface
88 pub menu: Option<String>,
89}
90
91#[derive(Debug, Clone, Copy, Deserialize, Default, Eq, PartialEq, Hash)]
92pub enum Category {
93 #[default]
94 ApplicationStatus,
95 Communications,
96 SystemServices,
97 Hardware,
98}
99
100impl From<&str> for Category {
101 fn from(value: &str) -> Self {
102 match value {
103 "Communications" => Self::Communications,
104 "SystemServices" => Self::SystemServices,
105 "Hardware" => Self::Hardware,
106 _ => Self::ApplicationStatus,
107 }
108 }
109}
110
111#[derive(Debug, Clone, Copy, Deserialize, Default, Eq, PartialEq, Hash)]
112pub enum Status {
113 #[default]
114 Unknown,
115 Passive,
116 Active,
117 NeedsAttention,
118}
119
120impl From<&str> for Status {
121 fn from(value: &str) -> Self {
122 match value {
123 "Passive" => Self::Passive,
124 "Active" => Self::Active,
125 "NeedsAttention" => Self::NeedsAttention,
126 _ => Self::Unknown,
127 }
128 }
129}
130
131#[derive(Deserialize, Clone, Eq, PartialEq, Hash)]
132pub struct IconPixmap {
133 pub width: i32,
134 pub height: i32,
135 pub pixels: Vec<u8>,
136}
137
138impl Debug for IconPixmap {
139 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
140 f.debug_struct("IconPixmap")
141 .field("width", &self.width)
142 .field("height", &self.height)
143 .field("pixels", &format!("<length: {}>", self.pixels.len()))
144 .finish()
145 }
146}
147
148impl IconPixmap {
149 /// Attempts to create a `Vec<IconPixmap>` from a provided `ZBus` `Array` type.
150 /// This assumes the array is actually pixmap data.
151 ///
152 /// # Errors
153 ///
154 /// An error will return if any of the fields are missing are of the wrong type,
155 /// indicating usually that the array passed in was likely not a `Pixmap`.
156 pub fn from_array(array: &Array) -> Result<Vec<Self>> {
157 array
158 .iter()
159 .map(|pixmap| {
160 let structure = pixmap.downcast_ref::<&Structure>()?;
161 let fields = structure.fields();
162
163 let width = fields
164 .first()
165 .ok_or(Error::InvalidData("invalid or missing width"))?
166 .downcast_ref::<i32>()?;
167
168 let height = fields
169 .first()
170 .ok_or(Error::InvalidData("invalid or missing width"))?
171 .downcast_ref::<i32>()?;
172
173 let pixel_values = fields
174 .get(2)
175 .ok_or(Error::InvalidData("invalid or missing pixel values"))?
176 .downcast_ref::<&Array>()?;
177
178 let pixels = pixel_values
179 .iter()
180 .map(|p| p.downcast_ref::<u8>().map_err(Into::into))
181 .collect::<Result<_>>()?;
182
183 Ok(IconPixmap {
184 width,
185 height,
186 pixels,
187 })
188 })
189 .collect()
190 }
191}
192
193/// Data structure that describes extra information associated to this item, that can be visualized for instance by a tooltip
194/// (or by any other mean the visualization consider appropriate.
195#[derive(Debug, Clone, Deserialize)]
196pub struct Tooltip {
197 pub icon_name: String,
198 pub icon_data: Vec<IconPixmap>,
199 pub title: String,
200 pub description: String,
201}
202
203impl TryFrom<&Structure<'_>> for Tooltip {
204 type Error = Error;
205
206 fn try_from(value: &Structure) -> Result<Self> {
207 let fields = value.fields();
208
209 Ok(Self {
210 icon_name: fields
211 .first()
212 .ok_or(Error::InvalidData("icon_name"))?
213 .downcast_ref::<&str>()
214 .map(ToString::to_string)?,
215
216 icon_data: fields
217 .get(1)
218 .ok_or(Error::InvalidData("icon_data"))?
219 .downcast_ref::<&Array>()
220 .map_err(Into::into)
221 .and_then(IconPixmap::from_array)?,
222
223 title: fields
224 .get(2)
225 .ok_or(Error::InvalidData("title"))?
226 .downcast_ref::<&str>()
227 .map(ToString::to_string)?,
228
229 description: fields
230 .get(3)
231 .ok_or(Error::InvalidData("description"))?
232 .downcast_ref::<&str>()
233 .map(ToString::to_string)?,
234 })
235 }
236}
237
238impl TryFrom<DBusProps> for StatusNotifierItem {
239 type Error = Error;
240
241 fn try_from(props: DBusProps) -> Result<Self> {
242 if let Some(id) = props.get_string("Id") {
243 let id = id?;
244 Ok(Self {
245 id,
246 title: props.get_string("Title").transpose()?,
247 status: props.get_status()?,
248 window_id: props
249 .get::<i32>("WindowId")
250 .transpose()?
251 .copied()
252 .unwrap_or_default() as u32,
253 icon_theme_path: props.get_string("IconThemePath").transpose()?,
254 icon_name: props.get_string("IconName").transpose()?,
255 icon_pixmap: props.get_icon_pixmap("IconPixmap").transpose()?,
256 overlay_icon_name: props.get_string("OverlayIconName").transpose()?,
257 overlay_icon_pixmap: props.get_icon_pixmap("OverlayIconPixmap").transpose()?,
258 attention_icon_name: props.get_string("AttentionIconName").transpose()?,
259 attention_icon_pixmap: props.get_icon_pixmap("AttentionIconPixmap").transpose()?,
260 attention_movie_name: props.get_string("AttentionMovieName").transpose()?,
261 tool_tip: props.get_tooltip().transpose()?,
262 item_is_menu: props
263 .get("ItemIsMenu")
264 .transpose()?
265 .copied()
266 .unwrap_or_default(),
267 category: props.get_category()?,
268 menu: props.get_object_path("Menu").transpose()?,
269 })
270 } else {
271 Err(Error::MissingProperty("Id"))
272 }
273 }
274}
275
276impl DBusProps {
277 fn get_category(&self) -> Result<Category> {
278 Ok(self
279 .get::<str>("Category")
280 .transpose()?
281 .map(Category::from)
282 .unwrap_or_default())
283 }
284
285 fn get_status(&self) -> Result<Status> {
286 Ok(self
287 .get::<str>("Status")
288 .transpose()?
289 .map(Status::from)
290 .unwrap_or_default())
291 }
292
293 fn get_icon_pixmap(&self, key: &str) -> Option<Result<Vec<IconPixmap>>> {
294 self.get::<Array>(key)
295 .map(|arr| arr.and_then(IconPixmap::from_array))
296 }
297
298 fn get_tooltip(&self) -> Option<Result<Tooltip>> {
299 self.get::<Structure>("ToolTip")
300 .map(|t| t.and_then(Tooltip::try_from))
301 }
302}