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

refactor: allow changing the menu event sender #8

Merged
merged 8 commits into from
Jan 3, 2023
Merged
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
5 changes: 5 additions & 0 deletions .changes/event_handler.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tray-icon": "patch"
---

Add `TrayEvent::set_event_handler` to set a handler for new tray events.
5 changes: 5 additions & 0 deletions .changes/muda-0.3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tray-icon": patch
---

Update `muda` to `0.2`.
5 changes: 5 additions & 0 deletions .changes/rm-tray-event-receiver.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tray-icon": "minor"
---

**Breaking change** Remove `tray_event_receiver` function, use `TrayEvent::receiver` instead.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ license = "MIT OR Apache-2.0"
categories = [ "gui" ]

[dependencies]
muda = "0.2"
muda = "0.3"
crossbeam-channel = "0.5"
once_cell = "1"
thiserror = "1.0"
Expand Down
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,26 +32,26 @@ let tray_icon = TrayIconBuilder::new()

## Processing tray events

You can use `tray_event_receiver` to get a reference to the `TrayEventReceiver`
You can use `TrayEvent::receiver` to get a reference to the `TrayEventReceiver`
which you can use to listen to events when a click happens on the tray icon
```rs
use tray_icon::tray_event_receiver;
use tray_icon::TrayEvent;

if let Ok(event) = tray_event_receiver().try_recv() {
if let Ok(event) = TrayEvent::receiver().try_recv() {
println!("{:?}", event);
}
```

You can also listen for the menu events using `menu_event_listener` to get events for the tray context menu.
You can also listen for the menu events using `TrayEvent::receiver` to get events for the tray context menu.

```rs
use tray_icon::{tray_event_receiver, menu::menu_event_receiver};
use tray_icon::{TrayEvent, menu::{MenuEvent}};

if let Ok(event) = tray_event_receiver().try_recv() {
if let Ok(event) = TrayEvent::receiver().try_recv() {
println!("tray event: {:?}", event);
}

if let Ok(event) = menu_event_receiver().try_recv() {
if let Ok(event) = MenuEvent::receiver().try_recv() {
println!("menu event: {:?}", event);
}
```
Expand Down
8 changes: 4 additions & 4 deletions examples/tao.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

use tao::event_loop::{ControlFlow, EventLoopBuilder};
use tray_icon::{
menu::{menu_event_receiver, AboutMetadata, Menu, MenuItem, PredefinedMenuItem},
tray_event_receiver, TrayIconBuilder,
menu::{AboutMetadata, Menu, MenuEvent, MenuItem, PredefinedMenuItem},
TrayEvent, TrayIconBuilder,
};

fn main() {
Expand Down Expand Up @@ -41,8 +41,8 @@ fn main() {
.unwrap(),
);

let menu_channel = menu_event_receiver();
let tray_channel = tray_event_receiver();
let menu_channel = MenuEvent::receiver();
let tray_channel = TrayEvent::receiver();

event_loop.run(move |_event, _, control_flow| {
*control_flow = ControlFlow::Poll;
Expand Down
8 changes: 4 additions & 4 deletions examples/winit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
#![allow(unused)]

use tray_icon::{
menu::{menu_event_receiver, AboutMetadata, Menu, MenuItem, PredefinedMenuItem},
tray_event_receiver, TrayIconBuilder,
menu::{AboutMetadata, Menu, MenuEvent, MenuItem, PredefinedMenuItem},
TrayEvent, TrayIconBuilder,
};
use winit::event_loop::{ControlFlow, EventLoopBuilder};

Expand Down Expand Up @@ -41,8 +41,8 @@ fn main() {
.unwrap(),
);

let menu_channel = menu_event_receiver();
let tray_channel = tray_event_receiver();
let menu_channel = MenuEvent::receiver();
let tray_channel = TrayEvent::receiver();

event_loop.run(move |_event, _, control_flow| {
*control_flow = ControlFlow::Poll;
Expand Down
123 changes: 77 additions & 46 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,26 +38,26 @@
//!
//! # Processing tray events
//!
//! You can use [`tray_event_receiver`] to get a reference to the [`TrayEventReceiver`]
//! You can use [`TrayEvent::receiver`] to get a reference to the [`TrayEventReceiver`]
//! which you can use to listen to events when a click happens on the tray icon
//! ```no_run
//! use tray_icon::tray_event_receiver;
//! use tray_icon::TrayEvent;
//!
//! if let Ok(event) = tray_event_receiver().try_recv() {
//! if let Ok(event) = TrayEvent::receiver().try_recv() {
//! println!("{:?}", event);
//! }
//! ```
//!
//! You can also listen for the menu events using [`menu_event_receiver`](crate::menu::menu_event_receiver) to get events for the tray context menu.
//! You can also listen for the menu events using [`TrayEvent::receiver`] to get events for the tray context menu.
//!
//! ```no_run
//! use tray_icon::{tray_event_receiver, menu::menu_event_receiver};
//! use tray_icon::{TrayEvent, menu::MenuEvent};
//!
//! if let Ok(event) = tray_event_receiver().try_recv() {
//! if let Ok(event) = TrayEvent::receiver().try_recv() {
//! println!("tray event: {:?}", event);
//! }
//!
//! if let Ok(event) = menu_event_receiver().try_recv() {
//! if let Ok(event) = MenuEvent::receiver().try_recv() {
//! println!("menu event: {:?}", event);
//! }
//! ```
Expand All @@ -67,7 +67,7 @@ use std::path::{Path, PathBuf};
use counter::Counter;
use crossbeam_channel::{unbounded, Receiver, Sender};
use icon::Icon;
use once_cell::sync::Lazy;
use once_cell::sync::{Lazy, OnceCell};

mod counter;
mod error;
Expand All @@ -83,44 +83,6 @@ pub mod menu {

static COUNTER: Counter = Counter::new();

/// Describes a menu event emitted when a menu item is activated
#[derive(Debug)]
pub struct TrayEvent {
/// Id of the tray icon which triggered this event
pub id: u32,
pub x: f64,
pub y: f64,
pub icon_rect: Rectangle,
pub event: ClickEvent,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ClickEvent {
Left,
Right,
Double,
}

/// Describes a rectangle including position (x - y axis) and size.
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct Rectangle {
left: f64,
right: f64,
top: f64,
bottom: f64,
}

/// A reciever that could be used to listen to tray events.
pub type TrayEventReceiver = Receiver<TrayEvent>;

static TRAY_CHANNEL: Lazy<(Sender<TrayEvent>, TrayEventReceiver)> = Lazy::new(unbounded);

/// Gets a reference to the event channel's [TrayEventReceiver]
/// which can be used to listen for tray events.
pub fn tray_event_receiver<'a>() -> &'a TrayEventReceiver {
&TRAY_CHANNEL.1
}

/// Attributes to use when creating a tray icon.
pub struct TrayIconAttributes {
/// Tooltip for the tray icon
Expand Down Expand Up @@ -277,3 +239,72 @@ impl TrayIcon {
let _ = enable;
}
}

/// Describes a menu event emitted when a menu item is activated
#[derive(Debug)]
pub struct TrayEvent {
/// Id of the tray icon which triggered this event
pub id: u32,
pub x: f64,
pub y: f64,
pub icon_rect: Rectangle,
pub event: ClickEvent,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ClickEvent {
Left,
Right,
Double,
}

/// Describes a rectangle including position (x - y axis) and size.
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct Rectangle {
left: f64,
right: f64,
top: f64,
bottom: f64,
}

/// A reciever that could be used to listen to tray events.
pub type TrayEventReceiver = Receiver<TrayEvent>;
type TrayEventHandler = Box<dyn Fn(TrayEvent) + Send + Sync + 'static>;

static TRAY_CHANNEL: Lazy<(Sender<TrayEvent>, TrayEventReceiver)> = Lazy::new(unbounded);
static TRAY_EVENT_HANDLER: OnceCell<Option<TrayEventHandler>> = OnceCell::new();

impl TrayEvent {
/// Gets a reference to the event channel's [`TrayEventReceiver`]
/// which can be used to listen for tray events.
///
/// ## Note
///
/// This will not receive any events if [`TrayEvent::set_event_handler`] has been called with a `Some` value.
pub fn receiver<'a>() -> &'a TrayEventReceiver {
&TRAY_CHANNEL.1
}

/// Set a handler to be called for new events. Useful for implementing custom event sender.
///
/// ## Note
///
/// Calling this function with a `Some` value,
/// will not send new events to the channel associated with [`TrayEvent::receiver`]
pub fn set_event_handler<F: Fn(TrayEvent) + Send + Sync + 'static>(f: Option<F>) {
if let Some(f) = f {
let _ = TRAY_EVENT_HANDLER.set(Some(Box::new(f)));
} else {
let _ = TRAY_EVENT_HANDLER.set(None);
}
}

#[allow(unused)]
pub(crate) fn send(event: TrayEvent) {
if let Some(handler) = TRAY_EVENT_HANDLER.get_or_init(|| None) {
handler(event);
} else {
let _ = TRAY_CHANNEL.0.send(event);
}
}
}
4 changes: 2 additions & 2 deletions src/platform_impl/macos/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use objc::{
sel, sel_impl,
};

use crate::{icon::Icon, menu, ClickEvent, Rectangle, TrayEvent, TrayIconAttributes, TRAY_CHANNEL};
use crate::{icon::Icon, menu, ClickEvent, Rectangle, TrayEvent, TrayIconAttributes};

const TRAY_ID: &str = "id";
const TRAY_MENU: &str = "menu";
Expand Down Expand Up @@ -257,7 +257,7 @@ extern "C" fn perform_tray_click(this: &mut Object, _: Sel, button: id) {
event: click_event,
};

let _ = &TRAY_CHANNEL.0.send(event);
TrayEvent::send(event);

let menu = this.get_ivar::<id>(TRAY_MENU);
if *menu != nil {
Expand Down
4 changes: 2 additions & 2 deletions src/platform_impl/windows/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use windows_sys::{
},
};

use crate::{icon::Icon, menu, ClickEvent, Rectangle, TrayIconAttributes, TRAY_CHANNEL};
use crate::{icon::Icon, menu, ClickEvent, Rectangle, TrayEvent, TrayIconAttributes};

pub(crate) use self::icon::WinIcon as PlatformIcon;

Expand Down Expand Up @@ -313,7 +313,7 @@ unsafe extern "system" fn tray_subclass_proc(
_ => unreachable!(),
};

let _ = &TRAY_CHANNEL.0.send(crate::TrayEvent {
TrayEvent::send(crate::TrayEvent {
id: subclass_input.id,
x,
y,
Expand Down