gr.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python
  2. # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
  3. import os
  4. import sys
  5. import zlib
  6. from base64 import standard_b64encode
  7. from contextlib import suppress
  8. write = getattr(sys.stdout, 'buffer', sys.stdout).write
  9. def clear_screen():
  10. write(b'\033[2J')
  11. def move_cursor(x, y):
  12. write(f'\033[{y};{x}H'.encode('ascii'))
  13. def write_gr_cmd(cmd, payload):
  14. cmd = ','.join(f'{k}={v}' for k, v in cmd.items())
  15. w = write
  16. w(b'\033_G'), w(cmd.encode('ascii')), w(b';'), w(payload), w(b'\033\\')
  17. sys.stdout.flush()
  18. def display(data, width, height, x, y, z, ncols=0, nrows=0):
  19. move_cursor(x, y)
  20. cmd = {'a': 'T', 's': width, 'v': height, 'c': ncols, 'r': nrows, 'S': len(data), 'z': z}
  21. data = zlib.compress(data)
  22. cmd['o'] = 'z'
  23. data = standard_b64encode(data)
  24. while data:
  25. chunk, data = data[:4096], data[4096:]
  26. m = 1 if data else 0
  27. cmd['m'] = m
  28. write_gr_cmd(cmd, chunk)
  29. cmd.clear()
  30. def display_png_file(path):
  31. cmd = {'a': 'T', 't': 'f', 'f': '100'}
  32. path = os.path.abspath(path)
  33. if not isinstance(path, bytes):
  34. path = path.encode(sys.getfilesystemencoding() or 'utf-8')
  35. data = standard_b64encode(path)
  36. write_gr_cmd(cmd, data)
  37. def main():
  38. from kitty.constants import logo_png_file
  39. photo = sys.argv[-1]
  40. if not photo.lower().endswith('.png'):
  41. raise SystemExit('Must specify a PNG file to display')
  42. clear_screen()
  43. display(b'\xdd\xdd\xdd\xff', 1, 1, 0, 0, -10, 40, 20)
  44. with open(logo_png_file.replace('.png', '.rgba'), 'rb') as f:
  45. display(f.read(), 256, 256, 0, 5, -9)
  46. display(b'\0\0\0\xaa', 1, 1, 0, 7, -8, 40, 3)
  47. move_cursor(5, 8)
  48. print('kitty is \033[3m\033[32mawesome\033[m!')
  49. move_cursor(0, 21)
  50. print('Photo...')
  51. display_png_file(photo)
  52. with suppress(EOFError, KeyboardInterrupt):
  53. input()
  54. if __name__ == '__main__':
  55. main()