Fixed shutdown problems. Everything should properly shut down now.
[rodin/chimara.git] / libchimara / stream.c
1 #include "stream.h"
2 #include "fileref.h"
3 #include "magic.h"
4 #include <errno.h>
5 #include <stdio.h>
6 #include <glib.h>
7 #include <glib/gstdio.h>
8
9 #include "chimara-glk-private.h"
10 extern GPrivate *glk_data_key;
11
12 /* Internal function: create a stream with a specified rock value */
13 strid_t
14 stream_new_common(glui32 rock)
15 {
16         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
17         
18         strid_t str = g_new0(struct glk_stream_struct, 1);
19         str->magic = MAGIC_STREAM;
20         str->rock = rock;
21         if(glk_data->register_obj)
22                 str->disprock = (*glk_data->register_obj)(str, gidisp_Class_Stream);
23                 
24         /* Add it to the global stream list */
25         glk_data->stream_list = g_list_prepend(glk_data->stream_list, str);
26         str->stream_list = glk_data->stream_list;
27         
28         return str;
29 }
30
31 /* Internal function: Stuff to do upon closing any type of stream. Call only 
32  from Glk thread. */
33 void
34 stream_close_common(strid_t str, stream_result_t *result)
35 {
36         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
37
38         if(glk_data->unregister_obj)
39         {
40                 (*glk_data->unregister_obj)(str, gidisp_Class_Stream, str->disprock);
41                 str->disprock.ptr = NULL;
42         }
43         
44         /* If the stream was one or more windows' echo streams, set those to NULL */
45         winid_t win;
46         for(win = glk_window_iterate(NULL, NULL); win; 
47                 win = glk_window_iterate(win, NULL))
48                 if(win->echo_stream == str)
49                         win->echo_stream = NULL;
50         
51         /* Return the character counts */
52         if(result) 
53         {
54                 result->readcount = str->read_count;
55                 result->writecount = str->write_count;
56         }
57
58         /* Remove the stream from the global stream list */
59         glk_data->stream_list = g_list_delete_link(glk_data->stream_list, str->stream_list);
60         
61         /* If it was the current output stream, set that to NULL */
62         if(glk_data->current_stream == str)
63                 glk_data->current_stream = NULL;
64         
65         str->magic = MAGIC_FREE;
66         g_free(str);
67 }
68
69 /**
70  * glk_stream_iterate:
71  * @str: A stream, or %NULL.
72  * @rockptr: Return location for the next window's rock, or %NULL.
73  *
74  * Iterates through all the existing streams. See <link
75  * linkend="chimara-Iterating-Through-Opaque-Objects">Iterating Through Opaque
76  * Objects</link>.
77  *
78  * Returns: the next stream, or %NULL if there are no more.
79  */
80 strid_t
81 glk_stream_iterate(strid_t str, glui32 *rockptr)
82 {
83         VALID_STREAM_OR_NULL(str, return NULL);
84
85         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
86         GList *retnode;
87         
88         if(str == NULL)
89                 retnode = glk_data->stream_list;
90         else
91                 retnode = str->stream_list->next;
92         strid_t retval = retnode? (strid_t)retnode->data : NULL;
93                 
94         /* Store the stream's rock in rockptr */
95         if(retval && rockptr)
96                 *rockptr = glk_stream_get_rock(retval);
97                 
98         return retval;
99 }
100
101 /**
102  * glk_stream_get_rock:
103  * @str: A stream.
104  * 
105  * Retrieves the stream @str's rock value. See <link 
106  * linkend="chimara-Rocks">Rocks</link>.
107  *
108  * Returns: A rock value.
109  */
110 glui32
111 glk_stream_get_rock(strid_t str)
112 {
113         VALID_STREAM(str, return 0);
114         return str->rock;
115 }
116
117 /**
118  * glk_stream_set_current:
119  * @str: An output stream, or %NULL.
120  *
121  * Sets the current stream to @str, which must be an output stream. You may set
122  * the current stream to %NULL, which means the current stream is not set to
123  * anything. 
124  */
125 void
126 glk_stream_set_current(strid_t str)
127 {
128         VALID_STREAM_OR_NULL(str, return);
129
130         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
131         
132         if(str != NULL && str->file_mode == filemode_Read)
133         {
134                 ILLEGAL("Cannot set current stream to non output stream");
135                 return;
136         }
137
138         glk_data->current_stream = str;
139 }
140
141 /**
142  * glk_stream_get_current:
143  * 
144  * Returns the current stream, or %NULL if there is none.
145  *
146  * Returns: A stream, or %NULL.
147  */
148 strid_t
149 glk_stream_get_current()
150 {
151         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
152         return glk_data->current_stream;
153 }
154
155 /**
156  * glk_put_char:
157  * @ch: A character in Latin-1 encoding.
158  *
159  * Prints one character to the current stream. As with all basic functions, the
160  * character is assumed to be in the Latin-1 character encoding. See <link
161  * linkend="chimara-Character-Encoding">Character Encoding</link>.
162  */
163 void
164 glk_put_char(unsigned char ch)
165 {
166         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
167         VALID_STREAM(glk_data->current_stream, return);
168         glk_put_char_stream(glk_data->current_stream, ch);
169 }
170
171 /**
172  * glk_put_char_uni:
173  * @ch: A Unicode code point.
174  *
175  * Prints one character to the current stream. The character is assumed to be a
176  * Unicode code point. See <link linkend="chimara-Character-Encoding">Character
177  * Encoding</link>.
178  */
179 void
180 glk_put_char_uni(glui32 ch)
181 {
182         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
183         VALID_STREAM(glk_data->current_stream, return);
184         glk_put_char_stream_uni(glk_data->current_stream, ch);
185 }
186
187 /**
188  * glk_put_string:
189  * @s: A null-terminated string in Latin-1 encoding.
190  *
191  * Prints a null-terminated string to the current stream. It is exactly
192  * equivalent to
193  * |[
194  * for (ptr = s; *ptr; ptr++)
195  *      #glk_put_char(*ptr);
196  * ]|
197  * However, it may be more efficient.
198  */
199 void
200 glk_put_string(char *s)
201 {
202         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
203         VALID_STREAM(glk_data->current_stream, return);
204         glk_put_string_stream(glk_data->current_stream, s);
205 }
206
207 /**
208  * glk_put_string_uni:
209  * @s: A zero-terminated string of Unicode code points.
210  * 
211  * Prints a string of Unicode characters to the current stream. It is equivalent
212  * to a series of glk_put_char_uni() calls. A string ends on a #glui32 whose
213  * value is 0.
214  */
215 void
216 glk_put_string_uni(glui32 *s)
217 {
218         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
219         VALID_STREAM(glk_data->current_stream, return);
220         glk_put_string_stream_uni(glk_data->current_stream, s);
221 }
222
223 /**
224  * glk_put_buffer:
225  * @buf: An array of characters in Latin-1 encoding.
226  * @len: Length of @buf.
227  *
228  * Prints a block of characters to the current stream. It is exactly equivalent
229  * to:
230  * |[
231  * for (i = 0; i < len; i++)
232  *      #glk_put_char(buf[i]);
233  * ]|
234  * However, it may be more efficient.
235  */
236 void
237 glk_put_buffer(char *buf, glui32 len)
238 {
239         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
240         VALID_STREAM(glk_data->current_stream, return);
241         glk_put_buffer_stream(glk_data->current_stream, buf, len);
242 }
243
244 /**
245  * glk_put_buffer_uni:
246  * @buf: An array of Unicode code points.
247  * @len: Length of @buf.
248  *
249  * Prints a block of Unicode characters to the current stream. It is equivalent
250  * to a series of glk_put_char_uni() calls.
251  */
252 void
253 glk_put_buffer_uni(glui32 *buf, glui32 len)
254 {
255         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
256         VALID_STREAM(glk_data->current_stream, return);
257         glk_put_buffer_stream_uni(glk_data->current_stream, buf, len);
258 }
259
260 /**
261  * glk_stream_open_memory:
262  * @buf: An allocated buffer, or %NULL.
263  * @buflen: Length of @buf.
264  * @fmode: Mode in which the buffer will be opened. Must be one of 
265  * %filemode_Read, %filemode_Write, or %filemode_ReadWrite.
266  * @rock: The new stream's rock value.
267  *
268  * Opens a stream which reads from or writes to a space in memory. @buf points
269  * to the buffer where output will be read from or written to. @buflen is the
270  * length of the buffer.
271  *
272  * Unicode values (characters greater than 255) cannot be written to the buffer.
273  * If you try, they will be stored as 0x3F (<code>"?"</code>) characters.
274  *
275  * Returns: the new stream, or %NULL on error.
276  */
277 strid_t
278 glk_stream_open_memory(char *buf, glui32 buflen, glui32 fmode, glui32 rock)
279 {
280         g_return_val_if_fail(fmode != filemode_WriteAppend, NULL);
281         
282         strid_t str = stream_new_common(rock);
283         str->file_mode = fmode;
284         str->type = STREAM_TYPE_MEMORY;
285         str->mark = 0;
286         str->unicode = FALSE;
287
288         if(buf && buflen) 
289         {
290                 ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
291                 str->buffer = buf;
292                 str->buflen = buflen;
293                 if(glk_data->register_arr) 
294                         str->buffer_rock = (*glk_data->register_arr)(buf, buflen, "&+#!Cn");
295         }
296         
297         return str;
298 }
299
300 /**
301  * glk_stream_open_memory_uni:
302  * @buf: An allocated buffer, or %NULL.
303  * @buflen: Length of @buf.
304  * @fmode: Mode in which the buffer will be opened. Must be one of 
305  * %filemode_Read, %filemode_Write, or %filemode_ReadWrite.
306  * @rock: The new stream's rock value.
307  *
308  * Works just like glk_stream_open_memory(), except that the buffer is an array
309  * of 32-bit words, instead of bytes. This allows you to write and read any
310  * Unicode character. The @buflen is the number of words, not the number of
311  * bytes.
312  * 
313  * Returns: the new stream, or %NULL on error.
314  */
315 strid_t
316 glk_stream_open_memory_uni(glui32 *buf, glui32 buflen, glui32 fmode, glui32 rock)
317 {
318         g_return_val_if_fail(fmode != filemode_WriteAppend, NULL);
319         
320         strid_t str = stream_new_common(rock);
321         str->file_mode = fmode;
322         str->type = STREAM_TYPE_MEMORY;
323         str->mark = 0;
324         str->unicode = TRUE;
325
326         if(buf && buflen) 
327         {
328                 ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
329                 str->ubuffer = buf;
330                 str->buflen = buflen;
331                 if(glk_data->register_arr) 
332                         str->buffer_rock = (*glk_data->register_arr)(buf, buflen, "&+#!Iu");
333         }
334         
335         return str;
336 }
337
338 /* Internal function: create a stream using the given parameters. */
339 strid_t
340 file_stream_new(frefid_t fileref, glui32 fmode, glui32 rock, gboolean unicode)
341 {
342         VALID_FILEREF(fileref, return NULL);
343         
344         gchar *modestr;
345         /* Binary mode is 0x000, text mode 0x100 */
346         gboolean binary = !(fileref->usage & fileusage_TextMode);
347         switch(fmode) 
348         {
349                 case filemode_Read:
350                         if(!g_file_test(fileref->filename, G_FILE_TEST_EXISTS)) {
351                                 ILLEGAL_PARAM("Tried to open a nonexistent file, '%s', in read mode", fileref->filename);
352                                 return NULL;
353                         }
354                         modestr = g_strdup(binary? "rb" : "r");
355                         break;
356                 case filemode_Write:
357                         modestr = g_strdup(binary? "wb" : "w");
358                         break;
359                 case filemode_WriteAppend:
360                         modestr = g_strdup(binary? "ab" : "a");
361                         break;
362                 case filemode_ReadWrite:
363                         if( g_file_test(fileref->filename, G_FILE_TEST_EXISTS) ) {
364                                 modestr = g_strdup(binary? "r+b" : "r+");
365                         } else {
366                                 modestr = g_strdup(binary? "w+b" : "w+");
367                         }
368                         break;
369                 default:
370                         ILLEGAL_PARAM("Invalid file mode: %u", fmode);
371                         return NULL;
372         }
373         
374         FILE *fp = g_fopen(fileref->filename, modestr);
375         g_free(modestr);
376         if(fp == NULL) {
377                 IO_WARNING( "Error opening file", fileref->filename, g_strerror(errno) );
378                 return NULL;
379         }
380         
381         /* If they opened a file in write mode but didn't specifically get
382         permission to do so, complain if the file already exists */
383         if(fileref->orig_filemode == filemode_Read && fmode != filemode_Read) {
384                 gdk_threads_enter();
385
386                 GtkWidget *dialog = gtk_message_dialog_new(NULL, 0,
387                         GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO,
388                         "File '%s' already exists. Overwrite?", fileref->filename);
389                 gint response = gtk_dialog_run(GTK_DIALOG(dialog));
390                 gtk_widget_destroy(dialog);
391
392                 gdk_threads_leave();
393
394                 if(response != GTK_RESPONSE_YES) {
395                         if(fclose(fp) != 0)
396                                 IO_WARNING( "Error closing file", fileref->filename, g_strerror(errno) );
397                         return NULL;
398                 }
399         }
400         
401         strid_t str = stream_new_common(rock);
402         str->file_mode = fmode;
403         str->type = STREAM_TYPE_FILE;
404         str->file_pointer = fp;
405         str->binary = binary;
406         str->unicode = unicode;
407         str->filename = g_filename_to_utf8(fileref->filename, -1, NULL, NULL, NULL);
408         if(str->filename == NULL)
409                 str->filename = g_strdup("Unknown file name"); /* fail silently */
410
411         return str;
412 }
413
414 /**
415  * glk_stream_open_file:
416  * @fileref: Indicates the file which will be opened.
417  * @fmode: Mode in which the file will be opened. Can be any of %filemode_Read,
418  * %filemode_Write, %filemode_WriteAppend, or %filemode_ReadWrite.
419  * @rock: The new stream's rock value.
420  *
421  * Opens a stream which reads to or writes from a disk file. If @fmode is
422  * %filemode_Read, the file must already exist; for the other modes, an empty
423  * file is created if none exists. If @fmode is %filemode_Write, and the file
424  * already exists, it is truncated down to zero length (an empty file). If
425  * @fmode is %filemode_WriteAppend, the file mark is set to the end of the 
426  * file.
427  *
428  * When writing in binary mode, Unicode values (characters greater than 255)
429  * cannot be written to the file. If you try, they will be stored as 0x3F
430  * (<code>"?"</code>) characters. In text mode, Unicode values may be stored
431  * exactly, approximated, or abbreviated, depending on what the platform's text
432  * files support.
433  *
434  * Returns: A new stream, or %NULL if the file operation failed.
435  */
436 strid_t
437 glk_stream_open_file(frefid_t fileref, glui32 fmode, glui32 rock)
438 {
439         return file_stream_new(fileref, fmode, rock, FALSE);
440 }
441
442 /**
443  * glk_stream_open_file_uni:
444  * @fileref: Indicates the file which will be opened.
445  * @fmode: Mode in which the file will be opened. Can be any of %filemode_Read,
446  * %filemode_Write, %filemode_WriteAppend, or %filemode_ReadWrite.
447  * @rock: The new stream's rock value.
448  *
449  * This works just like glk_stream_open_file(), except that in binary mode,
450  * characters are written and read as four-byte (big-endian) values. This
451  * allows you to write any Unicode character.
452  *
453  * In text mode, the file is written and read in a platform-dependent way, which
454  * may or may not handle all Unicode characters. A text-mode file created with
455  * glk_stream_open_file_uni() may have the same format as a text-mode file
456  * created with glk_stream_open_file(); or it may use a more Unicode-friendly
457  * format.
458  *
459  * Returns: A new stream, or %NULL if the file operation failed.
460  */
461 strid_t
462 glk_stream_open_file_uni(frefid_t fileref, glui32 fmode, glui32 rock)
463 {
464         return file_stream_new(fileref, fmode, rock, TRUE);
465 }
466
467 /**
468  * glk_stream_close:
469  * @str: Stream to close.
470  * @result: Pointer to a #stream_result_t, or %NULL.
471  *
472  * Closes the stream @str. The @result argument points to a structure which is
473  * filled in with the final character counts of the stream. If you do not care
474  * about these, you may pass %NULL as the @result argument.
475  *
476  * If @str is the current output stream, the current output stream is set to
477  * %NULL.
478  *
479  * You cannot close window streams; use glk_window_close() instead. See <link
480  * linkend="chimara-Window-Opening-Closing-and-Constraints">Window Opening,
481  * Closing, and Constraints</link>.
482  */
483 void 
484 glk_stream_close(strid_t str, stream_result_t *result)
485 {
486         VALID_STREAM(str, return);
487         
488         /* Free resources associated with one specific type of stream */
489         switch(str->type)
490         {
491                 case STREAM_TYPE_WINDOW:
492                         ILLEGAL("Attempted to close a window stream. Use glk_window_close() instead.");
493                         return;
494                         
495                 case STREAM_TYPE_MEMORY:
496                 {
497                         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
498                         if(glk_data->unregister_arr) 
499                         {
500                                 if(str->unicode)
501                                         (*glk_data->unregister_arr)(str->ubuffer, str->buflen, "&+#!Iu", str->buffer_rock);
502                                 else
503                                         (*glk_data->unregister_arr)(str->buffer, str->buflen, "&+#!Cn", str->buffer_rock);
504             }
505                 }
506                         break;
507                 
508                 case STREAM_TYPE_FILE:
509                         if(fclose(str->file_pointer) != 0)
510                                 IO_WARNING( "Failed to close file", str->filename, g_strerror(errno) );
511                         g_free(str->filename);
512                         break;
513                 default:
514                         ILLEGAL_PARAM("Unknown stream type: %u", str->type);
515                         return;
516         }
517
518         stream_close_common(str, result);
519 }