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)]
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)]
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)]
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 fn from_array(array: &Array) -> Result<Vec<Self>> {
150 array
151 .iter()
152 .map(|pixmap| {
153 let structure = pixmap.downcast_ref::<&Structure>()?;
154 let fields = structure.fields();
155
156 let width = fields
157 .first()
158 .ok_or(Error::InvalidData("invalid or missing width"))?
159 .downcast_ref::<i32>()?;
160
161 let height = fields
162 .first()
163 .ok_or(Error::InvalidData("invalid or missing width"))?
164 .downcast_ref::<i32>()?;
165
166 let pixel_values = fields
167 .get(2)
168 .ok_or(Error::InvalidData("invalid or missing pixel values"))?
169 .downcast_ref::<&Array>()?;
170
171 let pixels = pixel_values
172 .iter()
173 .map(|p| p.downcast_ref::<u8>().map_err(Into::into))
174 .collect::<Result<_>>()?;
175
176 Ok(IconPixmap {
177 width,
178 height,
179 pixels,
180 })
181 })
182 .collect()
183 }
184}
185
186/// Data structure that describes extra information associated to this item, that can be visualized for instance by a tooltip
187/// (or by any other mean the visualization consider appropriate.
188#[derive(Debug, Clone, Deserialize)]
189pub struct Tooltip {
190 pub icon_name: String,
191 pub icon_data: Vec<IconPixmap>,
192 pub title: String,
193 pub description: String,
194}
195
196impl TryFrom<&Structure<'_>> for Tooltip {
197 type Error = Error;
198
199 fn try_from(value: &Structure) -> Result<Self> {
200 let fields = value.fields();
201
202 Ok(Self {
203 icon_name: fields
204 .first()
205 .ok_or(Error::InvalidData("icon_name"))?
206 .downcast_ref::<&str>()
207 .map(ToString::to_string)?,
208
209 icon_data: fields
210 .get(1)
211 .ok_or(Error::InvalidData("icon_data"))?
212 .downcast_ref::<&Array>()
213 .map_err(Into::into)
214 .and_then(IconPixmap::from_array)?,
215
216 title: fields
217 .get(2)
218 .ok_or(Error::InvalidData("title"))?
219 .downcast_ref::<&str>()
220 .map(ToString::to_string)?,
221
222 description: fields
223 .get(3)
224 .ok_or(Error::InvalidData("description"))?
225 .downcast_ref::<&str>()
226 .map(ToString::to_string)?,
227 })
228 }
229}
230
231impl TryFrom<DBusProps> for StatusNotifierItem {
232 type Error = Error;
233
234 fn try_from(props: DBusProps) -> Result<Self> {
235 if let Some(id) = props.get_string("Id") {
236 let id = id?;
237 Ok(Self {
238 id,
239 title: props.get_string("Title").transpose()?,
240 status: props.get_status()?,
241 window_id: props
242 .get::<i32>("WindowId")
243 .transpose()?
244 .copied()
245 .unwrap_or_default() as u32,
246 icon_theme_path: props.get_string("IconThemePath").transpose()?,
247 icon_name: props.get_string("IconName").transpose()?,
248 icon_pixmap: props.get_icon_pixmap("IconPixmap").transpose()?,
249 overlay_icon_name: props.get_string("OverlayIconName").transpose()?,
250 overlay_icon_pixmap: props.get_icon_pixmap("OverlayIconPixmap").transpose()?,
251 attention_icon_name: props.get_string("AttentionIconName").transpose()?,
252 attention_icon_pixmap: props.get_icon_pixmap("AttentionIconPixmap").transpose()?,
253 attention_movie_name: props.get_string("AttentionMovieName").transpose()?,
254 tool_tip: props.get_tooltip().transpose()?,
255 item_is_menu: props
256 .get("ItemIsMenu")
257 .transpose()?
258 .copied()
259 .unwrap_or_default(),
260 category: props.get_category()?,
261 menu: props.get_object_path("Menu").transpose()?,
262 })
263 } else {
264 Err(Error::MissingProperty("Id"))
265 }
266 }
267}
268
269impl DBusProps {
270 fn get_category(&self) -> Result<Category> {
271 Ok(self
272 .get::<str>("Category")
273 .transpose()?
274 .map(Category::from)
275 .unwrap_or_default())
276 }
277
278 fn get_status(&self) -> Result<Status> {
279 Ok(self
280 .get::<str>("Status")
281 .transpose()?
282 .map(Status::from)
283 .unwrap_or_default())
284 }
285
286 fn get_icon_pixmap(&self, key: &str) -> Option<Result<Vec<IconPixmap>>> {
287 self.get::<Array>(key)
288 .map(|arr| arr.and_then(IconPixmap::from_array))
289 }
290
291 fn get_tooltip(&self) -> Option<Result<Tooltip>> {
292 self.get::<Structure>("ToolTip")
293 .map(|t| t.and_then(Tooltip::try_from))
294 }
295}