summaryrefslogtreecommitdiffstats
path: root/cursed.py
blob: e5c17ee839a340233413e5db451ca2ebc9ee997c (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
42
43
44
45
46
47
48
49
50
51
import curses
import asyncio
import sys
from message import Message

class Console():
    def __init__(self, messages):
        self.stdscr = curses.initscr()
        self.messages = messages
        self.typed_message = ""

    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()

    def redraw(self):
        self.stdscr.clear()
        for msg in self.messages:
            self.stdscr.addstr(str(msg) + '\n')
        if self.typed_message != "":
            self.stdscr.addstr(self.typed_message)
        self.stdscr.refresh()

    async def start(self, client, on_str, on_tab):
        async for message in client.iter_messages("+46763060644", limit=10):
            self.messages.insert(0, Message(message.raw_text, message.id, " "))

        while True:
            self.redraw()
            char = await asyncio.to_thread(self.stdscr.get_wch)
            if isinstance(char, str):
                if char == '\n':
                    if self.typed_message != "":
                        await on_str(self.typed_message)
                        self.messages.append(Message(self.typed_message, -1, ">"))
                        self.typed_message = ""
                elif char == '\t':
                    await on_tab()
                else:
                    self.typed_message += char
            else:
                if char == 263:
                    self.typed_message = self.typed_message[:-1]