123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- use std::path::Path;
- use std::thread;
- use mpd;
- use mpd::idle;
- use mpd::idle::Idle;
- use mpd::song::Song;
- use mpd::status::State;
- use style;
- use ui::context::Context;
- use widgets::{Message, MessageSender, Update, Widget, WidgetParams};
- const WIDTH: u16 = 250;
- pub struct Mpd {
- context: Context,
- tx: MessageSender,
- state: State,
- song: Option<Song>
- }
- pub fn mpd(params: WidgetParams) -> Box<Widget> {
- let widget = Mpd {
- context: params.context,
- tx: params.tx,
- state: State::Stop,
- song: None
- };
- Box::new(widget)
- }
- impl Mpd {
- fn icon(&self) -> &'static str {
- match self.state {
- State::Play => "",
- State::Pause => "",
- State::Stop => ""
- }
- }
- fn get_text(&self) -> String {
- match self.song {
- Some(ref song) => match (&song.title, &song.tags.get("Artist")) {
- (&Some(ref title), &Some(ref artist)) => format!("{} - {}", artist, title),
- (&Some(ref title), &None) => title.to_string(),
- _ => {
- let path = Path::new(&song.file);
- let path = path.file_name().and_then(|s| s.to_str());
- path.unwrap_or("Unknown").to_string()
- }
- },
- None => "mpd".to_string()
- }
- }
- }
- impl Widget for Mpd {
- fn init(&mut self) {
- let tx = self.tx.clone();
- thread::spawn(move || monitor_thread(tx));
- }
- fn render(&mut self, x: u16, w: u16) {
- style::render(&self.context, self.icon(), &self.get_text(), x, w);
- }
- fn width(&mut self) -> u16 {
- WIDTH
- }
- fn handle_event(&mut self, event: &Message) -> Update {
- match event {
- &Message::MpdEvent(ref state, ref song) => {
- self.state = state.clone();
- self.song = song.clone();
- Update::Rerender
- },
- &Message::MousePress(_x) => {
- toggle();
- Update::Nothing
- },
- _ => Update::Nothing
- }
- }
- }
- fn monitor_thread(tx: MessageSender) {
- let mut conn = mpd::client::Client::connect("127.0.0.1:6600").unwrap();
- loop {
- match (conn.status(), conn.currentsong()) {
- (Ok(status), Ok(song)) => {
- let state = status.state;
- let event = Message::MpdEvent(state, song);
- tx.send(event).expect("Failed to send mpd event");
- },
- _ => {}
- }
- conn.wait(&[idle::Subsystem::Player]).ok();
- }
- }
- fn toggle() {
- let mut conn = mpd::client::Client::connect("127.0.0.1:6600").unwrap();
- conn.toggle_pause().expect("Failed to pause");
- }
|