Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use ksni on linux #7

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[target.'cfg(target_os="linux")'.dependencies]
libappindicator = "0.5" # Tray icon
gtk = "0.9"
ksni = "0.1.3"

[target.'cfg(target_os="windows")'.dependencies]
winapi = { version = "0.3", features = ["shellapi", "libloaderapi", "errhandlingapi", "impl-default"] }
Expand Down
13 changes: 4 additions & 9 deletions examples/linux.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
use tray_item::TrayItem;
use gtk;
use tray_item::{TrayItem, IconSource};

fn main() {

gtk::init().unwrap();

let mut tray = TrayItem::new("Tray Example", "accessories-calculator").unwrap();
let mut tray = TrayItem::new("Tray Example", IconSource::Resource("accessories-calculator")).unwrap();

tray.add_label("Tray Label").unwrap();

Expand All @@ -14,9 +10,8 @@ fn main() {
}).unwrap();

tray.add_menu_item("Quit", || {
gtk::main_quit();
std::process::exit(0);
}).unwrap();

gtk::main();

std::io::stdin().read_line(&mut String::new()).unwrap();
}
4 changes: 2 additions & 2 deletions examples/macos.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use tray_item::TrayItem;
use tray_item::{TrayItem, IconSource};

fn main() {

let mut tray = TrayItem::new("Tray Example", "").unwrap();
let mut tray = TrayItem::new("Tray Example", IconSource::Resource("")).unwrap();

tray.add_label("Tray Label").unwrap();

Expand Down
6 changes: 3 additions & 3 deletions examples/windows.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use tray_item::TrayItem;
use tray_item::{TrayItem, IconSource};

fn main() {

let mut tray = TrayItem::new("Tray Example", "name-of-icon-in-rc-file").unwrap();
let mut tray = TrayItem::new("Tray Example", IconSource::Resource("name-of-icon-in-rc-file")).unwrap();

tray.add_label("Tray Label").unwrap();

Expand All @@ -15,7 +15,7 @@ fn main() {
std::process::exit(0);
}).unwrap();

tray.set_icon("another-name-from-rc-file").unwrap();
tray.set_icon(IconSource::Resource("another-name-from-rc-file")).unwrap();

std::io::stdin().read_line(&mut String::new()).unwrap();

Expand Down
120 changes: 93 additions & 27 deletions src/api/linux/mod.rs
Original file line number Diff line number Diff line change
@@ -1,53 +1,119 @@
use crate::TIError;
use gtk::prelude::*;
use libappindicator::{AppIndicator, AppIndicatorStatus};
use crate::{TIError, IconSource};
use ksni::{menu::StandardItem, Handle, Icon};
use std::sync::Arc;

struct TrayItem {
label: String,
action: Option<Arc<dyn Fn() + Send + Sync + 'static>>
}

struct Tray {
title: String,
icon: IconSource,
actions: Vec<TrayItem>
}

pub struct TrayItemLinux {
tray: AppIndicator,
menu: gtk::Menu,
tray: Handle<Tray>
}

impl ksni::Tray for Tray {
fn title(&self) -> String {
self.title.clone()
}

fn icon_name(&self) -> String {
match &self.icon {
IconSource::Resource(name) => name.to_string(),
IconSource::Data{..} => String::new(),
}
}

fn icon_pixmap(&self) -> Vec<Icon> {
match &self.icon {
IconSource::Resource(_) => vec![],
IconSource::Data{data, height, width} => {
vec![Icon {
width: *height,
height: *width,
data: data.clone()
}]
},
}
}

fn menu(&self) -> Vec<ksni::MenuItem<Self>> {
self.actions.iter().map(|item| {
let action = item.action.clone();
if let Some(action) = action {
StandardItem {
label: item.label.clone(),
activate: Box::new(move |_| {
action();
}),
..Default::default()
}
.into()
} else {
StandardItem {
label: item.label.clone(),
enabled: false,
..Default::default()
}
.into()
}
}).collect()
}
}

impl TrayItemLinux {
pub fn new(title: &str, icon: &str) -> Result<Self, TIError> {
let mut t = Self {
tray: AppIndicator::new(title, icon),
menu: gtk::Menu::new(),
};
pub fn new(title: &str, icon: IconSource) -> Result<Self, TIError> {
let svc = ksni::TrayService::new(Tray {
title: title.to_string(),
icon,
actions: vec![]
});

t.set_icon(icon)?;
let handle = svc.handle();
svc.spawn();

Ok(t)
Ok(Self {
tray: handle
})
}

pub fn set_icon(&mut self, icon: &str) -> Result<(), TIError> {
self.tray.set_icon(icon);
self.tray.set_status(AppIndicatorStatus::Active);
pub fn set_icon(&mut self, icon: IconSource) -> Result<(), TIError> {
self.tray.update(|tray| {
tray.icon = icon.clone()
});

Ok(())
}

pub fn add_label(&mut self, label: &str) -> Result<(), TIError> {
let item = gtk::MenuItem::with_label(label.as_ref());
item.set_sensitive(false);
self.menu.append(&item);
self.menu.show_all();
self.tray.set_menu(&mut self.menu);
self.tray.update(move |tray| {
tray.actions.push(TrayItem {
label: label.to_string(),
action: None
});
});

Ok(())
}

pub fn add_menu_item<F>(&mut self, label: &str, cb: F) -> Result<(), TIError>
where
F: Fn() -> () + Send + Sync + 'static,
where F: Fn() -> () + Send + Sync + 'static,
{
let item = gtk::MenuItem::with_label(label.as_ref());
item.connect_activate(move |_| {
let action = Arc::new(move ||{
cb();
});
self.menu.append(&item);
self.menu.show_all();
self.tray.set_menu(&mut self.menu);

self.tray.update(move |tray| {
tray.actions.push(TrayItem {
label: label.to_string(),
action: Some(action.clone())
});
});
Ok(())
}
}
9 changes: 5 additions & 4 deletions src/api/macos/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::TIError;
use crate::{TIError, IconSource};
use cocoa::{
appkit::{
NSApp, NSApplication, NSApplicationActivateIgnoringOtherApps, NSImage, NSMenu, NSMenuItem,
Expand All @@ -22,10 +22,11 @@ pub struct TrayItemMacOS {
}

impl TrayItemMacOS {
pub fn new(title: &str, icon: &str) -> Result<Self, TIError> {
pub fn new(title: &str, icon: IconSource) -> Result<Self, TIError> {
unsafe {
let pool = NSAutoreleasePool::new(nil);

let icon = icon.as_str();
let icon = Some(icon).filter(|icon| !icon.is_empty());
let icon = icon.map(|icon_name| {
let icon_name = NSString::alloc(nil).init_str(icon_name);
Expand All @@ -46,9 +47,9 @@ impl TrayItemMacOS {
}
}

pub fn set_icon(&mut self, icon: &str) -> Result<(), TIError> {
pub fn set_icon(&mut self, icon: IconSource) -> Result<(), TIError> {
unsafe {
let icon_name = NSString::alloc(nil).init_str(icon);
let icon_name = NSString::alloc(nil).init_str(icon.as_str());
self.icon = Some(NSImage::imageNamed_(NSImage::alloc(nil), icon_name));
}
Ok(())
Expand Down
11 changes: 4 additions & 7 deletions src/api/windows/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Most of this code is taken from https://github.com/qdot/systray-rs/blob/master/src/api/win32/mod.rs
// Open source is great :)

use crate::TIError;
use crate::{TIError, IconSource};
use std::{
self,
cell::RefCell,
Expand Down Expand Up @@ -47,7 +47,7 @@ pub struct TrayItemWindows {

impl TrayItemWindows {

pub fn new(title: &str, icon: &str) -> Result<Self, TIError> {
pub fn new(title: &str, icon: IconSource) -> Result<Self, TIError> {

let entries = Arc::new(Mutex::new(Vec::new()));
let (tx, rx) = channel();
Expand Down Expand Up @@ -135,13 +135,10 @@ impl TrayItemWindows {
w.set_icon(icon)?;

Ok(w)

}

pub fn set_icon(&self, icon: &str) -> Result<(), TIError> {

self.set_icon_from_resource(icon)

pub fn set_icon(&self, icon: IconSource) -> Result<(), TIError> {
self.set_icon_from_resource(icon.as_str())
}

pub fn add_label(&mut self, label: &str) -> Result<(), TIError> {
Expand Down
27 changes: 25 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,32 @@ pub use error::TIError;

pub struct TrayItem(api::TrayItemImpl);

#[derive(Clone)]
pub enum IconSource {
Resource(&'static str),
#[cfg(target_os = "linux")]
Data {
height: i32,
width: i32,
data: Vec<u8>
},
}

impl IconSource {
pub fn as_str(&self) -> &str {
match self {
IconSource::Resource(res) => {
res
},
#[allow(unreachable_patterns)]
_ => unimplemented!()
}
}
}

impl TrayItem {

pub fn new(title: &str, icon: &str) -> Result<Self, TIError> {
pub fn new(title: &str, icon: IconSource) -> Result<Self, TIError> {

Ok(
Self(
Expand All @@ -16,7 +39,7 @@ impl TrayItem {

}

pub fn set_icon(&mut self, icon: &str) -> Result<(), TIError> {
pub fn set_icon(&mut self, icon: IconSource) -> Result<(), TIError> {

self.0.set_icon(icon)

Expand Down