mirror of
https://github.com/Zedfrigg/ironbar.git
synced 2025-08-17 14:51:04 +02:00
Merge pull request #609 from ClaireNeveu/menu-widget
feat: Add Menu module
This commit is contained in:
commit
333796a9ae
14 changed files with 1419 additions and 6 deletions
|
@ -21,6 +21,8 @@ use crate::modules::keyboard::KeyboardModule;
|
|||
use crate::modules::label::LabelModule;
|
||||
#[cfg(feature = "launcher")]
|
||||
use crate::modules::launcher::LauncherModule;
|
||||
#[cfg(feature = "menu")]
|
||||
use crate::modules::menu::MenuModule;
|
||||
#[cfg(feature = "music")]
|
||||
use crate::modules::music::MusicModule;
|
||||
#[cfg(feature = "network_manager")]
|
||||
|
@ -75,6 +77,8 @@ pub enum ModuleConfig {
|
|||
Label(Box<LabelModule>),
|
||||
#[cfg(feature = "launcher")]
|
||||
Launcher(Box<LauncherModule>),
|
||||
#[cfg(feature = "menu")]
|
||||
Menu(Box<MenuModule>),
|
||||
#[cfg(feature = "music")]
|
||||
Music(Box<MusicModule>),
|
||||
#[cfg(feature = "network_manager")]
|
||||
|
@ -127,6 +131,8 @@ impl ModuleConfig {
|
|||
Self::Label(module) => create!(module),
|
||||
#[cfg(feature = "launcher")]
|
||||
Self::Launcher(module) => create!(module),
|
||||
#[cfg(feature = "menu")]
|
||||
Self::Menu(module) => create!(module),
|
||||
#[cfg(feature = "music")]
|
||||
Self::Music(module) => create!(module),
|
||||
#[cfg(feature = "network_manager")]
|
||||
|
|
|
@ -53,6 +53,8 @@ impl DesktopFileRef {
|
|||
let mut has_wm_class = false;
|
||||
let mut has_exec = false;
|
||||
let mut has_icon = false;
|
||||
let mut has_categories = false;
|
||||
let mut has_no_display = false;
|
||||
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
let Some((key, value)) = line.split_once('=') else {
|
||||
|
@ -60,31 +62,46 @@ impl DesktopFileRef {
|
|||
};
|
||||
|
||||
match key {
|
||||
"Name" => {
|
||||
"Name" if !has_name => {
|
||||
desktop_file.name = Some(value.to_string());
|
||||
has_name = true;
|
||||
}
|
||||
"Type" => {
|
||||
"Type" if !has_type => {
|
||||
desktop_file.app_type = Some(value.to_string());
|
||||
has_type = true;
|
||||
}
|
||||
"StartupWMClass" => {
|
||||
"StartupWMClass" if !has_wm_class => {
|
||||
desktop_file.startup_wm_class = Some(value.to_string());
|
||||
has_wm_class = true;
|
||||
}
|
||||
"Exec" => {
|
||||
"Exec" if !has_exec => {
|
||||
desktop_file.exec = Some(value.to_string());
|
||||
has_exec = true;
|
||||
}
|
||||
"Icon" => {
|
||||
"Icon" if !has_icon => {
|
||||
desktop_file.icon = Some(value.to_string());
|
||||
has_icon = true;
|
||||
}
|
||||
"Categories" if !has_categories => {
|
||||
desktop_file.categories = value.split(';').map(|s| s.to_string()).collect();
|
||||
has_categories = true;
|
||||
}
|
||||
"NoDisplay" if !has_no_display => {
|
||||
desktop_file.no_display = Some(value.parse()?);
|
||||
has_no_display = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// parsing complete - don't bother with the rest of the lines
|
||||
if has_name && has_type && has_wm_class && has_exec && has_icon {
|
||||
if has_name
|
||||
&& has_type
|
||||
&& has_wm_class
|
||||
&& has_exec
|
||||
&& has_icon
|
||||
&& has_categories
|
||||
&& has_no_display
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
@ -101,6 +118,8 @@ pub struct DesktopFile {
|
|||
pub startup_wm_class: Option<String>,
|
||||
pub exec: Option<String>,
|
||||
pub icon: Option<String>,
|
||||
pub categories: Vec<String>,
|
||||
pub no_display: Option<bool>,
|
||||
}
|
||||
|
||||
impl DesktopFile {
|
||||
|
@ -112,6 +131,8 @@ impl DesktopFile {
|
|||
startup_wm_class: None,
|
||||
exec: None,
|
||||
icon: None,
|
||||
categories: vec![],
|
||||
no_display: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -159,6 +180,18 @@ impl DesktopFiles {
|
|||
}
|
||||
}
|
||||
|
||||
pub async fn get_all(&self) -> Result<Vec<DesktopFile>> {
|
||||
let mut files = self.files.lock().await;
|
||||
|
||||
let mut res = Vec::with_capacity(files.len());
|
||||
for file in files.values_mut() {
|
||||
let file = file.get().await?;
|
||||
res.push(file);
|
||||
}
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
/// Attempts to locate a applications file by file name or contents.
|
||||
///
|
||||
/// Input should typically be the app id, app name or icon.
|
||||
|
|
271
src/modules/menu/config.rs
Normal file
271
src/modules/menu/config.rs
Normal file
|
@ -0,0 +1,271 @@
|
|||
use crate::config::{CommonConfig, TruncateMode};
|
||||
use crate::modules::menu::{MenuEntry, XdgSection};
|
||||
use indexmap::IndexMap;
|
||||
use serde::Deserialize;
|
||||
|
||||
/// An individual entry in the main menu section.
|
||||
#[derive(Debug, Deserialize, Clone)]
|
||||
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum MenuConfig {
|
||||
/// Contains all applications matching the configured `categories`.
|
||||
XdgEntry(XdgEntry),
|
||||
/// Contains all applications not covered by `xdg_entry` categories.
|
||||
XdgOther,
|
||||
/// Individual shell command entry.
|
||||
Custom(CustomEntry),
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Clone)]
|
||||
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
|
||||
pub struct XdgEntry {
|
||||
/// Text to display on the button.
|
||||
#[serde(default)]
|
||||
pub label: String,
|
||||
|
||||
/// Name of the image icon to show next to the label.
|
||||
#[serde(default)]
|
||||
pub icon: Option<String>,
|
||||
|
||||
/// XDG categories the associated submenu should contain.
|
||||
#[serde(default)]
|
||||
pub categories: Vec<String>,
|
||||
}
|
||||
|
||||
/// Individual shell command entry.
|
||||
#[derive(Debug, Deserialize, Clone)]
|
||||
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
|
||||
pub struct CustomEntry {
|
||||
/// Text to display on the button.
|
||||
#[serde(default)]
|
||||
pub label: String,
|
||||
|
||||
/// Name of the image icon to show next to the label.
|
||||
///
|
||||
/// **Default**: `null`
|
||||
pub icon: Option<String>,
|
||||
|
||||
/// Shell command to execute when the button is clicked.
|
||||
/// This is run using `sh -c`.
|
||||
#[serde(default)]
|
||||
pub on_click: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Clone)]
|
||||
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
|
||||
pub struct MenuModule {
|
||||
/// Items to add to the start of the main menu.
|
||||
///
|
||||
/// **Default**: `[]`
|
||||
#[serde(default)]
|
||||
pub(super) start: Vec<MenuConfig>,
|
||||
|
||||
/// Items to add to the start of the main menu.
|
||||
///
|
||||
/// By default, this shows a number of XDG entries
|
||||
/// that should cover all common applications.
|
||||
///
|
||||
/// **Default**: See `examples/menu/default`
|
||||
#[serde(default = "default_menu")]
|
||||
pub(super) center: Vec<MenuConfig>,
|
||||
|
||||
/// Items to add to the end of the main menu.
|
||||
///
|
||||
/// **Default**: `[]`
|
||||
#[serde(default)]
|
||||
pub(super) end: Vec<MenuConfig>,
|
||||
|
||||
/// Fixed height of the menu.
|
||||
///
|
||||
/// When set, if the number of (sub)menu entries exceeds this value,
|
||||
/// a scrollbar will be shown.
|
||||
///
|
||||
/// Leave null to resize dynamically.
|
||||
///
|
||||
/// **Default**: `null`
|
||||
#[serde(default)]
|
||||
pub(super) height: Option<i32>,
|
||||
|
||||
/// Fixed width of the menu.
|
||||
///
|
||||
/// Can be used with `truncate` options
|
||||
/// to customise how item labels are truncated.
|
||||
///
|
||||
/// **Default**: `null`
|
||||
#[serde(default)]
|
||||
pub(super) width: Option<i32>,
|
||||
|
||||
/// Label to show on the menu button on the bar.
|
||||
///
|
||||
/// **Default**: `≡`
|
||||
#[serde(default = "default_menu_popup_label")]
|
||||
pub(super) label: Option<String>,
|
||||
|
||||
/// Icon to show on the menu button on the bar.
|
||||
///
|
||||
/// **Default**: `null`
|
||||
#[serde(default)]
|
||||
pub(super) label_icon: Option<String>,
|
||||
|
||||
/// Size of the `label_icon` image.
|
||||
#[serde(default = "default_menu_popup_icon_size")]
|
||||
pub(super) label_icon_size: i32,
|
||||
|
||||
// -- common --
|
||||
/// Truncate options to apply to (sub)menu item labels.
|
||||
///
|
||||
/// See [truncate options](module-level-options#truncate-mode).
|
||||
///
|
||||
/// **Default**: `Auto (end)`
|
||||
#[serde(default)]
|
||||
pub(super) truncate: TruncateMode,
|
||||
|
||||
/// See [common options](module-level-options#common-options).
|
||||
#[serde(flatten)]
|
||||
pub common: Option<CommonConfig>,
|
||||
}
|
||||
|
||||
impl Default for MenuModule {
|
||||
fn default() -> Self {
|
||||
MenuModule {
|
||||
start: vec![],
|
||||
center: default_menu(),
|
||||
end: vec![],
|
||||
height: None,
|
||||
width: None,
|
||||
truncate: TruncateMode::default(),
|
||||
// max_label_length: default_length(),
|
||||
label: default_menu_popup_label(),
|
||||
label_icon: None,
|
||||
label_icon_size: default_menu_popup_icon_size(),
|
||||
common: Some(CommonConfig::default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_menu() -> Vec<MenuConfig> {
|
||||
vec![
|
||||
MenuConfig::XdgEntry(XdgEntry {
|
||||
label: "Accessories".to_string(),
|
||||
icon: Some("accessories".to_string()),
|
||||
categories: vec![
|
||||
"Accessibility".to_string(),
|
||||
"Core".to_string(),
|
||||
"Legacy".to_string(),
|
||||
"Utility".to_string(),
|
||||
],
|
||||
}),
|
||||
MenuConfig::XdgEntry(XdgEntry {
|
||||
label: "Development".to_string(),
|
||||
icon: Some("applications-development".to_string()),
|
||||
categories: vec!["Development".to_string()],
|
||||
}),
|
||||
MenuConfig::XdgEntry(XdgEntry {
|
||||
label: "Education".to_string(),
|
||||
icon: Some("applications-education".to_string()),
|
||||
categories: vec!["Education".to_string()],
|
||||
}),
|
||||
MenuConfig::XdgEntry(XdgEntry {
|
||||
label: "Games".to_string(),
|
||||
icon: Some("applications-games".to_string()),
|
||||
categories: vec!["Game".to_string()],
|
||||
}),
|
||||
MenuConfig::XdgEntry(XdgEntry {
|
||||
label: "Graphics".to_string(),
|
||||
icon: Some("applications-graphics".to_string()),
|
||||
categories: vec!["Graphics".to_string()],
|
||||
}),
|
||||
MenuConfig::XdgEntry(XdgEntry {
|
||||
label: "Multimedia".to_string(),
|
||||
icon: Some("applications-multimedia".to_string()),
|
||||
categories: vec![
|
||||
"Audio".to_string(),
|
||||
"Video".to_string(),
|
||||
"AudioVideo".to_string(),
|
||||
],
|
||||
}),
|
||||
MenuConfig::XdgEntry(XdgEntry {
|
||||
label: "Network".to_string(),
|
||||
icon: Some("applications-internet".to_string()),
|
||||
categories: vec!["Network".to_string()],
|
||||
}),
|
||||
MenuConfig::XdgEntry(XdgEntry {
|
||||
label: "Office".to_string(),
|
||||
icon: Some("applications-office".to_string()),
|
||||
categories: vec!["Office".to_string()],
|
||||
}),
|
||||
MenuConfig::XdgEntry(XdgEntry {
|
||||
label: "Science".to_string(),
|
||||
icon: Some("applications-science".to_string()),
|
||||
categories: vec!["Science".to_string()],
|
||||
}),
|
||||
MenuConfig::XdgEntry(XdgEntry {
|
||||
label: "System".to_string(),
|
||||
icon: Some("applications-system".to_string()),
|
||||
categories: vec!["Emulator".to_string(), "System".to_string()],
|
||||
}),
|
||||
MenuConfig::XdgOther,
|
||||
MenuConfig::XdgEntry(XdgEntry {
|
||||
label: "Settings".to_string(),
|
||||
icon: Some("preferences-system".to_string()),
|
||||
categories: vec!["Settings".to_string(), "Screensaver".to_string()],
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
fn default_menu_popup_label() -> Option<String> {
|
||||
Some("≡".to_string())
|
||||
}
|
||||
|
||||
const fn default_menu_popup_icon_size() -> i32 {
|
||||
16
|
||||
}
|
||||
|
||||
pub const OTHER_LABEL: &str = "Other";
|
||||
|
||||
pub fn parse_config(
|
||||
section_config: Vec<MenuConfig>,
|
||||
sections_by_cat: &mut IndexMap<String, Vec<String>>,
|
||||
) -> IndexMap<String, MenuEntry> {
|
||||
section_config
|
||||
.into_iter()
|
||||
.map(|entry_config| match entry_config {
|
||||
MenuConfig::XdgEntry(entry) => {
|
||||
entry.categories.into_iter().for_each(|cat| {
|
||||
let existing = sections_by_cat.get_mut(&cat);
|
||||
|
||||
if let Some(existing) = existing {
|
||||
existing.push(entry.label.clone());
|
||||
} else {
|
||||
sections_by_cat.insert(cat, vec![entry.label.clone()]);
|
||||
}
|
||||
});
|
||||
|
||||
(
|
||||
entry.label.clone(),
|
||||
MenuEntry::Xdg(XdgSection {
|
||||
label: entry.label,
|
||||
icon: entry.icon,
|
||||
applications: IndexMap::new(),
|
||||
}),
|
||||
)
|
||||
}
|
||||
MenuConfig::XdgOther => (
|
||||
OTHER_LABEL.to_string(),
|
||||
MenuEntry::Xdg(XdgSection {
|
||||
label: OTHER_LABEL.to_string(),
|
||||
icon: Some("applications-other".to_string()),
|
||||
applications: IndexMap::new(),
|
||||
}),
|
||||
),
|
||||
MenuConfig::Custom(entry) => (
|
||||
entry.label.clone(),
|
||||
MenuEntry::Custom(CustomEntry {
|
||||
icon: entry.icon,
|
||||
label: entry.label,
|
||||
on_click: entry.on_click,
|
||||
}),
|
||||
),
|
||||
})
|
||||
.collect()
|
||||
}
|
321
src/modules/menu/mod.rs
Normal file
321
src/modules/menu/mod.rs
Normal file
|
@ -0,0 +1,321 @@
|
|||
mod config;
|
||||
mod ui;
|
||||
|
||||
use color_eyre::Result;
|
||||
use color_eyre::eyre::Report;
|
||||
use config::*;
|
||||
use gtk::prelude::*;
|
||||
use gtk::{Align, Button, Orientation};
|
||||
use indexmap::IndexMap;
|
||||
use serde::Deserialize;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use super::{ModuleLocation, PopupButton};
|
||||
use crate::channels::{AsyncSenderExt, BroadcastReceiverExt};
|
||||
use crate::config::BarPosition;
|
||||
use crate::gtk_helpers::IronbarGtkExt;
|
||||
use crate::modules::{
|
||||
Module, ModuleInfo, ModuleParts, ModulePopup, ModuleUpdateEvent, WidgetContext,
|
||||
};
|
||||
use crate::{module_impl, spawn};
|
||||
|
||||
pub use config::MenuModule;
|
||||
|
||||
/// XDG button and menu from parsed config.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct XdgSection {
|
||||
pub label: String,
|
||||
pub icon: Option<String>,
|
||||
pub applications: IndexMap<String, MenuApplication>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Clone)]
|
||||
pub struct MenuApplication {
|
||||
pub label: String,
|
||||
pub file_name: String,
|
||||
pub categories: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum MenuEntry {
|
||||
Xdg(XdgSection),
|
||||
Custom(CustomEntry),
|
||||
}
|
||||
|
||||
impl MenuEntry {
|
||||
pub fn label(&self) -> String {
|
||||
match self {
|
||||
Self::Xdg(entry) => entry.label.clone(),
|
||||
Self::Custom(entry) => entry.label.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn icon(&self) -> Option<String> {
|
||||
match self {
|
||||
Self::Xdg(entry) => entry.icon.clone(),
|
||||
Self::Custom(entry) => entry.icon.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Module<Button> for MenuModule {
|
||||
type SendMessage = Vec<MenuApplication>;
|
||||
type ReceiveMessage = ();
|
||||
|
||||
module_impl!("menu");
|
||||
|
||||
fn spawn_controller(
|
||||
&self,
|
||||
_info: &ModuleInfo,
|
||||
context: &WidgetContext<Self::SendMessage, Self::ReceiveMessage>,
|
||||
mut rx: mpsc::Receiver<Self::ReceiveMessage>,
|
||||
) -> Result<()> {
|
||||
let tx = context.tx.clone();
|
||||
// let max_label_length = self.max_label_length;
|
||||
|
||||
let desktop_files = context.ironbar.desktop_files();
|
||||
|
||||
spawn(async move {
|
||||
// parsing all desktop files is heavy so wait until the popup is first opened before loading
|
||||
rx.recv().await;
|
||||
|
||||
let apps = desktop_files
|
||||
.get_all()
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter(|file| {
|
||||
file.no_display != Some(true)
|
||||
&& file.app_type.as_deref().is_some_and(|v| v == "Application")
|
||||
})
|
||||
.map(|file| MenuApplication {
|
||||
label: file.name.unwrap_or_default(),
|
||||
file_name: file.file_name,
|
||||
categories: file.categories,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
tx.send_update_spawn(apps);
|
||||
Ok::<(), Report>(())
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn into_widget(
|
||||
self,
|
||||
context: WidgetContext<Self::SendMessage, Self::ReceiveMessage>,
|
||||
info: &ModuleInfo,
|
||||
) -> Result<ModuleParts<Button>> {
|
||||
let button = Button::new();
|
||||
|
||||
if let Some(ref label) = self.label {
|
||||
button.set_label(label);
|
||||
}
|
||||
|
||||
if let Some(ref label_icon) = self.label_icon {
|
||||
let image_provider = context.ironbar.image_provider();
|
||||
|
||||
let gtk_image = gtk::Image::new();
|
||||
button.set_image(Some(>k_image));
|
||||
button.set_always_show_image(true);
|
||||
|
||||
let label_icon = label_icon.clone();
|
||||
|
||||
glib::spawn_future_local(async move {
|
||||
image_provider
|
||||
.load_into_image_silent(&label_icon, self.label_icon_size, true, >k_image)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
|
||||
let tx = context.tx.clone();
|
||||
let controller_tx = context.controller_tx.clone();
|
||||
button.connect_clicked(move |button| {
|
||||
tx.send_spawn(ModuleUpdateEvent::TogglePopup(button.popup_id()));
|
||||
|
||||
// channel will close after init event
|
||||
if !controller_tx.is_closed() {
|
||||
controller_tx.send_spawn(());
|
||||
}
|
||||
});
|
||||
|
||||
let popup = self
|
||||
.into_popup(context, info)
|
||||
.into_popup_parts(vec![&button]);
|
||||
|
||||
Ok(ModuleParts::new(button, popup))
|
||||
}
|
||||
|
||||
fn into_popup(
|
||||
self,
|
||||
context: WidgetContext<Self::SendMessage, Self::ReceiveMessage>,
|
||||
info: &ModuleInfo,
|
||||
) -> Option<gtk::Box> {
|
||||
let image_provider = context.ironbar.image_provider();
|
||||
|
||||
let alignment = {
|
||||
match info.bar_position {
|
||||
// For fixed height menus always align to the top
|
||||
_ if self.height.is_some() => Align::Start,
|
||||
|
||||
// Otherwise alignment is based on menu position
|
||||
BarPosition::Top => Align::Start,
|
||||
BarPosition::Bottom => Align::End,
|
||||
|
||||
_ => match &info.location {
|
||||
&ModuleLocation::Left | &ModuleLocation::Center => Align::Start,
|
||||
&ModuleLocation::Right => Align::End,
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
let mut sections_by_cat = IndexMap::<String, Vec<String>>::new();
|
||||
|
||||
let container = gtk::Box::new(Orientation::Horizontal, 4);
|
||||
|
||||
let main_menu = gtk::Box::new(Orientation::Vertical, 0);
|
||||
main_menu.set_valign(alignment);
|
||||
main_menu.set_vexpand(false);
|
||||
main_menu.add_class("main");
|
||||
|
||||
if let Some(width) = self.width {
|
||||
main_menu.set_width_request(width / 2);
|
||||
}
|
||||
|
||||
if let Some(max_height) = self.height {
|
||||
container.set_height_request(max_height);
|
||||
|
||||
let scrolled = gtk::ScrolledWindow::builder()
|
||||
.max_content_height(max_height)
|
||||
.hscrollbar_policy(gtk::PolicyType::Never)
|
||||
.build();
|
||||
|
||||
scrolled.add(&main_menu);
|
||||
container.add(&scrolled);
|
||||
} else {
|
||||
container.add(&main_menu);
|
||||
}
|
||||
container.show_all();
|
||||
|
||||
let mut start_entries = parse_config(self.start, &mut sections_by_cat);
|
||||
let mut center_entries = parse_config(self.center, &mut sections_by_cat);
|
||||
let mut end_entries = parse_config(self.end, &mut sections_by_cat);
|
||||
|
||||
let start_section = gtk::Box::new(Orientation::Vertical, 0);
|
||||
let center_section = gtk::Box::new(Orientation::Vertical, 0);
|
||||
let end_section = gtk::Box::new(Orientation::Vertical, 0);
|
||||
|
||||
start_section.add_class("main-start");
|
||||
center_section.add_class("main-center");
|
||||
end_section.add_class("main-end");
|
||||
|
||||
let container2 = container.clone();
|
||||
{
|
||||
let main_menu = main_menu.clone();
|
||||
let container = container.clone();
|
||||
let start_section = start_section.clone();
|
||||
let center_section = center_section.clone();
|
||||
let end_section = end_section.clone();
|
||||
|
||||
let truncate_mode = self.truncate;
|
||||
|
||||
context.subscribe().recv_glib(move |applications| {
|
||||
for application in applications.iter() {
|
||||
let mut inserted = false;
|
||||
|
||||
for category in application.categories.iter() {
|
||||
if let Some(section_names) = sections_by_cat.get(category) {
|
||||
for section_name in section_names.iter() {
|
||||
[&mut start_entries, &mut center_entries, &mut end_entries]
|
||||
.into_iter()
|
||||
.for_each(|entries| {
|
||||
let existing = entries.get_mut(section_name);
|
||||
if let Some(MenuEntry::Xdg(existing)) = existing {
|
||||
existing.applications.insert_sorted(
|
||||
application.label.clone(),
|
||||
application.clone(),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
inserted = true;
|
||||
}
|
||||
}
|
||||
|
||||
if !inserted {
|
||||
let other = center_entries.get_mut(OTHER_LABEL);
|
||||
if let Some(MenuEntry::Xdg(other)) = other {
|
||||
let _ = other
|
||||
.applications
|
||||
.insert_sorted(application.label.clone(), application.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main_menu.foreach(|child| {
|
||||
main_menu.remove(child);
|
||||
});
|
||||
|
||||
macro_rules! add_entries {
|
||||
($entries:expr, $section:expr) => {
|
||||
for entry in $entries.values() {
|
||||
let container1 = container.clone();
|
||||
let tx = context.tx.clone();
|
||||
let (button, sub_menu) =
|
||||
ui::make_entry(entry, tx, &image_provider, truncate_mode);
|
||||
|
||||
if let Some(sub_menu) = sub_menu.clone() {
|
||||
sub_menu.set_valign(alignment);
|
||||
sub_menu.add_class("sub-menu");
|
||||
if let Some(width) = self.width {
|
||||
sub_menu.set_width_request(width / 2);
|
||||
}
|
||||
}
|
||||
|
||||
ui::add_entries(
|
||||
entry,
|
||||
button,
|
||||
sub_menu.as_ref(),
|
||||
$section,
|
||||
&container1,
|
||||
self.height,
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
add_entries!(&start_entries, &start_section);
|
||||
add_entries!(¢er_entries, ¢er_section);
|
||||
add_entries!(&end_entries, &end_section);
|
||||
|
||||
main_menu.add(&start_section);
|
||||
main_menu.add(¢er_section);
|
||||
main_menu.add(&end_section);
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
let container = container2;
|
||||
|
||||
context.popup.window.connect_hide(move |_| {
|
||||
start_section.foreach(|child| {
|
||||
child.remove_class("open");
|
||||
});
|
||||
|
||||
center_section.foreach(|child| {
|
||||
child.remove_class("open");
|
||||
});
|
||||
|
||||
end_section.foreach(|child| {
|
||||
child.remove_class("open");
|
||||
});
|
||||
|
||||
container.children().iter().skip(1).for_each(|sub_menu| {
|
||||
sub_menu.hide();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Some(container)
|
||||
}
|
||||
}
|
221
src/modules/menu/ui.rs
Normal file
221
src/modules/menu/ui.rs
Normal file
|
@ -0,0 +1,221 @@
|
|||
use super::MenuEntry;
|
||||
use crate::channels::AsyncSenderExt;
|
||||
use crate::config::TruncateMode;
|
||||
use crate::gtk_helpers::{IronbarGtkExt, IronbarLabelExt};
|
||||
use crate::modules::ModuleUpdateEvent;
|
||||
use crate::script::Script;
|
||||
use crate::{image, spawn};
|
||||
use color_eyre::{Help, Report};
|
||||
use gtk::prelude::*;
|
||||
use gtk::{Align, Button, Label, Orientation};
|
||||
use std::process::{Command, Stdio};
|
||||
use tokio::sync::mpsc;
|
||||
use tracing::{debug, error};
|
||||
|
||||
pub fn make_entry<R>(
|
||||
entry: &MenuEntry,
|
||||
tx: mpsc::Sender<ModuleUpdateEvent<R>>,
|
||||
image_provider: &image::Provider,
|
||||
truncate_mode: TruncateMode,
|
||||
) -> (Button, Option<gtk::Box>)
|
||||
where
|
||||
R: Send + Clone + 'static,
|
||||
{
|
||||
let button = Button::new();
|
||||
button.add_class("category");
|
||||
|
||||
let button_container = gtk::Box::new(Orientation::Horizontal, 4);
|
||||
button.add(&button_container);
|
||||
|
||||
let label = Label::new(Some(&entry.label()));
|
||||
label.set_halign(Align::Start);
|
||||
label.truncate(truncate_mode);
|
||||
|
||||
if let Some(icon_name) = entry.icon() {
|
||||
let gtk_image = gtk::Image::new();
|
||||
gtk_image.set_halign(Align::Start);
|
||||
button_container.add(>k_image);
|
||||
|
||||
let image_provider = image_provider.clone();
|
||||
glib::spawn_future_local(async move {
|
||||
image_provider
|
||||
.load_into_image_silent(&icon_name, 16, true, >k_image)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
|
||||
button_container.add(&label);
|
||||
button_container.foreach(|child| {
|
||||
child.set_halign(Align::Start);
|
||||
});
|
||||
|
||||
if let MenuEntry::Xdg(_) = entry {
|
||||
let right_arrow = Label::new(Some("🢒"));
|
||||
right_arrow.set_halign(Align::End);
|
||||
button_container.pack_end(&right_arrow, false, false, 0);
|
||||
}
|
||||
|
||||
button.show_all();
|
||||
|
||||
let sub_menu = match entry {
|
||||
MenuEntry::Xdg(entry) => {
|
||||
let sub_menu = gtk::Box::new(Orientation::Vertical, 0);
|
||||
|
||||
entry.applications.values().for_each(|sub_entry| {
|
||||
let button = Button::new();
|
||||
button.add_class("application");
|
||||
|
||||
let button_container = gtk::Box::new(Orientation::Horizontal, 4);
|
||||
button.add(&button_container);
|
||||
|
||||
let label = Label::new(Some(&sub_entry.label));
|
||||
label.set_halign(Align::Start);
|
||||
label.truncate(truncate_mode);
|
||||
|
||||
let icon_name = sub_entry.file_name.trim_end_matches(".desktop").to_string();
|
||||
let gtk_image = gtk::Image::new();
|
||||
gtk_image.set_halign(Align::Start);
|
||||
|
||||
button_container.add(>k_image);
|
||||
button_container.add(&label);
|
||||
|
||||
let image_provider = image_provider.clone();
|
||||
|
||||
glib::spawn_future_local(async move {
|
||||
image_provider
|
||||
.load_into_image_silent(&icon_name, 16, true, >k_image)
|
||||
.await;
|
||||
});
|
||||
|
||||
button.foreach(|child| {
|
||||
child.set_halign(Align::Start);
|
||||
});
|
||||
|
||||
sub_menu.add(&button);
|
||||
|
||||
{
|
||||
let sub_menu = sub_menu.clone();
|
||||
let file_name = sub_entry.file_name.clone();
|
||||
let tx = tx.clone();
|
||||
|
||||
button.connect_clicked(move |_button| {
|
||||
if let Err(err) = Command::new("gtk-launch")
|
||||
.arg(&file_name)
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
{
|
||||
error!(
|
||||
"{:?}",
|
||||
Report::new(err)
|
||||
.wrap_err("Failed to run gtk-launch command.")
|
||||
.suggestion("Perhaps the applications file is invalid?")
|
||||
);
|
||||
}
|
||||
|
||||
sub_menu.hide();
|
||||
tx.send_spawn(ModuleUpdateEvent::ClosePopup);
|
||||
});
|
||||
}
|
||||
|
||||
button.show_all();
|
||||
});
|
||||
|
||||
Some(sub_menu)
|
||||
}
|
||||
MenuEntry::Custom(_) => None,
|
||||
};
|
||||
|
||||
(button, sub_menu)
|
||||
}
|
||||
|
||||
pub fn add_entries(
|
||||
entry: &MenuEntry,
|
||||
button: Button,
|
||||
sub_menu: Option<>k::Box>,
|
||||
main_menu: >k::Box,
|
||||
container: >k::Box,
|
||||
height: Option<i32>,
|
||||
) {
|
||||
let container1 = container.clone();
|
||||
main_menu.add(&button);
|
||||
|
||||
if let Some(sub_menu) = sub_menu {
|
||||
if let Some(height) = height {
|
||||
container.set_height_request(height);
|
||||
|
||||
let scrolled = gtk::ScrolledWindow::builder()
|
||||
.max_content_height(height)
|
||||
.hscrollbar_policy(gtk::PolicyType::Never)
|
||||
.build();
|
||||
|
||||
sub_menu.show();
|
||||
scrolled.add(sub_menu);
|
||||
container.add(&scrolled);
|
||||
|
||||
let sub_menu1 = scrolled.clone();
|
||||
let sub_menu_popup_container = sub_menu.clone();
|
||||
|
||||
button.connect_clicked(move |button| {
|
||||
container1.children().iter().skip(1).for_each(|sub_menu| {
|
||||
if sub_menu.get_visible() {
|
||||
sub_menu.hide();
|
||||
}
|
||||
});
|
||||
|
||||
button
|
||||
.parent()
|
||||
.expect("button parent should exist")
|
||||
.downcast::<gtk::Box>()
|
||||
.expect("button container should be gtk::Box")
|
||||
.children()
|
||||
.iter()
|
||||
.for_each(|child| child.remove_class("open"));
|
||||
|
||||
sub_menu1.show_all();
|
||||
button.add_class("open");
|
||||
|
||||
// Reset scroll to top.
|
||||
if let Some(w) = sub_menu_popup_container.children().first() {
|
||||
w.set_has_focus(true)
|
||||
}
|
||||
});
|
||||
} else {
|
||||
container.add(sub_menu);
|
||||
let sub_menu1 = sub_menu.clone();
|
||||
|
||||
button.connect_clicked(move |_button| {
|
||||
container1.children().iter().skip(1).for_each(|sub_menu| {
|
||||
if sub_menu.get_visible() {
|
||||
sub_menu.hide();
|
||||
}
|
||||
});
|
||||
sub_menu1.show();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if let MenuEntry::Custom(entry) = entry {
|
||||
let label = entry.on_click.clone();
|
||||
let container = container.clone();
|
||||
|
||||
button.connect_clicked(move |_button| {
|
||||
container.children().iter().skip(1).for_each(|sub_menu| {
|
||||
sub_menu.hide();
|
||||
});
|
||||
|
||||
let script = Script::from(label.as_str());
|
||||
debug!("executing command: '{}'", script.cmd);
|
||||
|
||||
let args = Vec::new();
|
||||
|
||||
spawn(async move {
|
||||
if let Err(err) = script.get_output(Some(&args)).await {
|
||||
error!("{err:?}");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
main_menu.show_all();
|
||||
}
|
|
@ -43,6 +43,8 @@ pub mod keyboard;
|
|||
pub mod label;
|
||||
#[cfg(feature = "launcher")]
|
||||
pub mod launcher;
|
||||
#[cfg(feature = "menu")]
|
||||
pub mod menu;
|
||||
#[cfg(feature = "music")]
|
||||
pub mod music;
|
||||
#[cfg(feature = "network_manager")]
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue