3 # Copyright © 2008,2010,2012,2019 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 IO::Socket::INET6;
22 use Getopt::Long qw(:config gnu_getopt);
23 use Scalar::Util qw(reftype);
24 use List::Util qw(any max);
33 my $SELF = "$FindBin::Bin/$FindBin::Script";
35 my $MUSIC = $ENV{MUSIC} // "/srv/music";
36 my $host = $ENV{MPD_HOST} // "localhost";
37 my $port = $ENV{MPD_PORT} // "6600";
40 my ($albumid, $trackid);
45 # Quotes the argument so that it is presented as a single argument to MPD
46 # at the protocol level. This also works OK for most FVWM arguments.
50 # No way to encode literal newlines in the protocol, so we
51 # convert any newlines in the arguments into a space, which
52 # can help with quoting.
64 # Submit a command to the MPD server; each argument to this function
65 # is quoted and sent as a single argument to MPD.
67 my $cmd = join(' ', map { escape } @_);
72 sub fvwm_cmd_unquoted {
73 print join(' ', @_), "\n";
77 fvwm_cmd_unquoted(map { escape } @_);
80 # Quotes the argument in such a way that it is passed unadulterated by
81 # both FVWM and the shell to a command as a single argument (for use as
82 # an # argument for e.g., the Exec or PipeRead FVWM commands).
84 # The result must be used with fvwm_cmd_unquoted;
85 sub fvwm_shell_literal {
97 # Escapes metacharacters in the argument used in FVWM menu labels. The
98 # string must still be quoted (e.g., by using fvwm_cmd).
99 sub fvwm_label_escape {
100 my @tokens = split /\t/, $_[0];
101 @tokens[0] =~ s/&/&&/g;
102 my $ret = join "\t", @tokens;
103 $ret =~ s/[\$@%^*]/$&$&/g;
107 # make_submenu(name, [args ...])
109 # Creates a submenu (with the specified name) constructed by invoking this
110 # script with the given arguments. Returns a list that can be passed to
111 # fvwm_cmd to display the menu.
115 unshift @_, ("exec", $SELF, "--topmenu=$topmenu", "--menu=$name");
117 fvwm_cmd("DestroyFunc", "Make$name");
118 fvwm_cmd("AddToFunc", "Make$name");
119 fvwm_cmd("+", "I", "DestroyMenu", $name);
121 fvwm_cmd("DestroyMenu", $name);
122 fvwm_cmd("AddToMenu", $name, "DynamicPopupAction", "Make$name");
123 fvwm_cmd("AddToFunc", "Kill$topmenu", "I", "DestroyMenu", $name);
125 fvwm_cmd("DestroyFunc", "Make$name");
126 fvwm_cmd("AddToFunc", "Make$name");
127 fvwm_cmd("+", "I", "DestroyMenu", $name);
128 fvwm_cmd("+", "I", "-PipeRead",
129 join(' ', map { fvwm_shell_literal } @_));
130 fvwm_cmd("AddToFunc", "Kill$topmenu", "I", "DestroyFunc", "Make$name");
132 return ("Popup", $name);
135 # get_item_thumbnails({ options }, file, ...)
136 # get_item_thumbnails(file, ...)
138 # For each music file listed, obtain a thumbnail (if any) for the cover art.
140 # The first argument is a hash reference to control the mode of operation;
141 # it may be omitted for default options.
143 # get_item_thumbnails({ small => 1 }, ...) - smaller thumbnails
145 # The returned list consists of strings (in the same order as the filename
146 # arguments) suitable for use directly in FVWM menus; by default the filename
147 # is bracketed by asterisks (e.g., "*thumbnail.png*"); in small mode it is
148 # surrounded by % (e.g., "%thumbnail.png%"). If no cover art was found, the
149 # empty string is returned for that file.
150 sub get_item_thumbnails {
155 $flags = shift if (reftype($_[0]) eq "HASH");
156 return @results unless @_;
159 if ($flags->{small}) {
160 push @opts, "--small";
164 open THUMB, "-|", "$FindBin::Bin/mpdthumb.sh", @opts, "--", @_;
169 $thumb = "$c$thumb$c" if (-f $thumb);
170 push @results, $thumb;
173 die("mpdthumb failed") if ($?);
178 # add_track_metadata(hashref, key, value)
180 # Inserts the given key into the referenced hash; if the key already exists
181 # in the hash then the hash element is converted to an array reference (if
182 # it isn't already) and the value is appended to that array.
183 sub add_track_metadata {
184 my ($entry, $key, $value) = @_;
186 if (exists($entry->{$key})) {
187 my $ref = $entry->{$key};
189 if (reftype($ref) ne "ARRAY") {
190 return if ($ref eq $value);
193 $entry->{$key} = $ref;
196 push(@$ref, $value) unless (any {$_ eq $value} @$ref);
198 $entry->{$key} = $value;
202 # get_track_metadata(hashref, key)
204 # Return the values associated with the given metadata key as a list.
205 sub get_track_metadata {
206 my ($entry, $key) = @_;
208 return () unless (exists($entry->{$key}));
210 my $ref = $entry->{$key};
211 return @$ref if (reftype($ref) eq "ARRAY");
215 # Given a music filename, search for the cover art in the same directory.
216 sub mpd_cover_filename {
220 $dir =~ s/\/[^\/]*$//;
221 foreach ("cover.png", "cover.jpg", "cover.tiff", "cover.bmp") {
227 return unless defined $file;
229 # Follow one level of symbolic link to get to the scans directory.
230 $file = readlink($file) // $file;
231 $file = "$dir/$file" unless ($file =~ /^\//);
235 # Generate the cover art entry in the top menu.
236 sub top_track_cover {
239 ($entry->{thumb}) = get_item_thumbnails($entry->{file});
240 print "$entry->{thumb}\n";
241 if ($entry->{thumb}) {
242 my $file = "$MUSIC/$entry->{file}";
243 my $cover = mpd_cover_filename($file);
245 $cover = fvwm_shell_literal($cover // $file);
246 fvwm_cmd_unquoted("AddToMenu", escape($menu),
247 escape($entry->{thumb}),
248 "Exec", "exec", "geeqie", $cover);
252 # Generate the "Title:" entry in the top menu.
253 sub top_track_title {
257 my ($mbid) = get_track_metadata($entry, "MUSICBRAINZ_RELEASETRACKID");
258 @submenu = make_submenu("$menu-$mbid", "--track-id=$mbid") if $mbid;
260 fvwm_cmd("AddToMenu", $menu,
261 fvwm_label_escape("Title:\t$entry->{Title}"),
265 # Generate the "Artist:" entry in the top menu.
266 sub top_track_artist {
270 # TODO: multi-artist tracks should get multiple artist menus; for now
271 # just combine the releases from all artists.
272 my @mbids = get_track_metadata($entry, "MUSICBRAINZ_ARTISTID");
274 @submenu = make_submenu("$menu-TopArtist",
275 map { "--artist-id=$_" } @mbids);
278 fvwm_cmd("AddToMenu", $menu,
279 fvwm_label_escape("Artist:\t$entry->{Artist}"),
283 # Generate the "Album:" entry in the top menu.
284 sub top_track_album {
288 my ($mbid) = get_track_metadata($entry, "MUSICBRAINZ_ALBUMID");
289 @submenu = make_submenu("$menu-$mbid", "--album-id=$mbid") if $mbid;
291 fvwm_cmd("AddToMenu", $menu,
292 fvwm_label_escape("Album:\t$entry->{Album}"),
296 # Given a work MBID, return a hash reference containing all tracks
297 # linked to that work. The hash keys are filenames.
298 sub get_tracks_by_work_mbid {
302 foreach my $mbid (@_) {
303 mpd_exec("search", "(MUSICBRAINZ_WORKID == \"$mbid\")");
308 if (/^(\w+): (.*)$/) {
310 if (exists($matches{$2})) {
311 $entry = $matches{$2};
314 $matches{$2} = $entry;
318 add_track_metadata($entry, $1, $2);
326 # Given a track MBID, return a hash reference containing all "related"
327 # tracks in the MPD database. The hash keys are filenames.
329 # Currently tracks are considered "related" if their associated recordings
330 # have at least one work in common.
331 sub get_tracks_by_track_mbid {
337 return \%matches unless ($mbid);
338 mpd_exec("search", "(MUSICBRAINZ_RELEASETRACKID == \"$mbid\")");
343 if (/^(\w+): (.*)$/) {
344 add_track_metadata(\%source, $1, $2);
348 # Always include the current track
349 $matches{$source{file}} = \%source;
351 # Find all tracks related by work
352 foreach my $mbid (get_track_metadata(\%source, "MUSICBRAINZ_WORKID")) {
353 my $related = get_tracks_by_work_mbid($mbid);
354 foreach (keys %$related) {
355 $matches{$_} //= $related->{$_};
362 # Given a release MBID, return a hash reference containing all its
363 # associated tracks in the MPD database. The hash keys are filenames.
364 sub get_tracks_by_release_mbid {
369 return \%matches unless ($mbid);
370 mpd_exec("search", "(MUSICBRAINZ_ALBUMID == \"$mbid\")");
375 if (/^(\w+): (.*)$/) {
377 if (exists($matches{$2})) {
378 $entry = $matches{$2};
381 $matches{$2} = $entry;
385 add_track_metadata($entry, $1, $2);
392 # Given an artist MBID, return a hash reference containing associated
393 # releases in the MPD database. The hash keys are release MBIDs.
395 # Since MPD returns results on a per-track basis, each entry in the
396 # hash has the metadata for one unspecified track from that release.
397 sub get_releases_by_artist_mbid {
401 foreach my $mbid (@_) {
402 mpd_exec("search", "(MUSICBRAINZ_ARTISTID == \"$mbid\")");
407 if (/^(\w+): (.*)$/) {
410 } elsif ($1 eq "MUSICBRAINZ_ALBUMID") {
411 $releases{$2} //= $entry;
414 add_track_metadata($entry, $1, $2);
422 # Given a filename, return the IDs (if any) for that file in the
423 # current MPD play queue.
424 sub get_ids_by_filename {
428 mpd_exec("playlistfind", "file", $file);
433 if (/^(\w+): (.*)$/) {
434 push @results, $2 if ($1 eq "Id");
441 # albumsort(matches, a, b)
443 # Sort hash keys (a, b) by disc/track number for album menus.
445 my ($matches, $a, $b) = @_;
447 return $matches->{$a}->{Disc} <=> $matches->{$b}->{Disc}
448 || $matches->{$a}->{Track} <=> $matches->{$b}->{Track}
452 # datesort(matches, a, b)
454 # Sort hash keys (a, b) by release date
456 my ($matches, $a, $b) = @_;
458 return $matches->{$a}->{Date} cmp $matches->{$b}->{Date}
462 # menu_trackname(entry)
464 # Format the track name for display in an FVWM menu, where entry
465 # is a hash reference containing the track metadata.
468 my $fmt = "$entry->{trackfmt}$entry->{Artist} - $entry->{Title}";
469 return "$entry->{thumb}" . fvwm_label_escape($fmt);
475 Copyright © 2019 Nick Bowler
476 License GPLv3+: GNU General Public License version 3 or any later version.
477 This is free software: you are free to change and redistribute it.
478 There is NO WARRANTY, to the extent permitted by law.
483 my $fh = $_[1] // *STDERR;
485 print $fh "Usage: $0 [options]\n";
486 print "Try $0 --help for more information.\n" unless (@_ > 0);
490 print_usage(*STDOUT);
492 This is "mpdmenu": a menu-based MPD client for FVWM.
495 -h, --host=HOST Connect to the MPD server on HOST, overriding defaults.
496 -p, --port=PORT Connect to the MPD server on PORT, overriding defaults.
497 -m, --menu=NAME Set the name of the generated menu.
498 --album-id=MBID Generate a menu for the given release MBID.
499 --artist-id=MBID Generate a menu for the given artist MBID.
500 --track-id=MBID Generate a menu for the given track MBID.
501 -V, --version Print a version message and then exit.
502 -H, --help Print this message and then exit.
507 'host|h=s' => \$host,
508 'port|p=s' => \$port,
509 'menu|m=s' => \$menu,
511 'artist-id=s' => sub { $artistids{$_[1]} = 1; $mode = "artist"; },
512 'album-id=s' => sub { $albumid = $_[1]; $mode = "album"; },
513 'track-id=s' => sub { $trackid = $_[1]; $mode = "track"; },
515 'V|version' => sub { print_version(); exit },
516 'H|help' => sub { print_help(); exit },
518 'topmenu=s' => \$topmenu, # top menu name (for submenu generation)
519 ) or do { print_usage; exit 1 };
521 unless (defined $menu) {
522 $topmenu //= "MenuMPD";
523 $menu = $topmenu . ($mode ne "top" ? $mode : "");
528 $sock = new IO::Socket::INET6(
533 ) or die("could not open socket: $!.\n");
534 binmode($sock, ":utf8");
536 die("could not connect to MPD: $!.\n")
537 if (!(<$sock> =~ /^OK MPD ([0-9]+)\.([0-9]+)\.([0-9]+)$/));
539 die("MPD version $1.$2.$3 insufficient.\n")
540 if ( ($1 < MPD_MJR_MIN)
541 || ($1 == MPD_MJR_MIN && $2 < MPD_MNR_MIN)
542 || ($1 == MPD_MJR_MIN && $2 == MPD_MNR_MIN && $3 < MPD_REV_MIN));
544 if ($mode eq "top") {
555 if (/^(\w+): (.*)$/) {
560 mpd_exec("currentsong");
565 if (/^(\w+): (.*)$/) {
566 add_track_metadata(\%current, $1, $2);
570 my $playstate = $state{state} eq "play" ? "Playing"
571 : $state{state} eq "stop" ? "Stopped"
572 : $state{state} eq "pause" ? "Paused"
574 fvwm_cmd("AddToMenu", $menu, $playstate, "Title");
576 if (exists($current{file})) {
577 top_track_cover(\%current);
578 top_track_title(\%current);
579 top_track_artist(\%current);
580 top_track_album(\%current);
582 fvwm_cmd("AddToMenu", $menu, "[current track unavailable]");
585 if ($state{state} =~ /^p/) {
586 my $pp = $state{state} eq "pause" ? "lay" : "ause";
588 fvwm_cmd("AddToMenu", $menu, "", "Nop");
589 fvwm_cmd("AddToMenu", $menu, "Next%next.svg:16x16%",
590 "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "next");
591 fvwm_cmd("AddToMenu", $menu, "P$pp%p$pp.svg:16x16%",
592 "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "p$pp");
593 fvwm_cmd("AddToMenu", $menu, "Stop%stop.svg:16x16%",
594 "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "stop");
595 fvwm_cmd("AddToMenu", $menu, "Prev%prev.svg:16x16%",
596 "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "previous");
597 } elsif ($state{state} eq "stop") {
598 fvwm_cmd("AddToMenu", $menu, "", "Nop");
599 fvwm_cmd("AddToMenu", $menu, "Play%play.svg:16x16%",
600 "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "play");
602 } elsif ($mode eq "album") {
603 my $matches = get_tracks_by_release_mbid($albumid);
606 $menu //= "MenuMPDAlbum";
608 my $track_max = max(map { $_->{Track} } values %$matches);
609 my $disc_max = max(map { $_->{Disc} } values %$matches);
611 # CDs have a max of 99 tracks and I hope 100+-disc-releases
612 # don't exist so this is fine.
613 my $track_digits = $track_max >= 10 ? 2 : 1;
614 my $disc_digits = $disc_max > 1 ? $disc_max >= 10 ? 2 : 1 : 0;
617 fvwm_cmd("AddToMenu", $menu);
618 fvwm_cmd("+", "Release not found", "Title") unless keys %$matches;
619 foreach my $file (sort { albumsort($matches, $a, $b) } keys %$matches) {
620 my $entry = $matches->{$file};
622 # Format disc/track numbers
623 $entry->{trackfmt} = sprintf("%*.*s%.*s%*d\t",
624 $disc_digits, $disc_digits, $entry->{Disc},
626 $track_digits, $entry->{Track});
627 $entry->{trackfmt} =~ s/ /\N{U+2007}/g;
629 unless (exists $entry->{Id}) {
630 my ($id) = get_ids_by_filename($file);
634 push @notqueued, $entry;
639 if (defined $currentdisc && $currentdisc != $entry->{Disc}) {
640 fvwm_cmd("+", "", "Nop");
642 $currentdisc = $entry->{Disc};
644 fvwm_cmd("+", menu_trackname($entry), "Exec",
645 "exec", "$FindBin::Bin/mpdexec.pl",
646 "playid", $entry->{Id});
649 fvwm_cmd("+", "Not in play queue", "Title") if @notqueued;
650 foreach my $entry (@notqueued) {
651 fvwm_cmd("+", menu_trackname($entry));
653 } elsif ($mode eq "artist") {
654 # Create an artist menu.
655 my $matches = get_releases_by_artist_mbid(keys %artistids);
658 $menu //= "MenuMPDArtist";
660 my @mbids = sort { datesort($matches, $a, $b) } keys %$matches;
661 my @files = map { $matches->{$_}->{file} } @mbids;
662 my @thumbs = get_item_thumbnails({ small => 1 }, @files);
663 fvwm_cmd("AddToMenu", $menu, "No releases found", "Title") unless @mbids;
665 foreach my $mbid (@mbids) {
666 my $entry = $matches->{$mbid};
667 my $thumb = shift @thumbs;
669 my @submenu = make_submenu("$topmenu-$mbid",
671 fvwm_cmd("AddToMenu", $menu,
672 $thumb . fvwm_label_escape($entry->{Album}),
675 } elsif ($mode eq "track") {
676 my $matches = get_tracks_by_track_mbid($trackid);
679 $menu //= "MenuMPDTrack";
681 my @files = sort { datesort($matches, $a, $b) } keys %$matches;
682 my @thumbs = get_item_thumbnails({ small => 1 }, @files);
684 fvwm_cmd("AddToMenu", $menu);
685 fvwm_cmd("+", "No tracks found", "Title") unless @files;
686 foreach my $file (@files) {
687 my $entry = $matches->{$file};
688 $entry->{thumb} = shift @thumbs;
690 unless (exists $entry->{Id}) {
691 my ($id) = get_ids_by_filename($file);
695 push @notqueued, $entry;
700 fvwm_cmd("+", menu_trackname($entry), "Exec",
701 "exec", "$FindBin::Bin/mpdexec.pl",
702 "playid", $entry->{Id});
705 fvwm_cmd("+", "Not in play queue", "Title") if @notqueued;
706 foreach my $entry (@notqueued) {
707 fvwm_cmd("+", menu_trackname($entry));
712 print $sock "close\n";