home · contact · privacy
Server, plugin: Refactor thingproliferation (plugin integration).
[plomrogue] / roguelike-client
1 #!/usr/bin/python3
2
3 # This file is part of PlomRogue. PlomRogue is licensed under the GPL version 3
4 # or any later version. For details on its copyright, license, and warranties,
5 # see the file NOTICE in the root directory of the PlomRogue source package.
6
7
8 import curses
9 import os
10 import signal
11 import time
12
13 from client.config.world_data import world_data
14 from client.config.io import io
15 from client.config.commands import commands
16 from client.window_management import redraw_windows, set_windows, draw_screen, \
17                                      stdscr
18 from client.query_mapcell import query_mapcell
19
20
21 message_queue = {
22     "open_end": False,
23     "messages": []
24 }
25
26
27 def read_worldstate():
28     global redraw_windows
29     if not os.access(io["path_worldstate"], os.F_OK):
30         msg = "No world state file found at " + io["path_worldstate"] + "."
31         raise SystemExit(msg)
32     read_anew = False
33     worldstate_file = open(io["path_worldstate"], "r")
34     turn_string = worldstate_file.readline()
35     if int(turn_string) != world_data["turn"]:
36         read_anew = True
37     if not read_anew: # In rare cases, world may change, but not turn number.
38         mtime = os.stat(io["path_worldstate"])
39         if mtime != read_worldstate.last_checked_mtime:
40             read_worldstate.last_checked_mtime = mtime
41             read_anew = True
42     if read_anew:
43         # TODO: Hardcode order of necessary fields, ensure order dependencies.
44         redraw_windows = True
45         world_data["turn"] = int(turn_string)
46         for entry in io["worldstate_read_order"]:
47             if entry[1] == "int":
48                 if 2 == len(entry):
49                     world_data[entry[0]] = int(worldstate_file.readline())
50                 elif 3 == len(entry):
51                     world_data[entry[0]][entry[2]] = \
52                             int(worldstate_file.readline())
53             elif entry[1] == "lines":
54                 world_data[entry[0]] = []
55                 while True:
56                     line = worldstate_file.readline().replace("\n", "")
57                     if line == '%':
58                         break
59                     world_data[entry[0]] += [line]
60             elif entry[1] == "map":
61                 world_data[entry[0]] = ""
62                 for i in range(world_data["map_size"]):
63                     line = worldstate_file.readline().replace("\n", "")
64                     world_data[entry[0]] += line
65         if not world_data["look_mode"]:
66             world_data["map_center"] = world_data["avatar_position"][:]
67     worldstate_file.close()
68 read_worldstate.last_checked_mtime = -1
69
70
71 def read_message_queue():
72     global redraw_windows
73     while (len(message_queue["messages"]) > 1
74         or (len(message_queue["messages"]) == 1
75             and not message_queue["open_end"])):
76         message = message_queue["messages"].pop(0)
77         if message == "THINGS_HERE START":
78             read_message_queue.parse_thingshere = True
79             world_data["look"] = []
80         elif message == "THINGS_HERE END":
81             read_message_queue.parse_thingshere = False
82             if world_data["look"] == []:
83                 world_data["look"] = ["(none known)"]
84             redraw_windows = True
85         elif read_message_queue.parse_thingshere:
86             world_data["look"] += [message]
87         elif message[0:4] == "LOG ":
88             world_data["log"] += [message[4:]]
89             redraw_windows = True
90         elif message == "WORLD_UPDATED":
91             query_mapcell()
92         elif message[:6] == "PLUGIN":
93             str_plugin = message[7:]
94             if (str_plugin.replace("_", "").isalnum()
95                 and os.access("plugins/client/" + str_plugin + ".py",
96                     os.F_OK)):
97                 exec(open("plugins/client/" + str_plugin + ".py").read())
98                 return
99             raise SystemExit("Invalid plugin load path in message: " + message)
100 read_message_queue.parse_thingshere = False
101
102
103 def cursed_main(stdscr):
104     global redraw_windows
105
106     def ping_test():
107         half_wait_time = 5
108         if len(new_data_from_server) > 0:
109             ping_test.sent = False
110         elif ping_test.wait_start + half_wait_time < time.time():
111             if not ping_test.sent:
112                 io["file_out"].write("PING\n")
113                 io["file_out"].flush()
114                 ping_test.sent = True
115                 ping_test.wait_start = time.time()
116             elif ping_test.sent:
117                 raise SystemExit("Server not answering anymore.")
118     ping_test.wait_start = 0
119
120     def read_into_message_queue():
121         if new_data_from_server == "":
122             return
123         new_open_end = False
124         if new_data_from_server[-1] is not "\n":
125             new_open_end = True
126         new_messages = new_data_from_server.splitlines()
127         if message_queue["open_end"]:
128             message_queue["messages"][-1] += new_messages[0]
129             del new_messages[0]
130         message_queue["messages"] += new_messages
131         if new_open_end:
132             message_queue["open_end"] = True
133
134     def set_and_redraw_windows(*ignore):
135         set_windows()
136         draw_screen()
137
138     curses.noecho()
139     curses.curs_set(False)
140     signal.signal(signal.SIGWINCH, set_and_redraw_windows)
141     set_windows()
142     delay = 1
143     while True:
144         stdscr.timeout(int(delay))
145         if delay < 1000:
146             delay = delay * 1.1
147         if redraw_windows:
148             delay = 1
149             draw_screen()
150             redraw_windows = False
151         char = stdscr.getch()
152         if char >= 0:
153             char = chr(char)
154             if char in commands:
155                 if len(commands[char]) == 1 or not world_data["look_mode"]:
156                     commands[char][0]()
157                 else:
158                     commands[char][1]()
159                 redraw_windows = True
160         new_data_from_server = io["file_in"].read()
161         ping_test()
162         read_into_message_queue()
163         read_worldstate()
164         read_message_queue()
165
166
167 try:
168     if (not os.access(io["path_out"], os.F_OK)):
169         msg = "No server input file found at " + io["path_out"] + "."
170         raise SystemExit(msg)
171     io["file_out"] = open(io["path_out"], "a")
172     io["file_in"] = open(io["path_in"], "r")
173     curses.wrapper(cursed_main)
174 except SystemExit as exit:
175     print("ABORTING: " + exit.args[0])
176 except:
177     print("SOMETHING WENT WRONG IN UNEXPECTED WAYS")
178     raise
179 finally:
180     if "file_out" in io:
181         io["file_out"].close()
182     if "file_in" in io:
183         io["file_in"].close()