forked from orhun/runst
/
dbus.rs
277 lines (255 loc) · 8.56 KB
/
dbus.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use crate::error::{self, Error};
use crate::notification::{Notification, Action};
use dbus::arg::{RefArg, Variant};
use dbus::blocking::stdintf::org_freedesktop_dbus::RequestNameReply;
use dbus::blocking::{Connection, Proxy};
use dbus::channel::MatchingReceiver;
use dbus::message::MatchRule;
use dbus::MethodErr;
use dbus_crossroads::Crossroads;
use log::{trace, debug};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::mpsc::Sender;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
/// D-Bus server information.
///
/// Specifically, the server name, vendor, version, and spec version.
const SERVER_INFO: [&str; 4] = [
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_AUTHORS"),
env!("CARGO_PKG_VERSION"),
"1.2",
];
/// D-Bus server capabilities.
///
/// - `actions`: The server will provide the specified actions to the user.
/// - `body`: Supports body text.
const SERVER_CAPABILITIES: [&str; 2] = ["actions", "body"];
mod dbus_server {
#![allow(clippy::too_many_arguments)]
include!(concat!(env!("OUT_DIR"), "/introspection.rs"));
}
/// ID counter for the notification.
static ID_COUNT: AtomicU32 = AtomicU32::new(1);
/// D-Bus interface for desktop notifications.
const NOTIFICATION_INTERFACE: &str = "org.freedesktop.Notifications";
/// D-Bus path for desktop notifications.
const NOTIFICATION_PATH: &str = "/org/freedesktop/Notifications";
/// D-Bus notification implementation.
///
/// <https://specifications.freedesktop.org/notification-spec/latest/ar01s09.html>
pub struct DbusNotification {
sender: Sender<Action>,
}
impl dbus_server::OrgFreedesktopNotifications for DbusNotification {
fn get_capabilities(&mut self) -> Result<Vec<String>, dbus::MethodErr> {
Ok(SERVER_CAPABILITIES.into_iter().map(String::from).collect())
}
fn notify(
&mut self,
application: String,
replaces_id: u32,
icon: String,
summary: String,
body: String,
actions: Vec<String>,
hints: dbus::arg::PropMap,
_expire_timeout: i32,
) -> Result<u32, dbus::MethodErr> {
let id = if replaces_id == 0 {
ID_COUNT.fetch_add(1, Ordering::Relaxed)
} else {
replaces_id
};
let notification = Notification {
id,
summary,
body,
application,
icon,
urgency: hints
.get("urgency")
.and_then(|v| v.as_u64())
.map(|v| v.into())
.unwrap_or_default(),
actions,
hints: hints
.into_iter()
.map(|(k, v)| (k, v.as_str().unwrap_or_default().to_string()))
.collect(),
timestamp: SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|e| dbus::MethodErr::failed(&e))?
.as_secs(),
};
debug!("Received notification {} from dbus", notification.id);
match self.sender.send(Action::Show(notification)) {
Ok(_) => Ok(id),
Err(e) => Err(dbus::MethodErr::failed(&e)),
}
}
fn close_notification(&mut self, id: u32) -> Result<(), dbus::MethodErr> {
debug!("Received close signal for notification {}", id);
match self.sender.send(Action::Close(Some(id))) {
Ok(_) => Ok(()),
Err(e) => Err(dbus::MethodErr::failed(&e)),
}
}
fn get_server_information(
&mut self,
) -> Result<(String, String, String, String), dbus::MethodErr> {
Ok((
SERVER_INFO[0].to_string(),
SERVER_INFO[1].to_string(),
SERVER_INFO[2].to_string(),
SERVER_INFO[3].to_string(),
))
}
}
/// Wrapper for a [`D-Bus connection`] and [`server`] handler.
///
/// [`D-Bus connection`]: Connection
/// [`server`]: Crossroads
pub struct DbusServer {
/// Connection to D-Bus.
connection: Connection,
/// Server handler.
crossroads: Crossroads,
}
impl DbusServer {
/// Initializes the D-Bus controller.
pub fn init() -> error::Result<Self> {
debug!("D-Bus server information: {:#?}", SERVER_INFO);
debug!("D-Bus server capabilities: {:?}", SERVER_CAPABILITIES);
let connection = Connection::new_session()?;
let crossroads = Crossroads::new();
Ok(Self {
connection,
crossroads,
})
}
/// Registers a handler for handling D-Bus notifications.
///
/// Handles the incoming messages in a blocking manner.
pub fn register_notification_handler(
mut self,
sender: Sender<Action>,
timeout: Duration,
) -> Result<(), Error> {
let reply = self.connection
.request_name(NOTIFICATION_INTERFACE, false, true, false)?;
if reply != RequestNameReply::PrimaryOwner {
return Err(error::Error::InitializationError);
}
let token = dbus_server::register_org_freedesktop_notifications(&mut self.crossroads);
self.crossroads.insert(
NOTIFICATION_PATH,
&[token],
DbusNotification {
sender: sender.clone(),
},
);
let token = self.crossroads.register(NOTIFICATION_INTERFACE, |builder| {
let sender_cloned = sender.clone();
builder.method("History", (), ("reply",), move |_, _, ()| {
sender_cloned
.send(Action::ShowLast)
.map_err(|e| MethodErr::failed(&e))?;
Ok((String::from("history signal sent"),))
});
let sender_cloned = sender.clone();
builder.method("Close", (), ("reply",), move |_, _, (): ()| {
sender_cloned
.send(Action::Close(None))
.map_err(|e| MethodErr::failed(&e))?;
Ok((String::from("close signal sent"),))
});
builder.method("CloseAll", (), ("reply",), move |_, _, ()| {
sender
.send(Action::CloseAll)
.map_err(|e| MethodErr::failed(&e))?;
Ok((String::from("close all signal sent"),))
});
});
self.crossroads
.insert(format!("{NOTIFICATION_PATH}/ctl"), &[token], ());
self.connection.start_receive(
MatchRule::new_method_call(),
Box::new(move |message, connection| {
self.crossroads
.handle_message(message, connection)
.expect("failed to handle message");
true
}),
);
loop {
self.connection.process(timeout)?;
}
}
}
/// Wrapper for a [`D-Bus connection`] without the server part.
///
/// [`D-Bus connection`]: Connection
pub struct DbusClient {
/// Connection to D-Bus.
connection: Connection,
}
unsafe impl Send for DbusClient {}
unsafe impl Sync for DbusClient {}
impl DbusClient {
/// Initializes the D-Bus controller.
pub fn init() -> error::Result<Self> {
let connection = Connection::new_session()?;
Ok(Self { connection })
}
/// Sends a notification.
///
/// See `org.freedesktop.Notifications.Notify`
pub fn notify<S: Into<String>>(
&self,
app_name: S,
summary: S,
body: S,
expire_timeout: i32,
) -> error::Result<()> {
let proxy = Proxy::new(
NOTIFICATION_INTERFACE,
NOTIFICATION_PATH,
Duration::from_millis(1000),
&self.connection,
);
proxy.method_call(
NOTIFICATION_INTERFACE,
"Notify",
(
app_name.into(),
0_u32,
String::new(),
summary.into(),
body.into(),
Vec::<String>::new(),
{
let mut hints = HashMap::<String, Variant<Box<dyn RefArg + 'static>>>::new();
hints.insert(String::from("urgency"), Variant(Box::new(0_u8)));
hints
},
expire_timeout,
),
)?;
Ok(())
}
/// Closes the notification.
///
/// See `org.freedesktop.Notifications.CloseNotification`
pub fn close_notification(&self, id: u32, timeout: Duration) -> error::Result<()> {
let proxy = Proxy::new(
NOTIFICATION_INTERFACE,
NOTIFICATION_PATH,
timeout,
&self.connection,
);
proxy.method_call(NOTIFICATION_INTERFACE, "CloseNotification", (id,))?;
Ok(())
}
}