imgcat 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #!/bin/bash
  2. # tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
  3. # <sequence> ST, and for all ESCs in <sequence> to be replaced with ESC ESC. It
  4. # only accepts ESC backslash for ST.
  5. function print_osc() {
  6. if [[ $TERM == screen* ]] ; then
  7. printf "\033Ptmux;\033\033]"
  8. else
  9. printf "\033]"
  10. fi
  11. }
  12. # More of the tmux workaround described above.
  13. function print_st() {
  14. if [[ $TERM == screen* ]] ; then
  15. printf "\a\033\\"
  16. else
  17. printf "\a"
  18. fi
  19. }
  20. # print_image filename inline base64contents
  21. # filename: Filename to convey to client
  22. # inline: 0 or 1
  23. # base64contents: Base64-encoded contents
  24. function print_image() {
  25. print_osc
  26. printf '1337;File='
  27. if [[ -n "$1" ]]; then
  28. printf 'name='`echo -n "$1" | base64`";"
  29. fi
  30. if $(base64 --version 2>&1 | egrep 'fourmilab|GNU' > /dev/null)
  31. then
  32. BASE64ARG=-d
  33. else
  34. BASE64ARG=-D
  35. fi
  36. echo -n "$3" | base64 $BASE64ARG | wc -c | awk '{printf "size=%d",$1}'
  37. printf ";inline=$2"
  38. printf ":"
  39. echo -n "$3"
  40. print_st
  41. printf '\n'
  42. }
  43. function error() {
  44. echo "ERROR: $*" 1>&2
  45. }
  46. function show_help() {
  47. echo "Usage: imgcat filename ..." 1>& 2
  48. echo " or: cat filename | imgcat" 1>& 2
  49. }
  50. ## Main
  51. if [ -t 0 ]; then
  52. has_stdin=f
  53. else
  54. has_stdin=t
  55. fi
  56. # Show help if no arguments and no stdin.
  57. if [ $has_stdin = f -a $# -eq 0 ]; then
  58. show_help
  59. exit
  60. fi
  61. # Look for command line flags.
  62. while [ $# -gt 0 ]; do
  63. case "$1" in
  64. -h|--h|--help)
  65. show_help
  66. exit
  67. ;;
  68. -*)
  69. error "Unknown option flag: $1"
  70. show_help
  71. exit 1
  72. ;;
  73. *)
  74. if [ -r "$1" ] ; then
  75. print_image "$1" 1 "$(base64 < "$1")"
  76. else
  77. error "imgcat: $1: No such file or directory"
  78. exit 2
  79. fi
  80. ;;
  81. esac
  82. shift
  83. done
  84. # Read and print stdin
  85. if [ $has_stdin = t ]; then
  86. print_image "" 1 "$(cat | base64)"
  87. fi
  88. exit 0