1#!/bin/bash
23
# tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
4# <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
5# only accepts ESC backslash for ST. We use TERM instead of TMUX because TERM
6# gets passed through ssh.
7function print_osc() {
8if [[ $TERM == screen* ]] ; then
9printf "\033Ptmux;\033\033]"
10else
11printf "\033]"
12fi
13}
1415
# More of the tmux workaround described above.
16function print_st() {
17if [[ $TERM == screen* ]] ; then
18printf "\a\033\\"
19else
20printf "\a"
21fi
22}
2324
# print_image filename inline base64contents print_filename
25# filename: Filename to convey to client
26# inline: 0 or 1
27# base64contents: Base64-encoded contents
28# print_filename: If non-empty, print the filename
29# before outputting the image
30function print_image() {
31print_osc
32printf '1337;File='
33if [[ -n "$1" ]]; then
34printf 'name='`printf "%s" "$1" | base64`";"
35fi
3637
VERSION=$(base64 --version 2>&1)
38if [[ "$VERSION" =~ fourmilab ]]; then
39BASE64ARG=-d
40elif [[ "$VERSION" =~ GNU ]]; then
41BASE64ARG=-di
42else
43BASE64ARG=-D
44fi
4546
printf "%s" "$3" | base64 $BASE64ARG | wc -c | awk '{printf "size=%d",$1}'
47printf ";inline=$2"
48printf ":"
49printf "%s" "$3"
50print_st
51printf '\n'
52if [[ -n "$4" ]]; then
53echo $1
54fi
55}
5657
function error() {
58echo "ERROR: $*" 1>&2
59}
6061
function show_help() {
62echo "Usage: imgcat [-p] filename ..." 1>& 2
63echo " or: cat filename | imgcat" 1>& 2
64}
6566
function check_dependency() {
67if ! (builtin command -V "$1" > /dev/null 2>& 1); then
68echo "imgcat: missing dependency: can't find $1" 1>& 2
69exit 1
70fi
71}
7273
## Main
7475
if [ -t 0 ]; then
76has_stdin=f
77else
78has_stdin=t
79fi
8081
# Show help if no arguments and no stdin.
82if [ $has_stdin = f -a $# -eq 0 ]; then
83show_help
84exit
85fi
8687
check_dependency awk
88check_dependency base64
89check_dependency wc
9091
# Look for command line flags.
92while [ $# -gt 0 ]; do
93case "$1" in
94-h|--h|--help)
95show_help
96exit
97;;
98-p|--p|--print)
99print_filename=1
100;;
101-u|--u|--url)
102check_dependency curl
103encoded_image=$(curl -s "$2" | base64) || (error "No such file or url $2"; exit 2)
104has_stdin=f
105print_image "$2" 1 "$encoded_image" "$print_filename"
106set -- ${@:1:1} "-u" ${@:3}
107if [ "$#" -eq 2 ]; then
108exit
109fi
110;;
111-*)
112error "Unknown option flag: $1"
113show_help
114exit 1
115;;
116*)
117if [ -r "$1" ] ; then
118has_stdin=f
119print_image "$1" 1 "$(base64 < "$1")" "$print_filename"
120else
121error "imgcat: $1: No such file or directory"
122exit 2
123fi
124;;
125esac
126shift
127done
128129
# Read and print stdin
130if [ $has_stdin = t ]; then
131print_image "" 1 "$(cat | base64)" ""
132fi
133134
exit 0