[bocfel] Remove debug printf
[projects/chimara/chimara.git] / interpreters / bocfel / io.c
1 /*-
2  * Copyright 2010-2012 Chris Spiegel.
3  *
4  * This file is part of Bocfel.
5  *
6  * Bocfel is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License, version
8  * 2 or 3, as published by the Free Software Foundation.
9  *
10  * Bocfel is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with Bocfel.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include <stdlib.h>
20 #include <stdint.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <limits.h>
24
25 #ifdef ZTERP_GLK
26 #include <glk.h>
27 #endif
28
29 #include "io.h"
30 #include "osdep.h"
31 #include "unicode.h"
32
33 #define MAX_PATH        4096
34
35 int use_utf8_io;
36
37 /* Generally speaking, UNICODE_LINEFEED (10) is used as a newline.  Glk
38  * requires this (Glk API 0.7.0 §2.2), and when Unicode is available, we
39  * write characters out by hand even with stdio, so no translation can
40  * be done.  However, when stdio is being used, Unicode is not
41  * available, and the file usage will be for a transcript or
42  * command-script, use '\n' as a newline so translation can be done;
43  * this is the only case where streams are opened in text mode.
44  *
45  * zterp_io_stdio() and zterp_io_stdout() are considered text-mode if
46  * Unicode is not available, binary otherwise.
47  */
48 #define textmode(io)    (!use_utf8_io && ((io->mode) & (ZTERP_IO_TRANS | ZTERP_IO_INPUT)))
49
50 struct zterp_io
51 {
52   enum type { IO_STDIO, IO_GLK } type;
53
54   FILE *fp;
55   int mode;
56 #ifdef ZTERP_GLK
57   strid_t file;
58 #endif
59 };
60
61 /* Glk does not like you to be able to pass a full filename to
62  * glk_fileref_create_by_name(); this means that Glk cannot be used to
63  * open arbitrary files.  However, Glk is still required to prompt for
64  * files, such as in a save game situation.  To allow zterp_io to work
65  * for opening files both with and without a prompt, it will use stdio
66  * when either Glk is not available, or when Glk is available but
67  * prompting is not necessary.
68  *
69  * This is needed because the IFF parser is required for both opening
70  * games (zblorb files) and for saving/restoring.  The former needs to
71  * be able to access any file on the filesystem, and the latter needs to
72  * prompt.  This is a headache.
73  *
74  * Prompting is assumed to be necessary if “filename” is NULL.
75  */
76 zterp_io *zterp_io_open(const char *filename, int mode)
77 {
78   zterp_io *io;
79   char smode[] = "wb";
80
81   io = malloc(sizeof *io);
82   if(io == NULL) goto err;
83   io->mode = mode;
84
85   if     (mode & ZTERP_IO_RDONLY) smode[0] = 'r';
86   else if(mode & ZTERP_IO_APPEND) smode[0] = 'a';
87
88   if(textmode(io)) smode[1] = 0;
89
90 #ifdef ZTERP_GLK
91   int usage = fileusage_BinaryMode, filemode;
92
93   if     (mode & ZTERP_IO_SAVE)  usage |= fileusage_SavedGame;
94   else if(mode & ZTERP_IO_TRANS) usage |= fileusage_Transcript;
95   else if(mode & ZTERP_IO_INPUT) usage |= fileusage_InputRecord;
96   else                           usage |= fileusage_Data;
97
98   if     (mode & ZTERP_IO_RDONLY) filemode = filemode_Read;
99   else if(mode & ZTERP_IO_WRONLY) filemode = filemode_Write;
100   else if(mode & ZTERP_IO_APPEND) filemode = filemode_WriteAppend;
101
102   else goto err;
103 #else
104   const char *prompt;
105
106   if     (mode & ZTERP_IO_SAVE)  prompt = "Enter filename for save game: ";
107   else if(mode & ZTERP_IO_TRANS) prompt = "Enter filename for transcript: ";
108   else if(mode & ZTERP_IO_INPUT) prompt = "Enter filename for command record: ";
109   else                           prompt = "Enter filename for data: ";
110 #endif
111
112   /* No need to prompt. */
113   if(filename != NULL)
114   {
115     io->type = IO_STDIO;
116     io->fp = fopen(filename, smode);
117     if(io->fp == NULL) goto err;
118   }
119   /* Prompt. */
120   else
121   {
122 #ifdef ZTERP_GLK
123     frefid_t ref;
124
125     ref = glk_fileref_create_by_prompt(usage, filemode, 0);
126     if(ref == NULL) goto err;
127
128     io->type = IO_GLK;
129     io->file = glk_stream_open_file(ref, filemode, 0);
130     glk_fileref_destroy(ref);
131     if(io->file == NULL) goto err;
132 #else
133     char fn[MAX_PATH], *p;
134
135     printf("\n%s", prompt);
136     fflush(stdout);
137     if(fgets(fn, sizeof fn, stdin) == NULL || fn[0] == '\n') goto err;
138     p = strchr(fn, '\n');
139     if(p != NULL) *p = 0;
140
141     io->type = IO_STDIO;
142     io->fp = fopen(fn, smode);
143     if(io->fp == NULL) goto err;
144 #endif
145   }
146
147   return io;
148
149 err:
150   free(io);
151
152   return NULL;
153 }
154
155 /* The zterp_os_reopen_binary() calls attempt to reopen stdin/stdout as
156  * binary streams so that reading/writing UTF-8 doesn’t cause unwanted
157  * translations.  The mode of ZTERP_IO_TRANS is set when Unicode is
158  * unavailable as a way to signal that these are text streams.
159  */
160 const zterp_io *zterp_io_stdin(void)
161 {
162   static zterp_io io;
163
164   if(io.fp == NULL)
165   {
166     io.type = IO_STDIO;
167     io.mode = ZTERP_IO_RDONLY;
168     if(use_utf8_io) zterp_os_reopen_binary(stdin);
169     else            io.mode |= ZTERP_IO_TRANS;
170     io.fp = stdin;
171   }
172
173   return &io;
174 }
175
176 const zterp_io *zterp_io_stdout(void)
177 {
178   static zterp_io io;
179
180   if(io.fp == NULL)
181   {
182     io.type = IO_STDIO;
183     io.mode = ZTERP_IO_WRONLY;
184     if(use_utf8_io) zterp_os_reopen_binary(stdout);
185     else            io.mode |= ZTERP_IO_TRANS;
186     io.fp = stdout;
187   }
188
189   return &io;
190 }
191
192 void zterp_io_close(zterp_io *io)
193 {
194 #ifdef ZTERP_GLK
195   if(io->type == IO_GLK)
196   {
197     glk_stream_close(io->file, NULL);
198   }
199   else
200 #endif
201   {
202     fclose(io->fp);
203   }
204
205   free(io);
206 }
207
208 int zterp_io_seek(const zterp_io *io, long offset, int whence)
209 {
210   /* To smooth over differences between Glk and standard I/O, don’t
211    * allow seeking in append-only streams.
212    */
213   if(io->mode & ZTERP_IO_APPEND) return -1;
214
215 #ifdef ZTERP_GLK
216   if(io->type == IO_GLK)
217   {
218     glk_stream_set_position(io->file, offset, whence == SEEK_SET ? seekmode_Start : whence == SEEK_CUR ? seekmode_Current : seekmode_End);
219     return 0; /* dammit */
220   }
221   else
222 #endif
223   {
224     return fseek(io->fp, offset, whence);
225   }
226 }
227
228 long zterp_io_tell(const zterp_io *io)
229 {
230 #ifdef ZTERP_GLK
231   if(io->type == IO_GLK)
232   {
233     return glk_stream_get_position(io->file);
234   }
235   else
236 #endif
237   {
238     return ftell(io->fp);
239   }
240 }
241
242 /* zterp_io_read() and zterp_io_write() always operate in terms of
243  * bytes, whether or not Unicode is available.
244  */
245 size_t zterp_io_read(const zterp_io *io, void *buf, size_t n)
246 {
247 #ifdef ZTERP_GLK
248   if(io->type == IO_GLK)
249   {
250     glui32 s = glk_get_buffer_stream(io->file, buf, n);
251     /* This should only happen if io->file is invalid. */
252     if(s == (glui32)-1) s = 0;
253     return s;
254   }
255   else
256 #endif
257   {
258     return fread(buf, 1, n, io->fp);
259   }
260 }
261
262 size_t zterp_io_write(const zterp_io *io, const void *buf, size_t n)
263 {
264 #ifdef ZTERP_GLK
265   if(io->type == IO_GLK)
266   {
267     glk_put_buffer_stream(io->file, (char *)buf, n);
268     return n; /* dammit */
269   }
270   else
271 #endif
272   {
273     return fwrite(buf, 1, n, io->fp);
274   }
275 }
276
277 int zterp_io_read16(const zterp_io *io, uint16_t *v)
278 {
279   uint8_t buf[2];
280
281   if(zterp_io_read(io, buf, sizeof buf) != sizeof buf) return 0;
282
283   *v = (buf[0] << 8) | buf[1];
284
285   return 1;
286 }
287
288 int zterp_io_read32(const zterp_io *io, uint32_t *v)
289 {
290   uint8_t buf[4];
291
292   if(zterp_io_read(io, buf, sizeof buf) != sizeof buf) return 0;
293
294   *v = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
295
296   return 1;
297 }
298
299 /* Read a byte and make sure it’s part of a valid UTF-8 sequence. */
300 static int read_byte(const zterp_io *io, uint8_t *c)
301 {
302   if(zterp_io_read(io, c, sizeof *c) != sizeof *c) return 0;
303   if((*c & 0x80) != 0x80) return 0;
304
305   return 1;
306 }
307
308 /* zterp_io_getc() and zterp_io_putc() are meant to operate in terms of
309  * characters, not bytes.  That is, unlike C, bytes and characters are
310  * not equivalent as far as Zterp’s I/O system is concerned.
311  */
312
313 /* Read a UTF-8 character, returning it.
314  * -1 is returned on EOF.
315  *
316  * If there is a problem reading the UTF-8 (either from an invalid
317  * sequence or from a too-large value), a question mark is returned.
318  *
319  * If Unicode is not available, read a single byte (assumed to be
320  * Latin-1).
321  * If Unicode is not available, IO_STDIO is in use, and text mode is
322  * set, do newline translation.  Text mode is likely to always be
323  * set—this function really shouldn’t be used in binary mode.
324  */
325 long zterp_io_getc(const zterp_io *io)
326 {
327   long ret;
328
329   if(!use_utf8_io)
330   {
331 #ifdef ZTERP_GLK
332     if(io->type == IO_GLK)
333     {
334       ret = glk_get_char_stream(io->file);
335     }
336     else
337 #endif
338     {
339       int c;
340
341       c = getc(io->fp);
342       if(c == EOF) ret = -1;
343       else         ret = c;
344
345       if(textmode(io) && c == '\n') ret = UNICODE_LINEFEED;
346     }
347   }
348   else
349   {
350     uint8_t c;
351
352     if(zterp_io_read(io, &c, sizeof c) != sizeof c)
353     {
354       ret = -1;
355     }
356     else if((c & 0x80) == 0) /* One byte. */
357     {
358       ret = c;
359     }
360     else if((c & 0xe0) == 0xc0) /* Two bytes. */
361     {
362       ret = (c & 0x1f) << 6;
363
364       if(!read_byte(io, &c)) return UNICODE_QUESTIONMARK;
365
366       ret |= (c & 0x3f);
367     }
368     else if((c & 0xf0) == 0xe0) /* Three bytes. */
369     {
370       ret = (c & 0x0f) << 12;
371
372       if(!read_byte(io, &c)) return UNICODE_QUESTIONMARK;
373
374       ret |= ((c & 0x3f) << 6);
375
376       if(!read_byte(io, &c)) return UNICODE_QUESTIONMARK;
377
378       ret |= (c & 0x3f);
379     }
380     else if((c & 0xf8) == 0xf0) /* Four bytes. */
381     {
382       /* The Z-machine doesn’t support Unicode this large, but at
383        * least try not to leave a partial character in the stream.
384        */
385       zterp_io_seek(io, 3, SEEK_CUR);
386
387       ret = UNICODE_QUESTIONMARK;
388     }
389     else /* Invalid value. */
390     {
391       ret = UNICODE_QUESTIONMARK;
392     }
393   }
394
395   if(ret > UINT16_MAX) ret = UNICODE_QUESTIONMARK;
396
397   return ret;
398 }
399
400 /* Write a Unicode character as UTF-8.
401  *
402  * If Unicode is not available, write the value out as a single Latin-1
403  * byte.  If it is too large for a byte, write out a question mark.
404  *
405  * If Unicode is not available, IO_STDIO is in use, and text mode is
406  * set, do newline translation.
407  *
408  * Text mode is likely to always be set—this function really shouldn’t
409  * be used in binary mode.
410  */
411 void zterp_io_putc(const zterp_io *io, uint16_t c)
412 {
413   if(!use_utf8_io)
414   {
415     if(c > UINT8_MAX) c = UNICODE_QUESTIONMARK;
416 #ifdef ZTERP_GLK
417     if(io->type == IO_GLK)
418     {
419       glk_put_char_stream(io->file, c);
420     }
421     else
422 #endif
423     {
424       if(textmode(io) && c == UNICODE_LINEFEED) c = '\n';
425       putc(c, io->fp);
426     }
427   }
428   else
429   {
430     uint8_t hi = c >> 8, lo = c & 0xff;
431
432 #define WRITE(c)        zterp_io_write(io, &(uint8_t){ c }, sizeof (uint8_t))
433     if(c < 128)
434     {
435       WRITE(c);
436     }
437     else if(c < 2048)
438     {
439       WRITE(0xc0 | (hi << 2) | (lo >> 6));
440       WRITE(0x80 | (lo & 0x3f));
441     }
442     else
443     {
444       WRITE(0xe0 | (hi >> 4));
445       WRITE(0x80 | ((hi << 2) & 0x3f) | (lo >> 6));
446       WRITE(0x80 | (lo & 0x3f));
447     }
448 #undef WRITE
449   }
450 }
451
452 long zterp_io_readline(const zterp_io *io, uint16_t *buf, size_t len)
453 {
454   long ret;
455
456   if(len > LONG_MAX) return -1;
457
458   for(ret = 0; ret < len; ret++)
459   {
460     long c = zterp_io_getc(io);
461
462     /* EOF before newline means there was a problem. */
463     if(c == -1) return -1;
464
465     /* Don’t count the newline. */
466     if(c == UNICODE_LINEFEED) break;
467
468     buf[ret] = c;
469   }
470
471   return ret;
472 }
473
474 long zterp_io_filesize(const zterp_io *io)
475 {
476   if(io->type == IO_STDIO && !textmode(io))
477   {
478     return zterp_os_filesize(io->fp);
479   }
480   else
481   {
482     return -1;
483   }
484 }
485
486 void zterp_io_flush(const zterp_io *io)
487 {
488   if(io == NULL || io->type != IO_STDIO || !(io->mode & (ZTERP_IO_WRONLY | ZTERP_IO_APPEND))) return;
489
490   fflush(io->fp);
491 }