FIx big mistake. Restart from scratch.

This commit is contained in:
Candifloss 2024-09-01 13:50:17 +05:30
parent 1ea24e900d
commit fddd48d98a
3 changed files with 50 additions and 229 deletions

View File

@ -6,8 +6,6 @@ authors = ["candifloss <candifloss.cc>"]
[dependencies]
zbus = "4.4.0"
zbus_macros = "4.4.0"
zbus_names = "3.0.0"
zvariant = "4.2.0"
# rson_rs = "0.2.1"
tokio = { version = "1.39.3", features = ["full"] }
tokio = { version = "1.40.0", features = ["full"] }
futures-util = "0.3.30"
# rson_rs = "0.2.1"

View File

@ -1,105 +1,13 @@
use std::collections::HashMap;
use zbus::Connection;
use zbus::blocking::MessageIterator;
use zbus::fdo::Result;
use zbus::zvariant::Value;
use zbus::MatchRule;
use zbus_names::InterfaceName;
use zbus_names::WellKnownName;
use std::fmt;
//use tokio;
fn print_type_of<T>(_: &T) {
println!("{}", std::any::type_name::<T>());
}
// Actions field of notication
struct NotifAction<'a> {
action_id: &'a str,
action: &'a str,
}
impl fmt::Display for NotifAction<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "{}: {}", &self.action_id, &self.action)?;
Ok(())
}
}
// Structure of a notification
struct Notif<'a> {
app_name: &'a str,
replace_id: u32,
ico: &'a str,
summary: &'a str,
body: &'a str,
actions: &'a [&'a str],
hints: HashMap<&'a str, &'a zbus::zvariant::Value<'a >>,
expir_timeout: i32,
}
// Function to print the contents of the notification
impl fmt::Display for Notif<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "AppName: {}", &self.app_name)?;
writeln!(f, "ReplaceId: {}", &self.replace_id)?;
write!(
f,
"Icon: {}\nSummary: {}\nBody: {}\nActions:\n",
&self.ico, &self.summary, &self.body
)?;
let actions_len = self.actions.len();
let mut i = 0;
while i < actions_len {
let a = NotifAction {
action_id: &self.actions[i],
action: &self.actions[i+1],
};
println!("{a}");
i += 2;
};
writeln!(f, "Hints:")?;
for (key, value) in &self.hints {
writeln!(f, "\t{key}: {value}")?;
}
match self.expir_timeout {
-1 => writeln!(f, "None")?,
_ => writeln!(f, "Expiration Timeout: {}", self.expir_timeout)?,
//None => writeln!(f, "Error getting timeout")?,
}
Ok(()) // Return Ok to indicate success
}
}
use zbus::{Connection, Result, MessageStream};
use futures_util::stream::TryStreamExt;
#[tokio::main]
async fn main() -> Result<()> {
let interface = InterfaceName::try_from("org.freedesktop.Notifications").unwrap();
let busname = WellKnownName::try_from("org.freedesktop.Notifications").unwrap();
// Establish a connection to the session bus
let connection = Connection::session().await?;
connection
.request_name("org.freedesktop.Notifications") // Requesting dbus for this service name
.await?;
// Loop to handle incoming messages
loop {
let msg = connection.receive_message()?;
let msg_header = msg.header()?;
dbg!(&msg);
match msg_header.message_type()? {
zbus::message::Type::Signal => {
// real code would check msg_header path(), interface() and member()
// handle invalid calls, introspection, errors etc
let arg: &str = msg.body()?;
println!("Msg.body: {arg}");
}
_ => continue,
}
}
Ok(())
}
//
loop {}
}

View File

@ -1,149 +1,64 @@
fn main() -> Result<(), dbus::Error> {
/*
// Example notif
let mut not = Notif {
app_name: "snot".to_string(),
replace_id: Some(0),
ico: "alert.png".to_string(),
summary: "This is a very long suuummmaaarrryyy! Don't you believe me????".to_string(),
body: "short body(hehe)".to_string(),
actions: vec![
("reply".to_string(), "Reply".to_string()),
("close".to_string(), "Close".to_string()),
],
hints: HashMap::new(), // Create an empty HashMap for hints, add the hints later
expir_timeout: Some(0),
};
not.hints
.insert("urgency".to_string(), "critical".to_string());
not.hints
.insert("category".to_string(), "network.error".to_string());
// End of eg. notif
truncate_summary(&mut not); //Limit the summary length
*/
}
//println!("{not}");
fn print_type_of<T>(_: &T) {
println!("{}", std::any::type_name::<T>());
}
// Actions field of notication
struct NotifAction<'a> {
action_id: &'a str,
action: &'a str,
}
fn handle_notification_added(message: Message) {
if message.get_type() == MessageType::Signal {
let signal_name = message.get_signature().unwrap();
impl fmt::Display for NotifAction<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "{}: {}", &self.action_id, &self.action)?;
if signal_name == "notification_added" {
let (id, app_name, icon, summary, body, actions, hints, timeout) = message
.get_arguments::<(
u32,
String,
String,
String,
String,
Vec<String>,
HashMap<String, String>,
i32,
)>()
.unwrap();
let notif = Notif {
app_name,
replace_id: Some(id), // Assuming you want to use the ID for replacement
ico: icon,
summary,
body,
actions: actions
.iter()
.map(|(key, value)| (key.clone(), value.clone()))
.collect(),
hints: hints
.iter()
.map(|(key, value)| (key.clone(), value.to_string()))
.collect(),
expir_timeout: if timeout < 0 {
None
} else {
Some(timeout as u32)
},
};
// Print or process the notification object
println!("{notif}");
}
Ok(())
}
}
/* Subscribe to the "notification added" signal
let mut match_rule: MatchRule = MatchRule::new();
match_rule.msg_type = Some(Signal);
match_rule.path = Some(Path::new(object_path).expect("Failed to create path"));
match_rule.path_is_namespace = false;
match_rule.interface = Some(Interface::from(interface_name));
match_rule.eavesdrop = true;
conn.add_match( match_rule, handle_notif)?; */
// Structure of a notification
struct Notif {
app_name: String,
replace_id: Option<u32>,
ico: String,
summary: String,
body: String,
actions: Vec<(String, String)>,
hints: HashMap<String, String>,
expir_timeout: Option<u32>,
struct Notif<'a> {
app_name: &'a str,
replace_id: u32,
ico: &'a str,
summary: &'a str,
body: &'a str,
actions: &'a [&'a str],
hints: HashMap<&'a str, &'a zbus::zvariant::Value<'a >>,
expir_timeout: i32,
}
// Function to print the contents of the notification
impl fmt::Display for Notif {
impl fmt::Display for Notif<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "AppName: {}", &self.app_name)?;
match self.replace_id {
Some(notif_id) => writeln!(f, "ReplaceId: {notif_id}")?,
None => writeln!(f, "None")?,
}
writeln!(f, "ReplaceId: {}", &self.replace_id)?;
write!(
f,
"Icon: {}\nSummary: {}\nBody: {}\nActions:\n",
&self.ico, &self.summary, &self.body
)?;
for (key, label) in &self.actions {
writeln!(f, "\t{key}: {label}")?;
}
let actions_len = self.actions.len();
let mut i = 0;
while i < actions_len {
let a = NotifAction {
action_id: &self.actions[i],
action: &self.actions[i+1],
};
println!("{a}");
i += 2;
};
writeln!(f, "Hints:")?;
for (key, value) in &self.hints {
writeln!(f, "\t{key}: {value}")?;
}
match self.expir_timeout {
Some(millisec) => writeln!(f, "Expiration Timeout: {millisec}")?,
None => writeln!(f, "None")?,
-1 => writeln!(f, "None")?,
_ => writeln!(f, "Expiration Timeout: {}", self.expir_timeout)?,
//None => writeln!(f, "Error getting timeout")?,
}
Ok(()) // Return Ok to indicate success
}
}
// Summary should be generally <= 40 chars, as per the specification.
fn truncate_summary(notif: &mut Notif) {
if notif.summary.len() > 40 {
notif.summary.truncate(39);
notif.summary.push('…');
}
}
/*/ Define a match rule for the notifications
let match_rule = MatchRule::builder()
.msg_type(zbus::MessageType::Signal)
.interface("org.freedesktop.Notifications")?
.path("/org/freedesktop/Notifications")?
.build();*/
// Proxy
let proxy = Proxy::new(
&connection,
"org.freedesktop.Notifications", // Service/Bus name
"/org/freedesktop/Notifications", // Object path
"org.freedesktop.Notifications", // Interface name
)?;
}