krateio 1.0.0

Show job progress in the Plasma notification area via the KDE JobView D-Bus protocol
Documentation
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! Show job progress in the Plasma notification area.
//!
//! krateio talks to the KDE JobView D Bus protocol that Plasma uses to
//! display long running jobs such as file transfers or package installs.
//! It prefers the JobViewServerV2 protocol from Plasma 6 and falls back
//! to the older JobViewServer protocol when V2 is not available.
//!
//! ```no_run
//! let tracker = krateio::Tracker::new("org.blossomos.pkglayer")?
//!     .with_app_name("Package Manager")
//!     .with_app_icon("system-software-update");
//!
//! let job = tracker
//!     .job()
//!     .title("Installing packages")
//!     .cancellable(true)
//!     .start()?;
//!
//! job.set_description(1, "Package", "firefox")?;
//! job.progress(krateio::Unit::Items, 3, 10)?;
//!
//! if job.cancel_requested() {
//!     job.fail(1, "Cancelled by user")?;
//! } else {
//!     job.finish()?;
//! }
//! # krateio::Result::Ok(())
//! ```

mod proxy;

use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Weak};
use std::thread;

use zbus::blocking::Connection;
use zbus::zvariant::{OwnedObjectPath, Value};

pub use zbus::Error;

pub type Result<T> = std::result::Result<T, Error>;

const SERVICE: &str = "org.kde.JobViewServer";

/// Measurement unit for job amounts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Unit {
    Bytes,
    Files,
    Directories,
    Items,
}

impl Unit {
    fn v2_name(self) -> &'static str {
        match self {
            Unit::Bytes => "bytes",
            Unit::Files => "files",
            Unit::Directories => "dirs",
            Unit::Items => "items",
        }
    }

    fn v3_total_key(self) -> &'static str {
        match self {
            Unit::Bytes => "totalBytes",
            Unit::Files => "totalFiles",
            Unit::Directories => "totalDirectories",
            Unit::Items => "totalItems",
        }
    }

    fn v3_processed_key(self) -> &'static str {
        match self {
            Unit::Bytes => "processedBytes",
            Unit::Files => "processedFiles",
            Unit::Directories => "processedDirectories",
            Unit::Items => "processedItems",
        }
    }
}

/// Entry point that connects to the session bus and creates jobs.
pub struct Tracker {
    conn: Connection,
    desktop_entry: String,
    app_name: Option<String>,
    app_icon: Option<String>,
}

impl Tracker {
    /// Connects to the session bus.
    ///
    /// The desktop entry should match the desktop file name of the
    /// application without the extension so Plasma can show its name
    /// and icon.
    pub fn new(desktop_entry: impl Into<String>) -> Result<Self> {
        Ok(Self {
            conn: Connection::session()?,
            desktop_entry: desktop_entry.into(),
            app_name: None,
            app_icon: None,
        })
    }

    /// Display name shown when the desktop entry cannot be resolved.
    pub fn with_app_name(mut self, name: impl Into<String>) -> Self {
        self.app_name = Some(name.into());
        self
    }

    /// Icon name shown when the desktop entry cannot be resolved.
    pub fn with_app_icon(mut self, icon: impl Into<String>) -> Self {
        self.app_icon = Some(icon.into());
        self
    }

    /// Starts building a new job.
    pub fn job(&self) -> JobBuilder<'_> {
        JobBuilder {
            tracker: self,
            title: None,
            info_message: None,
            dest_url: None,
            cancellable: false,
            suspendable: false,
            transient: false,
            immediate: false,
        }
    }
}

/// Configures a job before it is shown.
pub struct JobBuilder<'a> {
    tracker: &'a Tracker,
    title: Option<String>,
    info_message: Option<String>,
    dest_url: Option<String>,
    cancellable: bool,
    suspendable: bool,
    transient: bool,
    immediate: bool,
}

impl JobBuilder<'_> {
    /// Heading of the job popup, for example Installing packages.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Status line below the title.
    pub fn info_message(mut self, message: impl Into<String>) -> Self {
        self.info_message = Some(message.into());
        self
    }

    /// Destination URL the job writes to.
    pub fn dest_url(mut self, url: impl Into<String>) -> Self {
        self.dest_url = Some(url.into());
        self
    }

    /// Lets the user request cancellation from the popup.
    pub fn cancellable(mut self, value: bool) -> Self {
        self.cancellable = value;
        self
    }

    /// Lets the user request suspend and resume from the popup.
    pub fn suspendable(mut self, value: bool) -> Self {
        self.suspendable = value;
        self
    }

    /// Hides the job from the notification history once finished.
    pub fn transient(mut self, value: bool) -> Self {
        self.transient = value;
        self
    }

    /// Shows the popup right away instead of after a short delay.
    pub fn immediate(mut self, value: bool) -> Self {
        self.immediate = value;
        self
    }

    /// Registers the job with Plasma and returns a handle for updates.
    pub fn start(self) -> Result<Job> {
        let t = self.tracker;
        // KJob capability bits are Killable 0x1 and Suspendable 0x2
        let capabilities = (self.cancellable as i32) | ((self.suspendable as i32) << 1);

        let mut hints: HashMap<String, Value> = HashMap::new();
        if let Some(v) = t.app_name.as_deref() {
            hints.insert("application-display-name".into(), v.into());
        }
        if let Some(v) = t.app_icon.as_deref() {
            hints.insert("application-icon-name".into(), v.into());
        }
        if let Some(v) = self.title.as_deref() {
            hints.insert("title".into(), v.into());
        }
        if let Some(v) = self.info_message.as_deref() {
            hints.insert("infoMessage".into(), v.into());
        }
        if let Some(v) = self.dest_url.as_deref() {
            hints.insert("destUrl".into(), v.into());
        }
        if self.transient {
            hints.insert("transient".into(), true.into());
        }
        if self.immediate {
            hints.insert("immediate".into(), true.into());
        }

        let server = proxy::JobViewServerV2ProxyBlocking::new(&t.conn)?;
        match server.request_view(&t.desktop_entry, capabilities, hints) {
            Ok(path) => Job::new_v3(&t.conn, path),
            Err(err) if interface_missing(&err) => {
                let name = t.app_name.as_deref().unwrap_or(&t.desktop_entry);
                let icon = t.app_icon.as_deref().unwrap_or_default();
                let server = proxy::JobViewServerProxyBlocking::new(&t.conn)?;
                let path = server.request_view(name, icon, capabilities)?;
                let job = Job::new_v2(&t.conn, path)?;
                if let Some(v) = self.info_message.as_deref() {
                    job.set_info_message(v)?;
                }
                if let Some(v) = self.dest_url.as_deref() {
                    job.set_dest_url(v)?;
                }
                Ok(job)
            }
            Err(err) => Err(err),
        }
    }
}

fn interface_missing(err: &Error) -> bool {
    if let Error::MethodError(name, _, _) = err {
        matches!(
            name.as_str(),
            "org.freedesktop.DBus.Error.UnknownInterface"
                | "org.freedesktop.DBus.Error.UnknownMethod"
                | "org.freedesktop.DBus.Error.UnknownObject"
        )
    } else {
        false
    }
}

#[derive(Default)]
struct Flags {
    cancel: AtomicBool,
    suspend: AtomicBool,
}

enum View {
    V3(proxy::JobViewV3ProxyBlocking<'static>),
    V2(proxy::JobViewV2ProxyBlocking<'static>),
}

/// Handle for a job shown in the Plasma notification area.
///
/// The job is terminated as successful when the handle is dropped
/// without an explicit call to finish or fail.
pub struct Job {
    view: View,
    flags: Arc<Flags>,
    done: bool,
}

impl Job {
    fn new_v3(conn: &Connection, path: OwnedObjectPath) -> Result<Self> {
        let view = proxy::JobViewV3ProxyBlocking::builder(conn)
            .path(path.clone())?
            .build()?;
        let flags = Arc::new(Flags::default());
        spawn_signal_listener(
            conn.clone(),
            path,
            "org.kde.JobViewV3",
            Arc::downgrade(&flags),
        );
        Ok(Self {
            view: View::V3(view),
            flags,
            done: false,
        })
    }

    fn new_v2(conn: &Connection, path: OwnedObjectPath) -> Result<Self> {
        let view = proxy::JobViewV2ProxyBlocking::builder(conn)
            .path(path.clone())?
            .build()?;
        let flags = Arc::new(Flags::default());
        spawn_signal_listener(
            conn.clone(),
            path,
            "org.kde.JobViewV2",
            Arc::downgrade(&flags),
        );
        Ok(Self {
            view: View::V2(view),
            flags,
            done: false,
        })
    }

    fn update_v3(
        p: &proxy::JobViewV3ProxyBlocking<'_>,
        props: HashMap<String, Value<'_>>,
    ) -> Result<()> {
        p.update(props)
    }

    /// Updates the popup heading. Ignored by the legacy protocol.
    pub fn set_title(&self, title: &str) -> Result<()> {
        match &self.view {
            View::V3(p) => Self::update_v3(p, single("title", title.into())),
            View::V2(_) => Ok(()),
        }
    }

    /// Updates the status line.
    pub fn set_info_message(&self, message: &str) -> Result<()> {
        match &self.view {
            View::V3(p) => Self::update_v3(p, single("infoMessage", message.into())),
            View::V2(p) => p.set_info_message(message),
        }
    }

    /// Sets completion as a value from 0 to 100.
    pub fn set_percent(&self, percent: u32) -> Result<()> {
        let percent = percent.min(100);
        match &self.view {
            View::V3(p) => Self::update_v3(p, single("percent", Value::U32(percent))),
            View::V2(p) => p.set_percent(percent),
        }
    }

    /// Sets the current speed in bytes per second.
    pub fn set_speed(&self, bytes_per_second: u64) -> Result<()> {
        match &self.view {
            View::V3(p) => Self::update_v3(p, single("speed", Value::U64(bytes_per_second))),
            View::V2(p) => p.set_speed(bytes_per_second),
        }
    }

    /// Sets the total amount of work for a unit.
    pub fn set_total(&self, unit: Unit, amount: u64) -> Result<()> {
        match &self.view {
            View::V3(p) => Self::update_v3(p, single(unit.v3_total_key(), Value::U64(amount))),
            View::V2(p) => p.set_total_amount(amount, unit.v2_name()),
        }
    }

    /// Sets the processed amount of work for a unit.
    pub fn set_processed(&self, unit: Unit, amount: u64) -> Result<()> {
        match &self.view {
            View::V3(p) => Self::update_v3(p, single(unit.v3_processed_key(), Value::U64(amount))),
            View::V2(p) => p.set_processed_amount(amount, unit.v2_name()),
        }
    }

    /// Sets processed and total amounts and the derived percentage in one call.
    pub fn progress(&self, unit: Unit, processed: u64, total: u64) -> Result<()> {
        let percent = (processed.min(total) * 100).checked_div(total).unwrap_or(0) as u32;
        match &self.view {
            View::V3(p) => {
                let mut props: HashMap<String, Value> = HashMap::new();
                props.insert(unit.v3_processed_key().into(), Value::U64(processed));
                props.insert(unit.v3_total_key().into(), Value::U64(total));
                props.insert("percent".into(), Value::U32(percent));
                Self::update_v3(p, props)
            }
            View::V2(p) => {
                p.set_total_amount(total, unit.v2_name())?;
                p.set_processed_amount(processed, unit.v2_name())?;
                p.set_percent(percent)
            }
        }
    }

    /// Sets one of the two detail rows, for example Package and its name.
    /// Plasma shows slots 1 and 2.
    pub fn set_description(&self, slot: u32, label: &str, value: &str) -> Result<()> {
        match &self.view {
            View::V3(p) => {
                let mut props: HashMap<String, Value> = HashMap::new();
                props.insert(format!("descriptionLabel{slot}"), label.into());
                props.insert(format!("descriptionValue{slot}"), value.into());
                Self::update_v3(p, props)
            }
            View::V2(p) => p.set_description_field(slot, label, value).map(|_| ()),
        }
    }

    /// Clears a detail row.
    pub fn clear_description(&self, slot: u32) -> Result<()> {
        match &self.view {
            View::V3(_) => self.set_description(slot, "", ""),
            View::V2(p) => p.clear_description_field(slot),
        }
    }

    /// Updates the destination URL.
    pub fn set_dest_url(&self, url: &str) -> Result<()> {
        match &self.view {
            View::V3(p) => Self::update_v3(p, single("destUrl", url.into())),
            View::V2(p) => p.set_dest_url(url.into()),
        }
    }

    /// Reflects a suspended or resumed state in the popup.
    pub fn set_suspended(&self, suspended: bool) -> Result<()> {
        match &self.view {
            View::V3(p) => Self::update_v3(p, single("suspended", suspended.into())),
            View::V2(p) => p.set_suspended(suspended),
        }
    }

    /// True once the user pressed cancel in the popup.
    pub fn cancel_requested(&self) -> bool {
        self.flags.cancel.load(Ordering::Relaxed)
    }

    /// True while the user wants the job suspended.
    pub fn suspend_requested(&self) -> bool {
        self.flags.suspend.load(Ordering::Relaxed)
    }

    /// Terminates the job as successful.
    pub fn finish(mut self) -> Result<()> {
        self.terminate(0, "")
    }

    /// Terminates the job as failed with a message shown to the user.
    /// An error code of zero is raised to one.
    pub fn fail(mut self, error_code: u32, error_message: &str) -> Result<()> {
        self.terminate(error_code.max(1), error_message)
    }

    fn terminate(&mut self, error_code: u32, error_message: &str) -> Result<()> {
        self.done = true;
        match &self.view {
            View::V3(p) => p.terminate(error_code, error_message, HashMap::new()),
            View::V2(p) => p.terminate(error_message),
        }
    }
}

impl Drop for Job {
    fn drop(&mut self) {
        if !self.done {
            let _ = self.terminate(0, "");
        }
    }
}

fn single<'a>(key: &str, value: Value<'a>) -> HashMap<String, Value<'a>> {
    let mut props = HashMap::new();
    props.insert(key.into(), value);
    props
}

fn spawn_signal_listener(
    conn: Connection,
    path: OwnedObjectPath,
    interface: &'static str,
    flags: Weak<Flags>,
) {
    thread::spawn(move || {
        let Ok(proxy) = zbus::blocking::Proxy::new(&conn, SERVICE, path, interface) else {
            return;
        };
        let Ok(signals) = proxy.receive_all_signals() else {
            return;
        };
        for msg in signals {
            let Some(flags) = flags.upgrade() else {
                return;
            };
            let header = msg.header();
            match header.member().map(|m| m.as_str()) {
                Some("cancelRequested") => flags.cancel.store(true, Ordering::Relaxed),
                Some("suspendRequested") => flags.suspend.store(true, Ordering::Relaxed),
                Some("resumeRequested") => flags.suspend.store(false, Ordering::Relaxed),
                _ => {}
            }
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unit_names() {
        assert_eq!(Unit::Bytes.v2_name(), "bytes");
        assert_eq!(Unit::Directories.v2_name(), "dirs");
        assert_eq!(Unit::Files.v3_total_key(), "totalFiles");
        assert_eq!(Unit::Items.v3_processed_key(), "processedItems");
    }
}