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