| 1 | use dbus::{ |
| 2 | arg::messageitem::{MessageItem, MessageItemArray}, |
| 3 | ffidisp::{BusType, Connection, ConnectionItem}, |
| 4 | Message, |
| 5 | }; |
| 6 | |
| 7 | use super::{bus::NotificationBus, NOTIFICATION_INTERFACE}; |
| 8 | use crate::response::{CloseReason, NotificationResponse, ResponseHandler}; |
| 9 | |
| 10 | use crate::{ |
| 11 | error::*, |
| 12 | hints::message::HintMessage, |
| 13 | notification::Notification, |
| 14 | xdg::{ServerInformation, NOTIFICATION_OBJECTPATH}, |
| 15 | }; |
| 16 | |
| 17 | pub mod bus { |
| 18 | |
| 19 | use crate::xdg::NOTIFICATION_DEFAULT_BUS; |
| 20 | |
| 21 | fn skip_first_slash(s: &str) -> &str { |
| 22 | if let Some('/') = s.chars().next() { |
| 23 | &s[1..] |
| 24 | } else { |
| 25 | s |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | use std::path::PathBuf; |
| 30 | |
| 31 | type BusNameType = dbus::strings::BusName<'static>; |
| 32 | |
| 33 | #[derive(Clone, Debug)] |
| 34 | pub struct NotificationBus(BusNameType); |
| 35 | |
| 36 | impl Default for NotificationBus { |
| 37 | fn default() -> Self { |
| 38 | Self(dbus::strings::BusName::from_slice(NOTIFICATION_DEFAULT_BUS).unwrap()) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | impl NotificationBus { |
| 43 | fn namespaced_custom(custom_path: &str) -> Option<String> { |
| 44 | // abusing path for semantic join |
| 45 | skip_first_slash( |
| 46 | PathBuf::from("/de/hoodie/Notification") |
| 47 | .join(custom_path) |
| 48 | .to_str()?, |
| 49 | ) |
| 50 | .replace('/', ".") |
| 51 | .into() |
| 52 | } |
| 53 | |
| 54 | pub fn custom(custom_path: &str) -> Option<Self> { |
| 55 | let name = dbus::strings::BusName::new(Self::namespaced_custom(custom_path)?).ok()?; |
| 56 | Some(Self(name)) |
| 57 | } |
| 58 | |
| 59 | pub fn into_name(self) -> BusNameType { |
| 60 | self.0 |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /// A handle to a shown notification. |
| 66 | /// |
| 67 | /// This keeps a connection alive to ensure actions work on certain desktops. |
| 68 | #[derive(Debug)] |
| 69 | pub struct DbusNotificationHandle { |
| 70 | pub(crate) id: u32, |
| 71 | pub(crate) connection: Connection, |
| 72 | pub(crate) notification: Notification, |
| 73 | } |
| 74 | |
| 75 | impl DbusNotificationHandle { |
| 76 | pub(crate) fn new( |
| 77 | id: u32, |
| 78 | connection: Connection, |
| 79 | notification: Notification, |
| 80 | ) -> DbusNotificationHandle { |
| 81 | DbusNotificationHandle { |
| 82 | id, |
| 83 | connection, |
| 84 | notification, |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | pub fn wait_for_action(self, invocation_closure: impl ResponseHandler) -> Result<()> { |
| 89 | wait_for_action_signal(&self.connection, self.id, invocation_closure) |
| 90 | } |
| 91 | |
| 92 | pub fn close(self) { |
| 93 | let mut message = build_message("CloseNotification", Default::default()); |
| 94 | message.append_items(&[self.id.into()]); |
| 95 | let _ = self.connection.send(message); // If closing fails there's nothing we could do anyway |
| 96 | } |
| 97 | |
| 98 | pub fn on_close<F>(self, closure: F) -> Result<()> |
| 99 | where |
| 100 | F: FnOnce(CloseReason), |
| 101 | { |
| 102 | self.wait_for_action(|action: &NotificationResponse| { |
| 103 | if let NotificationResponse::Closed(reason) = action { |
| 104 | closure(*reason); |
| 105 | } |
| 106 | }) |
| 107 | } |
| 108 | |
| 109 | pub fn update(&mut self) -> Result<()> { |
| 110 | self.id = send_notification_via_connection(&self.notification, self.id, &self.connection)?; |
| 111 | Ok(()) |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | pub fn send_notification_via_connection( |
| 116 | notification: &Notification, |
| 117 | id: u32, |
| 118 | connection: &Connection, |
| 119 | ) -> Result<u32> { |
| 120 | send_notification_via_connection_at_bus(notification, id, connection, Default::default()) |
| 121 | } |
| 122 | |
| 123 | pub fn send_notification_via_connection_at_bus( |
| 124 | notification: &Notification, |
| 125 | id: u32, |
| 126 | connection: &Connection, |
| 127 | bus: NotificationBus, |
| 128 | ) -> Result<u32> { |
| 129 | let mut message = build_message("Notify", bus); |
| 130 | let timeout: i32 = notification.timeout.into(); |
| 131 | message.append_items(&[ |
| 132 | notification.appname.to_owned().into(), // appname |
| 133 | id.into(), // notification to update |
| 134 | notification.icon.to_owned().into(), // icon |
| 135 | notification.summary.to_owned().into(), // summary (title) |
| 136 | notification.body.to_owned().into(), // body |
| 137 | pack_actions(notification), // actions |
| 138 | pack_hints(notification)?, // hints |
| 139 | timeout.into(), // timeout |
| 140 | ]); |
| 141 | |
| 142 | let reply = connection.send_with_reply_and_block(message, 2000)?; |
| 143 | |
| 144 | match reply.get_items().first() { |
| 145 | Some(MessageItem::UInt32(ref id)) => Ok(*id), |
| 146 | _ => Ok(0), |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | pub fn connect_and_send_notification( |
| 151 | notification: &Notification, |
| 152 | ) -> Result<DbusNotificationHandle> { |
| 153 | let bus = notification.bus.clone(); |
| 154 | connect_and_send_notification_at_bus(notification, bus) |
| 155 | } |
| 156 | |
| 157 | pub fn connect_and_send_notification_at_bus( |
| 158 | notification: &Notification, |
| 159 | bus: NotificationBus, |
| 160 | ) -> Result<DbusNotificationHandle> { |
| 161 | let connection = Connection::get_private(BusType::Session)?; |
| 162 | let inner_id = notification.id.unwrap_or(0); |
| 163 | let id = send_notification_via_connection_at_bus(notification, inner_id, &connection, bus)?; |
| 164 | |
| 165 | Ok(DbusNotificationHandle::new( |
| 166 | id, |
| 167 | connection, |
| 168 | notification.clone(), |
| 169 | )) |
| 170 | } |
| 171 | |
| 172 | fn build_message(method_name: &str, bus: NotificationBus) -> Message { |
| 173 | Message::new_method_call( |
| 174 | bus.into_name(), |
| 175 | NOTIFICATION_OBJECTPATH, |
| 176 | NOTIFICATION_INTERFACE, |
| 177 | method_name, |
| 178 | ) |
| 179 | .unwrap_or_else(|_| panic!("Error building message call {:?}.", method_name)) |
| 180 | } |
| 181 | |
| 182 | pub fn pack_hints(notification: &Notification) -> Result<MessageItem> { |
| 183 | if !notification.hints.is_empty() || !notification.hints_unique.is_empty() { |
| 184 | let hints = notification |
| 185 | .get_hints() |
| 186 | .cloned() |
| 187 | .map(HintMessage::wrap_hint) |
| 188 | .collect::<Vec<(MessageItem, MessageItem)>>(); |
| 189 | |
| 190 | if let Ok(array) = MessageItem::new_dict(hints) { |
| 191 | return Ok(array); |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | Ok(MessageItem::Array( |
| 196 | MessageItemArray::new(vec![], "a{sv}".into()).unwrap(), |
| 197 | )) |
| 198 | } |
| 199 | |
| 200 | pub fn pack_actions(notification: &Notification) -> MessageItem { |
| 201 | if !notification.actions.is_empty() { |
| 202 | let mut actions = vec![]; |
| 203 | for action in ¬ification.actions { |
| 204 | actions.push(action.to_owned().into()); |
| 205 | } |
| 206 | if let Ok(array) = MessageItem::new_array(actions) { |
| 207 | return array; |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | MessageItem::Array(MessageItemArray::new(vec![], "as".into()).unwrap()) |
| 212 | } |
| 213 | |
| 214 | pub fn get_capabilities() -> Result<Vec<String>> { |
| 215 | let mut capabilities = vec![]; |
| 216 | |
| 217 | let message = build_message("GetCapabilities", Default::default()); |
| 218 | let connection = Connection::get_private(BusType::Session)?; |
| 219 | let reply = connection.send_with_reply_and_block(message, 2000)?; |
| 220 | |
| 221 | if let Some(MessageItem::Array(items)) = reply.get_items().first() { |
| 222 | for item in items.iter() { |
| 223 | if let MessageItem::Str(ref cap) = *item { |
| 224 | capabilities.push(cap.clone()); |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | Ok(capabilities) |
| 230 | } |
| 231 | |
| 232 | fn unwrap_message_string(item: Option<&MessageItem>) -> String { |
| 233 | match item { |
| 234 | Some(MessageItem::Str(value)) => value.to_owned(), |
| 235 | _ => "".to_owned(), |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | #[allow(clippy::get_first)] |
| 240 | pub fn get_server_information() -> Result<ServerInformation> { |
| 241 | let message = build_message("GetServerInformation", Default::default()); |
| 242 | let connection = Connection::get_private(BusType::Session)?; |
| 243 | let reply = connection.send_with_reply_and_block(message, 2000)?; |
| 244 | |
| 245 | let items = reply.get_items(); |
| 246 | |
| 247 | Ok(ServerInformation { |
| 248 | name: unwrap_message_string(items.get(0)), |
| 249 | vendor: unwrap_message_string(items.get(1)), |
| 250 | version: unwrap_message_string(items.get(2)), |
| 251 | spec_version: unwrap_message_string(items.get(3)), |
| 252 | }) |
| 253 | } |
| 254 | |
| 255 | /// Listens for the `ActionInvoked(UInt32, String)` Signal. |
| 256 | /// |
| 257 | /// No need to use this, check out `Notification::show_and_wait_for_action(FnOnce(action:&str))` |
| 258 | pub fn handle_action(id: u32, func: impl ResponseHandler) -> Result<()> { |
| 259 | let connection = Connection::get_private(BusType::Session)?; |
| 260 | wait_for_action_signal(&connection, id, func) |
| 261 | } |
| 262 | |
| 263 | // Listens for the `ActionInvoked(UInt32, String)` signal. |
| 264 | fn wait_for_action_signal( |
| 265 | connection: &Connection, |
| 266 | id: u32, |
| 267 | handler: impl ResponseHandler, |
| 268 | ) -> Result<()> { |
| 269 | connection.add_match(&format!( |
| 270 | "interface='{}',member='ActionInvoked'", |
| 271 | NOTIFICATION_INTERFACE |
| 272 | ))?; |
| 273 | connection.add_match(&format!( |
| 274 | "interface='{}',member='NotificationClosed'", |
| 275 | NOTIFICATION_INTERFACE |
| 276 | ))?; |
| 277 | |
| 278 | for item in connection.iter(1000) { |
| 279 | if let ConnectionItem::Signal(message) = item { |
| 280 | let items = message.get_items(); |
| 281 | |
| 282 | let (path, interface, member) = ( |
| 283 | message.path().map_or_else(String::new, |p| { |
| 284 | p.into_cstring().to_string_lossy().into_owned() |
| 285 | }), |
| 286 | message.interface().map_or_else(String::new, |p| { |
| 287 | p.into_cstring().to_string_lossy().into_owned() |
| 288 | }), |
| 289 | message.member().map_or_else(String::new, |p| { |
| 290 | p.into_cstring().to_string_lossy().into_owned() |
| 291 | }), |
| 292 | ); |
| 293 | match (path.as_str(), interface.as_str(), member.as_str()) { |
| 294 | // match (protocol.unwrap(), iface.unwrap(), member.unwrap()) { |
| 295 | // Action Invoked |
| 296 | (path, interface, "ActionInvoked") |
| 297 | if path == NOTIFICATION_OBJECTPATH && interface == NOTIFICATION_INTERFACE => |
| 298 | { |
| 299 | if let (&MessageItem::UInt32(nid), MessageItem::Str(ref action)) = |
| 300 | (&items[0], &items[1]) |
| 301 | { |
| 302 | if nid == id { |
| 303 | let response = if action == "default" { |
| 304 | NotificationResponse::Default |
| 305 | } else { |
| 306 | NotificationResponse::Action(action.to_string()) |
| 307 | }; |
| 308 | handler.call(&response); |
| 309 | break; |
| 310 | } |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | // Notification Closed |
| 315 | (path, interface, "NotificationClosed") |
| 316 | if path == NOTIFICATION_OBJECTPATH && interface == NOTIFICATION_INTERFACE => |
| 317 | { |
| 318 | if let (&MessageItem::UInt32(nid), &MessageItem::UInt32(reason)) = |
| 319 | (&items[0], &items[1]) |
| 320 | { |
| 321 | if nid == id { |
| 322 | handler.call(&NotificationResponse::Closed(reason.into())); |
| 323 | break; |
| 324 | } |
| 325 | } |
| 326 | } |
| 327 | (..) => (), |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | Ok(()) |
| 332 | } |