summaryrefslogtreecommitdiffstats
path: root/cursed.py
blob: 70d9c7e2e200c848ff419bbaafaa7fa41378468d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import curses
import asyncio
import sys

class Console():
    def __init__(self):
        self.stdscr = curses.initscr()

    def __enter__(self):
        curses.noecho()
        curses.cbreak()
        self.stdscr.keypad(True)
        return self

    def __exit__(self, *_):
        curses.nocbreak()
        self.stdscr.keypad(False)
        curses.echo()
        curses.endwin()


async def start(c, on_str, on_tab, messages):
    string = ""
    redraw(c.stdscr, messages)
    while True:
        char = await asyncio.to_thread(c.stdscr.getkey)
        if char == '\n' and string != "":
            await on_str(string)
            messages.append(string)
            redraw(c.stdscr, messages)
            string = ""
        elif char == '\t':
            await on_tab()
        else:
            string += char


def redraw(stdscr, messages):
    stdscr.clear()
    for msg in messages:
        stdscr.addstr(msg + '\n')