This commit is contained in:
jmb05
2026-11-02 17:26:51 +01:00
parent cdfc5b8d36
commit 11fb03427c
7 changed files with 94 additions and 94 deletions

View File

@@ -475,7 +475,7 @@ impl BackendThread<MediaMessage, Sender<MediaMessage>> for MediaBackend {
let instance = instance.clone(); let instance = instance.clone();
move || { move || {
while let Ok(sender) = registration_rx.recv() { while let Ok(sender) = registration_rx.recv() {
if let Ok(_) = sender.send(MediaMessage::Init(tx.clone())) { if sender.send(MediaMessage::Init(tx.clone())).is_ok() {
let mut instance_guard = instance.lock().unwrap(); let mut instance_guard = instance.lock().unwrap();
if let Some(name) = &instance_guard.active_player if let Some(name) = &instance_guard.active_player
&& let Some(status) = instance_guard.players.get(name) && let Some(status) = instance_guard.players.get(name)
@@ -517,8 +517,9 @@ impl BackendThread<MediaMessage, Sender<MediaMessage>> for MediaBackend {
}; };
while let Ok(msg) = rx.recv() { while let Ok(msg) = rx.recv() {
let mut instance_guard = instance.lock().unwrap(); let mut instance_guard = instance.lock().unwrap();
if let Some(name) = &instance_guard.active_player { if let Some(name) = &instance_guard.active_player
if let Some(status) = instance_guard.players.get(name) { && let Some(status) = instance_guard.players.get(name)
{
match msg { match msg {
MediaMessage::PlayerPlay => { MediaMessage::PlayerPlay => {
if let PlayerStatus::Paused(_) = status { if let PlayerStatus::Paused(_) = status {
@@ -542,7 +543,6 @@ impl BackendThread<MediaMessage, Sender<MediaMessage>> for MediaBackend {
} }
} }
} }
}
}); });
}); });
} }
@@ -575,7 +575,7 @@ impl MediaBackend {
.collect(); .collect();
for player in players { for player in players {
Self::spawn_new_player_watcher(&connection, &instance, &player); Self::spawn_new_player_watcher(connection, &instance, &player);
} }
Ok(()) Ok(())
@@ -680,13 +680,13 @@ impl MediaBackend {
continue; continue;
} }
if let Some(value) = args.changed_properties().get("PlaybackStatus") { if let Some(value) = args.changed_properties().get("PlaybackStatus")
if let Ok(status) = <String>::try_from(value.clone()) { && let Ok(status) = <String>::try_from(value.clone())
{
debug!(&LOGGER, "Player ({name}) status has changed to: '{status}'"); debug!(&LOGGER, "Player ({name}) status has changed to: '{status}'");
Self::insert_or_update_player(&instance, &props, name.into(), status).await; Self::insert_or_update_player(&instance, &props, name.into(), status).await;
} }
} }
}
debug!(&LOGGER, "(2) Removing player: {name}"); debug!(&LOGGER, "(2) Removing player: {name}");
instance.lock().unwrap().players.remove(name); instance.lock().unwrap().players.remove(name);
@@ -699,7 +699,7 @@ impl MediaBackend {
player_name: String, player_name: String,
player_status: String, player_status: String,
) { ) {
match Self::get_player_status_from_string(&props, player_status).await { match Self::get_player_status_from_string(props, player_status).await {
Ok(status) => { Ok(status) => {
let mut instance_guard = instance.lock().unwrap(); let mut instance_guard = instance.lock().unwrap();
instance_guard.players.insert(player_name.clone(), status); instance_guard.players.insert(player_name.clone(), status);
@@ -757,58 +757,52 @@ impl MediaBackend {
} }
async fn active_player_play(&self, connection: &zbus::Connection) { async fn active_player_play(&self, connection: &zbus::Connection) {
if let Some(player_name) = &self.active_player { if let Some(player_name) = &self.active_player
if let Ok(proxy) = zbus::Proxy::new( && let Ok(proxy) = zbus::Proxy::new(
&connection, connection,
player_name.as_str(), player_name.as_str(),
MPRIS_PATH, MPRIS_PATH,
MPRIS_PLAYER_INTERFACE, MPRIS_PLAYER_INTERFACE,
) )
.await .await
&& let Err(e) = proxy.call_method("Play", &()).await
{ {
if let Err(e) = proxy.call_method("Play", &()).await {
warn!( warn!(
&LOGGER, &LOGGER,
"Error starting play for player: {player_name}, {e}" "Error starting play for player: {player_name}, {e}"
); );
} }
} }
}
}
async fn active_player_pause(&mut self, connection: &zbus::Connection) { async fn active_player_pause(&mut self, connection: &zbus::Connection) {
if let Some(player_name) = &self.active_player { if let Some(player_name) = &self.active_player
if let Ok(proxy) = zbus::Proxy::new( && let Ok(proxy) = zbus::Proxy::new(
&connection, connection,
player_name.as_str(), player_name.as_str(),
MPRIS_PATH, MPRIS_PATH,
MPRIS_PLAYER_INTERFACE, MPRIS_PLAYER_INTERFACE,
) )
.await .await
&& let Err(e) = proxy.call_method("Pause", &()).await
{ {
if let Err(e) = proxy.call_method("Pause", &()).await {
warn!(&LOGGER, "Error pausing player: {player_name}, {e}"); warn!(&LOGGER, "Error pausing player: {player_name}, {e}");
}
}
self.select_active_player(self.active_player.clone()); self.select_active_player(self.active_player.clone());
} }
} }
async fn active_player_stop(&mut self, connection: &zbus::Connection) { async fn active_player_stop(&mut self, connection: &zbus::Connection) {
if let Some(player_name) = &self.active_player { if let Some(player_name) = &self.active_player
if let Ok(proxy) = zbus::Proxy::new( && let Ok(proxy) = zbus::Proxy::new(
&connection, connection,
player_name.as_str(), player_name.as_str(),
MPRIS_PATH, MPRIS_PATH,
MPRIS_PLAYER_INTERFACE, MPRIS_PLAYER_INTERFACE,
) )
.await .await
&& let Err(e) = proxy.call_method("Stop", &()).await
{ {
if let Err(e) = proxy.call_method("Stop", &()).await {
warn!(&LOGGER, "Error stopping player: {player_name}, {e}"); warn!(&LOGGER, "Error stopping player: {player_name}, {e}");
} }
}
}
self.select_active_player(None); self.select_active_player(None);
} }

View File

@@ -6,6 +6,7 @@ use jmb_logger_rs::*;
use std::io::Read; use std::io::Read;
use std::net::Shutdown; use std::net::Shutdown;
use std::os::unix::net::UnixListener; use std::os::unix::net::UnixListener;
use std::str::FromStr;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
pub struct ControlSocket { pub struct ControlSocket {
@@ -34,12 +35,12 @@ impl SimpleBackendThread<ControlCommand> for ControlSocket {
} }
}); });
std::thread::spawn(move || { std::thread::spawn(move || {
if std::fs::metadata(SOCKET_PATH).is_ok() { if std::fs::metadata(SOCKET_PATH).is_ok()
if let Err(e) = std::fs::remove_file(SOCKET_PATH) { && let Err(e) = std::fs::remove_file(SOCKET_PATH)
{
error!(&LOGGER, "Error deleting old socket file: {e}"); error!(&LOGGER, "Error deleting old socket file: {e}");
return; return;
} }
}
let socket = UnixListener::bind(SOCKET_PATH); let socket = UnixListener::bind(SOCKET_PATH);
let Ok(socket) = socket else { let Ok(socket) = socket else {
error!(&LOGGER, "Error creating socket {}", socket.err().unwrap()); error!(&LOGGER, "Error creating socket {}", socket.err().unwrap());
@@ -58,7 +59,7 @@ impl SimpleBackendThread<ControlCommand> for ControlSocket {
let _ = stream.shutdown(Shutdown::Both); let _ = stream.shutdown(Shutdown::Both);
continue; continue;
} }
if let Some(command) = ControlCommand::from_str(&read) { if let Ok(command) = ControlCommand::from_str(&read) {
instance.lock().unwrap().publish(command); instance.lock().unwrap().publish(command);
} }
} }

View File

@@ -97,11 +97,13 @@ impl I915Engine {
let pmu_type = read_number(&format!("{base}/type"))? as u32; let pmu_type = read_number(&format!("{base}/type"))? as u32;
let config = read_config(&format!("{base}/events/{name}"))?; let config = read_config(&format!("{base}/events/{name}"))?;
let mut attr = PerfEventAttr::default(); let attr = PerfEventAttr {
attr.type_ = pmu_type; type_: pmu_type,
attr.size = size_of::<PerfEventAttr>() as u32; size: size_of::<PerfEventAttr>() as u32,
attr.config = config; config,
attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING; read_format: PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING,
..Default::default()
};
// pid = -1 and cpu = -1: system-wide event, if permitted. // pid = -1 and cpu = -1: system-wide event, if permitted.
let fd = unsafe { let fd = unsafe {
@@ -181,7 +183,7 @@ impl I915UtilizationMonitor {
for (engine, sample) in &mut self.engines { for (engine, sample) in &mut self.engines {
let new_sample = engine.read().unwrap(); let new_sample = engine.read().unwrap();
if let Some(last) = sample { if let Some(last) = sample {
values.push(new_sample.calculate_utilization(&last) as u8); values.push(new_sample.calculate_utilization(last) as u8);
} }
let _ = sample.insert(new_sample); let _ = sample.insert(new_sample);
} }

View File

@@ -204,7 +204,7 @@ impl HyprlandComms {
.output() .output()
} }
pub fn cursor_monitor() -> Option<MonitorId> { pub fn _cursor_monitor() -> Option<MonitorId> {
if let Ok(pos) = CursorPosition::get() if let Ok(pos) = CursorPosition::get()
&& let Ok(monitors) = Monitors::get() && let Ok(monitors) = Monitors::get()
{ {

View File

@@ -1,4 +1,5 @@
use serde::Deserialize; use serde::Deserialize;
use std::default::Default;
use std::fs; use std::fs;
#[derive(Deserialize, Debug, Clone, Default)] #[derive(Deserialize, Debug, Clone, Default)]
@@ -10,8 +11,7 @@ impl Config {
pub fn load() -> Config { pub fn load() -> Config {
fs::read_to_string("jmb-bar.conf") fs::read_to_string("jmb-bar.conf")
.ok() .ok()
.map(|s| toml::from_str::<Config>(&s).ok()) .and_then(|s| toml::from_str::<Config>(&s).ok())
.flatten()
.unwrap_or_default() .unwrap_or_default()
} }
} }
@@ -33,7 +33,8 @@ impl Default for IdleConfig {
dim_timeout: 60, dim_timeout: 60,
lock_timeout: 300, lock_timeout: 300,
sleep_timeout: 320, sleep_timeout: 320,
..Default::default() lock_command: String::default(),
sleep_command: String::default(),
} }
} }
} }

View File

@@ -1,7 +1,9 @@
use jmb_logger_rs::*; use jmb_logger_rs::*;
use std::env; use std::env;
use std::fmt::{Display, Formatter};
use std::io::Write; use std::io::Write;
use std::os::unix::net::UnixStream; use std::os::unix::net::UnixStream;
use std::str::FromStr;
const CTL_LOGGER: Logger = Logger::create_with_custom_format(Level::DEBUG, String::new()); const CTL_LOGGER: Logger = Logger::create_with_custom_format(Level::DEBUG, String::new());
pub const SOCKET_PATH: &str = "/run/user/1000/jmb-bar.sock"; pub const SOCKET_PATH: &str = "/run/user/1000/jmb-bar.sock";
@@ -11,17 +13,21 @@ pub enum ControlCommand {
OpenRunMenu, OpenRunMenu,
} }
impl ControlCommand { impl Display for ControlCommand {
pub fn from_str(s: &str) -> Option<Self> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match s {
"menu" => Some(ControlCommand::OpenRunMenu),
_ => None,
}
}
pub fn to_string(self) -> String {
match self { match self {
ControlCommand::OpenRunMenu => String::from("menu"), ControlCommand::OpenRunMenu => f.write_str("menu"),
}
}
}
impl FromStr for ControlCommand {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"menu" => Ok(ControlCommand::OpenRunMenu),
other => Err(format!("Unknown command: {other}")),
} }
} }
} }
@@ -43,7 +49,7 @@ fn main() {
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
match args.get(1) { match args.get(1) {
Some(str) if let Some(cmd) = ControlCommand::from_str(str) => stream Some(str) if let Ok(cmd) = ControlCommand::from_str(str) => stream
.write(cmd.to_string().as_bytes()) .write(cmd.to_string().as_bytes())
.expect("Error sending message"), .expect("Error sending message"),
_ => 0usize, _ => 0usize,

View File

@@ -75,8 +75,6 @@ impl RunMenu {
window.set_monitor(monitor.as_ref()); window.set_monitor(monitor.as_ref());
if let Some(monitor) = monitor { if let Some(monitor) = monitor {
let geometry = monitor.geometry(); let geometry = monitor.geometry();
let (_, natural_height, _, _) =
window.child().unwrap().measure(Orientation::Vertical, -1);
let top_margin = (geometry.height()) / 2; let top_margin = (geometry.height()) / 2;
window.set_margin(Edge::Top, top_margin - 100); window.set_margin(Edge::Top, top_margin - 100);
} else { } else {
@@ -100,14 +98,12 @@ impl RunMenu {
} }
if e.text_length() > 0 { if e.text_length() > 0 {
let text = e.text(); let text = e.text();
if text.starts_with("=") { if let Some(eval) = text.strip_prefix("=") {
if let Ok(eval) = meval::eval_str(&text[1..]) { let label = gtk::Label::new(Some(eval));
let label = gtk::Label::new(Some(&format!("{eval}")));
label.add_css_class("exec-button"); label.add_css_class("exec-button");
label.set_halign(Align::Start); label.set_halign(Align::Start);
label.set_hexpand(true); label.set_hexpand(true);
content_box.append(&label); content_box.append(&label);
}
} else { } else {
instance_clone.list_matching(e, &content_box, &mut matcher_rc.borrow_mut()); instance_clone.list_matching(e, &content_box, &mut matcher_rc.borrow_mut());
instance_clone.window.set_default_size(500, -1); instance_clone.window.set_default_size(500, -1);
@@ -164,8 +160,8 @@ impl RunMenu {
self.window.present(); self.window.present();
} }
fn create_entry(&self, content_box: &gtk::Box, entry: &String) -> gtk::Button { fn create_entry(&self, content_box: &gtk::Box, entry: &str) -> gtk::Button {
let entry_clone = entry.clone(); let entry_clone = entry.to_owned();
let button = gtk::Button::new(); let button = gtk::Button::new();
button.set_halign(Align::Fill); button.set_halign(Align::Fill);
button.set_hexpand(true); button.set_hexpand(true);
@@ -198,14 +194,14 @@ impl RunMenu {
content_box: &gtk::Box, content_box: &gtk::Box,
matcher: &mut Matcher, matcher: &mut Matcher,
) -> bool { ) -> bool {
let keys: Vec<String> = self.entries.borrow().keys().map(|i| i.clone()).collect(); let keys: Vec<String> = self.entries.borrow().keys().cloned().collect();
let mut first = true; let mut first = true;
let mut added = false; let mut added = false;
for (entry, _) in Pattern::parse(&entry.text(), CaseMatching::Ignore, Normalization::Smart) for (entry, _) in Pattern::parse(&entry.text(), CaseMatching::Ignore, Normalization::Smart)
.match_list(keys, matcher) .match_list(keys, matcher)
.iter() .iter()
{ {
let button = self.create_entry(content_box, &entry); let button = self.create_entry(content_box, entry);
if first { if first {
button.add_css_class("suggested"); button.add_css_class("suggested");
first = false; first = false;