use std::{path::Path, rc::Rc, sync::RwLock};
use crossbeam_channel::Sender;
use derivative::Derivative;
use gtk::{prelude::*, Menu, MenuItem, RadioMenuItem, SeparatorMenuItem};
use libappindicator::{AppIndicator, AppIndicatorStatus};
use log::{debug, error, warn};
use shadowsocks_gtk_rs::{consts::*, notify_method::NotifyMethod, util};
use crate::{event::AppEvent, io::profile_loader::ProfileFolder};
type ListeningRadioMenuItem = (RadioMenuItem, Rc<RwLock<bool>>);
#[derive(Debug, Clone)]
enum ProfileMenuItem {
Profile(ListeningRadioMenuItem),
Group(MenuItem),
}
#[derive(Derivative)]
#[derivative(Debug)]
pub struct TrayItem {
#[derivative(Debug(format_with = "shadowsocks_gtk_rs::util::hacks::omit_ai"))]
ai: AppIndicator,
menu: Menu,
manual_stop_item: ListeningRadioMenuItem,
profile_items: Vec<ListeningRadioMenuItem>,
notify_method_items: Vec<ListeningRadioMenuItem>,
}
impl TrayItem {
pub fn build_and_show(
icon_name: &str,
icon_theme_dir: Option<impl AsRef<Path>>,
events_tx: Sender<AppEvent>,
profile_folder: &ProfileFolder,
notify_method: NotifyMethod,
) -> Self {
let manual_stop_item = {
let events_tx = events_tx.clone();
let enable_flag = Rc::new(RwLock::new(true));
let enable_flag_mv = Rc::clone(&enable_flag);
let menu_item = RadioMenuItem::with_label("Stop sslocal");
menu_item.connect_toggled(move |item| {
if item.is_active() && *util::rwlock_read(&enable_flag_mv) {
if let Err(_) = events_tx.send(AppEvent::ManualStop) {
error!("Trying to send ManualStop event, but all receivers have hung up.");
}
}
});
(menu_item, enable_flag)
};
let mut tray = Self {
ai: match icon_theme_dir {
Some(dir) => {
let dir_str = dir.as_ref().to_str().unwrap(); AppIndicator::with_path(APP_NAME, icon_name, dir_str)
}
None => AppIndicator::new(APP_NAME, icon_name),
},
menu: Menu::new(),
manual_stop_item,
profile_items: vec![], notify_method_items: vec![], };
tray.ai.set_status(AppIndicatorStatus::Active);
tray.add_label("Profiles");
tray.add_separator();
tray.load_profiles(profile_folder, events_tx.clone());
tray.add_separator();
tray.menu.append(&tray.manual_stop_item.0);
let (notify_selector_item, notify_method_items) =
generate_notify_method_selector(notify_method, events_tx.clone());
tray.notify_method_items = notify_method_items;
tray.menu.append(¬ify_selector_item);
let log_viewer_tx = events_tx.clone();
tray.add_menu_item("Show sslocal Output", move || {
if let Err(_) = log_viewer_tx.send(AppEvent::LogViewerShow) {
error!("Trying to send LogViewerShow event, but all receivers have hung up.");
}
});
let quit_tx = events_tx.clone();
tray.add_menu_item("Quit", move || {
if let Err(_) = quit_tx.send(AppEvent::Quit) {
error!("Trying to send Quit event, but all receivers have hung up.");
}
});
tray.finalize();
tray
}
pub fn notify_sslocal_stop(&mut self) {
debug!("Setting tray to stopped state");
*util::rwlock_write(&self.manual_stop_item.1) = false; self.manual_stop_item.0.set_active(true);
*util::rwlock_write(&self.manual_stop_item.1) = true; }
pub fn notify_profile_switch(&mut self, name: impl AsRef<str>) {
let profile_item = self.profile_items.iter().find(|(item, _)| {
let item_name = item
.label()
.expect("A profile's RadioMenuItem has no label")
.to_string();
name.as_ref() == item_name
});
match profile_item {
Some((item, listen_enable)) => {
debug!("Setting tray to active state with profile \"{}\"", name.as_ref());
*util::rwlock_write(listen_enable) = false; item.set_active(true);
*util::rwlock_write(listen_enable) = true; }
None => warn!("Cannot find RadioMenuItem for profile named \"{}\"", name.as_ref()),
}
}
#[cfg(feature = "runtime-api")]
pub fn notify_notify_method_change(&mut self, method: NotifyMethod) {
let (method_item, listen_enable) = self
.notify_method_items
.iter()
.find(|(item, _)| {
let item_name = item
.label()
.unwrap() .to_string();
item_name == method.to_string()
})
.unwrap();
debug!("Setting tray to notification method \"{}\"", method);
*util::rwlock_write(listen_enable) = false; method_item.set_active(true);
*util::rwlock_write(listen_enable) = true; }
fn add_separator(&mut self) {
let sep = SeparatorMenuItem::new();
self.menu.append(&sep);
}
fn add_label(&mut self, label: &str) {
let item = MenuItem::with_label(label.as_ref());
item.set_sensitive(false);
self.menu.append(&item);
}
fn add_menu_item<F>(&mut self, label: &str, action: F)
where
F: Fn() -> () + Send + Sync + 'static,
{
let item = MenuItem::with_label(label);
item.connect_activate(move |_| action());
self.menu.append(&item);
}
fn load_profiles(&mut self, profile_folder: &ProfileFolder, events_tx: Sender<AppEvent>) {
let radio_group = &self.manual_stop_item.0; let mut radio_menu_item_list = vec![];
match profile_folder {
ProfileFolder::Group(g) => {
for cf in g.content.iter() {
let child = generate_profile_tree(cf, radio_group, events_tx.clone(), &mut radio_menu_item_list);
match child {
ProfileMenuItem::Profile(radio_item) => {
self.menu.append(&radio_item.0); radio_menu_item_list.push(radio_item); }
ProfileMenuItem::Group(item) => self.menu.append(&item), }
}
}
profile => {
let profile_menu_item =
generate_profile_tree(profile, radio_group, events_tx, &mut radio_menu_item_list);
match profile_menu_item {
ProfileMenuItem::Profile(radio_item) => {
self.menu.append(&radio_item.0); radio_menu_item_list.push(radio_item); }
ProfileMenuItem::Group(_) => unreachable!("profile_menu_item should be a profile"),
}
}
}
self.profile_items = radio_menu_item_list;
}
fn finalize(&mut self) {
self.menu.show_all();
self.ai.set_menu(&mut self.menu);
}
}
fn generate_profile_tree(
profile_folder: &ProfileFolder,
group: &impl IsA<RadioMenuItem>,
events_tx: Sender<AppEvent>,
radio_menu_item_list: &mut Vec<ListeningRadioMenuItem>,
) -> ProfileMenuItem {
match profile_folder {
ProfileFolder::Profile(p) => {
let profile = p.clone();
let enable_flag = Rc::new(RwLock::new(true));
let enable_flag_mv = Rc::clone(&enable_flag);
let menu_item = RadioMenuItem::with_label_from_widget(group, Some(&p.metadata.display_name));
menu_item.set_sensitive(true);
menu_item.connect_toggled(move |item| {
if item.is_active() && *util::rwlock_read(&enable_flag_mv) {
if let Err(_) = events_tx.send(AppEvent::SwitchProfile(profile.clone())) {
error!("Trying to send SwitchProfile event, but all receivers have hung up.");
}
}
});
ProfileMenuItem::Profile((menu_item, enable_flag))
}
ProfileFolder::Group(g) => {
let submenu = Menu::new();
for cf in g.content.iter() {
match generate_profile_tree(cf, group, events_tx.clone(), radio_menu_item_list) {
ProfileMenuItem::Profile(radio_item) => {
submenu.append(&radio_item.0); radio_menu_item_list.push(radio_item); }
ProfileMenuItem::Group(item) => submenu.append(&item), }
}
let parent = MenuItem::with_label(&g.display_name);
parent.set_sensitive(true);
parent.set_submenu(Some(&submenu));
ProfileMenuItem::Group(parent)
}
}
}
fn generate_notify_method_selector(
initial: NotifyMethod,
events_tx: Sender<AppEvent>,
) -> (MenuItem, Vec<ListeningRadioMenuItem>) {
let radios: Vec<_> = enum_iterator::all::<NotifyMethod>()
.map(|method| {
let radio_item = RadioMenuItem::with_label(&method.to_string());
radio_item.set_sensitive(true);
(radio_item, method)
})
.collect();
let group_ref = &radios[0].0;
radios
.iter()
.for_each(|(radio_item, _)| radio_item.join_group(Some(group_ref)));
radios
.iter()
.find(|(_, method)| *method == initial)
.unwrap() .0
.set_active(true);
let submenu = Menu::new();
radios.iter().for_each(|(radio_item, _)| submenu.append(radio_item));
let connected_radios = radios
.into_iter()
.map(|(radio_item, method)| {
let enable_flag = Rc::new(RwLock::new(true));
let enable_flag_mv = Rc::clone(&enable_flag);
let events_tx = events_tx.clone();
radio_item.connect_toggled(move |radio| {
if radio.is_active() && *util::rwlock_read(&enable_flag_mv) {
if let Err(_) = events_tx.send(AppEvent::SetNotify(method)) {
error!("Trying to send SetNotify event, but all receivers have hung up.");
}
}
});
(radio_item, enable_flag)
})
.collect();
let parent = MenuItem::with_label("Notifications");
parent.set_sensitive(true);
parent.set_submenu(Some(&submenu));
(parent, connected_radios)
}