#!/usr/bin/env sh

# Description: Terminal based file previewer
#
# Note: This plugin needs a "NNN_FIFO" to work. See man.
#
# Dependencies:
#    - Supports 3 independent methods to preview with:
#        - tmux (>=3.0), or
#        - kitty with allow_remote_control on, or
#        - $TERMINAL set to a terminal (it's xterm by default).
#    - less or $PAGER
#    - tree or exa or ls
#    - mediainfo or file
#    - mktemp
#    - unzip
#    - tar
#    - man
#    - optional: bsdtar or atool for additional archive preview
#    - optional: bat for code syntax highlighting
#    - optional: ueberzug, kitty terminal, viu or catimg for images.
#    - optional: convert(ImageMagick) for playing gif preview
#    - optional: ffmpegthumbnailer for video thumbnails (https://github.com/dirkvdb/ffmpegthumbnailer).
#    - optional: ffmpeg for audio thumbnails
#    - optional: libreoffce for opendocument/officedocument preview
#    - optional: pdftoppm(poppler) for pdf thumbnails
#    - optional: gnome-epub-thumbnailer for epub thumbnails (https://gitlab.gnome.org/GNOME/gnome-epub-thumbnailer)
#    - optional: fontpreview for font preview (https://github.com/sdushantha/fontpreview)
#    - optional: glow or lowdown for markdown
#    - optional: w3m or lynx or elinks for html
#    - optional: scope.sh file viewer from ranger.
#                To use:
#                1. drop scope.sh executable in $PATH
#                2. set/export $USE_SCOPE as 1
#    - optional: pistol file viewer (https://github.com/doronbehar/pistol).
#                To use:
#                1. install pistol
#                2. set/export $USE_PISTOL as 1
#
# Usage:
#   You need to set a NNN_FIFO path and a key for the plugin with NNN_PLUG,
#   then start `nnn`:
#
#     $ nnn -a
#
#   or
#
#     $ NNN_FIFO=/tmp/nnn.fifo nnn
#
#   Then in `nnn`, launch the `preview-tui` plugin.
#
#   If you provide the same NNN_FIFO to all nnn instances, there will be a
#   single common preview window. If you provide different FIFO path (e.g.
#   with -a), they will be independent.
#
#   The previews will be shown in a tmux split. If that isn't possible, it
#   will try to use a kitty terminal split. And as a final fallback, a
#   different terminal window will be used ($TERMINAL).
#
#   Tmux and kitty users can configure $SPLIT to either "h" or "v" to set a
#   'h'orizontal split or a 'v'ertical split (as in, the line that splits the
#   windows will be horizontal or vertical).
#
#   Kitty users need `allow_remote_control` set to `yes`. To customize the
#   window split, `enabled_layouts` has to be set to `all` or `splits` (the
#   former is the default value). This terminal is also able to show images
#   without extra dependencies.
#
# Shell: POSIX compliant
# Authors: Todd Yamakawa, Léo Villeveygoux, @Recidiviste, Mario Ortiz Manero, Luuk van Baal

SPLIT="$SPLIT"  # you can set a permanent split here
TERMINAL="$TERMINAL"  # same goes for the terminal
USE_SCOPE="${USE_SCOPE:-0}"
USE_PISTOL="${USE_PISTOL:-0}"
PAGER="${PAGER:-less -P?n -R}"
ARCHIVES="$(echo "$NNN_ARCHIVE" | sed 's/.*(\(.*\)).*/\1/;s/|/ /g')"
TMPDIR="${TMPDIR:-/tmp}"
NUMPREVIEWTUI="$(($(find "$TMPDIR" -maxdepth 1 -name 'nnn-preview-tui-pagerpid*' 2>/dev/null | wc -l) + 1))"
PAGERPID="$TMPDIR/nnn-preview-tui-pagerpid.$NUMPREVIEWTUI"
GIFPID="$TMPDIR/nnn-preview-tui-gifpid.$NUMPREVIEWTUI"
CURSEL="$TMPDIR/nnn-preview-tui-selection.$NUMPREVIEWTUI"
FIFO_UEBERZUG="$TMPDIR/nnn-preview-tui-ueberzug-fifo.$NUMPREVIEWTUI"

[ "$PAGER" = "most" ] && PAGER="less -R"

if [ -e "${TMUX%%,*}" ] && tmux -V | grep -q '[ -][3456789]\.'; then
    TERMINAL=tmux
elif [ -n "$KITTY_WINDOW_ID" ] && kitty @ ls >/dev/null 2>&1; then
    TERMINAL=kitty
else
    TERMINAL="${TERMINAL:-xterm}"
fi

if [ -z "$SPLIT" ] && [ $(($(tput lines) * 2)) -gt "$(tput cols)" ]; then
    SPLIT='h'
elif [ "$SPLIT" != 'h' ]; then
    SPLIT='v'
fi

exists() {
    which "$1" >/dev/null 2>&1
}

fifo_pager() {
    cmd="$1"
    shift

    # We use a FIFO to access $PAGER PID in jobs control
    tmpfifopath="$TMPDIR/nnn-preview-tui-fifo.$$"
    mkfifo "$tmpfifopath" || return

    $PAGER < "$tmpfifopath" &
    echo "$!" > "$PAGERPID"

    (
        exec > "$tmpfifopath"
        "$cmd" "$@" &
    )

    rm "$tmpfifopath"
}

# Binary file: show file info inside the pager
print_bin_info() {
    printf -- "-------- \033[1;31mBinary file\033[0m --------\n"
    if exists mediainfo; then
        mediainfo "$1" 2>/dev/null
    else
        file -b "$1"
    fi
}

preview_file () {
    clear
    # Trying to use pistol if it's available.
    if [ "$USE_PISTOL" -ne 0 ] && exists pistol; then
        fifo_pager pistol "$1"
        return
    fi

    # Trying to use scope.sh if it's available.
    if [ "$USE_SCOPE" -ne 0 ] && exists scope.sh; then
        fifo_pager scope.sh "$1" "$cols" "$lines" "$(mktemp -d)" \
            "True" 2>/dev/null
        return
    fi

    # Detecting the exact type of the file: the encoding, mime type, and
    # extension in lowercase.
    encoding="$(file -bL --mime-encoding -- "$1")"
    mimetype="$(file -bL --mime-type -- "$1")"
    ext="${1##*.}"
    if [ -n "$ext" ]; then
        ext="$(printf "%s" "${ext}" | tr '[:upper:]' '[:lower:]')"
    fi
    lines=$(tput lines)
    cols=$(tput cols)

    # Otherwise, falling back to the defaults.
    if [ -d "$1" ]; then
        cd "$1" || return
        if exists tree; then
            fifo_pager tree -L 1 --dirsfirst -F -C
        elif exists exa; then
            fifo_pager exa -G --colour=always 2>/dev/null
        else
            fifo_pager ls --color=always
        fi
    elif [ "$encoding" = "binary" ]; then
        if [ "$ext" = "gif" ]; then
            generate_preview "$cols" "$lines" "$1" "gif"
        elif [ "${mimetype#*/}" = "x-xcf" ]; then
            generate_preview "$cols" "$lines" "$1" "xcf"
        elif [ "${mimetype%%/*}" = "image" ]; then
            image_preview "$cols" "$lines" "$1"
        elif [ "${mimetype%%/*}" = "audio" ] && exists ffmpeg; then
            generate_preview "$cols" "$lines" "$1" "audio"
        elif [ "${mimetype%%/*}" = "video" ] && exists ffmpegthumbnailer; then
            generate_preview "$cols" "$lines" "$1" "video"
        elif [ "$ext" = "pdf" ] && exists pdftoppm; then
            generate_preview "$cols" "$lines" "$1" "pdf"
        elif [ "$ext" = "epub" ] && exists gnome-epub-thumbnailer; then
            generate_preview "$cols" "$lines" "$1" "epub"
        elif [ "${mimetype#*opentype}" != "$mimetype" ] || [ "${mimetype#*font}" != "$mimetype" ] && exists fontpreview; then
            generate_preview "$cols" "$lines" "$1" "font"
        elif [ "${mimetype#*office}" != "$mimetype" ] || [ "${mimetype#*document}" != "$mimetype" ] && exists libreoffice; then
            generate_preview "$cols" "$lines" "$1" "office"
        elif [ "${ARCHIVES#*$ext}" != "$ARCHIVES" ]; then
            if exists bsdtar; then
                fifo_pager bsdtar -tvf "$1"
            elif exists atool; then
                fifo_pager atool -l "$1"
            fi
        elif [ "$mimetype" = "application/zip" ]; then
            fifo_pager unzip -l "$1"
        elif [ "$ext" = "gz" ] || [ "$ext" = "bz2" ]; then
            fifo_pager tar -tvf "$1"
        else
            fifo_pager print_bin_info "$1"
        fi
    elif [ "$ext" = "md" ]; then
        if exists glow; then
            fifo_pager glow -s dark "$1"
        elif exists lowdown; then
            lowdown -Tterm "$1"
        fi
    elif [ "$ext" = "htm" ] || [ "$ext" = "html" ] || [ "$ext" = "xhtml" ]; then
        if exists w3m; then
            fifo_pager w3m "$1"
        elif exists lynx; then
            fifo_pager lynx "$1"
        elif exists elinks; then
            fifo_pager elinks "$1"
        fi
    elif [ "$mimetype" = "text/troff" ]; then
        fifo_pager man -Pcat -l "$1"
    else
        if exists bat; then
            fifo_pager bat --terminal-width="$cols" --paging=never --decorations=always --color=always \
                "$1" 2>/dev/null
        else
            $PAGER "$1" &
        fi
    fi
}

generate_preview() {
    if [ ! -f "$TMPDIR/$3.jpg" ]; then
        mkdir -p "$TMPDIR/${3%/*}"
        case $4 in
            audio) ffmpeg -i "$3" "$TMPDIR/$3.jpg" -y >/dev/null 2>&1 ;;
            epub) gnome-epub-thumbnailer "$3" "$TMPDIR/$3.jpg" >/dev/null 2>&1 ;;
            font) fontpreview -i "$3" -o "$TMPDIR/$3.jpg" >/dev/null 2>&1 ;;
            gif) if exists ueberzug && exists convert || [ "$TERMINAL" = "kitty" ]; then
                    if [ ! -d "$TMPDIR/$3" ]; then
                        mkdir -p "$TMPDIR/$3"
                        convert -coalesce "$3" "$TMPDIR/$3/${3##*/}.jpg"
                    fi
                        while true; do
                            for frame in $(find "$TMPDIR/$3"/*.jpg | sort -V); do
                                image_preview "$1" "$2" "$frame"
                                sleep 0.1
                            done
                            [ "$LOOP_GIFS" -eq 0 ] && return
                        done &
                        echo "$!" > "$GIFPID"
                        return
                 else
                    image_preview "$1" "$2" "$3"
                    return
                 fi ;;
            office) libreoffice --convert-to jpg "$3" --outdir "$TMPDIR/${3%/*}" > /dev/null 2>&1
                    filename="$(echo "${3##*/}" | cut -d. -f1)"
                    mv "$TMPDIR/${3%/*}/$filename.jpg" "$TMPDIR/$3.jpg" ;;
            pdf) pdftoppm -jpeg -f 1 -singlefile "$3" "$TMPDIR/$3" >/dev/null 2>&1 ;;
            video) if ! ffmpegthumbnailer -i "$3" -o "$TMPDIR/$3.jpg" -s 0 -q 10 >/dev/null 2>&1; then
                       rm "$TMPDIR/$3.jpg"
                       fifo_pager print_bin_info "$3"
                       return
                   fi ;;
            xcf) convert -flatten "$3" "$TMPDIR/$3.jpg" ;;
        esac
    fi
    if [ -f "$TMPDIR/$3.jpg" ]; then
        image_preview "$1" "$2" "$TMPDIR/$3.jpg"
    else
        fifo_pager print_bin_info "$3"
    fi
}

image_preview() {
    clear
    if [ "$TERMINAL" = "kitty" ]; then
        # Kitty terminal users can use the native image preview method.
        kitty +kitten icat --silent --place "$1"x"$2"@0x0 --transfer-mode=stream --stdin=no \
            "$3"
    elif exists ueberzug; then
        ueberzug_layer "$1" "$2" "$3"
    elif exists catimg; then
        catimg "$3" &
        echo "$!" > "$GIFPID"
    elif exists viu; then
        viu -t "$3" &
        echo "$!" > "$GIFPID"
    else
        fifo_pager print_bin_info "$3"
    fi
}

ueberzug_layer() {
    printf '{"action": "add", "identifier": "nnn_ueberzug", "x": 0, "y": 0, "width": "%s", "height": "%s", "scaler": "fit_contain", "path": "%s"}\n' "$1" "$2" "$3" > "$FIFO_UEBERZUG"
}

ueberzug_remove() {
    printf '{"action": "remove", "identifier": "nnn_ueberzug"}\n' > "$FIFO_UEBERZUG"
}

ueberzug_refresh() {
    clear
    kill "$(cat "$GIFPID" 2>/dev/null)" >/dev/null 2>&1
    pkill -P "$$" >/dev/null 2>&1
    pkill -f -n preview-tui-ext >/dev/null 2>&1
    tail --follow "$FIFO_UEBERZUG" | ueberzug layer --silent --parser json &
    preview_file "$(cat "$CURSEL")"
    echo > "$NNN_FIFO"
    preview_fifo &
    wait
}
if [ "$TERMINAL" != "kitty" ] && [ "$PREVIEW_MODE" ] && exists ueberzug; then
    trap 'ueberzug_refresh' WINCH
    trap 'rm "$FIFO_UEBERZUG" "$PAGERPID" "$GIFPID" "$CURSEL"' INT HUP EXIT
fi

preview_fifo() {
    # use cat instead of 'exec <' to avoid issues with dash shell
    # shellcheck disable=SC2002
    cat "$NNN_FIFO" |\
    while read -r selection ; do
        kill "$(cat "$GIFPID" 2>/dev/null)" >/dev/null 2>&1
        kill "$(cat "$PAGERPID" 2>/dev/null)" >/dev/null 2>&1
        [ "$TERMINAL" != "kitty" ] && exists ueberzug && ueberzug_remove
        preview_file "$selection"
        echo "$selection" > "$CURSEL"
    done
    [ "$TERMINAL" != "kitty" ] && exists ueberzug && rm "$FIFO_UEBERZUG"
    rm "$PAGERPID" "$GIFPID" "$CURSEL" >/dev/null 2>&1
    pkill -P "$$" >/dev/null 2>&1
}


if [ "$PREVIEW_MODE" ]; then
    if [ ! -r "$NNN_FIFO" ]; then
        echo "No FIFO available! (\$NNN_FIFO='$NNN_FIFO')" >&2
        read -r
        exit 1
    fi

    if [ "$TERMINAL" != "kitty" ] && exists ueberzug; then
        mkfifo "$FIFO_UEBERZUG"
        tail --follow "$FIFO_UEBERZUG" | ueberzug layer --silent --parser json &
    fi

    preview_file "$1"
    preview_fifo &
    wait

    # Restoring the previous layout for kitty users. This will only work for
    # kitty >= 0.18.0.
    if [ "$TERMINAL" = "kitty" ]; then
        kitty @ last-used-layout --no-response >/dev/null 2>&1
    fi

    exit 0
fi

if [ "$TERMINAL" = "tmux" ]; then
    # tmux splits are inverted
    if [ "$SPLIT" = "v" ]; then SPLIT="h"; else SPLIT="v"; fi

    tmux split-window -e "NNN_FIFO=$NNN_FIFO" -e "PREVIEW_MODE=1" -d"$SPLIT" "$0" "$1"
elif [ "$TERMINAL" = "kitty" ]; then
    # Setting the layout for the new window. It will be restored after the
    # script ends.
    kitty @ goto-layout splits >/dev/null

    # Trying to use kitty's integrated window management as the split window.
    # All environmental variables that will be used in the new window must
    # be explicitly passed.
    kitty @ launch --no-response --title "nnn preview" --keep-focus \
          --cwd "$PWD" --env "PATH=$PATH" --env "NNN_FIFO=$NNN_FIFO" \
          --env "PREVIEW_MODE=1" --env "PAGER=$PAGER" \
          --env "USE_SCOPE=$USE_SCOPE" --env "SPLIT=$SPLIT" \
          --env "USE_PISTOL=$USE_PISTOL" \
          --location "${SPLIT}split" "$0" "$1" >/dev/null
else
    PREVIEW_MODE=1 $TERMINAL -e "$0" "$1" &
fi