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