eris/eris/terminal.py
Andrew Hamilton 787c304d06 Files don't need individual license headers.
- All files are licensed by the LICENSE file at root.
- Updated the license to 2021.
- Have kept the license in LS_COLORS since its 3rd party.
2021-04-12 02:25:49 +10:00

96 lines
2.2 KiB
Python

import contextlib
import sys
import termios
ESC = "\x1b"
MOUSE = ESC + "[M"
normal = "[m"
bold = "[1m"
italic = "[3m"
standout = "[7m"
underline = "[4m"
UP_KEY = ESC + "[A"
DOWN_KEY = ESC + "[B"
RIGHT_KEY = ESC + "[C"
LEFT_KEY = ESC + "[D"
PAGE_UP_KEY = ESC + "[5~"
PAGE_DOWN_KEY = ESC + "[6~"
HOME_KEY = ESC + "[H"
END_KEY = ESC + "[F"
def color(color_number, is_foreground):
return f"[{'38' if is_foreground else '48'};5;{color_number:d}m"
def rgb_color(rgb, is_foreground):
return f"[{'38' if is_foreground else '48'};2;" + "%i;%i;%im" % rgb
def move(x, y):
return ESC + f"[{y + 1:d};{x + 1:d}H"
@contextlib.contextmanager
def terminal_title(title):
sys.stdout.write(ESC + "7") # save
sys.stdout.write(f"\033]0;{title}\007") # set title
try:
yield
finally:
sys.stdout.write(ESC + "8") # restore
@contextlib.contextmanager
def mouse_tracking():
sys.stdout.write(ESC + "[?1000h" + ESC + "[?1002h") # tracking on
try:
yield
finally:
sys.stdout.write(ESC + "[?1002l" + ESC + "[?1000l") # tracking off
@contextlib.contextmanager
def alternate_buffer():
sys.stdout.write(ESC + "7" + ESC + "[?47h") # switch to alternate buffer
try:
yield
finally:
sys.stdout.write(ESC + "[?47l" + ESC + "8") # restore normal buffer
@contextlib.contextmanager
def interactive():
old_termios_settings = termios.tcgetattr(sys.stdin)
new_settings = termios.tcgetattr(sys.stdin)
new_settings[3] = new_settings[3] & ~termios.ECHO & ~termios.ICANON
new_settings[6][termios.VMIN] = 0
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, new_settings)
try:
yield
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_termios_settings)
def decode_mouse_input(term_code):
keys = [ord(byte) for byte in term_code]
b = keys[0] - 32
x, y = (keys[1] - 33) % 256, (keys[2] - 33) % 256
button = ((b & 64) / 64 * 3) + (b & 3) + 1
if b & 3 == 3:
action = "release"
button = 0
elif b & 2048:
action = "release"
elif b & 32:
action = "drag"
elif b & 1536:
action = "click"
else:
action = "press"
return ("mouse " + action, button, x, y)