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";
#[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",
}
}
}
pub struct Tracker {
conn: Connection,
desktop_entry: String,
app_name: Option<String>,
app_icon: Option<String>,
}
impl Tracker {
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,
})
}
pub fn with_app_name(mut self, name: impl Into<String>) -> Self {
self.app_name = Some(name.into());
self
}
pub fn with_app_icon(mut self, icon: impl Into<String>) -> Self {
self.app_icon = Some(icon.into());
self
}
pub fn job(&self) -> JobBuilder<'_> {
JobBuilder {
tracker: self,
title: None,
info_message: None,
dest_url: None,
cancellable: false,
suspendable: false,
transient: false,
immediate: false,
}
}
}
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<'_> {
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn info_message(mut self, message: impl Into<String>) -> Self {
self.info_message = Some(message.into());
self
}
pub fn dest_url(mut self, url: impl Into<String>) -> Self {
self.dest_url = Some(url.into());
self
}
pub fn cancellable(mut self, value: bool) -> Self {
self.cancellable = value;
self
}
pub fn suspendable(mut self, value: bool) -> Self {
self.suspendable = value;
self
}
pub fn transient(mut self, value: bool) -> Self {
self.transient = value;
self
}
pub fn immediate(mut self, value: bool) -> Self {
self.immediate = value;
self
}
pub fn start(self) -> Result<Job> {
let t = self.tracker;
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>),
}
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)
}
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(()),
}
}
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),
}
}
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),
}
}
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),
}
}
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()),
}
}
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()),
}
}
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)
}
}
}
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(|_| ()),
}
}
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),
}
}
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()),
}
}
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),
}
}
pub fn cancel_requested(&self) -> bool {
self.flags.cancel.load(Ordering::Relaxed)
}
pub fn suspend_requested(&self) -> bool {
self.flags.suspend.load(Ordering::Relaxed)
}
pub fn finish(mut self) -> Result<()> {
self.terminate(0, "")
}
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");
}
}