3 # Copyright © 2008,2010,2012,2020 Nick Bowler
5 # Silly little script to generate an FVWM menu with various bits of MPD
6 # status information and controls.
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.
16 use Encode qw(decode encode);
17 use Encode::Locale qw(decode_argv);
18 decode_argv(Encode::FB_CROAK);
19 binmode(STDOUT, ":utf8");
21 use Getopt::Long qw(:config gnu_getopt);
22 use Scalar::Util qw(reftype);
23 use List::Util qw(any max);
26 use lib "$FindBin::Bin";
35 my $SELF = "$FindBin::Bin/$FindBin::Script";
37 my $MUSIC = $ENV{MUSIC} // "/srv/music";
40 my ($albumid, $trackid);
45 sub fvwm_cmd_unquoted {
46 print join(' ', @_), "\n";
50 fvwm_cmd_unquoted(map { MPD::escape } @_);
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).
57 # The result must be used with fvwm_cmd_unquoted;
58 sub fvwm_shell_literal {
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;
80 # make_submenu(name, [args ...])
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.
88 unshift @_, ("exec", $SELF, "--topmenu=$topmenu", "--menu=$name");
90 fvwm_cmd("DestroyFunc", "Make$name");
91 fvwm_cmd("AddToFunc", "Make$name");
92 fvwm_cmd("+", "I", "DestroyMenu", $name);
94 fvwm_cmd("DestroyMenu", $name);
95 fvwm_cmd("AddToMenu", $name, "DynamicPopupAction", "Make$name");
96 fvwm_cmd("AddToFunc", "Kill$topmenu", "I", "DestroyMenu", $name);
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");
105 return ("Popup", $name);
108 # get_item_thumbnails({ options }, file, ...)
109 # get_item_thumbnails(file, ...)
111 # For each music file listed, obtain a thumbnail (if any) for the cover art.
113 # The first argument is a hash reference to control the mode of operation;
114 # it may be omitted for default options.
116 # get_item_thumbnails({ small => 1 }, ...) - smaller thumbnails
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 {
128 $flags = shift if (reftype($_[0]) eq "HASH");
129 return @results unless @_;
132 if ($flags->{small}) {
133 push @opts, "--small";
137 open THUMB, "-|", "$FindBin::Bin/mpdthumb.sh", @opts, "--", @_;
142 $thumb = "$c$thumb$c" if (-f $thumb);
143 push @results, $thumb;
146 die("mpdthumb failed") if ($?);
151 # add_track_metadata(hashref, key, value)
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) = @_;
159 if (exists($entry->{$key})) {
160 my $ref = $entry->{$key};
162 if (reftype($ref) ne "ARRAY") {
163 return if ($ref eq $value);
166 $entry->{$key} = $ref;
169 push(@$ref, $value) unless (any {$_ eq $value} @$ref);
171 $entry->{$key} = $value;
175 # get_track_metadata(hashref, key)
177 # Return the values associated with the given metadata key as a list.
178 sub get_track_metadata {
179 my ($entry, $key) = @_;
181 return () unless (exists($entry->{$key}));
183 my $ref = $entry->{$key};
184 return @$ref if (reftype($ref) eq "ARRAY");
188 # Given a music filename, search for the cover art in the same directory.
189 sub mpd_cover_filename {
193 $dir =~ s/\/[^\/]*$//;
194 foreach ("cover.png", "cover.jpg", "cover.tiff", "cover.bmp") {
200 return unless defined $file;
202 # Follow one level of symbolic link to get to the scans directory.
203 $file = readlink($file) // $file;
204 $file = "$dir/$file" unless ($file =~ /^\//);
208 # Generate the cover art entry in the top menu.
209 sub top_track_cover {
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);
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);
225 # Generate the "Title:" entry in the top menu.
226 sub top_track_title {
230 my ($mbid) = get_track_metadata($entry, "MUSICBRAINZ_RELEASETRACKID");
231 @submenu = make_submenu("$menu-$mbid", "--track-id=$mbid") if $mbid;
233 fvwm_cmd("AddToMenu", $menu,
234 fvwm_label_escape("Title:\t$entry->{Title}"),
238 # Generate the "Artist:" entry in the top menu.
239 sub top_track_artist {
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");
247 @submenu = make_submenu("$menu-TopArtist",
248 map { "--artist-id=$_" } @mbids);
251 fvwm_cmd("AddToMenu", $menu,
252 fvwm_label_escape("Artist:\t$entry->{Artist}"),
256 # Generate the "Album:" entry in the top menu.
257 sub top_track_album {
261 my ($mbid) = get_track_metadata($entry, "MUSICBRAINZ_ALBUMID");
262 @submenu = make_submenu("$menu-$mbid", "--album-id=$mbid") if $mbid;
264 fvwm_cmd("AddToMenu", $menu,
265 fvwm_label_escape("Album:\t$entry->{Album}"),
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 {
275 foreach my $mbid (@_) {
276 MPD::exec("search", "(MUSICBRAINZ_WORKID == \"$mbid\")");
281 if (/^(\w+): (.*)$/) {
283 if (exists($matches{$2})) {
284 $entry = $matches{$2};
287 $matches{$2} = $entry;
291 add_track_metadata($entry, $1, $2);
299 # Given a track MBID, return a hash reference containing all "related"
300 # tracks in the MPD database. The hash keys are filenames.
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");
310 return \%matches unless ($mbid);
311 MPD::exec("search", "(MUSICBRAINZ_RELEASETRACKID == \"$mbid\")");
316 if (/^(\w+): (.*)$/) {
317 add_track_metadata(\%source, $1, $2);
321 # Always include the current track
322 $matches{$source{file}} = \%source;
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->{$_};
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 {
342 return \%matches unless ($mbid);
343 MPD::exec("search", "(MUSICBRAINZ_ALBUMID == \"$mbid\")");
348 if (/^(\w+): (.*)$/) {
350 if (exists($matches{$2})) {
351 $entry = $matches{$2};
354 $matches{$2} = $entry;
358 add_track_metadata($entry, $1, $2);
365 # Given an artist MBID, return a hash reference containing associated
366 # releases in the MPD database. The hash keys are release MBIDs.
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 {
374 foreach my $mbid (@_) {
375 MPD::exec("search", "(MUSICBRAINZ_ARTISTID == \"$mbid\")");
380 if (/^(\w+): (.*)$/) {
383 } elsif ($1 eq "MUSICBRAINZ_ALBUMID") {
384 $releases{$2} //= $entry;
387 add_track_metadata($entry, $1, $2);
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 {
401 MPD::exec("playlistfind", "file", $file);
406 if (/^(\w+): (.*)$/) {
407 push @results, $2 if ($1 eq "Id");
414 # albumsort(matches, a, b)
416 # Sort hash keys (a, b) by disc/track number for album menus.
418 my ($matches, $a, $b) = @_;
420 return $matches->{$a}->{Disc} <=> $matches->{$b}->{Disc}
421 || $matches->{$a}->{Track} <=> $matches->{$b}->{Track}
425 # datesort(matches, a, b)
427 # Sort hash keys (a, b) by release date
429 my ($matches, $a, $b) = @_;
431 return $matches->{$a}->{Date} cmp $matches->{$b}->{Date}
435 # menu_trackname(entry)
437 # Format the track name for display in an FVWM menu, where entry
438 # is a hash reference containing the track metadata.
441 my $fmt = "$entry->{trackfmt}$entry->{Artist} - $entry->{Title}";
442 return "$entry->{thumb}" . fvwm_label_escape($fmt);
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.
456 my $fh = $_[1] // *STDERR;
458 print $fh "Usage: $0 [options]\n";
459 print "Try $0 --help for more information.\n" unless (@_ > 0);
463 print_usage(*STDOUT);
465 This is "mpdmenu": a menu-based MPD client for FVWM.
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.
480 'host|h=s' => \$MPD::host,
481 'port|p=s' => \$MPD::port,
482 'menu|m=s' => \$menu,
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"; },
488 'V|version' => sub { print_version(); exit },
489 'H|help' => sub { print_help(); exit },
491 'topmenu=s' => \$topmenu, # top menu name (for submenu generation)
492 ) or do { print_usage; exit 1 };
494 unless (defined $menu) {
495 $topmenu //= "MenuMPD";
496 $menu = $topmenu . ($mode ne "top" ? $mode : "");
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);
505 if ($mode eq "top") {
516 if (/^(\w+): (.*)$/) {
521 MPD::exec("currentsong");
526 if (/^(\w+): (.*)$/) {
527 add_track_metadata(\%current, $1, $2);
531 my $playstate = $state{state} eq "play" ? "Playing"
532 : $state{state} eq "stop" ? "Stopped"
533 : $state{state} eq "pause" ? "Paused"
535 fvwm_cmd("AddToMenu", $menu, $playstate, "Title");
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);
543 fvwm_cmd("AddToMenu", $menu, "[current track unavailable]");
546 if ($state{state} =~ /^p/) {
547 my $pp = $state{state} eq "pause" ? "lay" : "ause";
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");
563 } elsif ($mode eq "album") {
564 my $matches = get_tracks_by_release_mbid($albumid);
567 $menu //= "MenuMPDAlbum";
569 my $track_max = max(map { $_->{Track} } values %$matches);
570 my $disc_max = max(map { $_->{Disc} } values %$matches);
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;
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};
583 # Format disc/track numbers
584 $entry->{trackfmt} = sprintf("%*.*s%.*s%*d\t",
585 $disc_digits, $disc_digits, $entry->{Disc},
587 $track_digits, $entry->{Track});
588 $entry->{trackfmt} =~ s/ /\N{U+2007}/g;
590 unless (exists $entry->{Id}) {
591 my ($id) = get_ids_by_filename($file);
595 push @notqueued, $entry;
600 if (defined $currentdisc && $currentdisc != $entry->{Disc}) {
601 fvwm_cmd("+", "", "Nop");
603 $currentdisc = $entry->{Disc};
605 fvwm_cmd("+", menu_trackname($entry), "Exec",
606 "exec", "$FindBin::Bin/mpdexec.pl",
607 "playid", $entry->{Id});
610 fvwm_cmd("+", "Not in play queue", "Title") if @notqueued;
611 foreach my $entry (@notqueued) {
612 fvwm_cmd("+", menu_trackname($entry));
614 } elsif ($mode eq "artist") {
615 # Create an artist menu.
616 my $matches = get_releases_by_artist_mbid(keys %artistids);
619 $menu //= "MenuMPDArtist";
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;
626 foreach my $mbid (@mbids) {
627 my $entry = $matches->{$mbid};
628 my $thumb = shift @thumbs;
630 my @submenu = make_submenu("$topmenu-$mbid",
632 fvwm_cmd("AddToMenu", $menu,
633 $thumb . fvwm_label_escape($entry->{Album}),
636 } elsif ($mode eq "track") {
637 my $matches = get_tracks_by_track_mbid($trackid);
640 $menu //= "MenuMPDTrack";
642 my @files = sort { datesort($matches, $a, $b) } keys %$matches;
643 my @thumbs = get_item_thumbnails({ small => 1 }, @files);
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;
651 unless (exists $entry->{Id}) {
652 my ($id) = get_ids_by_filename($file);
656 push @notqueued, $entry;
661 fvwm_cmd("+", menu_trackname($entry), "Exec",
662 "exec", "$FindBin::Bin/mpdexec.pl",
663 "playid", $entry->{Id});
666 fvwm_cmd("+", "Not in play queue", "Title") if @notqueued;
667 foreach my $entry (@notqueued) {
668 fvwm_cmd("+", menu_trackname($entry));
673 print $sock "close\n";