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

WIP update of networkmanager & volume modules

This commit is contained in:
Reinout Meliesie 2025-08-10 16:37:55 +02:00
parent c42024d48a
commit 26686739a0
Signed by: zedfrigg
GPG key ID: 3AFCC06481308BC6
5 changed files with 323 additions and 522 deletions

View file

@ -1,71 +1,71 @@
use color_eyre::Result; use color_eyre::Result;
use zbus::dbus_proxy; use zbus::proxy;
use zbus::zvariant::{ObjectPath, OwnedValue, Str}; use zbus::zvariant::{ObjectPath, OwnedValue, Str};
#[dbus_proxy( #[proxy(
default_service = "org.freedesktop.NetworkManager", default_service = "org.freedesktop.NetworkManager",
interface = "org.freedesktop.NetworkManager", interface = "org.freedesktop.NetworkManager",
default_path = "/org/freedesktop/NetworkManager" default_path = "/org/freedesktop/NetworkManager"
)] )]
trait Dbus { pub(super) trait Dbus {
#[dbus_proxy(property)] #[zbus(property)]
fn active_connections(&self) -> Result<Vec<ObjectPath>>; fn active_connections(&self) -> Result<Vec<ObjectPath>>;
#[dbus_proxy(property)] #[zbus(property)]
fn devices(&self) -> Result<Vec<ObjectPath>>; fn devices(&self) -> Result<Vec<ObjectPath>>;
// #[dbus_proxy(property)] // #[zbus(property)]
// fn networking_enabled(&self) -> Result<bool>; // fn networking_enabled(&self) -> Result<bool>;
// #[dbus_proxy(property)] // #[zbus(property)]
// fn primary_connection(&self) -> Result<ObjectPath>; // fn primary_connection(&self) -> Result<ObjectPath>;
// #[dbus_proxy(property)] // #[zbus(property)]
// fn primary_connection_type(&self) -> Result<Str>; // fn primary_connection_type(&self) -> Result<Str>;
// #[dbus_proxy(property)] // #[zbus(property)]
// fn wireless_enabled(&self) -> Result<bool>; // fn wireless_enabled(&self) -> Result<bool>;
} }
#[dbus_proxy( #[proxy(
default_service = "org.freedesktop.NetworkManager", default_service = "org.freedesktop.NetworkManager",
interface = "org.freedesktop.NetworkManager.Connection.Active" interface = "org.freedesktop.NetworkManager.Connection.Active"
)] )]
trait ActiveConnectionDbus { pub(super) trait ActiveConnectionDbus {
// #[dbus_proxy(property)] // #[zbus(property)]
// fn connection(&self) -> Result<ObjectPath>; // fn connection(&self) -> Result<ObjectPath>;
// #[dbus_proxy(property)] // #[zbus(property)]
// fn default(&self) -> Result<bool>; // fn default(&self) -> Result<bool>;
// #[dbus_proxy(property)] // #[zbus(property)]
// fn default6(&self) -> Result<bool>; // fn default6(&self) -> Result<bool>;
#[dbus_proxy(property)] #[zbus(property)]
fn devices(&self) -> Result<Vec<ObjectPath>>; fn devices(&self) -> Result<Vec<ObjectPath>>;
// #[dbus_proxy(property)] // #[zbus(property)]
// fn id(&self) -> Result<Str>; // fn id(&self) -> Result<Str>;
#[dbus_proxy(property)] #[zbus(property)]
fn type_(&self) -> Result<Str>; fn type_(&self) -> Result<Str>;
// #[dbus_proxy(property)] // #[zbus(property)]
// fn uuid(&self) -> Result<Str>; // fn uuid(&self) -> Result<Str>;
} }
#[dbus_proxy( #[proxy(
default_service = "org.freedesktop.NetworkManager", default_service = "org.freedesktop.NetworkManager",
interface = "org.freedesktop.NetworkManager.Device" interface = "org.freedesktop.NetworkManager.Device"
)] )]
trait DeviceDbus { pub(super) trait DeviceDbus {
// #[dbus_proxy(property)] // #[zbus(property)]
// fn active_connection(&self) -> Result<ObjectPath>; // fn active_connection(&self) -> Result<ObjectPath>;
#[dbus_proxy(property)] #[zbus(property)]
fn device_type(&self) -> Result<DeviceType>; fn device_type(&self) -> Result<DeviceType>;
#[dbus_proxy(property)] #[zbus(property)]
fn state(&self) -> Result<DeviceState>; fn state(&self) -> Result<DeviceState>;
} }

View file

@ -2,17 +2,16 @@ use std::collections::HashMap;
use std::sync::{Arc, RwLock}; use std::sync::{Arc, RwLock};
use color_eyre::Result; use color_eyre::Result;
use futures_lite::StreamExt;
use futures_signals::signal::{Mutable, MutableSignalCloned}; use futures_signals::signal::{Mutable, MutableSignalCloned};
use tracing::error; use tracing::error;
use zbus::blocking::Connection; use zbus::Connection;
use zbus::zvariant::ObjectPath; use zbus::zvariant::ObjectPath;
use crate::clients::networkmanager::dbus::{ use crate::clients::networkmanager::dbus::{ActiveConnectionDbusProxy, DbusProxy, DeviceDbusProxy};
ActiveConnectionDbusProxyBlocking, DbusProxyBlocking, DeviceDbusProxyBlocking,
};
use crate::clients::networkmanager::state::{ use crate::clients::networkmanager::state::{
determine_cellular_state, determine_vpn_state, determine_wifi_state, determine_wired_state, CellularState, State, VpnState, WifiState, WiredState, determine_cellular_state,
CellularState, State, VpnState, WifiState, WiredState, determine_vpn_state, determine_wifi_state, determine_wired_state,
}; };
use crate::{ use crate::{
read_lock, register_fallible_client, spawn_blocking, spawn_blocking_result, write_lock, read_lock, register_fallible_client, spawn_blocking, spawn_blocking_result, write_lock,
@ -29,23 +28,23 @@ pub struct Client(Arc<ClientInner<'static>>);
#[derive(Debug)] #[derive(Debug)]
struct ClientInner<'l> { struct ClientInner<'l> {
state: Mutable<State>, state: Mutable<State>,
root_object: &'l DbusProxyBlocking<'l>, root_object: &'l DbusProxy<'l>,
active_connections: RwLock<PathMap<'l, ActiveConnectionDbusProxyBlocking<'l>>>, active_connections: RwLock<PathMap<'l, ActiveConnectionDbusProxy<'l>>>,
devices: RwLock<PathMap<'l, DeviceDbusProxyBlocking<'l>>>, devices: RwLock<PathMap<'l, DeviceDbusProxy<'l>>>,
dbus_connection: Connection, dbus_connection: Connection,
} }
impl Client { impl Client {
fn new() -> Result<Client> { async fn new() -> Result<Client> {
let state = Mutable::new(State { let state = Mutable::new(State {
wired: WiredState::Unknown, wired: WiredState::Unknown,
wifi: WifiState::Unknown, wifi: WifiState::Unknown,
cellular: CellularState::Unknown, cellular: CellularState::Unknown,
vpn: VpnState::Unknown, vpn: VpnState::Unknown,
}); });
let dbus_connection = Connection::system()?; let dbus_connection = Connection::system().await?;
let root_object = { let root_object = {
let root_object = DbusProxyBlocking::new(&dbus_connection)?; let root_object = DbusProxy::new(&dbus_connection).await?;
// Workaround for the fact that zbus (unnecessarily) requires a static lifetime here // Workaround for the fact that zbus (unnecessarily) requires a static lifetime here
Box::leak(Box::new(root_object)) Box::leak(Box::new(root_object))
}; };
@ -59,158 +58,159 @@ impl Client {
}))) })))
} }
fn run(&self) -> Result<()> { async fn run(&self) -> Result<()> {
macro_rules! update_state_for_device_change { // TODO: Reimplement DBus watching without these write-only macros
($client:ident) => {
$client.state.set(State { let mut active_connections_stream = self.0.root_object.receive_active_connections_changed().await;
wired: determine_wired_state(&read_lock!($client.devices))?, while let Some(change) = active_connections_stream.next().await {
wifi: determine_wifi_state(&read_lock!($client.devices))?,
cellular: determine_cellular_state(&read_lock!($client.devices))?,
vpn: $client.state.get_cloned().vpn,
});
};
} }
macro_rules! initialise_path_map { // ActiveConnectionDbusProxy::builder(&self.0.dbus_connection)
(
$client:expr,
$path_map:ident,
$proxy_type:ident
$(, |$new_path:ident| $property_watcher:expr)*
) => {
let new_paths = $client.root_object.$path_map()?;
let mut path_map = HashMap::new();
for new_path in new_paths {
let new_proxy = $proxy_type::builder(&$client.dbus_connection)
.path(new_path.clone())?
.build()?;
path_map.insert(new_path.clone(), new_proxy);
$({
let $new_path = &new_path;
$property_watcher;
})*
}
*write_lock!($client.$path_map) = path_map;
};
}
macro_rules! spawn_path_list_watcher { // macro_rules! update_state_for_device_change {
( // ($client:ident) => {
$client:expr, // $client.state.set(State {
$property:ident, // wired: determine_wired_state(&read_lock!($client.devices)).await?,
$property_changes:ident, // wifi: determine_wifi_state(&read_lock!($client.devices)).await?,
$proxy_type:ident, // cellular: determine_cellular_state(&read_lock!($client.devices)).await?,
|$state_client:ident| $state_update:expr // vpn: $client.state.get_cloned().vpn,
$(, |$property_client:ident, $new_path:ident| $property_watcher:expr)* // });
) => { // };
let client = $client.clone(); // }
spawn_blocking_result!({ //
let changes = client.root_object.$property_changes(); // macro_rules! initialise_path_map {
for _ in changes { // (
let mut new_path_map = HashMap::new(); // $client:expr,
{ // $path_map:ident,
let new_paths = client.root_object.$property()?; // $proxy_type:ident
let path_map = read_lock!(client.$property); // $(, |$new_path:ident| $property_watcher:expr)*
for new_path in new_paths { // ) => {
if path_map.contains_key(&new_path) { // let new_paths = $client.root_object.$path_map().await?;
let proxy = path_map // let mut path_map = HashMap::new();
.get(&new_path) // for new_path in new_paths {
.expect("Should contain the key, guarded by runtime check"); // let new_proxy = $proxy_type::builder(&$client.dbus_connection)
new_path_map.insert(new_path, proxy.to_owned()); // .path(new_path.clone())?
} else { // .build().await?;
let new_proxy = $proxy_type::builder(&client.dbus_connection) // path_map.insert(new_path.clone(), new_proxy);
.path(new_path.clone())? // $({
.build()?; // let $new_path = &new_path;
new_path_map.insert(new_path.clone(), new_proxy); // $property_watcher;
$({ // })*
let $property_client = &client; // }
let $new_path = &new_path; // *write_lock!($client.$path_map) = path_map;
$property_watcher; // };
})* // }
} //
} // macro_rules! spawn_path_list_watcher {
} // (
*write_lock!(client.$property) = new_path_map; // $client:expr,
let $state_client = &client; // $property:ident,
$state_update; // $property_changes:ident,
} // $proxy_type:ident,
Ok(()) // |$state_client:ident| $state_update:expr
}); // $(, |$property_client:ident, $new_path:ident| $property_watcher:expr)*
} // ) => {
} // let client = $client.clone();
//
macro_rules! spawn_property_watcher { // let changes = client.root_object.$property_changes();
( // for _ in changes {
$client:expr, // let mut new_path_map = HashMap::new();
$path:expr, // {
$property_changes:ident, // let new_paths = client.root_object.$property()?;
$containing_list:ident, // let path_map = read_lock!(client.$property);
|$inner_client:ident| $state_update:expr // for new_path in new_paths {
) => { // if path_map.contains_key(&new_path) {
let client = $client.clone(); // let proxy = path_map
let path = $path.clone(); // .get(&new_path)
spawn_blocking_result!({ // .expect("Should contain the key, guarded by runtime check");
let changes = read_lock!(client.$containing_list) // new_path_map.insert(new_path, proxy.to_owned());
.get(&path) // } else {
.expect("Should contain the key upon watcher start") // let new_proxy = $proxy_type::builder(&client.dbus_connection)
.$property_changes(); // .path(new_path.clone())?
for _ in changes { // .build()?;
if !read_lock!(client.$containing_list).contains_key(&path) { // new_path_map.insert(new_path.clone(), new_proxy);
break; // $({
} // let $property_client = &client;
let $inner_client = &client; // let $new_path = &new_path;
$state_update; // $property_watcher;
} // })*
Ok(()) // }
}); // }
}; // }
} // *write_lock!(client.$property) = new_path_map;
// let $state_client = &client;
initialise_path_map!( // $state_update;
self.0, // }
active_connections, // }
ActiveConnectionDbusProxyBlocking // }
); //
initialise_path_map!(self.0, devices, DeviceDbusProxyBlocking, |path| { // macro_rules! spawn_property_watcher {
spawn_property_watcher!(self.0, path, receive_state_changed, devices, |client| { // (
update_state_for_device_change!(client); // $client:expr,
}); // $path:expr,
}); // $property_changes:ident,
self.0.state.set(State { // $containing_list:ident,
wired: determine_wired_state(&read_lock!(self.0.devices))?, // |$inner_client:ident| $state_update:expr
wifi: determine_wifi_state(&read_lock!(self.0.devices))?, // ) => {
cellular: determine_cellular_state(&read_lock!(self.0.devices))?, // let client = $client.clone();
vpn: determine_vpn_state(&read_lock!(self.0.active_connections))?, // let path = $path.clone();
}); //
// let changes = read_lock!(client.$containing_list)
spawn_path_list_watcher!( // .get(&path)
self.0, // .expect("Should contain the key upon watcher start")
active_connections, // .$property_changes().await;
receive_active_connections_changed, // for _ in changes {
ActiveConnectionDbusProxyBlocking, // if !read_lock!(client.$containing_list).contains_key(&path) {
|client| { // break;
client.state.set(State { // }
wired: client.state.get_cloned().wired, // let $inner_client = &client;
wifi: client.state.get_cloned().wifi, // $state_update;
cellular: client.state.get_cloned().cellular, // }
vpn: determine_vpn_state(&read_lock!(client.active_connections))?, // };
}); // }
} //
); // initialise_path_map!(self.0, active_connections, ActiveConnectionDbusProxy);
spawn_path_list_watcher!( // initialise_path_map!(self.0, devices, DeviceDbusProxy, |path| {
self.0, // spawn_property_watcher!(self.0, path, receive_state_changed, devices, |client| {
devices, // update_state_for_device_change!(client);
receive_devices_changed, // });
DeviceDbusProxyBlocking, // });
|client| { // self.0.state.set(State {
update_state_for_device_change!(client); // wired: determine_wired_state(&read_lock!(self.0.devices))?,
}, // wifi: determine_wifi_state(&read_lock!(self.0.devices))?,
|client, path| { // cellular: determine_cellular_state(&read_lock!(self.0.devices))?,
spawn_property_watcher!(client, path, receive_state_changed, devices, |client| { // vpn: determine_vpn_state(&read_lock!(self.0.active_connections))?,
update_state_for_device_change!(client); // });
}); //
} // spawn_path_list_watcher!(
); // self.0,
// active_connections,
// receive_active_connections_changed,
// ActiveConnectionDbusProxy,
// |client| {
// client.state.set(State {
// wired: client.state.get_cloned().wired,
// wifi: client.state.get_cloned().wifi,
// cellular: client.state.get_cloned().cellular,
// vpn: determine_vpn_state(&read_lock!(client.active_connections))?,
// });
// }
// );
// spawn_path_list_watcher!(
// self.0,
// devices,
// receive_devices_changed,
// DeviceDbusProxy,
// |client| {
// update_state_for_device_change!(client);
// },
// |client, path| {
// spawn_property_watcher!(client, path, receive_state_changed, devices, |client| {
// update_state_for_device_change!(client);
// });
// }
// );
Ok(()) Ok(())
} }
@ -220,15 +220,9 @@ impl Client {
} }
} }
pub fn create_client() -> Result<Arc<Client>> { pub async fn create_client() -> Result<Arc<Client>> {
let client = Arc::new(Client::new()?); let client = Arc::new(Client::new().await?);
{ client.run().await?;
let client = client.clone();
spawn_blocking_result!({
client.run()?;
Ok(())
});
}
Ok(client) Ok(client)
} }

View file

@ -1,9 +1,9 @@
use color_eyre::Result; use color_eyre::Result;
use crate::clients::networkmanager::dbus::{
ActiveConnectionDbusProxyBlocking, DeviceDbusProxyBlocking, DeviceState, DeviceType,
};
use crate::clients::networkmanager::PathMap; use crate::clients::networkmanager::PathMap;
use crate::clients::networkmanager::dbus::{
ActiveConnectionDbusProxy, DeviceDbusProxy, DeviceState, DeviceType,
};
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct State { pub struct State {
@ -56,16 +56,16 @@ pub struct VpnConnectedState {
pub name: String, pub name: String,
} }
pub(super) fn determine_wired_state( pub(super) async fn determine_wired_state(
devices: &PathMap<DeviceDbusProxyBlocking>, devices: &PathMap<'_, DeviceDbusProxy<'_>>,
) -> Result<WiredState> { ) -> Result<WiredState> {
let mut present = false; let mut present = false;
let mut connected = false; let mut connected = false;
for device in devices.values() { for device in devices.values() {
if device.device_type()? == DeviceType::Ethernet { if device.device_type().await? == DeviceType::Ethernet {
present = true; present = true;
if device.state()?.is_enabled() { if device.state().await?.is_enabled() {
connected = true; connected = true;
break; break;
} }
@ -81,19 +81,19 @@ pub(super) fn determine_wired_state(
} }
} }
pub(super) fn determine_wifi_state( pub(super) async fn determine_wifi_state(
devices: &PathMap<DeviceDbusProxyBlocking>, devices: &PathMap<'_, DeviceDbusProxy<'_>>,
) -> Result<WifiState> { ) -> Result<WifiState> {
let mut present = false; let mut present = false;
let mut enabled = false; let mut enabled = false;
let mut connected = false; let mut connected = false;
for device in devices.values() { for device in devices.values() {
if device.device_type()? == DeviceType::Wifi { if device.device_type().await? == DeviceType::Wifi {
present = true; present = true;
if device.state()?.is_enabled() { if device.state().await?.is_enabled() {
enabled = true; enabled = true;
if device.state()? == DeviceState::Activated { if device.state().await? == DeviceState::Activated {
connected = true; connected = true;
break; break;
} }
@ -115,19 +115,19 @@ pub(super) fn determine_wifi_state(
} }
} }
pub(super) fn determine_cellular_state( pub(super) async fn determine_cellular_state(
devices: &PathMap<DeviceDbusProxyBlocking>, devices: &PathMap<'_, DeviceDbusProxy<'_>>,
) -> Result<CellularState> { ) -> Result<CellularState> {
let mut present = false; let mut present = false;
let mut enabled = false; let mut enabled = false;
let mut connected = false; let mut connected = false;
for device in devices.values() { for device in devices.values() {
if device.device_type()? == DeviceType::Modem { if device.device_type().await? == DeviceType::Modem {
present = true; present = true;
if device.state()?.is_enabled() { if device.state().await?.is_enabled() {
enabled = true; enabled = true;
if device.state()? == DeviceState::Activated { if device.state().await? == DeviceState::Activated {
connected = true; connected = true;
break; break;
} }
@ -146,11 +146,11 @@ pub(super) fn determine_cellular_state(
} }
} }
pub(super) fn determine_vpn_state( pub(super) async fn determine_vpn_state(
active_connections: &PathMap<ActiveConnectionDbusProxyBlocking>, active_connections: &PathMap<'_, ActiveConnectionDbusProxy<'_>>,
) -> Result<VpnState> { ) -> Result<VpnState> {
for connection in active_connections.values() { for connection in active_connections.values() {
match connection.type_()?.as_str() { match connection.type_().await?.as_str() {
"vpn" | "wireguard" => { "vpn" | "wireguard" => {
return Ok(VpnState::Connected(VpnConnectedState { return Ok(VpnState::Connected(VpnConnectedState {
name: "unknown".into(), name: "unknown".into(),

View file

@ -6,15 +6,15 @@ use gtk::{Box as GtkBox, Image, Orientation};
use serde::Deserialize; use serde::Deserialize;
use tokio::sync::mpsc::Receiver; use tokio::sync::mpsc::Receiver;
use crate::channels::{AsyncSenderExt, BroadcastReceiverExt};
use crate::clients::networkmanager::Client;
use crate::clients::networkmanager::state::{ use crate::clients::networkmanager::state::{
CellularState, State, VpnState, WifiState, WiredState, CellularState, State, VpnState, WifiState, WiredState,
}; };
use crate::clients::networkmanager::Client;
use crate::config::CommonConfig; use crate::config::CommonConfig;
use crate::gtk_helpers::IronbarGtkExt; use crate::gtk_helpers::IronbarGtkExt;
use crate::image::ImageProvider;
use crate::modules::{Module, ModuleInfo, ModuleParts, ModuleUpdateEvent, WidgetContext}; use crate::modules::{Module, ModuleInfo, ModuleParts, ModuleUpdateEvent, WidgetContext};
use crate::{glib_recv, module_impl, send_async, spawn}; use crate::{module_impl, spawn};
#[derive(Debug, Deserialize, Clone)] #[derive(Debug, Deserialize, Clone)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
@ -38,9 +38,9 @@ impl Module<GtkBox> for NetworkManagerModule {
fn spawn_controller( fn spawn_controller(
&self, &self,
_: &ModuleInfo, _info: &ModuleInfo,
context: &WidgetContext<State, ()>, context: &WidgetContext<State, ()>,
_: Receiver<()>, _rx: Receiver<()>,
) -> Result<()> { ) -> Result<()> {
let client = context.try_client::<Client>()?; let client = context.try_client::<Client>()?;
let mut client_signal = client.subscribe().to_stream(); let mut client_signal = client.subscribe().to_stream();
@ -48,7 +48,9 @@ impl Module<GtkBox> for NetworkManagerModule {
spawn(async move { spawn(async move {
while let Some(state) = client_signal.next().await { while let Some(state) = client_signal.next().await {
send_async!(widget_transmitter, ModuleUpdateEvent::Update(state)); widget_transmitter
.send_expect(ModuleUpdateEvent::Update(state))
.await;
} }
}); });
@ -58,7 +60,7 @@ impl Module<GtkBox> for NetworkManagerModule {
fn into_widget( fn into_widget(
self, self,
context: WidgetContext<State, ()>, context: WidgetContext<State, ()>,
info: &ModuleInfo, _info: &ModuleInfo,
) -> Result<ModuleParts<GtkBox>> { ) -> Result<ModuleParts<GtkBox>> {
let container = GtkBox::new(Orientation::Horizontal, 0); let container = GtkBox::new(Orientation::Horizontal, 0);
@ -86,48 +88,80 @@ impl Module<GtkBox> for NetworkManagerModule {
vpn_icon.add_class("vpn-icon"); vpn_icon.add_class("vpn-icon");
container.add(&vpn_icon); container.add(&vpn_icon);
let icon_theme = info.icon_theme.clone(); context.subscribe().recv_glib_async((), move |(), state| {
glib_recv!(context.subscribe(), state => { // TODO: Make this whole section less boneheaded
macro_rules! update_icon {
(
$icon_var:expr,
$state_type:ident,
{$($state:pat => $icon_name:expr,)+}
) => {
let icon_name = match state.$state_type {
$($state => $icon_name,)+
};
if icon_name.is_empty() {
$icon_var.hide();
} else {
ImageProvider::parse(icon_name, &icon_theme, false, self.icon_size)
.map(|provider| provider.load_into_image($icon_var.clone()));
$icon_var.show();
}
};
}
update_icon!(wired_icon, wired, { let wired_icon_name = match state.wired {
WiredState::Connected => "icon:network-wired-symbolic", WiredState::Connected => "icon:network-wired-symbolic",
WiredState::Disconnected => "icon:network-wired-disconnected-symbolic", WiredState::Disconnected => "icon:network-wired-disconnected-symbolic",
WiredState::NotPresent | WiredState::Unknown => "", WiredState::NotPresent | WiredState::Unknown => "",
}); };
update_icon!(wifi_icon, wifi, { let wifi_icon_name = match state.wifi {
WifiState::Connected(_) => "icon:network-wireless-connected-symbolic", WifiState::Connected(_) => "icon:network-wireless-connected-symbolic",
WifiState::Disconnected => "icon:network-wireless-offline-symbolic", WifiState::Disconnected => "icon:network-wireless-offline-symbolic",
WifiState::Disabled => "icon:network-wireless-hardware-disabled-symbolic", WifiState::Disabled => "icon:network-wireless-hardware-disabled-symbolic",
WifiState::NotPresent | WifiState::Unknown => "", WifiState::NotPresent | WifiState::Unknown => "",
}); };
update_icon!(cellular_icon, cellular, { let cellular_icon_name = match state.cellular {
CellularState::Connected => "icon:network-cellular-connected-symbolic", CellularState::Connected => "icon:network-cellular-connected-symbolic",
CellularState::Disconnected => "icon:network-cellular-offline-symbolic", CellularState::Disconnected => "icon:network-cellular-offline-symbolic",
CellularState::Disabled => "icon:network-cellular-hardware-disabled-symbolic", CellularState::Disabled => "icon:network-cellular-hardware-disabled-symbolic",
CellularState::NotPresent | CellularState::Unknown => "", CellularState::NotPresent | CellularState::Unknown => "",
}); };
update_icon!(vpn_icon, vpn, { let vpn_icon_name = match state.vpn {
VpnState::Connected(_) => "icon:network-vpn-symbolic", VpnState::Connected(_) => "icon:network-vpn-symbolic",
VpnState::Disconnected | VpnState::Unknown => "", VpnState::Disconnected | VpnState::Unknown => "",
}); };
let wired_icon = wired_icon.clone();
let wifi_icon = wifi_icon.clone();
let cellular_icon = cellular_icon.clone();
let vpn_icon = vpn_icon.clone();
let image_provider = context.ironbar.image_provider();
async move {
if wired_icon_name.is_empty() {
wired_icon.hide();
} else {
image_provider
.load_into_image_silent(wired_icon_name, self.icon_size, false, &wired_icon)
.await;
wired_icon.show();
}
if wifi_icon_name.is_empty() {
wifi_icon.hide();
} else {
image_provider
.load_into_image_silent(wifi_icon_name, self.icon_size, false, &wifi_icon)
.await;
wifi_icon.show();
}
if cellular_icon_name.is_empty() {
cellular_icon.hide();
} else {
image_provider
.load_into_image_silent(
cellular_icon_name,
self.icon_size,
false,
&cellular_icon,
)
.await;
cellular_icon.show();
}
if vpn_icon_name.is_empty() {
vpn_icon.hide();
} else {
image_provider
.load_into_image_silent(vpn_icon_name, self.icon_size, false, &vpn_icon)
.await;
vpn_icon.show();
}
}
}); });
Ok(ModuleParts::new(container, None)) Ok(ModuleParts::new(container, None))

View file

@ -1,21 +1,16 @@
use crate::channels::{AsyncSenderExt, BroadcastReceiverExt};
use crate::clients::volume::{self, Event}; use crate::clients::volume::{self, Event};
use crate::config::CommonConfig; use crate::config::{CommonConfig, LayoutConfig, TruncateMode};
use crate::gtk_helpers::IronbarGtkExt; use crate::gtk_helpers::IronbarGtkExt;
use crate::image::ImageProvider;
use crate::modules::{ use crate::modules::{
Module, ModuleInfo, ModuleParts, ModulePopup, ModuleUpdateEvent, PopupButton, WidgetContext, Module, ModuleInfo, ModuleParts, ModuleUpdateEvent, PopupButton, WidgetContext,
}; };
use crate::{glib_recv, lock, module_impl, send_async, spawn, try_send}; use crate::{lock, module_impl, spawn};
use glib::Propagation;
use gtk::pango::EllipsizeMode;
use gtk::prelude::*; use gtk::prelude::*;
use gtk::{ use gtk::{Button, Image, Label, Scale, ToggleButton};
Box as GtkBox, Button, CellRendererText, ComboBoxText, Image, Label, Orientation, Scale,
ToggleButton,
};
use serde::Deserialize; use serde::Deserialize;
use std::collections::HashMap;
use tokio::sync::mpsc; use tokio::sync::mpsc;
use tracing::trace;
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
@ -30,6 +25,16 @@ pub struct VolumeModule {
#[serde(default = "default_icon_size")] #[serde(default = "default_icon_size")]
icon_size: i32, icon_size: i32,
// -- Common --
/// See [truncate options](module-level-options#truncate-mode).
///
/// **Default**: `null`
pub(crate) truncate: Option<TruncateMode>,
/// See [layout options](module-level-options#layout)
#[serde(default, flatten)]
layout: LayoutConfig,
/// See [common options](module-level-options#common-options). /// See [common options](module-level-options#common-options).
#[serde(flatten)] #[serde(flatten)]
pub common: Option<CommonConfig>, pub common: Option<CommonConfig>,
@ -83,26 +88,28 @@ impl Module<Button> for VolumeModule {
sinks.iter().cloned().collect::<Vec<_>>() sinks.iter().cloned().collect::<Vec<_>>()
}; };
trace!("initial syncs: {sinks:?}");
let inputs = { let inputs = {
let inputs = client.sink_inputs(); let inputs = client.sink_inputs();
let inputs = lock!(inputs); let inputs = lock!(inputs);
inputs.iter().cloned().collect::<Vec<_>>() inputs.iter().cloned().collect::<Vec<_>>()
}; };
trace!("initial inputs: {inputs:?}");
for sink in sinks { for sink in sinks {
send_async!(tx, ModuleUpdateEvent::Update(Event::AddSink(sink))); tx.send_update(Event::AddSink(sink)).await;
} }
for input in inputs { for input in inputs {
send_async!( tx.send_update(Event::AddInput(input)).await;
tx,
ModuleUpdateEvent::Update(Event::AddInput(input.clone()))
);
} }
// recv loop // recv loop
while let Ok(event) = rx.recv().await { while let Ok(event) = rx.recv().await {
send_async!(tx, ModuleUpdateEvent::Update(event)); trace!("received event: {event:?}");
tx.send_update(event).await;
} }
}); });
} }
@ -126,7 +133,7 @@ impl Module<Button> for VolumeModule {
fn into_widget( fn into_widget(
self, self,
context: WidgetContext<Self::SendMessage, Self::ReceiveMessage>, context: WidgetContext<Self::SendMessage, Self::ReceiveMessage>,
info: &ModuleInfo, _info: &ModuleInfo,
) -> color_eyre::Result<ModuleParts<Button>> ) -> color_eyre::Result<ModuleParts<Button>>
where where
<Self as Module<Button>>::SendMessage: Clone, <Self as Module<Button>>::SendMessage: Clone,
@ -137,280 +144,46 @@ impl Module<Button> for VolumeModule {
let tx = context.tx.clone(); let tx = context.tx.clone();
button.connect_clicked(move |button| { button.connect_clicked(move |button| {
try_send!(tx, ModuleUpdateEvent::TogglePopup(button.popup_id())); tx.send_spawn(ModuleUpdateEvent::TogglePopup(button.popup_id()));
}); });
} }
{ let rx = context.subscribe();
let rx = context.subscribe();
let icon_theme = info.icon_theme.clone();
let image_icon = Image::new(); let image_icon = Image::new();
image_icon.add_class("icon"); image_icon.add_class("icon");
button.set_image(Some(&image_icon)); button.set_image(Some(&image_icon));
glib_recv!(rx, event => { rx.recv_glib_async((), move |(), event| {
let image_icon = image_icon.clone();
let image_provider = context.ironbar.image_provider();
async move {
match event { match event {
Event::AddSink(sink) | Event::UpdateSink(sink) if sink.active => { Event::AddSink(sink) | Event::UpdateSink(sink) if sink.active => {
ImageProvider::parse( image_provider
&determine_volume_icon(sink.muted, sink.volume), .load_into_image_silent(
&icon_theme, &determine_volume_icon(sink.muted, sink.volume),
false,
self.icon_size,
).map(|provider| provider.load_into_image(image_icon.clone()));
},
_ => {},
}
});
}
let popup = self
.into_popup(
context.controller_tx.clone(),
context.subscribe(),
context,
info,
)
.into_popup_parts(vec![&button]);
Ok(ModuleParts::new(button, popup))
}
fn into_popup(
self,
tx: mpsc::Sender<Self::ReceiveMessage>,
rx: tokio::sync::broadcast::Receiver<Self::SendMessage>,
_context: WidgetContext<Self::SendMessage, Self::ReceiveMessage>,
info: &ModuleInfo,
) -> Option<GtkBox>
where
Self: Sized,
{
let container = GtkBox::new(Orientation::Horizontal, 10);
let sink_container = GtkBox::new(Orientation::Vertical, 5);
sink_container.add_class("device-box");
let input_container = GtkBox::new(Orientation::Vertical, 5);
input_container.add_class("apps-box");
container.add(&sink_container);
container.add(&input_container);
let sink_selector = ComboBoxText::new();
sink_selector.add_class("device-selector");
let renderer = sink_selector
.cells()
.first()
.expect("to exist")
.clone()
.downcast::<CellRendererText>()
.expect("to be valid cast");
renderer.set_width_chars(20);
renderer.set_ellipsize(EllipsizeMode::End);
{
let tx = tx.clone();
sink_selector.connect_changed(move |selector| {
if let Some(name) = selector.active_id() {
try_send!(tx, Update::SinkChange(name.into()));
}
});
}
sink_container.add(&sink_selector);
let slider = Scale::builder()
.orientation(Orientation::Vertical)
.height_request(100)
.inverted(true)
.build();
slider.add_class("slider");
slider.set_range(0.0, self.max_volume);
slider.set_value(50.0);
sink_container.add(&slider);
{
let tx = tx.clone();
let selector = sink_selector.clone();
slider.connect_button_release_event(move |scale, _| {
if let Some(sink) = selector.active_id() {
// GTK will send values outside min/max range
let val = scale.value().clamp(0.0, self.max_volume);
try_send!(tx, Update::SinkVolume(sink.into(), val));
}
Propagation::Proceed
});
}
let btn_mute = ToggleButton::new();
btn_mute.add_class("btn-mute");
let btn_mute_icon = Image::new();
btn_mute.set_image(Some(&btn_mute_icon));
sink_container.add(&btn_mute);
{
let tx = tx.clone();
let selector = sink_selector.clone();
btn_mute.connect_toggled(move |btn| {
if let Some(sink) = selector.active_id() {
let muted = btn.is_active();
try_send!(tx, Update::SinkMute(sink.into(), muted));
}
});
}
container.show_all();
let mut inputs = HashMap::new();
{
let icon_theme = info.icon_theme.clone();
let input_container = input_container.clone();
let mut sinks = vec![];
glib_recv!(rx, event => {
match event {
Event::AddSink(info) => {
sink_selector.append(Some(&info.name), &info.description);
if info.active {
sink_selector.set_active(Some(sinks.len() as u32));
slider.set_value(info.volume);
btn_mute.set_active(info.muted);
ImageProvider::parse(
&determine_volume_icon(info.muted, info.volume),
&icon_theme,
false,
self.icon_size, self.icon_size,
).map(|provider| provider.load_into_image(btn_mute_icon.clone()));
}
sinks.push(info);
}
Event::UpdateSink(info) => {
if info.active {
if let Some(pos) = sinks.iter().position(|s| s.name == info.name) {
sink_selector.set_active(Some(pos as u32));
slider.set_value(info.volume);
btn_mute.set_active(info.muted);
ImageProvider::parse(
&determine_volume_icon(info.muted, info.volume),
&icon_theme,
false,
self.icon_size,
).map(|provider| provider.load_into_image(btn_mute_icon.clone()));
}
}
}
Event::RemoveSink(name) => {
if let Some(pos) = sinks.iter().position(|s| s.name == name) {
ComboBoxTextExt::remove(&sink_selector, pos as i32);
sinks.remove(pos);
}
}
Event::AddInput(info) => {
let index = info.index;
let item_container = GtkBox::new(Orientation::Vertical, 0);
item_container.add_class("app-box");
let label = Label::new(Some(&info.name));
label.add_class("title");
let slider = Scale::builder().sensitive(info.can_set_volume).build();
slider.set_range(0.0, self.max_volume);
slider.set_value(info.volume);
slider.add_class("slider");
{
let tx = tx.clone();
slider.connect_button_release_event(move |scale, _| {
// GTK will send values outside min/max range
let val = scale.value().clamp(0.0, self.max_volume);
try_send!(tx, Update::InputVolume(index, val));
Propagation::Proceed
});
}
let btn_mute = ToggleButton::new();
btn_mute.add_class("btn-mute");
let btn_mute_icon = Image::new();
btn_mute.set_image(Some(&btn_mute_icon));
btn_mute.set_active(info.muted);
ImageProvider::parse(
&determine_volume_icon(info.muted, info.volume),
&icon_theme,
false,
self.icon_size,
).map(|provider| provider.load_into_image(btn_mute_icon.clone()));
{
let tx = tx.clone();
btn_mute.connect_toggled(move |btn| {
let muted = btn.is_active();
try_send!(tx, Update::InputMute(index, muted));
});
}
item_container.add(&label);
item_container.add(&slider);
item_container.add(&btn_mute);
item_container.show_all();
input_container.add(&item_container);
inputs.insert(info.index, InputUi {
container: item_container,
label,
slider,
btn_mute_icon,
});
}
Event::UpdateInput(info) => {
if let Some(ui) = inputs.get(&info.index) {
ui.label.set_label(&info.name);
ui.slider.set_value(info.volume);
ui.slider.set_sensitive(info.can_set_volume);
ImageProvider::parse(
&determine_volume_icon(info.muted, info.volume),
&icon_theme,
false, false,
self.icon_size, &image_icon,
).map(|provider| provider.load_into_image(ui.btn_mute_icon.clone())); )
} .await;
}
Event::RemoveInput(index) => {
if let Some(ui) = inputs.remove(&index) {
input_container.remove(&ui.container);
}
} }
_ => {}
} }
}); }
} });
Some(container) Ok(ModuleParts::new(button, None))
} }
} }
struct InputUi { struct InputUi {
container: GtkBox, container: gtk::Box,
label: Label, label: Label,
slider: Scale, slider: Scale,
btn_mute_icon: Image, btn_mute: ToggleButton,
} }
fn determine_volume_icon(muted: bool, volume: f64) -> String { fn determine_volume_icon(muted: bool, volume: f64) -> String {