home · contact · privacy
New client: Reorganize code.
[plomrogue] / client_prototype.py
1 import curses
2 import os
3 import signal
4 import time
5
6
7 def set_window_geometries():
8
9     def set_window_size():
10         win["size"], win["start"] = [0, 0], [0, 0]
11         win["size"][0] = win["config"][0]
12         if (win["config"][0] == 0):
13             win["size"][0] = screen_size[0] - sep_size
14         elif (win["config"][0] < 0):
15             win["size"][0] = screen_size[0] + win["config"][0] - sep_size
16         win["size"][1] = win["config"][1]
17         if (win["config"][1] == 0):
18             win["size"][1] = screen_size[1]
19         elif (win["config"][1] < 0):
20             win["size"][1] = screen_size[1] + win["config"][1]
21
22     def place_window():
23         win_i = windows.index(win)
24
25         # If win is first window, it goes into the top left corner.
26         win["start"][0] = 0 + sep_size
27         win["start"][1] = 0
28         if (win_i > 0):
29
30             # If not, get win's closest predecessor starting a new stack on the
31             # screen top,fit win's top left to that win_top's top right corner.
32             win_top = None
33             for i in range(win_i - 1, -1, -1):
34                 win_top = windows[i]
35                 if (win_top["start"][0] == 0 + sep_size):
36                     break
37             win["start"][1] = win_top["start"][1] + win_top["size"][1] \
38                 + sep_size
39
40             # If enough space is found below win's predecessor, fit win's top
41             # left corner to that predecessor's bottom left corner.
42             win_prev = windows[win_i - 1]
43             next_free_y = win_prev["start"][0] + win_prev["size"][0] + sep_size
44             if (win["size"][1] <= win_prev["size"][1] and
45                     win["size"][0] <= screen_size[0] - next_free_y):
46                 win["start"][1] = win_prev["start"][1]
47                 win["start"][0] = next_free_y
48
49             # If that fails, try to fit win's top left corner to the top right
50             # corner of its closest predecessor win_test 1) below win_top (see
51             # above) 2) and with enough space open to its right between its
52             # right edge and the lower edge of a win_high located directly
53             # above win_test to fit win there (without growing further to the
54             # right than win_high does or surpassing the screen's lower edge).
55             else:
56                 win_test = win_prev
57                 win_high = None
58                 while (win_test != win_top):
59                     for i in range(win_i - 2, -1, -1):
60                         win_high = windows[i]
61                         if win_test["start"][0] > win_high["start"][0]:
62                             break
63                     next_free_y = win_high["start"][0] + win_high["size"][0] \
64                         + sep_size
65                     first_free_x = win_test["start"][1] + win_test["size"][1] \
66                         + sep_size
67                     last_free_x = win_high["start"][1] + win_high["size"][1]
68                     if (win["size"][0] <= screen_size[0] - next_free_y and
69                             win["size"][1] <= last_free_x - first_free_x):
70                         win["start"][1] = first_free_x
71                         win["start"][0] = next_free_y
72                         break
73                     win_test = win_high
74
75     global screen_size, stdscr
76     curses.endwin()
77     stdscr = curses.initscr()
78     screen_size = stdscr.getmaxyx()
79     for win in windows:
80         set_window_size()
81         place_window()
82     cursed_main.redraw = True
83
84
85 def draw_screen():
86
87     def draw_window_border_lines():
88         for win in windows:
89             for k in range(2):
90                 j = win["start"][int(k == 0)] - sep_size
91                 if (j >= 0 and j < screen_size[int(k == 0)]):
92                     start = win["start"][k]
93                     # start = start if start >= 0 else 0
94                     end = win["start"][k] + win["size"][k]
95                     end = end if end < screen_size[k] else screen_size[k]
96                     if k:
97                         [stdscr.addch(j, i, '-') for i in range(start, end)]
98                     else:
99                         [stdscr.addch(i, j, '|') for i in range(start, end)]
100
101     def draw_window_border_corners():
102         for win in windows:
103             up = win["start"][0] - sep_size
104             down = win["start"][0] + win["size"][0]
105             left = win["start"][1] - sep_size
106             right = win["start"][1] + win["size"][1]
107             if (up >= 0 and up < screen_size[0]):
108                 if (left >= 0 and left < screen_size[1]):
109                     stdscr.addch(up, left, '+')
110                 if (right >= 0 and right < screen_size[1]):
111                     stdscr.addch(up, right, '+')
112             if (down >= 0 and down < screen_size[0]):
113                 if (left >= 0 and left < screen_size[1]):
114                     stdscr.addch(down, left, '+')
115                 if (right >= 0 and right < screen_size[1]):
116                     stdscr.addch(down, right, '+')
117
118     def draw_window_contents():
119         def draw_winmap():
120             stop = [0, 0]
121             for i in range(2):
122                 stop[i] = win["size"][i] + offset[i]
123                 stop[i] = stop[i] if stop[i] < size[i] else size[i]
124             for y in range(offset[0], stop[0]):
125                 for x in range(offset[1], stop[1]):
126                     cell = winmap[y * size[1] + x]
127                     y_in_screen = win["start"][0] + (y - offset[0])
128                     x_in_screen = win["start"][1] + (x - offset[1])
129                     if (y_in_screen < screen_size[0]
130                             and x_in_screen < screen_size[1]):
131                         stdscr.addch(y_in_screen, x_in_screen, cell)
132         def draw_scroll_hints():
133             def draw_scroll_string(n_lines_outside):
134                 hint = ' ' + str(n_lines_outside + 1) + ' more ' + unit + ' '
135                 if len(hint) <= win["size"][ni]:
136                     non_hint_space = win["size"][ni] - len(hint)
137                     hint_offset = int(non_hint_space / 2)
138                     for j in range(win["size"][ni] - non_hint_space):
139                         pos_2 = win["start"][ni] + hint_offset + j
140                         x, y = (pos_2, pos_1) if ni else (pos_1, pos_2)
141                         stdscr.addch(y, x, hint[j], curses.A_REVERSE)
142             def draw_scroll_arrows(ar1, ar2):
143                 for j in range(win["size"][ni]):
144                     pos_2 = win["start"][ni] + j
145                     x, y = (pos_2, pos_1) if ni else (pos_1, pos_2)
146                     stdscr.addch(y, x, ar1 if ni else ar2, curses.A_REVERSE)
147             for i in range(2):
148                 ni = int(i == 0)
149                 unit = 'rows' if ni else 'columns'
150                 if (offset[i] > 0):
151                     pos_1 = win["start"][i]
152                     draw_scroll_arrows('^', '<')
153                     draw_scroll_string(offset[i])
154                 if (size[i] > offset[i] + win["size"][i]):
155                     pos_1 = win["start"][i] + win["size"][i] - 1
156                     draw_scroll_arrows('v', '>')
157                     draw_scroll_string(size[i] - offset[i] - win["size"][i])
158         for win in windows:
159             offset, size, winmap = win["func"]()
160             draw_winmap()
161             draw_scroll_hints()
162
163     stdscr.clear()
164     draw_window_border_lines()
165     draw_window_border_corners()
166     draw_window_contents()
167     stdscr.refresh()
168
169
170
171
172 def cursed_main(stdscr):
173
174     def ping_test(server_answered):
175         half_wait_time = 5
176         if server_answered:
177             ping_test.sent = False
178         elif ping_test.wait_start + half_wait_time < time.time():
179             if not ping_test.sent:
180                 io["file_out"].write("PING\n")
181                 io["file_out"].flush()
182                 ping_test.sent = True
183                 ping_test.wait_start = time.time()
184             elif ping_test.sent:
185                 raise SystemExit("Server not answering anymore.")
186     ping_test.wait_start = 0
187
188     def read_into_message_queue(string):
189         if string == "":
190             return
191         new_open_end = False
192         if string[-1] is not "\n":
193             new_open_end = True
194         new_messages = string.splitlines()
195         if message_queue["open_end"]:
196             message_queue["messages"][-1] += new_messages[0]
197             del new_messages[0]
198         message_queue["messages"] += new_messages
199         if new_open_end:
200             message_queue["open_end"] = True
201
202     curses.noecho()
203     curses.curs_set(False)
204     # stdscr.keypad(True)
205     signal.signal(signal.SIGWINCH,
206         lambda ignore_1, ignore_2: set_window_geometries())
207     set_window_geometries()
208     delay = 1
209     while True:
210         stdscr.timeout(delay)
211         delay = delay * 2 if delay < 1000 else delay
212         if cursed_main.redraw:
213             delay = 1
214             draw_screen()
215             cursed_main.redraw = False
216         char = stdscr.getch()
217         if (char >= 0):
218             if chr(char) in commands:
219                 commands[chr(char)]()
220                 cursed_main.redraw = True
221         new_data_from_server = io["file_in"].read()
222         ping_test(len(new_data_from_server) > 0)
223         read_into_message_queue(new_data_from_server)
224
225
226 def foo():
227     winmap = ['.', 'o', '.', 'o', 'O', 'o', '.', 'o', '.', 'x', 'y', 'x']
228     size = [4, 3]
229     offset = [0, 0]
230     return offset, size, winmap
231
232
233 def command_quit():
234     io["file_out"].write("QUIT\n")
235     io["file_out"].flush()
236     raise SystemExit("Received QUIT command, forwarded to server, leaving.")
237
238
239 windows = [
240     {"config": [1, 33], "func": foo},
241     {"config": [-7, 33], "func": foo},
242     {"config": [4, 16], "func": foo},
243     {"config": [4, 16], "func": foo},
244     {"config": [0, -34], "func": foo}
245 ]
246 io = {
247     "path_out": "server/in",
248     "path_in": "server/out"
249 }
250 commands = {
251     "Q": command_quit
252 }
253 message_queue = {
254     "open_end": False,
255     "messages": []
256 }
257 sep_size = 1  # Width of inter-window borders and title bars.
258 stdscr = None
259 screen_size = [0,0]
260
261
262 try:
263     if (not os.access(io["path_out"], os.F_OK)):
264         msg = "No server input file found at " + io["path_out"] + "."
265         raise SystemExit(msg)
266     io["file_out"] = open(io["path_out"], "a")
267     io["file_in"] = open(io["path_in"], "r")
268     curses.wrapper(cursed_main)
269 except SystemExit as exit:
270     print("ABORTING: " + exit.args[0])
271 except:
272     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
273     raise
274 finally:
275     logfile = open("log", "a")
276     logfile.write(str(message_queue))
277     logfile.close()
278     if "file_out" in io:
279         io["file_out"].close()
280     if "file_in" in io:
281         io["file_in"].close()