home · contact · privacy
More TUI code refactoring.
[plomrogue2] / plomrogue_client / tui.py
1 #!/usr/bin/env python3
2 import curses
3
4
5
6 class TUI:
7
8     def __init__(self):
9         self._log = []
10         curses.wrapper(self.run_loop)
11
12     def addstr(self, y, x, line, attr=0):
13         if y < self.size.y - 1 or x + len(line) < self.size.x:
14             self.stdscr.addstr(y, x, line, attr)
15         else:  # workaround to <https://stackoverflow.com/q/7063128>
16             cut_i = self.size.x - x - 1
17             cut = line[:cut_i]
18             last_char = line[cut_i]
19             self.stdscr.addstr(y, self.size.x - 2, last_char, attr)
20             self.stdscr.insstr(y, self.size.x - 2, ' ')
21             self.stdscr.addstr(y, x, cut, attr)
22
23     def reset_size(self):
24         from plomrogue.mapping import YX
25         self.size = YX(*self.stdscr.getmaxyx())
26         self.size = self.size - YX(self.size.y % 4, 0)
27         self.size = self.size - YX(0, self.size.x % 4)
28
29     def init_loop(self):
30         curses.curs_set(0)  # hide cursor
31         self.stdscr.timeout(10)
32         self.reset_size()
33
34     def run_loop(self, stdscr):
35         self.stdscr = stdscr
36         self.init_loop()
37         while True:
38             self.loop()
39
40     def log(self, msg):
41         self._log += [msg]
42
43
44
45 def msg_into_lines_of_width(msg, width):
46     chunk = ''
47     lines = []
48     x = 0
49     for i in range(len(msg)):
50         if x >= width or msg[i] == "\n":
51             lines += [chunk]
52             chunk = ''
53             x = 0
54             if msg[i] == "\n":
55                 x -= 1
56         if msg[i] != "\n":
57             chunk += msg[i]
58         x += 1
59     lines += [chunk]
60     return lines