]> git.draconx.ca Git - mpdhacks.git/blob - mpdmenu.pl
mpdmenu: Add MusicBrainz links for the current track.
[mpdhacks.git] / mpdmenu.pl
1 #!/usr/bin/perl
2 #
3 # Copyright © 2008,2010,2012,2020-2021 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, $albumname, $trackid, $recordingid);
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         if ($mbid) {
232                 @submenu = make_submenu("$menu-$mbid", "--track-id=$mbid")
233         } else {
234                 ($mbid) = get_track_metadata($entry, "MUSICBRAINZ_TRACKID");
235                 @submenu = make_submenu("$menu-track-$mbid", "--recording-id=$mbid")
236                         if ($mbid);
237         }
238
239         fvwm_cmd("AddToMenu", $menu,
240                  fvwm_label_escape("Title:\t$entry->{Title}"),
241                  @submenu);
242 }
243
244 # Generate the "Artist:" entry in the top menu.
245 sub top_track_artist {
246         my ($entry) = @_;
247         my @submenu;
248
249         # TODO: multi-artist tracks should get multiple artist menus; for now
250         # just combine the releases from all artists.
251         my @mbids = get_track_metadata($entry, "MUSICBRAINZ_ARTISTID");
252         if (@mbids) {
253                 @submenu = make_submenu("$menu-TopArtist",
254                                         map { "--artist-id=$_" } @mbids);
255         }
256
257         fvwm_cmd("AddToMenu", $menu,
258                  fvwm_label_escape("Artist:\t$entry->{Artist}"),
259                  @submenu);
260 }
261
262 # Generate the "Album:" entry in the top menu.
263 sub top_track_album {
264         my ($entry) = @_;
265         my @submenu;
266         my $mbid;
267
268         if (($mbid) = get_track_metadata($entry, "MUSICBRAINZ_ALBUMID")) {
269                 @submenu = make_submenu("$menu-$mbid", "--album-id=$mbid");
270         } elsif (($mbid) = get_track_metadata($entry, "MUSICBRAINZ_TRACKID")) {
271                 # Standalone recording
272                 my @a = get_track_metadata($entry, "MUSICBRAINZ_ARTISTID");
273                 my ($album) = get_track_metadata($entry, "Album");
274
275                 @submenu = make_submenu("$menu-$mbid", "--album-name=$album",
276                                         map { "--artist-id=$_" } @a);
277
278         }
279
280         fvwm_cmd("AddToMenu", $menu,
281                  fvwm_label_escape("Album:\t$entry->{Album}"),
282                  @submenu);
283 }
284
285 # Generate the "MusicBrainz:" entry in the top menu.
286 sub top_track_musicbrainz {
287         my ($entry) = @_;
288         my ($track_mbid, $recording_mbid, $release_mbid);
289         my @artist_mbids;
290         my $label = "MB:";
291         my %idmap;
292
293         ($track_mbid) = get_track_metadata($entry, "MUSICBRAINZ_RELEASETRACKID");
294         ($recording_mbid) = get_track_metadata($entry, "MUSICBRAINZ_TRACKID");
295         ($release_mbid) = get_track_metadata($entry, "MUSICBRAINZ_ALBUMID");
296         @artist_mbids = get_track_metadata($entry, "MUSICBRAINZ_ARTISTID");
297         return unless $track_mbid // $recording_mbid
298                    // $release_mbid // @artist_mbids;
299
300         foreach (get_track_metadata($entry, "Comment")) {
301                 $idmap{$1} = $2 if /^([^=]*)=(.*) \(idmap\)$/;
302         }
303
304         fvwm_cmd("AddToMenu", $menu, "", "Nop");
305         if ($track_mbid) {
306                 fvwm_cmd("AddToMenu", $menu, "$label\tShow track",
307                         "Exec", "exec", "xdg-open",
308                         "https://musicbrainz.org/track/$track_mbid");
309                 $label = "";
310         } elsif ($recording_mbid) {
311                 fvwm_cmd("AddToMenu", $menu, "$label\tShow recording",
312                         "Exec", "exec", "xdg-open",
313                         "https://musicbrainz.org/recording/$recording_mbid");
314                 $label = "";
315         } elsif ($release_mbid) {
316                 fvwm_cmd("AddToMenu", $menu, "$label\tShow",
317                         "Exec", "exec", "xdg-open",
318                         "https://musicbrainz.org/release/$release_mbid");
319                 $label = "";
320         }
321
322         foreach my $mbid (@artist_mbids) {
323                 my $name = " $idmap{$mbid}" if $idmap{$mbid};
324
325                 fvwm_cmd("AddToMenu", $menu, "$label\tShow artist$name",
326                         "Exec", "exec", "xdg-open",
327                         "https://musicbrainz.org/artist/$mbid");
328                 $label = "";
329         }
330 }
331
332 # Given a work MBID, return a hash reference containing all tracks
333 # linked to that work.  The hash keys are filenames.
334 sub get_tracks_by_work_mbid {
335         my %matches;
336         my $entry;
337
338         foreach my $mbid (@_) {
339                 MPD::exec("search", "(MUSICBRAINZ_WORKID == \"$mbid\")");
340                 while (<$sock>) {
341                         last if (/^OK/);
342                         die($_) if (/^ACK/);
343
344                         if (/^(\w+): (.*)$/) {
345                                 if ($1 eq "file") {
346                                         if (exists($matches{$2})) {
347                                                 $entry = $matches{$2};
348                                         } else {
349                                                 $entry = {};
350                                                 $matches{$2} = $entry;
351                                         }
352                                 }
353
354                                 add_track_metadata($entry, $1, $2);
355                         }
356                 }
357         }
358
359         return \%matches;
360 }
361
362 # Given a track MBID, return a hash reference containing all "related"
363 # tracks in the MPD database.  The hash keys are filenames.
364 #
365 # Currently tracks are considered "related" if their associated recordings
366 # have at least one work in common.
367 sub get_tracks_by_track_mbid {
368         my ($mbid, $tagname) = (@_, "MUSICBRAINZ_RELEASETRACKID");
369         my %source;
370         my %matches;
371         my $entry;
372
373         return \%matches unless ($mbid);
374         MPD::exec("search", "($tagname == \"$mbid\")");
375         while (<$sock>) {
376                 last if (/^OK/);
377                 die($_) if (/^ACK/);
378
379                 if (/^(\w+): (.*)$/) {
380                         add_track_metadata(\%source, $1, $2);
381                 }
382         }
383
384         # Always include the current track
385         $matches{$source{file}} = \%source;
386
387         # Find all tracks related by work
388         foreach my $mbid (get_track_metadata(\%source, "MUSICBRAINZ_WORKID")) {
389                 my $related = get_tracks_by_work_mbid($mbid);
390                 foreach (keys %$related) {
391                         $matches{$_} //= $related->{$_};
392                 }
393         }
394
395         return \%matches;
396 }
397
398 sub get_tracks_by_recording_mbid {
399         return get_tracks_by_track_mbid($_[0], "MUSICBRAINZ_TRACKID");
400 }
401
402 # Given a release MBID, return a hash reference containing all its
403 # associated tracks in the MPD database.  The hash keys are filenames.
404 sub get_tracks_by_release_mbid {
405         my ($mbid) = @_;
406         my %matches;
407         my $entry;
408
409         return \%matches unless ($mbid);
410         MPD::exec("search", "(MUSICBRAINZ_ALBUMID == \"$mbid\")");
411         while (<$sock>) {
412                 last if (/^OK/);
413                 die($_) if (/^ACK/);
414
415                 if (/^(\w+): (.*)$/) {
416                         if ($1 eq "file") {
417                                 if (exists($matches{$2})) {
418                                         $entry = $matches{$2};
419                                 } else {
420                                         $entry = {};
421                                         $matches{$2} = $entry;
422                                 }
423                         }
424
425                         add_track_metadata($entry, $1, $2);
426                 }
427         }
428
429         return \%matches;
430 }
431
432 # Insert the given entry into the referenced hash if it represents a
433 # standalone recording (not associated with a release).  The recording
434 # MBID is used as the hash key.
435 sub check_standalone {
436         my ($outhash, $entry) = @_;
437         my ($mbid) = get_track_metadata($entry, "MUSICBRAINZ_TRACKID");
438
439         return if exists $entry->{MUSICBRAINZ_ALBUMID};
440         $outhash->{$mbid} = $entry if ($mbid);
441 }
442
443 # Given an artist MBID, return a list of two hash refererences.  The
444 # first contains the associated releases in the MPD database and the
445 # hash keys are release MBIDs.  The second contains the artist's
446 # standalone recordings and the hash keys are recording MBIDs.
447 #
448 # In scalar context only the release hash is returned.
449 #
450 # Since MPD returns results on a per-track basis, each entry in the
451 # hash has the metadata for one unspecified track from that release.
452 sub get_releases_by_artist_mbid {
453         my (%releases, %standalones);
454         my $entry;
455
456         foreach my $mbid (@_) {
457                 MPD::exec("search", "(MUSICBRAINZ_ARTISTID == \"$mbid\")");
458                 while (<$sock>) {
459                         last if (/^OK/);
460                         die($_) if (/^ACK/);
461
462                         if (/^(\w+): (.*)$/) {
463                                 if ($1 eq "file") {
464                                         check_standalone(\%standalones, $entry);
465                                         $entry = {};
466                                 } elsif ($1 eq "MUSICBRAINZ_ALBUMID") {
467                                         $releases{$2} //= $entry;
468                                 }
469
470                                 add_track_metadata($entry, $1, $2);
471                         }
472                 }
473                 check_standalone(\%standalones, $entry);
474         }
475
476         return wantarray ? (\%releases, values %standalones) : \%releases;
477 }
478
479 # Given a filename, return the IDs (if any) for that file in the
480 # current MPD play queue.
481 sub get_ids_by_filename {
482         my ($file) = @_;
483         my @results = ();
484
485         MPD::exec("playlistfind", "file", $file);
486         while (<$sock>) {
487                 last if (/^OK/);
488                 die($_) if (/^ACK/);
489
490                 if (/^(\w+): (.*)$/) {
491                         push @results, $2 if ($1 eq "Id");
492                 }
493         }
494
495         return @results;
496 }
497
498 sub update_entry_ids {
499         my @notqueued = ();
500
501         foreach my $entry (@_) {
502                 unless (exists $entry->{Id}) {
503                         my ($id) = get_ids_by_filename($entry->{file});
504                         if (defined $id) {
505                                 $entry->{Id} = $id;
506                         } else {
507                                 push @notqueued, $entry;
508                                 next;
509                         }
510                 }
511         }
512
513         return @notqueued;
514 }
515
516 # albumsort(matches, a, b)
517 #
518 # Sort hash keys (a, b) by disc/track number for album menus.
519 sub albumsort {
520         my ($matches, $a, $b) = @_;
521
522         return $matches->{$a}->{Disc} <=> $matches->{$b}->{Disc}
523             || $matches->{$a}->{Track} <=> $matches->{$b}->{Track}
524             || $a cmp $b;
525 }
526
527 # datesort(matches, a, b)
528 #
529 # Sort hash keys (a, b) by release date
530 sub datesort {
531         my ($matches, $a, $b) = @_;
532
533         return $matches->{$a}->{Date} cmp $matches->{$b}->{Date}
534             || $a cmp $b;
535 }
536
537 # menu_trackname(entry)
538 #
539 # Format the track name for display in an FVWM menu, where entry
540 # is a hash reference containing the track metadata.
541 sub menu_trackname {
542         my ($entry) = @_;
543         my $fmt = "$entry->{trackfmt}$entry->{Artist} - $entry->{Title}";
544         return "$entry->{thumb}" . fvwm_label_escape($fmt);
545 }
546
547 sub print_version {
548         print <<EOF
549 mpdmenu.pl 0.9
550 Copyright © 2021 Nick Bowler
551 License GPLv3+: GNU General Public License version 3 or any later version.
552 This is free software: you are free to change and redistribute it.
553 There is NO WARRANTY, to the extent permitted by law.
554 EOF
555 }
556
557 sub print_usage {
558         my ($fh) = (@_, *STDERR);
559
560         print $fh "Usage: $0 [options]\n";
561         print $fh "Try $0 --help for more information.\n" unless (@_ > 0);
562 }
563
564 sub print_help {
565         print_usage(*STDOUT);
566         print <<EOF
567 This is "mpdmenu": a menu-based MPD client for FVWM.
568
569 Options:
570   -h, --host=HOST   Connect to the MPD server on HOST, overriding defaults.
571   -p, --port=PORT   Connect to the MPD server on PORT, overriding defaults.
572   -m, --menu=NAME   Set the name of the generated menu.
573   --album-id=MBID   Generate a menu for the given release MBID.
574   --album-name=NAME
575                     Generate a menu for standalone tracks with the given
576                     "album" NAME.  An artist MBID must be supplied.
577   --artist-id=MBID  Generate a menu for the given artist MBID.
578   --track-id=MBID   Generate a menu for the given track MBID.
579   --recording-id=MBID
580                     Generate a menu for the given recording MBID.
581   -V, --version     Print a version message and then exit.
582   -H, --help        Print this message and then exit.
583 EOF
584 }
585
586 GetOptions(
587         'host|h=s'       => \$MPD::host,
588         'port|p=s'       => \$MPD::port,
589         'menu|m=s'       => \$menu,
590
591         'artist-id=s'    => sub { $artistids{$_[1]} = 1; $mode = "artist"; },
592         'album-id=s'     => sub { $albumid = $_[1]; $mode = "album"; },
593         'album-name=s'   => sub { $albumname = $_[1]; $mode = "albumname"; },
594         'track-id=s'     => sub { $trackid = $_[1]; $mode = "track"; },
595         'recording-id=s' => sub { $recordingid = $_[1]; $mode = "recording"; },
596
597         'V|version'      => sub { print_version(); exit },
598         'H|help'         => sub { print_help(); exit },
599
600         'topmenu=s'      => \$topmenu, # top menu name (for submenu generation)
601 ) or do { print_usage; exit 1 };
602
603 $mode = "albumname" if ($albumname && $mode eq "artist");
604
605 unless (defined $menu) {
606         $topmenu //= "MenuMPD";
607         $menu = $topmenu . ($mode ne "top" ? $mode : "");
608 }
609 $topmenu //= $menu;
610
611 # Connect to MPD.
612 $sock = MPD::connect();
613 die("MPD version $MPD::major.$MPD::minor.$MPD::revision insufficient.")
614         unless MPD::min_version(MPD_MJR_MIN, MPD_MNR_MIN, MPD_REV_MIN);
615
616 if ($mode eq "top") {
617         my %current;
618         my %state;
619
620         $menu //= "MenuMPD";
621
622         MPD::exec("status");
623         while (<$sock>) {
624                 last if (/^OK/);
625                 die($_) if (/^ACK/);
626
627                 if (/^(\w+): (.*)$/) {
628                         $state{$1} = $2;
629                 }
630         }
631
632         MPD::exec("currentsong");
633         while (<$sock>) {
634                 last if (/^OK/);
635                 die($_) if (/^ACK/);
636
637                 if (/^(\w+): (.*)$/) {
638                         add_track_metadata(\%current, $1, $2);
639                 }
640         }
641
642         my $playstate = $state{state} eq "play"  ? "Playing"
643                       : $state{state} eq "stop"  ? "Stopped"
644                       : $state{state} eq "pause" ? "Paused"
645                       : "Unknown";
646         fvwm_cmd("AddToMenu", $menu, $playstate, "Title");
647
648         if (exists($current{file})) {
649                 top_track_cover(\%current);
650                 top_track_title(\%current);
651                 top_track_artist(\%current);
652                 top_track_album(\%current);
653                 top_track_musicbrainz(\%current);
654         } else {
655                 fvwm_cmd("AddToMenu", $menu, "[current track unavailable]");
656         }
657
658         if ($state{state} =~ /^p/) {
659                 my $pp = $state{state} eq "pause" ? "lay" : "ause";
660
661                 fvwm_cmd("AddToMenu", $menu, "", "Nop");
662                 fvwm_cmd("AddToMenu", $menu, "Next%next.svg:16x16%",
663                        "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "next");
664                 fvwm_cmd("AddToMenu", $menu, "P$pp%p$pp.svg:16x16%",
665                        "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "p$pp");
666                 fvwm_cmd("AddToMenu", $menu, "Stop%stop.svg:16x16%",
667                        "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "stop");
668                 fvwm_cmd("AddToMenu", $menu, "Prev%prev.svg:16x16%",
669                        "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "previous");
670         } elsif ($state{state} eq "stop") {
671                 fvwm_cmd("AddToMenu", $menu, "", "Nop");
672                 fvwm_cmd("AddToMenu", $menu, "Play%play.svg:16x16%",
673                        "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "play");
674         }
675 } elsif ($mode eq "album") {
676         my $matches = get_tracks_by_release_mbid($albumid);
677         my @notqueued = ();
678
679         $menu //= "MenuMPDAlbum";
680
681         my $track_max = max(map { $_->{Track} } values %$matches);
682         my $disc_max = max(map { $_->{Disc} } values %$matches);
683
684         # CDs have a max of 99 tracks and I hope 100+-disc-releases
685         # don't exist so this is fine.
686         my $track_digits = $track_max >= 10 ? 2 : 1;
687         my $disc_digits = $disc_max > 1 ? $disc_max >= 10 ? 2 : 1 : 0;
688         my $currentdisc;
689
690         fvwm_cmd("AddToMenu", $menu);
691         fvwm_cmd("+", "Release not found", "Title") unless keys %$matches;
692         foreach my $file (sort { albumsort($matches, $a, $b) } keys %$matches) {
693                 my $entry = $matches->{$file};
694
695                 # Format disc/track numbers
696                 $entry->{trackfmt} = sprintf("%*.*s%.*s%*d\t",
697                                   $disc_digits, $disc_digits, $entry->{Disc},
698                                   $disc_digits, "-",
699                                   $track_digits, $entry->{Track});
700                 $entry->{trackfmt} =~ s/ /\N{U+2007}/g;
701
702                 unless (exists $entry->{Id}) {
703                         my ($id) = get_ids_by_filename($file);
704                         if (defined $id) {
705                                 $entry->{Id} = $id;
706                         } else {
707                                 push @notqueued, $entry;
708                                 next;
709                         }
710                 }
711
712                 if (defined $currentdisc && $currentdisc != $entry->{Disc}) {
713                         fvwm_cmd("+", "", "Nop");
714                 }
715                 $currentdisc = $entry->{Disc};
716
717                 fvwm_cmd("+", menu_trackname($entry), "Exec",
718                          "exec", "$FindBin::Bin/mpdexec.pl",
719                          "playid", $entry->{Id});
720         }
721
722         fvwm_cmd("+", "Not in play queue", "Title") if @notqueued;
723         foreach my $entry (@notqueued) {
724                 fvwm_cmd("+", menu_trackname($entry));
725         }
726 } elsif ($mode eq "artist") {
727         # Create an artist menu.
728         my ($matches, @recs) = get_releases_by_artist_mbid(keys %artistids);
729
730         $menu //= "MenuMPDArtist";
731
732         my @mbids = sort { datesort($matches, $a, $b) } keys %$matches;
733         my @files = map { $matches->{$_}->{file} } @mbids;
734         my @thumbs = get_item_thumbnails({ small => 1 }, @files);
735
736         unless (@mbids) {
737                 fvwm_cmd("AddToMenu", $menu, "No releases found", "Title")
738         }
739
740         foreach my $mbid (@mbids) {
741                 my $entry = $matches->{$mbid};
742                 my $thumb = shift @thumbs;
743
744                 my @submenu = make_submenu("$topmenu-$mbid",
745                                            "--album-id=$mbid");
746                 fvwm_cmd("AddToMenu", $menu,
747                          $thumb . fvwm_label_escape($entry->{Album}),
748                          @submenu);
749         }
750
751         my @artists = map { "--artist-id=$_" } keys %artistids;
752         my %nonalbums = map { $_->{Album} => $_ } @recs;
753         foreach my $name (sort keys %nonalbums) {
754                 my $mbid = $nonalbums{$name}->{MUSICBRAINZ_TRACKID};
755                 my @submenu = make_submenu("$topmenu-$mbid", @artists,
756                                            "--album-name=$name");
757                 fvwm_cmd("AddToMenu", $menu, fvwm_label_escape($name), @submenu);
758         }
759 } elsif ($mode eq "albumname") {
760         # Create a standalone recordings menu
761         my ($releases, @recs) = get_releases_by_artist_mbid(keys %artistids);
762
763         $menu //= "MenuMPDRecordings";
764         my @tracks = sort { $a->{Title} cmp $b->{Title} }
765                      grep { $_->{Album} eq $albumname } @recs;
766         my @notqueued = update_entry_ids(@tracks);
767
768         fvwm_cmd("AddToMenu", $menu);
769         fvwm_cmd("+", "No tracks found", "Title") unless @tracks;
770
771         foreach my $entry (@tracks) {
772                 next unless exists $entry->{Id};
773
774                 fvwm_cmd("+", menu_trackname($entry), "Exec",
775                          "exec", "$FindBin::Bin/mpdexec.pl",
776                          "playid", $entry->{Id});
777         }
778
779         fvwm_cmd("+", "Not in play queue", "Title") if @notqueued;
780         foreach my $entry (@notqueued) {
781                 fvwm_cmd("+", menu_trackname($entry));
782         }
783 } elsif ($mode eq "track" || $mode eq "recording") {
784         my ($matches, $mbid);
785         my @notqueued;
786
787         if ($mode eq "track") {
788                 $matches = get_tracks_by_track_mbid($trackid)
789         } else {
790                 $matches = get_tracks_by_recording_mbid($recordingid)
791         }
792
793         $menu //= "MenuMPDTrack";
794         fvwm_cmd("DestroyMenu", $menu);
795
796         my @files = sort { datesort($matches, $a, $b) } keys %$matches;
797         my @thumbs = get_item_thumbnails({ small => 1 }, @files);
798
799         fvwm_cmd("AddToMenu", $menu);
800         fvwm_cmd("+", "No tracks found", "Title") unless @files;
801         foreach my $file (@files) {
802                 my $entry = $matches->{$file};
803                 $entry->{thumb} = shift @thumbs;
804
805                 unless (exists $entry->{Id}) {
806                         my ($id) = get_ids_by_filename($file);
807                         if (defined $id) {
808                                 $entry->{Id} = $id;
809                         } else {
810                                 push @notqueued, $entry;
811                                 next;
812                         }
813                 }
814
815                 fvwm_cmd("+", menu_trackname($entry), "Exec",
816                          "exec", "$FindBin::Bin/mpdexec.pl",
817                          "playid", $entry->{Id});
818         }
819
820         fvwm_cmd("+", "Not in play queue", "Title") if @notqueued;
821         foreach my $entry (@notqueued) {
822                 fvwm_cmd("+", menu_trackname($entry));
823         }
824 }
825
826 # Finished.
827 print $sock "close\n";