]> git.draconx.ca Git - mpdhacks.git/blob - mpdmenu.pl
mpdthumb: Add --help and --version options.
[mpdhacks.git] / mpdmenu.pl
1 #!/usr/bin/perl
2 #
3 # Copyright © 2008,2010,2012,2020 Nick Bowler
4 #
5 # Silly little script to generate an FVWM menu with various bits of MPD
6 # status information and controls.
7 #
8 # License GPLv3+: GNU General Public License version 3 or any later version.
9 # This is free software: you are free to change and redistribute it.
10 # There is NO WARRANTY, to the extent permitted by law.
11
12 use strict;
13
14 use utf8;
15
16 use Encode qw(decode encode);
17 use Encode::Locale qw(decode_argv);
18 decode_argv(Encode::FB_CROAK);
19 binmode(STDOUT, ":utf8");
20
21 use Getopt::Long qw(:config gnu_getopt);
22 use Scalar::Util qw(reftype);
23 use List::Util qw(any max);
24 use FindBin;
25
26 use lib "$FindBin::Bin";
27 use MPDHacks;
28
29 use constant {
30         MPD_MJR_MIN => 0,
31         MPD_MNR_MIN => 21,
32         MPD_REV_MIN => 0,
33 };
34
35 my $SELF = "$FindBin::Bin/$FindBin::Script";
36
37 my $MUSIC = $ENV{MUSIC}    // "/srv/music";
38 my $sock;
39
40 my ($albumid, $trackid);
41 my ($topmenu, $menu);
42 my $mode = "top";
43 my %artistids;
44
45 sub fvwm_cmd_unquoted {
46         print join(' ', @_), "\n";
47 }
48
49 sub fvwm_cmd {
50         fvwm_cmd_unquoted(map { MPD::escape } @_);
51 }
52
53 # Quotes the argument in such a way that it is passed unadulterated by
54 # both FVWM and the shell to a command as a single argument (for use as
55 # an # argument for e.g., the Exec or PipeRead FVWM commands).
56 #
57 # The result must be used with fvwm_cmd_unquoted;
58 sub fvwm_shell_literal {
59         my $s = @_[0] // $_;
60
61         $s =~ s/\$/\$\$/g;
62         if ($s =~ /[' \t]/) {
63                 $s =~ s/'/'\\''/g;
64                 return "'$s'";
65         }
66         $s =~ s/^\s*$/'$&'/;
67         return "$s";
68 }
69
70 # Escapes metacharacters in the argument used in FVWM menu labels.  The
71 # string must still be quoted (e.g., by using fvwm_cmd).
72 sub fvwm_label_escape {
73         my @tokens = split /\t/, $_[0];
74         @tokens[0] =~ s/&/&&/g;
75         my $ret = join "\t", @tokens;
76         $ret =~ s/[\$@%^*]/$&$&/g;
77         return $ret;
78 }
79
80 # make_submenu(name, [args ...])
81 #
82 # Creates a submenu (with the specified name) constructed by invoking this
83 # script with the given arguments.  Returns a list that can be passed to
84 # fvwm_cmd to display the menu.
85 sub make_submenu {
86         my $name = shift;
87         $name =~ s/-/_/g;
88         unshift @_, ("exec", $SELF, "--topmenu=$topmenu", "--menu=$name");
89
90         fvwm_cmd("DestroyFunc", "Make$name");
91         fvwm_cmd("AddToFunc", "Make$name");
92         fvwm_cmd("+", "I", "DestroyMenu", $name);
93
94         fvwm_cmd("DestroyMenu", $name);
95         fvwm_cmd("AddToMenu", $name, "DynamicPopupAction", "Make$name");
96         fvwm_cmd("AddToFunc", "Kill$topmenu", "I", "DestroyMenu", $name);
97
98         fvwm_cmd("DestroyFunc", "Make$name");
99         fvwm_cmd("AddToFunc", "Make$name");
100         fvwm_cmd("+", "I", "DestroyMenu", $name);
101         fvwm_cmd("+", "I", "-PipeRead",
102                  join(' ', map { fvwm_shell_literal } @_));
103         fvwm_cmd("AddToFunc", "Kill$topmenu", "I", "DestroyFunc", "Make$name");
104
105         return ("Popup", $name);
106 }
107
108 # get_item_thumbnails({ options }, file, ...)
109 # get_item_thumbnails(file, ...)
110 #
111 # For each music file listed, obtain a thumbnail (if any) for the cover art.
112 #
113 # The first argument is a hash reference to control the mode of operation;
114 # it may be omitted for default options.
115 #
116 #   get_item_thumbnails({ small => 1 }, ...) - smaller thumbnails
117 #
118 # The returned list consists of strings (in the same order as the filename
119 # arguments) suitable for use directly in FVWM menus; by default the filename
120 # is bracketed by asterisks (e.g., "*thumbnail.png*"); in small mode it is
121 # surrounded by % (e.g., "%thumbnail.png%").  If no cover art was found, the
122 # empty string is returned for that file.
123 sub get_item_thumbnails {
124         my @results = ();
125         my $flags = {};
126         my @opts = ();
127
128         $flags = shift if (reftype($_[0]) eq "HASH");
129         return @results unless @_;
130
131         my $c = "*";
132         if ($flags->{small}) {
133                 push @opts, "--small";
134                 $c = "%";
135         }
136
137         open THUMB, "-|", "$FindBin::Bin/mpdthumb.sh", @opts, "--", @_;
138         foreach (@_) {
139                 my $thumb = <THUMB>;
140                 chomp $thumb;
141
142                 $thumb = "$c$thumb$c" if (-f $thumb);
143                 push @results, $thumb;
144         }
145         close THUMB;
146         die("mpdthumb failed") if ($?);
147
148         return @results;
149 }
150
151 # add_track_metadata(hashref, key, value)
152 #
153 # Inserts the given key into the referenced hash; if the key already exists
154 # in the hash then the hash element is converted to an array reference (if
155 # it isn't already) and the value is appended to that array.
156 sub add_track_metadata {
157         my ($entry, $key, $value) = @_;
158
159         if (exists($entry->{$key})) {
160                 my $ref = $entry->{$key};
161
162                 if (reftype($ref) ne "ARRAY") {
163                         return if ($ref eq $value);
164
165                         $ref = [$ref];
166                         $entry->{$key} = $ref;
167                 }
168
169                 push(@$ref, $value) unless (any {$_ eq $value} @$ref);
170         } else {
171                 $entry->{$key} = $value;
172         }
173 }
174
175 # get_track_metadata(hashref, key)
176 #
177 # Return the values associated with the given metadata key as a list.
178 sub get_track_metadata {
179         my ($entry, $key) = @_;
180
181         return () unless (exists($entry->{$key}));
182
183         my $ref = $entry->{$key};
184         return @$ref if (reftype($ref) eq "ARRAY");
185         return $ref
186 }
187
188 # Given a music filename, search for the cover art in the same directory.
189 sub mpd_cover_filename {
190         my ($dir) = @_;
191         my $file;
192
193         $dir =~ s/\/[^\/]*$//;
194         foreach ("cover.png", "cover.jpg", "cover.tiff", "cover.bmp") {
195                 if (-f "$dir/$_") {
196                         $file = "$dir/$_";
197                         last;
198                 }
199         }
200         return unless defined $file;
201
202         # Follow one level of symbolic link to get to the scans directory.
203         $file = readlink($file) // $file;
204         $file = "$dir/$file" unless ($file =~ /^\//);
205         return $file;
206 }
207
208 # Generate the cover art entry in the top menu.
209 sub top_track_cover {
210         my ($entry) = @_;
211
212         ($entry->{thumb}) = get_item_thumbnails($entry->{file});
213         print "$entry->{thumb}\n";
214         if ($entry->{thumb}) {
215                 my $file = "$MUSIC/$entry->{file}";
216                 my $cover = mpd_cover_filename($file);
217
218                 $cover = fvwm_shell_literal($cover // $file);
219                 fvwm_cmd_unquoted("AddToMenu", MPD::escape($menu),
220                                   MPD::escape($entry->{thumb}),
221                                   "Exec", "exec", "geeqie", $cover);
222         }
223 }
224
225 # Generate the "Title:" entry in the top menu.
226 sub top_track_title {
227         my ($entry) = @_;
228         my @submenu;
229
230         my ($mbid) = get_track_metadata($entry, "MUSICBRAINZ_RELEASETRACKID");
231         @submenu = make_submenu("$menu-$mbid", "--track-id=$mbid") if $mbid;
232
233         fvwm_cmd("AddToMenu", $menu,
234                  fvwm_label_escape("Title:\t$entry->{Title}"),
235                  @submenu);
236 }
237
238 # Generate the "Artist:" entry in the top menu.
239 sub top_track_artist {
240         my ($entry) = @_;
241         my @submenu;
242
243         # TODO: multi-artist tracks should get multiple artist menus; for now
244         # just combine the releases from all artists.
245         my @mbids = get_track_metadata($entry, "MUSICBRAINZ_ARTISTID");
246         if (@mbids) {
247                 @submenu = make_submenu("$menu-TopArtist",
248                                         map { "--artist-id=$_" } @mbids);
249         }
250
251         fvwm_cmd("AddToMenu", $menu,
252                  fvwm_label_escape("Artist:\t$entry->{Artist}"),
253                  @submenu);
254 }
255
256 # Generate the "Album:" entry in the top menu.
257 sub top_track_album {
258         my ($entry) = @_;
259         my @submenu;
260
261         my ($mbid) = get_track_metadata($entry, "MUSICBRAINZ_ALBUMID");
262         @submenu = make_submenu("$menu-$mbid", "--album-id=$mbid") if $mbid;
263
264         fvwm_cmd("AddToMenu", $menu,
265                  fvwm_label_escape("Album:\t$entry->{Album}"),
266                  @submenu);
267 }
268
269 # Given a work MBID, return a hash reference containing all tracks
270 # linked to that work.  The hash keys are filenames.
271 sub get_tracks_by_work_mbid {
272         my %matches;
273         my $entry;
274
275         foreach my $mbid (@_) {
276                 MPD::exec("search", "(MUSICBRAINZ_WORKID == \"$mbid\")");
277                 while (<$sock>) {
278                         last if (/^OK/);
279                         die($_) if (/^ACK/);
280
281                         if (/^(\w+): (.*)$/) {
282                                 if ($1 eq "file") {
283                                         if (exists($matches{$2})) {
284                                                 $entry = $matches{$2};
285                                         } else {
286                                                 $entry = {};
287                                                 $matches{$2} = $entry;
288                                         }
289                                 }
290
291                                 add_track_metadata($entry, $1, $2);
292                         }
293                 }
294         }
295
296         return \%matches;
297 }
298
299 # Given a track MBID, return a hash reference containing all "related"
300 # tracks in the MPD database.  The hash keys are filenames.
301 #
302 # Currently tracks are considered "related" if their associated recordings
303 # have at least one work in common.
304 sub get_tracks_by_track_mbid {
305         my ($mbid, $tagname) = (@_, "MUSICBRAINZ_RELEASETRACKID");
306         my %source;
307         my %matches;
308         my $entry;
309
310         return \%matches unless ($mbid);
311         MPD::exec("search", "(MUSICBRAINZ_RELEASETRACKID == \"$mbid\")");
312         while (<$sock>) {
313                 last if (/^OK/);
314                 die($_) if (/^ACK/);
315
316                 if (/^(\w+): (.*)$/) {
317                         add_track_metadata(\%source, $1, $2);
318                 }
319         }
320
321         # Always include the current track
322         $matches{$source{file}} = \%source;
323
324         # Find all tracks related by work
325         foreach my $mbid (get_track_metadata(\%source, "MUSICBRAINZ_WORKID")) {
326                 my $related = get_tracks_by_work_mbid($mbid);
327                 foreach (keys %$related) {
328                         $matches{$_} //= $related->{$_};
329                 }
330         }
331
332         return \%matches;
333 }
334
335 # Given a release MBID, return a hash reference containing all its
336 # associated tracks in the MPD database.  The hash keys are filenames.
337 sub get_tracks_by_release_mbid {
338         my ($mbid) = @_;
339         my %matches;
340         my $entry;
341
342         return \%matches unless ($mbid);
343         MPD::exec("search", "(MUSICBRAINZ_ALBUMID == \"$mbid\")");
344         while (<$sock>) {
345                 last if (/^OK/);
346                 die($_) if (/^ACK/);
347
348                 if (/^(\w+): (.*)$/) {
349                         if ($1 eq "file") {
350                                 if (exists($matches{$2})) {
351                                         $entry = $matches{$2};
352                                 } else {
353                                         $entry = {};
354                                         $matches{$2} = $entry;
355                                 }
356                         }
357
358                         add_track_metadata($entry, $1, $2);
359                 }
360         }
361
362         return \%matches;
363 }
364
365 # Given an artist MBID, return a hash reference containing associated
366 # releases in the MPD database.  The hash keys are release MBIDs.
367 #
368 # Since MPD returns results on a per-track basis, each entry in the
369 # hash has the metadata for one unspecified track from that release.
370 sub get_releases_by_artist_mbid {
371         my %releases;
372         my $entry;
373
374         foreach my $mbid (@_) {
375                 MPD::exec("search", "(MUSICBRAINZ_ARTISTID == \"$mbid\")");
376                 while (<$sock>) {
377                         last if (/^OK/);
378                         die($_) if (/^ACK/);
379
380                         if (/^(\w+): (.*)$/) {
381                                 if ($1 eq "file") {
382                                         $entry = {};
383                                 } elsif ($1 eq "MUSICBRAINZ_ALBUMID") {
384                                         $releases{$2} //= $entry;
385                                 }
386
387                                 add_track_metadata($entry, $1, $2);
388                         }
389                 }
390         }
391
392         return \%releases;
393 }
394
395 # Given a filename, return the IDs (if any) for that file in the
396 # current MPD play queue.
397 sub get_ids_by_filename {
398         my ($file) = @_;
399         my @results = ();
400
401         MPD::exec("playlistfind", "file", $file);
402         while (<$sock>) {
403                 last if (/^OK/);
404                 die($_) if (/^ACK/);
405
406                 if (/^(\w+): (.*)$/) {
407                         push @results, $2 if ($1 eq "Id");
408                 }
409         }
410
411         return @results;
412 }
413
414 # albumsort(matches, a, b)
415 #
416 # Sort hash keys (a, b) by disc/track number for album menus.
417 sub albumsort {
418         my ($matches, $a, $b) = @_;
419
420         return $matches->{$a}->{Disc} <=> $matches->{$b}->{Disc}
421             || $matches->{$a}->{Track} <=> $matches->{$b}->{Track}
422             || $a cmp $b;
423 }
424
425 # datesort(matches, a, b)
426 #
427 # Sort hash keys (a, b) by release date
428 sub datesort {
429         my ($matches, $a, $b) = @_;
430
431         return $matches->{$a}->{Date} cmp $matches->{$b}->{Date}
432             || $a cmp $b;
433 }
434
435 # menu_trackname(entry)
436 #
437 # Format the track name for display in an FVWM menu, where entry
438 # is a hash reference containing the track metadata.
439 sub menu_trackname {
440         my ($entry) = @_;
441         my $fmt = "$entry->{trackfmt}$entry->{Artist} - $entry->{Title}";
442         return "$entry->{thumb}" . fvwm_label_escape($fmt);
443 }
444
445 sub print_version {
446         print <<EOF
447 mpdmenu.pl 0.8
448 Copyright © 2019 Nick Bowler
449 License GPLv3+: GNU General Public License version 3 or any later version.
450 This is free software: you are free to change and redistribute it.
451 There is NO WARRANTY, to the extent permitted by law.
452 EOF
453 }
454
455 sub print_usage {
456         my ($fh) = (@_, *STDERR);
457
458         print $fh "Usage: $0 [options]\n";
459         print $fh "Try $0 --help for more information.\n" unless (@_ > 0);
460 }
461
462 sub print_help {
463         print_usage(*STDOUT);
464         print <<EOF
465 This is "mpdmenu": a menu-based MPD client for FVWM.
466
467 Options:
468   -h, --host=HOST   Connect to the MPD server on HOST, overriding defaults.
469   -p, --port=PORT   Connect to the MPD server on PORT, overriding defaults.
470   -m, --menu=NAME   Set the name of the generated menu.
471   --album-id=MBID   Generate a menu for the given release MBID.
472   --artist-id=MBID  Generate a menu for the given artist MBID.
473   --track-id=MBID   Generate a menu for the given track MBID.
474   -V, --version     Print a version message and then exit.
475   -H, --help        Print this message and then exit.
476 EOF
477 }
478
479 GetOptions(
480         'host|h=s'    => \$MPD::host,
481         'port|p=s'    => \$MPD::port,
482         'menu|m=s'    => \$menu,
483
484         'artist-id=s' => sub { $artistids{$_[1]} = 1; $mode = "artist"; },
485         'album-id=s'  => sub { $albumid = $_[1]; $mode = "album"; },
486         'track-id=s'  => sub { $trackid = $_[1]; $mode = "track"; },
487
488         'V|version'   => sub { print_version(); exit },
489         'H|help'      => sub { print_help(); exit },
490
491         'topmenu=s'   => \$topmenu, # top menu name (for submenu generation)
492 ) or do { print_usage; exit 1 };
493
494 unless (defined $menu) {
495         $topmenu //= "MenuMPD";
496         $menu = $topmenu . ($mode ne "top" ? $mode : "");
497 }
498 $topmenu //= $menu;
499
500 # Connect to MPD.
501 $sock = MPD::connect();
502 die("MPD version $MPD::major.$MPD::minor.$MPD::revision insufficient.")
503         unless MPD::min_version(MPD_MJR_MIN, MPD_MNR_MIN, MPD_REV_MIN);
504
505 if ($mode eq "top") {
506         my %current;
507         my %state;
508
509         $menu //= "MenuMPD";
510
511         MPD::exec("status");
512         while (<$sock>) {
513                 last if (/^OK/);
514                 die($_) if (/^ACK/);
515
516                 if (/^(\w+): (.*)$/) {
517                         $state{$1} = $2;
518                 }
519         }
520
521         MPD::exec("currentsong");
522         while (<$sock>) {
523                 last if (/^OK/);
524                 die($_) if (/^ACK/);
525
526                 if (/^(\w+): (.*)$/) {
527                         add_track_metadata(\%current, $1, $2);
528                 }
529         }
530
531         my $playstate = $state{state} eq "play"  ? "Playing"
532                       : $state{state} eq "stop"  ? "Stopped"
533                       : $state{state} eq "pause" ? "Paused"
534                       : "Unknown";
535         fvwm_cmd("AddToMenu", $menu, $playstate, "Title");
536
537         if (exists($current{file})) {
538                 top_track_cover(\%current);
539                 top_track_title(\%current);
540                 top_track_artist(\%current);
541                 top_track_album(\%current);
542         } else {
543                 fvwm_cmd("AddToMenu", $menu, "[current track unavailable]");
544         }
545
546         if ($state{state} =~ /^p/) {
547                 my $pp = $state{state} eq "pause" ? "lay" : "ause";
548
549                 fvwm_cmd("AddToMenu", $menu, "", "Nop");
550                 fvwm_cmd("AddToMenu", $menu, "Next%next.svg:16x16%",
551                        "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "next");
552                 fvwm_cmd("AddToMenu", $menu, "P$pp%p$pp.svg:16x16%",
553                        "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "p$pp");
554                 fvwm_cmd("AddToMenu", $menu, "Stop%stop.svg:16x16%",
555                        "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "stop");
556                 fvwm_cmd("AddToMenu", $menu, "Prev%prev.svg:16x16%",
557                        "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "previous");
558         } elsif ($state{state} eq "stop") {
559                 fvwm_cmd("AddToMenu", $menu, "", "Nop");
560                 fvwm_cmd("AddToMenu", $menu, "Play%play.svg:16x16%",
561                        "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "play");
562         }
563 } elsif ($mode eq "album") {
564         my $matches = get_tracks_by_release_mbid($albumid);
565         my @notqueued = ();
566
567         $menu //= "MenuMPDAlbum";
568
569         my $track_max = max(map { $_->{Track} } values %$matches);
570         my $disc_max = max(map { $_->{Disc} } values %$matches);
571
572         # CDs have a max of 99 tracks and I hope 100+-disc-releases
573         # don't exist so this is fine.
574         my $track_digits = $track_max >= 10 ? 2 : 1;
575         my $disc_digits = $disc_max > 1 ? $disc_max >= 10 ? 2 : 1 : 0;
576         my $currentdisc;
577
578         fvwm_cmd("AddToMenu", $menu);
579         fvwm_cmd("+", "Release not found", "Title") unless keys %$matches;
580         foreach my $file (sort { albumsort($matches, $a, $b) } keys %$matches) {
581                 my $entry = $matches->{$file};
582
583                 # Format disc/track numbers
584                 $entry->{trackfmt} = sprintf("%*.*s%.*s%*d\t",
585                                   $disc_digits, $disc_digits, $entry->{Disc},
586                                   $disc_digits, "-",
587                                   $track_digits, $entry->{Track});
588                 $entry->{trackfmt} =~ s/ /\N{U+2007}/g;
589
590                 unless (exists $entry->{Id}) {
591                         my ($id) = get_ids_by_filename($file);
592                         if (defined $id) {
593                                 $entry->{Id} = $id;
594                         } else {
595                                 push @notqueued, $entry;
596                                 next;
597                         }
598                 }
599
600                 if (defined $currentdisc && $currentdisc != $entry->{Disc}) {
601                         fvwm_cmd("+", "", "Nop");
602                 }
603                 $currentdisc = $entry->{Disc};
604
605                 fvwm_cmd("+", menu_trackname($entry), "Exec",
606                          "exec", "$FindBin::Bin/mpdexec.pl",
607                          "playid", $entry->{Id});
608         }
609
610         fvwm_cmd("+", "Not in play queue", "Title") if @notqueued;
611         foreach my $entry (@notqueued) {
612                 fvwm_cmd("+", menu_trackname($entry));
613         }
614 } elsif ($mode eq "artist") {
615         # Create an artist menu.
616         my $matches = get_releases_by_artist_mbid(keys %artistids);
617         my $entry;
618
619         $menu //= "MenuMPDArtist";
620
621         my @mbids = sort { datesort($matches, $a, $b) } keys %$matches;
622         my @files = map { $matches->{$_}->{file} } @mbids;
623         my @thumbs = get_item_thumbnails({ small => 1 }, @files);
624         fvwm_cmd("AddToMenu", $menu, "No releases found", "Title") unless @mbids;
625
626         foreach my $mbid (@mbids) {
627                 my $entry = $matches->{$mbid};
628                 my $thumb = shift @thumbs;
629
630                 my @submenu = make_submenu("$topmenu-$mbid",
631                                            "--album-id=$mbid");
632                 fvwm_cmd("AddToMenu", $menu,
633                          $thumb . fvwm_label_escape($entry->{Album}),
634                          @submenu);
635         }
636 } elsif ($mode eq "track") {
637         my $matches = get_tracks_by_track_mbid($trackid);
638         my @notqueued;
639
640         $menu //= "MenuMPDTrack";
641
642         my @files = sort { datesort($matches, $a, $b) } keys %$matches;
643         my @thumbs = get_item_thumbnails({ small => 1 }, @files);
644
645         fvwm_cmd("AddToMenu", $menu);
646         fvwm_cmd("+", "No tracks found", "Title") unless @files;
647         foreach my $file (@files) {
648                 my $entry = $matches->{$file};
649                 $entry->{thumb} = shift @thumbs;
650
651                 unless (exists $entry->{Id}) {
652                         my ($id) = get_ids_by_filename($file);
653                         if (defined $id) {
654                                 $entry->{Id} = $id;
655                         } else {
656                                 push @notqueued, $entry;
657                                 next;
658                         }
659                 }
660
661                 fvwm_cmd("+", menu_trackname($entry), "Exec",
662                          "exec", "$FindBin::Bin/mpdexec.pl",
663                          "playid", $entry->{Id});
664         }
665
666         fvwm_cmd("+", "Not in play queue", "Title") if @notqueued;
667         foreach my $entry (@notqueued) {
668                 fvwm_cmd("+", menu_trackname($entry));
669         }
670 }
671
672 # Finished.
673 print $sock "close\n";