about summary refs log tree commit diff stats
path: root/examples/rifle_sxiv.sh
blob: 68b6d21c7f89ae8282f83d8b3d313b140a6c7b47 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/bin/sh
# Compatible with ranger 1.6.0 through 1.7.*
#
# This script searches image files in a directory, opens them all with sxiv and
# sets the first argument to the first image displayed by sxiv.
#
# This is supposed to be used in rifle.conf as a workaround for the fact that
# sxiv takes no file name arguments for the first image, just the number.  Copy
# this file somewhere into your $PATH and add this at the top of rifle.conf:
#
#   mime ^image, has sxiv, X, flag f = path/to/this/script -- "$@"
#
# Implementation notes: this script is quite slow because of POSIX limitations
# and portability concerns. First, using case statement to get absolute path is
# quicker than calling 'realpath' because it would fork a whole process, which
# is slow. Second, we need to append a file list to sxiv, which can only be done
# properly in two ways: arrays (which are not POSIX) or \0 sperated
# strings. Unfortunately, assigning \0 to a variable is not POSIX either (will
# not work in dash and others), so we cannot store the result of listfiles to a
# variable.

tmp="/tmp/sxiv_rifle_$$"

listfiles () {
    find -L "///${target%/*}" -maxdepth 1 -type f -iregex \
      '.*\.\(jpe?g\|png\|gif\|webp\|tiff\|bmp\)$' -print | sort | tee "$tmp"
}

is_img () {
    case "${1##*.}" in
        "jpg"|"jpeg"|"png"|"gif"|"webp"|"tiff"|"bmp") return 0 ;;
        *) return 1 ;;
    esac
}

[ "$1" = '--' ] && shift
case "$1" in
    "") echo "Usage: ${0##*/} PICTURES" >/dev/stderr && exit ;;
    /*) target="$1" ;;
    "~"/*) target="$HOME/${1#"~"/}" ;;
    *)  target="$PWD/$1" ;;
esac

trap "rm -f $tmp" EXIT
is_img "$target" && count="$(listfiles | grep -nF "$target")"

if [ -n "$count" ]; then
    sxiv -i -n "${count%%:*}" -- < "$tmp"
else
    sxiv -- "$@" # fallback
fi