Eliminated warnings about static functions declared with G_GNUC_INTERNAL
[projects/chimara/chimara.git] / src / stream.c
index da470ba2b48b41514a3241b7385bba849a12439e..804399213ae7cbe87ebcbb96134130d5d4d51dd6 100644 (file)
@@ -1,52 +1,62 @@
 #include "stream.h"
 #include "fileref.h"
-#include <string.h>
+#include "magic.h"
+#include <errno.h>
 #include <stdio.h>
+#include <glib.h>
 #include <glib/gstdio.h>
 
-/* Global current stream */
-static strid_t current_stream = NULL;
-/* List of streams currently in existence */
-static GList *stream_list = NULL;
+#include "chimara-glk-private.h"
+extern ChimaraGlkPrivate *glk_data;
+
+/* Internal function: create a stream with a specified rock value */
+static strid_t
+stream_new_common(glui32 rock, glui32 fmode, enum StreamType type)
+{
+       strid_t str = g_new0(struct glk_stream_struct, 1);
+       str->magic = MAGIC_STREAM;
+       str->rock = rock;
+       str->file_mode = fmode;
+       str->type = type;
+               
+       /* Add it to the global stream list */
+       glk_data->stream_list = g_list_prepend(glk_data->stream_list, str);
+       str->stream_list = glk_data->stream_list;
+       
+       return str;
+}
 
 /* Internal function: create a window stream to go with window. */
 strid_t
 window_stream_new(winid_t window)
 {
        /* Create stream and connect it to window */
-       strid_t s = g_new0(struct glk_stream_struct, 1);
-       s->file_mode = filemode_Write;
-       s->stream_type = STREAM_TYPE_WINDOW;
-       s->window = window;
-       /* Add it to the global stream list */
-       stream_list = g_list_prepend(stream_list, s);
-       s->stream_list = stream_list;
-
-       return s;
+       strid_t str = stream_new_common(0, filemode_Write, STREAM_TYPE_WINDOW);
+       str->window = window;
+       str->style = "normal";
+       return str;
 }
 
 /**
  * glk_stream_iterate:
- * @str: A stream, or #NULL.
- * @rockptr: Return location for the next window's rock, or #NULL.
- *
- * Iterates over the list of streams; if @str is #NULL, it returns the first
- * stream, otherwise the next stream after @str. If there are no more, it
- * returns #NULL. The stream's rock is stored in @rockptr. If you don't want
- * the rocks to be returned, you may set @rockptr to #NULL.
+ * @str: A stream, or %NULL.
+ * @rockptr: Return location for the next window's rock, or %NULL.
  *
- * The order in which streams are returned is arbitrary. The order may change
- * every time you create or destroy a stream, invalidating the iteration.
+ * Iterates through all the existing streams. See <link
+ * linkend="chimara-Iterating-Through-Opaque-Objects">Iterating Through Opaque
+ * Objects</link>.
  *
- * Returns: the next stream, or #NULL if there are no more.
+ * Returns: the next stream, or %NULL if there are no more.
  */
 strid_t
 glk_stream_iterate(strid_t str, glui32 *rockptr)
 {
+       VALID_STREAM_OR_NULL(str, return NULL);
+       
        GList *retnode;
        
        if(str == NULL)
-               retnode = stream_list;
+               retnode = glk_data->stream_list;
        else
                retnode = str->stream_list->next;
        strid_t retval = retnode? (strid_t)retnode->data : NULL;
@@ -62,75 +72,115 @@ glk_stream_iterate(strid_t str, glui32 *rockptr)
  * glk_stream_get_rock:
  * @str: A stream.
  * 
- * Returns the stream @str's rock value.
+ * Retrieves the stream @str's rock value. See <link 
+ * linkend="chimara-Rocks">Rocks</link>.
  *
  * Returns: A rock value.
  */
 glui32
 glk_stream_get_rock(strid_t str)
 {
-       g_return_val_if_fail(str != NULL, 0);
+       VALID_STREAM(str, return 0);
        return str->rock;
 }
 
 /**
  * glk_stream_set_current:
- * @str: An output stream, or NULL.
+ * @str: An output stream, or %NULL.
  *
- * Sets the current stream to @str, or to nothing if @str is #NULL.
+ * Sets the current stream to @str, which must be an output stream. You may set
+ * the current stream to %NULL, which means the current stream is not set to
+ * anything. 
  */
 void
 glk_stream_set_current(strid_t str)
 {
-       if(str != NULL && str->file_mode != filemode_Write)
+       VALID_STREAM_OR_NULL(str, return);
+       
+       if(str != NULL && str->file_mode == filemode_Read)
        {
-               g_warning("glk_stream_set_current: "
-                       "Cannot set current stream to non output stream");
+               ILLEGAL("Cannot set current stream to non output stream");
                return;
        }
 
-       current_stream = str;
+       glk_data->current_stream = str;
 }
 
 /**
  * glk_stream_get_current:
  * 
- * Returns the current stream, or #NULL if there is none.
+ * Returns the current stream, or %NULL if there is none.
  *
- * Returns: A stream.
+ * Returns: A stream, or %NULL.
  */
 strid_t
 glk_stream_get_current()
 {
-       return current_stream;
+       return glk_data->current_stream;
 }
 
 /**
  * glk_put_char:
  * @ch: A character in Latin-1 encoding.
  *
- * Prints one character @ch to the current stream.
+ * Prints one character to the current stream. As with all basic functions, the
+ * character is assumed to be in the Latin-1 character encoding. See <link
+ * linkend="chimara-Character-Encoding">Character Encoding</link>.
  */
 void
 glk_put_char(unsigned char ch)
 {
-       /* Illegal to print to the current stream if it is NULL */
-       g_return_if_fail(current_stream != NULL);
-       glk_put_char_stream(current_stream, ch);
+       VALID_STREAM(glk_data->current_stream, return);
+       glk_put_char_stream(glk_data->current_stream, ch);
+}
+
+/**
+ * glk_put_char_uni:
+ * @ch: A Unicode code point.
+ *
+ * Prints one character to the current stream. The character is assumed to be a
+ * Unicode code point. See <link linkend="chimara-Character-Encoding">Character
+ * Encoding</link>.
+ */
+void
+glk_put_char_uni(glui32 ch)
+{
+       VALID_STREAM(glk_data->current_stream, return);
+       glk_put_char_stream_uni(glk_data->current_stream, ch);
 }
 
 /**
  * glk_put_string:
  * @s: A null-terminated string in Latin-1 encoding.
  *
- * Prints @s to the current stream.
+ * Prints a null-terminated string to the current stream. It is exactly
+ * equivalent to
+ * |[
+ * for (ptr = @s; *ptr; ptr++)
+ *     #glk_put_char(*ptr);
+ * ]|
+ * However, it may be more efficient.
  */
 void
 glk_put_string(char *s)
 {
-       /* Illegal to print to the current stream if it is NULL */
-       g_return_if_fail(current_stream != NULL);
-       glk_put_string_stream(current_stream, s);
+       VALID_STREAM(glk_data->current_stream, return);
+       glk_put_string_stream(glk_data->current_stream, s);
+}
+
+/**
+ * glk_put_string_uni:
+ * @s: A zero-terminated string of Unicode code points.
+ * 
+ * Prints a string of Unicode characters to the current stream. It is equivalent
+ * to a series of glk_put_char_uni() calls. A string ends on a #glui32 whose
+ * value is 0.
+ */
+void
+glk_put_string_uni(glui32 *s)
+{
+       VALID_STREAM(glk_data->current_stream, return);
+       glk_put_string_stream_uni(glk_data->current_stream, s);
 }
 
 /**
@@ -138,170 +188,108 @@ glk_put_string(char *s)
  * @buf: An array of characters in Latin-1 encoding.
  * @len: Length of @buf.
  *
- * Prints @buf to the current stream.
+ * Prints a block of characters to the current stream. It is exactly equivalent
+ * to:
+ * |[
+ * for (i = 0; i < @len; i++)
+ *     #glk_put_char(@buf[i]);
+ * ]|
+ * However, it may be more efficient.
  */
 void
 glk_put_buffer(char *buf, glui32 len)
 {
-       /* Illegal to print to the current stream if it is NULL */
-       g_return_if_fail(current_stream != NULL);
-       glk_put_buffer_stream(current_stream, buf, len);
+       VALID_STREAM(glk_data->current_stream, return);
+       glk_put_buffer_stream(glk_data->current_stream, buf, len);
 }
 
 /**
- * glk_put_char_stream:
- * @str: An output stream.
- * @ch: A character in Latin-1 encoding.
+ * glk_put_buffer_uni:
+ * @buf: An array of Unicode code points.
+ * @len: Length of @buf.
  *
- * Prints one character @ch to the stream @str. It is illegal for @str to be
- * #NULL, or an input-only stream.
+ * Prints a block of Unicode characters to the current stream. It is equivalent
+ * to a series of glk_put_char_uni() calls.
  */
 void
-glk_put_char_stream(strid_t str, unsigned char ch)
+glk_put_buffer_uni(glui32 *buf, glui32 len)
 {
-       g_return_if_fail(str != NULL);
-       g_return_if_fail(str->file_mode != filemode_Read);
-       
-       /* Convert ch to a null-terminated string, call glk_put_string_stream() */
-       gchar *s = g_strndup((gchar *)&ch, 1);
-       glk_put_string_stream(str, s);
-       g_free(s);
-}
-
-/* Internal function: change illegal (control) characters in a string to a
-placeholder character. Must free returned string afterwards. */
-static gchar *
-remove_latin1_control_characters(gchar *s)
-{
-       gchar *retval = g_strdup(s);
-       unsigned char *ptr;
-       for(ptr = (unsigned char *)retval; *ptr != '\0'; ptr++)
-               if( (*ptr < 32 && *ptr != 10) || (*ptr >= 127 && *ptr <= 159) )
-                       *ptr = '?';
-                       /* Our placeholder character is '?'; other options are possible,
-                       like printing "0x7F" or something */
-       return retval;
-}
-
-/* Internal function: convert a Latin-1 string to a UTF-8 string, replacing
-Latin-1 control characters by a placeholder first. The UTF-8 string must be
-freed afterwards. Returns NULL on error. */
-static gchar *
-convert_latin1_to_utf8(gchar *s)
-{
-       GError *error = NULL;
-       gchar *utf8;
-       gchar *canonical = remove_latin1_control_characters(s);
-       utf8 = g_convert(canonical, -1, "UTF-8", "ISO-8859-1", NULL, NULL, &error);
-       g_free(canonical);
-       
-       if(utf8 == NULL)
-       {
-               error_dialog(NULL, error, "Error during latin1->utf8 conversion: ");
-               return NULL;
-       }
-       
-       return utf8;
-}
-
-/* Internal function: write a UTF-8 string to a window's text buffer. */
-static void
-write_utf8_to_window(winid_t win, gchar *s)
-{
-       GtkTextBuffer *buffer = 
-               gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );
-
-       GtkTextIter iter;
-       gtk_text_buffer_get_end_iter(buffer, &iter);
-       gtk_text_buffer_insert(buffer, &iter, s, -1);
+       VALID_STREAM(glk_data->current_stream, return);
+       glk_put_buffer_stream_uni(glk_data->current_stream, buf, len);
 }
 
 /**
- * glk_put_string_stream:
- * @str: An output stream.
- * @s: A null-terminated string in Latin-1 encoding.
+ * glk_stream_open_memory:
+ * @buf: An allocated buffer, or %NULL.
+ * @buflen: Length of @buf.
+ * @fmode: Mode in which the buffer will be opened. Must be one of 
+ * #filemode_Read, #filemode_Write, or #filemode_ReadWrite.
+ * @rock: The new stream's rock value.
  *
- * Prints @s to the stream @str. It is illegal for @str to be #NULL, or an
- * input-only stream.
+ * Opens a stream which reads from or writes to a space in memory. @buf points
+ * to the buffer where output will be read from or written to. @buflen is the
+ * length of the buffer.
+ *
+ * Unicode values (characters greater than 255) cannot be written to the buffer.
+ * If you try, they will be stored as 0x3F (<code>"?"</code>) characters.
+ *
+ * Returns: the new stream, or %NULL on error.
  */
-void
-glk_put_string_stream(strid_t str, char *s)
+strid_t
+glk_stream_open_memory(char *buf, glui32 buflen, glui32 fmode, glui32 rock)
 {
-       g_return_if_fail(str != NULL);
-       g_return_if_fail(str->file_mode != filemode_Read);
-
-       switch(str->stream_type)
-       {
-               case STREAM_TYPE_WINDOW:
-                       /* Each window type has a different way of printing to it */
-                       switch(str->window->window_type)
-                       {
-                               /* Printing to a these windows' streams does nothing */
-                               case wintype_Blank:
-                               case wintype_Pair:
-                               case wintype_Graphics:
-                                       current_stream->write_count += strlen(s);
-                                       break;
-                               /* Text buffer window */        
-                               case wintype_TextBuffer:
-                               {
-                                       gchar *utf8 = convert_latin1_to_utf8(s);
-                                       write_utf8_to_window(str->window, utf8);
-                                       g_free(utf8);
-                               }       
-                                       str->write_count += strlen(s);
-                                       break;
-                               default:
-                                       g_warning("glk_put_string: "
-                                               "Writing to this kind of window unsupported.");
-                       }
-                       
-                       /* Now write the same buffer to the window's echo stream */
-                       if(str->window->echo_stream != NULL)
-                               glk_put_string_stream(str->window->echo_stream, s);
-                       
-                       break;
-               default:
-                       g_warning("glk_put_string: "
-                               "Writing to this kind of stream unsupported."); 
-       }
+       g_return_val_if_fail(fmode != filemode_WriteAppend, NULL);
+       
+       strid_t str = stream_new_common(rock, fmode, STREAM_TYPE_MEMORY);
+       str->buffer = buf;
+       str->mark = 0;
+       str->buflen = buflen;
+       str->unicode = FALSE;
+       return str;
 }
 
 /**
- * glk_put_buffer_stream:
- * @str: An output stream.
- * @buf: An array of characters in Latin-1 encoding.
- * @len: Length of @buf.
+ * glk_stream_open_memory_uni:
+ * @buf: An allocated buffer, or %NULL.
+ * @buflen: Length of @buf.
+ * @fmode: Mode in which the buffer will be opened. Must be one of 
+ * #filemode_Read, #filemode_Write, or #filemode_ReadWrite.
+ * @rock: The new stream's rock value.
  *
- * Prints @buf to the stream @str. It is illegal for @str to be #NULL, or an
- * input-only stream.
+ * Works just like glk_stream_open_memory(), except that the buffer is an array
+ * of 32-bit words, instead of bytes. This allows you to write and read any
+ * Unicode character. The @buflen is the number of words, not the number of
+ * bytes.
+ * 
+ * Returns: the new stream, or %NULL on error.
  */
-void
-glk_put_buffer_stream(strid_t str, char *buf, glui32 len)
+strid_t
+glk_stream_open_memory_uni(glui32 *buf, glui32 buflen, glui32 fmode, glui32 rock)
 {
-       g_return_if_fail(str != NULL);
-       g_return_if_fail(str->file_mode != filemode_Read);
+       g_return_val_if_fail(fmode != filemode_WriteAppend, NULL);
        
-       /* Convert buf to a null-terminated string, call glk_put_string_stream() */
-       gchar *s = g_strndup(buf, len);
-       glk_put_string_stream(str, s);
-       g_free(s);
+       strid_t str = stream_new_common(rock, fmode, STREAM_TYPE_MEMORY);
+       str->ubuffer = buf;
+       str->mark = 0;
+       str->buflen = buflen;
+       str->unicode = TRUE;
+       return str;
 }
 
 /* Internal function: create a stream using the given parameters. */
 static strid_t
-stream_new(frefid_t fileref, glui32 fmode, glui32 rock, gboolean unicode)
+file_stream_new(frefid_t fileref, glui32 fmode, glui32 rock, gboolean unicode)
 {
-       g_return_val_if_fail(fileref != NULL, NULL);
+       VALID_FILEREF(fileref, return NULL);
        
        gchar *modestr;
-       gboolean binary = fileref->usage & fileusage_BinaryMode;
+       /* Binary mode is 0x000, text mode 0x100 */
+       gboolean binary = !(fileref->usage & fileusage_TextMode);
        switch(fmode) 
        {
                case filemode_Read:
                        if(!g_file_test(fileref->filename, G_FILE_TEST_EXISTS)) {
-                               g_warning("glk_stream_open_file: Tried to open a file in read "
-                                                 "mode that didn't exist!");
+                               ILLEGAL_PARAM("Tried to open a nonexistent file, '%s', in read mode", fileref->filename);
                                return NULL;
                        }
                        modestr = g_strdup(binary? "rb" : "r");
@@ -313,44 +301,53 @@ stream_new(frefid_t fileref, glui32 fmode, glui32 rock, gboolean unicode)
                        modestr = g_strdup(binary? "ab" : "a");
                        break;
                case filemode_ReadWrite:
-                       modestr = g_strdup(binary? "r+b" : "r+");
+                       if( g_file_test(fileref->filename, G_FILE_TEST_EXISTS) ) {
+                               modestr = g_strdup(binary? "r+b" : "r+");
+                       } else {
+                               modestr = g_strdup(binary? "w+b" : "w+");
+                       }
                        break;
                default:
-                       g_warning("glk_stream_open_file: Invalid file mode");
+                       ILLEGAL_PARAM("Invalid file mode: %u", fmode);
                        return NULL;
        }
        
        FILE *fp = g_fopen(fileref->filename, modestr);
        g_free(modestr);
        if(fp == NULL) {
-               g_warning("glk_stream_open_file: Error opening file");
+               IO_WARNING( "Error opening file", fileref->filename, g_strerror(errno) );
                return NULL;
        }
        
        /* If they opened a file in write mode but didn't specifically get
        permission to do so, complain if the file already exists */
        if(fileref->orig_filemode == filemode_Read && fmode != filemode_Read) {
+               gdk_threads_enter();
+
                GtkWidget *dialog = gtk_message_dialog_new(NULL, 0,
                        GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO,
-                       "File %s already exists. Overwrite?", fileref->filename);
+                       "File '%s' already exists. Overwrite?", fileref->filename);
                gint response = gtk_dialog_run(GTK_DIALOG(dialog));
                gtk_widget_destroy(dialog);
+
+               gdk_threads_leave();
+
                if(response != GTK_RESPONSE_YES) {
-                       fclose(fp);
+                       if(fclose(fp) != 0)
+                               IO_WARNING( "Error closing file", fileref->filename, g_strerror(errno) );
                        return NULL;
                }
        }
        
-       strid_t s = g_new0(struct glk_stream_struct, 1);
-       s->file_mode = fmode;
-       s->stream_type = unicode? STREAM_TYPE_UNICODE_FILE : STREAM_TYPE_FILE;
-       s->file_pointer = fp;
-       s->binary = binary;
-       /* Add it to the global stream list */
-       stream_list = g_list_prepend(stream_list, s);
-       s->stream_list = stream_list;
+       strid_t str = stream_new_common(rock, fmode, STREAM_TYPE_FILE);
+       str->file_pointer = fp;
+       str->binary = binary;
+       str->unicode = unicode;
+       str->filename = g_filename_to_utf8(fileref->filename, -1, NULL, NULL, NULL);
+       if(str->filename == NULL)
+               str->filename = g_strdup("Unknown file name"); /* fail silently */
 
-       return s;
+       return str;
 }
 
 /**
@@ -366,21 +363,19 @@ stream_new(frefid_t fileref, glui32 fmode, glui32 rock, gboolean unicode)
  * already exists, it is truncated down to zero length (an empty file). If
  * @fmode is #filemode_WriteAppend, the file mark is set to the end of the 
  * file.
- * 
- * The file may be written in text or binary mode; this is determined by the
- * @fileref argument. Similarly, platform-dependent attributes such as file 
- * type are determined by @fileref.
  *
  * When writing in binary mode, Unicode values (characters greater than 255)
- * cannot be written to the file. If you try, they will be stored as 0x3F ("?")
- * characters. In text mode, Unicode values are stored in UTF-8.
+ * cannot be written to the file. If you try, they will be stored as 0x3F
+ * (<code>"?"</code>) characters. In text mode, Unicode values may be stored
+ * exactly, approximated, or abbreviated, depending on what the platform's text
+ * files support.
  *
  * Returns: A new stream, or %NULL if the file operation failed.
  */
 strid_t
 glk_stream_open_file(frefid_t fileref, glui32 fmode, glui32 rock)
 {
-       return stream_new(fileref, fmode, rock, FALSE);
+       return file_stream_new(fileref, fmode, rock, FALSE);
 }
 
 /**
@@ -394,13 +389,90 @@ glk_stream_open_file(frefid_t fileref, glui32 fmode, glui32 rock)
  * characters are written and read as four-byte (big-endian) values. This
  * allows you to write any Unicode character.
  *
- * In text mode, the file is written and read in UTF-8.
+ * In text mode, the file is written and read in a platform-dependent way, which
+ * may or may not handle all Unicode characters. A text-mode file created with
+ * glk_stream_open_file_uni() may have the same format as a text-mode file
+ * created with glk_stream_open_file(); or it may use a more Unicode-friendly
+ * format.
  *
  * Returns: A new stream, or %NULL if the file operation failed.
  */
 strid_t
 glk_stream_open_file_uni(frefid_t fileref, glui32 fmode, glui32 rock)
 {
-       return stream_new(fileref, fmode, rock, TRUE);
+       return file_stream_new(fileref, fmode, rock, TRUE);
+}
+
+/**
+ * glk_stream_close:
+ * @str: Stream to close.
+ * @result: Pointer to a #stream_result_t, or %NULL.
+ *
+ * Closes the stream @str. The @result argument points to a structure which is
+ * filled in with the final character counts of the stream. If you do not care
+ * about these, you may pass %NULL as the @result argument.
+ *
+ * If @str is the current output stream, the current output stream is set to
+ * %NULL.
+ *
+ * You cannot close window streams; use glk_window_close() instead. See <link
+ * linkend="chimara-Window-Opening-Closing-and-Constraints">Window Opening,
+ * Closing, and Constraints</link>.
+ */
+void 
+glk_stream_close(strid_t str, stream_result_t *result)
+{
+       VALID_STREAM(str, return);
+       
+       /* Free resources associated with one specific type of stream */
+       switch(str->type)
+       {
+               case STREAM_TYPE_WINDOW:
+                       ILLEGAL("Attempted to close a window stream. Use glk_window_close() instead.");
+                       return;
+                       
+               case STREAM_TYPE_MEMORY:
+                       /* Do nothing */
+                       break;
+                       
+               case STREAM_TYPE_FILE:
+                       if(fclose(str->file_pointer) != 0)
+                               IO_WARNING( "Failed to close file", str->filename, g_strerror(errno) );
+                       g_free(str->filename);
+                       break;
+               default:
+                       ILLEGAL_PARAM("Unknown stream type: %u", str->type);
+                       return;
+       }
+
+       stream_close_common(str, result);
 }
 
+/* Internal function: Stuff to do upon closing any type of stream. */
+void
+stream_close_common(strid_t str, stream_result_t *result)
+{
+       /* Remove the stream from the global stream list */
+       glk_data->stream_list = g_list_delete_link(glk_data->stream_list, str->stream_list);
+       
+       /* If it was the current output stream, set that to NULL */
+       if(glk_data->current_stream == str)
+               glk_data->current_stream = NULL;
+               
+       /* If it was one or more windows' echo streams, set those to NULL */
+       winid_t win;
+       for(win = glk_window_iterate(NULL, NULL); win; 
+               win = glk_window_iterate(win, NULL))
+               if(win->echo_stream == str)
+                       win->echo_stream = NULL;
+                       
+       /* Return the character counts */
+       if(result) 
+       {
+               result->readcount = str->read_count;
+               result->writecount = str->write_count;
+       }
+       
+       str->magic = MAGIC_FREE;
+       g_free(str);
+}