11 Commits

Author SHA1 Message Date
Szymon
21a09f9722 Merge pull request #3 from szymon-jozef/docs/everything
docs/everything
2026-10-02 15:30:25 +02:00
173d04c39c chore: version bump 2026-10-02 15:29:43 +02:00
6be65a249e docs: write super cool documentation 2026-10-02 15:29:17 +02:00
Szymon
2140751d2f Merge pull request #2 from szymon-jozef/refactor/split-modules
refactor: split modules into separate dirs
2026-10-01 21:35:48 +02:00
b4c8bceb4c refactor: split modules into separate dirs 2026-10-01 21:34:47 +02:00
Szymon
5b0da1e9c6 Merge pull request #1 from szymon-jozef/feat/builder
feat/builder
2026-10-01 21:25:27 +02:00
6cbb7524cf chore: version bump 2026-10-01 21:22:40 +02:00
5f0b2f199a feat: add example for builder 2026-10-01 21:00:23 +02:00
744efe8ec9 feat: add notifaction builder 2026-10-01 20:59:14 +02:00
7966726534 feat: add libnotify context 2026-10-01 16:31:16 +02:00
da89268e83 fix: badge 2026-09-30 20:34:39 +02:00
16 changed files with 243 additions and 21 deletions

2
Cargo.lock generated
View File

@@ -247,7 +247,7 @@ dependencies = [
[[package]]
name = "libnotify-rs"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"bindgen",
"glib",

View File

@@ -1,6 +1,6 @@
[package]
name = "libnotify-rs"
version = "0.1.0"
version = "0.2.1"
edition = "2024"
authors = [ "szymon_jozef"]
description = "Rust bindings for libnotify"

View File

@@ -1,6 +1,6 @@
![Tests](https://github.com/szymon-jozef/libnotify-rs/actions/workflows/tests.yml/badge.svg)
![GitHub License](https://img.shields.io/github/license/szymon-jozef/libnotify-rs)
![Gitea Release](https://img.shields.io/gitea/v/release/szymon-jozef/libnotify-rs)
![GitHub Release](https://img.shields.io/github/v/release/szymon-jozef/libnotify-rs)
<!--toc:start-->
- [Rust bindings for libnotify](#rust-bindings-for-libnotify)

23
examples/builder.rs Normal file
View File

@@ -0,0 +1,23 @@
use libnotify_rs::{builder::NotificationBuilder, context::LibnotifyContext};
/// Builder is recommended way to interact with libnotify notifications
fn main() -> Result<(), Box<dyn std::error::Error>> {
let ctx = LibnotifyContext::new("Coffee addicted reminder")?; // builder requires context
let notification_builder = NotificationBuilder::new(
"Remember about your coffee!",
"Only idiots forget about coffee!",
None,
&ctx,
)?
.set_urgency(libnotify_rs::api::notification::Urgency::Critical)
.set_timeout(libnotify_rs::api::notification::Timeout::Never)
.set_category("Coffee")?;
notification_builder.show()?;
// you don't need to uninitialize libnotify, cause context already does that!
Ok(())
}

View File

@@ -1,7 +1,7 @@
use glib::MainLoop;
use libnotify_rs::{
functions::{init, uninit},
notification::Notification,
api::functions::{init, uninit},
api::notification::Notification,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {

View File

@@ -1,4 +1,4 @@
use libnotify_rs::functions::{self, uninit};
use libnotify_rs::api::functions::{self, uninit};
fn main() -> Result<(), Box<dyn std::error::Error>> {
functions::init("Morbius")?;

View File

@@ -1,6 +1,6 @@
use libnotify_rs::{
use libnotify_rs::api::{
functions::{init, uninit},
notification::Notification,
notification::{self, Notification},
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
@@ -11,8 +11,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
None,
)?;
notify.set_timeout(libnotify_rs::notification::Timeout::Custom(1000 * 10)); // 10 secs
notify.set_urgency(libnotify_rs::notification::Urgency::Critical); // coffee is very important
notify.set_timeout(notification::Timeout::Custom(1000 * 10)); // 10 secs
notify.set_urgency(notification::Urgency::Critical); // coffee is very important
notify.set_category("Coffee")?;
notify.show()?;

View File

@@ -1,6 +1,6 @@
use crate::utils::c_str_to_rs_str_and_free;
use super::utils::c_str_to_rs_str_and_free;
use crate::libnotify::*;
use super::libnotify::*;
/* Initting
*
@@ -116,6 +116,7 @@ pub fn get_server_caps() -> Option<Vec<String>> {
if vec.is_empty() { None } else { Some(vec) }
}
/// Contains server information. Refer to [libnotify get_server_info docs](https://gnome.pages.gitlab.gnome.org/libnotify/func.get_server_info.html) to better understand specific fields
pub struct ServerInfo {
/// A location to store the server name, or `None`
pub name: Option<String>,

6
src/api/mod.rs Normal file
View File

@@ -0,0 +1,6 @@
/// Same as [libnotify global functions](https://gnome.pages.gitlab.gnome.org/libnotify/index.html#functions)
pub mod functions;
mod libnotify;
/// Same as [libnotify notification](https://gnome.pages.gitlab.gnome.org/libnotify/class.Notification.html)
pub mod notification;
mod utils;

View File

@@ -1,13 +1,18 @@
use crate::libnotify::*;
use super::libnotify::*;
#[derive(Debug, Clone, Copy)]
/// Notification urgency level. Refer to [libnotify docs](https://gnome.pages.gitlab.gnome.org/libnotify/enum.Urgency.html) for more info
pub enum Urgency {
/// Low urgency. Used for unimportant notifications
Low,
/// Normal urgency. Used for most standard notifications
Normal,
/// Critical urgency. Used for very important notifications
Critical,
}
#[derive(Debug, Clone, Copy)]
/// Reason why notification was closed. Refer to [libnotify docs](https://gnome.pages.gitlab.gnome.org/libnotify/enum.ClosedReason.html)
pub enum ClosedReason {
/// Notification not closed
Unset,
@@ -29,24 +34,39 @@ pub enum ClosedReason {
/// Used in set hint.
#[derive(Debug, Clone)]
pub enum HintValue {
#[allow(missing_docs)]
String(String),
#[allow(missing_docs)]
Int32(i32),
#[allow(missing_docs)]
Boolean(bool),
}
/// The timeout in milliseconds
/// Notification timeout, until close
#[derive(Debug, Clone, Copy)]
pub enum Timeout {
#[allow(missing_docs)]
Default,
#[allow(missing_docs)]
Never,
/// Custom timeout in milliseconds
Custom(i32),
}
/// Represents one notification. Wraps most of [libnotify::notifaction](https://gnome.pages.gitlab.gnome.org/libnotify/class.Notification.html) functions.
pub struct Notification {
inner: *mut NotifyNotification,
}
impl<'a> Notification {
/// Create new notification.
///
/// # Errors
/// This function will return an error if the supplied bytes contain an
/// internal 0 byte. The [`NulError`](https://doc.rust-lang.org/stable/alloc/ffi/c_str/struct.NulError.html) returned will contain the bytes as well as
/// the position of the nul byte.
///
/// On libnotify fail it will return Err(&str.into). May change in the future.
pub fn new<T, Y>(summary: &str, body: T, icon: Y) -> Result<Self, Box<dyn std::error::Error>>
where
T: Into<Option<&'a str>>,
@@ -73,6 +93,15 @@ impl<'a> Notification {
Ok(Self { inner })
}
/// Add callback to notification.
///
/// # Args
/// `action` – action identifier. `default` will work for most use cases. Other text will be
/// displayed as button names.
///
/// `label` – label for user
///
/// `callback` - any closure that accepts &str as an argument, where &str is action name.
pub fn add_action<F>(
&mut self,
action: &str,
@@ -162,7 +191,7 @@ impl<'a> Notification {
/// `set_app_icon()`.
///
/// Available since: 0.8.4
pub fn set_app_icon(&mut self, app_icon: &str) -> Result<(), Box<dyn std::error::Error>> {
pub fn set_app_icon(&mut self, app_icon: &str) -> Result<(), std::ffi::NulError> {
let app_icon_c = std::ffi::CString::new(app_icon)?;
unsafe { notify_notification_set_app_icon(self.inner, app_icon_c.as_ptr()) };

View File

@@ -7,7 +7,7 @@ pub unsafe fn c_str_to_rs_str_and_free(c_str: *mut std::os::raw::c_char) -> Opti
.to_string_lossy()
.to_string();
unsafe { crate::libnotify::g_free(c_str as *mut std::ffi::c_void) };
unsafe { super::libnotify::g_free(c_str as *mut std::ffi::c_void) };
Some(normal_string)
}

View File

@@ -1,9 +1,20 @@
#![cfg_attr(not(doctest), doc = include_str!("./../README.md"))]
//! This crate exposes two modules:
//!
//! # Api
//! This module contains a basic wrapper for libnotify calls. It just translates data types, etc,
//! so usage is basically the same as libnotify.
//!
//! # Wrappers
//! This module is a higher level abstraction over api. Recommended to use over api.
//!
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![warn(missing_docs)]
pub mod functions;
mod libnotify;
pub mod notification;
mod utils;
/// Basic libnotify rust wrapper
pub mod api;
/// Higher level abstraction over api
pub mod wrappers;
pub use wrappers::{builder, context};

100
src/wrappers/builder.rs Normal file
View File

@@ -0,0 +1,100 @@
use crate::{
api::notification::{HintValue, Notification, Timeout, Urgency},
wrappers::context::LibnotifyContext,
};
/// Higher level abstraction of `Notification`. Allow for builder pattern notification construction.
/// Requires `LibnotifyContext`
pub struct NotificationBuilder<'a> {
notification: Notification,
_context: &'a LibnotifyContext,
}
impl<'a> NotificationBuilder<'a> {
/// Create new NotificationBuilder, with given context.
pub fn new<T, Y>(
summary: &str,
body: T,
icon: Y,
context: &'a LibnotifyContext,
) -> Result<Self, Box<dyn std::error::Error>>
where
T: Into<Option<&'a str>>,
Y: Into<Option<&'a str>>,
{
let notification = Notification::new(summary, body, icon)?;
Ok(Self {
notification,
_context: context,
})
}
/// Sets app name for this specific notification.
pub fn set_app_name(mut self, app_name: &str) -> Result<Self, std::ffi::NulError> {
self.notification.set_app_name(app_name)?;
Ok(self)
}
/// Sets app icon fot this specific notification.
pub fn set_app_icon(mut self, app_icon: &str) -> Result<Self, std::ffi::NulError> {
self.notification.set_app_icon(app_icon)?;
Ok(self)
}
/// Sets category for this specific notification
pub fn set_category(mut self, category: &str) -> Result<Self, std::ffi::NulError> {
self.notification.set_category(category)?;
Ok(self)
}
/// Set hint for this specific notification
pub fn set_hint(
mut self,
key: &str,
value: HintValue,
) -> Result<Self, Box<dyn std::error::Error>> {
self.notification.set_hint(key, value)?;
Ok(self)
}
/// Set timeout until close
pub fn set_timeout(mut self, timeout: Timeout) -> Self {
self.notification.set_timeout(timeout);
self
}
/// Set notification urgency level
pub fn set_urgency(mut self, urgency: Urgency) -> Self {
self.notification.set_urgency(urgency);
self
}
/// Add callback
pub fn add_action<F>(
mut self,
action: &str,
label: &str,
callback: F,
) -> Result<Self, Box<dyn std::error::Error>>
where
F: Fn(&str) + 'static,
{
self.notification.add_action(action, label, callback)?;
Ok(self)
}
/// Show notification
///
/// Uses `&self` borrow, so you can use this object later, after showing.
pub fn show(&self) -> Result<(), Box<dyn std::error::Error>> {
self.notification.show()?;
Ok(())
}
/// Close notification synchronously.
pub fn close(&self) -> Result<(), Box<dyn std::error::Error>> {
self.notification.close()?;
Ok(())
}
}

48
src/wrappers/context.rs Normal file
View File

@@ -0,0 +1,48 @@
use crate::api::functions::{init, is_initted, set_app_icon, set_app_name, uninit};
/// Notification context. Handles libnotify initializing and uninitializing.
pub struct LibnotifyContext {}
static IS_CONTEXT_CREATED: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
impl LibnotifyContext {
/// Try initializing libnotify
///
/// # Error
/// Returns an error, if libnotify cannot be initialized or if there already exists a context
/// object
pub fn new(app_name: &str) -> Result<LibnotifyContext, Box<dyn std::error::Error>> {
if IS_CONTEXT_CREATED.swap(true, std::sync::atomic::Ordering::SeqCst) {
return Err("You can create only one context at a time".into());
}
if !is_initted() {
init(app_name)?;
}
Ok(Self {})
}
/// Sets global app name
pub fn set_new_name(&self, app_name: &str) -> Result<(), std::ffi::NulError> {
set_app_name(app_name)?;
Ok(())
}
/// Sets global app icon
pub fn set_app_icon(&self, app_icon: &str) -> Result<(), std::ffi::NulError> {
set_app_icon(app_icon)?;
Ok(())
}
}
impl Drop for LibnotifyContext {
fn drop(&mut self) {
if is_initted() {
uninit();
IS_CONTEXT_CREATED.store(false, std::sync::atomic::Ordering::SeqCst);
}
}
}

4
src/wrappers/mod.rs Normal file
View File

@@ -0,0 +1,4 @@
/// Contains notification builder
pub mod builder;
/// Containx libnotify context
pub mod context;