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