]> Sergey Matveev's repositories - nnn.git/blob - plugins/preview-tui
Clear less'es screen
[nnn.git] / plugins / preview-tui
1 #!/usr/bin/env bash
2
3 # Description: Terminal based file previewer
4 #
5 # Note: This plugin needs a "NNN_FIFO" to work. See man.
6 #
7 # Dependencies:
8 #   - Supports 6 independent methods to preview with:
9 #       - tmux (>=3.0), or
10 #       - kitty with allow_remote_control and listen_on set in kitty.conf, or
11 #       - wezterm (https://wezfurlong.org/wezterm), or
12 #       - QuickLook on WSL (https://github.com/QL-Win/QuickLook), or
13 #       - Windows Terminal (https://github.com/Microsoft/Terminal | https://aka.ms/terminal) with WSL, or
14 #       - $NNN_TERMINAL set to a terminal (it's xterm by default).
15 #   - less or $NNN_PAGER
16 #   - tree or exa/eza or (GNU) ls
17 #   - mediainfo or file
18 #   - mktemp
19 #   - unzip
20 #   - tar
21 #   - man
22 #   - optional: bsdtar or atool for additional archive preview
23 #   - optional: bat for code syntax highlighting
24 #   - optional: ueberzug, kitty terminal, wezterm terminal, img2sixel, viu, catimg or chafa for images
25 #   - optional: convert(ImageMagick) for playing gif preview (mandatory for kitty image previews)
26 #   - optional: mpv for gif and video
27 #       Also requires a terminal supporting the sixel (https://www.arewesixelyet.com/)
28 #       or kitty (https://sw.kovidgoyal.net/kitty/graphics-protocol) video_output backends.
29 #       Requires tmux compiled with `./configure --enable-sixel` if used.
30 #   - optional: ffmpegthumbnailer for video thumbnails (https://github.com/dirkvdb/ffmpegthumbnailer)
31 #   - optional: ffmpeg for audio thumbnails
32 #   - optional: libreoffce for opendocument/officedocument preview
33 #   - optional: pdftoppm(poppler) for pdf thumbnails
34 #   - optional: gnome-epub-thumbnailer for epub thumbnails (https://gitlab.gnome.org/GNOME/gnome-epub-thumbnailer)
35 #   - optional: fontpreview for font preview (https://github.com/sdushantha/fontpreview)
36 #   - optional: djvulibre for djvu
37 #   - optional: glow or lowdown for markdown
38 #   - optional: w3m or lynx or elinks for html
39 #   - optional: set/export NNN_ICONLOOKUP as 1 to enable file icons in front of directory previews with .iconlookup
40 #       Icons and colors are configurable in .iconlookup
41 #   - optional: scope.sh file viewer from ranger.
42 #       1. drop scope.sh executable in $PATH
43 #       2. set/export $NNN_SCOPE as 1
44 #   - optional: pistol file viewer (https://github.com/doronbehar/pistol).
45 #       1. install pistol
46 #       2. set/export $NNN_PISTOL as 1
47 #
48 # Usage:
49 #   You need to set a NNN_FIFO path and a key for the plugin with NNN_PLUG,
50 #   then start `nnn`:
51 #
52 #     $ nnn -a
53 #
54 #   or
55 #
56 #     $ NNN_FIFO=/tmp/nnn.fifo nnn
57 #
58 #   Then launch the `preview-tui` plugin in `nnn`.
59 #
60 #   If you provide the same NNN_FIFO to all nnn instances, there will be a
61 #   single common preview window. If you provide different FIFO path (e.g.
62 #   with -a), they will be independent.
63 #
64 #   The previews will be shown in a tmux split. If that isn't possible, it
65 #   will try to use a kitty terminal split. And as a final fallback, a
66 #   different terminal window will be used ($NNN_TERMINAL).
67 #
68 #   Kitty users need something similar to the following in their kitty.conf:
69 #   - `allow_remote_control yes`
70 #   - `listen_on unix:$TMPDIR/kitty`
71 #   - `enabled_layouts splits` (optional)
72 #   With ImageMagick installed, this terminal can use the icat kitten to display images.
73 #   Refer to kitty documentation for further details.
74 #
75 #   Wezterm should work out of the box. If `NNN_PREVIEWIMGPROG` is not specified it will use
76 #   built in iTerm2 image protocol.
77 #
78 #   Note that GNU ls is used for its `--group-directories-first` flag.
79 #   On MacOS this may be installed with `brew install coreutils`, or the flag can be removed.
80 #   iTerm2 users are recommended to use viu to view images without getting pixelated.
81 #
82 #   Windows Terminal users can set "Profile termination behavior" under "Profile > Advanced" settings
83 #   to automatically close pane on quit when exit code is 0.
84 #
85 #   When specifying a different terminal, additional arguments are supported. In particular, you can
86 #   append a specific title to the terminal and set it to "nofocus" in your WM config.
87 #   E.g for alacritty and i3, you can set $NNN_TERMINAL to 'alacritty --title preview-tui' and add
88 #   'no_focus [title="preview-tui"]' to your i3 config file.
89 #
90 # Shell: Bash (for environment manipulation through arrays)
91 # Authors: Todd Yamakawa, Léo Villeveygoux, @Recidiviste, Mario Ortiz Manero, Luuk van Baal, @WanderLanz
92
93 # Configurable environment variables:
94 NNN_SPLIT=${NNN_SPLIT:-}                                   # permanent split direction
95 NNN_TERMINAL=${NNN_TERMINAL:-}                             # external terminal to be used
96 NNN_SPLITSIZE=${NNN_SPLITSIZE:-50}                         # previewer split size percentage
97 TMPDIR=${TMPDIR:-/tmp}                                     # location of temporary files
98 ENVVARS=(
99   "NNN_SCOPE=${NNN_SCOPE:-0}"                              # use scope
100   "NNN_PISTOL=${NNN_PISTOL:-0}"                            # use pistol
101   "NNN_ICONLOOKUP=${NNN_ICONLOOKUP:-0}"                    # use .iconlookup
102   "NNN_PAGER=${NNN_PAGER:-less -P?n -R -C}"                # pager options
103   "NNN_BATTHEME=${NNN_BATTHEME:-ansi}"                     # bat theme
104   "NNN_BATSTYLE=${NNN_BATSTYLE:-numbers}"                  # bat style
105   "NNN_PREVIEWWIDTH=${NNN_PREVIEWWIDTH:-1920}"             # width of generated preview images
106   "NNN_PREVIEWHEIGHT=${NNN_PREVIEWHEIGHT:-1080}"           # height of generated preview images
107   "NNN_PREVIEWDIR=${NNN_PREVIEWDIR:-$TMPDIR/nnn/previews}" # location of generated preview images
108   "NNN_PREVIEWIMGPROG=${NNN_PREVIEWIMGPROG:-}"             # program used to preview images
109   "NNN_PREVIEWVIDEO=${NNN_PREVIEWVIDEO:-}"                 # mpv backend used to preview video
110 )
111 # Non-configurable environment variables
112 NNN_PARENT=${NNN_FIFO#*.}
113 [ "$NNN_PARENT" -eq "$NNN_PARENT" ] 2>/dev/null || NNN_PARENT="" # Make empty if non-numeric
114 ENVVARS+=(
115   "PWD=$PWD"
116   "PATH=$PATH"
117   "NNN_FIFO=$NNN_FIFO"
118   "FIFOPID=$TMPDIR/nnn-preview-tui-fifopid.$NNN_PARENT"
119   "FIFOPATH=$TMPDIR/nnn-preview-tui-fifo.$NNN_PARENT"
120   "PREVIEWPID=$TMPDIR/nnn-preview-tui-previewpid.$NNN_PARENT"
121   "CURSEL=$TMPDIR/nnn-preview-tui-selection.$NNN_PARENT"
122   "FIFO_UEBERZUG=$TMPDIR/nnn-preview-tui-ueberzug-fifo.$NNN_PARENT"
123   "POSOFFSET=$TMPDIR/nnn-preview-tui-posoffset"
124 )
125
126 trap '' PIPE
127 exists() { type "$1" >/dev/null 2>&1 ;}
128 pkill() { command pkill "$@" >/dev/null 2>&1 ;}
129 prompt() { clear; printf "%b" "$@"; cfg=$(stty -g); stty raw -echo; head -c 1; stty "$cfg" ;}
130 pidkill() {
131     if [ -f "$1" ]; then
132         PID="$(cat "$1" 2>/dev/null)" || return 1
133         kill "$PID" >/dev/null 2>&1
134         RET=$?
135         wait "$PID" 2>/dev/null
136         return $RET
137     fi
138     return 1
139 }
140
141 start_preview() {
142     if [ -e "${TMUX%%,*}" ] && tmux -V | grep -q '[ -][3456789]\.'; then
143         NNN_TERMINAL=tmux
144         exists mpv && tmux display -p '#{client_termfeatures}' | grep -q 'sixel' && ENVVARS+=("NNN_PREVIEWVIDEO=sixel")
145     elif [ -n "$KITTY_LISTEN_ON" ]; then
146         NNN_TERMINAL=kitty
147         exists mpv && ENVVARS+=("NNN_PREVIEWVIDEO=kitty")
148     elif [ -n "$WEZTERM_PANE" ]; then
149         NNN_TERMINAL=wezterm
150         exists mpv && ENVVARS+=("NNN_PREVIEWVIDEO=kitty")
151     elif [ -z "$NNN_TERMINAL" ] && [ "$TERM_PROGRAM" = "iTerm.app" ]; then
152         NNN_TERMINAL=iterm
153         exists mpv && ENVVARS+=("NNN_PREVIEWVIDEO=sixel")
154     elif [ -n "$WT_SESSION" ]; then
155         NNN_TERMINAL=winterm
156     else
157         NNN_TERMINAL="${NNN_TERMINAL:-xterm}"
158     fi
159
160     if [ -z "$NNN_SPLIT" ] && [ $(($(tput lines) * 2)) -gt "$(tput cols)" ]; then
161         NNN_SPLIT='h'
162     elif [ "$NNN_SPLIT" != 'h' ]; then
163         NNN_SPLIT='v'
164     fi
165
166     ENVVARS+=("NNN_TERMINAL=$NNN_TERMINAL" "NNN_SPLIT=$NNN_SPLIT" "QLPATH=$2" "PREVIEW_MODE=1")
167     case "$NNN_TERMINAL" in
168         iterm|winterm) # has to run in separate shell command: escape
169             ENVVARS=("${ENVVARS[@]/#/\\\"}")
170             ENVVARS=("${ENVVARS[@]/%/\\\"}")
171             command="$SHELL -c 'env ${ENVVARS[*]} \\\"$0\\\" \\\"$1\\\"'" ;;
172     esac
173
174     case "$NNN_TERMINAL" in
175         tmux) # tmux splits are inverted
176             ENVVARS=("${ENVVARS[@]/#/-e}")
177             if [ "$NNN_SPLIT" = "v" ]; then split="h"; else split="v"; fi
178             tmux split-window -l"$NNN_SPLITSIZE"% "${ENVVARS[@]}" -d"$split" -p"$NNN_SPLITSIZE" "$0" "$1" ;;
179         kitty) # Setting the layout for the new window. It will be restored after the script ends.
180             ENVVARS=("${ENVVARS[@]/#/--env=}")
181             kitty @ goto-layout splits
182             # Trying to use kitty's integrated window management as the split window.
183             kitty @ launch --no-response --title "preview-tui" --keep-focus \
184                 --cwd "$PWD" "${ENVVARS[@]}" --location "${NNN_SPLIT}split" "$0" "$1" ;;
185         wezterm)
186             export "${ENVVARS[@]}"
187             if [ "$NNN_SPLIT" = "v" ]; then split="--horizontal"; else split="--bottom"; fi
188             wezterm cli split-pane --cwd "$PWD" $split --percent "$NNN_SPLITSIZE" "$0" "$1" >/dev/null
189             wezterm cli activate-pane-direction Prev ;;
190         iterm)
191             if [ "$NNN_SPLIT" = "h" ]; then split="horizontally"; else split="vertically"; fi
192             osascript <<-EOF
193             tell application "iTerm"
194                 tell current session of current window
195                     split $split with default profile command "$command"
196                 end tell
197             end tell
198 EOF
199             ;;
200         winterm)
201             if [ "$NNN_SPLIT" = "h" ]; then split="H"; else split="V"; fi
202             wt -w 0 sp -$split -s"0.$NNN_SPLITSIZE" "$command" \; -w 0 mf previous 2>/dev/null ;;
203         *)  if [ -n "$2" ]; then
204                 env "${ENVVARS[@]}" QUICKLOOK=1 "$0" "$1" &
205             else
206                 # shellcheck disable=SC2086 # (allow arguments)
207                 env "${ENVVARS[@]}" $NNN_TERMINAL -e "$0" "$1" &
208             fi ;;
209     esac
210 }
211
212 toggle_preview() {
213     export "${ENVVARS[@]}"
214     if exists QuickLook.exe; then
215         QLPATH="QuickLook.exe"
216     elif exists Bridge.exe; then
217         QLPATH="Bridge.exe"
218     fi
219     if pidkill "$FIFOPID"; then
220         [ -p "$NNN_PPIPE" ] && printf "0" > "$NNN_PPIPE"
221         pidkill "$PREVIEWPID"
222         pkill -f "tail --follow $FIFO_UEBERZUG"
223         if [ -n "$QLPATH" ] && stat "$1"; then
224             f="$(wslpath -w "$1")" && "$QLPATH" "$f" &
225         fi
226     else
227         [ -p "$NNN_PPIPE" ] && printf "1" > "$NNN_PPIPE"
228         start_preview "$1" "$QLPATH"
229     fi
230 }
231
232 fifo_pager() {
233     cmd="$1"
234     shift
235
236     # We use a FIFO to access $NNN_PAGER PID in jobs control
237     mkfifo "$FIFOPATH" || return
238
239     $NNN_PAGER < "$FIFOPATH" &
240     printf "%s" "$!" > "$PREVIEWPID"
241
242     (
243         exec > "$FIFOPATH"
244         if [ "$cmd" = "pager" ]; then
245             if exists bat; then
246                 bat --terminal-width="$cols" --decorations=always --color=always \
247                     --paging=never --style="$NNN_BATSTYLE" --theme="$NNN_BATTHEME" "$@" &
248             else
249                 $NNN_PAGER "$@" &
250             fi
251         else
252             "$cmd" "$@" &
253         fi
254     )
255
256     rm "$FIFOPATH"
257 }
258
259 # Binary file: show file info inside the pager
260 print_bin_info() {
261     printf -- "-------- \033[1;31mBinary file\033[0m --------\n"
262     if exists mediainfo; then
263         mediainfo "$1"
264     else
265         file -b "$1"
266     fi
267 }
268
269 handle_mime() {
270     case "$2" in
271         image/jpeg) image_preview "$cols" "$lines" "$1" ;;
272         image/gif) generate_preview "$cols" "$lines" "$1" "gif" ;;
273         image/vnd.djvu) generate_preview "$cols" "$lines" "$1" "djvu" ;;
274         image/*) generate_preview "$cols" "$lines" "$1" "image" ;;
275         video/*) generate_preview "$cols" "$lines" "$1" "video" ;;
276         audio/*) generate_preview "$cols" "$lines" "$1" "audio" ;;
277         application/font*|application/*opentype|font/*) generate_preview "$cols" "$lines" "$1" "font" ;;
278         */*office*|*/*document*|*/*msword|*/*ms-excel) generate_preview "$cols" "$lines" "$1" "office" ;;
279         application/zip) fifo_pager unzip -l "$1" ;;
280         text/troff)
281             if exists man; then
282                 fifo_pager man -Pcat -l "$1"
283             else
284                 fifo_pager pager "$1"
285             fi ;;
286         *) handle_ext "$1" "$3" "$4" ;;
287     esac
288 }
289
290 handle_ext() {
291     case "$2" in
292         epub) generate_preview "$cols" "$lines" "$1" "epub" ;;
293         pdf) generate_preview "$cols" "$lines" "$1" "pdf" ;;
294         gz|bz2) fifo_pager tar -tvf "$1" ;;
295         md) if exists glow; then
296                 fifo_pager glow -s dark "$1"
297             elif exists lowdown; then
298                 fifo_pager lowdown -Tterm "$1"
299             else
300                 fifo_pager pager "$1"
301             fi ;;
302         htm|html|xhtml)
303             if exists w3m; then
304                 fifo_pager w3m "$1"
305             elif exists lynx; then
306                 fifo_pager lynx "$1"
307             elif exists elinks; then
308                 fifo_pager elinks "$1"
309             else
310                 fifo_pager pager "$1"
311             fi ;;
312         7z|a|ace|alz|arc|arj|bz|cab|cpio|deb|jar|lha|lz|lzh|lzma|lzo\
313         |rar|rpm|rz|t7z|tar|tbz|tbz2|tgz|tlz|txz|tZ|tzo|war|xpi|xz|Z)
314             if exists atool; then
315                 fifo_pager atool -l "$1"
316             elif exists bsdtar; then
317                 fifo_pager bsdtar -tvf "$1"
318             fi ;;
319         *) if [ "$3" = "bin" ]; then
320                fifo_pager print_bin_info "$1"
321            else
322                fifo_pager pager "$1"
323            fi ;;
324     esac
325 }
326
327 preview_file() {
328     clear
329     # Trying to use pistol if it's available.
330     if [ "$NNN_PISTOL" -ne 0 ] && exists pistol; then
331         fifo_pager pistol "$1"
332         return
333     fi
334
335     # Trying to use scope.sh if it's available.
336     if [ "$NNN_SCOPE" -ne 0 ] && exists scope.sh; then
337         fifo_pager scope.sh "$1" "$cols" "$lines" "$(mktemp -d)" "True"
338         return
339     fi
340
341     # Use QuickLook if it's available.
342     if [ -n "$QUICKLOOK" ]; then
343         stat "$1" && f="$(wslpath -w "$1")" && "$QLPATH" "$f" &
344         return
345     fi
346
347     # Detecting the exact type of the file: the encoding, mime type, and extension in lowercase.
348     encoding="$(file -bL --mime-encoding -- "$1")"
349     mimetype="$(file -bL --mime-type -- "$1")"
350     ext="${1##*.}"
351     [ -n "$ext" ] && ext="$(printf "%s" "${ext}" | tr '[:upper:]' '[:lower:]')"
352     lines=$(tput lines)
353     cols=$(tput cols)
354
355     # Otherwise, falling back to the defaults.
356     if [ -d "$1" ]; then
357         cd "$1" || return
358         if [ "$NNN_ICONLOOKUP" -ne 0 ] && [ -f "$(dirname "$0")"/.iconlookup ]; then
359             [ "$NNN_SPLIT" = v ] && BSTR="\n"
360             # shellcheck disable=SC2012
361             ls -F --group-directories-first | head -n "$((lines - 3))" | "$(dirname "$0")"/.iconlookup -l "$cols" -B "$BSTR" -b " "
362         elif exists tree; then
363             fifo_pager tree --filelimit "$(find . -maxdepth 1 | wc -l)" -L 3 -C -F --dirsfirst --noreport
364         elif exists exa; then
365             exa -G --group-directories-first --colour=always
366         elif exists eza; then # eza is a community fork of exa (exa is unmaintained)
367             eza -G --group-directories-first --colour=always
368         else
369             fifo_pager ls -F --group-directories-first --color=always
370         fi
371         cd ..
372     elif [ "${encoding#*)}" = "binary" ]; then
373         handle_mime "$1" "$mimetype" "$ext" "bin"
374     else
375         handle_mime "$1" "$mimetype" "$ext"
376     fi
377 }
378
379 generate_preview() {
380   if [ -n "$QLPATH" ] && stat "$3"; then
381         f="$(wslpath -w "$3")" && "$QLPATH" "$f" &
382   elif [ -n "$NNN_PREVIEWVIDEO" ] && [[ "$4" == +(gif|video) ]]; then
383     [ "$4" = "video" ] && args=(--start=10% --length=4) || args=()
384     video_preview "$1" "$2" "$3" "${args[@]}" && return
385   elif [ ! -f "$NNN_PREVIEWDIR/$3.jpg" ] || [ -n "$(find -L "$3" -newer "$NNN_PREVIEWDIR/$3.jpg")" ]; then
386         mkdir -p "$NNN_PREVIEWDIR/${3%/*}"
387         case $4 in
388             audio) ffmpeg -i "$3" -filter_complex "scale=iw*min(1\,min($NNN_PREVIEWWIDTH/iw\,ih)):-1" "$NNN_PREVIEWDIR/$3.jpg" -y ;;
389             epub) gnome-epub-thumbnailer "$3" "$NNN_PREVIEWDIR/$3.jpg" ;;
390             font) fontpreview -i "$3" -o "$NNN_PREVIEWDIR/$3.jpg" ;;
391             gif) if [ -p "$FIFO_UEBERZUG" ] && exists convert; then
392                     frameprefix="$NNN_PREVIEWDIR/$3/${3##*/}"
393                     if [ ! -d "$NNN_PREVIEWDIR/$3" ]; then
394                         mkdir -p "$NNN_PREVIEWDIR/$3"
395                         convert -coalesce -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$3" "$frameprefix.jpg" ||
396                         MAGICK_TMPDIR="/tmp" convert -coalesce -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$3" "$frameprefix.jpg"
397                     fi
398                     frames=$(($(find "$NNN_PREVIEWDIR/$3" | wc -l) - 2))
399                     [ $frames -lt 0 ] && return
400                     while true; do
401                         for i in $(seq 0 $frames); do
402                             image_preview "$1" "$2" "$frameprefix-$i.jpg"
403                             sleep 0.1
404                         done
405                     done &
406                     printf "%s" "$!" > "$PREVIEWPID"
407                     return
408                  elif [ -n "$NNN_PREVIEWVIDEO" ]; then
409                     video_preview "$1" "$2" "$3" && return
410                  else
411                     image_preview "$1" "$2" "$3" && return
412                  fi ;;
413             image) if exists convert; then
414                        convert "$3" -flatten -resize "$NNN_PREVIEWWIDTH"x"$NNN_PREVIEWHEIGHT"\> "$NNN_PREVIEWDIR/$3.jpg"
415                    else
416                        image_preview "$1" "$2" "$3" && return
417                    fi ;;
418             office) libreoffice --convert-to jpg "$3" --outdir "$NNN_PREVIEWDIR/${3%/*}"
419                     filename="$(printf "%s" "${3##*/}" | cut -d. -f1)"
420                     mv "$NNN_PREVIEWDIR/${3%/*}/$filename.jpg" "$NNN_PREVIEWDIR/$3.jpg" ;;
421             pdf) pdftoppm -jpeg -f 1 -singlefile "$3" "$NNN_PREVIEWDIR/$3" ;;
422             djvu) ddjvu -format=ppm -page=1 "$3" "$NNN_PREVIEWDIR/$3.jpg" ;;
423             video) video_preview "$1" "$2" "$3" && return ;;
424         esac
425     fi
426     if [ -f "$NNN_PREVIEWDIR/$3.jpg" ]; then
427         image_preview "$1" "$2" "$NNN_PREVIEWDIR/$3.jpg"
428     else
429         fifo_pager print_bin_info "$3"
430     fi
431 } >/dev/null 2>&1
432
433 image_preview() {
434     clear
435     exec >/dev/tty
436     if [ "$NNN_TERMINAL" = "kitty" ] && [[ "$NNN_PREVIEWIMGPROG" == +(|icat) ]]; then
437         kitty +kitten icat --silent --scale-up --place "$1"x"$2"@0x0 --transfer-mode=stream --stdin=no "$3" &
438     elif [ "$NNN_TERMINAL" = "wezterm" ] && [[ "$NNN_PREVIEWIMGPROG" == +(|imgcat) ]]; then
439         wezterm imgcat "$3" &
440     elif exists ueberzug && [[ "$NNN_PREVIEWIMGPROG" == +(|ueberzug) ]]; then
441         ueberzug_layer "$1" "$2" "$3" && return
442     elif exists catimg && [[ "$NNN_PREVIEWIMGPROG" == +(|catimg) ]]; then
443         catimg "$3" &
444     elif exists viu && [[ "$NNN_PREVIEWIMGPROG" == +(|viu) ]]; then
445         viu -t "$3" &
446     elif exists chafa && [[ "$NNN_PREVIEWIMGPROG" == +(|chafa) ]]; then
447         chafa "$3" &
448     elif exists img2sixel && [[ "$NNN_PREVIEWIMGPROG" == +(|img2sixel) ]]; then
449         img2sixel -g "$3" &
450     else
451         fifo_pager print_bin_info "$3" && return
452     fi
453     printf "%s" "$!" > "$PREVIEWPID"
454 }
455
456 video_preview() {
457     clear
458     exec >/dev/tty
459     if [ -n "$NNN_PREVIEWVIDEO" ]; then
460         mpv --no-config --really-quiet --vo="$NNN_PREVIEWVIDEO" --profile=sw-fast --loop-file --no-audio "$4" "$3" &
461     else
462         ffmpegthumbnailer -m -s0 -i "$3" -o "$NNN_PREVIEWDIR/$3.jpg" || rm "$NNN_PREVIEWDIR/$3.jpg" &
463     fi
464     printf "%s" "$!" > "$PREVIEWPID"
465 }
466
467 ueberzug_layer() {
468     [ -f "$POSOFFSET" ] && read -r x y < "$POSOFFSET"
469     printf '{"action": "add", "identifier": "nnn_ueberzug", "x": %d, "y": %d, "width": "%d", "height": "%d", "scaler": "fit_contain", "path": "%s"}\n'\
470         "${x:-0}" "${y:-0}" "$1" "$2" "$3" > "$FIFO_UEBERZUG"
471 }
472
473 ueberzug_remove() {
474     printf '{"action": "remove", "identifier": "nnn_ueberzug"}\n' > "$FIFO_UEBERZUG"
475 }
476
477 winch_handler() {
478     clear
479     pidkill "$PREVIEWPID"
480     if [ -p "$FIFO_UEBERZUG" ]; then
481         pkill -f "tail --follow $FIFO_UEBERZUG"
482         tail --follow "$FIFO_UEBERZUG" | ueberzug layer --silent --parser json &
483     fi
484     preview_file "$(cat "$CURSEL")"
485 }
486
487 preview_fifo() {
488     while read -r selection; do
489         if [ -n "$selection" ]; then
490             pidkill "$PREVIEWPID"
491             [ -p "$FIFO_UEBERZUG" ] && ueberzug_remove
492             [ "$selection" = "close" ] && break
493             preview_file "$selection"
494             printf "%s" "$selection" > "$CURSEL"
495         fi
496     done < "$NNN_FIFO"
497     sleep 0.1 # make sure potential preview by winch_handler is killed
498     pkill -P "$$"
499 }
500
501 if [ "$PREVIEW_MODE" -eq 1 ] 2>/dev/null; then
502     if exists ueberzug && [ "$NNN_TERMINAL" != "kitty" ] && [[ "$NNN_PREVIEWIMGPROG" == +(|ueberzug) ]]; then
503         mkfifo "$FIFO_UEBERZUG"
504         tail --follow "$FIFO_UEBERZUG" | ueberzug layer --silent --parser json &
505     fi
506
507     preview_file "$PWD/$1"
508     preview_fifo & WAITPID=$!
509     printf "%s" "$!" > "$FIFOPID"
510     printf "%s" "$PWD/$1" > "$CURSEL"
511     trap 'winch_handler' WINCH
512     trap 'rm "$PREVIEWPID" "$CURSEL" "$FIFO_UEBERZUG" "$FIFOPID" "$POSOFFSET" 2>/dev/null' INT HUP EXIT
513     while kill -s 0 $WAITPID; do
514       wait $WAITPID 2>/dev/null
515     done
516     exit 0
517 else
518     if [ ! -r "$NNN_FIFO" ]; then
519         prompt "No FIFO available! (\$NNN_FIFO='$NNN_FIFO')\nPlease read Usage in '$0'."
520     elif [ "$KITTY_WINDOW_ID" ] && [ -z "$TMUX" ] && [ -z "$KITTY_LISTEN_ON" ]; then
521         prompt "\$KITTY_LISTEN_ON not set!\nPlease read Usage in '$0'."
522     else
523         toggle_preview "$1" &
524     fi
525 fi