use std::sync::{Arc, Mutex};
pub struct Beeper {
enabled: Arc<Mutex<bool>>,
}
impl Beeper {
pub fn new() -> Self {
Self {
enabled: Arc::new(Mutex::new(false)),
}
}
pub fn toggle(&self) {
if let Ok(mut enabled) = self.enabled.lock() {
*enabled = !*enabled;
}
}
pub fn is_enabled(&self) -> bool {
self.enabled.lock().map(|e| *e).unwrap_or(false)
}
pub fn beep(&self) {
if !self.is_enabled() {
return;
}
let enabled = Arc::clone(&self.enabled);
std::thread::spawn(move || {
if let Ok(true) = enabled.lock().map(|e| *e) {
play_beep();
}
});
}
}
fn play_beep() {
use std::io::Write;
print!("\x07");
let _ = std::io::stdout().flush();
}
impl Clone for Beeper {
fn clone(&self) -> Self {
Self {
enabled: Arc::clone(&self.enabled),
}
}
}