f9a6cf5bf4cea649c405ff7382dc8a5767276707
[projects/chimara/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>. Window streams always have rock 0; all
107  * other streams return whatever rock you created them with.
108  *
109  * Returns: A rock value.
110  */
111 glui32
112 glk_stream_get_rock(strid_t str)
113 {
114         VALID_STREAM(str, return 0);
115         return str->rock;
116 }
117
118 /**
119  * glk_stream_set_current:
120  * @str: An output stream, or %NULL.
121  *
122  * Sets the current stream to @str, which must be an output stream. You may set
123  * the current stream to %NULL, which means the current stream is not set to
124  * anything. 
125  */
126 void
127 glk_stream_set_current(strid_t str)
128 {
129         VALID_STREAM_OR_NULL(str, return);
130
131         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
132         
133         if(str != NULL && str->file_mode == filemode_Read)
134         {
135                 ILLEGAL("Cannot set current stream to non output stream");
136                 return;
137         }
138
139         glk_data->current_stream = str;
140 }
141
142 /**
143  * glk_stream_get_current:
144  * 
145  * Returns the current stream, or %NULL if there is none.
146  *
147  * Returns: A stream, or %NULL.
148  */
149 strid_t
150 glk_stream_get_current()
151 {
152         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
153         return glk_data->current_stream;
154 }
155
156 /**
157  * glk_put_char:
158  * @ch: A character in Latin-1 encoding.
159  *
160  * Prints one character to the current stream. As with all basic functions, the
161  * character is assumed to be in the Latin-1 character encoding. See <link
162  * linkend="chimara-Character-Encoding">Character Encoding</link>.
163  */
164 void
165 glk_put_char(unsigned char ch)
166 {
167         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
168         VALID_STREAM(glk_data->current_stream, return);
169         glk_put_char_stream(glk_data->current_stream, ch);
170 }
171
172 /**
173  * glk_put_char_uni:
174  * @ch: A Unicode code point.
175  *
176  * Prints one character to the current stream. The character is assumed to be a
177  * Unicode code point. See <link linkend="chimara-Character-Encoding">Character
178  * Encoding</link>.
179  */
180 void
181 glk_put_char_uni(glui32 ch)
182 {
183         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
184         VALID_STREAM(glk_data->current_stream, return);
185         glk_put_char_stream_uni(glk_data->current_stream, ch);
186 }
187
188 /**
189  * glk_put_string:
190  * @s: A null-terminated string in Latin-1 encoding.
191  *
192  * Prints a null-terminated string to the current stream. It is exactly
193  * equivalent to
194  * |[
195  * for (ptr = s; *ptr; ptr++)
196  *     glk_put_char(*ptr);
197  * ]|
198  * However, it may be more efficient.
199  */
200 void
201 glk_put_string(char *s)
202 {
203         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
204         VALID_STREAM(glk_data->current_stream, return);
205         glk_put_string_stream(glk_data->current_stream, s);
206 }
207
208 /**
209  * glk_put_string_uni:
210  * @s: A zero-terminated string of Unicode code points.
211  * 
212  * Prints a string of Unicode characters to the current stream. It is equivalent
213  * to a series of glk_put_char_uni() calls. A string ends on a #glui32 whose
214  * value is 0.
215  */
216 void
217 glk_put_string_uni(glui32 *s)
218 {
219         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
220         VALID_STREAM(glk_data->current_stream, return);
221         glk_put_string_stream_uni(glk_data->current_stream, s);
222 }
223
224 /**
225  * glk_put_buffer:
226  * @buf: An array of characters in Latin-1 encoding.
227  * @len: Length of @buf.
228  *
229  * Prints a block of characters to the current stream. It is exactly equivalent
230  * to:
231  * |[
232  * for (i = 0; i < len; i++)
233  *     glk_put_char(buf[i]);
234  * ]|
235  * However, it may be more efficient.
236  */
237 void
238 glk_put_buffer(char *buf, glui32 len)
239 {
240         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
241         VALID_STREAM(glk_data->current_stream, return);
242         glk_put_buffer_stream(glk_data->current_stream, buf, len);
243 }
244
245 /**
246  * glk_put_buffer_uni:
247  * @buf: An array of Unicode code points.
248  * @len: Length of @buf.
249  *
250  * Prints a block of Unicode characters to the current stream. It is equivalent
251  * to a series of glk_put_char_uni() calls.
252  */
253 void
254 glk_put_buffer_uni(glui32 *buf, glui32 len)
255 {
256         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
257         VALID_STREAM(glk_data->current_stream, return);
258         glk_put_buffer_stream_uni(glk_data->current_stream, buf, len);
259 }
260
261 /**
262  * glk_stream_open_memory:
263  * @buf: An allocated buffer, or %NULL.
264  * @buflen: Length of @buf.
265  * @fmode: Mode in which the buffer will be opened. Must be one of 
266  * %filemode_Read, %filemode_Write, or %filemode_ReadWrite.
267  * @rock: The new stream's rock value.
268  *
269  * Opens a stream which reads from or writes to a space in memory. @buf points
270  * to the buffer where output will be read from or written to. @buflen is the
271  * length of the buffer.
272  *
273  * Unicode values (characters greater than 255) cannot be written to the buffer.
274  * If you try, they will be stored as 0x3F (<code>"?"</code>) characters.
275  *
276  * Returns: the new stream, or %NULL on error.
277  */
278 strid_t
279 glk_stream_open_memory(char *buf, glui32 buflen, glui32 fmode, glui32 rock)
280 {
281         g_return_val_if_fail(fmode != filemode_WriteAppend, NULL);
282         
283         strid_t str = stream_new_common(rock);
284         str->file_mode = fmode;
285         str->type = STREAM_TYPE_MEMORY;
286         str->mark = 0;
287         str->endmark = 0;
288         str->unicode = FALSE;
289
290         if(buf && buflen) 
291         {
292                 ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
293                 str->buffer = buf;
294                 str->buflen = buflen;
295                 if(glk_data->register_arr) 
296                         str->buffer_rock = (*glk_data->register_arr)(buf, buflen, "&+#!Cn");
297         }
298         
299         return str;
300 }
301
302 /**
303  * glk_stream_open_memory_uni:
304  * @buf: An allocated buffer, or %NULL.
305  * @buflen: Length of @buf.
306  * @fmode: Mode in which the buffer will be opened. Must be one of 
307  * %filemode_Read, %filemode_Write, or %filemode_ReadWrite.
308  * @rock: The new stream's rock value.
309  *
310  * Works just like glk_stream_open_memory(), except that the buffer is an array
311  * of 32-bit words, instead of bytes. This allows you to write and read any
312  * Unicode character. The @buflen is the number of words, not the number of
313  * bytes.
314  * 
315  * Returns: the new stream, or %NULL on error.
316  */
317 strid_t
318 glk_stream_open_memory_uni(glui32 *buf, glui32 buflen, glui32 fmode, glui32 rock)
319 {
320         g_return_val_if_fail(fmode != filemode_WriteAppend, NULL);
321         
322         strid_t str = stream_new_common(rock);
323         str->file_mode = fmode;
324         str->type = STREAM_TYPE_MEMORY;
325         str->mark = 0;
326         str->endmark = 0;
327         str->unicode = TRUE;
328
329         if(buf && buflen) 
330         {
331                 ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
332                 str->ubuffer = buf;
333                 str->buflen = buflen;
334                 if(glk_data->register_arr) 
335                         str->buffer_rock = (*glk_data->register_arr)(buf, buflen, "&+#!Iu");
336         }
337         
338         return str;
339 }
340
341 /* Internal function: create a stream using the given parameters. */
342 strid_t
343 file_stream_new(frefid_t fileref, glui32 fmode, glui32 rock, gboolean unicode)
344 {
345         VALID_FILEREF(fileref, return NULL);
346         
347         const gchar *modestr;
348         /* Binary mode is 0x000, text mode 0x100 */
349         gboolean binary = !(fileref->usage & fileusage_TextMode);
350         switch(fmode) 
351         {
352                 case filemode_Read:
353                         if(!g_file_test(fileref->filename, G_FILE_TEST_EXISTS)) {
354                                 ILLEGAL_PARAM("Tried to open a nonexistent file, '%s', in read mode", fileref->filename);
355                                 return NULL;
356                         }
357                         modestr = binary? "rb" : "r";
358                         break;
359                 case filemode_Write:
360                         modestr = binary? "wb" : "w";
361                         break;
362                 case filemode_WriteAppend:
363                 case filemode_ReadWrite:
364                 {
365                         /* We have to open the file first and then close it, in order to
366                          both make sure it exists and be able to seek in it later */
367                         FILE *fp = g_fopen(fileref->filename, binary? "ab" : "a");
368                         if(fclose(fp) != 0) {
369                                 IO_WARNING( "Error opening file", fileref->filename, g_strerror(errno) );
370                                 return NULL;
371                         }
372                         modestr = binary? "r+b" : "r+";
373                 }
374                         break;
375                 default:
376                         ILLEGAL_PARAM("Invalid file mode: %u", fmode);
377                         return NULL;
378         }
379         
380         FILE *fp = g_fopen(fileref->filename, modestr);
381         if(fp == NULL) {
382                 IO_WARNING( "Error opening file", fileref->filename, g_strerror(errno) );
383                 return NULL;
384         }
385         
386         /* Fast-forward to the end if we are appending */
387         if(fmode == filemode_WriteAppend && fseek(fp, 0, SEEK_END) != 0) {
388                 IO_WARNING("Error fast-forwarding file to end", fileref->filename, g_strerror(errno));
389                 return NULL;
390         }
391
392         /* If they opened a file in write mode but didn't specifically get
393         permission to do so, complain if the file already exists */
394         if(fileref->orig_filemode == filemode_Read && fmode != filemode_Read) {
395                 gdk_threads_enter();
396
397                 GtkWidget *dialog = gtk_message_dialog_new(NULL, 0,
398                         GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO,
399                         "File '%s' already exists. Overwrite?", fileref->filename);
400                 gint response = gtk_dialog_run(GTK_DIALOG(dialog));
401                 gtk_widget_destroy(dialog);
402
403                 gdk_threads_leave();
404
405                 if(response != GTK_RESPONSE_YES) {
406                         if(fclose(fp) != 0)
407                                 IO_WARNING( "Error closing file", fileref->filename, g_strerror(errno) );
408                         return NULL;
409                 }
410         }
411         
412         strid_t str = stream_new_common(rock);
413         str->file_mode = fmode;
414         str->type = STREAM_TYPE_FILE;
415         str->file_pointer = fp;
416         str->binary = binary;
417         str->unicode = unicode;
418         str->filename = g_filename_to_utf8(fileref->filename, -1, NULL, NULL, NULL);
419         if(str->filename == NULL)
420                 str->filename = g_strdup("Unknown file name"); /* fail silently */
421
422         return str;
423 }
424
425 /**
426  * glk_stream_open_file:
427  * @fileref: Indicates the file which will be opened.
428  * @fmode: Mode in which the file will be opened. Can be any of %filemode_Read,
429  * %filemode_Write, %filemode_WriteAppend, or %filemode_ReadWrite.
430  * @rock: The new stream's rock value.
431  *
432  * Opens a stream which reads to or writes from a disk file. If @fmode is
433  * %filemode_Read, the file must already exist; for the other modes, an empty
434  * file is created if none exists. If @fmode is %filemode_Write, and the file
435  * already exists, it is truncated down to zero length (an empty file); the
436  * other modes do not truncate. If @fmode is %filemode_WriteAppend, the file
437  * mark is set to the end of the file.
438  *
439  * <note><para>
440  *   Note, again, that this doesn't match stdio's fopen() call very well. See
441  *   <link linkend="filemode-WriteAppend">the file mode constants</link>.
442  * </para></note>
443  *
444  * If the filemode requires the file to exist, but the file does not exist,
445  * glk_stream_open_file() returns %NULL.
446  *
447  * The file may be read or written in text or binary mode; this is determined
448  * by the @fileref argument. Similarly, platform-dependent attributes such as
449  * file type are determined by @fileref. See <link
450  * linkend="chimara-File-References">File References</link>.
451  *
452  * When writing in binary mode, Unicode values (characters greater than 255)
453  * cannot be written to the file. If you try, they will be stored as 0x3F
454  * (<code>"?"</code>) characters. In text mode, Unicode values may be stored
455  * exactly, approximated, or abbreviated, depending on what the platform's text
456  * files support.
457  *
458  * Returns: A new stream, or %NULL if the file operation failed.
459  */
460 strid_t
461 glk_stream_open_file(frefid_t fileref, glui32 fmode, glui32 rock)
462 {
463         return file_stream_new(fileref, fmode, rock, FALSE);
464 }
465
466 /**
467  * glk_stream_open_file_uni:
468  * @fileref: Indicates the file which will be opened.
469  * @fmode: Mode in which the file will be opened. Can be any of %filemode_Read,
470  * %filemode_Write, %filemode_WriteAppend, or %filemode_ReadWrite.
471  * @rock: The new stream's rock value.
472  *
473  * This works just like glk_stream_open_file(), except that in binary mode,
474  * characters are written and read as four-byte (big-endian) values. This
475  * allows you to write any Unicode character.
476  *
477  * In text mode, the file is written and read in a platform-dependent way, which
478  * may or may not handle all Unicode characters. A text-mode file created with
479  * glk_stream_open_file_uni() may have the same format as a text-mode file
480  * created with glk_stream_open_file(); or it may use a more Unicode-friendly
481  * format.
482  *
483  * Returns: A new stream, or %NULL if the file operation failed.
484  */
485 strid_t
486 glk_stream_open_file_uni(frefid_t fileref, glui32 fmode, glui32 rock)
487 {
488         return file_stream_new(fileref, fmode, rock, TRUE);
489 }
490
491 /**
492  * glk_stream_open_resource:
493  * @filenum: Resource chunk number to open.
494  * @rock: The new stream's rock value.
495  *
496  * Open the given data resource for reading (only), as a normal stream.
497  *
498  * <note><para>
499  *   Note that there is no notion of file usage &mdash; the resource does not
500  *   have to be specified as <quote>saved game</quote> or whatever.
501  * </para></note>
502  *
503  * If no resource chunk of the given number exists, the open function returns
504  * %NULL.
505  *
506  * As with file streams, a binary resource stream reads the resource as bytes. A
507  * text resource stream reads characters encoded as Latin-1.
508  *
509  * When reading from a resource stream, newlines are not remapped, even if they
510  * normally would be when reading from a text file on the host OS. If you read a
511  * line (glk_get_line_stream() or glk_get_line_stream_uni()), a Unix newline
512  * (0x0A) terminates the line.
513  *
514  * Returns: the new stream, or %NULL.
515  */
516 strid_t
517 glk_stream_open_resource(glui32 filenum, glui32 rock)
518 {
519         g_warning("Not implemented");
520         return NULL;
521 }
522
523 /**
524  * glk_stream_open_resource_uni:
525  * @filenum: Resource chunk number to open.
526  * @rock: The new stream's rock value.
527  *
528  * Open the given data resource for reading (only), as a Unicode stream. See
529  * glk_stream_open_resource() for more information.
530  *
531  * As with file streams, a binary resource stream reads the resource as
532  * four-byte (big-endian) words. A text resource stream reads characters encoded
533  * as UTF-8.
534  *
535  * <note><para>
536  *   Thus, the difference between text and binary resources is only important
537  *   when opened as a Unicode stream.
538  * </para></note>
539  *
540  * Returns: the new stream, or %NULL.
541  */
542 strid_t
543 glk_stream_open_resource_uni(glui32 filenum, glui32 rock)
544 {
545         g_warning("Not implemented");
546         return NULL;
547 }
548
549 /**
550  * glk_stream_close:
551  * @str: Stream to close.
552  * @result: Pointer to a #stream_result_t, or %NULL.
553  *
554  * Closes the stream @str. The @result argument points to a structure which is
555  * filled in with the final character counts of the stream. If you do not care
556  * about these, you may pass %NULL as the @result argument.
557  *
558  * If @str is the current output stream, the current output stream is set to
559  * %NULL.
560  *
561  * You cannot close window streams; use glk_window_close() instead. See <link
562  * linkend="chimara-Window-Opening-Closing-and-Constraints">Window Opening,
563  * Closing, and Constraints</link>.
564  */
565 void 
566 glk_stream_close(strid_t str, stream_result_t *result)
567 {
568         VALID_STREAM(str, return);
569         
570         /* Free resources associated with one specific type of stream */
571         switch(str->type)
572         {
573                 case STREAM_TYPE_WINDOW:
574                         ILLEGAL("Attempted to close a window stream. Use glk_window_close() instead.");
575                         return;
576                         
577                 case STREAM_TYPE_MEMORY:
578                 {
579                         ChimaraGlkPrivate *glk_data = g_private_get(glk_data_key);
580                         if(glk_data->unregister_arr) 
581                         {
582                                 if(str->unicode)
583                                         (*glk_data->unregister_arr)(str->ubuffer, str->buflen, "&+#!Iu", str->buffer_rock);
584                                 else
585                                         (*glk_data->unregister_arr)(str->buffer, str->buflen, "&+#!Cn", str->buffer_rock);
586             }
587                 }
588                         break;
589                 
590                 case STREAM_TYPE_FILE:
591                         if(fclose(str->file_pointer) != 0)
592                                 IO_WARNING( "Failed to close file", str->filename, g_strerror(errno) );
593                         g_free(str->filename);
594                         break;
595                 default:
596                         ILLEGAL_PARAM("Unknown stream type: %u", str->type);
597                         return;
598         }
599
600         stream_close_common(str, result);
601 }