Add some protection to failing to connect to MPD.
[picture-display.git] / lib / Display / Plugins / MPD.pm
1 package Display::Plugins::MPD;
2
3 use Clutter;
4 use Carp qw(cluck);
5 use Audio::MPD;
6 use POSIX qw/strftime/;
7 use POE::Session;
8 use base ('Display::Plugins');
9 use FindBin qw/$Bin/;
10 use strict;
11
12 my $delay = 5;
13
14 sub new {
15   my $proto = shift;
16   my $class = ref($proto) || $proto;
17
18   my $self = $class->SUPER::new(@_);
19   bless ($self, $class);
20
21   eval {
22     $self->{'mpd'} = Audio::MPD->new();
23   };
24   if ($@) {
25     carp "Failed to connect to MPD: $@";
26   } else {
27     $self->init_delay($delay, 'mpd_display');
28     $self->init();
29   }
30
31   $self->{'file'} = '';
32   $self->{'active'} = 0;
33
34   return $self;
35 }
36
37 sub display {
38   my ($self, $kernel) = @_[OBJECT, KERNEL];
39
40   my $current = $self->{'mpd'}->current();
41
42   if (defined $current && $self->{'file'} ne $current->file()) {
43     my @lines = ();
44     push @lines, $current->title()  if defined $current->title();
45     push @lines, $current->album()  if defined $current->album();
46     push @lines, $current->artist() if defined $current->artist();
47
48     $self->{'status'}->set_text(join("\n", @lines));
49
50     $self->{'file'} = $current->file();
51
52     $kernel->yield('notifications_add', $self->{'status'}, $self->{'logo'});
53   }
54
55   $self->delay();
56 }
57
58 sub init {
59   my $self = shift;
60
61   $self->{'kernel'}->state('mpd_display', $self, 'display');
62
63   $self->{'status'} = Clutter::Label->new('Sans 20', "Song\nAlbum");
64   $self->{'status'}->set_color(Clutter::Color->parse('White'));
65   $self->{'status'}->set_ellipsize('end');
66
67   $self->{'logo'} = Clutter::Texture->new("$Bin/share/MPD.png");
68
69   $self->{'kernel'}->yield('mpd_display');
70 }
71
72 1;