home · contact · privacy
On world (re-)generation, server sends 'NEW_WORLD', client clears log.
[plomrogue] / src / client / io.c
index 2f7d18ad25f5c6c6fc43db5657700b750cd0b23e..45008155098ac03150c1ad53bf6a9ea8f503866c 100644 (file)
@@ -1,24 +1,33 @@
-/* src/client/io.c */
+/* src/client/io.c
+ *
+ * This file is part of PlomRogue. PlomRogue is licensed under the GPL version 3
+ * or any later version. For details on its copyright, license, and warranties,
+ * see the file NOTICE in the root directory of the PlomRogue source package.
+ */
 
+#define _POSIX_C_SOURCE 1 /* PIPE_BUF */
 #include "io.h"
-#include <errno.h> /* global errno */
-#include <fcntl.h> /* open() */
 #include <limits.h> /* PIPE_BUF */
 #include <ncurses.h> /* halfdelay(), getch() */
+#include <stddef.h> /* NULL */
 #include <stdint.h> /* uint8_t, uint16_t, uint32_t */
-#include <stdio.h> /* FILE, sprintf(), fseek() */
+#include <stdio.h> /* FILE, sprintf(), fseek(), fflush() */
 #include <string.h> /* strcmp(), strlen(), memcpy() */
 #include <stdlib.h> /* free(), atoi() */
 #include <sys/stat.h> /* stat() */
-#include <unistd.h> /* access(), write() */
+#include <sys/types.h> /* time_t */
+#include <time.h> /* time() */
+#include <unistd.h> /* access() */
 #include "../common/try_malloc.h" /* try_malloc() */
 #include "../common/rexit.h" /* exit_trouble(), exit_err() */
 #include "../common/readwrite.h" /* try_fopen(), try_fclose(), try_fgets(),
-                                  * try_fgetc()
+                                  * try_fgetc(), textfile_width(), try_fputc(),
+                                  * read_file_into_queue(),
+                                  * get_message_from_queue(),
                                   */
 #include "control.h" /* try_key() */
-#include "map_window.h" /* for map_center() */
-#include "windows.h" /* draw_all_wins() */
+#include "map.h" /* map_center() */
+#include "windows.h" /* reset_windows_on_winch(), draw_all_wins() */
 #include "world.h" /* world global */
 
 
  */
 static void read_inventory(char * read_buf, uint32_t linemax, FILE * file);
 
-/* Read the next characters in "file" into world.map.cells. In detail: Read
- * world.map.size.y times world.map.size.x characters, followed by one ignored
+/* Read the next characters in "file" into "map". In detail: Read
+ * world.map.length times world.map.length characters, followed by one ignored
  * character (that we assume is a newline).
  */
-static void read_map_cells(FILE * file);
-
-/* Repeatedly use try_fgets() with given arguments to read the remaining lines
- * of "file" into the world.log string.
- */
-static void read_log(char * read_buf, uint32_t linemax, FILE * file);
+static void read_map_cells(FILE * file, char ** map);
 
 /* Return value seen by atoi() in next line of "file" when passed to try_fgets()
  * with the given arguments.
@@ -45,8 +49,8 @@ static void read_log(char * read_buf, uint32_t linemax, FILE * file);
 static uint16_t read_value_from_line(char * read_buf, uint32_t linemax,
                                      FILE * file);
 
-/* If the server's out file has changed since the last read_world(), return a
- * pointer to its file descriptor; else, return NULL.
+/* If the server's worldstate file has changed since the last read_worldstate(),
+ * return a pointer to its file descriptor; else, return NULL.
  *
  * Two tests are performed to check for a file change. The file's last data
  * modification time in seconds via stat() is compared against world.last_update
@@ -59,41 +63,50 @@ static uint16_t read_value_from_line(char * read_buf, uint32_t linemax,
  * the new world also starts in turn 1, not signifying any world change to the
  * turn check. The stat() check detects this change with at most 1 second delay.
  */
-static FILE * changed_server_out_file(char * path);
+static FILE * changed_worldstate_file(char * path);
 
-/* Attempt to read the server's out file as representation of the game world in
- * a hard-coded serialization format. Returns 1 on success and 0 if the out file
- * wasn't read for supposedly not having changed since a last read_world() call.
+/* Attempt to read the server's worldstate file as representation of the game
+ * world in a hard-coded serialization format. Returns 1 on success, or 0 if the
+ * out file wasn't read for supposedly not having changed since a last
+ * read_worldstate() call.
  *
- * Note that the first successful read_world() triggers map_center(), so that on
- * start the client focuses the map window on the player.
+ * map_center() is triggered by either, the first successful read_worldstate()
+ * (thus on client start), or on turn 1 (thus on world start).
+ */
+static uint8_t read_worldstate();
+
+/* Poll server for queue input. If no new input, send ping, or, if ping already
+ * sent but unanswered for some time, abort.
  */
-static uint8_t read_world();
+static void test_and_poll_server();
+
+/* Read messages from queue, act on them. */
+static uint8_t read_queue();
 
 
 
 static void read_inventory(char * read_buf, uint32_t linemax, FILE * file)
 {
-    char * f_name = "read_inventory()";
     char * delimiter = "%\n";
     free(world.player_inventory);
-    world.player_inventory = NULL;
+    world.player_inventory = NULL;          /* Avoids illegal strlen() below. */
     while (1)
     {
-        try_fgets(read_buf, linemax + 1, file, f_name);
+        try_fgets(read_buf, linemax + 1, file, __func__);
         if (!(strcmp(read_buf, delimiter)))
         {
             break;
         }
         int old_size = 0;
-        if (NULL != world.player_inventory)
+        if (world.player_inventory)
         {
             old_size = strlen(world.player_inventory);
         }
         int new_size = strlen(read_buf);
-        char * new_inventory = try_malloc(old_size + new_size + 1, f_name);
+        char * new_inventory = try_malloc(old_size + new_size + 1, __func__);
         memcpy(new_inventory, world.player_inventory, old_size);
-        sprintf(new_inventory + old_size, "%s", read_buf);
+        int test = sprintf(new_inventory + old_size, "%s", read_buf);
+        exit_trouble(test < 0, __func__, "sprintf");
         free(world.player_inventory);
         world.player_inventory = new_inventory;
     }
@@ -103,43 +116,24 @@ static void read_inventory(char * read_buf, uint32_t linemax, FILE * file)
 
 
 
-static void read_map_cells(FILE * file)
+static void read_map_cells(FILE * file, char ** map)
 {
-    char * f_name = "read_map_cells()";
-    free(world.map.cells);
-    world.map.cells = try_malloc(world.map.size.y * world.map.size.x, f_name);
-    uint16_t y, x;
-    for (y = 0; y < world.map.size.y; y++)
+    if (*map)
     {
-        for (x = 0; x < world.map.size.x; x++)
-        {
-            char c = try_fgetc(file, f_name);
-            world.map.cells[(y * world.map.size.x) + x] = c;
-        }
-        try_fgetc(file, f_name);
+        free(*map);
+        *map = NULL;
     }
-}
-
-
-
-static void read_log(char * read_buf, uint32_t linemax, FILE * file)
-{
-    char * f_name = "read_log()";
-    free(world.log);
-    world.log = NULL;
-    while (try_fgets(read_buf, linemax + 1, file, f_name))
+    *map = try_malloc(world.map.length * world.map.length, __func__);
+    char * map_cells = *map;
+    uint16_t y, x;
+    for (y = 0; y < world.map.length; y++)
     {
-        int old_size = 0;
-        if (NULL != world.log)
+        for (x = 0; x < world.map.length; x++)
         {
-            old_size = strlen(world.log);
+            char c = try_fgetc(file, __func__);
+            map_cells[y * world.map.length + x] = c;
         }
-        int new_size = strlen(read_buf);
-        char * new_log = try_malloc(old_size + new_size + 1, f_name);
-        memcpy(new_log, world.log, old_size);
-        sprintf(new_log + old_size, "%s", read_buf);
-        free(world.log);
-        world.log = new_log;
+        try_fgetc(file, __func__);
     }
 }
 
@@ -148,117 +142,166 @@ static void read_log(char * read_buf, uint32_t linemax, FILE * file)
 static uint16_t read_value_from_line(char * read_buf, uint32_t linemax,
                                      FILE * file)
 {
-    char * f_name = "read_value_from_line()";
-    try_fgets(read_buf, linemax + 1, file, f_name);
+    try_fgets(read_buf, linemax + 1, file, __func__);
     return atoi(read_buf);
 }
 
 
 
-static FILE * changed_server_out_file(char * path)
+static FILE * changed_worldstate_file(char * path)
 {
-    char * f_name = "changed_server_out_file()";
     struct stat stat_buf;
-    exit_trouble(stat(path, &stat_buf), f_name, "stat()");
+    exit_trouble(stat(path, &stat_buf), __func__, "stat");
     if (stat_buf.st_mtime != world.last_update)
     {
         world.last_update = stat_buf.st_mtime;
-        return try_fopen(path, "r", f_name);
+        return try_fopen(path, "r", __func__);
     }
-    FILE * file = try_fopen(path, "r", f_name);
+    FILE * file = try_fopen(path, "r", __func__);
     char turn_string[6];
-    try_fgets(turn_string, 6, file, f_name);
+    try_fgets(turn_string, 6, file, __func__);
     if (world.turn == atoi(turn_string))
     {
-        try_fclose(file, f_name);
+        try_fclose(file, __func__);
         return NULL;
     }
-    exit_trouble(fseek(file, 0, SEEK_SET), f_name, "fseek()");
+    exit_trouble(fseek(file, 0, SEEK_SET), __func__, "fseek");
     return file;
 }
 
 
 
-static uint8_t read_world()
+static uint8_t read_worldstate()
 {
-    char * f_name = "read_world()";
-    char * path = "server/out";
-    char * quit_msg = "No server out file found to read. Server may be down.";
+    char * path = "server/worldstate";
+    char * quit_msg = "No worldstate file found to read. Server may be down.";
     static uint8_t first_read = 1;
     exit_err(access(path, F_OK), quit_msg);
-    FILE * file = changed_server_out_file(path);
+    FILE * file = changed_worldstate_file(path);
     if (!file)
     {
         return 0;
     }
-    uint32_t linemax = textfile_sizes(file, NULL);
-    char * read_buf = try_malloc(linemax + 1, f_name);
+    uint32_t linemax = textfile_width(file);
+    char * read_buf = try_malloc(linemax + 1, __func__);
     world.turn = read_value_from_line(read_buf, linemax, file);
-    world.score = read_value_from_line(read_buf, linemax, file);
     world.player_lifepoints = read_value_from_line(read_buf, linemax, file);
     read_inventory(read_buf, linemax, file);
     world.player_pos.y = read_value_from_line(read_buf, linemax, file);
     world.player_pos.x = read_value_from_line(read_buf, linemax, file);
-    if (first_read)
+    if (1 == world.turn || first_read)
     {
         map_center();
         first_read = 0;
     }
-    world.map.size.y = read_value_from_line(read_buf, linemax, file);
-    world.map.size.x = read_value_from_line(read_buf, linemax, file);
-    read_map_cells(file);
-    read_log(read_buf, linemax, file);
+    world.map.length = read_value_from_line(read_buf, linemax, file);
+    read_map_cells(file, &world.map.cells);
+    read_map_cells(file, &world.mem_map);
     free(read_buf);
-    try_fclose(file, f_name);
+    try_fclose(file, __func__);
     return 1;
 }
 
 
 
-extern void try_send(char * msg)
+static void test_and_poll_server()
 {
-    char * f_name = "try_send()";
-    uint32_t msg_size = strlen(msg) + 1;
-    char * err = "try_send() tries to send message larger than PIPE_BUF bytes.";
-    exit_err(msg_size > PIPE_BUF, err);
-    int fd_out;
-    uint16_t j = 1;
-    while (0 != j)
+    static time_t last_server_answer_time = 0;
+    static uint8_t ping_sent = 0;
+    if (read_file_into_queue(world.file_server_out, &world.queue))
     {
-        fd_out = open(world.path_server_in, O_WRONLY | O_NONBLOCK);
-        if (fd_out > 0)
-        {
-            break;
-        }
-        exit_err(-1 == fd_out && ENXIO != errno, "Server fifo not found.");
-        j++;
+        last_server_answer_time = time(0);
+        return;
+    }
+    time_t now = time(0);
+    if (ping_sent && last_server_answer_time > now - 3)  /* Re-set if last    */
+    {                                                    /* ping was answered */
+        ping_sent = 0;                                   /* with server       */
+        return;                                          /* activity.         */
     }
-    exit_err(0 == j, "Failed to open server fifo for writing.");
-    j = 1;
-    while (0 != j)
+    if (!ping_sent && last_server_answer_time < now - 3)
     {
-        int test = write(fd_out, msg, msg_size);
-        if (test > 0)
+        send("PING");
+        ping_sent = 1;
+        return;
+    }
+    exit_err(last_server_answer_time < now - 6, "Server not answering.");
+}
+
+
+
+static uint8_t read_queue()
+{
+    uint8_t ret = 0;
+    char * msg;
+    while (NULL != (msg = get_message_from_queue(&world.queue)))
+    {
+        char * log_prefix = "LOG ";
+        char * new_world = "NEW_WORLD";
+        if (!strcmp(msg, new_world))
         {
-            break;
+            ret = 1;
+            free(world.log);
+            world.log = NULL;
+        }
+        else if (!strncmp(msg, log_prefix, strlen(log_prefix)))
+        {
+            ret = 1;
+            char * log_msg = msg + strlen(log_prefix);
+            int old_size = 0;
+            if (world.log)
+            {
+                old_size = strlen(world.log);
+            }
+            int new_size = strlen(log_msg);
+            char * new_log = try_malloc(old_size + 1 + new_size + 1, __func__);
+            memcpy(new_log, world.log, old_size);
+            int test = sprintf(new_log + old_size, "\n%s", log_msg);
+            exit_trouble(test < 0, __func__, "sprintf");
+            free(world.log);
+            world.log = new_log;
         }
-        j++;
+        free(msg);
     }
-    exit_err(0 == j, "Failed to write to server fifo.");
-    exit_trouble(-1 == close(fd_out), f_name, "close()");
+    return ret;
+}
+
+
+
+extern void send(char * msg)
+{
+    uint32_t msg_size = strlen(msg) + 1;
+    char * err = "send() tried to send message larger than PIPE_BUF bytes.";
+    exit_err(msg_size > PIPE_BUF, err);
+    try_fwrite(msg, strlen(msg), 1, world.file_server_in, __func__);
+    try_fputc('\n', world.file_server_in, __func__);
+    fflush(world.file_server_in);
 }
 
 
 
 extern char * io_loop()
 {
-    world.halfdelay = 1;            /* Ensures read_world() is only called 10 */
-    halfdelay(world.halfdelay);     /* times a second during user inactivity. */
+    world.halfdelay = 1;             /* Ensure server is polled only 10 times */
+    halfdelay(world.halfdelay);      /* a second during user inactivity.      */
     uint8_t change_in_client = 0;
+    uint16_t last_focused_turn = world.turn;
     while (1)
     {
-        if (read_world() || change_in_client)
+        test_and_poll_server();
+        if (world.winch)
+        {
+            reset_windows_on_winch();
+            world.winch = 0;
+            change_in_client++;
+        }
+        if (change_in_client || read_worldstate() || read_queue())
         {
+            if (world.turn != last_focused_turn && world.focus_each_turn)
+            {
+                last_focused_turn = world.turn;
+                map_center();
+            }
             draw_all_wins();
         }
         change_in_client = 0;
@@ -272,6 +315,6 @@ extern char * io_loop()
             }
         }
     }
-    try_send("QUIT");
+    send("QUIT");
     return "Sent QUIT to server.";
 }