scripts/sxiv_browser.sh
2018-10-20 19:13:27 +03:00

81 lines
2.7 KiB
Bash
Executable File

#!/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 calling the shell function 'abspath' 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.
#
# Implementation notes (lanxu): I wanted to add Natural Ordering support to the
# script. Therefore, I decided to use ls with '-v' flag and pass it to awk
# which adds the required null terminator. Additionally, I added max-chars
# parameter for xargs because I was hitting the default limit with my
# abnormally large image directories (5000+ files).
#
# vim: set tabstop=8 softtabstop=0 shiftwidth=4 expandtab smarttab
if [ $# -eq 0 ]; then
echo "Usage: ${0##*/} PICTURES"
exit
fi
[ "$1" == '--' ] && shift
abspath () {
case "$1" in
/*) printf "%s\n" "$1";;
*) printf "%s\n" "$PWD/$1";;
esac
}
listfiles () {
#find -L "$(dirname "$target")" -maxdepth 1 -type f -iregex '.*\(jpe?g\|bmp\|png\|gif\)$' -print0 | sort -z
ls -dv "$(dirname "$target")"/* | egrep '.*(jpe?g|bmp|png|gif)$' | awk '{print}' ORS='\0'
}
isarchive () {
FILE_PATH="${1}"
FILE_EXTENSION="${FILE_PATH##*.}"
FILE_EXTENSION_LOWER="${FILE_EXTENSION,,}"
MIMETYPE="$(xdg-mime query filetype "$1" )"
case "${FILE_EXTENSION_LOWER}" in
a|ace|alz|arc|arj|bz|bz2|cab|cpio|deb|gz|jar|lha|lz|lzh|lzma|lzo|\
rar|rpm|rz|t7z|tar|tbz|tbz2|tgz|tlz|txz|tZ|tzo|war|xpi|xz|Z|zip|7z)
return 0
esac
case "${FILE_EXTENSION_LOWER}" in
cbz|cbr)
return 0
esac
return -1
}
target="$(abspath "$1")"
if isarchive "$target"; then
TEMPDIR=$(mktemp -d)
atool --quiet --extract-to=$TEMPDIR --each -- "$target" 2&> /dev/null
find $TEMPDIR/**/* -print0 | xargs -0 -n 1 -Ifoo cp "foo" $TEMPDIR/
target=$TEMPDIR/.
fi
count="$(listfiles | grep -m 1 -ZznF "$target" | cut -d: -f1)"
if [ -n "$count" ]; then
listfiles | xargs -s 1280000 -0 sxiv -an "$count" --
else
sxiv -- "$target" # fallback
fi