unibar/src/bar_modules/bar_module_music.rs
Mahesh Asolkar 7245914da8
Added mechanism to skip updates in a module
* This is useful in modules where HTTP API calls are made. Updating them
  every second is expensive, network intensive and can cause rate limits
  to be hit
* Added get_name() function to modules for easier debug statements
2025-06-14 17:33:24 -07:00

104 lines
3.2 KiB
Rust

use std::process::{Stdio, Command};
use crate::common;
use crate::bar_modules;
#[derive(Clone)]
pub struct UnibarModuleMusic {
opts: common::AppOptions,
current_stdout: String,
progress_stdout: String,
state_stdout: String,
}
impl UnibarModuleMusic {
// --------------------
pub fn new(o :common::AppOptions) -> Self {
UnibarModuleMusic {
opts: o,
current_stdout: "".to_string(),
progress_stdout: "".to_string(),
state_stdout: "stopped".to_string(),
}
}
}
impl bar_modules::BarModuleActions for UnibarModuleMusic {
// --------------------
fn get_name(&self) -> String {
return "UnibarModuleMusic".to_string();
}
// --------------------
fn clear(&mut self) {
self.current_stdout = "".to_string();
self.progress_stdout = "".to_string();
self.state_stdout = "stopped".to_string();
}
// --------------------
fn generate_data(&mut self) {
// MPD format options here:
// https://manpages.ubuntu.com/manpages/plucky/man1/mpc.1.html
let current_output = Command::new("mpc")
.arg("--format")
.arg("[%artist% - ][%title%]")
.arg("current")
.stdout(Stdio::piped())
.output()
.unwrap();
self.current_stdout = String::from_utf8(current_output.stdout).unwrap();
self.current_stdout.pop();
if self.opts.music_progress {
let progress_output = Command::new("mpc")
.arg("status")
.arg("%percenttime% %totaltime%")
.stdout(Stdio::piped())
.output()
.unwrap();
self.progress_stdout = String::from_utf8(progress_output.stdout).unwrap();
self.progress_stdout.pop();
}
let icon_output = Command::new("mpc")
.arg("status")
.arg("%state%")
.stdout(Stdio::piped())
.output()
.unwrap();
self.state_stdout = String::from_utf8(icon_output.stdout).unwrap();
self.state_stdout.pop();
}
// --------------------
fn get_content(&self) -> String {
let mut parts = Vec::new();
parts.push(format!("{}", self.current_stdout));
if self.opts.music_progress {
parts.push(format!("[{}]", self.progress_stdout.trim()));
}
return format!("{}", parts.join(" "));
}
// --------------------
fn get_icon(&self) -> String {
// MPD state can be 'playing', 'paused' or 'stopped'
match self.state_stdout.as_str() {
"paused" => return "".to_string(),
"stopped" => return "".to_string(),
_ => return "𝄞".to_string(),
}
}
}
impl bar_modules::BarModuleDebug for UnibarModuleMusic {
// --------------------
fn post_debug(&self) {
}
}