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