home · contact · privacy
ba9e54348af063f8d77b7b90f349759d8c7365bb
[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 def read_worldstate():
171     if not os.access(io["path_worldstate"], os.F_OK):
172         msg = "No world state file found at " + io["path_worldstate"] + "."
173         raise SystemExit(msg)
174     read_anew = False
175     worldstate_file = open(io["path_worldstate"], "r")
176     turn_string = worldstate_file.readline()
177     if int(turn_string) != world_data["turn"]:
178         read_anew = True
179     if not read_anew: # In rare cases, world may change, but not turn number.
180         mtime = os.stat(io["path_worldstate"])
181         if mtime != read_worldstate.last_checked_mtime:
182             read_worldstate.last_checked_mtime = mtime
183             read_anew = True
184     if read_anew:
185         cursed_main.redraw = True
186         world_data["turn"] = int(turn_string)
187         world_data["lifepoints"] = int(worldstate_file.readline())
188         world_data["satiation"] = int(worldstate_file.readline())
189     worldstate_file.close()
190 read_worldstate.last_checked_mtime = -1
191
192
193 def cursed_main(stdscr):
194
195     def ping_test():
196         half_wait_time = 5
197         if len(new_data_from_server) > 0:
198             ping_test.sent = False
199         elif ping_test.wait_start + half_wait_time < time.time():
200             if not ping_test.sent:
201                 io["file_out"].write("PING\n")
202                 io["file_out"].flush()
203                 ping_test.sent = True
204                 ping_test.wait_start = time.time()
205             elif ping_test.sent:
206                 raise SystemExit("Server not answering anymore.")
207     ping_test.wait_start = 0
208
209     def read_into_message_queue():
210         if new_data_from_server == "":
211             return
212         new_open_end = False
213         if new_data_from_server[-1] is not "\n":
214             new_open_end = True
215         new_messages = new_data_from_server.splitlines()
216         if message_queue["open_end"]:
217             message_queue["messages"][-1] += new_messages[0]
218             del new_messages[0]
219         message_queue["messages"] += new_messages
220         if new_open_end:
221             message_queue["open_end"] = True
222
223     curses.noecho()
224     curses.curs_set(False)
225     # stdscr.keypad(True)
226     signal.signal(signal.SIGWINCH,
227         lambda ignore_1, ignore_2: set_window_geometries())
228     set_window_geometries()
229     delay = 1
230     while True:
231         stdscr.timeout(delay)
232         delay = delay * 2 if delay < 1000 else delay
233         if cursed_main.redraw:
234             delay = 1
235             draw_screen()
236             cursed_main.redraw = False
237         char = stdscr.getch()
238         if char >= 0 and chr(char) in commands:
239             commands[chr(char)]()
240             cursed_main.redraw = True
241         new_data_from_server = io["file_in"].read()
242         ping_test()
243         read_into_message_queue()
244         read_worldstate()
245
246
247 def win_foo():
248     winmap = ['.', 'o', '.', 'o', 'O', 'o', '.', 'o', '.', 'x', 'y', 'x']
249     size = [4, 3]
250     offset = [0, 0]
251     return offset, size, winmap
252
253
254 def win_info():
255     winmap = "T: " + str(world_data["turn"]) \
256         + " H: " + str(world_data["lifepoints"]) \
257         + " S: " + str(world_data["satiation"])
258     size = [1, len(winmap)]
259     offset = [0, 0]
260     return offset, size, winmap
261
262
263 def command_quit():
264     io["file_out"].write("QUIT\n")
265     io["file_out"].flush()
266     raise SystemExit("Received QUIT command, forwarded to server, leaving.")
267
268
269 windows = [
270     {"config": [1, 33], "func": win_info},
271     {"config": [-7, 33], "func": win_foo},
272     {"config": [4, 16], "func": win_foo},
273     {"config": [4, 16], "func": win_foo},
274     {"config": [0, -34], "func": win_foo}
275 ]
276 io = {
277     "path_out": "server/in",
278     "path_in": "server/out",
279     "path_worldstate": "server/worldstate"
280 }
281 commands = {
282     "Q": command_quit
283 }
284 message_queue = {
285     "open_end": False,
286     "messages": []
287 }
288 world_data = {
289     "lifepoints": -1,
290     "satiation": -1,
291     "turn": -1
292 }
293 sep_size = 1  # Width of inter-window borders and title bars.
294 stdscr = None
295 screen_size = [0,0]
296
297
298 try:
299     if (not os.access(io["path_out"], os.F_OK)):
300         msg = "No server input file found at " + io["path_out"] + "."
301         raise SystemExit(msg)
302     io["file_out"] = open(io["path_out"], "a")
303     io["file_in"] = open(io["path_in"], "r")
304     curses.wrapper(cursed_main)
305 except SystemExit as exit:
306     print("ABORTING: " + exit.args[0])
307 except:
308     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
309     raise
310 finally:
311     if "file_out" in io:
312         io["file_out"].close()
313     if "file_in" in io:
314         io["file_in"].close()