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