summaryrefslogtreecommitdiff
path: root/curses/cui.py
blob: 540576546dc3bb9d504dad007520b1b97f771c18 (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#-*- coding: utf-8 -*-
"""
Curses-based console user interface for TMW chat client.
"""

import curses
from curses.textpad import Textbox

stdscr = None
chatlog_win = None
input_win = None
players_win = None
input_textbox = None


def init():
    global stdscr, chatlog_win, input_win, players_win, input_textbox

    stdscr = curses.initscr()
    curses.cbreak()
    curses.noecho()
    stdscr.keypad(1)

    h, w = stdscr.getmaxyx()
    PNW = 20  # player name width
    INH = 4   # input window height

    stdscr.vline(0, w - PNW - 1, curses.ACS_VLINE, h)
    stdscr.hline(h - INH - 1, 0, curses.ACS_HLINE, w - PNW - 1)

    chatlog_win = curses.newwin(h - INH - 1, w - PNW - 1, 0, 0)
    input_win = curses.newwin(INH, w - PNW - 1, h - INH, 0)
    players_win = curses.newwin(h, PNW, 0, w - PNW)

    chatlog_win.idlok(1)
    chatlog_win.scrollok(1)

    players_win.idlok(1)
    players_win.scrollok(1)

    input_textbox = Textbox(input_win)
    input_textbox.stripspaces = True

    stdscr.noutrefresh()
    input_win.noutrefresh()
    players_win.noutrefresh()
    chatlog_win.noutrefresh()

    curses.doupdate()


def chatlog_append(line):
    if line[-1] != "\n":
        line = line + "\n"
    chatlog_win.addstr(line)
    chatlog_win.refresh()


def input_loop(callback):
    def v(ch):
        # chatlog_append(curses.keyname(ch))
        if ch in (curses.KEY_ENTER, curses.ascii.NL):
            return curses.ascii.BEL
        return ch

    cmd = ''
    while cmd not in ('/exit', '/quit'):
        cmd = input_textbox.edit(v).strip()
        callback(cmd)
        input_win.clear()
        input_win.move(0, 0)


def finalize():
    stdscr.keypad(0)
    curses.echo()
    curses.nocbreak()
    curses.endwin()