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 # Submit a command to the MPD server; each argument to this function
46 # is quoted and sent as a single argument to MPD.
48 my $cmd = join(' ', map { MPD::escape } @_);
53 sub fvwm_cmd_unquoted {
54 print join(' ', @_), "\n";
58 fvwm_cmd_unquoted(map { MPD::escape } @_);
61 # Quotes the argument in such a way that it is passed unadulterated by
62 # both FVWM and the shell to a command as a single argument (for use as
63 # an # argument for e.g., the Exec or PipeRead FVWM commands).
65 # The result must be used with fvwm_cmd_unquoted;
66 sub fvwm_shell_literal {
78 # Escapes metacharacters in the argument used in FVWM menu labels. The
79 # string must still be quoted (e.g., by using fvwm_cmd).
80 sub fvwm_label_escape {
81 my @tokens = split /\t/, $_[0];
82 @tokens[0] =~ s/&/&&/g;
83 my $ret = join "\t", @tokens;
84 $ret =~ s/[\$@%^*]/$&$&/g;
88 # make_submenu(name, [args ...])
90 # Creates a submenu (with the specified name) constructed by invoking this
91 # script with the given arguments. Returns a list that can be passed to
92 # fvwm_cmd to display the menu.
96 unshift @_, ("exec", $SELF, "--topmenu=$topmenu", "--menu=$name");
98 fvwm_cmd("DestroyFunc", "Make$name");
99 fvwm_cmd("AddToFunc", "Make$name");
100 fvwm_cmd("+", "I", "DestroyMenu", $name);
102 fvwm_cmd("DestroyMenu", $name);
103 fvwm_cmd("AddToMenu", $name, "DynamicPopupAction", "Make$name");
104 fvwm_cmd("AddToFunc", "Kill$topmenu", "I", "DestroyMenu", $name);
106 fvwm_cmd("DestroyFunc", "Make$name");
107 fvwm_cmd("AddToFunc", "Make$name");
108 fvwm_cmd("+", "I", "DestroyMenu", $name);
109 fvwm_cmd("+", "I", "-PipeRead",
110 join(' ', map { fvwm_shell_literal } @_));
111 fvwm_cmd("AddToFunc", "Kill$topmenu", "I", "DestroyFunc", "Make$name");
113 return ("Popup", $name);
116 # get_item_thumbnails({ options }, file, ...)
117 # get_item_thumbnails(file, ...)
119 # For each music file listed, obtain a thumbnail (if any) for the cover art.
121 # The first argument is a hash reference to control the mode of operation;
122 # it may be omitted for default options.
124 # get_item_thumbnails({ small => 1 }, ...) - smaller thumbnails
126 # The returned list consists of strings (in the same order as the filename
127 # arguments) suitable for use directly in FVWM menus; by default the filename
128 # is bracketed by asterisks (e.g., "*thumbnail.png*"); in small mode it is
129 # surrounded by % (e.g., "%thumbnail.png%"). If no cover art was found, the
130 # empty string is returned for that file.
131 sub get_item_thumbnails {
136 $flags = shift if (reftype($_[0]) eq "HASH");
137 return @results unless @_;
140 if ($flags->{small}) {
141 push @opts, "--small";
145 open THUMB, "-|", "$FindBin::Bin/mpdthumb.sh", @opts, "--", @_;
150 $thumb = "$c$thumb$c" if (-f $thumb);
151 push @results, $thumb;
154 die("mpdthumb failed") if ($?);
159 # add_track_metadata(hashref, key, value)
161 # Inserts the given key into the referenced hash; if the key already exists
162 # in the hash then the hash element is converted to an array reference (if
163 # it isn't already) and the value is appended to that array.
164 sub add_track_metadata {
165 my ($entry, $key, $value) = @_;
167 if (exists($entry->{$key})) {
168 my $ref = $entry->{$key};
170 if (reftype($ref) ne "ARRAY") {
171 return if ($ref eq $value);
174 $entry->{$key} = $ref;
177 push(@$ref, $value) unless (any {$_ eq $value} @$ref);
179 $entry->{$key} = $value;
183 # get_track_metadata(hashref, key)
185 # Return the values associated with the given metadata key as a list.
186 sub get_track_metadata {
187 my ($entry, $key) = @_;
189 return () unless (exists($entry->{$key}));
191 my $ref = $entry->{$key};
192 return @$ref if (reftype($ref) eq "ARRAY");
196 # Given a music filename, search for the cover art in the same directory.
197 sub mpd_cover_filename {
201 $dir =~ s/\/[^\/]*$//;
202 foreach ("cover.png", "cover.jpg", "cover.tiff", "cover.bmp") {
208 return unless defined $file;
210 # Follow one level of symbolic link to get to the scans directory.
211 $file = readlink($file) // $file;
212 $file = "$dir/$file" unless ($file =~ /^\//);
216 # Generate the cover art entry in the top menu.
217 sub top_track_cover {
220 ($entry->{thumb}) = get_item_thumbnails($entry->{file});
221 print "$entry->{thumb}\n";
222 if ($entry->{thumb}) {
223 my $file = "$MUSIC/$entry->{file}";
224 my $cover = mpd_cover_filename($file);
226 $cover = fvwm_shell_literal($cover // $file);
227 fvwm_cmd_unquoted("AddToMenu", MPD::escape($menu),
228 MPD::escape($entry->{thumb}),
229 "Exec", "exec", "geeqie", $cover);
233 # Generate the "Title:" entry in the top menu.
234 sub top_track_title {
238 my ($mbid) = get_track_metadata($entry, "MUSICBRAINZ_RELEASETRACKID");
239 @submenu = make_submenu("$menu-$mbid", "--track-id=$mbid") if $mbid;
241 fvwm_cmd("AddToMenu", $menu,
242 fvwm_label_escape("Title:\t$entry->{Title}"),
246 # Generate the "Artist:" entry in the top menu.
247 sub top_track_artist {
251 # TODO: multi-artist tracks should get multiple artist menus; for now
252 # just combine the releases from all artists.
253 my @mbids = get_track_metadata($entry, "MUSICBRAINZ_ARTISTID");
255 @submenu = make_submenu("$menu-TopArtist",
256 map { "--artist-id=$_" } @mbids);
259 fvwm_cmd("AddToMenu", $menu,
260 fvwm_label_escape("Artist:\t$entry->{Artist}"),
264 # Generate the "Album:" entry in the top menu.
265 sub top_track_album {
269 my ($mbid) = get_track_metadata($entry, "MUSICBRAINZ_ALBUMID");
270 @submenu = make_submenu("$menu-$mbid", "--album-id=$mbid") if $mbid;
272 fvwm_cmd("AddToMenu", $menu,
273 fvwm_label_escape("Album:\t$entry->{Album}"),
277 # Given a work MBID, return a hash reference containing all tracks
278 # linked to that work. The hash keys are filenames.
279 sub get_tracks_by_work_mbid {
283 foreach my $mbid (@_) {
284 mpd_exec("search", "(MUSICBRAINZ_WORKID == \"$mbid\")");
289 if (/^(\w+): (.*)$/) {
291 if (exists($matches{$2})) {
292 $entry = $matches{$2};
295 $matches{$2} = $entry;
299 add_track_metadata($entry, $1, $2);
307 # Given a track MBID, return a hash reference containing all "related"
308 # tracks in the MPD database. The hash keys are filenames.
310 # Currently tracks are considered "related" if their associated recordings
311 # have at least one work in common.
312 sub get_tracks_by_track_mbid {
318 return \%matches unless ($mbid);
319 mpd_exec("search", "(MUSICBRAINZ_RELEASETRACKID == \"$mbid\")");
324 if (/^(\w+): (.*)$/) {
325 add_track_metadata(\%source, $1, $2);
329 # Always include the current track
330 $matches{$source{file}} = \%source;
332 # Find all tracks related by work
333 foreach my $mbid (get_track_metadata(\%source, "MUSICBRAINZ_WORKID")) {
334 my $related = get_tracks_by_work_mbid($mbid);
335 foreach (keys %$related) {
336 $matches{$_} //= $related->{$_};
343 # Given a release MBID, return a hash reference containing all its
344 # associated tracks in the MPD database. The hash keys are filenames.
345 sub get_tracks_by_release_mbid {
350 return \%matches unless ($mbid);
351 mpd_exec("search", "(MUSICBRAINZ_ALBUMID == \"$mbid\")");
356 if (/^(\w+): (.*)$/) {
358 if (exists($matches{$2})) {
359 $entry = $matches{$2};
362 $matches{$2} = $entry;
366 add_track_metadata($entry, $1, $2);
373 # Given an artist MBID, return a hash reference containing associated
374 # releases in the MPD database. The hash keys are release MBIDs.
376 # Since MPD returns results on a per-track basis, each entry in the
377 # hash has the metadata for one unspecified track from that release.
378 sub get_releases_by_artist_mbid {
382 foreach my $mbid (@_) {
383 mpd_exec("search", "(MUSICBRAINZ_ARTISTID == \"$mbid\")");
388 if (/^(\w+): (.*)$/) {
391 } elsif ($1 eq "MUSICBRAINZ_ALBUMID") {
392 $releases{$2} //= $entry;
395 add_track_metadata($entry, $1, $2);
403 # Given a filename, return the IDs (if any) for that file in the
404 # current MPD play queue.
405 sub get_ids_by_filename {
409 mpd_exec("playlistfind", "file", $file);
414 if (/^(\w+): (.*)$/) {
415 push @results, $2 if ($1 eq "Id");
422 # albumsort(matches, a, b)
424 # Sort hash keys (a, b) by disc/track number for album menus.
426 my ($matches, $a, $b) = @_;
428 return $matches->{$a}->{Disc} <=> $matches->{$b}->{Disc}
429 || $matches->{$a}->{Track} <=> $matches->{$b}->{Track}
433 # datesort(matches, a, b)
435 # Sort hash keys (a, b) by release date
437 my ($matches, $a, $b) = @_;
439 return $matches->{$a}->{Date} cmp $matches->{$b}->{Date}
443 # menu_trackname(entry)
445 # Format the track name for display in an FVWM menu, where entry
446 # is a hash reference containing the track metadata.
449 my $fmt = "$entry->{trackfmt}$entry->{Artist} - $entry->{Title}";
450 return "$entry->{thumb}" . fvwm_label_escape($fmt);
456 Copyright © 2019 Nick Bowler
457 License GPLv3+: GNU General Public License version 3 or any later version.
458 This is free software: you are free to change and redistribute it.
459 There is NO WARRANTY, to the extent permitted by law.
464 my $fh = $_[1] // *STDERR;
466 print $fh "Usage: $0 [options]\n";
467 print "Try $0 --help for more information.\n" unless (@_ > 0);
471 print_usage(*STDOUT);
473 This is "mpdmenu": a menu-based MPD client for FVWM.
476 -h, --host=HOST Connect to the MPD server on HOST, overriding defaults.
477 -p, --port=PORT Connect to the MPD server on PORT, overriding defaults.
478 -m, --menu=NAME Set the name of the generated menu.
479 --album-id=MBID Generate a menu for the given release MBID.
480 --artist-id=MBID Generate a menu for the given artist MBID.
481 --track-id=MBID Generate a menu for the given track MBID.
482 -V, --version Print a version message and then exit.
483 -H, --help Print this message and then exit.
488 'host|h=s' => \$MPD::host,
489 'port|p=s' => \$MPD::port,
490 'menu|m=s' => \$menu,
492 'artist-id=s' => sub { $artistids{$_[1]} = 1; $mode = "artist"; },
493 'album-id=s' => sub { $albumid = $_[1]; $mode = "album"; },
494 'track-id=s' => sub { $trackid = $_[1]; $mode = "track"; },
496 'V|version' => sub { print_version(); exit },
497 'H|help' => sub { print_help(); exit },
499 'topmenu=s' => \$topmenu, # top menu name (for submenu generation)
500 ) or do { print_usage; exit 1 };
502 unless (defined $menu) {
503 $topmenu //= "MenuMPD";
504 $menu = $topmenu . ($mode ne "top" ? $mode : "");
509 $sock = MPD::connect();
510 die("MPD version $MPD::major.$MPD::minor.$MPD::revision insufficient.")
511 unless MPD::min_version(MPD_MJR_MIN, MPD_MNR_MIN, MPD_REV_MIN);
513 if ($mode eq "top") {
524 if (/^(\w+): (.*)$/) {
529 mpd_exec("currentsong");
534 if (/^(\w+): (.*)$/) {
535 add_track_metadata(\%current, $1, $2);
539 my $playstate = $state{state} eq "play" ? "Playing"
540 : $state{state} eq "stop" ? "Stopped"
541 : $state{state} eq "pause" ? "Paused"
543 fvwm_cmd("AddToMenu", $menu, $playstate, "Title");
545 if (exists($current{file})) {
546 top_track_cover(\%current);
547 top_track_title(\%current);
548 top_track_artist(\%current);
549 top_track_album(\%current);
551 fvwm_cmd("AddToMenu", $menu, "[current track unavailable]");
554 if ($state{state} =~ /^p/) {
555 my $pp = $state{state} eq "pause" ? "lay" : "ause";
557 fvwm_cmd("AddToMenu", $menu, "", "Nop");
558 fvwm_cmd("AddToMenu", $menu, "Next%next.svg:16x16%",
559 "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "next");
560 fvwm_cmd("AddToMenu", $menu, "P$pp%p$pp.svg:16x16%",
561 "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "p$pp");
562 fvwm_cmd("AddToMenu", $menu, "Stop%stop.svg:16x16%",
563 "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "stop");
564 fvwm_cmd("AddToMenu", $menu, "Prev%prev.svg:16x16%",
565 "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "previous");
566 } elsif ($state{state} eq "stop") {
567 fvwm_cmd("AddToMenu", $menu, "", "Nop");
568 fvwm_cmd("AddToMenu", $menu, "Play%play.svg:16x16%",
569 "Exec", "exec", "$FindBin::Bin/mpdexec.pl", "play");
571 } elsif ($mode eq "album") {
572 my $matches = get_tracks_by_release_mbid($albumid);
575 $menu //= "MenuMPDAlbum";
577 my $track_max = max(map { $_->{Track} } values %$matches);
578 my $disc_max = max(map { $_->{Disc} } values %$matches);
580 # CDs have a max of 99 tracks and I hope 100+-disc-releases
581 # don't exist so this is fine.
582 my $track_digits = $track_max >= 10 ? 2 : 1;
583 my $disc_digits = $disc_max > 1 ? $disc_max >= 10 ? 2 : 1 : 0;
586 fvwm_cmd("AddToMenu", $menu);
587 fvwm_cmd("+", "Release not found", "Title") unless keys %$matches;
588 foreach my $file (sort { albumsort($matches, $a, $b) } keys %$matches) {
589 my $entry = $matches->{$file};
591 # Format disc/track numbers
592 $entry->{trackfmt} = sprintf("%*.*s%.*s%*d\t",
593 $disc_digits, $disc_digits, $entry->{Disc},
595 $track_digits, $entry->{Track});
596 $entry->{trackfmt} =~ s/ /\N{U+2007}/g;
598 unless (exists $entry->{Id}) {
599 my ($id) = get_ids_by_filename($file);
603 push @notqueued, $entry;
608 if (defined $currentdisc && $currentdisc != $entry->{Disc}) {
609 fvwm_cmd("+", "", "Nop");
611 $currentdisc = $entry->{Disc};
613 fvwm_cmd("+", menu_trackname($entry), "Exec",
614 "exec", "$FindBin::Bin/mpdexec.pl",
615 "playid", $entry->{Id});
618 fvwm_cmd("+", "Not in play queue", "Title") if @notqueued;
619 foreach my $entry (@notqueued) {
620 fvwm_cmd("+", menu_trackname($entry));
622 } elsif ($mode eq "artist") {
623 # Create an artist menu.
624 my $matches = get_releases_by_artist_mbid(keys %artistids);
627 $menu //= "MenuMPDArtist";
629 my @mbids = sort { datesort($matches, $a, $b) } keys %$matches;
630 my @files = map { $matches->{$_}->{file} } @mbids;
631 my @thumbs = get_item_thumbnails({ small => 1 }, @files);
632 fvwm_cmd("AddToMenu", $menu, "No releases found", "Title") unless @mbids;
634 foreach my $mbid (@mbids) {
635 my $entry = $matches->{$mbid};
636 my $thumb = shift @thumbs;
638 my @submenu = make_submenu("$topmenu-$mbid",
640 fvwm_cmd("AddToMenu", $menu,
641 $thumb . fvwm_label_escape($entry->{Album}),
644 } elsif ($mode eq "track") {
645 my $matches = get_tracks_by_track_mbid($trackid);
648 $menu //= "MenuMPDTrack";
650 my @files = sort { datesort($matches, $a, $b) } keys %$matches;
651 my @thumbs = get_item_thumbnails({ small => 1 }, @files);
653 fvwm_cmd("AddToMenu", $menu);
654 fvwm_cmd("+", "No tracks found", "Title") unless @files;
655 foreach my $file (@files) {
656 my $entry = $matches->{$file};
657 $entry->{thumb} = shift @thumbs;
659 unless (exists $entry->{Id}) {
660 my ($id) = get_ids_by_filename($file);
664 push @notqueued, $entry;
669 fvwm_cmd("+", menu_trackname($entry), "Exec",
670 "exec", "$FindBin::Bin/mpdexec.pl",
671 "playid", $entry->{Id});
674 fvwm_cmd("+", "Not in play queue", "Title") if @notqueued;
675 foreach my $entry (@notqueued) {
676 fvwm_cmd("+", menu_trackname($entry));
681 print $sock "close\n";