This commit is contained in:
jmb05
2026-10-25 00:02:36 +02:00
parent d6a2c6afea
commit 4ca6596b1d
14 changed files with 351 additions and 386 deletions

View File

@@ -307,8 +307,8 @@ impl BackendThread<MediaCommand, Sender<MediaCommand>> for MediaBackend {
loop {
while let Ok(msg) = controller_rx.try_recv() {
match msg {
ControllerMsg::Request => {
let _ = instance_clone.lock().expect("Couldn't get lock").publish(
Request => {
instance_clone.lock().expect("Couldn't get lock").publish(
MediaCommand::Cmd(
controller.current_vol,
controller.current_mute,
@@ -319,7 +319,7 @@ impl BackendThread<MediaCommand, Sender<MediaCommand>> for MediaBackend {
ControllerMsg::NotifyServer => {
controller.query_default_device_blocking();
let _ = controller.query_state_blocking();
let _ = instance_clone.lock().expect("Couldn't get lock").publish(
instance_clone.lock().expect("Couldn't get lock").publish(
MediaCommand::Cmd(
controller.current_vol,
controller.current_mute,
@@ -331,14 +331,13 @@ impl BackendThread<MediaCommand, Sender<MediaCommand>> for MediaBackend {
if controller.device_index.is_some_and(|i| i == idx) {
let changed = controller.query_state_blocking();
if changed {
let _ = instance_clone
.lock()
.expect("Couldn't get lock")
.publish(MediaCommand::Cmd(
instance_clone.lock().expect("Couldn't get lock").publish(
MediaCommand::Cmd(
controller.current_vol,
controller.current_mute,
controller.device_bt.unwrap_or(false),
));
),
);
trace!(
&LOGGER,
"Change: {} muted: {}",
@@ -350,7 +349,7 @@ impl BackendThread<MediaCommand, Sender<MediaCommand>> for MediaBackend {
}
ControllerMsg::Set(volume, mute) => {
controller.set_state(volume, mute);
let _ = instance_clone.lock().expect("Couldn't get lock").publish(
instance_clone.lock().expect("Couldn't get lock").publish(
MediaCommand::Cmd(
controller.current_vol,
controller.current_mute,

View File

@@ -15,7 +15,7 @@ use std::{fs, thread};
pub enum DisplayBackend {
Sysfs(BrightnessDevice),
DdcCi(ddc_hi::Display),
DdcCi(Box<ddc_hi::Display>),
}
fn get_sysfs_dev(id: &str) -> Option<BrightnessDevice> {
@@ -47,7 +47,7 @@ impl DisplayBackend {
pub fn get_brightness(&mut self) -> Option<u8> {
match self {
DisplayBackend::Sysfs(dev) => dev.get().and_then(|val| Ok(val as u8)).ok(),
DisplayBackend::Sysfs(dev) => dev.get().map(|val| val as u8).ok(),
DisplayBackend::DdcCi(display) => {
if let Ok(val) = display.handle.get_vcp_feature(0x10) {
Some(val.value() as u8)
@@ -70,11 +70,11 @@ struct DisplayData(DisplayBackend, u8);
impl DisplayData {
fn update(&mut self) -> bool {
if let Some(value) = self.0.get_brightness() {
if self.1 != value {
self.1 = value;
return true;
}
if let Some(value) = self.0.get_brightness()
&& self.1 != value
{
self.1 = value;
return true;
}
false
}
@@ -116,7 +116,7 @@ impl BackendThread<BrightnessMessage, Sender<BrightnessMessage>> for BrightnessM
subscribers: Vec::new(),
}));
let instance_clone = instance.clone();
std::thread::spawn(move || {
thread::spawn(move || {
while let Ok(tx) = registration_rx.recv() {
if tx.send(BrightnessMessage::Init(f2b_tx.clone())).is_ok() {
trace!(&LOGGER, "Added Brightness Subscriber: {tx:?}");
@@ -129,7 +129,7 @@ impl BackendThread<BrightnessMessage, Sender<BrightnessMessage>> for BrightnessM
}
});
let instance_clone = instance.clone();
std::thread::spawn(move || {
thread::spawn(move || {
while let Ok(mut msg) = f2b_rx.recv() {
while let Ok(newer) = f2b_rx.try_recv() {
msg = newer;
@@ -151,7 +151,7 @@ impl BackendThread<BrightnessMessage, Sender<BrightnessMessage>> for BrightnessM
.expect("Couldn't get lock")
.display_cache
.get(&id)
.and_then(|v| Some(v.1))
.map(|v| v.1)
{
instance_clone
.lock()
@@ -216,23 +216,21 @@ impl BrightnessManager {
if path.file_name().eq("device")
&& let Ok(link) = fs::read_link(path.path())
&& let Some(name) = link.file_name()
{
if name
&& name
.to_str()
.is_some_and(|name| name.eq(&format!("card1-{connector}")))
{
println!("Found sysfs display {connector}");
let path = bl_path.file_name();
let Some(name) = path.to_str() else { continue };
let Some(device) = get_sysfs_dev(name) else {
continue;
};
let mut backend = DisplayBackend::Sysfs(device);
let value = backend.get_brightness().unwrap_or(60);
self.display_cache
.insert(connector.clone(), DisplayData(backend, value));
return;
}
{
println!("Found sysfs display {connector}");
let path = bl_path.file_name();
let Some(name) = path.to_str() else { continue };
let Some(device) = get_sysfs_dev(name) else {
continue;
};
let mut backend = DisplayBackend::Sysfs(device);
let value = backend.get_brightness().unwrap_or(60);
self.display_cache
.insert(connector.clone(), DisplayData(backend, value));
return;
}
}
}
@@ -244,7 +242,7 @@ impl BrightnessManager {
println!("Found DDC/CI display {connector}");
for display in ddc_hi::Display::enumerate() {
if id.to_string().eq(&display.info.id) {
let mut backend = DisplayBackend::DdcCi(display);
let mut backend = DisplayBackend::DdcCi(Box::new(display));
let value = backend.get_brightness().unwrap_or(60);
self.display_cache
.insert(connector.clone(), DisplayData(backend, value));
@@ -307,10 +305,10 @@ impl BrightnessManager {
}
}
if drm_connector.as_deref() == Some(connector) {
if let Some(bus) = bus {
return Ok(bus);
}
if drm_connector.as_deref() == Some(connector)
&& let Some(bus) = bus
{
return Ok(bus);
}
}

View File

@@ -39,7 +39,7 @@ impl PartialEq<Self> for NetworkInfo {
impl PartialOrd<Self> for NetworkInfo {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(other.cmp(self))
Some(self.cmp(other))
}
}
@@ -82,20 +82,17 @@ impl From<ConnectionError> for ConnectError {
match value {
ConnectionError::AuthFailed => ConnectError::AuthFailed,
ConnectionError::NotFound => ConnectError::NotFound,
ConnectionError::Dbus(err) => match err {
Error::MethodError(name, ..) => {
if name.eq(&ErrorName::try_from(
"org.freedesktop.NetworkManager.Device.SpecificObjectNotFound",
)
.unwrap())
{
ConnectError::NotFound
} else {
ConnectError::Unknown
}
ConnectionError::Dbus(Error::MethodError(name, ..)) => {
if name.eq(&ErrorName::try_from(
"org.freedesktop.NetworkManager.Device.SpecificObjectNotFound",
)
.unwrap())
{
ConnectError::NotFound
} else {
ConnectError::Unknown
}
_ => ConnectError::Unknown,
},
}
_ => ConnectError::Unknown,
}
}
@@ -208,13 +205,13 @@ impl BackendThread<NetworkState, UnboundedSender<NetworkCommand>> for NetworkBac
} else {
match auth {
Auth::Open => {
if let Ok(networks) = nm.list_access_points(None).await {
if let Some(ap) = networks.iter().find(|net| net.ssid.eq(&ssid)) {
if ap.security.is_open() {
instance_clone.connect(&nm, ssid, WifiSecurity::Open).await;
} else {
instance_clone.publish(NetworkState::Auth(ssid, AuthType::Password));
}
if let Ok(networks) = nm.list_access_points(None).await
&& let Some(ap) = networks.iter().find(|net| net.ssid.eq(&ssid))
{
if ap.security.is_open() {
instance_clone.connect(&nm, ssid, WifiSecurity::Open).await;
} else {
instance_clone.publish(NetworkState::Auth(ssid, AuthType::Password));
}
}
}
@@ -269,23 +266,23 @@ impl NetworkBackendHandle {
}
async fn print_network_info(&self, nm: &NetworkManager, ssid: &str, level: Level) {
if let Ok(nets) = nm.list_networks(None).await {
if let Some(net) = nets.iter().find(|net| net.ssid.eq(ssid)) {
log!(&LOGGER, level, "Network:");
log!(&LOGGER, level, " SSID: {}", net.ssid);
log!(&LOGGER, level, " Active: {}", net.is_active);
log!(&LOGGER, level, " Known: {}", net.known);
log!(&LOGGER, level, " Secured: {}", net.secured);
if net.secured {
log!(&LOGGER, level, " Features: {:?}", net.security_features);
log!(&LOGGER, level, " EAP: {}", net.is_eap);
log!(&LOGGER, level, " PSK: {}", net.is_psk);
}
log!(&LOGGER, level, " Strength: {:?}", net.strength);
log!(&LOGGER, level, " Device: {}", net.device);
log!(&LOGGER, level, " Addr(4): {:?}", net.ip4_address);
log!(&LOGGER, level, " Addr(6): {:?}", net.ip6_address);
if let Ok(nets) = nm.list_networks(None).await
&& let Some(net) = nets.iter().find(|net| net.ssid.eq(ssid))
{
log!(&LOGGER, level, "Network:");
log!(&LOGGER, level, " SSID: {}", net.ssid);
log!(&LOGGER, level, " Active: {}", net.is_active);
log!(&LOGGER, level, " Known: {}", net.known);
log!(&LOGGER, level, " Secured: {}", net.secured);
if net.secured {
log!(&LOGGER, level, " Features: {:?}", net.security_features);
log!(&LOGGER, level, " EAP: {}", net.is_eap);
log!(&LOGGER, level, " PSK: {}", net.is_psk);
}
log!(&LOGGER, level, " Strength: {:?}", net.strength);
log!(&LOGGER, level, " Device: {}", net.device);
log!(&LOGGER, level, " Addr(4): {:?}", net.ip4_address);
log!(&LOGGER, level, " Addr(6): {:?}", net.ip6_address);
}
}
@@ -304,7 +301,7 @@ impl NetworkBackendHandle {
NetworkEvent::WirelessEnabledChanged => {
if let Ok(state) = nm.wifi_state().await {
if !state.enabled {
let _ = self.publish(NetworkState::ChangeNetwork(None));
self.publish(NetworkState::ChangeNetwork(None));
} else {
let _ = self.send_active_connection(nm).await;
}
@@ -313,23 +310,22 @@ impl NetworkBackendHandle {
NetworkEvent::ActiveConnectionsChanged => {
let _ = self.send_active_connection(nm).await;
}
NetworkEvent::DeviceChanged { interface } => match interface {
Some(interface) => match nm.active_vpn_connections().await {
Ok(connections) => {
let mut connected = false;
for conn in connections {
if conn.interface.is_some_and(|s| s.eq(&interface)) {
connected = true;
}
NetworkEvent::DeviceChanged {
interface: Some(interface),
} => match nm.active_vpn_connections().await {
Ok(connections) => {
let mut connected = false;
for conn in connections {
if conn.interface.is_some_and(|s| s.eq(&interface)) {
connected = true;
}
let _ = self.publish(NetworkState::VpnState {
profile: interface,
connected,
});
}
Err(err) => error!(&LOGGER, "Error getting active vpns: {}", err.to_string()),
},
None => {}
self.publish(NetworkState::VpnState {
profile: interface,
connected,
});
}
Err(err) => error!(&LOGGER, "Error getting active vpns: {}", err.to_string()),
},
_ => {}
}
@@ -443,7 +439,7 @@ impl NetworkBackendHandle {
secured: None,
known: true,
};
let _ = self.publish(NetworkState::ChangeNetwork(Some(info)));
self.publish(NetworkState::ChangeNetwork(Some(info)));
}
ActiveConnection::Wifi(c) => {
let info = NetworkInfo {
@@ -453,13 +449,13 @@ impl NetworkBackendHandle {
secured: None, // Not relevant here
known: true,
};
let _ = self.publish(NetworkState::ChangeNetwork(Some(info)));
self.publish(NetworkState::ChangeNetwork(Some(info)));
}
_ => {}
}
}
None => {
let _ = self.publish(NetworkState::ChangeNetwork(None));
self.publish(NetworkState::ChangeNetwork(None));
}
}
}
@@ -478,11 +474,8 @@ impl NetworkBackendHandle {
Ok::<bool, Box<dyn std::error::Error>>(active.iter().any(|vpn| vpn.name == profile))
};
match operation.await {
Ok(connected) => {
let _ = self.publish(NetworkState::VpnState { profile, connected });
}
Err(_) => {}
if let Ok(connected) = operation.await {
self.publish(NetworkState::VpnState { profile, connected });
}
}
}

View File

@@ -91,33 +91,31 @@ impl BackendThread<Stats, ()> for StatsBackend {
let mut battery_draw: f32 = 0.0;
let mut battery_time: u64 = 0;
if let Ok(manager) = &manager {
if let Ok(mut batteries) = manager.batteries() {
match batteries.next() {
Some(Ok(battery)) => {
battery_charge =
battery.state_of_charge().get::<percent>().round() as u8;
battery_state = battery.state();
battery_draw = battery.energy_rate().get::<watt>();
battery_time = if battery_state == State::Charging {
battery
.time_to_full()
.unwrap_or(Time::new::<millisecond>(0.0))
.get::<millisecond>()
as u64
} else if battery_state == State::Discharging {
battery
.time_to_empty()
.unwrap_or(Time::new::<millisecond>(0.0))
.get::<millisecond>()
as u64
} else {
0
};
}
Some(Err(e)) => error!(&LOGGER, "Error accessing battery: {e:?}"),
None => {}
if let Ok(manager) = &manager
&& let Ok(mut batteries) = manager.batteries()
{
match batteries.next() {
Some(Ok(battery)) => {
battery_charge =
battery.state_of_charge().get::<percent>().round() as u8;
battery_state = battery.state();
battery_draw = battery.energy_rate().get::<watt>();
battery_time = if battery_state == State::Charging {
battery
.time_to_full()
.unwrap_or(Time::new::<millisecond>(0.0))
.get::<millisecond>() as u64
} else if battery_state == State::Discharging {
battery
.time_to_empty()
.unwrap_or(Time::new::<millisecond>(0.0))
.get::<millisecond>() as u64
} else {
0
};
}
Some(Err(e)) => error!(&LOGGER, "Error accessing battery: {e:?}"),
None => {}
}
}

View File

@@ -89,13 +89,13 @@ impl TailscaleBackend {
match serde_json::from_slice::<serde_json::Value>(line) {
Ok(notification) => {
if let Some(state) = notification.get("State") {
if !state.is_null() {
let state =
TailscaleState::try_from_value(state.as_i64().unwrap_or(4))
.unwrap_or(TailscaleState::Stopped);
instance.lock().expect("Couldn't get lock").publish(state);
}
if let Some(state) = notification.get("State")
&& !state.is_null()
{
let state =
TailscaleState::try_from_value(state.as_i64().unwrap_or(4))
.unwrap_or(TailscaleState::Stopped);
instance.lock().expect("Couldn't get lock").publish(state);
}
}
Err(err) => {
@@ -174,11 +174,11 @@ fn initial_state() -> TailscaleState {
.output()
{
let val: Result<serde_json::Value, _> = serde_json::from_slice(&output.stdout);
if val.is_ok() {
if let Some(res) = val.unwrap().get("BackendState").and_then(|v| v.as_str()) {
if res.eq("Running") {
return TailscaleState::Running;
}
if let Ok(val) = val {
if let Some(res) = val.get("BackendState").and_then(|v| v.as_str())
&& res.eq("Running")
{
return TailscaleState::Running;
}
} else {
error!(&LOGGER, "{:?}", val.err());

View File

@@ -45,13 +45,13 @@ impl BackendThread<WindowManagerEvent, ()> for HyprlandComms {
let inst_clone = instance.clone();
listener.add_workspace_changed_handler(move |workspace| {
if let WorkspaceType::Regular(name) = workspace.name {
if let Ok(id) = name.parse::<i32>() {
inst_clone
.lock()
.expect("Couldn't get Subscribers")
.publish(WindowManagerEvent::WorkspaceChanged(id));
}
if let WorkspaceType::Regular(name) = workspace.name
&& let Ok(id) = name.parse::<i32>()
{
inst_clone
.lock()
.expect("Couldn't get Subscribers")
.publish(WindowManagerEvent::WorkspaceChanged(id));
}
});
@@ -84,13 +84,13 @@ impl BackendThread<WindowManagerEvent, ()> for HyprlandComms {
let inst_clone = instance.clone();
listener.add_workspace_deleted_handler(move |workspace| {
if let WorkspaceType::Regular(name) = workspace.name {
if let Ok(id) = name.parse::<i32>() {
inst_clone
.lock()
.expect("Couldn't get Subscribers")
.publish(WindowManagerEvent::WorkspaceRemoved(id));
}
if let WorkspaceType::Regular(name) = workspace.name
&& let Ok(id) = name.parse::<i32>()
{
inst_clone
.lock()
.expect("Couldn't get Subscribers")
.publish(WindowManagerEvent::WorkspaceRemoved(id));
}
});
@@ -159,10 +159,10 @@ impl BackendThread<WindowManagerEvent, ()> for HyprlandComms {
impl HyprlandComms {
fn monitor_id_from_workspace_id(id: WorkspaceId) -> Option<MonitorId> {
if let Ok(wss) = Workspaces::get() {
if let Some(ws) = wss.to_vec().iter().find(|ws| ws.id().unwrap() == id) {
return ws.monitor_id;
}
if let Ok(wss) = Workspaces::get()
&& let Some(ws) = wss.to_vec().iter().find(|ws| ws.id().unwrap() == id)
{
return ws.monitor_id;
}
None
}

View File

@@ -1,3 +1,4 @@
use crate::LOGGER;
use glib::ControlFlow;
use jmb_logger_rs::*;
use notify::EventKind::{Create, Modify, Remove};
@@ -5,35 +6,30 @@ use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use std::path::Path;
use std::sync::mpsc;
use std::time::Duration;
use crate::LOGGER;
pub fn parse_css() -> Option<String> {
match grass::from_path(
"style/style.scss",
&grass::Options::default(),
) {
match grass::from_path("style/style.scss", &grass::Options::default()) {
Ok(css) => {
debug!(&LOGGER, "(Re-)Loading CSS");
Some(css)
},
}
Err(err) => {
error!(&LOGGER, "SCSS compilation failed: {err}");
None
},
}
}
}
pub fn watch_css<F>(reload: F) -> RecommendedWatcher
where F: Fn(String) -> () + 'static {
where
F: Fn(String) + 'static,
{
let (tx, rx) = mpsc::channel();
let mut watcher = notify::recommended_watcher(tx).unwrap();
watcher
.watch(
Path::new("style"),
RecursiveMode::Recursive,
)
.watch(Path::new("style"), RecursiveMode::Recursive)
.unwrap();
glib::timeout_add_local(Duration::from_millis(1000), move || {
@@ -53,4 +49,4 @@ where F: Fn(String) -> () + 'static {
});
watcher
}
}

View File

@@ -80,11 +80,7 @@ fn create_bar(
.expect("Tried taking unavailable Hyprland Channel Receiver");
let player_opt = if let Ok(player_finder) = PlayerFinder::new() {
if let Ok(player) = player_finder.find_active() {
Some(player)
} else {
None
}
player_finder.find_active().ok()
} else {
None
};
@@ -105,10 +101,10 @@ fn create_bar(
window.set_anchor(Edge::Left, true);
window.set_anchor(Edge::Right, true);
window.set_margin(Edge::Top, 20);
if let Some(monitor) = monitors.item(monitor_idx) {
if let Ok(monitor) = monitor.downcast::<gdk::Monitor>() {
window.set_monitor(Some(&monitor));
}
if let Some(monitor) = monitors.item(monitor_idx)
&& let Ok(monitor) = monitor.downcast::<gdk::Monitor>()
{
window.set_monitor(Some(&monitor));
}
window.set_exclusive_zone(30);
@@ -116,10 +112,7 @@ fn create_bar(
let mut buttons: HashMap<i32, Button> = HashMap::new();
let (workspaces, submap) = workspaces_panel::build(
&mut buttons,
window
.monitor()
.map(|monitor| monitor_index(&monitor))
.flatten(),
window.monitor().and_then(|monitor| monitor_index(&monitor)),
);
let title_button: Option<Button>;
@@ -205,7 +198,7 @@ fn handle_wm_event(
for (&id, button) in buttons {
if id == workspace
&& current_monitor.as_ref().is_none_or(|cur_mon| {
monitor_index(&cur_mon).is_some_and(|idx| idx == monitor as u32)
monitor_index(cur_mon).is_some_and(|idx| idx == monitor as u32)
})
{
button.set_visible(true);

View File

@@ -136,34 +136,31 @@ impl ActionCentre {
glib::timeout_add_local(Duration::from_millis(100), move || {
while let Ok(message) = net_rx.try_recv() {
match message {
NetworkState::ChangeNetwork(info) => match info {
Some(info) => {
for (name, widget) in wifi_networks_clone.borrow().iter() {
if name.eq(&info.name) {
widget.add_css_class("connected");
} else {
widget.remove_css_class("connected");
}
NetworkState::ChangeNetwork(Some(info)) => {
for (name, widget) in wifi_networks_clone.borrow().iter() {
if name.eq(&info.name) {
widget.add_css_class("connected");
} else {
widget.remove_css_class("connected");
}
}
None => {}
},
}
NetworkState::Networks(networks) => {
for network in &networks {
let borrowed_wifi_networks_clone = wifi_networks_clone.borrow_mut();
let widget = borrowed_wifi_networks_clone.get(&network.name);
if widget.is_none() {
if let Some(widget) = widget {
let idx = ((network.signal as f32 / 100.0)
* (WIFI_ICONS.len() - 1) as f32
+ 0.5) as usize;
widget.set_wifi_icon_from_name(WIFI_ICONS[idx]);
} else {
let widget = Self::create_wifi_widget(
&channels,
network,
borrowed_wifi_networks_clone,
);
content.append(&widget);
} else {
let idx = ((network.signal as f32 / 100.0)
* (WIFI_ICONS.len() - 1) as f32
+ 0.5) as usize;
widget.unwrap().set_wifi_icon_from_name(WIFI_ICONS[idx]);
}
}
let mut removal: Vec<String> = Vec::new();
@@ -179,7 +176,7 @@ impl ActionCentre {
}
}
NetworkState::Auth(ssid, auth) => {
if let Some(widget) = Self::find_focused_widget((&window_clone).as_ref()) {
if let Some(widget) = Self::find_focused_widget(window_clone.as_ref()) {
match auth {
AuthType::Password => {
if widget.ssid().eq(&ssid) {
@@ -268,7 +265,7 @@ impl ActionCentre {
wifi_networks: &Rc<RefCell<HashMap<String, WifiWidget>>>,
window: &ApplicationWindow,
) {
for (_, widget) in wifi_networks.clone().borrow().iter() {
for widget in wifi_networks.clone().borrow().values() {
let focused_inside = window.focus().is_some_and(|mut focus| {
loop {
if focus == *widget {
@@ -329,8 +326,6 @@ impl ActionCentre {
if !window.is_visible() {
self.animate_margin(-window.width() - 20, 20, ANIMATION_DURATION, || {});
window.present();
} else {
return;
}
}

View File

@@ -17,22 +17,21 @@ pub fn build() -> Button {
title.set_visible(false);
title.add_css_class("title");
title.connect_clicked(|button| {
if button.has_css_class("media") {
if let Ok(player_finder) = PlayerFinder::new() {
if let Ok(player) = player_finder.find_active() {
let _ = player.play_pause();
}
}
if button.has_css_class("media")
&& let Ok(player_finder) = PlayerFinder::new()
&& let Ok(player) = player_finder.find_active()
{
let _ = player.play_pause();
}
});
let right_click = GestureClick::new();
right_click.set_button(3);
right_click.connect_pressed(|_gesture, _n_press, _, _| {
if let Ok(player_finder) = PlayerFinder::new() {
if let Ok(player) = player_finder.find_active() {
let _ = player.stop();
}
if let Ok(player_finder) = PlayerFinder::new()
&& let Ok(player) = player_finder.find_active()
{
let _ = player.stop();
}
});
title.add_controller(right_click);
@@ -41,35 +40,35 @@ pub fn build() -> Button {
pub fn manage_title(button_opt: &Option<Button>, player_opt: &Option<Player>) {
let mut handled = false;
if let Some(button) = button_opt {
if let Some(player) = player_opt {
if let Ok(status) = player.get_playback_status() {
if let Ok(metadata) = player.get_metadata() {
match status {
PlaybackStatus::Playing => {
button.set_visible(true);
button.child()
.and_downcast::<Label>()
.unwrap()
.set_label(&format!("{}", metadata.title().unwrap_or("")));
button.add_css_class("media");
button.add_css_class("playing");
handled = true;
}
PlaybackStatus::Paused => {
button.set_visible(true);
button.child()
.and_downcast::<Label>()
.unwrap()
.set_label(&format!("{}", metadata.title().unwrap_or("")));
button.add_css_class("media");
button.remove_css_class("playing");
handled = true;
}
PlaybackStatus::Stopped => {},
}
}
if let Some(button) = button_opt
&& let Some(player) = player_opt
&& let Ok(status) = player.get_playback_status()
&& let Ok(metadata) = player.get_metadata()
{
match status {
PlaybackStatus::Playing => {
button.set_visible(true);
button
.child()
.and_downcast::<Label>()
.unwrap()
.set_label(&format!("{}", metadata.title().unwrap_or("")));
button.add_css_class("media");
button.add_css_class("playing");
handled = true;
}
PlaybackStatus::Paused => {
button.set_visible(true);
button
.child()
.and_downcast::<Label>()
.unwrap()
.set_label(&format!("{}", metadata.title().unwrap_or("")));
button.add_css_class("media");
button.remove_css_class("playing");
handled = true;
}
PlaybackStatus::Stopped => {}
}
if !handled {
button.set_visible(true);
@@ -87,9 +86,10 @@ pub fn set_title(title: &str, title_button: &Option<Button>) {
} else {
button.set_visible(true);
}
button.child()
button
.child()
.and_downcast::<Label>()
.unwrap()
.set_label(&HyprlandComms::get_current_title());
}
}
}

View File

@@ -148,7 +148,7 @@ pub fn build(
button.remove_css_class("on")
}
} else {
if let Ok(_) = child.as_mut().unwrap().kill() {
if child.as_mut().unwrap().kill().is_ok() {
let _ = child.take();
button.add_css_class("on");
}
@@ -316,10 +316,9 @@ pub fn build(
glib::timeout_add_local(Duration::from_millis(1000), move || {
let timestamp = time_format::now().unwrap();
let time_str = time_format::strftime_local("%H:%M", timestamp).unwrap_or(String::new());
let time_str = time_format::strftime_local("%H:%M", timestamp).unwrap_or_default();
time.set_title(&time_str);
let time_sec =
time_format::strftime_local(":%S %Y-%m-%d", timestamp).unwrap_or(String::new());
let time_sec = time_format::strftime_local(":%S %Y-%m-%d", timestamp).unwrap_or_default();
time_hidden.set_label(&time_sec);
ControlFlow::Continue
});
@@ -332,46 +331,40 @@ pub fn build(
let hypridle = channels.hypridle();
glib::timeout_add_local(Duration::from_millis(100), move || {
while let Ok(command) = media_rx.try_recv() {
match command {
MediaCommand::Cmd(vol, mute, bt) => {
changed_progr.set(true);
volume.set_value(vol as f64);
changed_progr.set(false);
volume.show_scale(!mute);
volume.imp().button.set_active(mute);
if mute {
volume.imp().button.add_css_class("muted");
volume.imp().second_icon.add_child_css_class("muted");
volume
.imp()
.main_icon
.set_icon_path("icons/volume-mute.svg");
} else {
volume.imp().button.remove_css_class("muted");
volume.imp().second_icon.remove_child_css_class("muted");
let idx = ((volume.value() / 100.0) * (VOLUME_ICON_PATHS.len() - 1) as f64
+ 0.5) as usize;
volume.imp().main_icon.set_icon_path(VOLUME_ICON_PATHS[idx]);
}
volume.imp().second_icon.set_visible(bt);
if let MediaCommand::Cmd(vol, mute, bt) = command {
changed_progr.set(true);
volume.set_value(vol as f64);
changed_progr.set(false);
volume.show_scale(!mute);
volume.imp().button.set_active(mute);
if mute {
volume.imp().button.add_css_class("muted");
volume.imp().second_icon.add_child_css_class("muted");
volume
.imp()
.main_icon
.set_icon_path("icons/volume-mute.svg");
} else {
volume.imp().button.remove_css_class("muted");
volume.imp().second_icon.remove_child_css_class("muted");
let idx = ((volume.value() / 100.0) * (VOLUME_ICON_PATHS.len() - 1) as f64
+ 0.5) as usize;
volume.imp().main_icon.set_icon_path(VOLUME_ICON_PATHS[idx]);
}
_ => {}
volume.imp().second_icon.set_visible(bt);
}
}
while let Ok(message) = br_rx.try_recv() {
match message {
BrightnessMessage::Value(mon, value) => {
if monitor.eq(&mon) {
brightness.set_value(value as f64);
let idx = ((value as f32 / 100.0) * (BRIGHTNESS_ICONS.len() - 1) as f32
+ 0.5) as usize;
brightness
.imp()
.main_icon
.set_font_icon(BRIGHTNESS_ICONS[idx]);
}
}
_ => {}
if let BrightnessMessage::Value(mon, value) = message
&& monitor.eq(&mon)
{
brightness.set_value(value as f64);
let idx =
((value as f32 / 100.0) * (BRIGHTNESS_ICONS.len() - 1) as f32 + 0.5) as usize;
brightness
.imp()
.main_icon
.set_font_icon(BRIGHTNESS_ICONS[idx]);
}
}
if let Ok(mut hypridle) = hypridle.try_lock() {
@@ -416,16 +409,13 @@ pub fn build(
}
}
}
NetworkState::VpnState { connected, profile } => match profile.as_str() {
"wg" => {
if connected {
wg_button.add_css_class("on");
} else {
wg_button.remove_css_class("on");
}
NetworkState::VpnState { connected, profile } if profile.as_str() == "wg" => {
if connected {
wg_button.add_css_class("on");
} else {
wg_button.remove_css_class("on");
}
_ => {}
},
}
_ => {}
}
}
@@ -468,9 +458,8 @@ pub fn build(
}
}
for gpu in stats.gpus {
if let Some(gpu) = stats.gpus.into_iter().next() {
gpu_label.set_label(&format!("{}%", gpu.1));
break;
}
set_battery_css_classes(&battery_widget, stats.battery_state, stats.battery_charge);

View File

@@ -7,7 +7,10 @@ use hyprland::prelude::HyprDataActive;
use jmb_logger_rs::*;
use std::collections::HashMap;
pub(crate) fn build(buttons: &mut HashMap<i32, Button>, monitor: Option<u32>) -> (gtk::Box, Button) {
pub(crate) fn build(
buttons: &mut HashMap<i32, Button>,
monitor: Option<u32>,
) -> (gtk::Box, Button) {
let workspaces = gtk::Box::new(Orientation::Horizontal, 0);
workspaces.set_halign(Align::Start);
workspaces.set_valign(Align::Center);
@@ -24,13 +27,12 @@ pub(crate) fn build(buttons: &mut HashMap<i32, Button>, monitor: Option<u32>) ->
let initial_workspace = Workspace::get_active()
.ok()
.map(|workspace| workspace.id().unwrap_or(1) as i32)
.map(|workspace| workspace.id().unwrap_or(1))
.unwrap_or(1);
let is_active_ws_on_current_monitor = Workspace::get_active()
.ok()
.map(|ws| ws.monitor_id)
.flatten()
.and_then(|ws| ws.monitor_id)
.is_some_and(|id| monitor.is_some_and(|other_id| id == other_id as i128));
if workspace == initial_workspace && is_active_ws_on_current_monitor {
@@ -41,8 +43,14 @@ pub(crate) fn build(buttons: &mut HashMap<i32, Button>, monitor: Option<u32>) ->
button.set_visible(true);
}
button.connect_clicked(move |_button| {
if let Err(err) = HyprlandComms::dispatch(&format!("hl.dsp.focus({{ workspace = {workspace} }})")) {
warn!(&LOGGER, "Couldn't change workspace focus {}", err.to_string());
if let Err(err) =
HyprlandComms::dispatch(&format!("hl.dsp.focus({{ workspace = {workspace} }})"))
{
warn!(
&LOGGER,
"Couldn't change workspace focus {}",
err.to_string()
);
}
});
workspaces.append(&button);
@@ -59,4 +67,4 @@ pub(crate) fn build(buttons: &mut HashMap<i32, Button>, monitor: Option<u32>) ->
workspaces.append(&submap_button);
(workspaces, submap_button)
}
}