Use statically-allocated thread private data
[projects/chimara/chimara.git] / libchimara / stream.c
1 #include <config.h>
2 #include "stream.h"
3 #include "fileref.h"
4 #include "magic.h"
5 #include "gi_blorb.h"
6 #include <errno.h>
7 #include <stdio.h>
8 #include <glib.h>
9 #include <glib/gstdio.h>
10 #include <glib/gi18n-lib.h>
11
12 #include "chimara-glk-private.h"
13 extern GPrivate glk_data_key;
14
15 /* Internal function: create a stream with a specified rock value */
16 strid_t
17 stream_new_common(glui32 rock)
18 {
19         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
20
21         strid_t str = g_new0(struct glk_stream_struct, 1);
22         str->magic = MAGIC_STREAM;
23         str->rock = rock;
24         if(glk_data->register_obj)
25                 str->disprock = (*glk_data->register_obj)(str, gidisp_Class_Stream);
26                 
27         /* Add it to the global stream list */
28         glk_data->stream_list = g_list_prepend(glk_data->stream_list, str);
29         str->stream_list = glk_data->stream_list;
30
31         return str;
32 }
33
34 /* Internal function: Stuff to do upon closing any type of stream. Call only 
35  from Glk thread. */
36 void
37 stream_close_common(strid_t str, stream_result_t *result)
38 {
39         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
40
41         if(glk_data->unregister_obj)
42         {
43                 (*glk_data->unregister_obj)(str, gidisp_Class_Stream, str->disprock);
44                 str->disprock.ptr = NULL;
45         }
46         
47         /* If the stream was one or more windows' echo streams, set those to NULL */
48         winid_t win;
49         for(win = glk_window_iterate(NULL, NULL); win; 
50                 win = glk_window_iterate(win, NULL))
51                 if(win->echo_stream == str)
52                         win->echo_stream = NULL;
53         
54         /* Return the character counts */
55         if(result) 
56         {
57                 result->readcount = str->read_count;
58                 result->writecount = str->write_count;
59         }
60
61         /* Remove the stream from the global stream list */
62         glk_data->stream_list = g_list_delete_link(glk_data->stream_list, str->stream_list);
63         
64         /* If it was the current output stream, set that to NULL */
65         if(glk_data->current_stream == str)
66                 glk_data->current_stream = NULL;
67         
68         str->magic = MAGIC_FREE;
69         g_free(str);
70 }
71
72 /**
73  * glk_stream_iterate:
74  * @str: A stream, or %NULL.
75  * @rockptr: Return location for the next window's rock, or %NULL.
76  *
77  * Iterates through all the existing streams. See <link
78  * linkend="chimara-Iterating-Through-Opaque-Objects">Iterating Through Opaque
79  * Objects</link>.
80  *
81  * Returns: the next stream, or %NULL if there are no more.
82  */
83 strid_t
84 glk_stream_iterate(strid_t str, glui32 *rockptr)
85 {
86         VALID_STREAM_OR_NULL(str, return NULL);
87
88         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
89         GList *retnode;
90         
91         if(str == NULL)
92                 retnode = glk_data->stream_list;
93         else
94                 retnode = str->stream_list->next;
95         strid_t retval = retnode? (strid_t)retnode->data : NULL;
96                 
97         /* Store the stream's rock in rockptr */
98         if(retval && rockptr)
99                 *rockptr = glk_stream_get_rock(retval);
100                 
101         return retval;
102 }
103
104 /**
105  * glk_stream_get_rock:
106  * @str: A stream.
107  * 
108  * Retrieves the stream @str's rock value. See <link 
109  * linkend="chimara-Rocks">Rocks</link>. Window streams always have rock 0; all
110  * other streams return whatever rock you created them with.
111  *
112  * Returns: A rock value.
113  */
114 glui32
115 glk_stream_get_rock(strid_t str)
116 {
117         VALID_STREAM(str, return 0);
118         return str->rock;
119 }
120
121 /**
122  * glk_stream_set_current:
123  * @str: An output stream, or %NULL.
124  *
125  * Sets the current stream to @str, which must be an output stream. You may set
126  * the current stream to %NULL, which means the current stream is not set to
127  * anything. 
128  */
129 void
130 glk_stream_set_current(strid_t str)
131 {
132         VALID_STREAM_OR_NULL(str, return);
133
134         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
135
136         if(str != NULL && str->file_mode == filemode_Read)
137         {
138                 ILLEGAL("Cannot set current stream to non output stream");
139                 return;
140         }
141
142         glk_data->current_stream = str;
143 }
144
145 /**
146  * glk_stream_get_current:
147  * 
148  * Returns the current stream, or %NULL if there is none.
149  *
150  * Returns: A stream, or %NULL.
151  */
152 strid_t
153 glk_stream_get_current()
154 {
155         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
156         return glk_data->current_stream;
157 }
158
159 /**
160  * glk_put_char:
161  * @ch: A character in Latin-1 encoding.
162  *
163  * Prints one character to the current stream. As with all basic functions, the
164  * character is assumed to be in the Latin-1 character encoding. See <link
165  * linkend="chimara-Character-Encoding">Character Encoding</link>.
166  */
167 void
168 glk_put_char(unsigned char ch)
169 {
170         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
171         VALID_STREAM(glk_data->current_stream, return);
172         glk_put_char_stream(glk_data->current_stream, ch);
173 }
174
175 /**
176  * glk_put_char_uni:
177  * @ch: A Unicode code point.
178  *
179  * Prints one character to the current stream. The character is assumed to be a
180  * Unicode code point. See <link linkend="chimara-Character-Encoding">Character
181  * Encoding</link>.
182  */
183 void
184 glk_put_char_uni(glui32 ch)
185 {
186         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
187         VALID_STREAM(glk_data->current_stream, return);
188         glk_put_char_stream_uni(glk_data->current_stream, ch);
189 }
190
191 /**
192  * glk_put_string:
193  * @s: A null-terminated string in Latin-1 encoding.
194  *
195  * Prints a null-terminated string to the current stream. It is exactly
196  * equivalent to
197  * |[
198  * for (ptr = s; *ptr; ptr++)
199  *     glk_put_char(*ptr);
200  * ]|
201  * However, it may be more efficient.
202  */
203 void
204 glk_put_string(char *s)
205 {
206         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
207         VALID_STREAM(glk_data->current_stream, return);
208         glk_put_string_stream(glk_data->current_stream, s);
209 }
210
211 /**
212  * glk_put_string_uni:
213  * @s: A zero-terminated string of Unicode code points.
214  * 
215  * Prints a string of Unicode characters to the current stream. It is equivalent
216  * to a series of glk_put_char_uni() calls. A string ends on a #glui32 whose
217  * value is 0.
218  */
219 void
220 glk_put_string_uni(glui32 *s)
221 {
222         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
223         VALID_STREAM(glk_data->current_stream, return);
224         glk_put_string_stream_uni(glk_data->current_stream, s);
225 }
226
227 /**
228  * glk_put_buffer:
229  * @buf: An array of characters in Latin-1 encoding.
230  * @len: Length of @buf.
231  *
232  * Prints a block of characters to the current stream. It is exactly equivalent
233  * to:
234  * |[
235  * for (i = 0; i < len; i++)
236  *     glk_put_char(buf[i]);
237  * ]|
238  * However, it may be more efficient.
239  */
240 void
241 glk_put_buffer(char *buf, glui32 len)
242 {
243         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
244         VALID_STREAM(glk_data->current_stream, return);
245         glk_put_buffer_stream(glk_data->current_stream, buf, len);
246 }
247
248 /**
249  * glk_put_buffer_uni:
250  * @buf: An array of Unicode code points.
251  * @len: Length of @buf.
252  *
253  * Prints a block of Unicode characters to the current stream. It is equivalent
254  * to a series of glk_put_char_uni() calls.
255  */
256 void
257 glk_put_buffer_uni(glui32 *buf, glui32 len)
258 {
259         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
260         VALID_STREAM(glk_data->current_stream, return);
261         glk_put_buffer_stream_uni(glk_data->current_stream, buf, len);
262 }
263
264 /**
265  * glk_stream_open_memory:
266  * @buf: An allocated buffer, or %NULL.
267  * @buflen: Length of @buf.
268  * @fmode: Mode in which the buffer will be opened. Must be one of 
269  * %filemode_Read, %filemode_Write, or %filemode_ReadWrite.
270  * @rock: The new stream's rock value.
271  *
272  * Opens a stream which reads from or writes to a space in memory. @buf points
273  * to the buffer where output will be read from or written to. @buflen is the
274  * length of the buffer.
275  *
276  * Unicode values (characters greater than 255) cannot be written to the buffer.
277  * If you try, they will be stored as 0x3F (<code>"?"</code>) characters.
278  *
279  * Returns: the new stream, or %NULL on error.
280  */
281 strid_t
282 glk_stream_open_memory(char *buf, glui32 buflen, glui32 fmode, glui32 rock)
283 {
284         g_return_val_if_fail(fmode != filemode_WriteAppend, NULL);
285         
286         strid_t str = stream_new_common(rock);
287         str->file_mode = fmode;
288         str->type = STREAM_TYPE_MEMORY;
289         str->mark = 0;
290         str->endmark = 0;
291         str->unicode = FALSE;
292
293         if(buf && buflen) 
294         {
295                 ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
296                 str->buffer = buf;
297                 str->buflen = buflen;
298                 if(glk_data->register_arr) 
299                         str->buffer_rock = (*glk_data->register_arr)(buf, buflen, "&+#!Cn");
300         }
301         
302         return str;
303 }
304
305 /**
306  * glk_stream_open_memory_uni:
307  * @buf: An allocated buffer, or %NULL.
308  * @buflen: Length of @buf.
309  * @fmode: Mode in which the buffer will be opened. Must be one of 
310  * %filemode_Read, %filemode_Write, or %filemode_ReadWrite.
311  * @rock: The new stream's rock value.
312  *
313  * Works just like glk_stream_open_memory(), except that the buffer is an array
314  * of 32-bit words, instead of bytes. This allows you to write and read any
315  * Unicode character. The @buflen is the number of words, not the number of
316  * bytes.
317  * 
318  * Returns: the new stream, or %NULL on error.
319  */
320 strid_t
321 glk_stream_open_memory_uni(glui32 *buf, glui32 buflen, glui32 fmode, glui32 rock)
322 {
323         g_return_val_if_fail(fmode != filemode_WriteAppend, NULL);
324         
325         strid_t str = stream_new_common(rock);
326         str->file_mode = fmode;
327         str->type = STREAM_TYPE_MEMORY;
328         str->mark = 0;
329         str->endmark = 0;
330         str->unicode = TRUE;
331
332         if(buf && buflen) 
333         {
334                 ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
335                 str->ubuffer = buf;
336                 str->buflen = buflen;
337                 if(glk_data->register_arr) 
338                         str->buffer_rock = (*glk_data->register_arr)(buf, buflen, "&+#!Iu");
339         }
340         
341         return str;
342 }
343
344 /* Internal function: create a stream using the given parameters. */
345 strid_t
346 file_stream_new(frefid_t fileref, glui32 fmode, glui32 rock, gboolean unicode)
347 {
348         VALID_FILEREF(fileref, return NULL);
349         
350         const gchar *modestr;
351         /* Binary mode is 0x000, text mode 0x100 */
352         gboolean binary = !(fileref->usage & fileusage_TextMode);
353         switch(fmode) 
354         {
355                 case filemode_Read:
356                         if(!g_file_test(fileref->filename, G_FILE_TEST_EXISTS)) {
357                                 ILLEGAL_PARAM("Tried to open a nonexistent file, '%s', in read mode", fileref->filename);
358                                 return NULL;
359                         }
360                         modestr = binary? "rb" : "r";
361                         break;
362                 case filemode_Write:
363                         modestr = binary? "wb" : "w";
364                         break;
365                 case filemode_WriteAppend:
366                 case filemode_ReadWrite:
367                 {
368                         /* We have to open the file first and then close it, in order to
369                          both make sure it exists and be able to seek in it later */
370                         FILE *fp = g_fopen(fileref->filename, binary? "ab" : "a");
371                         if(fclose(fp) != 0) {
372                                 IO_WARNING( "Error opening file", fileref->filename, g_strerror(errno) );
373                                 return NULL;
374                         }
375                         modestr = binary? "r+b" : "r+";
376                 }
377                         break;
378                 default:
379                         ILLEGAL_PARAM("Invalid file mode: %u", fmode);
380                         return NULL;
381         }
382         
383         FILE *fp = g_fopen(fileref->filename, modestr);
384         if(fp == NULL) {
385                 IO_WARNING( "Error opening file", fileref->filename, g_strerror(errno) );
386                 return NULL;
387         }
388         
389         /* Fast-forward to the end if we are appending */
390         if(fmode == filemode_WriteAppend && fseek(fp, 0, SEEK_END) != 0) {
391                 IO_WARNING("Error fast-forwarding file to end", fileref->filename, g_strerror(errno));
392                 return NULL;
393         }
394
395         /* If they opened a file in write mode but didn't specifically get
396         permission to do so, complain if the file already exists */
397         if(fileref->orig_filemode == filemode_Read && fmode != filemode_Read) {
398                 gdk_threads_enter();
399
400                 GtkWidget *dialog = gtk_message_dialog_new(NULL, 0,
401                         GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO,
402                         "File '%s' already exists. Overwrite?", fileref->filename);
403                 gint response = gtk_dialog_run(GTK_DIALOG(dialog));
404                 gtk_widget_destroy(dialog);
405
406                 gdk_threads_leave();
407
408                 if(response != GTK_RESPONSE_YES) {
409                         if(fclose(fp) != 0)
410                                 IO_WARNING( "Error closing file", fileref->filename, g_strerror(errno) );
411                         return NULL;
412                 }
413         }
414         
415         strid_t str = stream_new_common(rock);
416         str->file_mode = fmode;
417         str->type = STREAM_TYPE_FILE;
418         str->file_pointer = fp;
419         str->binary = binary;
420         str->unicode = unicode;
421         str->filename = g_filename_to_utf8(fileref->filename, -1, NULL, NULL, NULL);
422         if(str->filename == NULL)
423                 str->filename = g_strdup("Unknown file name"); /* fail silently */
424
425         return str;
426 }
427
428 /**
429  * glk_stream_open_file:
430  * @fileref: Indicates the file which will be opened.
431  * @fmode: Mode in which the file will be opened. Can be any of %filemode_Read,
432  * %filemode_Write, %filemode_WriteAppend, or %filemode_ReadWrite.
433  * @rock: The new stream's rock value.
434  *
435  * Opens a stream which reads to or writes from a disk file. If @fmode is
436  * %filemode_Read, the file must already exist; for the other modes, an empty
437  * file is created if none exists. If @fmode is %filemode_Write, and the file
438  * already exists, it is truncated down to zero length (an empty file); the
439  * other modes do not truncate. If @fmode is %filemode_WriteAppend, the file
440  * mark is set to the end of the file.
441  *
442  * <note><para>
443  *   Note, again, that this doesn't match stdio's fopen() call very well. See
444  *   <link linkend="filemode-WriteAppend">the file mode constants</link>.
445  * </para></note>
446  *
447  * If the filemode requires the file to exist, but the file does not exist,
448  * glk_stream_open_file() returns %NULL.
449  *
450  * The file may be read or written in text or binary mode; this is determined
451  * by the @fileref argument. Similarly, platform-dependent attributes such as
452  * file type are determined by @fileref. See <link
453  * linkend="chimara-File-References">File References</link>.
454  *
455  * When writing in binary mode, Unicode values (characters greater than 255)
456  * cannot be written to the file. If you try, they will be stored as 0x3F
457  * (<code>"?"</code>) characters. In text mode, Unicode values may be stored
458  * exactly, approximated, or abbreviated, depending on what the platform's text
459  * files support.
460  *
461  * Returns: A new stream, or %NULL if the file operation failed.
462  */
463 strid_t
464 glk_stream_open_file(frefid_t fileref, glui32 fmode, glui32 rock)
465 {
466         return file_stream_new(fileref, fmode, rock, FALSE);
467 }
468
469 /**
470  * glk_stream_open_file_uni:
471  * @fileref: Indicates the file which will be opened.
472  * @fmode: Mode in which the file will be opened. Can be any of %filemode_Read,
473  * %filemode_Write, %filemode_WriteAppend, or %filemode_ReadWrite.
474  * @rock: The new stream's rock value.
475  *
476  * This works just like glk_stream_open_file(), except that in binary mode,
477  * characters are written and read as four-byte (big-endian) values. This
478  * allows you to write any Unicode character.
479  *
480  * In text mode, the file is written and read in a platform-dependent way, which
481  * may or may not handle all Unicode characters. A text-mode file created with
482  * glk_stream_open_file_uni() may have the same format as a text-mode file
483  * created with glk_stream_open_file(); or it may use a more Unicode-friendly
484  * format.
485  *
486  * Returns: A new stream, or %NULL if the file operation failed.
487  */
488 strid_t
489 glk_stream_open_file_uni(frefid_t fileref, glui32 fmode, glui32 rock)
490 {
491         return file_stream_new(fileref, fmode, rock, TRUE);
492 }
493
494 /**
495  * glk_stream_open_resource:
496  * @filenum: Resource chunk number to open.
497  * @rock: The new stream's rock value.
498  *
499  * Open the given data resource for reading (only), as a normal stream.
500  *
501  * <note><para>
502  *   Note that there is no notion of file usage &mdash; the resource does not
503  *   have to be specified as <quote>saved game</quote> or whatever.
504  * </para></note>
505  *
506  * If no resource chunk of the given number exists, the open function returns
507  * %NULL.
508  *
509  * As with file streams, a binary resource stream reads the resource as bytes. A
510  * text resource stream reads characters encoded as Latin-1.
511  *
512  * When reading from a resource stream, newlines are not remapped, even if they
513  * normally would be when reading from a text file on the host OS. If you read a
514  * line (glk_get_line_stream() or glk_get_line_stream_uni()), a Unix newline
515  * (0x0A) terminates the line.
516  *
517  * Returns: the new stream, or %NULL.
518  */
519 strid_t
520 glk_stream_open_resource(glui32 filenum, glui32 rock)
521 {
522         /* Adapted from CheapGlk */
523         strid_t str;
524         gboolean isbinary;
525         giblorb_err_t err;
526         giblorb_result_t res;
527         giblorb_map_t *map = giblorb_get_resource_map();
528         if(map == NULL) {
529                 WARNING(_("Could not create resource stream, because there was no "
530                         "resource map."));
531                 return NULL; /* Not running from a blorb file */
532         }
533
534         err = giblorb_load_resource(map, giblorb_method_Memory, &res, giblorb_ID_Data, filenum);
535         if(err) {
536                 WARNING_S(_("Could not create resource stream, because the resource "
537                         "could not be loaded"), giblorb_get_error_message(err));
538                 return 0; /* Not found, or some other error */
539         }
540
541         /* We'll use the in-memory copy of the chunk data as the basis for
542         our new stream. It's important to not call chunk_unload() until
543         the stream is closed (and we won't).
544
545         This will be memory-hoggish for giant data chunks, but I don't
546         expect giant data chunks at this point. A more efficient model
547         would be to use the file on disk, but this requires some hacking
548         into the file stream code (we'd need to open a new FILE*) and
549         I don't feel like doing that. */
550
551         if(res.chunktype == giblorb_ID_TEXT)
552                 isbinary = FALSE;
553         else if(res.chunktype == giblorb_ID_BINA)
554                 isbinary = TRUE;
555         else {
556                 WARNING(_("Could not create resource stream, because chunk was of "
557                         "unknown type."));
558                 return NULL; /* Unknown chunk type */
559         }
560
561         str = stream_new_common(rock);
562         str->type = STREAM_TYPE_RESOURCE;
563         str->file_mode = filemode_Read;
564         str->binary = isbinary;
565
566         if (res.data.ptr && res.length) {
567                 str->buffer = res.data.ptr;
568                 str->mark = 0;
569                 str->buflen = res.length;
570                 str->endmark = str->buflen;
571         }
572
573         return str;
574 }
575
576 /**
577  * glk_stream_open_resource_uni:
578  * @filenum: Resource chunk number to open.
579  * @rock: The new stream's rock value.
580  *
581  * Open the given data resource for reading (only), as a Unicode stream. See
582  * glk_stream_open_resource() for more information.
583  *
584  * As with file streams, a binary resource stream reads the resource as
585  * four-byte (big-endian) words. A text resource stream reads characters encoded
586  * as UTF-8.
587  *
588  * <note><para>
589  *   Thus, the difference between text and binary resources is only important
590  *   when opened as a Unicode stream.
591  * </para></note>
592  *
593  * Returns: the new stream, or %NULL.
594  */
595 strid_t
596 glk_stream_open_resource_uni(glui32 filenum, glui32 rock)
597 {
598         /* Adapted from CheapGlk */
599         /* We have been handed an array of bytes. (They're big-endian
600         four-byte chunks, or perhaps a UTF-8 byte sequence, rather than
601         native-endian four-byte integers). So we drop it into str->buffer,
602         rather than str->ubuffer -- we'll have to do the translation in the
603         get() functions. */
604         strid_t str = glk_stream_open_resource(filenum, rock);
605         if(str != NULL)
606                 str->unicode = TRUE;
607         return str;
608 }
609
610 /**
611  * glk_stream_close:
612  * @str: Stream to close.
613  * @result: Pointer to a #stream_result_t, or %NULL.
614  *
615  * Closes the stream @str. The @result argument points to a structure which is
616  * filled in with the final character counts of the stream. If you do not care
617  * about these, you may pass %NULL as the @result argument.
618  *
619  * If @str is the current output stream, the current output stream is set to
620  * %NULL.
621  *
622  * You cannot close window streams; use glk_window_close() instead. See <link
623  * linkend="chimara-Window-Opening-Closing-and-Constraints">Window Opening,
624  * Closing, and Constraints</link>.
625  */
626 void 
627 glk_stream_close(strid_t str, stream_result_t *result)
628 {
629         VALID_STREAM(str, return);
630         
631         /* Free resources associated with one specific type of stream */
632         switch(str->type)
633         {
634                 case STREAM_TYPE_WINDOW:
635                         ILLEGAL("Attempted to close a window stream. Use glk_window_close() instead.");
636                         return;
637                         
638                 case STREAM_TYPE_MEMORY:
639                 {
640                         ChimaraGlkPrivate *glk_data = g_private_get(&glk_data_key);
641                         if(glk_data->unregister_arr) 
642                         {
643                                 if(str->unicode)
644                                         (*glk_data->unregister_arr)(str->ubuffer, str->buflen, "&+#!Iu", str->buffer_rock);
645                                 else
646                                         (*glk_data->unregister_arr)(str->buffer, str->buflen, "&+#!Cn", str->buffer_rock);
647             }
648                 }
649                         break;
650                 
651                 case STREAM_TYPE_FILE:
652                         if(fclose(str->file_pointer) != 0)
653                                 IO_WARNING( "Failed to close file", str->filename, g_strerror(errno) );
654                         g_free(str->filename);
655                         break;
656
657                 case STREAM_TYPE_RESOURCE:
658                         /* Shouldn't free the chunk; someone else might be using it. It will
659                         be freed when the resource map is freed. */
660                         break;
661
662                 default:
663                         ILLEGAL_PARAM("Unknown stream type: %u", str->type);
664                         return;
665         }
666
667         stream_close_common(str, result);
668 }