libnotify_rs/wrappers/context.rs
1use crate::api::{
2 errors::LibnotifyError,
3 functions::{init, is_initted, set_app_icon, set_app_name, uninit},
4};
5
6/// Notification context. Handles libnotify initializing and uninitializing.
7pub struct LibnotifyContext {}
8
9static IS_CONTEXT_CREATED: std::sync::atomic::AtomicBool =
10 std::sync::atomic::AtomicBool::new(false);
11
12impl LibnotifyContext {
13 /// Try initializing libnotify
14 ///
15 /// # Errors
16 /// Returns an error, if libnotify cannot be initialized or if there already exists a context
17 /// object
18 ///
19 /// # Example
20 /// ```
21 /// use libnotify_rs::context::LibnotifyContext;
22 ///
23 /// fn main() -> Result<(), Box<dyn std::error::Error>> {
24 /// let ctx = LibnotifyContext::new("Coffee addicted reminder")?;
25 ///
26 /// // you don't need to uninitialize libnotify, cause context already does that!
27 ///
28 /// Ok(())
29 /// }
30 /// ```
31 pub fn new(app_name: &str) -> Result<LibnotifyContext, Box<dyn std::error::Error>> {
32 if IS_CONTEXT_CREATED.swap(true, std::sync::atomic::Ordering::SeqCst) {
33 return Err("You can create only one context at a time".into());
34 }
35
36 if !is_initted() {
37 init(app_name)?;
38 }
39
40 Ok(Self {})
41 }
42
43 /// Sets global app name
44 /// # Errors
45 ///
46 /// This function can return LibnotifyError::NulError
47 pub fn set_new_name(&self, app_name: &str) -> Result<(), LibnotifyError> {
48 set_app_name(app_name)?;
49 Ok(())
50 }
51
52 /// Sets global app icon
53 ///
54 /// # Errors
55 ///
56 /// This function can return LibnotifyError::NulError
57 pub fn set_app_icon(&self, app_icon: &str) -> Result<(), LibnotifyError> {
58 set_app_icon(app_icon)?;
59 Ok(())
60 }
61}
62
63impl Drop for LibnotifyContext {
64 fn drop(&mut self) {
65 if is_initted() {
66 uninit();
67
68 IS_CONTEXT_CREATED.store(false, std::sync::atomic::Ordering::SeqCst);
69 }
70 }
71}