#!/bin/sh
+#
+# Copyright © 2008, 2017 Nick Bowler
+#
# Generates an FVWM menu for selecting the PNG images found in a given
-# directory. Thumbnails for the images are generated on the fly using convert
-# from ImageMagick, and stored in the .thumbs subdirectory. The menu items
-# run the specified function with the filename as the first argument.
+# directory. Thumbnails for the images are generated on the fly using
+# the thumbnailer.zsh script. Menu items run the specified function
+# with the filename as the first argument.
-menu="MenuWallpaper"
-func="SetWallpaper"
-thumber="$HOME/.fvwm/scripts/thumbnail.sh"
+thumber="$FVWM_USERDIR/scripts/thumbnail.zsh --size x160"
+xaspect=$FVWM_USERDIR/scripts/C/xaspect
+menu=MenuWallpaper
+func=SetWallpaper
-if [ ! -d "$1" ]; then
- echo "usage: $0 <directory> [menuname]" 1>&2
- exit 1
-fi
-[ -n "$2" ] && menu="$2"
+lastarg=
+dashdash=
+for arg; do
+ if test ${lastarg:+y}; then
+ arg=$lastarg=$arg
+ lastarg=
+ fi
-for i in "$1"/*.png; do
- thumb="`$thumber --size x160 "$i"`"
- echo "AddToMenu $menu \"`basename "${i%.png}"`*$thumb*\" $func \"$i\""
+ case $dashdash$arg in
+ --menu=*) menu=${arg#--menu=} ;;
+ --func=*) func=${arg#--func=} ;;
+ --menu|--func) lastarg=$arg ;;
+ --) dashdash=: ;;
+ -*) printf '%s: unrecognized argument: %s\n' "$0" "$arg" 1>&2; exit 1 ;;
+ *) set x "$@" "$arg"; shift
+ esac
+
+ shift
done
+
+case $# in
+1) dir=$1 ;;
+*) printf 'usage: %s [options] directory\n' "$0" 1>&2
+esac
+
+size=`$xaspect -dimensions`
+find $1 -maxdepth 1 -name "*$size.png" -print0 -exec $thumber {} \; |
+ awk -F '\0' '{
+ gsub(/["\\]/, "\\\\&");
+ caption = gensub(/.*\/(.*)\..*/, "\\1", 1, $1);
+ print "AddToMenu", menuname, "\"" caption "*" $2 "*\"",
+ funcname, "\"" $1 "\""
+ }' "menuname=$menu" "funcname=$func"