1
0
Fork 0
mirror of https://github.com/Zedfrigg/ironbar.git synced 2025-08-16 06:11:03 +02:00

feat: add menu module

Adds a new Menu module which allows users to create XDG or custom menus that open after clicking on a button.

Resolves #534

Co-authored-by: Jake Stanger <mail@jstanger.dev>
This commit is contained in:
Claire Neveu 2024-04-07 17:23:59 -04:00 committed by Jake Stanger
parent e99a04923d
commit 96e10fe139
No known key found for this signature in database
GPG key ID: C51FC8F9CB0BEA61
14 changed files with 1419 additions and 6 deletions

View file

@ -113,6 +113,7 @@ jobs:
- keyboard+hyprland
- label
- launcher
- menu
- music+all
- music+mpris
- music+mpd

View file

@ -23,6 +23,7 @@ default = [
"keyboard+all",
"launcher",
"label",
"menu",
"music+all",
"network_manager",
"notifications",
@ -76,6 +77,8 @@ label = []
launcher = []
menu = []
music = ["dep:regex"]
"music+all" = ["music", "music+mpris", "music+mpd"]
"music+mpris" = ["music", "mpris"]

157
docs/modules/Menu.md Normal file
View file

@ -0,0 +1,157 @@
Application menu that shows installed programs and optionally custom entries.
This works by reading all `.desktop` files on the system.
Clicking the menu button will open the main menu.
Clicking on any application category will open a sub-menu with any installed applications that match.
It is also possible to add custom categories and actions into the menu.
![Screenshot of open menu showing applications inside Office category](https://f.jstanger.dev/github/ironbar/menu.png)
## Configuration
| | Type | Default | Description |
|-----------------------|------------------------------------------------------|------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `start` | `MenuEntry[]` | `[]` | Items to add to the start of the main menu. |
| `center` | `MenuEntry[]` | Default XDG menu | Items to add to the centre of the main menu. By default this shows a number of XDG entries that should cover all common applications. |
| `end` | `MenuEntry[]` | `[]` | Items to add to the end of the main menu. |
| `height` | `integer` | `null` | Height of the menu. Leave null to resize dynamically. |
| `width` | `integer` | `null` | Width of the menu. Leave null to resize dynamically. |
| `label` | `string` | `≡` | Label to show on the menu button on the bar. |
| `label_icon` | `string` | `null` | Icon to show on the menu button on the bar. |
| `label_icon_size` | `integer` | `16` | Size of the label_icon image. |
| `truncate` | `'start'` or `'middle'` or `'end'` or `off` or `Map` | `off` | Applies to popup. The location of the ellipses and where to truncate text from. Leave null to avoid truncating. Use the long-hand `Map` version if specifying a length. |
| `truncate.mode` | `'start'` or `'middle'` or `'end'` or `off` | `off` | Applies to popup. The location of the ellipses and where to truncate text from. Leave null to avoid truncating. |
| `truncate.length` | `integer` | `null` | Applies to popup. The fixed width (in chars) of the widget. Leave blank to let GTK automatically handle. |
| `truncate.max_length` | `integer` | `null` | Applies to popup. The maximum number of characters before truncating. Leave blank to let GTK automatically handle. |
### `MenuEntry`
Each entry can be one of three types:
- `xdg_entry` - Contains all applications matching the configured `categories`.
- `xdg_other` - Contains all applications not covered by `xdg_entry` categories.
- `custom` - Individual shell command entry.
| | Type | Default | Description |
|--------------|----------------------------------------|---------|----------------------------------------------------------------------------------------|
| `type` | `xdg_entry` or `xdg_other` or `custom` | | Type of the entry. |
| `label` | `string` | `''` | Label of the entry's button. |
| `icon` | `string` | `null` | Icon for the entry's button. |
| `categories` | `string[]` | `[]` | [`xfg_entry`] List of freedesktop.org categories to include in this entry's sub menu . |
| `on_click` | `string` | `''` | [`custom`] Shell command to execute when the entry's button is clicked |
### Default XDG Menu
Setting the `center` menu entries will override the default menu.
The default menu can be found in the `default` example files [here](https://github.com/jakestanger/ironbar/blob/examples/menu/).
<details>
<summary>JSON</summary>
```json
{
"start": [
{
"type": "menu",
"start": [
{
"type": "custom",
"label": "Terminal",
"on_click": "xterm"
}
],
"height": 440,
"width": 200,
"icon": "archlinux",
"label": null
}
]
}
```
</details>
<details>
<summary>TOML</summary>
```toml
[[start]]
type = "memu"
height = 400
width = 200
icon = "archlinux"
[[start.start]]
type = "custom"
label = "Terminal"
on_click = "xterm"
```
</details>
<details>
<summary>YAML</summary>
```yaml
start:
- type: "menu"
start:
- type: custom
label: Terminal
on_click: xterm
height: 440
width: 200
icon: archlinux
label: null
```
</details>
<details>
<summary>Corn</summary>
```corn
{
start = [
{
type = "menu"
start = [
{
type = "custom"
label = "Terminal"
on_click = "xterm"
}
]
height = 440
width = 200
icon = "archlinux"
label = null
}
]
}
```
</details>
## Styling
| Selector | Description |
|--------------------------------------|-----------------------------------|
| `.menu` | Menu button |
| `.popup-menu` | Main container of the popup |
| `.popup-menu .main` | Main menu of the menu |
| `.popup-menu .main .category` | Category button |
| `.popup-menu .main .category.open` | Open category button |
| `.popup-menu .main .main-start` | Container for `start` entries |
| `.popup-menu .main .main-center` | Container for `center` entries |
| `.popup-menu .main .main-end` | Container for `end` entries |
| `.popup-menu .sub-menu` | All sub-menus |
| `.popup-menu .sub-menu .application` | Application button within submenu |
For more information on styling, please see the [styling guide](styling-guide).

102
examples/menu/default.corn Normal file
View file

@ -0,0 +1,102 @@
let {
$menu = [
{
type = "xdg_entry"
label = "Accessories"
icon = "accessories"
categories = [
"Accessibility"
"Core"
"Legacy"
"Utility"
]
}
{
type = "xdg_entry"
label = "Development"
icon = "applications-development"
categories = [
"Development"
]
}
{
type = "xdg_entry"
label = "Education"
icon = "applications-education"
categories = [
"Education"
]
}
{
type = "xdg_entry"
label = "Games"
icon = "applications-games"
categories = [
"Games"
]
}
{
type = "xdg_entry"
label = "Graphics"
icon = "applications-graphics"
categories = [
"Graphics"
]
}
{
type = "xdg_entry"
label = "Multimedia"
icon = "applications-multimedia"
categories = [
"Audio"
"Video"
"AudioVideo"
]
}
{
type = "xdg_entry"
label = "Network"
icon = "applications-internet"
categories = [
"Network"
]
}
{
type = "xdg_entry"
label = "Office"
icon = "applications-office"
categories = [
"Office"
]
}
{
type = "xdg_entry"
label = "Science"
icon = "applications-science"
categories = [
"Science"
]
}
{
type = "xdg_entry"
label = "System"
icon = "applications-system"
categories = [
"Emulator"
"System"
]
}
{ type = "xdg_other" }
{
type = "xdg_entry"
label = "Settings"
icon = "preferences-system"
categories = [
"Settings"
"Screensaver"
]
}
]
} in {
start = [ { type = "menu" center = $menu } ]
}

107
examples/menu/default.json Normal file
View file

@ -0,0 +1,107 @@
{
"start": [
{
"type": "menu",
"center": [
{
"type": "xdg_entry",
"label": "Accessories",
"icon": "accessories",
"categories": [
"Accessibility",
"Core",
"Legacy",
"Utility"
]
},
{
"type": "xdg_entry",
"label": "Development",
"icon": "applications-development",
"categories": [
"Development"
]
},
{
"type": "xdg_entry",
"label": "Education",
"icon": "applications-education",
"categories": [
"Education"
]
},
{
"type": "xdg_entry",
"label": "Games",
"icon": "applications-games",
"categories": [
"Games"
]
},
{
"type": "xdg_entry",
"label": "Graphics",
"icon": "applications-graphics",
"categories": [
"Graphics"
]
},
{
"type": "xdg_entry",
"label": "Multimedia",
"icon": "applications-multimedia",
"categories": [
"Audio",
"Video",
"AudioVideo"
]
},
{
"type": "xdg_entry",
"label": "Network",
"icon": "applications-internet",
"categories": [
"Network"
]
},
{
"type": "xdg_entry",
"label": "Office",
"icon": "applications-office",
"categories": [
"Office"
]
},
{
"type": "xdg_entry",
"label": "Science",
"icon": "applications-science",
"categories": [
"Science"
]
},
{
"type": "xdg_entry",
"label": "System",
"icon": "applications-system",
"categories": [
"Emulator",
"System"
]
},
{
"type": "xdg_other"
},
{
"type": "xdg_entry",
"label": "Settings",
"icon": "preferences-system",
"categories": [
"Settings",
"Screensaver"
]
}
]
}
]
}

View file

@ -0,0 +1,87 @@
[[start]]
type = "menu"
[[start.center]]
type = "xdg_entry"
label = "Accessories"
icon = "accessories"
categories = [
"Accessibility",
"Core",
"Legacy",
"Utility",
]
[[start.center]]
type = "xdg_entry"
label = "Development"
icon = "applications-development"
categories = ["Development"]
[[start.center]]
type = "xdg_entry"
label = "Education"
icon = "applications-education"
categories = ["Education"]
[[start.center]]
type = "xdg_entry"
label = "Games"
icon = "applications-games"
categories = ["Games"]
[[start.center]]
type = "xdg_entry"
label = "Graphics"
icon = "applications-graphics"
categories = ["Graphics"]
[[start.center]]
type = "xdg_entry"
label = "Multimedia"
icon = "applications-multimedia"
categories = [
"Audio",
"Video",
"AudioVideo",
]
[[start.center]]
type = "xdg_entry"
label = "Network"
icon = "applications-internet"
categories = ["Network"]
[[start.center]]
type = "xdg_entry"
label = "Office"
icon = "applications-office"
categories = ["Office"]
[[start.center]]
type = "xdg_entry"
label = "Science"
icon = "applications-science"
categories = ["Science"]
[[start.center]]
type = "xdg_entry"
label = "System"
icon = "applications-system"
categories = [
"Emulator",
"System",
]
[[start.center]]
type = "xdg_other"
[[start.center]]
type = "xdg_entry"
label = "Settings"
icon = "preferences-system"
categories = [
"Settings",
"Screensaver",
]

68
examples/menu/default.yml Normal file
View file

@ -0,0 +1,68 @@
start:
- type: menu
center:
- type: xdg_entry
label: Accessories
icon: accessories
categories:
- Accessibility
- Core
- Legacy
- Utility
- type: xdg_entry
label: Development
icon: applications-development
categories:
- Development
- type: xdg_entry
label: Education
icon: applications-education
categories:
- Education
- type: xdg_entry
label: Games
icon: applications-games
categories:
- Games
- type: xdg_entry
label: Graphics
icon: applications-graphics
categories:
- Graphics
- type: xdg_entry
label: Multimedia
icon: applications-multimedia
categories:
- Audio
- Video
- AudioVideo
- type: xdg_entry
label: Network
icon: applications-internet
categories:
- Network
- type: xdg_entry
label: Office
icon: applications-office
categories:
- Office
- type: xdg_entry
label: Science
icon: applications-science
categories:
- Science
- type: xdg_entry
label: System
icon: applications-system
categories:
- Emulator
- System
- type: xdg_other
- type: xdg_entry
label: Settings
icon: preferences-system
categories:
- Settings
- Screensaver

View file

@ -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")]

View file

@ -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
View 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
View 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(&gtk_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, &gtk_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!(&center_entries, &center_section);
add_entries!(&end_entries, &end_section);
main_menu.add(&start_section);
main_menu.add(&center_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
View 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(&gtk_image);
let image_provider = image_provider.clone();
glib::spawn_future_local(async move {
image_provider
.load_into_image_silent(&icon_name, 16, true, &gtk_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(&gtk_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, &gtk_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<&gtk::Box>,
main_menu: &gtk::Box,
container: &gtk::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();
}

View file

@ -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")]

34
test-configs/menu.corn Normal file
View file

@ -0,0 +1,34 @@
{
icon_theme = "Paper"
position = "bottom"
start = [
{
type = "menu"
label = null
label_icon = "archlinux"
label_icon_size = 36
height = 500
width = 440
start = [
{
type = "custom"
label = "Terminal"
icon = "kitty"
on_click = "kitty"
}
]
end = [
{
type = "custom"
label = "Logout"
icon = "logout"
on_click = "wlogout"
}
]
}
{ type = "launcher" }
]
end = [ { type = "clock" }]
}