opt: listen status for system tray on Linux

This commit is contained in:
Kingtous
2022-12-10 10:57:21 +08:00
parent 122a52d66a
commit 7f4a453cc8
3 changed files with 108 additions and 15 deletions

View File

@@ -88,6 +88,9 @@ pub fn start_tray() {
/// This function will block current execution, show the tray icon and handle events.
#[cfg(target_os = "linux")]
pub fn start_tray() {
use std::time::Duration;
use glib::{clone, Continue};
use gtk::traits::{GtkMenuItemExt, MenuShellExt, WidgetExt};
info!("configuring tray");
@@ -106,9 +109,9 @@ pub fn start_tray() {
crate::client::translate("Stop service".to_owned())
};
let menu_item_service = gtk::MenuItem::with_label(label.as_str());
menu_item_service.connect_activate(move |item| {
menu_item_service.connect_activate(move |_| {
let _lock = crate::ui_interface::SENDER.lock().unwrap();
update_tray_service_item(item);
change_service_state();
});
menu.append(&menu_item_service);
// show tray item
@@ -116,6 +119,16 @@ pub fn start_tray() {
appindicator.set_menu(&mut menu);
// start event loop
info!("Setting tray event loop");
// check the connection status for every second
glib::timeout_add_local(
Duration::from_secs(1),
clone!(@strong menu_item_service as item => move || {
let _lock = crate::ui_interface::SENDER.lock().unwrap();
update_tray_service_item(&item);
// continue to trigger the next status check
Continue(true)
}),
);
gtk::main();
} else {
error!("Tray process exit now");
@@ -123,17 +136,25 @@ pub fn start_tray() {
}
#[cfg(target_os = "linux")]
fn change_service_state() {
if is_service_stoped() {
debug!("Now try to start service");
crate::ipc::set_option("stop-service", "");
} else {
debug!("Now try to stop service");
crate::ipc::set_option("stop-service", "Y");
}
}
#[cfg(target_os = "linux")]
#[inline]
fn update_tray_service_item(item: &gtk::MenuItem) {
use gtk::traits::GtkMenuItemExt;
if is_service_stoped() {
debug!("Now try to start service");
item.set_label(&crate::client::translate("Stop service".to_owned()));
crate::ipc::set_option("stop-service", "");
} else {
debug!("Now try to stop service");
item.set_label(&crate::client::translate("Start Service".to_owned()));
crate::ipc::set_option("stop-service", "Y");
} else {
item.set_label(&crate::client::translate("Stop service".to_owned()));
}
}
@@ -189,10 +210,10 @@ pub fn make_tray() {
match mode {
dark_light::Mode::Dark => {
icon_path = "mac-tray-light.png";
},
}
dark_light::Mode::Light => {
icon_path = "mac-tray-dark.png";
},
}
}
if let Ok(mut tray) = TrayItem::new(&crate::get_app_name(), icon_path) {
tray.add_label(&format!(
@@ -211,4 +232,3 @@ pub fn make_tray() {
}
}
}