commit 0c09bba14ad217569827379ebdcde22d3440e99d parent 9ce3fae4a48d4e217c7f54dd138a9571b454dc6c Author: Anders Damsgaard <anders@adamsgaard.dk> Date: Thu, 8 Oct 2020 10:25:59 +0200 maimpick: autoconvert to jpeg if smaller and support saving to X selection Diffstat:
M | .local/bin/maimpick | | | 100 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------- |
1 file changed, 72 insertions(+), 28 deletions(-)
diff --git a/.local/bin/maimpick b/.local/bin/maimpick @@ -1,33 +1,77 @@ #!/bin/sh set -e -c="$(printf 'area\nwindow\nscreen' | dmenu -i)" -out="$(printf 'tmp/pic-%s-%s.png' "$c" "$(date '+%y-%m-%d_%H:%M:%S')" | dmenu -l 1 -p "outfile:")" +#selection="primary" +selection="clipboard" -if [ ! "${out##*.}" = "png" ]; then - out="${out}.png" -fi +die() +{ + printf '%s: %s\n' "${0##*/}" "$1" >&2 + exit 1 +} + +choose_mode() +{ + printf 'area\nwindow\nscreen' | dmenu -i +} + +choose_output_target() +{ + printf 'file\nclipboard' | dmenu -i -p "output:" +} + +name_outfile() +{ + out="$(printf 'tmp/pic-%s-%s.png' "$1" "$(date '+%y-%m-%d_%H:%M:%S')" | \ + dmenu -l 1 -p "outfile:")" + if [ ! "${out##*.}" = "png" ]; then + out="${out}.png" + fi + printf '%s/%s' "$HOME" "$out" +} -case "$c" in - area) - maim --hidecursor -s "$out" ;; - window) - maim --hidecursor -i "$(xdotool getactivewindow)" "$out" ;; - screen) - maim "$out" ;; -esac - -c="$(printf 'no\nyes' | dmenu -i -p "convert to jpg?")" -case "$c" in - yes) - convert "$out" "${out%.png}.jpg" - rm "$out" - out="${out%.png}.jpg";; -esac - -case "$out" in - /*) - printf '%s' "$out" | xclip -i;; - *) - printf '%s/%s' "$HOME" "$out" | xclip -i;; -esac +take_screenshot() +{ + case "$1" in + area) + maim --hidecursor -s "$2";; + window) + maim --hidecursor -i "$(xdotool getactivewindow)" "$2";; + screen) + maim "$2";; + *) + die "mode $1 not understood";; + esac +} + +post_process_output() +{ + out="$1" + out_jpeg="${out%.png}.jpg" + format="png" + convert "${out}" "${out_jpeg}" + if [ "$(stat -f "%z" "${out_jpeg}")" -lt "$(stat -f "%z" "${out}")" ]; then + format="jpeg" + rm "${out}" + out="${out_jpeg}" + else + rm "${out_jpeg}" + fi + if [ "$target" = "clipboard" ]; then + xclip -t "image/${format}" -selection "$selection" "${out}" + rm "${out}" + else + printf '%s' "${out}" | xclip -i -selection "$selection" + printf '%s\n' "${out}" + fi +} + +mode="$(choose_mode)" +target="$(choose_output_target)" +if [ "$target" = "file" ]; then + f="$(name_outfile "$mode")" +else + f="$(mktemp).png" +fi +take_screenshot "$mode" "$f" +post_process_output "$f"