Debian Codegraph @

terps/agility/os_glk.c

raw symbols SCIP
1 /* vi: set ts=2 shiftwidth=2 expandtab:
2 *
3 * Copyright (C) 2002-2006 Simon Baldwin, [email protected]
4 * Mac portions Copyright (C) 2002 Ben Hines
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of version 2 of the GNU General Public License
8 * as published by the Free Software Foundation.
9 *
10 * This program 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 this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18 * USA
19 */
20
21 /*
22 * Glk interface for AGiliTy 1.1.1
23 * -------------------------------
24 *
25 * This module contains the the Glk porting layer for AGiliTy. It
26 * defines the Glk arguments list structure, the entry points for the
27 * Glk library framework to use, and all platform-abstracted I/O to
28 * link to Glk's I/O.
29 *
30 * The following items are omitted from this Glk port:
31 *
32 * o Calls to glk_tick(). The Glk documentation states that the
33 * interpreter should call glk_tick() every opcode or so. This is
34 * intrusive to code (it goes outside of this module), and since
35 * most Glk libraries do precisely nothing in glk_tick(), there is
36 * little motivation to add it.
37 *
38 * o Glk tries to assert control over _all_ file I/O. It's just too
39 * disruptive to add it to existing code, so for now, the AGiliTy
40 * interpreter is still dependent on stdio and the like.
41 */
42
43 #include <assert.h>
44 #include <errno.h>
45 #include <stdlib.h>
46 #include <stdarg.h>
47 #include <string.h>
48 #include <time.h>
49 #include <ctype.h>
50 #include <limits.h>
51 #include <stddef.h>
52
53 #ifndef GLK_ANSI_ONLY
54 # if !defined (__USE_POSIX)
55 # define __USE_POSIX /* Gets fdopen() definition. */
56 # include <stdio.h>
57 # undef __USE_POSIX
58 # else
59 # include <stdio.h>
60 # endif
61
62 # if TARGET_RT_MAC_CFM
63 # include <time.h>
64 /* Sys/types.h absent on CW MSL (aka CFM), replace with fcntls. */
65 # include <fcntl.h>
66 # define FD_SETSIZE 1024
67 /*
68 * CW's MSL defines exec() in unistd.h which conflicts with exec in
69 * interp. To work around this I'll put prototypes of the stuff we
70 * use from it here.
71 */
72 _MSL_IMP_EXP_C int close (int);
73 # else
74 # include <unistd.h>
75 # include <fcntl.h>
76 # include <sys/types.h>
77 # endif
78 #else
79 # include <stdio.h>
80 #endif
81
82 #include "agility.h"
83 #include "interp.h"
84
85 #include "glk.h"
86
87 #ifdef GARGLK
88 #include "glkstart.h"
89 #endif
90
91 /*
92 * True and false definitions -- usually defined in glkstart.h, but we need
93 * them early, so we'll define them here too. We also need NULL, but that's
94 * normally from stdio.h or one of it's cousins.
95 */
96 #ifndef FALSE
97 # define FALSE 0
98 #endif
99 #ifndef TRUE
100 # define TRUE (!FALSE)
101 #endif
102
103
104 /*---------------------------------------------------------------------*/
105 /* Module variables, miscellaneous externals not in header files */
106 /*---------------------------------------------------------------------*/
107
108 /* Glk AGiliTy port version number. */
109 static const glui32 GAGT_PORT_VERSION = 0x00010701;
110
111 /*
112 * We use two Glk windows; one is two lines at the top of the display area
113 * for status, and the other is the remainder of the display area, used for,
114 * well, everything else. Where a particular Glk implementation won't do
115 * more than one window, the status window remains NULL.
116 */
117 static winid_t gagt_main_window = NULL,
118 gagt_status_window = NULL;
119
120 /*
121 * Transcript stream and input log. These are NULL if there is no current
122 * collection of these strings.
123 */
124 static strid_t gagt_transcript_stream = NULL,
125 gagt_inputlog_stream = NULL;
126
127 /* Input read log stream, for reading back an input log. */
128 static strid_t gagt_readlog_stream = NULL;
129
130 /* Options that may be turned off or set by command line flags. */
131 static enum {
132 FONT_AUTOMATIC, FONT_FIXED_WIDTH, FONT_PROPORTIONAL, FONT_DEBUG
133 }
134 gagt_font_mode = FONT_AUTOMATIC;
135 static enum {
136 DELAY_FULL, DELAY_SHORT, DELAY_OFF
137 }
138 gagt_delay_mode = DELAY_SHORT;
139 static int gagt_replacement_enabled = TRUE,
140 gagt_extended_status_enabled = TRUE,
141 gagt_abbreviations_enabled = TRUE,
142 gagt_commands_enabled = TRUE;
143
144 /* Forward declaration of event wait functions. */
145 static void gagt_event_wait (glui32 wait_type, event_t * event);
146 static void gagt_event_wait_2 (glui32 wait_type_1,
147 glui32 wait_type_2,
148 event_t * event);
149
150 /*
151 * Forward declaration of the glk_exit() wrapper. Normal functions in this
152 * module should not to call glk_exit() directly; they should always call it
153 * through the wrapper instead.
154 */
155 static void gagt_exit (void);
156
157
158 /*---------------------------------------------------------------------*/
159 /* Glk port utility functions */
160 /*---------------------------------------------------------------------*/
161
162 /*
163 * gagt_fatal()
164 *
165 * Fatal error handler. The function returns, expecting the caller to
166 * abort() or otherwise handle the error.
167 */
168 static void
169 gagt_fatal (const char *string)
170 {
171 /*
172 * If the failure happens too early for us to have a window, print
173 * the message to stderr.
174 */
175 if (!gagt_main_window)
176 {
177 fprintf (stderr, "\n\nINTERNAL ERROR: %s\n", string);
178
179 fprintf (stderr, "\nPlease record the details of this error, try to"
180 " note down everything you did to cause it, and email"
181 " this information to [email protected].\n\n");
182 return;
183 }
184
185 /* Cancel all possible pending window input events. */
186 glk_cancel_line_event (gagt_main_window, NULL);
187 glk_cancel_char_event (gagt_main_window);
188
189 /* Print a message indicating the error. */
190 glk_set_window (gagt_main_window);
191 glk_set_style (style_Normal);
192 glk_put_string ("\n\nINTERNAL ERROR: ");
193 glk_put_string ((char *) string);
194
195 glk_put_string ("\n\nPlease record the details of this error, try to"
196 " note down everything you did to cause it, and email"
197 " this information to [email protected].\n\n");
198 }
199
200
201 /*
202 * gagt_malloc()
203 * gagt_realloc()
204 *
205 * Non-failing malloc and realloc; call gagt_fatal() and exit if memory
206 * allocation fails.
207 */
208 static void *
209 gagt_malloc (size_t size)
210 {
211 void *pointer;
212
213 pointer = malloc (size);
214 if (!pointer)
215 {
216 gagt_fatal ("GLK: Out of system memory");
217 gagt_exit ();
218 }
219
220 return pointer;
221 }
222
223 static void *
224 gagt_realloc (void *ptr, size_t size)
225 {
226 void *pointer;
227
228 pointer = realloc (ptr, size);
229 if (!pointer)
230 {
231 gagt_fatal ("GLK: Out of system memory");
232 gagt_exit ();
233 }
234
235 return pointer;
236 }
237
238
239 /*
240 * gagt_strncasecmp()
241 * gagt_strcasecmp()
242 *
243 * Strncasecmp and strcasecmp are not ANSI functions, so here are local
244 * definitions to do the same jobs.
245 */
246 static int
247 gagt_strncasecmp (const char *s1, const char *s2, size_t n)
248 {
249 size_t index;
250
251 for (index = 0; index < n; index++)
252 {
253 int diff;
254
255 diff = glk_char_to_lower (s1[index]) - glk_char_to_lower (s2[index]);
256 if (diff < 0 || diff > 0)
257 return diff < 0 ? -1 : 1;
258 }
259
260 return 0;
261 }
262
263 static int
264 gagt_strcasecmp (const char *s1, const char *s2)
265 {
266 size_t s1len, s2len;
267 int result;
268
269 s1len = strlen (s1);
270 s2len = strlen (s2);
271
272 result = gagt_strncasecmp (s1, s2, s1len < s2len ? s1len : s2len);
273 if (result < 0 || result > 0)
274 return result;
275 else
276 return s1len < s2len ? -1 : s1len > s2len ? 1 : 0;
277 }
278
279
280 /*
281 * gagt_debug()
282 *
283 * Handler for module debug output. If no debug, it ignores the call,
284 * otherwise it prints a debug message, prefixed by the function name.
285 */
286 static void
287 gagt_debug (const char *function, const char *format, ...)
288 {
289 if (DEBUG_OUT)
290 {
291 fprintf (debugfile, "%s (", function);
292 if (format && strlen (format) > 0)
293 {
294 va_list ap;
295
296 va_start (ap, format);
297 vfprintf (debugfile, format, ap);
298 va_end (ap);
299 }
300
301 fprintf (debugfile, ")\n");
302 fflush (debugfile);
303 }
304 }
305
306
307 /*---------------------------------------------------------------------*/
308 /* Functions not ported - functionally unchanged from os_none.c */
309 /*---------------------------------------------------------------------*/
310
311 /*
312 * agt_tone()
313 *
314 * Produce a hz-Hertz sound for ms milliseconds.
315 */
316 void
317 agt_tone (int hz, int ms)
318 {
319 gagt_debug ("agt_tone", "hz=%d, ms=%d", hz, ms);
320 }
321
322
323 /*
324 * agt_rand()
325 *
326 * Return random number from a to b inclusive. The random number generator
327 * is seeded on the first call, to a reproducible sequence if stable_random,
328 * otherwise using time().
329 */
330 int
331 agt_rand (int a, int b)
332 {
333 static int is_initialized = FALSE;
334
335 int result;
336
337 if (!is_initialized)
338 {
339 srand (stable_random ? 6 : time (0));
340
341 is_initialized = TRUE;
342 gagt_debug ("agt_rand", "[initialized]");
343 }
344
345 result = a + (rand () >> 2) % (b - a + 1);
346 gagt_debug ("agt_rand", "a=%d, b=%d -> %d", a, b, result);
347 return result;
348 }
349
350
351 /*---------------------------------------------------------------------*/
352 /* Workrounds for bugs in core AGiliTy. */
353 /*---------------------------------------------------------------------*/
354
355 /*
356 * gagt_workround_menus()
357 *
358 * Somewhere in AGiliTy's menu handling stuff is a condition that sets up
359 * an eventual NULL dereference in rstrncpy(), called from num_name_func().
360 * For some reason, perhaps memory overruns, perhaps something else, it
361 * happens after a few turns have been made through agt_menu(). Replacing
362 * agt_menu() won't avoid it.
363 *
364 * However, the menu stuff isn't too useful, or attractive, in a game, so one
365 * solution is to simply disable it. While not possible to do this directly,
366 * there is a sneaky way, using our carnal knowledge of core AGiliTy. In
367 * runverb.c, there is code to prevent menu mode from being turned on where
368 * verbmenu is NULL. Verbmenu is set up in agil.c on loading the game, but,
369 * crucially, is set up before agil.c calls start_interface(). So... here
370 * we can free it, set it to NULL, set menu_mode to 0 (it probably is already)
371 * and AGiliTy behaves as if the game prevents menu mode.
372 */
373 static void
374 gagt_workround_menus (void)
375 {
376 free (verbmenu);
377 verbmenu = NULL;
378
379 menu_mode = 0;
380 }
381
382
383 /*
384 * gagt_workround_fileexist()
385 *
386 * This function verifies that the game file can be opened, in effect second-
387 * guessing run_game().
388 *
389 * AGiliTy's fileexist() has in it either a bug, or a misfeature. It always
390 * passes a nofix value of 1 into try_open_file(), which defeats the code to
391 * retry with both upper and lower cased filenames. So here we have to go
392 * round the houses, with readopen()/readclose().
393 */
394 static int
395 gagt_workround_fileexist (fc_type fc, filetype ft)
396 {
397 genfile file;
398 char *errstr;
399
400 errstr = NULL;
401 file = readopen (fc, ft, &errstr);
402 free (errstr);
403
404 if (file)
405 {
406 readclose (file);
407 return TRUE;
408 }
409 return FALSE;
410 }
411
412
413 /*---------------------------------------------------------------------*/
414 /* I/O interface start and stop functions. */
415 /*---------------------------------------------------------------------*/
416
417 /* AGiliTy font_status values that indicate what font may be used. */
418 enum {
419 GAGT_FIXED_REQUIRED = 1, GAGT_PROPORTIONAL_OKAY = 2
420 };
421
422
423 /*
424 * start_interface()
425 * close_interface()
426 *
427 * Startup and shutdown callout points. The start function for Glk looks
428 * at the value of font_status that the game sets, to see if it has a strong
429 * view of the font to use. If it does, then we'll reflect that in the
430 * module's font contol, perhaps overriding any command line options that the
431 * user has passed in.
432 */
433 void
434 start_interface (fc_type fc)
435 {
436 switch (font_status)
437 {
438 case GAGT_FIXED_REQUIRED:
439 gagt_font_mode = FONT_FIXED_WIDTH;
440 break;
441
442 case GAGT_PROPORTIONAL_OKAY:
443 gagt_font_mode = FONT_PROPORTIONAL;
444 break;
445
446 default:
447 break;
448 }
449
450 gagt_workround_menus ();
451
452 gagt_debug ("start_interface", "fc=%p", fc);
453 }
454
455 void
456 close_interface (void)
457 {
458 if (filevalid (scriptfile, fSCR))
459 close_pfile (scriptfile, 0);
460
461 gagt_debug ("close_interface", "");
462 }
463
464
465 /*---------------------------------------------------------------------*/
466 /* Code page 437 to ISO 8859 Latin-1 translations */
467 /*---------------------------------------------------------------------*/
468
469 /*
470 * AGiliTy uses IBM code page 437 characters, and Glk works in ISO 8859
471 * Latin-1. There's some good news, in that a number of the characters,
472 * especially international ones, in these two sets are the same. The bad
473 * news is that, for codes above 127 (that is, beyond 7-bit ASCII), or for
474 * codes below 32, they live in different places. So, here is a table of
475 * conversions for codes not equivalent to 7-bit ASCII, and a pair of
476 * conversion routines.
477 *
478 * Note that some code page 437 characters don't have ISO 8859 Latin-1
479 * equivalents. Predominantly, these are the box-drawing characters, which
480 * is a pity, because these are the ones that are used the most. Anyway,
481 * in these cases, the table substitutes an approximated base ASCII char-
482 * acter in its place.
483 *
484 * The first entry of table comments below is the character's UNICODE value,
485 * just in case it's useful at some future date.
486 */
487 typedef const struct
488 {
489 const unsigned char cp437; /* Code page 437 character. */
490 const unsigned char iso8859_1; /* ISO 8859 Latin-1 character. */
491 } gagt_char_t;
492 typedef gagt_char_t *gagt_charref_t;
493
494 static gagt_char_t GAGT_CHAR_TABLE[] = {
495 /*
496 * Low characters -- those below 0x20. These are the really odd code
497 * page 437 characters, rarely used by AGT games. Low characters are
498 * omitted from the reverse lookup, and participate only in the forwards
499 * lookup from code page 437 to ISO 8859 Latin-1.
500 */
501 {0x01, '@'}, /* 263a White smiling face */
502 {0x02, '@'}, /* 263b Black smiling face */
503 {0x03, '?'}, /* 2665 Black heart suit */
504 {0x04, '?'}, /* 2666 Black diamond suit */
505 {0x05, '?'}, /* 2663 Black club suit */
506 {0x06, '?'}, /* 2660 Black spade suit */
507 {0x07, 0xb7}, /* 2022 Bullet */
508 {0x08, 0xb7}, /* 25d8 Inverse bullet */
509 {0x09, 0xb7}, /* 25e6 White bullet */
510 {0x0a, 0xb7}, /* 25d9 Inverse white circle */
511 {0x0b, '?'}, /* 2642 Male sign */
512 {0x0c, '?'}, /* 2640 Female sign */
513 {0x0d, '?'}, /* 266a Eighth note */
514 {0x0e, '?'}, /* 266b Beamed eighth notes */
515 {0x0f, 0xa4}, /* 263c White sun with rays */
516 {0x10, '>'}, /* 25b6 Black right-pointing triangle */
517 {0x11, '<'}, /* 25c0 Black left-pointing triangle */
518 {0x12, 0xa6}, /* 2195 Up down arrow */
519 {0x13, '!'}, /* 203c Double exclamation mark */
520 {0x14, 0xb6}, /* 00b6 Pilcrow sign */
521 {0x15, 0xa7}, /* 00a7 Section sign */
522 {0x16, '#'}, /* 25ac Black rectangle */
523 {0x17, 0xa6}, /* 21a8 Up down arrow with base */
524 {0x18, '^'}, /* 2191 Upwards arrow */
525 {0x19, 'v'}, /* 2193 Downwards arrow */
526 {0x1a, '>'}, /* 2192 Rightwards arrow */
527 {0x1b, '<'}, /* 2190 Leftwards arrow */
528 {0x1c, '?'}, /* 2310 Reversed not sign */
529 {0x1d, '-'}, /* 2194 Left right arrow */
530 {0x1e, '^'}, /* 25b2 Black up-pointing triangle */
531 {0x1f, 'v'}, /* 25bc Black down-pointing triangle */
532
533 /*
534 * High characters -- those above 0x7f. These are more often used by AGT
535 * games, particularly for box drawing.
536 */
537 {0x80, 0xc7}, /* 00c7 Latin capital letter c with cedilla */
538 {0x81, 0xfc}, /* 00fc Latin small letter u with diaeresis */
539 {0x82, 0xe9}, /* 00e9 Latin small letter e with acute */
540 {0x83, 0xe2}, /* 00e2 Latin small letter a with circumflex */
541 {0x84, 0xe4}, /* 00e4 Latin small letter a with diaeresis */
542 {0x85, 0xe0}, /* 00e0 Latin small letter a with grave */
543 {0x86, 0xe5}, /* 00e5 Latin small letter a with ring above */
544 {0x87, 0xe7}, /* 00e7 Latin small letter c with cedilla */
545 {0x88, 0xea}, /* 00ea Latin small letter e with circumflex */
546 {0x89, 0xeb}, /* 00eb Latin small letter e with diaeresis */
547 {0x8a, 0xe8}, /* 00e8 Latin small letter e with grave */
548 {0x8b, 0xef}, /* 00ef Latin small letter i with diaeresis */
549 {0x8c, 0xee}, /* 00ee Latin small letter i with circumflex */
550 {0x8d, 0xec}, /* 00ec Latin small letter i with grave */
551 {0x8e, 0xc4}, /* 00c4 Latin capital letter a with diaeresis */
552 {0x8f, 0xc5}, /* 00c5 Latin capital letter a with ring above */
553 {0x90, 0xc9}, /* 00c9 Latin capital letter e with acute */
554 {0x91, 0xe6}, /* 00e6 Latin small ligature ae */
555 {0x92, 0xc6}, /* 00c6 Latin capital ligature ae */
556 {0x93, 0xf4}, /* 00f4 Latin small letter o with circumflex */
557 {0x94, 0xf6}, /* 00f6 Latin small letter o with diaeresis */
558 {0x95, 0xf2}, /* 00f2 Latin small letter o with grave */
559 {0x96, 0xfb}, /* 00fb Latin small letter u with circumflex */
560 {0x97, 0xf9}, /* 00f9 Latin small letter u with grave */
561 {0x98, 0xff}, /* 00ff Latin small letter y with diaeresis */
562 {0x99, 0xd6}, /* 00d6 Latin capital letter o with diaeresis */
563 {0x9a, 0xdc}, /* 00dc Latin capital letter u with diaeresis */
564 {0x9b, 0xa2}, /* 00a2 Cent sign */
565 {0x9c, 0xa3}, /* 00a3 Pound sign */
566 {0x9d, 0xa5}, /* 00a5 Yen sign */
567 {0x9e, 'p'}, /* 20a7 Peseta sign */
568 {0x9f, 'f'}, /* 0192 Latin small letter f with hook */
569 {0xa0, 0xe1}, /* 00e1 Latin small letter a with acute */
570 {0xa1, 0xed}, /* 00ed Latin small letter i with acute */
571 {0xa2, 0xf3}, /* 00f3 Latin small letter o with acute */
572 {0xa3, 0xfa}, /* 00fa Latin small letter u with acute */
573 {0xa4, 0xf1}, /* 00f1 Latin small letter n with tilde */
574 {0xa5, 0xd1}, /* 00d1 Latin capital letter n with tilde */
575 {0xa6, 0xaa}, /* 00aa Feminine ordinal indicator */
576 {0xa7, 0xba}, /* 00ba Masculine ordinal indicator */
577 {0xa8, 0xbf}, /* 00bf Inverted question mark */
578 {0xa9, '.'}, /* 2310 Reversed not sign */
579 {0xaa, 0xac}, /* 00ac Not sign */
580 {0xab, 0xbd}, /* 00bd Vulgar fraction one half */
581 {0xac, 0xbc}, /* 00bc Vulgar fraction one quarter */
582 {0xad, 0xa1}, /* 00a1 Inverted exclamation mark */
583 {0xae, 0xab}, /* 00ab Left-pointing double angle quotation mark */
584 {0xaf, 0xbb}, /* 00bb Right-pointing double angle quotation mark */
585 {0xb0, '#'}, /* 2591 Light shade */
586 {0xb1, '#'}, /* 2592 Medium shade */
587 {0xb2, '#'}, /* 2593 Dark shade */
588 {0xb3, '|'}, /* 2502 Box light vertical */
589 {0xb4, '+'}, /* 2524 Box light vertical and left */
590 {0xb5, '+'}, /* 2561 Box vertical single and left double */
591 {0xb6, '|'}, /* 2562 Box vertical double and left single */
592 {0xb7, '+'}, /* 2556 Box down double and left single */
593 {0xb8, '+'}, /* 2555 Box down single and left double */
594 {0xb9, '+'}, /* 2563 Box double vertical and left */
595 {0xba, '|'}, /* 2551 Box double vertical */
596 {0xbb, '\\'}, /* 2557 Box double down and left */
597 {0xbc, '/'}, /* 255d Box double up and left */
598 {0xbd, '+'}, /* 255c Box up double and left single */
599 {0xbe, '+'}, /* 255b Box up single and left double */
600 {0xbf, '\\'}, /* 2510 Box light down and left */
601 {0xc0, '\\'}, /* 2514 Box light up and right */
602 {0xc1, '+'}, /* 2534 Box light up and horizontal */
603 {0xc2, '+'}, /* 252c Box light down and horizontal */
604 {0xc3, '+'}, /* 251c Box light vertical and right */
605 {0xc4, '-'}, /* 2500 Box light horizontal */
606 {0xc5, '+'}, /* 253c Box light vertical and horizontal */
607 {0xc6, '|'}, /* 255e Box vertical single and right double */
608 {0xc7, '|'}, /* 255f Box vertical double and right single */
609 {0xc8, '\\'}, /* 255a Box double up and right */
610 {0xc9, '/'}, /* 2554 Box double down and right */
611 {0xca, '+'}, /* 2569 Box double up and horizontal */
612 {0xcb, '+'}, /* 2566 Box double down and horizontal */
613 {0xcc, '+'}, /* 2560 Box double vertical and right */
614 {0xcd, '='}, /* 2550 Box double horizontal */
615 {0xce, '+'}, /* 256c Box double vertical and horizontal */
616 {0xcf, '='}, /* 2567 Box up single and horizontal double */
617 {0xd0, '+'}, /* 2568 Box up double and horizontal single */
618 {0xd1, '='}, /* 2564 Box down single and horizontal double */
619 {0xd2, '+'}, /* 2565 Box down double and horizontal single */
620 {0xd3, '+'}, /* 2559 Box up double and right single */
621 {0xd4, '+'}, /* 2558 Box up single and right double */
622 {0xd5, '+'}, /* 2552 Box down single and right double */
623 {0xd6, '+'}, /* 2553 Box down double and right single */
624 {0xd7, '+'}, /* 256b Box vertical double and horizontal single */
625 {0xd8, '+'}, /* 256a Box vertical single and horizontal double */
626 {0xd9, '/'}, /* 2518 Box light up and left */
627 {0xda, '/'}, /* 250c Box light down and right */
628 {0xdb, '@'}, /* 2588 Full block */
629 {0xdc, '@'}, /* 2584 Lower half block */
630 {0xdd, '@'}, /* 258c Left half block */
631 {0xde, '@'}, /* 2590 Right half block */
632 {0xdf, '@'}, /* 2580 Upper half block */
633 {0xe0, 'a'}, /* 03b1 Greek small letter alpha */
634 {0xe1, 0xdf}, /* 00df Latin small letter sharp s */
635 {0xe2, 'G'}, /* 0393 Greek capital letter gamma */
636 {0xe3, 'p'}, /* 03c0 Greek small letter pi */
637 {0xe4, 'S'}, /* 03a3 Greek capital letter sigma */
638 {0xe5, 's'}, /* 03c3 Greek small letter sigma */
639 {0xe6, 0xb5}, /* 00b5 Micro sign */
640 {0xe7, 't'}, /* 03c4 Greek small letter tau */
641 {0xe8, 'F'}, /* 03a6 Greek capital letter phi */
642 {0xe9, 'T'}, /* 0398 Greek capital letter theta */
643 {0xea, 'O'}, /* 03a9 Greek capital letter omega */
644 {0xeb, 'd'}, /* 03b4 Greek small letter delta */
645 {0xec, '.'}, /* 221e Infinity */
646 {0xed, 'f'}, /* 03c6 Greek small letter phi */
647 {0xee, 'e'}, /* 03b5 Greek small letter epsilon */
648 {0xef, '^'}, /* 2229 Intersection */
649 {0xf0, '='}, /* 2261 Identical to */
650 {0xf1, 0xb1}, /* 00b1 Plus-minus sign */
651 {0xf2, '>'}, /* 2265 Greater-than or equal to */
652 {0xf3, '<'}, /* 2264 Less-than or equal to */
653 {0xf4, 'f'}, /* 2320 Top half integral */
654 {0xf5, 'j'}, /* 2321 Bottom half integral */
655 {0xf6, 0xf7}, /* 00f7 Division sign */
656 {0xf7, '='}, /* 2248 Almost equal to */
657 {0xf8, 0xb0}, /* 00b0 Degree sign */
658 {0xf9, 0xb7}, /* 2219 Bullet operator */
659 {0xfa, 0xb7}, /* 00b7 Middle dot */
660 {0xfb, '/'}, /* 221a Square root */
661 {0xfc, 'n'}, /* 207f Superscript latin small letter n */
662 {0xfd, 0xb2}, /* 00b2 Superscript two */
663 {0xfe, '#'}, /* 25a0 Black square */
664 {0xff, 0xa0}, /* 00a0 No-break space */
665 {0, 0} /* 0000 [END OF TABLE] */
666 };
667
668
669 /*
670 * gagt_cp_to_iso()
671 *
672 * Convert a string from code page 437 into ISO 8859 Latin-1. The input and
673 * output buffers may be one and the same.
674 */
675 static void
676 gagt_cp_to_iso (const unsigned char *from_string, unsigned char *to_string)
677 {
678 static int is_initialized = FALSE;
679 static unsigned char table[UCHAR_MAX + 1];
680
681 int index;
682 unsigned char cp437, iso8859_1;
683 assert (from_string && to_string);
684
685 if (!is_initialized)
686 {
687 gagt_charref_t entry;
688
689 /*
690 * Create a lookup entry for each code in the main table. Fill in gaps
691 * for 7-bit characters with their ASCII equivalent values. Any
692 * remaining codes not represented in the main table will map to zeroes
693 * in the lookup table, as static variables are initialized to zero.
694 */
695 for (entry = GAGT_CHAR_TABLE; entry->cp437; entry++)
696 {
697 cp437 = entry->cp437;
698 iso8859_1 = entry->iso8859_1;
699
700 assert (cp437 < 0x20 || (cp437 > SCHAR_MAX && cp437 <= UCHAR_MAX));
701 table[cp437] = iso8859_1;
702 }
703 for (index = 0; index <= SCHAR_MAX; index++)
704 {
705 if (table[index] == 0)
706 table[index] = index;
707 }
708
709 is_initialized = TRUE;
710 }
711
712 for (index = 0; from_string[index] != '\0'; index++)
713 {
714 cp437 = from_string[index];
715 iso8859_1 = table[cp437];
716
717 to_string[index] = iso8859_1 ? iso8859_1 : cp437;
718 }
719
720 to_string[index] = '\0';
721 }
722
723
724 /*
725 * gagt_iso_to_cp()
726 *
727 * Convert a string from ISO 8859 Latin-1 to code page 437. The input and
728 * output buffers may be one and the same.
729 */
730 static void
731 gagt_iso_to_cp (const unsigned char *from_string, unsigned char *to_string)
732 {
733 static int is_initialized = FALSE;
734 static unsigned char table[UCHAR_MAX + 1];
735
736 int index;
737 unsigned char iso8859_1, cp437;
738 assert (from_string && to_string);
739
740 if (!is_initialized)
741 {
742 gagt_charref_t entry;
743
744 /*
745 * Create a reverse lookup entry for each code in the main table,
746 * overriding all of the low table entries (that is, anything under
747 * 128) with their ASCII no matter what the table contained.
748 *
749 * Any codes not represented in the main table will map to zeroes in
750 * the reverse lookup table, since static variables are initialized to
751 * zero. The first 128 characters are equivalent to ASCII. Moreover,
752 * some ISO 8859 Latin-1 entries are faked as base ASCII; where an
753 * entry is already occupied, the main table entry is skipped, so the
754 * match, which is n:1 in the reverse direction, works in first-found
755 * mode.
756 */
757 for (entry = GAGT_CHAR_TABLE; entry->iso8859_1; entry++)
758 {
759 cp437 = entry->cp437;
760 iso8859_1 = entry->iso8859_1;
761
762 assert (iso8859_1 <= UCHAR_MAX);
763 if (table[iso8859_1] == 0)
764 table[iso8859_1] = cp437;
765 }
766 for (index = 0; index <= SCHAR_MAX; index++)
767 table[index] = index;
768
769 is_initialized = TRUE;
770 }
771
772 for (index = 0; from_string[index] != '\0'; index++)
773 {
774 iso8859_1 = from_string[index];
775 cp437 = table[iso8859_1];
776
777 to_string[index] = cp437 ? cp437 : iso8859_1;
778 }
779
780 to_string[index] = '\0';
781 }
782
783
784 /*---------------------------------------------------------------------*/
785 /* Glk port status line functions */
786 /*---------------------------------------------------------------------*/
787
788 /*
789 * Buffered copy of the latest status line passed in by the interpreter.
790 * Buffering it means it's readily available to print for Glk libraries
791 * that don't support separate windows. We also need a copy of the last
792 * status buffer printed for non-windowing Glk libraries, for comparison.
793 */
794 static char *gagt_status_buffer = NULL,
795 *gagt_status_buffer_printed = NULL;
796
797 /*
798 * Indication that we are in mid-delay. The delay is silent, and can look
799 * kind of confusing, so to try to make it less so, we'll have the status
800 * window show something about it.
801 */
802 static int gagt_inside_delay = FALSE;
803
804
805 /*
806 * agt_statline()
807 *
808 * This function is called from our call to print_statline(). Here we'll
809 * convert the string and buffer in an allocated area for later use.
810 */
811 void
812 agt_statline (const char *cp_string)
813 {
814 assert (cp_string);
815
816 free (gagt_status_buffer);
817 gagt_status_buffer = gagt_malloc (strlen (cp_string) + 1);
818 gagt_cp_to_iso ((const unsigned char *)cp_string, (unsigned char *)gagt_status_buffer);
819
820 gagt_debug ("agt_statline", "string='%s'", cp_string);
821 }
822
823
824 /*
825 * gagt_status_update_extended()
826 *
827 * Helper for gagt_status_update() and gagt_status_in_delay(). This function
828 * displays the second line of any extended status display, giving a list of
829 * exits from the compass rose, and if in an AGT delay, a waiting indicator.
830 */
831 static void
832 gagt_status_update_extended (void)
833 {
834 glui32 width, height;
835 assert (gagt_status_window);
836
837 glk_window_get_size (gagt_status_window, &width, &height);
838 if (height > 1)
839 {
840 int index, exit;
841
842 /* Clear the second status line only. */
843 glk_window_move_cursor (gagt_status_window, 0, 1);
844 glk_set_window (gagt_status_window);
845 glk_set_style (style_User1);
846 for (index = 0; index < width; index++)
847 glk_put_char (' ');
848
849 /*
850 * Check bits in the compass rose, and print out exit names from
851 * the exitname[] array.
852 */
853 glk_window_move_cursor (gagt_status_window, 0, 1);
854 glk_put_string (" Exits: ");
855 for (exit = 0; exit < sizeof (exitname) / sizeof (exitname[0]); exit++)
856 {
857 if (compass_rose & (1 << exit))
858 {
859 glk_put_string ((char *) exitname[exit]);
860 glk_put_char (' ');
861 }
862 }
863
864 /* If the delay flag is set, print a waiting indicator at the right. */
865 if (gagt_inside_delay)
866 {
867 glk_window_move_cursor (gagt_status_window,
868 width - strlen ("Waiting... "), 1);
869 glk_put_string ("Waiting... ");
870 }
871
872 glk_set_window (gagt_main_window);
873 }
874 }
875
876
877 /*
878 * gagt_status_update()
879 *
880 *
881 * This function calls print_statline() to prompt the interpreter into calling
882 * our agt_statline(), then if we have a status window, displays the status
883 * string, and calls gagt_status_update_extended() if necessary to handle the
884 * second status line. If we don't see a call to our agt_statline, we output
885 * a default status string.
886 */
887 static void
888 gagt_status_update (void)
889 {
890 glui32 width, height;
891 int index;
892 assert (gagt_status_window);
893
894 glk_window_get_size (gagt_status_window, &width, &height);
895 if (height > 0)
896 {
897 glk_window_clear (gagt_status_window);
898 glk_window_move_cursor (gagt_status_window, 0, 0);
899 glk_set_window (gagt_status_window);
900
901 glk_set_style (style_User1);
902 for (index = 0; index < width; index++)
903 glk_put_char (' ');
904 glk_window_move_cursor (gagt_status_window, 0, 0);
905
906 /* Call print_statline() to refresh status line buffer contents. */
907 print_statline ();
908
909 /* See if we have a buffered status line available. */
910 if (gagt_status_buffer)
911 {
912 glui32 print_width;
913
914 /*
915 * Print the basic buffered status string, truncating to the
916 * current status window width if necessary, then try adding a
917 * second line if extended status enabled.
918 */
919 print_width = width < strlen (gagt_status_buffer)
920 ? width : strlen (gagt_status_buffer);
921 glk_put_buffer (gagt_status_buffer, print_width);
922
923 if (gagt_extended_status_enabled)
924 gagt_status_update_extended ();
925 }
926 else
927 {
928 /*
929 * We don't (yet) have a status line. Perhaps we're at the
930 * very start of a game. Print a standard message.
931 */
932 glk_put_string ("Glk AGiliTy version 1.1.1");
933 }
934
935 glk_set_window (gagt_main_window);
936 }
937 }
938
939
940 /*
941 * gagt_status_print()
942 *
943 * Print the current contents of the completed status line buffer out in the
944 * main window, if it has changed since the last call. This is for non-
945 * windowing Glk libraries.
946 *
947 * Like gagt_status_update(), this function calls print_statline() to prompt
948 * the interpreter into calling our agt_statline(), then if we have a new
949 * status line, it prints it.
950 */
951 static void
952 gagt_status_print (void)
953 {
954 /* Call print_statline() to refresh status line buffer contents. */
955 print_statline ();
956
957 /*
958 * Do no more if there is no status line to print, or if the status
959 * line hasn't changed since last printed.
960 */
961 if (!gagt_status_buffer
962 || (gagt_status_buffer_printed
963 && strcmp (gagt_status_buffer, gagt_status_buffer_printed) == 0))
964 return;
965
966 /* Set fixed width font to try to preserve status line formatting. */
967 glk_set_style (style_Preformatted);
968
969 /*
970 * Bracket, and output the status line buffer. We don't need to put any
971 * spacing after the opening bracket or before the closing one, because
972 * AGiliTy puts leading/trailing spaces on its status lines.
973 */
974 glk_put_string ("[");
975 glk_put_string (gagt_status_buffer);
976 glk_put_string ("]\n");
977
978 /* Save the details of the printed status buffer. */
979 free (gagt_status_buffer_printed);
980 gagt_status_buffer_printed = gagt_malloc (strlen (gagt_status_buffer) + 1);
981 strcpy (gagt_status_buffer_printed, gagt_status_buffer);
982 }
983
984
985 /*
986 * gagt_status_notify()
987 *
988 * Front end function for updating status. Either updates the status window
989 * or prints the status line to the main window.
990 *
991 * Functions interested in updating the status line should call either this
992 * function, or gagt_status_redraw(), and not print_statline().
993 */
994 static void
995 gagt_status_notify (void)
996 {
997 if (!BATCH_MODE)
998 {
999 if (gagt_status_window)
1000 gagt_status_update ();
1001 else
1002 gagt_status_print ();
1003 }
1004 }
1005
1006
1007 /*
1008 * gagt_status_redraw()
1009 *
1010 * Redraw the contents of any status window with the buffered status string.
1011 * This function handles window sizing, and updates the interpreter with
1012 * status_width, so may, and should, be called on resize and arrange events.
1013 *
1014 * Functions interested in updating the status line should call either this
1015 * function, or gagt_status_notify(), and not print_statline().
1016 */
1017 static void
1018 gagt_status_redraw (void)
1019 {
1020 if (!BATCH_MODE)
1021 {
1022 if (gagt_status_window)
1023 {
1024 glui32 width, height;
1025 winid_t parent;
1026
1027 /*
1028 * Measure the status window, and update the interpreter's
1029 * status_width variable.
1030 */
1031 glk_window_get_size (gagt_status_window, &width, &height);
1032 status_width = width;
1033
1034 /*
1035 * Rearrange the status window, without changing its actual
1036 * arrangement in any way. This is a hack to work round
1037 * incorrect window repainting in Xglk; it forces a complete
1038 * repaint of affected windows on Glk window resize and
1039 * arrange events, and works in part because Xglk doesn't
1040 * check for actual arrangement changes in any way before
1041 * invalidating its windows. The hack should be harmless to
1042 * Glk libraries other than Xglk, moreover, we're careful to
1043 * activate it only on resize and arrange events.
1044 */
1045 parent = glk_window_get_parent (gagt_status_window);
1046 glk_window_set_arrangement (parent,
1047 winmethod_Above | winmethod_Fixed,
1048 height, NULL);
1049
1050 gagt_status_update ();
1051 }
1052 }
1053 }
1054
1055
1056 /*
1057 * gagt_status_in_delay()
1058 *
1059 * Tells status line functions whether the game is delaying, or not. This
1060 * function updates the extended status line, if present, automatically.
1061 */
1062 static void
1063 gagt_status_in_delay (int inside_delay)
1064 {
1065 if (!BATCH_MODE)
1066 {
1067 /* Save the new delay status flag. */
1068 gagt_inside_delay = inside_delay;
1069
1070 /*
1071 * Update just the second line of the status window display, if
1072 * extended status is being displayed.
1073 */
1074 if (gagt_status_window && gagt_extended_status_enabled)
1075 gagt_status_update_extended ();
1076 }
1077 }
1078
1079
1080 /*
1081 * gagt_status_cleanup()
1082 *
1083 * Free memory resources allocated by status line functions. Called on game
1084 * end.
1085 */
1086 static void
1087 gagt_status_cleanup (void)
1088 {
1089 free (gagt_status_buffer);
1090 gagt_status_buffer = NULL;
1091
1092 free (gagt_status_buffer_printed);
1093 gagt_status_buffer_printed = NULL;
1094 }
1095
1096
1097 /*---------------------------------------------------------------------*/
1098 /* Glk port color and text attribute handling */
1099 /*---------------------------------------------------------------------*/
1100
1101 /*
1102 * AGT color and character attribute definitions. This is the range of
1103 * values passed in to agt_textcolor().
1104 */
1105 enum {
1106 AGT_BLACK = 0,
1107 AGT_BLUE = 1,
1108 AGT_GREEN = 2,
1109 AGT_CYAN = 3,
1110 AGT_RED = 4,
1111 AGT_MAGENTA = 5,
1112 AGT_BROWN = 6,
1113 AGT_NORMAL = 7,
1114 AGT_BLINKING = 8,
1115 AGT_WHITE = 9,
1116 AGT_FIXED_FONT = 10,
1117 AGT_VARIABLE_FONT = 11,
1118 AGT_EMPHASIS = -1,
1119 AGT_DE_EMPHASIS = -2
1120 };
1121
1122 /*
1123 * AGiliTy colors and text attributes seem a bit confused. Let's see if we
1124 * can sort them out. Sadly, once we have, it's often not possible to
1125 * render the full range in all Glk's anyway. Nevertheless...
1126 */
1127 typedef struct {
1128 int color; /* Text color. */
1129 int blink; /* Text blinking flag. */
1130 int fixed; /* Text fixed font flag. */
1131 int emphasis; /* Text emphasized flag. */
1132 } gagt_attrset_t;
1133
1134 /*
1135 * Attributes as currently set by AGiliTy. The default values set up here
1136 * correspond to AGT_NORMAL.
1137 */
1138 static gagt_attrset_t gagt_current_attribute_set = { AGT_WHITE, FALSE,
1139 FALSE, FALSE };
1140
1141 /*
1142 * An extra flag to indicate if we have coerced fixed font override. On
1143 * some occasions, we need to ensure that we get fixed font no matter what
1144 * the game says.
1145 */
1146 static int gagt_coerced_fixed = FALSE;
1147
1148 /*
1149 * Bit masks for packing colors and attributes. Normally, I don't like
1150 * bit-twiddling all that much, but for packing all of the above into a
1151 * single byte, that's what we need. Stuff color into the low four bits,
1152 * convenient since color is from 0 to 9, then use three bits for the other
1153 * attributes.
1154 */
1155 static const unsigned char GAGT_COLOR_MASK = 0x0f,
1156 GAGT_BLINK_MASK = 1 << 4,
1157 GAGT_FIXED_MASK = 1 << 5,
1158 GAGT_EMPHASIS_MASK = 1 << 6;
1159
1160 /* Forward declaration of message function. */
1161 static void gagt_standout_string (const char *message);
1162
1163
1164 /*
1165 * agt_textcolor()
1166 *
1167 * The AGiliTy porting guide defines the use of this function as:
1168 *
1169 * Set text color to color #c, where the colors are as follows:
1170 * 0=Black, 1=Blue, 2=Green, 3=Cyan,
1171 * 4=Red, 5=Magenta, 6=Brown,
1172 * 7=Normal("White"-- which may actually be some other color)
1173 * This should turn off blinking, bold, color, etc. and restore
1174 * the text mode to its default appearance.
1175 * 8=Turn on blinking.
1176 * 9= *Just* White (not neccessarily "normal" and no need to turn off
1177 * blinking)
1178 * 10=Turn on fixed pitch font.
1179 * 11=Turn off fixed pitch font
1180 * Also used to set other text attributes:
1181 * -1=emphasized text, used (e.g.) for room titles
1182 * -2=end emphasized text
1183 *
1184 * Here we try to make sense of all this. Given an argument, we'll try to
1185 * update our separated color and text attributes flags to reflect the
1186 * expected text rendering.
1187 */
1188 void
1189 agt_textcolor (int color)
1190 {
1191 switch (color)
1192 {
1193 case AGT_BLACK:
1194 case AGT_BLUE:
1195 case AGT_GREEN:
1196 case AGT_CYAN:
1197 case AGT_RED:
1198 case AGT_MAGENTA:
1199 case AGT_BROWN:
1200 case AGT_WHITE:
1201 gagt_current_attribute_set.color = color;
1202 break;
1203
1204 case AGT_NORMAL:
1205 gagt_current_attribute_set.color = AGT_WHITE;
1206 gagt_current_attribute_set.blink = FALSE;
1207 gagt_current_attribute_set.fixed = FALSE;
1208 gagt_current_attribute_set.emphasis = FALSE;
1209 break;
1210
1211 case AGT_BLINKING:
1212 gagt_current_attribute_set.blink = TRUE;
1213 break;
1214
1215 case AGT_FIXED_FONT:
1216 gagt_current_attribute_set.fixed = TRUE;
1217 break;
1218
1219 case AGT_VARIABLE_FONT:
1220 gagt_current_attribute_set.fixed = FALSE;
1221 break;
1222
1223 case AGT_EMPHASIS:
1224 gagt_current_attribute_set.emphasis = TRUE;
1225 break;
1226
1227 case AGT_DE_EMPHASIS:
1228 gagt_current_attribute_set.emphasis = FALSE;
1229 break;
1230
1231 default:
1232 gagt_fatal ("GLK: Unknown color encountered");
1233 gagt_exit ();
1234 }
1235
1236 gagt_debug ("agt_textcolor", "color=% d -> %d%s%s%s",
1237 color,
1238 gagt_current_attribute_set.color,
1239 gagt_current_attribute_set.blink ? " blink" : "",
1240 gagt_current_attribute_set.fixed ? " fixed" : "",
1241 gagt_current_attribute_set.emphasis ? " bold" : "");
1242 }
1243
1244
1245 /*
1246 * gagt_coerce_fixed_font()
1247 *
1248 * This coerces, or relaxes, a fixed font setting. Used by box drawing, to
1249 * ensure that we get a temporary fixed font setting for known differenti-
1250 * ated parts of game output text. Pass in TRUE to coerce fixed font, and
1251 * FALSE to relax it.
1252 */
1253 static void
1254 gagt_coerce_fixed_font (int coerce)
1255 {
1256 gagt_coerced_fixed = coerce;
1257 }
1258
1259
1260 /*
1261 * gagt_pack_attributes()
1262 *
1263 * Pack a set of color and text rendering attributes into a single byte,
1264 * and return it. This function is used so that a set of text attributes
1265 * can be encoded into a byte array that parallels the output strings that
1266 * we buffer from the interpreter.
1267 */
1268 static unsigned char
1269 gagt_pack_attributes (const gagt_attrset_t * attribute_set, int coerced)
1270 {
1271 unsigned char packed;
1272 assert (attribute_set);
1273
1274 /* Set the initial result to be color; these are the low bits. */
1275 assert ((attribute_set->color & ~GAGT_COLOR_MASK) == 0);
1276 packed = attribute_set->color;
1277
1278 /*
1279 * Now OR in the text attributes settings, taking either the value for
1280 * fixed or the coerced fixed font.
1281 */
1282 packed |= attribute_set->blink ? GAGT_BLINK_MASK : 0;
1283 packed |= attribute_set->fixed || coerced ? GAGT_FIXED_MASK : 0;
1284 packed |= attribute_set->emphasis ? GAGT_EMPHASIS_MASK : 0;
1285
1286 return packed;
1287 }
1288
1289
1290 /*
1291 * gagt_unpack_attributes()
1292 *
1293 * Unpack a set of packed current color and text rendering attributes from a
1294 * single byte, and return the result of unpacking. This reconstitutes the
1295 * text attributes that were current at the time of packing.
1296 */
1297 static void
1298 gagt_unpack_attributes (unsigned char packed, gagt_attrset_t * attribute_set)
1299 {
1300 assert (attribute_set);
1301
1302 attribute_set->color = packed & GAGT_COLOR_MASK;
1303 attribute_set->blink = (packed & GAGT_BLINK_MASK) != 0;
1304 attribute_set->fixed = (packed & GAGT_FIXED_MASK) != 0;
1305 attribute_set->emphasis = (packed & GAGT_EMPHASIS_MASK) != 0;
1306 }
1307
1308
1309 /*
1310 * gagt_pack_current_attributes()
1311 *
1312 * Pack the current color and text rendering attributes into a single byte,
1313 * and return it.
1314 */
1315 static unsigned char
1316 gagt_pack_current_attributes (void)
1317 {
1318 return gagt_pack_attributes (&gagt_current_attribute_set, gagt_coerced_fixed);
1319 }
1320
1321
1322 /*
1323 * gagt_init_user_styles()
1324 *
1325 * Attempt to set up two defined styles, User1 and User2, to represent
1326 * fixed font with AGT emphasis (rendered as Glk subheader), and fixed font
1327 * with AGT blink (rendered as Glk emphasis), respectively.
1328 *
1329 * The Glk stylehints here may not actually be honored by the Glk library.
1330 * We'll try to detect this later on.
1331 */
1332 static void
1333 gagt_init_user_styles (void)
1334 {
1335 /*
1336 * Set User1 to be fixed width, bold, and not italic. Here we're sort of
1337 * assuming that the style starts life equal to Normal.
1338 */
1339 glk_stylehint_set (wintype_TextBuffer, style_User1,
1340 stylehint_Proportional, 0);
1341 glk_stylehint_set (wintype_TextBuffer, style_User1, stylehint_Weight, 1);
1342 glk_stylehint_set (wintype_TextBuffer, style_User1, stylehint_Oblique, 0);
1343
1344 /*
1345 * Set User2 to be fixed width, normal, and italic, with the same
1346 * assumptions.
1347 */
1348 glk_stylehint_set (wintype_TextBuffer, style_User2,
1349 stylehint_Proportional, 0);
1350 glk_stylehint_set (wintype_TextBuffer, style_User2, stylehint_Weight, 0);
1351 glk_stylehint_set (wintype_TextBuffer, style_User2, stylehint_Oblique, 1);
1352 }
1353
1354
1355 /*
1356 * gagt_confirm_appearance()
1357 *
1358 * Attempt to find out if a Glk style's on screen appearance matches a given
1359 * expectation. There's a chance (often 100% with current Xglk) that we
1360 * can't tell, in which case we'll play safe, and say that it doesn't (our
1361 * caller is hoping it does).
1362 *
1363 * That is, when we return FALSE, we mean either it's not as expected, or we
1364 * don't know.
1365 */
1366 static int
1367 gagt_confirm_appearance (glui32 style, glui32 stylehint, glui32 expected)
1368 {
1369 glui32 result;
1370
1371 if (glk_style_measure (gagt_main_window, style, stylehint, &result))
1372 {
1373 /*
1374 * Measurement succeeded, so return TRUE if the result matches the
1375 * caller's expectation.
1376 */
1377 if (result == expected)
1378 return TRUE;
1379 }
1380
1381 /* No straight answer, or the style's stylehint failed to match. */
1382 return FALSE;
1383 }
1384
1385
1386 /*
1387 * gagt_is_style_fixed()
1388 * gagt_is_style_bold()
1389 * gagt_is_style_oblique()
1390 *
1391 * Convenience functions for gagt_select_style(). A return of TRUE indicates
1392 * that the style has this attribute; FALSE indicates either that it hasn't,
1393 * or that it's not determinable.
1394 */
1395 static int
1396 gagt_is_style_fixed (glui32 style)
1397 {
1398 return gagt_confirm_appearance (style, stylehint_Proportional, 0);
1399 }
1400
1401 static int
1402 gagt_is_style_bold (glui32 style)
1403 {
1404 return gagt_confirm_appearance (style, stylehint_Weight, 1);
1405 }
1406
1407 static int
1408 gagt_is_style_oblique (glui32 style)
1409 {
1410 return gagt_confirm_appearance (style, stylehint_Oblique, 1);
1411 }
1412
1413
1414 /*
1415 * gagt_select_style()
1416 *
1417 * Given a set of AGT text attributes, this function returns a Glk style that
1418 * is suitable (or more accurately, the best we can come up with) for render-
1419 * ing this set of attributes.
1420 *
1421 * For now, we ignore color totally, and just concentrate on the other attr-
1422 * ibutes. This is because few, if any, games use color (no Photopia here),
1423 * few Glk libraries, at least on Linux, allow fine grained control over text
1424 * color, and even if you can get it, the scarcity of user-defined styles in
1425 * Glk makes it too painful to contemplate.
1426 */
1427 static glui32
1428 gagt_select_style (gagt_attrset_t * attribute_set)
1429 {
1430 glui32 style;
1431 assert (attribute_set);
1432
1433 /*
1434 * Glk styles are mutually exclusive, so here we'll work here by making a
1435 * precedence selection: AGT emphasis take precedence over AGT blinking,
1436 * which itself takes precedence over normal text. Fortunately, few, if
1437 * any, AGT games set both emphasis and blinking (not likely to be a
1438 * pleasant combination).
1439 *
1440 * We'll try to map AGT emphasis to Glk Subheader, AGT blink to Glk
1441 * Emphasized, and normal text to Glk Normal, with modifications to this
1442 * for fixed width requests.
1443 *
1444 * First, then, see if emphasized text is requested in the attributes.
1445 */
1446 if (attribute_set->emphasis)
1447 {
1448 /*
1449 * Consider whether something requested a fixed width font or
1450 * disallowed a proportional one.
1451 *
1452 * Glk Preformatted is boring, flat, and lifeless. It often offers no
1453 * fine grained control over emphasis, and so on. So here we try to
1454 * find something better. However, not all Glk libraries implement
1455 * stylehints, so we need to try to be careful to ensure that we get a
1456 * fixed width font, no matter what else we may miss out on.
1457 */
1458 if (attribute_set->fixed)
1459 {
1460 /*
1461 * To start off, we'll see if User1, the font we set up for fixed
1462 * width bold, really is fixed width and bold. If it is, we'll
1463 * use it.
1464 *
1465 * If it isn't, we'll check Subheader. Our Glk library probably
1466 * isn't implementing stylehints, but if Subheader is fixed width,
1467 * it may provide a better look than Preformatted -- certainly
1468 * it's worth a go.
1469 *
1470 * If Subheader isn't fixed width, we'll take another look at User1.
1471 * It could be that the check for bold wasn't definitive, but it
1472 * is nevertheless bold. So check for fixed width -- if set, it's
1473 * probably good enough to use this font, certainly no worse than
1474 * Preformatted.
1475 *
1476 * If Subheader isn't guaranteed fixed width, nor is User1, we're
1477 * cornered into Preformatted.
1478 */
1479 if (gagt_is_style_fixed (style_User1)
1480 && gagt_is_style_bold (style_User1))
1481 style = style_User1;
1482
1483 else if (gagt_is_style_fixed (style_Subheader))
1484 style = style_Subheader;
1485
1486 else if (gagt_is_style_fixed (style_User1))
1487 style = style_User1;
1488
1489 else
1490 style = style_Preformatted;
1491 }
1492 else
1493 /* This is the easy case, use Subheader. */
1494 style = style_Subheader;
1495 }
1496 else if (attribute_set->blink)
1497 {
1498 /*
1499 * Again, consider whether something requested a fixed width
1500 * font or disallowed a proportional one.
1501 */
1502 if (attribute_set->fixed)
1503 {
1504 /*
1505 * As above, try to find something better than Preformatted, first
1506 * trying User2, then Emphasized, then User2 again, and finally
1507 * settling for Preformatted if neither of these two looks any
1508 * better.
1509 */
1510 if (gagt_is_style_fixed (style_User2)
1511 && gagt_is_style_oblique (style_User2))
1512 style = style_User2;
1513
1514 else if (gagt_is_style_fixed (style_Emphasized))
1515 style = style_Emphasized;
1516
1517 else if (gagt_is_style_fixed (style_User2))
1518 style = style_User2;
1519
1520 else
1521 style = style_Preformatted;
1522 }
1523 else
1524 /* This is the easy case, use Emphasized. */
1525 style = style_Emphasized;
1526 }
1527 else
1528 {
1529 /*
1530 * There's no emphasis or blinking in the attributes. In this case,
1531 * use Preformatted for fixed width, and Normal for text that can be
1532 * rendered proportionally.
1533 */
1534 if (attribute_set->fixed)
1535 style = style_Preformatted;
1536 else
1537 style = style_Normal;
1538 }
1539
1540 return style;
1541 }
1542
1543
1544 /*---------------------------------------------------------------------*/
1545 /* Glk port output buffering functions */
1546 /*---------------------------------------------------------------------*/
1547
1548 /*
1549 * Buffering game output happens at two levels. The first level is a single
1550 * line buffer, used to catch text sent to us with agt_puts(). In parallel
1551 * with the text strings, we keep and buffer the game text attributes, as
1552 * handed to agt_textcolor(), that are in effect at the time the string is
1553 * handed to us, packed for brevity.
1554 *
1555 * As each line is completed, by a call to agt_newline(), this single line
1556 * buffer is transferred to a main text page buffer. The main page buffer
1557 * has places in it where we can assign paragraph, font hints, and perhaps
1558 * other marker information to a line. Initially unset, they're filled in
1559 * at the point where we need to display the buffer.
1560 */
1561
1562 /*
1563 * Definition of font hints values. Font hints may be:
1564 * o none, for lines not in a definite paragraph;
1565 * o proportional, for lines that can probably be safely rendered in a
1566 * proportional font (if the AGT game text attributes allow it) and
1567 * where the newline may be replaced by a space;
1568 * o proportional_newline, for lines that may be rendered using a
1569 * proportional font, but where the newline looks like it matters;
1570 * o proportional_newline_standout, for proportional_newline lines that
1571 * are also standout (for spacing in display functions);
1572 * o fixed_width, for tables and other text that looks like it is a
1573 * candidate for fixed font output.
1574 */
1575 typedef enum {
1576 HINT_NONE,
1577 HINT_PROPORTIONAL,
1578 HINT_PROPORTIONAL_NEWLINE,
1579 HINT_PROPORTIONAL_NEWLINE_STANDOUT,
1580 HINT_FIXED_WIDTH
1581 } gagt_font_hint_t;
1582
1583 /* Magic number used to ensure a pointer points to a page buffer line. */
1584 static const unsigned int GAGT_LINE_MAGIC = 0x5bc14482;
1585
1586 /*
1587 * Definition of a single line buffer. This is a growable string and a
1588 * parallel growable attributes array. The string is buffered without any
1589 * null terminator -- not needed since we retain length.
1590 */
1591 typedef struct {
1592 unsigned char *data; /* Buffered character data. */
1593 unsigned char *attributes; /* Parallel character attributes, packed. */
1594 int allocation; /* Bytes allocated to each of the above. */
1595 int length; /* Amount of data actually buffered. */
1596 } gagt_string_t;
1597 typedef gagt_string_t * gagt_stringref_t;
1598
1599 /*
1600 * Definition of a page buffer entry. This is a structure that holds the
1601 * the result of a single line buffer above, plus additional areas that
1602 * describe line text positioning, a blank line flag, a paragraph pointer
1603 * (NULL if not in a paragraph), and a font hint.
1604 */
1605 typedef struct gagt_line_s *gagt_lineref_t;
1606 typedef struct gagt_paragraph_s *gagt_paragraphref_t;
1607
1608 struct gagt_line_s
1609 {
1610 unsigned int magic; /* Assertion check dog-tag. */
1611
1612 gagt_string_t buffer; /* Buffered line string data. */
1613
1614 int indent; /* Line indentation. */
1615 int outdent; /* Trailing line whitespace. */
1616 int real_length; /* Real line length. */
1617 int is_blank; /* Line blank flag. */
1618 int is_hyphenated; /* Line hyphenated flag. */
1619
1620 gagt_paragraphref_t paragraph; /* Paragraph containing the line. */
1621 gagt_font_hint_t font_hint; /* Line's font hint. */
1622
1623 gagt_lineref_t next; /* List next element. */
1624 gagt_lineref_t prior; /* List prior element. */
1625 };
1626
1627 /*
1628 * Definition of the actual page buffer. This is a doubly-linked list of
1629 * lines, with a tail pointer to facilitate adding entries at the end.
1630 */
1631 static gagt_lineref_t gagt_page_head = NULL,
1632 gagt_page_tail = NULL;
1633
1634 /*
1635 * Definition of the current output line; this one is appended to on
1636 * agt_puts(), and transferred into the page buffer on agt_newline().
1637 */
1638 static gagt_string_t gagt_current_buffer = { NULL, NULL, 0, 0 };
1639
1640 /*
1641 * gagt_string_append()
1642 * gagt_string_transfer()
1643 * gagt_string_free()
1644 *
1645 * String append, move, and allocation free for string_t buffers.
1646 */
1647 static void
1648 gagt_string_append (gagt_stringref_t buffer, const char *string,
1649 unsigned char packed_attributes)
1650 {
1651 int length, bytes;
1652
1653 /*
1654 * Find the size we'll need from the line buffer to add this string,
1655 * and grow buffer if necessary.
1656 */
1657 length = strlen (string);
1658 for (bytes = buffer->allocation; bytes < buffer->length + length; )
1659 bytes = bytes == 0 ? 1 : bytes << 1;
1660
1661 if (bytes > buffer->allocation)
1662 {
1663 buffer->data = gagt_realloc (buffer->data, bytes);
1664 buffer->attributes = gagt_realloc (buffer->attributes, bytes);
1665
1666 buffer->allocation = bytes;
1667 }
1668
1669 /* Add string to the line buffer, and store packed text attributes. */
1670 memcpy (buffer->data + buffer->length, string, length);
1671 memset (buffer->attributes + buffer->length, packed_attributes, length);
1672
1673 buffer->length += length;
1674 }
1675
1676 static void
1677 gagt_string_transfer (gagt_stringref_t from, gagt_stringref_t to)
1678 {
1679 *to = *from;
1680 from->data = from->attributes = NULL;
1681 from->allocation = from->length = 0;
1682 }
1683
1684 static void
1685 gagt_string_free (gagt_stringref_t buffer)
1686 {
1687 free (buffer->data);
1688 free (buffer->attributes);
1689 buffer->data = buffer->attributes = NULL;
1690 buffer->allocation = buffer->length = 0;
1691 }
1692
1693
1694 /*
1695 * gagt_get_string_indent()
1696 * gagt_get_string_outdent()
1697 * gagt_get_string_real_length()
1698 * gagt_is_string_blank()
1699 * gagt_is_string_hyphenated()
1700 *
1701 * Metrics functions for string_t buffers.
1702 */
1703 static int
1704 gagt_get_string_indent (const gagt_stringref_t buffer)
1705 {
1706 int indent, index;
1707
1708 indent = 0;
1709 for (index = 0;
1710 index < buffer->length && isspace (buffer->data[index]);
1711 index++)
1712 indent++;
1713
1714 return indent;
1715 }
1716
1717 static int
1718 gagt_get_string_outdent (const gagt_stringref_t buffer)
1719 {
1720 int outdent, index;
1721
1722 outdent = 0;
1723 for (index = buffer->length - 1;
1724 index >= 0 && isspace (buffer->data[index]); index--)
1725 outdent++;
1726
1727 return outdent;
1728 }
1729
1730
1731 static int
1732 gagt_get_string_real_length (const gagt_stringref_t buffer)
1733 {
1734 int indent, outdent;
1735
1736 indent = gagt_get_string_indent (buffer);
1737 outdent = gagt_get_string_outdent (buffer);
1738
1739 return indent == buffer->length ? 0 : buffer->length - indent - outdent;
1740 }
1741
1742 static int
1743 gagt_is_string_blank (const gagt_stringref_t buffer)
1744 {
1745 return gagt_get_string_indent (buffer) == buffer->length;
1746 }
1747
1748 static int
1749 gagt_is_string_hyphenated (const gagt_stringref_t buffer)
1750 {
1751 int is_hyphenated;
1752
1753 is_hyphenated = FALSE;
1754
1755 if (!gagt_is_string_blank (buffer)
1756 && gagt_get_string_real_length (buffer) > 1)
1757 {
1758 int last;
1759
1760 last = buffer->length - gagt_get_string_outdent (buffer) - 1;
1761
1762 if (buffer->data[last] == '-')
1763 {
1764 if (isalpha (buffer->data[last - 1]))
1765 is_hyphenated = TRUE;
1766 }
1767 }
1768
1769 return is_hyphenated;
1770 }
1771
1772
1773 /*
1774 * gagt_output_delete()
1775 *
1776 * Delete all buffered page and line text. Free all malloc'ed buffer memory,
1777 * and return the buffer variables to their initial values.
1778 */
1779 static void
1780 gagt_output_delete (void)
1781 {
1782 gagt_lineref_t line, next_line;
1783
1784 for (line = gagt_page_head; line; line = next_line)
1785 {
1786 assert (line->magic == GAGT_LINE_MAGIC);
1787 next_line = line->next;
1788
1789 gagt_string_free (&line->buffer);
1790
1791 memset (line, 0, sizeof (*line));
1792 free (line);
1793 }
1794
1795 gagt_page_head = gagt_page_tail = NULL;
1796
1797 gagt_string_free (&gagt_current_buffer);
1798 }
1799
1800
1801 /*
1802 * agt_puts()
1803 *
1804 * Buffer the string passed in into our current single line buffer. The
1805 * function converts to ISO 8859 Latin-1 encoding before buffering.
1806 */
1807 void
1808 agt_puts (const char *cp_string)
1809 {
1810 assert (cp_string);
1811
1812 if (!BATCH_MODE)
1813 {
1814 char *iso_string;
1815 unsigned char packed;
1816 int length;
1817
1818 /* Update the apparent (virtual) window x position. */
1819 length = strlen (cp_string);
1820 curr_x += length;
1821
1822 /*
1823 * Convert the buffer from IBM cp 437 to Glk's ISO 8859 Latin-1, and
1824 * add string and packed text attributes to the current line buffer.
1825 */
1826 iso_string = gagt_malloc (length + 1);
1827 gagt_cp_to_iso ((const unsigned char *)cp_string, (unsigned char *)iso_string);
1828 packed = gagt_pack_current_attributes ();
1829 gagt_string_append (&gagt_current_buffer, iso_string, packed);
1830
1831 /* Add the string to any script file. */
1832 if (script_on)
1833 textputs (scriptfile, iso_string);
1834
1835 free (iso_string);
1836 gagt_debug ("agt_puts", "string='%s'", cp_string);
1837 }
1838 }
1839
1840
1841 /*
1842 * agt_newline()
1843 *
1844 * Accept a newline to the main window. Our job here is to append the
1845 * current line buffer to the page buffer, and clear the line buffer to
1846 * begin accepting new text.
1847 */
1848 void
1849 agt_newline (void)
1850 {
1851 if (!BATCH_MODE)
1852 {
1853 gagt_lineref_t line;
1854
1855 /* Update the apparent (virtual) window x position. */
1856 curr_x = 0;
1857
1858 /* Create a new line entry for the page buffer. */
1859 line = gagt_malloc (sizeof (*line));
1860 line->magic = GAGT_LINE_MAGIC;
1861
1862 /* Move the line from the line buffer into the page buffer. */
1863 gagt_string_transfer (&gagt_current_buffer, &line->buffer);
1864
1865 /* Fill in the line buffer metrics. */
1866 line->indent = gagt_get_string_indent (&line->buffer);
1867 line->outdent = gagt_get_string_outdent (&line->buffer);
1868 line->real_length = gagt_get_string_real_length (&line->buffer);
1869 line->is_blank = gagt_is_string_blank (&line->buffer);
1870 line->is_hyphenated = gagt_is_string_hyphenated (&line->buffer);
1871
1872 /* For now, default the remaining page buffer fields for the line. */
1873 line->paragraph = NULL;
1874 line->font_hint = HINT_NONE;
1875
1876 /* Add to the list, creating a new list if necessary. */
1877 line->next = NULL;
1878 line->prior = gagt_page_tail;
1879 if (gagt_page_head)
1880 gagt_page_tail->next = line;
1881 else
1882 gagt_page_head = line;
1883 gagt_page_tail = line;
1884
1885 /* Add a newline to any script file. */
1886 if (script_on)
1887 textputs (scriptfile, "\n");
1888
1889 gagt_debug ("agt_newline", "");
1890 }
1891 }
1892
1893
1894 /*
1895 * gagt_get_first_page_line()
1896 * gagt_get_next_page_line()
1897 * gagt_get_prior_page_line()
1898 *
1899 * Iterator functions for the page buffer. These functions return the first
1900 * line from the page buffer, the next line, or the previous line, given a
1901 * line, respectively. They return NULL if no lines, or no more lines, are
1902 * available.
1903 */
1904 static gagt_lineref_t
1905 gagt_get_first_page_line (void)
1906 {
1907 gagt_lineref_t line;
1908
1909 line = gagt_page_head;
1910 assert (!line || line->magic == GAGT_LINE_MAGIC);
1911 return line;
1912 }
1913
1914 static gagt_lineref_t
1915 gagt_get_next_page_line (const gagt_lineref_t line)
1916 {
1917 gagt_lineref_t next_line;
1918 assert (line && line->magic == GAGT_LINE_MAGIC);
1919
1920 next_line = line->next;
1921 assert (!next_line || next_line->magic == GAGT_LINE_MAGIC);
1922 return next_line;
1923 }
1924
1925 static gagt_lineref_t
1926 gagt_get_prior_page_line (const gagt_lineref_t line)
1927 {
1928 gagt_lineref_t prior_line;
1929 assert (line && line->magic == GAGT_LINE_MAGIC);
1930
1931 prior_line = line->prior;
1932 assert (!prior_line || prior_line->magic == GAGT_LINE_MAGIC);
1933 return prior_line;
1934 }
1935
1936
1937 /*---------------------------------------------------------------------*/
1938 /* Glk port paragraphing functions and data */
1939 /*---------------------------------------------------------------------*/
1940
1941 /* Magic number used to ensure a pointer points to a paragraph. */
1942 static const unsigned int GAGT_PARAGRAPH_MAGIC = 0xb9a2297b;
1943
1944 /* Forward definition of special paragraph reference. */
1945 typedef const struct gagt_special_s *gagt_specialref_t;
1946
1947 /*
1948 * Definition of a paragraph entry. This is a structure that holds a
1949 * pointer to the first line buffer in the paragraph.
1950 */
1951 struct gagt_paragraph_s
1952 {
1953 unsigned int magic; /* Assertion check dog-tag. */
1954
1955 gagt_lineref_t first_line; /* First line in the paragraph. */
1956 gagt_specialref_t special; /* Special paragraph entry. */
1957
1958 int line_count; /* Number of lines in the paragraph. */
1959 int id; /* Paragraph id, sequence, for debug only. */
1960
1961 gagt_paragraphref_t next; /* List next element. */
1962 gagt_paragraphref_t prior; /* List prior element. */
1963 };
1964
1965 /*
1966 * A doubly-linked list of paragraphs, with a tail pointer to facilitate
1967 * adding entries at the end.
1968 */
1969 static gagt_paragraphref_t gagt_paragraphs_head = NULL,
1970 gagt_paragraphs_tail = NULL;
1971
1972 /*
1973 * gagt_paragraphs_delete()
1974 *
1975 * Delete paragraphs held in the list. This function doesn't delete the
1976 * page buffer lines, just the paragraphs describing the page.
1977 */
1978 static void
1979 gagt_paragraphs_delete (void)
1980 {
1981 gagt_paragraphref_t paragraph, next_paragraph;
1982
1983 for (paragraph = gagt_paragraphs_head; paragraph; paragraph = next_paragraph)
1984 {
1985 assert (paragraph->magic == GAGT_PARAGRAPH_MAGIC);
1986 next_paragraph = paragraph->next;
1987
1988 memset (paragraph, 0, sizeof (*paragraph));
1989 free (paragraph);
1990 }
1991
1992 gagt_paragraphs_head = gagt_paragraphs_tail = NULL;
1993 }
1994
1995
1996 /*
1997 * gagt_find_paragraph_start()
1998 *
1999 * Find and return the next non-blank line in the page buffer, given a start
2000 * point. Returns NULL if there are no more blank lines.
2001 */
2002 static gagt_lineref_t
2003 gagt_find_paragraph_start (const gagt_lineref_t begin)
2004 {
2005 gagt_lineref_t line, match;
2006
2007 /*
2008 * Advance line to the beginning of the next paragraph, stopping on the
2009 * first non-blank line, or at the end of the page buffer.
2010 */
2011 match = NULL;
2012 for (line = begin; line; line = gagt_get_next_page_line (line))
2013 {
2014 if (!line->is_blank)
2015 {
2016 match = line;
2017 break;
2018 }
2019 }
2020
2021 return match;
2022 }
2023
2024
2025 /*
2026 * gagt_find_block_end()
2027 * gagt_find_blank_line_block_end()
2028 *
2029 * Find and return the apparent end of a paragraph from the page buffer,
2030 * given a start point, and an indentation reference. The end is either
2031 * the point where indentation returns to the reference indentation, or
2032 * the next blank line.
2033 *
2034 * Indentation reference can be -1, indicating that only the next blank
2035 * line will end the paragraph. Indentation references less than 1 are
2036 * also ignored.
2037 */
2038 static gagt_lineref_t
2039 gagt_find_block_end (const gagt_lineref_t begin, int indent)
2040 {
2041 gagt_lineref_t line, match;
2042
2043 /*
2044 * Initialize the match to be the start of the block, then advance line
2045 * until we hit a blank line or the end of the page buffer. At this point,
2046 * match contains the last line checked.
2047 */
2048 match = begin;
2049 for (line = begin; line; line = gagt_get_next_page_line (line))
2050 {
2051 /*
2052 * Found if we reach a blank line, or when given an indentation to
2053 * check for, we find it.
2054 */
2055 if (line->is_blank || (indent > 0 && line->indent == indent))
2056 break;
2057
2058 match = line;
2059 }
2060
2061 return match;
2062 }
2063
2064 static gagt_lineref_t
2065 gagt_find_blank_line_block_end (const gagt_lineref_t begin)
2066 {
2067 return gagt_find_block_end (begin, -1);
2068 }
2069
2070
2071 /*
2072 * gagt_find_paragraph_end()
2073 *
2074 * Find and return the apparent end of a paragraph from the page buffer,
2075 * given a start point. The function attempts to recognize paragraphs by
2076 * the "shape" of indentation.
2077 */
2078 static gagt_lineref_t
2079 gagt_find_paragraph_end (const gagt_lineref_t first_line)
2080 {
2081 gagt_lineref_t second_line;
2082
2083 /*
2084 * If the start line is the last line in the buffer, or if the next line
2085 * is a blank line, return the start line as also being the end of the
2086 * paragraph.
2087 */
2088 second_line = gagt_get_next_page_line (first_line);
2089 if (!second_line || second_line->is_blank)
2090 {
2091 return first_line;
2092 }
2093
2094 /*
2095 * Time to look at line indentations...
2096 *
2097 * If either line is grossly indented, forget about trying to infer
2098 * anything from this, and just break the paragraph on the next blank line.
2099 */
2100 if (first_line->indent > screen_width / 4
2101 || second_line->indent > screen_width / 4)
2102 {
2103 return gagt_find_blank_line_block_end (second_line);
2104 }
2105
2106 /*
2107 * If the first line is indented more than the second, end the paragraph
2108 * on a blank line, or on a return in indentation to the level of the
2109 * first line. Here we're looking for paragraphs with the shape
2110 *
2111 * aksjdj jfkasjd fjkasjd ajksdj fkaj djf akjsd fkjas dfs
2112 * kasjdlkfjkj fj aksd jfjkasj dlkfja skjdk flaks dlf jalksdf
2113 * ksjdf kjs kdf lasjd fkjalks jdfkjasjd flkjasl djfkasjfdkl
2114 */
2115 else if (first_line->indent > second_line->indent)
2116 {
2117 return gagt_find_block_end (second_line, first_line->indent);
2118 }
2119
2120 /*
2121 * If the second line is more indented than the first, this may indicate
2122 * a title line, followed by normal indented paragraphing. In this case,
2123 * use the second line indentation as the reference, and begin searching
2124 * at the next line. This finds
2125 *
2126 * ksjdkfjask ksadf
2127 * kajskd fksjkfj jfkj jfkslaj fksjlfj jkjskjlfa j fjksal
2128 * sjkkdjf sj fkjkajkdlfj lsjak dfjk djkfjskl dklf alks dfll
2129 * fjksja jkj dksja kjdk kaj dskfj aksjdf aksjd kfjaks fjks
2130 *
2131 * and
2132 *
2133 * asdfj kjsdf kjs
2134 * akjsdkj fkjs kdjfa lskjdl fjalsj dlfjksj kdj fjkd jlsjd
2135 * jalksj jfk slj lkfjsa lkjd lfjlaks dlfkjals djkj alsjd
2136 * kj jfksj fjksjl alkjs dlkjf lakjsd fkjas ldkj flkja fsd
2137 */
2138 else if (second_line->indent > first_line->indent)
2139 {
2140 gagt_lineref_t third_line;
2141
2142 /*
2143 * See if we have a third buffer line to look at. If we don't, or if
2144 * we do but it's blank, the paragraph ends here.
2145 */
2146 third_line = gagt_get_next_page_line (second_line);
2147 if (!third_line || third_line->is_blank)
2148 {
2149 return second_line;
2150 }
2151
2152 /* As above, give up on gross indentation. */
2153 if (second_line->indent > screen_width / 4
2154 || third_line->indent > screen_width / 4)
2155 {
2156 return gagt_find_blank_line_block_end (third_line);
2157 }
2158
2159 /*
2160 * If the second line indentation exceeds the third, this is probably
2161 * a paragraph with a title line. In this case, end the paragraph on
2162 * a return to the indentation of the second line. If not, just find
2163 * the next blank line.
2164 */
2165 else if (second_line->indent > third_line->indent)
2166 {
2167 return gagt_find_block_end (third_line, second_line->indent);
2168 }
2169 else
2170 {
2171 return gagt_find_blank_line_block_end (third_line);
2172 }
2173 }
2174
2175 /*
2176 * Otherwise, the first and second line indentations are the same, so
2177 * break only on the next empty line. This finds the simple
2178 *
2179 * ksd kjal jdljf lakjsd lkj lakjsdl jfla jsldj lfaksdj fksj
2180 * lskjd fja kjsdlk fjlakjs ldkjfksj lkjdf kjalskjd fkjklal
2181 * skjd fkaj djfkjs dkfjal sjdlkfj alksjdf lkajs ldkjf alljjf
2182 */
2183 else
2184 {
2185 assert (second_line->indent == first_line->indent);
2186 return gagt_find_blank_line_block_end (second_line);
2187 }
2188 }
2189
2190
2191 /*
2192 * gagt_paragraph_page()
2193 *
2194 * This function breaks the page buffer into what appear to be paragraphs,
2195 * based on observations of indentation and blank separator lines.
2196 */
2197 static void
2198 gagt_paragraph_page (void)
2199 {
2200 gagt_lineref_t start;
2201
2202 assert (!gagt_paragraphs_head && !gagt_paragraphs_tail);
2203
2204 /* Find the start of the first paragraph. */
2205 start = gagt_find_paragraph_start (gagt_get_first_page_line ());
2206 while (start)
2207 {
2208 gagt_paragraphref_t paragraph;
2209 gagt_lineref_t end, line;
2210
2211 /* Create a new paragraph entry. */
2212 paragraph = gagt_malloc (sizeof (*paragraph));
2213 paragraph->magic = GAGT_PARAGRAPH_MAGIC;
2214 paragraph->first_line = start;
2215 paragraph->special = NULL;
2216 paragraph->line_count = 1;
2217 paragraph->id = gagt_paragraphs_tail ? gagt_paragraphs_tail->id + 1 : 0;
2218
2219 /* Add to the list, creating a new list if necessary. */
2220 paragraph->next = NULL;
2221 paragraph->prior = gagt_paragraphs_tail;
2222 if (gagt_paragraphs_head)
2223 gagt_paragraphs_tail->next = paragraph;
2224 else
2225 gagt_paragraphs_head = paragraph;
2226 gagt_paragraphs_tail = paragraph;
2227
2228 /* From the start, identify the paragraph end. */
2229 end = gagt_find_paragraph_end (start);
2230
2231 /*
2232 * Set paragraph in each line identified as part of this paragraph,
2233 * and increment the paragraph's line count.
2234 */
2235 for (line = start;
2236 line != end; line = gagt_get_next_page_line (line))
2237 {
2238 line->paragraph = paragraph;
2239 paragraph->line_count++;
2240 }
2241 end->paragraph = paragraph;
2242
2243 /*
2244 * If there's another line, look for the next paragraph there,
2245 * otherwise we're done.
2246 */
2247 line = gagt_get_next_page_line (end);
2248 if (line)
2249 start = gagt_find_paragraph_start (line);
2250 else
2251 start = NULL;
2252 }
2253 }
2254
2255
2256 /*
2257 * gagt_get_first_paragraph()
2258 * gagt_get_next_paragraph()
2259 *
2260 * Iterator functions for the paragraphs list.
2261 */
2262 static gagt_paragraphref_t
2263 gagt_get_first_paragraph (void)
2264 {
2265 gagt_paragraphref_t paragraph;
2266
2267 paragraph = gagt_paragraphs_head;
2268 assert (!paragraph || paragraph->magic == GAGT_PARAGRAPH_MAGIC);
2269 return paragraph;
2270 }
2271
2272 static gagt_paragraphref_t
2273 gagt_get_next_paragraph (const gagt_paragraphref_t paragraph)
2274 {
2275 gagt_paragraphref_t next_paragraph;
2276 assert (paragraph && paragraph->magic == GAGT_PARAGRAPH_MAGIC);
2277
2278 next_paragraph = paragraph->next;
2279 assert (!next_paragraph || next_paragraph->magic == GAGT_PARAGRAPH_MAGIC);
2280 return next_paragraph;
2281 }
2282
2283
2284 /*
2285 * gagt_get_first_paragraph_line()
2286 * gagt_get_next_paragraph_line()
2287 * gagt_get_prior_paragraph_line()
2288 *
2289 * Iterator functions for the page buffer. These functions implement a
2290 * paragraph-based view of the page buffer.
2291 *
2292 * The functions find the first line of a given paragraph; given a line,
2293 * the next line in the same paragraph, or NULL if line is the last para-
2294 * graph line (or the last line in the page buffer); and given a line,
2295 * the previous line in the same paragraph, or NULL if line is the first
2296 * paragraph line (or the first line in the page buffer).
2297 */
2298 static gagt_lineref_t
2299 gagt_get_first_paragraph_line (const gagt_paragraphref_t paragraph)
2300 {
2301 assert (paragraph && paragraph->magic == GAGT_PARAGRAPH_MAGIC);
2302
2303 /* Return the first line for the requested paragraph. */
2304 return paragraph->first_line;
2305 }
2306
2307 static gagt_lineref_t
2308 gagt_get_next_paragraph_line (const gagt_lineref_t line)
2309 {
2310 gagt_lineref_t next_line;
2311
2312 /* Get the next line; return it if the paragraph matches, else NULL. */
2313 next_line = gagt_get_next_page_line (line);
2314 if (next_line && next_line->paragraph == line->paragraph)
2315 return next_line;
2316 else
2317 return NULL;
2318 }
2319
2320 static gagt_lineref_t
2321 gagt_get_prior_paragraph_line (const gagt_lineref_t line)
2322 {
2323 gagt_lineref_t prior_line;
2324
2325 /* Get the previous line; return it if the paragraph matches, else NULL. */
2326 prior_line = gagt_get_prior_page_line (line);
2327 if (prior_line && prior_line->paragraph == line->paragraph)
2328 return prior_line;
2329 else
2330 return NULL;
2331 }
2332
2333
2334 /*
2335 * gagt_get_paragraph_line_count()
2336 *
2337 * Return the count of lines contained in the paragraph.
2338 */
2339 static int
2340 gagt_get_paragraph_line_count (const gagt_paragraphref_t paragraph)
2341 {
2342 assert (paragraph && paragraph->magic == GAGT_PARAGRAPH_MAGIC);
2343
2344 return paragraph->line_count;
2345 }
2346
2347
2348 /*---------------------------------------------------------------------*/
2349 /* Glk port page buffer analysis functions */
2350 /*---------------------------------------------------------------------*/
2351
2352 /*
2353 * Threshold for consecutive punctuation/spaces before we decide that a line
2354 * is in fact part of a table, and a small selection of characters to apply
2355 * a somewhat larger threshold to when looking for punctuation (typically,
2356 * characters that appear together multiple times in non-table text).
2357 */
2358 static const int GAGT_THRESHOLD = 4,
2359 GAGT_COMMON_THRESHOLD = 8;
2360 static const char * const GAGT_COMMON_PUNCTUATION = ".!?";
2361
2362
2363 /*
2364 * gagt_line_is_standout()
2365 *
2366 * Return TRUE if a page buffer line appears to contain "standout" text.
2367 * This is one of:
2368 * - a line where all characters have some form of AGT text attribute
2369 * set (blinking, fixed width font, or emphasis),
2370 * - a line where each alphabetical character is uppercase.
2371 * Typically, this describes room and other miscellaneous header lines.
2372 */
2373 static int
2374 gagt_line_is_standout (const gagt_lineref_t line)
2375 {
2376 int index, all_formatted, upper_count, lower_count;
2377
2378 /*
2379 * Look at the line, for cases where all characters in it have AGT font
2380 * attributes, and counting the upper and lower case characters. Iterate
2381 * over only the significant characters in the string.
2382 */
2383 all_formatted = TRUE;
2384 upper_count = lower_count = 0;
2385 for (index = line->indent;
2386 index < line->buffer.length - line->outdent; index++)
2387 {
2388 gagt_attrset_t attribute_set;
2389 unsigned char character;
2390
2391 gagt_unpack_attributes (line->buffer.attributes[index], &attribute_set);
2392 character = line->buffer.data[index];
2393
2394 /*
2395 * If no AGT attribute is set for this character, then not all of the
2396 * line is standout text. In this case, reset the all_formatted flag.
2397 */
2398 if (!(attribute_set.blink
2399 || attribute_set.fixed || attribute_set.emphasis))
2400 all_formatted = FALSE;
2401
2402 /* Count upper and lower case characters. */
2403 if (islower (character))
2404 lower_count++;
2405 else if (isupper (character))
2406 upper_count++;
2407 }
2408
2409 /*
2410 * Consider standout if every character was formatted, or if the string
2411 * is all uppercase.
2412 */
2413 return all_formatted || (upper_count > 0 && lower_count == 0);
2414 }
2415
2416
2417 /*
2418 * gagt_set_font_hint_proportional()
2419 * gagt_set_font_hint_proportional_newline()
2420 * gagt_set_font_hint_fixed_width()
2421 *
2422 * Helpers for assigning font hints. Font hints have strengths, and these
2423 * functions ensure that gagt_assign_paragraph_font_hints() only increases
2424 * strengths, and doesn't need to worry about checking before setting. In
2425 * the case of newline, the function also adds standout to the font hint if
2426 * appropriate.
2427 */
2428 static void
2429 gagt_set_font_hint_proportional (gagt_lineref_t line)
2430 {
2431 /* The only weaker hint than proportional is none. */
2432 if (line->font_hint == HINT_NONE)
2433 line->font_hint = HINT_PROPORTIONAL;
2434 }
2435
2436 static void
2437 gagt_set_font_hint_proportional_newline (gagt_lineref_t line)
2438 {
2439 /*
2440 * Proportional and none are weaker than newline. Because of the way we
2441 * set font hints, this function can't be called with a current line hint
2442 * of proportional newline.
2443 */
2444 if (line->font_hint == HINT_NONE || line->font_hint == HINT_PROPORTIONAL)
2445 {
2446 if (gagt_line_is_standout (line))
2447 line->font_hint = HINT_PROPORTIONAL_NEWLINE_STANDOUT;
2448 else
2449 line->font_hint = HINT_PROPORTIONAL_NEWLINE;
2450 }
2451 }
2452
2453 static void
2454 gagt_set_font_hint_fixed_width (gagt_lineref_t line)
2455 {
2456 /* Fixed width font is the strongest hint. */
2457 if (line->font_hint == HINT_NONE
2458 || line->font_hint == HINT_PROPORTIONAL
2459 || line->font_hint == HINT_PROPORTIONAL_NEWLINE
2460 || line->font_hint == HINT_PROPORTIONAL_NEWLINE_STANDOUT)
2461 line->font_hint = HINT_FIXED_WIDTH;
2462 }
2463
2464
2465 /*
2466 * gagt_assign_paragraph_font_hints()
2467 *
2468 * For a given paragraph in the page buffer, this function looks at the text
2469 * style used, and assigns a font hint value to each line. Font hints
2470 * indicate whether the line probably requires fixed width font, or may be
2471 * okay in variable width, and for lines that look like they might be okay
2472 * in variable width, whether the newline should probably be rendered at the
2473 * end of the line, or if it might be omitted.
2474 */
2475 static void
2476 gagt_assign_paragraph_font_hints (const gagt_paragraphref_t paragraph)
2477 {
2478 static int is_initialized = FALSE;
2479 static int threshold[UCHAR_MAX + 1];
2480
2481 gagt_lineref_t line, first_line;
2482 int is_table, in_list;
2483 assert (paragraph);
2484
2485 /* On first call, set up the table on punctuation run thresholds. */
2486 if (!is_initialized)
2487 {
2488 int character;
2489
2490 for (character = 0; character <= UCHAR_MAX; character++)
2491 {
2492 /*
2493 * Set the threshold, either a normal value, or a larger one for
2494 * punctuation characters that tend to have consecutive runs in
2495 * non-table text.
2496 */
2497 if (ispunct (character))
2498 {
2499 threshold[character] = strchr (GAGT_COMMON_PUNCTUATION, character)
2500 ? GAGT_COMMON_THRESHOLD : GAGT_THRESHOLD;
2501 }
2502 }
2503
2504 is_initialized = TRUE;
2505 }
2506
2507 /*
2508 * Note the first paragraph line. This value is commonly used, and under
2509 * certain circumstances, it's also modified later on.
2510 */
2511 first_line = gagt_get_first_paragraph_line (paragraph);
2512 assert (first_line);
2513
2514 /*
2515 * Phase 1 -- look for pages that consist of just one paragraph,
2516 * itself consisting of only one line.
2517 *
2518 * There is no point in attempting alignment of text in a one paragraph,
2519 * one line page. This would be, for example, an error message from the
2520 * interpreter parser. In this case, set the line for proportional with
2521 * newline, and return immediately.
2522 */
2523 if (gagt_get_first_paragraph () == paragraph
2524 && !gagt_get_next_paragraph (paragraph)
2525 && !gagt_get_next_paragraph_line (first_line))
2526 {
2527 /*
2528 * Set the first paragraph line for proportional with a newline, and
2529 * return.
2530 */
2531 gagt_set_font_hint_proportional_newline (first_line);
2532 return;
2533 }
2534
2535 /*
2536 * Phase 2 -- try to identify paragraphs that are tables, based on
2537 * looking for runs of punctuation.
2538 *
2539 * Search for any string that has a run of apparent line drawing or other
2540 * formatting characters in it. If we find one, we'll consider the
2541 * paragraph to be a "table", that is, it has some quality that we might
2542 * destroy if we used a proportional font.
2543 */
2544 is_table = FALSE;
2545 for (line = first_line;
2546 line && !is_table; line = gagt_get_next_paragraph_line (line))
2547 {
2548 int index, counts[UCHAR_MAX + 1], total_counts;
2549
2550 /*
2551 * Clear the initial counts. Using memset() here is an order of
2552 * magnitude or two faster than a for-loop. Also there's a total count
2553 * to detect when counts needs to be recleared, or is already clear.
2554 */
2555 memset (counts, 0, sizeof (counts));
2556 total_counts = 0;
2557
2558 /*
2559 * Count consecutive punctuation in the line, excluding the indentation
2560 * and outdent.
2561 */
2562 for (index = line->indent;
2563 index < line->buffer.length - line->outdent && !is_table; index++)
2564 {
2565 int character;
2566 character = line->buffer.data[index];
2567
2568 /* Test this character for punctuation. */
2569 if (ispunct (character))
2570 {
2571 /*
2572 * Increment the count for this character, and note that
2573 * counts are no longer empty, then compare against threshold.
2574 */
2575 counts[character]++;
2576 total_counts++;
2577
2578 is_table = (counts[character] >= threshold[character]);
2579 }
2580 else
2581 {
2582 /*
2583 * Re-clear all counts, again with memset() for speed, but only
2584 * if they need clearing. As they often won't, this optimization
2585 * saves quite a bit of work.
2586 */
2587 if (total_counts > 0)
2588 {
2589 memset (counts, 0, sizeof (counts));
2590 total_counts = 0;
2591 }
2592 }
2593 }
2594 }
2595
2596 /*
2597 * Phase 3 -- try again to identify paragraphs that are tables, based
2598 * this time on looking for runs of whitespace.
2599 *
2600 * If no evidence found so far, look again, this time searching for any
2601 * run of four or more spaces on the line (excluding any lead-in or
2602 * trailing spaces).
2603 */
2604 if (!is_table)
2605 {
2606 for (line = first_line;
2607 line && !is_table; line = gagt_get_next_paragraph_line (line))
2608 {
2609 int index, count;
2610
2611 /*
2612 * Count consecutive spaces in the line, excluding the indentation
2613 * and outdent.
2614 */
2615 count = 0;
2616 for (index = line->indent;
2617 index < line->buffer.length - line->outdent && !is_table;
2618 index++)
2619 {
2620 int character;
2621 character = line->buffer.data[index];
2622
2623 if (isspace (character))
2624 {
2625 count++;
2626 is_table = (count >= GAGT_THRESHOLD);
2627 }
2628 else
2629 count = 0;
2630 }
2631 }
2632 }
2633
2634 /*
2635 * If the paragraph appears to be a table, and if it consists of more than
2636 * just a single line, mark all lines as fixed font output and return.
2637 */
2638 if (is_table && gagt_get_next_paragraph_line (first_line))
2639 {
2640 for (line = first_line;
2641 line; line = gagt_get_next_paragraph_line (line))
2642 {
2643 gagt_set_font_hint_fixed_width (line);
2644 }
2645
2646 /* Nothing more to do. */
2647 return;
2648 }
2649
2650 /*
2651 * Phase 4 -- consider separating the first line from the rest of
2652 * the paragraph.
2653 *
2654 * Not a table, so the choice is between proportional rendering with a
2655 * newline, and proportional rendering without...
2656 *
2657 * If the first paragraph line is standout or short, render it pro-
2658 * portionally with a newline, and don't consider it as a further part of
2659 * the paragraph.
2660 */
2661 if (gagt_line_is_standout (first_line)
2662 || first_line->real_length < screen_width / 2)
2663 {
2664 /* Set the first paragraph line for a newline. */
2665 gagt_set_font_hint_proportional_newline (first_line);
2666
2667 /*
2668 * Disassociate this line from the rest of the paragraph by moving on
2669 * the value of the first_line variable. If it turns out that there
2670 * is no next paragraph line, then we have a one-line paragraph, and
2671 * there's no more to do.
2672 */
2673 first_line = gagt_get_next_paragraph_line (first_line);
2674 if (!first_line)
2675 return;
2676 }
2677
2678 /*
2679 * Phase 5 -- try to identify lists by a simple initial look at line
2680 * indentations.
2681 *
2682 * Look through the paragraph for apparent lists, and decide for each
2683 * line whether it's appropriate to output a newline, and render
2684 * proportionally, or just render proportionally.
2685 *
2686 * After this loop, each line will have some form of font hint assigned
2687 * to it.
2688 */
2689 in_list = FALSE;
2690 for (line = first_line;
2691 line; line = gagt_get_next_paragraph_line (line))
2692 {
2693 gagt_lineref_t next_line;
2694
2695 next_line = gagt_get_next_paragraph_line (line);
2696
2697 /*
2698 * Special last-iteration processing. The newline is always output at
2699 * the end of a paragraph, so if there isn't a next line, then this
2700 * line is the last paragraph line. Set its font hint appropriately,
2701 * and do no more for the line.
2702 */
2703 if (!next_line)
2704 {
2705 gagt_set_font_hint_proportional_newline (line);
2706 continue;
2707 }
2708
2709 /*
2710 * If the next line's indentation is deeper that that of the first
2711 * line, this paragraph looks like it is trying to be some form of a
2712 * list. In this case, make newline significant for the current line,
2713 * and set the in_list flag so we can delay the return to proportional
2714 * by one line. On return to first line indentation, make newline
2715 * significant for the return line.
2716 */
2717 if (next_line->indent > first_line->indent)
2718 {
2719 gagt_set_font_hint_proportional_newline (line);
2720 in_list = TRUE;
2721 }
2722 else
2723 {
2724 if (in_list)
2725 gagt_set_font_hint_proportional_newline (line);
2726 else
2727 gagt_set_font_hint_proportional (line);
2728 in_list = FALSE;
2729 }
2730 }
2731
2732 /*
2733 * Phase 6 -- look again for lines that look like they are supposed
2734 * to stand out from their neighbors.
2735 *
2736 * Now rescan the paragraph, looking this time for lines that stand out
2737 * from their neighbours. Make newline significant for each such line,
2738 * and the line above, if there is one.
2739 *
2740 * Here we split the loop on lines so that we avoid looking at the prior
2741 * line of the current first line -- because of "adjustments", it may not
2742 * be the real paragraph first line.
2743 *
2744 * So, deal with the current first line...
2745 */
2746 if (gagt_line_is_standout (first_line))
2747 {
2748 /* Make newline significant for this line. */
2749 gagt_set_font_hint_proportional_newline (first_line);
2750 }
2751
2752 /* ... then deal with the rest of the lines, looking for standouts. */
2753 for (line = gagt_get_next_paragraph_line (first_line);
2754 line; line = gagt_get_next_paragraph_line (line))
2755 {
2756 if (gagt_line_is_standout (line))
2757 {
2758 gagt_lineref_t prior_line;
2759
2760 /* Make newline significant for this line. */
2761 gagt_set_font_hint_proportional_newline (line);
2762
2763 /*
2764 * Make newline significant for the line above. There will always
2765 * be one because we start the loop past the first line.
2766 */
2767 prior_line = gagt_get_prior_paragraph_line (line);
2768 gagt_set_font_hint_proportional_newline (prior_line);
2769 }
2770 }
2771
2772 /*
2773 * Phase 7 -- special case short lines at the paragraph start.
2774 *
2775 * Make a special case of lines that begin a paragraph, and are short and
2776 * followed by a much longer line. This should catch games which output
2777 * room titles above descriptions without using AGT fonts/bold/whatever.
2778 * Without this trap, room titles and their descriptions are run together.
2779 * This is more programmatic guesswork than heuristics.
2780 */
2781 if (gagt_get_next_paragraph_line (first_line))
2782 {
2783 gagt_lineref_t next_line;
2784
2785 next_line = gagt_get_next_paragraph_line (first_line);
2786
2787 /*
2788 * See if the first line is less than half width, and the second line
2789 * is more than three quarters width. If it is, set newline as
2790 * significant for the first paragraph line.
2791 */
2792 if (first_line->real_length < screen_width / 2
2793 && next_line->real_length > screen_width * 3 / 4)
2794 {
2795 gagt_set_font_hint_proportional_newline (first_line);
2796 }
2797 }
2798
2799 /*
2800 * Phase 8 -- special case paragraphs of only short lines.
2801 *
2802 * Make a special case out of paragraphs where all lines are short. This
2803 * catches elements like indented addresses.
2804 */
2805 if (gagt_get_next_paragraph_line (first_line))
2806 {
2807 int all_short;
2808
2809 all_short = TRUE;
2810 for (line = first_line;
2811 line; line = gagt_get_next_paragraph_line (line))
2812 {
2813 /* Clear flag if this line isn't 'short'. */
2814 if (line->real_length >= screen_width / 2)
2815 {
2816 all_short = FALSE;
2817 break;
2818 }
2819 }
2820
2821 /*
2822 * If all lines were short, mark the complete paragraph as having
2823 * significant newlines.
2824 */
2825 if (all_short)
2826 {
2827 for (line = first_line;
2828 line; line = gagt_get_next_paragraph_line (line))
2829 {
2830 gagt_set_font_hint_proportional_newline (line);
2831 }
2832 }
2833 }
2834 }
2835
2836
2837 /*
2838 * gagt_assign_font_hints()
2839 *
2840 *
2841 * Sets a font hint for each line of each page buffer paragraph that is not
2842 * a special paragraph.
2843 */
2844 static void
2845 gagt_assign_font_hints (void)
2846 {
2847 gagt_paragraphref_t paragraph;
2848
2849 for (paragraph = gagt_get_first_paragraph ();
2850 paragraph; paragraph = gagt_get_next_paragraph (paragraph))
2851 {
2852 if (!paragraph->special)
2853 gagt_assign_paragraph_font_hints (paragraph);
2854 }
2855 }
2856
2857
2858 /*---------------------------------------------------------------------*/
2859 /* Glk port special paragraph functions and data */
2860 /*---------------------------------------------------------------------*/
2861
2862 /*
2863 * It's helpful to handle some AGiliTy interpreter output specially, to im-
2864 * prove the look of the text where Glk fonts and styles are available. We
2865 * build a table of paragraphs the interpreter can come out with, and the
2866 * replacement text we'll use when we see this paragraph. Note that matches
2867 * are made after factoring out indentation, and replacement lines do not
2868 * automatically print with a newline. All clear, then? Here's the table
2869 * entry definition.
2870 */
2871 enum { GAGT_SPECIAL_MATCH_MAX = 5 };
2872
2873 typedef const struct gagt_special_s
2874 {
2875 const int line_count;
2876 const char * const compare[GAGT_SPECIAL_MATCH_MAX + 1];
2877 const char * const replace;
2878 } gagt_special_t;
2879
2880 /*
2881 * Table of special AGiliTy interpreter strings and paragraphs -- where one
2882 * appears in game output, we'll print out its replacement instead. Be
2883 * warned; these strings are VERY specific to AGiliTy 1.1.1, and are extre-
2884 * mely likely to change with any future interpreter releases. They also
2885 * omit initializers with abandon, expecting the compiler to default these
2886 * to NULL/zero. Replacement strings embed style encoding as |x, where x is
2887 * E(mphasized), S(ubheader), or N(ormal) for convenience.
2888 */
2889 static gagt_special_t GAGT_SPECIALS[] = {
2890
2891 /* Initial screen AGT game type line. */
2892 {1,
2893 {"[Created with Malmberg and Welch's Adventure Game Toolkit]"},
2894 "|ECreated with Malmberg and Welch's Adventure Game Toolkit|N\n"},
2895
2896 /* Normal version of initial interpreter information block. */
2897 {4,
2898 {"This game is being executed by",
2899 "AGiliTy: The (Mostly) Universal AGT Interpreter version 1.1.2",
2900 "Copyright (C) 1996-99,2001 by Robert Masenten",
2901 "Glk version"},
2902 "This game is being executed by:\n\n"
2903 " |SAGiliTy, The (Mostly) Universal AGT Interpreter, Version 1.1.2|N\n"
2904 " |ECopyright (C) 1996-1999,2001 by Robert Masenten|N\n"
2905 " |EGlk version|N\n"},
2906
2907 /* AGiliTy "information" screen header block. */
2908 {5,
2909 {"AGiliTy",
2910 "The (Mostly) Universal AGT Interpreter, version 1.1.2",
2911 "Copyright (C) 1996-1999,2001 by Robert Masenten",
2912 "[Glk version]",
2913 "-----------------------------------------------------------"},
2914 "|SAGiliTy, The (Mostly) Universal AGT Interpreter, Version 1.1.2|N\n"
2915 "|ECopyright (C) 1996-1999,2001 by Robert Masenten|N\n"
2916 "|EGlk version|N\n"},
2917
2918 /* "HIT ANY KEY" message, usually displayed after a game's introduction. */
2919 {1,
2920 {"--- HIT ANY KEY ---"},
2921 "|E[Press any key...]|N"},
2922
2923 /* Alternative, shrunken version of initial interpreter information block. */
2924 {2,
2925 {"Being run by AGiliTy version 1.1.2, Copyright (C) 1996-99,2001"
2926 " Robert Masenten",
2927 "Glk version"},
2928 "This game is being executed by:\n\n"
2929 " |SAGiliTy, The (Mostly) Universal AGT Interpreter, Version 1.1.2|N\n"
2930 " |ECopyright (C) 1996-1999,2001 by Robert Masenten|N\n"
2931 " |EGlk version|N\n"},
2932
2933 /* Alternative, minimal version of initial interpreter information block. */
2934 {1,
2935 {"Being run by AGiliTy version 1.1.2, Copyright (C) 1996-99,2001"
2936 " Robert Masenten"},
2937 "This game is being executed by:\n\n"
2938 " |SAGiliTy, The (Mostly) Universal AGT Interpreter, Version 1.1.2|N\n"
2939 " |ECopyright (C) 1996-1999,2001 by Robert Masenten|N\n"
2940 " |EGlk version|N\n"},
2941
2942 /* Lengthy version of the "Created with..." message. */
2943 {2,
2944 {"This game was created with Malmberg and Welch's Adventure Game Toolkit;"
2945 " it is",
2946 "being executed by"},
2947 "|ECreated with Malmberg and Welch's Adventure Game Toolkit|N\n"},
2948
2949 /* Three-line version of initial interpreter information block. */
2950 {3,
2951 {"AGiliTy: The (Mostly) Universal AGT Interpreter version 1.1.2",
2952 "Copyright (C) 1996-99,2001 by Robert Masenten",
2953 "Glk version"},
2954 "This game is being executed by:\n\n"
2955 " |SAGiliTy, The (Mostly) Universal AGT Interpreter, Version 1.1.2|N\n"
2956 " |ECopyright (C) 1996-1999,2001 by Robert Masenten|N\n"
2957 " |EGlk version|N\n"},
2958
2959 /*
2960 * Assorted special verb output messages, with the extra icky quality that
2961 * we have to spot messages that wrap because we forced screen_width to 80.
2962 */
2963 {2,
2964 {"[Now in BRIEF mode (room descriptions will only be printed"
2965 " when they are entered",
2966 "the first time)]"},
2967 "|E[Now in BRIEF mode: Room descriptions will only be printed"
2968 " when rooms are entered for the first time.]|N\n"},
2969
2970 {2,
2971 {"[Now in VERBOSE mode (room descriptions will be printed"
2972 " every time you enter a",
2973 "room)]"},
2974 "|E[Now in VERBOSE mode: Room descriptions will be printed"
2975 " every time you enter a room.]|N\n"},
2976
2977 {1,
2978 {"[LISTEXIT mode on: room exits will be listed.]"},
2979 "|E[LISTEXIT mode on: Room exits will be listed.]|N\n"},
2980
2981 {1,
2982 {"[LISTEXIT mode off: room exits will not be listed.]"},
2983 "|E[LISTEXIT mode off: Room exits will not be listed.]|N\n"},
2984
2985 /* End of table sentinel entry. Do not delete. */
2986 {0, {NULL}, NULL}
2987 };
2988
2989
2990 /*
2991 * gagt_compare_special_line()
2992 * gagt_compare_special_paragraph()
2993 *
2994 * Helpers for gagt_find_equivalent_special(). Compare line data case-
2995 * insensitively, taking care to use lengths rather than relying on line
2996 * buffer data being NUL terminated (which it's not); and iterate a complete
2997 * special paragraph comparison.
2998 */
2999 static int
3000 gagt_compare_special_line (const char *compare, const gagt_lineref_t line)
3001 {
3002 /*
3003 * Return true if the lengths match, and the real line data (excluding
3004 * indent and outdent) also matches, ignoring case.
3005 */
3006 return strlen (compare) == line->real_length
3007 && gagt_strncasecmp (compare,
3008 (char *)line->buffer.data + line->indent,
3009 line->real_length) == 0;
3010 }
3011
3012 static int
3013 gagt_compare_special_paragraph (const gagt_specialref_t special,
3014 const gagt_paragraphref_t paragraph)
3015 {
3016 /* If the line counts match, compare line by line. */
3017 if (special->line_count == gagt_get_paragraph_line_count (paragraph))
3018 {
3019 gagt_lineref_t line;
3020 int index, is_match;
3021
3022 is_match = TRUE;
3023 for (index = 0, line = gagt_get_first_paragraph_line (paragraph);
3024 index < special->line_count && line;
3025 index++, line = gagt_get_next_paragraph_line (line))
3026 {
3027 if (!gagt_compare_special_line (special->compare[index], line))
3028 {
3029 is_match = FALSE;
3030 break;
3031 }
3032 }
3033
3034 return is_match;
3035 }
3036
3037 /* Line count mismatch; return FALSE. */
3038 return FALSE;
3039 }
3040
3041
3042 /*
3043 * gagt_find_equivalent_special()
3044 *
3045 * Given a paragraph, see if it matches any of the special ones set up in
3046 * our array. Returns the special, or NULL if no match.
3047 */
3048 static gagt_specialref_t
3049 gagt_find_equivalent_special (gagt_paragraphref_t paragraph)
3050 {
3051 gagt_specialref_t special, match;
3052
3053 /* Check each special paragraph entry for a match against this paragraph. */
3054 match = NULL;
3055 for (special = GAGT_SPECIALS; special->replace; special++)
3056 {
3057 if (gagt_compare_special_paragraph (special, paragraph))
3058 {
3059 match = special;
3060 break;
3061 }
3062 }
3063
3064 return match;
3065 }
3066
3067
3068 /*
3069 * gagt_mark_specials()
3070 *
3071 * Search for and mark any lines that match special paragraphs.
3072 */
3073 static void
3074 gagt_mark_specials (void)
3075 {
3076 static int is_verified = FALSE;
3077
3078 /*
3079 * Verify special paragraphs table contents. This checks that each entry
3080 * ends with a NULL comparison, has a replacement, and that the line count
3081 * matches.
3082 */
3083 if (!is_verified)
3084 {
3085 gagt_specialref_t special;
3086
3087 for (special = GAGT_SPECIALS; special->replace; special++)
3088 {
3089 int line_count, index;
3090
3091 line_count = 0;
3092 for (index = 0; special->compare[index]; index++)
3093 line_count++;
3094
3095 assert (special->line_count == line_count);
3096 assert (special->replace);
3097 assert (!special->compare[GAGT_SPECIAL_MATCH_MAX]);
3098 }
3099
3100 is_verified = TRUE;
3101 }
3102
3103 /*
3104 * Search all paragraphs for special matches, if enabled. When a special
3105 * match is found, mark the paragraph with a pointer to the matching entry.
3106 */
3107 if (gagt_replacement_enabled)
3108 {
3109 gagt_paragraphref_t paragraph;
3110
3111 for (paragraph = gagt_get_first_paragraph ();
3112 paragraph; paragraph = gagt_get_next_paragraph (paragraph))
3113 {
3114 paragraph->special = gagt_find_equivalent_special (paragraph);
3115 }
3116 }
3117 }
3118
3119
3120 /*
3121 * gagt_display_special()
3122 *
3123 * Display the replacement text for the specified special table entry. The
3124 * current Glk style in force is passed in; we return the Glk style in force
3125 * after we've done.
3126 */
3127 static glui32
3128 gagt_display_special (const gagt_specialref_t special, glui32 current_style)
3129 {
3130 glui32 set_style;
3131 int index, marker, length;
3132 const char *string;
3133 assert (special);
3134
3135 /* Extract replacement string and length. */
3136 string = special->replace;
3137 assert (string);
3138 length = strlen (string);
3139
3140 set_style = current_style;
3141
3142 /*
3143 * Iterate each character in replacement string, looking for style escapes,
3144 * and flushing delayed output when one is found.
3145 */
3146 marker = 0;
3147 for (index = 0; index < length; index++)
3148 {
3149 if (string[index] == '|')
3150 {
3151 glui32 style;
3152
3153 /* Flush delayed output accumulated so far, excluding escape. */
3154 glk_put_buffer ((char *) string + marker, index - marker);
3155 marker = index + 2;
3156
3157 /* Determine any new text style. */
3158 style = set_style;
3159 switch (string[++index])
3160 {
3161 case 'E':
3162 style = style_Emphasized;
3163 break;
3164
3165 case 'S':
3166 style = style_Subheader;
3167 break;
3168
3169 case 'N':
3170 style = style_Normal;
3171 break;
3172
3173 default:
3174 gagt_fatal ("GLK: Invalid replacement style escape");
3175 gagt_exit ();
3176 }
3177
3178 /* If style changed, update Glk's style setting. */
3179 if (style != set_style)
3180 {
3181 glk_set_style (style);
3182 set_style = style;
3183 }
3184 }
3185 }
3186
3187 /* Output any remaining delayed characters. */
3188 if (marker < length)
3189 glk_put_buffer ((char *) string + marker, length - marker);
3190
3191 return set_style;
3192 }
3193
3194
3195 /*---------------------------------------------------------------------*/
3196 /* Glk port output functions */
3197 /*---------------------------------------------------------------------*/
3198
3199 /*
3200 * Flag for if the user entered "help" as their last input, or if hints have
3201 * been silenced as a result of already using a Glk command.
3202 */
3203 static int gagt_help_requested = FALSE,
3204 gagt_help_hints_silenced = FALSE;
3205
3206 /*
3207 * gagt_display_register_help_request()
3208 * gagt_display_silence_help_hints()
3209 * gagt_display_provide_help_hint()
3210 *
3211 * Register a request for help, and print a note of how to get Glk command
3212 * help from the interpreter unless silenced.
3213 */
3214 static void
3215 gagt_display_register_help_request (void)
3216 {
3217 gagt_help_requested = TRUE;
3218 }
3219
3220 static void
3221 gagt_display_silence_help_hints (void)
3222 {
3223 gagt_help_hints_silenced = TRUE;
3224 }
3225
3226 static glui32
3227 gagt_display_provide_help_hint (glui32 current_style)
3228 {
3229 if (gagt_help_requested && !gagt_help_hints_silenced)
3230 {
3231 glk_set_style (style_Emphasized);
3232 glk_put_string ("[Try 'glk help' for help on special interpreter"
3233 " commands]\n");
3234
3235 gagt_help_requested = FALSE;
3236 return style_Emphasized;
3237 }
3238
3239 return current_style;
3240 }
3241
3242
3243 /*
3244 * gagt_display_text_element()
3245 *
3246 * Display an element of a buffer string using matching packed attributes.
3247 * The currently set Glk style is supplied, and the function returns the
3248 * new currently set Glk style.
3249 *
3250 * The function handles a flag to coerce fixed width font.
3251 */
3252 static glui32
3253 gagt_display_text_element (const char *string, const unsigned char *attributes,
3254 int length, glui32 current_style, int fixed_width)
3255 {
3256 int marker, index;
3257 glui32 set_style;
3258 assert (glk_stream_get_current ());
3259
3260 set_style = current_style;
3261
3262 /*
3263 * Iterate each character in the line range. We actually delay output
3264 * until we see a change in style; that way, we can send a buffer of
3265 * characters to Glk, rather than sending them just one at a time.
3266 */
3267 marker = 0;
3268 for (index = 0; index < length; index++)
3269 {
3270 gagt_attrset_t attribute_set;
3271 glui32 style;
3272 assert (attributes && string);
3273
3274 /*
3275 * Unpack the AGT font attributes for this character, and add fixed
3276 * width font coercion.
3277 */
3278 gagt_unpack_attributes (attributes[index], &attribute_set);
3279 attribute_set.fixed |= fixed_width;
3280
3281 /*
3282 * Decide on any applicable new Glk text styling. If it's different
3283 * to the current style, output the delayed characters, and update
3284 * Glk's style setting.
3285 */
3286 style = gagt_select_style (&attribute_set);
3287 if (style != set_style)
3288 {
3289 glk_put_buffer ((char *) string + marker, index - marker);
3290 marker = index;
3291
3292 glk_set_style (style);
3293 set_style = style;
3294 }
3295 }
3296
3297 /* Output any remaining delayed characters. */
3298 if (marker < length)
3299 glk_put_buffer ((char *) string + marker, length - marker);
3300
3301 return set_style;
3302 }
3303
3304
3305 /*
3306 * gagt_display_line()
3307 *
3308 * Display a page buffer line, starting in the current Glk style, and
3309 * returning the new current Glk style.
3310 *
3311 * The function takes additional flags to force fixed width font, skip over
3312 * indentation and trailing line whitespace, and trim hyphens (if skipping
3313 * trailing whitespace).
3314 */
3315 static glui32
3316 gagt_display_line (const gagt_lineref_t line, glui32 current_style,
3317 int fixed_width, int skip_indent, int skip_outdent,
3318 int trim_hyphen)
3319 {
3320 int start, length;
3321 glui32 set_style;
3322
3323 /*
3324 * Check the skip indent flag to find the first character to display, and
3325 * the count of characters to display.
3326 */
3327 start = 0;
3328 length = line->buffer.length;
3329 if (skip_indent)
3330 {
3331 start += line->indent;
3332 length -= line->indent;
3333 }
3334
3335 /* Adjust length for skipping outdent and trimming hyphens. */
3336 if (skip_outdent)
3337 {
3338 length -= line->outdent;
3339 if (trim_hyphen && line->is_hyphenated)
3340 length--;
3341 }
3342
3343 /* Display this line segment. */
3344 set_style = gagt_display_text_element ((const char *)line->buffer.data + start,
3345 line->buffer.attributes + start,
3346 length, current_style, fixed_width);
3347
3348 return set_style;
3349 }
3350
3351
3352 /*
3353 * gagt_display_hinted_line()
3354 *
3355 * Display a page buffer line, starting in the current Glk style, and
3356 * returning the new current Glk style. The function uses the font hints
3357 * from the line, and receives the font hint of the prior line.
3358 */
3359 static glui32
3360 gagt_display_hinted_line (const gagt_lineref_t line, glui32 current_style,
3361 gagt_font_hint_t prior_hint)
3362 {
3363 glui32 style;
3364
3365 style = current_style;
3366 switch (line->font_hint)
3367 {
3368 case HINT_FIXED_WIDTH:
3369 /* Force fixed width font on the line. */
3370 style = gagt_display_line (line, style, TRUE, FALSE, FALSE, FALSE);
3371
3372 glk_put_char ('\n');
3373 break;
3374
3375 case HINT_PROPORTIONAL:
3376 /*
3377 * Permit proportional font, and suppress outdent. Suppress indent
3378 * too if this line follows a line that suppressed newline, or is the
3379 * first line in the paragraph. For all cases, trim the hyphen from
3380 * hyphenated lines.
3381 */
3382 if (prior_hint == HINT_PROPORTIONAL || prior_hint == HINT_NONE)
3383 style = gagt_display_line (line, style, FALSE, TRUE, TRUE, TRUE);
3384 else
3385 style = gagt_display_line (line, style, FALSE, FALSE, TRUE, TRUE);
3386
3387 /*
3388 * Where the line is not hyphenated, output a space in place of newline.
3389 * This lets paragraph text to flow to the full display width.
3390 */
3391 if (!line->is_hyphenated)
3392 glk_put_char (' ');
3393 break;
3394
3395 case HINT_PROPORTIONAL_NEWLINE:
3396 case HINT_PROPORTIONAL_NEWLINE_STANDOUT:
3397 /*
3398 * As above, permit proportional font, suppress outdent, and suppress
3399 * indent too under certain conditions; in this case, only when the
3400 * prior line suppressed newline.
3401 */
3402 if (prior_hint == HINT_PROPORTIONAL)
3403 style = gagt_display_line (line, style, FALSE, TRUE, TRUE, FALSE);
3404 else
3405 style = gagt_display_line (line, style, FALSE, FALSE, TRUE, FALSE);
3406
3407 glk_put_char ('\n');
3408 break;
3409
3410 case HINT_NONE:
3411 gagt_fatal ("GLK: Page buffer line with no font hint");
3412 gagt_exit ();
3413
3414 default:
3415 gagt_fatal ("GLK: Invalid font hint encountered");
3416 gagt_exit ();
3417 }
3418
3419 return style;
3420 }
3421
3422
3423 /*
3424 * gagt_display_auto()
3425 *
3426 * Display buffered output text to the Glk main window using a bunch of
3427 * occasionally rather dodgy heuristics to try to automatically set a suitable
3428 * font for the way the text is structured, while replacing special paragraphs
3429 * with altered text.
3430 */
3431 static void
3432 gagt_display_auto (void)
3433 {
3434 gagt_paragraphref_t paragraph;
3435 glui32 style;
3436
3437 style = style_Normal;
3438 glk_set_style (style);
3439
3440 /* Handle each paragraph. */
3441 for (paragraph = gagt_get_first_paragraph ();
3442 paragraph; paragraph = gagt_get_next_paragraph (paragraph))
3443 {
3444 /* If a special paragraph, output replacement text instead. */
3445 if (paragraph->special)
3446 {
3447 style = gagt_display_special (paragraph->special, style);
3448 glk_put_char ('\n');
3449 }
3450 else
3451 {
3452 gagt_lineref_t line;
3453 gagt_font_hint_t prior_hint;
3454
3455 /* Get the first line of the paragraph. */
3456 line = gagt_get_first_paragraph_line (paragraph);
3457
3458 /*
3459 * Output a blank line where the first line of the first paragraph
3460 * is standout; this sets it apart from the prompt.
3461 */
3462 if (paragraph == gagt_get_first_paragraph ()
3463 && line == gagt_get_first_paragraph_line (paragraph))
3464 {
3465 if (line->font_hint == HINT_PROPORTIONAL_NEWLINE_STANDOUT)
3466 glk_put_char ('\n');
3467 }
3468
3469 /* Handle each line of the paragraph. */
3470 prior_hint = HINT_NONE;
3471 for (; line; line = gagt_get_next_paragraph_line (line))
3472 {
3473 /*
3474 * Print this line according to its font hint, noting any change
3475 * of style and the line's font hint for use next iteration as
3476 * the prior hint.
3477 */
3478 style = gagt_display_hinted_line (line, style, prior_hint);
3479 prior_hint = line->font_hint;
3480 }
3481
3482 /* Output the newline for the end of the paragraph. */
3483 glk_put_char ('\n');
3484 }
3485 }
3486
3487 /* If no paragraphs at all, but a current buffer, output a newline. */
3488 if (!gagt_get_first_paragraph () && gagt_current_buffer.length > 0)
3489 glk_put_char ('\n');
3490
3491 /* Output any help hint and unterminated line from the line buffer. */
3492 style = gagt_display_provide_help_hint (style);
3493 style = gagt_display_text_element ((char *)gagt_current_buffer.data,
3494 gagt_current_buffer.attributes,
3495 gagt_current_buffer.length, style, FALSE);
3496 }
3497
3498
3499 /*
3500 * gagt_display_manual()
3501 *
3502 * Display buffered output text in the Glk main window, with either a fixed
3503 * width or a proportional font.
3504 */
3505 static void
3506 gagt_display_manual (int fixed_width)
3507 {
3508 gagt_lineref_t line;
3509 glui32 style;
3510
3511 style = style_Normal;
3512 glk_set_style (style);
3513
3514 for (line = gagt_get_first_page_line ();
3515 line; line = gagt_get_next_page_line (line))
3516 {
3517 gagt_paragraphref_t paragraph;
3518
3519 paragraph = line->paragraph;
3520
3521 /*
3522 * If this is a special paragraph, display the replacement text on
3523 * its first line and ignore remaining special lines. Otherwise,
3524 * display the page buffer line using either fixed or proportional
3525 * font, as requested.
3526 */
3527 if (paragraph && paragraph->special)
3528 {
3529 if (gagt_get_first_paragraph_line (paragraph) == line)
3530 style = gagt_display_special (paragraph->special, style);
3531 }
3532 else
3533 {
3534 style = gagt_display_line (line, style, fixed_width,
3535 FALSE, FALSE, FALSE);
3536 glk_put_char ('\n');
3537 }
3538 }
3539
3540 /* Output any help hint and unterminated line from the line buffer. */
3541 style = gagt_display_provide_help_hint (style);
3542 style = gagt_display_text_element ((char *)gagt_current_buffer.data,
3543 gagt_current_buffer.attributes,
3544 gagt_current_buffer.length,
3545 style, fixed_width);
3546 }
3547
3548
3549 /*
3550 * gagt_display_debug()
3551 *
3552 * Display the analyzed page buffer in a form that shows all of its gory
3553 * detail.
3554 */
3555 static void
3556 gagt_display_debug (void)
3557 {
3558 gagt_lineref_t line;
3559 char buffer[256];
3560
3561 glk_set_style (style_Preformatted);
3562 for (line = gagt_get_first_page_line ();
3563 line; line = gagt_get_next_page_line (line))
3564 {
3565 gagt_paragraphref_t paragraph;
3566
3567 paragraph = line->paragraph;
3568 sprintf (buffer,
3569 "%2d:%2d->%2lld A=%-3d L=%-2d I=%-2d O=%-2d R=%-2d %c%c| ",
3570 paragraph ? paragraph->id + 1 : 0,
3571 paragraph ? paragraph->line_count : 0,
3572 (long long)(paragraph && paragraph->special
3573 ? paragraph->special - GAGT_SPECIALS + 1 : 0),
3574 line->buffer.allocation, line->buffer.length,
3575 line->indent, line->outdent,
3576 line->real_length,
3577 line->is_hyphenated ? 'h' : '_',
3578 line->is_blank ? 'b' :
3579 line->font_hint == HINT_PROPORTIONAL ? 'P' :
3580 line->font_hint == HINT_PROPORTIONAL_NEWLINE ? 'N' :
3581 line->font_hint == HINT_PROPORTIONAL_NEWLINE_STANDOUT ? 'S' :
3582 line->font_hint == HINT_FIXED_WIDTH ? 'F' : '_');
3583 glk_put_string (buffer);
3584
3585 glk_put_buffer ((char *)line->buffer.data, line->buffer.length);
3586 glk_put_char ('\n');
3587 }
3588
3589 if (gagt_current_buffer.length > 0)
3590 {
3591 sprintf (buffer,
3592 "__,__->__ A=%-3d L=%-2d I=__ O=__ R=__ %s| ",
3593 gagt_current_buffer.allocation, gagt_current_buffer.length,
3594 gagt_help_requested ? "HR" : "__");
3595 glk_put_string (buffer);
3596
3597 glk_put_buffer ((char *)gagt_current_buffer.data, gagt_current_buffer.length);
3598 }
3599
3600 gagt_help_requested = FALSE;
3601 }
3602
3603
3604 /*
3605 * gagt_output_flush()
3606 *
3607 * Flush any buffered output text to the Glk main window, and clear the
3608 * buffer ready for new output text. The function concerns itself with
3609 * both the page buffer and any unterminated line in the line buffer.
3610 */
3611 static void
3612 gagt_output_flush (void)
3613 {
3614 /*
3615 * Run the analysis of page buffer contents. This will fill in the
3616 * paragraph and font hints fields, any any applicable special pointer,
3617 * for every line held in the buffer.
3618 */
3619 gagt_paragraph_page ();
3620 gagt_mark_specials ();
3621 gagt_assign_font_hints ();
3622
3623 /*
3624 * Select the appropriate display routine to use, and call it. The display
3625 * routines present somewhat different output, and are responsible for
3626 * displaying both the page buffer _and_ any buffered current line text.
3627 */
3628 switch (gagt_font_mode)
3629 {
3630 case FONT_AUTOMATIC:
3631 gagt_display_auto ();
3632 break;
3633
3634 case FONT_FIXED_WIDTH:
3635 gagt_display_manual (TRUE);
3636 break;
3637
3638 case FONT_PROPORTIONAL:
3639 gagt_display_manual (FALSE);
3640 break;
3641
3642 case FONT_DEBUG:
3643 gagt_display_debug ();
3644 break;
3645
3646 default:
3647 gagt_fatal ("GLK: Invalid font mode encountered");
3648 gagt_exit ();
3649 }
3650
3651 /* Empty the buffer, ready for new game strings. */
3652 gagt_paragraphs_delete ();
3653 gagt_output_delete ();
3654 }
3655
3656
3657 /*
3658 * agt_clrscr()
3659 *
3660 * Clear the main playing area window. Although there may be little point
3661 * in flushing (rather than emptying) the buffers, nevertheless that is
3662 * what we do.
3663 */
3664 void
3665 agt_clrscr (void)
3666 {
3667 if (!BATCH_MODE)
3668 {
3669 /* Update the apparent (virtual) window x position. */
3670 curr_x = 0;
3671
3672 /* Flush any pending buffered output, and clear the main window. */
3673 gagt_output_flush ();
3674 glk_window_clear (gagt_main_window);
3675
3676 /* Add a series of newlines to any script file. */
3677 if (script_on)
3678 textputs (scriptfile, "\n\n\n\n");
3679
3680 gagt_debug ("agt_clrscr", "");
3681 }
3682 }
3683
3684
3685 /*
3686 * gagt_styled_string()
3687 * gagt_styled_char()
3688 * gagt_standout_string()
3689 * gagt_standout_char()
3690 * gagt_normal_string()
3691 * gagt_normal_char()
3692 * gagt_header_string()
3693 *
3694 * Convenience functions to print strings in assorted styles. A standout
3695 * string is one that hints that it's from the interpreter, not the game.
3696 */
3697 static void
3698 gagt_styled_string (glui32 style, const char *message)
3699 {
3700 assert (message);
3701
3702 glk_set_style (style);
3703 glk_put_string ((char *) message);
3704 glk_set_style (style_Normal);
3705 }
3706
3707 static void
3708 gagt_styled_char (glui32 style, char c)
3709 {
3710 char buffer[2];
3711
3712 buffer[0] = c;
3713 buffer[1] = '\0';
3714 gagt_styled_string (style, buffer);
3715 }
3716
3717 static void
3718 gagt_standout_string (const char *message)
3719 {
3720 gagt_styled_string (style_Emphasized, message);
3721 }
3722
3723 static void
3724 gagt_standout_char (char c)
3725 {
3726 gagt_styled_char (style_Emphasized, c);
3727 }
3728
3729 static void
3730 gagt_normal_string (const char *message)
3731 {
3732 gagt_styled_string (style_Normal, message);
3733 }
3734
3735 static void
3736 gagt_normal_char (char c)
3737 {
3738 gagt_styled_char (style_Normal, c);
3739 }
3740
3741 static void
3742 gagt_header_string (const char *message)
3743 {
3744 gagt_styled_string (style_Header, message);
3745 }
3746
3747
3748 /*---------------------------------------------------------------------*/
3749 /* Glk port delay functions */
3750 /*---------------------------------------------------------------------*/
3751
3752 /* Number of milliseconds in a second (traditionally, 1000). */
3753 static const int GAGT_MS_PER_SEC = 1000;
3754
3755 /*
3756 * Number of milliseconds to timeout. Because of jitter in the way Glk
3757 * generates timeouts, it's worthwhile implementing a delay using a number
3758 * of shorter timeouts. This minimizes inaccuracies in the actual delay.
3759 */
3760 static const glui32 GAGT_DELAY_TIMEOUT = 50;
3761
3762 /* The character key that can be pressed to cancel, and suspend, delays. */
3763 static const char GAGT_DELAY_SUSPEND = ' ';
3764
3765 /*
3766 * Flag to temporarily turn off all delays. This is set when the user
3767 * cancels a delay with a keypress, and remains set until the next time
3768 * that AGiliTy requests user input. This way, games that call agt_delay()
3769 * sequentially don't require multiple keypresses to jump out of delay
3770 * sections.
3771 */
3772 static int gagt_delays_suspended = FALSE;
3773
3774
3775 /*
3776 * agt_delay()
3777 *
3778 * Delay for the specified number of seconds. The delay can be canceled
3779 * by a user keypress.
3780 */
3781 void
3782 agt_delay (int seconds)
3783 {
3784 glui32 milliseconds, delayed;
3785 int delay_completed;
3786
3787 /* Suppress delay if in fast replay or batch mode. */
3788 if (fast_replay || BATCH_MODE)
3789 return;
3790
3791 /*
3792 * Do nothing if Glk doesn't have timers, if the delay state is set to
3793 * ignore delays, if a zero or negative delay was specified, or if delays
3794 * are currently temporarily suspended.
3795 */
3796 if (!glk_gestalt (gestalt_Timer, 0)
3797 || gagt_delay_mode == DELAY_OFF
3798 || seconds <= 0 || gagt_delays_suspended)
3799 return;
3800
3801 /* Flush any pending buffered output, and refresh status to show waiting. */
3802 gagt_output_flush ();
3803 gagt_status_in_delay (TRUE);
3804
3805 /* Calculate the number of milliseconds to delay. */
3806 milliseconds = (seconds * GAGT_MS_PER_SEC)
3807 / (gagt_delay_mode == DELAY_SHORT ? 2 : 1);
3808
3809 /* Request timer events, and let a keypress cancel the delay. */
3810 glk_request_char_event (gagt_main_window);
3811 glk_request_timer_events (GAGT_DELAY_TIMEOUT);
3812
3813 /*
3814 * Implement the delay using a sequence of shorter Glk timeouts, with an
3815 * option to cancel the delay with a keypress.
3816 */
3817 delay_completed = TRUE;
3818 for (delayed = 0; delayed < milliseconds; delayed += GAGT_DELAY_TIMEOUT)
3819 {
3820 event_t event;
3821
3822 /* Wait for the next timeout, or a character. */
3823 gagt_event_wait_2 (evtype_CharInput, evtype_Timer, &event);
3824 if (event.type == evtype_CharInput)
3825 {
3826 /*
3827 * If suspend requested, stop the delay, and set the delay
3828 * suspension flag, and a note that the delay loop didn't complete.
3829 * Otherwise, reissue the character input request.
3830 */
3831 if (event.val1 == GAGT_DELAY_SUSPEND)
3832 {
3833 gagt_delays_suspended = TRUE;
3834 delay_completed = FALSE;
3835 break;
3836 }
3837 else
3838 glk_request_char_event (gagt_main_window);
3839 }
3840 }
3841
3842 /* Cancel any pending character input, and timer events. */
3843 if (delay_completed)
3844 glk_cancel_char_event (gagt_main_window);
3845 glk_request_timer_events (0);
3846
3847 /* Clear the waiting indicator. */
3848 gagt_status_in_delay (FALSE);
3849
3850 gagt_debug ("agt_delay", "seconds=%d [%lu mS] -> %s", seconds, milliseconds,
3851 delay_completed ? "completed" : "canceled");
3852 }
3853
3854
3855 /*
3856 * gagt_delay_resume()
3857 *
3858 * Unsuspend delays. This function should be called by agt_input() and
3859 * agt_getkey(), to re-enable delays when the interpreter next requests
3860 * user input.
3861 */
3862 static void
3863 gagt_delay_resume (void)
3864 {
3865 gagt_delays_suspended = FALSE;
3866 }
3867
3868
3869 /*---------------------------------------------------------------------*/
3870 /* Glk port box drawing functions */
3871 /*---------------------------------------------------------------------*/
3872
3873 /* Saved details of any current box dimensions and flags. */
3874 static unsigned long gagt_box_flags = 0;
3875 static int gagt_box_busy = FALSE,
3876 gagt_box_width = 0,
3877 gagt_box_height = 0,
3878 gagt_box_startx = 0;
3879
3880
3881 /*
3882 * gagt_box_rule()
3883 * gagt_box_position()
3884 *
3885 * Draw a line at the top or bottom of a box, and position the cursor
3886 * with a box indent.
3887 */
3888 static void
3889 gagt_box_rule (int width)
3890 {
3891 char *ruler;
3892
3893 /* Write a +--...--+ ruler to delimit a box. */
3894 ruler = gagt_malloc (width + 2 + 1);
3895 memset (ruler + 1, '-', width);
3896 ruler[0] = ruler[width + 1] = '+';
3897 ruler[width + 2] = '\0';
3898 agt_puts (ruler);
3899 free (ruler);
3900 }
3901
3902 static void
3903 gagt_box_position (int indent)
3904 {
3905 char *spaces;
3906
3907 /* Write a newline before the indent. */
3908 agt_newline ();
3909
3910 /* Write the indent to the start of box text. */
3911 spaces = gagt_malloc (indent + 1);
3912 memset (spaces, ' ', indent);
3913 spaces[indent] = '\0';
3914 agt_puts (spaces);
3915 free (spaces);
3916 }
3917
3918
3919 /*
3920 * agt_makebox()
3921 * agt_qnewline()
3922 * agt_endbox()
3923 *
3924 * Start a box of given width, height, and with given flags. Write a new
3925 * line in the box. And end the box.
3926 */
3927 void
3928 agt_makebox (int width, int height, unsigned long flags)
3929 {
3930 assert (!gagt_box_busy);
3931
3932 gagt_box_busy = TRUE;
3933 gagt_box_flags = flags;
3934 gagt_box_width = width;
3935 gagt_box_height = height;
3936
3937 /* If no centering requested, set the indent to zero. */
3938 if (gagt_box_flags & TB_NOCENT)
3939 gagt_box_startx = 0;
3940 else
3941 {
3942 int centering_width;
3943
3944 /*
3945 * Calculate the indent for centering, adding 4 characters for borders.
3946 * Here, since screen_width is artificial, we'll center off status_width
3947 * if it is less than screen width, otherwise we'll center by using
3948 * screen_width. The reason for shrinking to screen_width is that if
3949 * we don't, we could drive curr_x to beyond screen_width with our box
3950 * indentations, and that confuses AGiliTy.
3951 */
3952 if (status_width < screen_width)
3953 centering_width = status_width;
3954 else
3955 centering_width = screen_width;
3956 if (gagt_box_flags & TB_BORDER)
3957 gagt_box_startx = (centering_width - gagt_box_width - 4) / 2;
3958 else
3959 gagt_box_startx = (centering_width - gagt_box_width) / 2;
3960
3961 /* If the box turns out wider than the window, abandon centering. */
3962 if (gagt_box_startx < 0)
3963 gagt_box_startx = 0;
3964 }
3965
3966 /*
3967 * When in a box, we'll coerce fixed width font by setting it in the AGT
3968 * font attributes. This ensures that the box displays as accurately as
3969 * we're able to achieve.
3970 */
3971 gagt_coerce_fixed_font (TRUE);
3972
3973 /* Position the cursor for the box, and if bordered, write the rule. */
3974 gagt_box_position (gagt_box_startx);
3975 if (gagt_box_flags & TB_BORDER)
3976 {
3977 gagt_box_rule (gagt_box_width + 2);
3978 gagt_box_position (gagt_box_startx);
3979 agt_puts ("| ");
3980 }
3981
3982 gagt_debug ("agt_makebox", "width=%d, height=%d, flags=0x%lx",
3983 width, height, flags);
3984 }
3985
3986 void
3987 agt_qnewline (void)
3988 {
3989 assert (gagt_box_busy);
3990
3991 /* Write box characters for the current and next line. */
3992 if (gagt_box_flags & TB_BORDER)
3993 {
3994 agt_puts (" |");
3995 gagt_box_position (gagt_box_startx);
3996 agt_puts ("| ");
3997 }
3998 else
3999 gagt_box_position (gagt_box_startx);
4000
4001 gagt_debug ("agt_qnewline", "");
4002 }
4003
4004 void
4005 agt_endbox (void)
4006 {
4007 assert (gagt_box_busy);
4008
4009 /* Finish off the current box. */
4010 if (gagt_box_flags & TB_BORDER)
4011 {
4012 agt_puts (" |");
4013 gagt_box_position (gagt_box_startx);
4014 gagt_box_rule (gagt_box_width + 2);
4015 }
4016 agt_newline ();
4017
4018 /* An extra newline here improves the appearance. */
4019 agt_newline ();
4020
4021 /* Back to allowing proportional font output again. */
4022 gagt_coerce_fixed_font (FALSE);
4023
4024 gagt_box_busy = FALSE;
4025 gagt_box_flags = gagt_box_width = gagt_box_startx = 0;
4026
4027 gagt_debug ("agt_endbox", "");
4028 }
4029
4030
4031 /*---------------------------------------------------------------------*/
4032 /* Glk command escape functions */
4033 /*---------------------------------------------------------------------*/
4034
4035 /*
4036 * gagt_command_script()
4037 *
4038 * Turn game output scripting (logging) on and off.
4039 */
4040 static void
4041 gagt_command_script (const char *argument)
4042 {
4043 assert (argument);
4044
4045 if (gagt_strcasecmp (argument, "on") == 0)
4046 {
4047 frefid_t fileref;
4048
4049 if (gagt_transcript_stream)
4050 {
4051 gagt_normal_string ("Glk transcript is already on.\n");
4052 return;
4053 }
4054
4055 fileref = glk_fileref_create_by_prompt (fileusage_Transcript
4056 | fileusage_TextMode,
4057 filemode_WriteAppend, 0);
4058 if (!fileref)
4059 {
4060 gagt_standout_string ("Glk transcript failed.\n");
4061 return;
4062 }
4063
4064 gagt_transcript_stream = glk_stream_open_file (fileref,
4065 filemode_WriteAppend, 0);
4066 glk_fileref_destroy (fileref);
4067 if (!gagt_transcript_stream)
4068 {
4069 gagt_standout_string ("Glk transcript failed.\n");
4070 return;
4071 }
4072
4073 glk_window_set_echo_stream (gagt_main_window, gagt_transcript_stream);
4074
4075 gagt_normal_string ("Glk transcript is now on.\n");
4076 }
4077
4078 else if (gagt_strcasecmp (argument, "off") == 0)
4079 {
4080 if (!gagt_transcript_stream)
4081 {
4082 gagt_normal_string ("Glk transcript is already off.\n");
4083 return;
4084 }
4085
4086 glk_stream_close (gagt_transcript_stream, NULL);
4087 gagt_transcript_stream = NULL;
4088
4089 glk_window_set_echo_stream (gagt_main_window, NULL);
4090
4091 gagt_normal_string ("Glk transcript is now off.\n");
4092 }
4093
4094 else if (strlen (argument) == 0)
4095 {
4096 gagt_normal_string ("Glk transcript is ");
4097 gagt_normal_string (gagt_transcript_stream ? "on" : "off");
4098 gagt_normal_string (".\n");
4099 }
4100
4101 else
4102 {
4103 gagt_normal_string ("Glk transcript can be ");
4104 gagt_standout_string ("on");
4105 gagt_normal_string (", or ");
4106 gagt_standout_string ("off");
4107 gagt_normal_string (".\n");
4108 }
4109 }
4110
4111
4112 /*
4113 * gagt_command_inputlog()
4114 *
4115 * Turn game input logging on and off.
4116 */
4117 static void
4118 gagt_command_inputlog (const char *argument)
4119 {
4120 assert (argument);
4121
4122 if (gagt_strcasecmp (argument, "on") == 0)
4123 {
4124 frefid_t fileref;
4125
4126 if (gagt_inputlog_stream)
4127 {
4128 gagt_normal_string ("Glk input logging is already on.\n");
4129 return;
4130 }
4131
4132 fileref = glk_fileref_create_by_prompt (fileusage_InputRecord
4133 | fileusage_BinaryMode,
4134 filemode_WriteAppend, 0);
4135 if (!fileref)
4136 {
4137 gagt_standout_string ("Glk input logging failed.\n");
4138 return;
4139 }
4140
4141 gagt_inputlog_stream = glk_stream_open_file (fileref,
4142 filemode_WriteAppend, 0);
4143 glk_fileref_destroy (fileref);
4144 if (!gagt_inputlog_stream)
4145 {
4146 gagt_standout_string ("Glk input logging failed.\n");
4147 return;
4148 }
4149
4150 gagt_normal_string ("Glk input logging is now on.\n");
4151 }
4152
4153 else if (gagt_strcasecmp (argument, "off") == 0)
4154 {
4155 if (!gagt_inputlog_stream)
4156 {
4157 gagt_normal_string ("Glk input logging is already off.\n");
4158 return;
4159 }
4160
4161 glk_stream_close (gagt_inputlog_stream, NULL);
4162 gagt_inputlog_stream = NULL;
4163
4164 gagt_normal_string ("Glk input log is now off.\n");
4165 }
4166
4167 else if (strlen (argument) == 0)
4168 {
4169 gagt_normal_string ("Glk input logging is ");
4170 gagt_normal_string (gagt_inputlog_stream ? "on" : "off");
4171 gagt_normal_string (".\n");
4172 }
4173
4174 else
4175 {
4176 gagt_normal_string ("Glk input logging can be ");
4177 gagt_standout_string ("on");
4178 gagt_normal_string (", or ");
4179 gagt_standout_string ("off");
4180 gagt_normal_string (".\n");
4181 }
4182 }
4183
4184
4185 /*
4186 * gagt_command_readlog()
4187 *
4188 * Set the game input log, to read input from a file.
4189 */
4190 static void
4191 gagt_command_readlog (const char *argument)
4192 {
4193 assert (argument);
4194
4195 if (gagt_strcasecmp (argument, "on") == 0)
4196 {
4197 frefid_t fileref;
4198
4199 if (gagt_readlog_stream)
4200 {
4201 gagt_normal_string ("Glk read log is already on.\n");
4202 return;
4203 }
4204
4205 fileref = glk_fileref_create_by_prompt (fileusage_InputRecord
4206 | fileusage_BinaryMode,
4207 filemode_Read, 0);
4208 if (!fileref)
4209 {
4210 gagt_standout_string ("Glk read log failed.\n");
4211 return;
4212 }
4213
4214 if (!glk_fileref_does_file_exist (fileref))
4215 {
4216 glk_fileref_destroy (fileref);
4217 gagt_standout_string ("Glk read log failed.\n");
4218 return;
4219 }
4220
4221 gagt_readlog_stream = glk_stream_open_file (fileref, filemode_Read, 0);
4222 glk_fileref_destroy (fileref);
4223 if (!gagt_readlog_stream)
4224 {
4225 gagt_standout_string ("Glk read log failed.\n");
4226 return;
4227 }
4228
4229 gagt_normal_string ("Glk read log is now on.\n");
4230 }
4231
4232 else if (gagt_strcasecmp (argument, "off") == 0)
4233 {
4234 if (!gagt_readlog_stream)
4235 {
4236 gagt_normal_string ("Glk read log is already off.\n");
4237 return;
4238 }
4239
4240 glk_stream_close (gagt_readlog_stream, NULL);
4241 gagt_readlog_stream = NULL;
4242
4243 gagt_normal_string ("Glk read log is now off.\n");
4244 }
4245
4246 else if (strlen (argument) == 0)
4247 {
4248 gagt_normal_string ("Glk read log is ");
4249 gagt_normal_string (gagt_readlog_stream ? "on" : "off");
4250 gagt_normal_string (".\n");
4251 }
4252
4253 else
4254 {
4255 gagt_normal_string ("Glk read log can be ");
4256 gagt_standout_string ("on");
4257 gagt_normal_string (", or ");
4258 gagt_standout_string ("off");
4259 gagt_normal_string (".\n");
4260 }
4261 }
4262
4263
4264 /*
4265 * gagt_command_abbreviations()
4266 *
4267 * Turn abbreviation expansions on and off.
4268 */
4269 static void
4270 gagt_command_abbreviations (const char *argument)
4271 {
4272 assert (argument);
4273
4274 if (gagt_strcasecmp (argument, "on") == 0)
4275 {
4276 if (gagt_abbreviations_enabled)
4277 {
4278 gagt_normal_string ("Glk abbreviation expansions are already on.\n");
4279 return;
4280 }
4281
4282 gagt_abbreviations_enabled = TRUE;
4283 gagt_normal_string ("Glk abbreviation expansions are now on.\n");
4284 }
4285
4286 else if (gagt_strcasecmp (argument, "off") == 0)
4287 {
4288 if (!gagt_abbreviations_enabled)
4289 {
4290 gagt_normal_string ("Glk abbreviation expansions are already off.\n");
4291 return;
4292 }
4293
4294 gagt_abbreviations_enabled = FALSE;
4295 gagt_normal_string ("Glk abbreviation expansions are now off.\n");
4296 }
4297
4298 else if (strlen (argument) == 0)
4299 {
4300 gagt_normal_string ("Glk abbreviation expansions are ");
4301 gagt_normal_string (gagt_abbreviations_enabled ? "on" : "off");
4302 gagt_normal_string (".\n");
4303 }
4304
4305 else
4306 {
4307 gagt_normal_string ("Glk abbreviation expansions can be ");
4308 gagt_standout_string ("on");
4309 gagt_normal_string (", or ");
4310 gagt_standout_string ("off");
4311 gagt_normal_string (".\n");
4312 }
4313 }
4314
4315
4316 /*
4317 * gagt_command_fonts()
4318 *
4319 * Set the value for gagt_font_mode depending on the argument from the
4320 * user's command escape.
4321 *
4322 * Despite our best efforts, font control may still be wrong in some games.
4323 * This command gives us a chance to correct that.
4324 */
4325 static void
4326 gagt_command_fonts (const char *argument)
4327 {
4328 assert (argument);
4329
4330 if (gagt_strcasecmp (argument, "fixed") == 0)
4331 {
4332 if (gagt_font_mode == FONT_FIXED_WIDTH)
4333 {
4334 gagt_normal_string ("Glk font control is already 'fixed'.\n");
4335 return;
4336 }
4337
4338 gagt_font_mode = FONT_FIXED_WIDTH;
4339 gagt_normal_string ("Glk font control is now 'fixed'.\n");
4340 }
4341
4342 else if (gagt_strcasecmp (argument, "variable") == 0
4343 || gagt_strcasecmp (argument, "proportional") == 0)
4344 {
4345 if (gagt_font_mode == FONT_PROPORTIONAL)
4346 {
4347 gagt_normal_string ("Glk font control is already 'proportional'.\n");
4348 return;
4349 }
4350
4351 gagt_font_mode = FONT_PROPORTIONAL;
4352 gagt_normal_string ("Glk font control is now 'proportional'.\n");
4353 }
4354
4355 else if (gagt_strcasecmp (argument, "auto") == 0
4356 || gagt_strcasecmp (argument, "automatic") == 0)
4357 {
4358 if (gagt_font_mode == FONT_AUTOMATIC)
4359 {
4360 gagt_normal_string ("Glk font control is already 'automatic'.\n");
4361 return;
4362 }
4363
4364 gagt_font_mode = FONT_AUTOMATIC;
4365 gagt_normal_string ("Glk font control is now 'automatic'.\n");
4366 }
4367
4368 else if (gagt_strcasecmp (argument, "debug") == 0)
4369 {
4370 if (gagt_font_mode == FONT_DEBUG)
4371 {
4372 gagt_normal_string ("Glk font control is already 'debug'.\n");
4373 return;
4374 }
4375
4376 gagt_font_mode = FONT_DEBUG;
4377 gagt_normal_string ("Glk font control is now 'debug'.\n");
4378 }
4379
4380 else if (strlen (argument) == 0)
4381 {
4382 gagt_normal_string ("Glk font control is set to '");
4383 switch (gagt_font_mode)
4384 {
4385 case FONT_AUTOMATIC:
4386 gagt_normal_string ("automatic");
4387 break;
4388
4389 case FONT_FIXED_WIDTH:
4390 gagt_normal_string ("fixed");
4391 break;
4392
4393 case FONT_PROPORTIONAL:
4394 gagt_normal_string ("proportional");
4395 break;
4396
4397 case FONT_DEBUG:
4398 gagt_normal_string ("debug");
4399 break;
4400
4401 default:
4402 gagt_fatal ("GLK: Invalid font mode encountered");
4403 gagt_exit ();
4404 }
4405 gagt_normal_string ("'.\n");
4406 }
4407
4408 else
4409 {
4410 /* Avoid mentioning the debug setting. */
4411 gagt_normal_string ("Glk font control can be ");
4412 gagt_standout_string ("fixed");
4413 gagt_normal_string (", ");
4414 gagt_standout_string ("proportional");
4415 gagt_normal_string (", or ");
4416 gagt_standout_string ("automatic");
4417 gagt_normal_string (".\n");
4418 }
4419 }
4420
4421
4422 /*
4423 * gagt_command_delays()
4424 *
4425 * Set a value for gagt_delay_mode depending on the argument from
4426 * the user's command escape.
4427 */
4428 static void
4429 gagt_command_delays (const char *argument)
4430 {
4431 assert (argument);
4432
4433 if (!glk_gestalt (gestalt_Timer, 0))
4434 {
4435 gagt_normal_string ("Glk delays are not available.\n");
4436 return;
4437 }
4438
4439 if (gagt_strcasecmp (argument, "full") == 0
4440 || gagt_strcasecmp (argument, "on") == 0)
4441 {
4442 if (gagt_delay_mode == DELAY_FULL)
4443 {
4444 gagt_normal_string ("Glk delay mode is already 'full'.\n");
4445 return;
4446 }
4447
4448 gagt_delay_mode = DELAY_FULL;
4449 gagt_normal_string ("Glk delay mode is now 'full'.\n");
4450 }
4451
4452 else if (gagt_strcasecmp (argument, "short") == 0
4453 || gagt_strcasecmp (argument, "half") == 0)
4454 {
4455 if (gagt_delay_mode == DELAY_SHORT)
4456 {
4457 gagt_normal_string ("Glk delay mode is already 'short'.\n");
4458 return;
4459 }
4460
4461 gagt_delay_mode = DELAY_SHORT;
4462 gagt_normal_string ("Glk delay mode is now 'short'.\n");
4463 }
4464
4465 else if (gagt_strcasecmp (argument, "none") == 0
4466 || gagt_strcasecmp (argument, "off") == 0)
4467 {
4468 if (gagt_delay_mode == DELAY_OFF)
4469 {
4470 gagt_normal_string ("Glk delay mode is already 'none'.\n");
4471 return;
4472 }
4473
4474 gagt_delay_mode = DELAY_OFF;
4475 gagt_normal_string ("Glk delay mode is now 'none'.\n");
4476 }
4477
4478 else if (strlen (argument) == 0)
4479 {
4480 gagt_normal_string ("Glk delay mode is set to '");
4481 switch (gagt_delay_mode)
4482 {
4483 case DELAY_FULL:
4484 gagt_normal_string ("full");
4485 break;
4486
4487 case DELAY_SHORT:
4488 gagt_normal_string ("short");
4489 break;
4490
4491 case DELAY_OFF:
4492 gagt_normal_string ("none");
4493 break;
4494
4495 default:
4496 gagt_fatal ("GLK: Invalid delay mode encountered");
4497 gagt_exit ();
4498 }
4499 gagt_normal_string ("'.\n");
4500 }
4501
4502 else
4503 {
4504 gagt_normal_string ("Glk delay mode can be ");
4505 gagt_standout_string ("full");
4506 gagt_normal_string (", ");
4507 gagt_standout_string ("short");
4508 gagt_normal_string (", or ");
4509 gagt_standout_string ("none");
4510 gagt_normal_string (".\n");
4511 }
4512 }
4513
4514
4515 /*
4516 * gagt_command_width()
4517 *
4518 * Print out the (approximate) display width, from status_width. It's
4519 * approximate because the main window might include a scrollbar that
4520 * the status window doesn't have, may use a different size font, and so
4521 * on. But the main window won't tell us a width at all - it always
4522 * returns zero. If we don't happen to have a status window available
4523 * to us, there's not much we can say.
4524 *
4525 * Note that this function uses the interpreter variable status_width,
4526 * so it's important to keep this updated with the current window size at
4527 * all times.
4528 */
4529 static void
4530 gagt_command_width (const char *argument)
4531 {
4532 char buffer[16];
4533 assert (argument);
4534
4535 if (!gagt_status_window)
4536 {
4537 gagt_normal_string ("Glk's current display width is unknown.\n");
4538 return;
4539 }
4540
4541 gagt_normal_string ("Glk's current display width is approximately ");
4542 sprintf (buffer, "%d", status_width);
4543 gagt_normal_string (buffer);
4544 gagt_normal_string (status_width == 1 ? " character" : " characters");
4545 gagt_normal_string (".\n");
4546 }
4547
4548
4549 /*
4550 * gagt_command_replacements()
4551 *
4552 * Turn Glk special paragraph replacement on and off.
4553 */
4554 static void
4555 gagt_command_replacements (const char *argument)
4556 {
4557 assert (argument);
4558
4559 if (gagt_strcasecmp (argument, "on") == 0)
4560 {
4561 if (gagt_replacement_enabled)
4562 {
4563 gagt_normal_string ("Glk replacements are already on.\n");
4564 return;
4565 }
4566
4567 gagt_replacement_enabled = TRUE;
4568 gagt_normal_string ("Glk replacements are now on.\n");
4569 }
4570
4571 else if (gagt_strcasecmp (argument, "off") == 0)
4572 {
4573 if (!gagt_replacement_enabled)
4574 {
4575 gagt_normal_string ("Glk replacements are already off.\n");
4576 return;
4577 }
4578
4579 gagt_replacement_enabled = FALSE;
4580 gagt_normal_string ("Glk replacements are now off.\n");
4581 }
4582
4583 else if (strlen (argument) == 0)
4584 {
4585 gagt_normal_string ("Glk replacements are ");
4586 gagt_normal_string (gagt_replacement_enabled ? "on" : "off");
4587 gagt_normal_string (".\n");
4588 }
4589
4590 else
4591 {
4592 gagt_normal_string ("Glk replacements can be ");
4593 gagt_standout_string ("on");
4594 gagt_normal_string (", or ");
4595 gagt_standout_string ("off");
4596 gagt_normal_string (".\n");
4597 }
4598 }
4599
4600
4601 /*
4602 * gagt_command_statusline()
4603 *
4604 * Turn the extended status line on and off.
4605 */
4606 static void
4607 gagt_command_statusline (const char *argument)
4608 {
4609 assert (argument);
4610
4611 if (!gagt_status_window)
4612 {
4613 gagt_normal_string ("Glk status window is not available.\n");
4614 return;
4615 }
4616
4617 if (gagt_strcasecmp (argument, "extended") == 0
4618 || gagt_strcasecmp (argument, "full") == 0)
4619 {
4620 if (gagt_extended_status_enabled)
4621 {
4622 gagt_normal_string ("Glk status line mode is already 'extended'.\n");
4623 return;
4624 }
4625
4626 /* Expand the status window down to a second line. */
4627 glk_window_set_arrangement (glk_window_get_parent (gagt_status_window),
4628 winmethod_Above | winmethod_Fixed, 2, NULL);
4629 gagt_extended_status_enabled = TRUE;
4630
4631 gagt_normal_string ("Glk status line mode is now 'extended'.\n");
4632 }
4633
4634 else if (gagt_strcasecmp (argument, "short") == 0
4635 || gagt_strcasecmp (argument, "normal") == 0)
4636 {
4637 if (!gagt_extended_status_enabled)
4638 {
4639 gagt_normal_string ("Glk status line mode is already 'short'.\n");
4640 return;
4641 }
4642
4643 /* Shrink the status window down to one line. */
4644 glk_window_set_arrangement (glk_window_get_parent (gagt_status_window),
4645 winmethod_Above | winmethod_Fixed, 1, NULL);
4646 gagt_extended_status_enabled = FALSE;
4647
4648 gagt_normal_string ("Glk status line mode is now 'short'.\n");
4649 }
4650
4651 else if (strlen (argument) == 0)
4652 {
4653 gagt_normal_string ("Glk status line mode is set to '");
4654 gagt_normal_string (gagt_extended_status_enabled ? "extended" : "short");
4655 gagt_normal_string ("'.\n");
4656 }
4657
4658 else
4659 {
4660 gagt_normal_string ("Glk status line can be ");
4661 gagt_standout_string ("extended");
4662 gagt_normal_string (", or ");
4663 gagt_standout_string ("short");
4664 gagt_normal_string (".\n");
4665 }
4666 }
4667
4668
4669 /*
4670 * gagt_command_print_version_number()
4671 * gagt_command_version()
4672 *
4673 * Print out the Glk library version number.
4674 */
4675 static void
4676 gagt_command_print_version_number (glui32 version)
4677 {
4678 char buffer[64];
4679
4680 sprintf (buffer, "%u.%u.%u",
4681 version >> 16, (version >> 8) & 0xff, version & 0xff);
4682 gagt_normal_string (buffer);
4683 }
4684
4685 static void
4686 gagt_command_version (const char *argument)
4687 {
4688 glui32 version;
4689 assert (argument);
4690
4691 gagt_normal_string ("This is version ");
4692 gagt_command_print_version_number (GAGT_PORT_VERSION);
4693 gagt_normal_string (" of the Glk AGiliTy port.\n");
4694
4695 version = glk_gestalt (gestalt_Version, 0);
4696 gagt_normal_string ("The Glk library version is ");
4697 gagt_command_print_version_number (version);
4698 gagt_normal_string (".\n");
4699 }
4700
4701
4702 /*
4703 * gagt_command_commands()
4704 *
4705 * Turn command escapes off. Once off, there's no way to turn them back on.
4706 * Commands must be on already to enter this function.
4707 */
4708 static void
4709 gagt_command_commands (const char *argument)
4710 {
4711 assert (argument);
4712
4713 if (gagt_strcasecmp (argument, "on") == 0)
4714 {
4715 gagt_normal_string ("Glk commands are already on.\n");
4716 }
4717
4718 else if (gagt_strcasecmp (argument, "off") == 0)
4719 {
4720 gagt_commands_enabled = FALSE;
4721 gagt_normal_string ("Glk commands are now off.\n");
4722 }
4723
4724 else if (strlen (argument) == 0)
4725 {
4726 gagt_normal_string ("Glk commands are ");
4727 gagt_normal_string (gagt_commands_enabled ? "on" : "off");
4728 gagt_normal_string (".\n");
4729 }
4730
4731 else
4732 {
4733 gagt_normal_string ("Glk commands can be ");
4734 gagt_standout_string ("on");
4735 gagt_normal_string (", or ");
4736 gagt_standout_string ("off");
4737 gagt_normal_string (".\n");
4738 }
4739 }
4740
4741
4742 /*
4743 * gagt_command_license()
4744 *
4745 * Print licensing terms.
4746 */
4747 static void
4748 gagt_command_license (const char *argument)
4749 {
4750 assert (argument);
4751
4752 gagt_normal_string ("This program is free software; you can redistribute it"
4753 " and/or modify it under the terms of version 2 of the"
4754 " GNU General Public License as published by the Free"
4755 " Software Foundation.\n\n");
4756
4757 gagt_normal_string ("This program is distributed in the hope that it will be"
4758 " useful, but ");
4759 gagt_standout_string ("WITHOUT ANY WARRANTY");
4760 gagt_normal_string ("; without even the implied warranty of ");
4761 gagt_standout_string ("MERCHANTABILITY");
4762 gagt_normal_string (" or ");
4763 gagt_standout_string ("FITNESS FOR A PARTICULAR PURPOSE");
4764 gagt_normal_string (". See the GNU General Public License for more"
4765 " details.\n\n");
4766
4767 gagt_normal_string ("You should have received a copy of the GNU General"
4768 " Public License along with this program; if not, write"
4769 " to the Free Software Foundation, Inc., 59 Temple"
4770 " Place, Suite 330, Boston, MA 02111-1307 USA\n\n");
4771
4772 gagt_normal_string ("Please report any bugs, omissions, or misfeatures to ");
4773 gagt_standout_string ("[email protected]");
4774 gagt_normal_string (".\n");
4775 }
4776
4777
4778 /* Glk subcommands and handler functions. */
4779 typedef const struct
4780 {
4781 const char * const command; /* Glk subcommand. */
4782 void (* const handler) (const char *argument); /* Subcommand handler. */
4783 const int takes_argument; /* Argument flag. */
4784 } gagt_command_t;
4785 typedef gagt_command_t *gagt_commandref_t;
4786
4787 static void gagt_command_summary (const char *argument);
4788 static void gagt_command_help (const char *argument);
4789
4790 static gagt_command_t GAGT_COMMAND_TABLE[] = {
4791 {"summary", gagt_command_summary, FALSE},
4792 {"script", gagt_command_script, TRUE},
4793 {"inputlog", gagt_command_inputlog, TRUE},
4794 {"readlog", gagt_command_readlog, TRUE},
4795 {"abbreviations", gagt_command_abbreviations, TRUE},
4796 {"fonts", gagt_command_fonts, TRUE},
4797 {"delays", gagt_command_delays, TRUE},
4798 {"width", gagt_command_width, FALSE},
4799 {"replacements", gagt_command_replacements, TRUE},
4800 {"statusline", gagt_command_statusline, TRUE},
4801 {"version", gagt_command_version, FALSE},
4802 {"commands", gagt_command_commands, TRUE},
4803 {"license", gagt_command_license, FALSE},
4804 {"help", gagt_command_help, TRUE},
4805 {NULL, NULL, FALSE}
4806 };
4807
4808
4809 /*
4810 * gagt_command_summary()
4811 *
4812 * Report all current Glk settings.
4813 */
4814 static void
4815 gagt_command_summary (const char *argument)
4816 {
4817 gagt_commandref_t entry;
4818 assert (argument);
4819
4820 /*
4821 * Call handlers that have status to report with an empty argument,
4822 * prompting each to print its current setting.
4823 */
4824 for (entry = GAGT_COMMAND_TABLE; entry->command; entry++)
4825 {
4826 if (entry->handler == gagt_command_summary
4827 || entry->handler == gagt_command_license
4828 || entry->handler == gagt_command_help)
4829 continue;
4830
4831 entry->handler ("");
4832 }
4833 }
4834
4835
4836 /*
4837 * gagt_command_help()
4838 *
4839 * Document the available Glk commands.
4840 */
4841 static void
4842 gagt_command_help (const char *command)
4843 {
4844 gagt_commandref_t entry, matched;
4845 assert (command);
4846
4847 if (strlen (command) == 0)
4848 {
4849 gagt_normal_string ("Glk commands are");
4850 for (entry = GAGT_COMMAND_TABLE; entry->command; entry++)
4851 {
4852 gagt_commandref_t next;
4853
4854 next = entry + 1;
4855 gagt_normal_string (next->command ? " " : " and ");
4856 gagt_standout_string (entry->command);
4857 gagt_normal_string (next->command ? "," : ".\n\n");
4858 }
4859
4860 gagt_normal_string ("Glk commands may be abbreviated, as long as"
4861 " the abbreviation is unambiguous. Use ");
4862 gagt_standout_string ("glk help");
4863 gagt_normal_string (" followed by a Glk command name for help on that"
4864 " command.\n");
4865 return;
4866 }
4867
4868 matched = NULL;
4869 for (entry = GAGT_COMMAND_TABLE; entry->command; entry++)
4870 {
4871 if (gagt_strncasecmp (command, entry->command, strlen (command)) == 0)
4872 {
4873 if (matched)
4874 {
4875 gagt_normal_string ("The Glk command ");
4876 gagt_standout_string (command);
4877 gagt_normal_string (" is ambiguous. Try ");
4878 gagt_standout_string ("glk help");
4879 gagt_normal_string (" for more information.\n");
4880 return;
4881 }
4882 matched = entry;
4883 }
4884 }
4885 if (!matched)
4886 {
4887 gagt_normal_string ("The Glk command ");
4888 gagt_standout_string (command);
4889 gagt_normal_string (" is not valid. Try ");
4890 gagt_standout_string ("glk help");
4891 gagt_normal_string (" for more information.\n");
4892 return;
4893 }
4894
4895 if (matched->handler == gagt_command_summary)
4896 {
4897 gagt_normal_string ("Prints a summary of all the current Glk AGiliTy"
4898 " settings.\n");
4899 }
4900
4901 else if (matched->handler == gagt_command_script)
4902 {
4903 gagt_normal_string ("Logs the game's output to a file.\n\nUse ");
4904 gagt_standout_string ("glk script on");
4905 gagt_normal_string (" to begin logging game output, and ");
4906 gagt_standout_string ("glk script off");
4907 gagt_normal_string (" to end it. Glk AGiliTy will ask you for a file"
4908 " when you turn scripts on.\n");
4909 }
4910
4911 else if (matched->handler == gagt_command_inputlog)
4912 {
4913 gagt_normal_string ("Records the commands you type into a game.\n\nUse ");
4914 gagt_standout_string ("glk inputlog on");
4915 gagt_normal_string (", to begin recording your commands, and ");
4916 gagt_standout_string ("glk inputlog off");
4917 gagt_normal_string (" to turn off input logs. You can play back"
4918 " recorded commands into a game with the ");
4919 gagt_standout_string ("glk readlog");
4920 gagt_normal_string (" command.\n");
4921 }
4922
4923 else if (matched->handler == gagt_command_readlog)
4924 {
4925 gagt_normal_string ("Plays back commands recorded with ");
4926 gagt_standout_string ("glk inputlog on");
4927 gagt_normal_string (".\n\nUse ");
4928 gagt_standout_string ("glk readlog on");
4929 gagt_normal_string (". Command play back stops at the end of the"
4930 " file. You can also play back commands from a"
4931 " text file created using any standard editor.\n");
4932 }
4933
4934 else if (matched->handler == gagt_command_abbreviations)
4935 {
4936 gagt_normal_string ("Controls abbreviation expansion.\n\nGlk AGiliTy"
4937 " automatically expands several standard single"
4938 " letter abbreviations for you; for example, \"x\""
4939 " becomes \"examine\". Use ");
4940 gagt_standout_string ("glk abbreviations on");
4941 gagt_normal_string (" to turn this feature on, and ");
4942 gagt_standout_string ("glk abbreviations off");
4943 gagt_normal_string (" to turn it off. While the feature is on, you"
4944 " can bypass abbreviation expansion for an"
4945 " individual game command by prefixing it with a"
4946 " single quote.\n");
4947 }
4948
4949 else if (matched->handler == gagt_command_fonts)
4950 {
4951 gagt_normal_string ("Controls the way Glk AGiliTy uses fonts.\n\n"
4952 "AGT games normally assume 80x25 monospaced font"
4953 " displays. Glk can often use proportional fonts."
4954 " To try to improve text display, Glk AGiliTy will"
4955 " attempt to automatically detect when game text"
4956 " can be displayed safely in a proportional font,"
4957 " and when fixed width fonts are required. For"
4958 " some games, however, you may need to override"
4959 " it. Use ");
4960 gagt_standout_string ("glk fonts automatic");
4961 gagt_normal_string (", ");
4962 gagt_standout_string ("glk fonts proportional");
4963 gagt_normal_string (", and ");
4964 gagt_standout_string ("glk fonts fixed");
4965 gagt_normal_string (" to switch between Glk AGiliTy font modes.\n");
4966 }
4967
4968 else if (matched->handler == gagt_command_delays)
4969 {
4970 gagt_normal_string ("Shortens, or eliminates, AGT game delays.\n\nUse ");
4971 gagt_standout_string ("glk delays full");
4972 gagt_normal_string (", ");
4973 gagt_standout_string ("glk delays short");
4974 gagt_normal_string (", or ");
4975 gagt_standout_string ("glk delays none");
4976 gagt_normal_string (". In Glk AGiliTy, you can also end an AGT game's"
4977 " delay early, by pressing Space while the game is"
4978 " delaying.\n");
4979 }
4980
4981 else if (matched->handler == gagt_command_width)
4982 {
4983 gagt_normal_string ("Prints the screen width available for fixed font"
4984 " display.\n\nEven though Glk AGiliTy tries to handle"
4985 " issues surrounding proportional font displays for"
4986 " you automatically, some game elements may still"
4987 " need to display in fixed width fonts. These"
4988 " elements will be happiest if the available screen"
4989 " width is at least 80 columns.\n");
4990 }
4991
4992 else if (matched->handler == gagt_command_replacements)
4993 {
4994 gagt_normal_string ("Controls game text scanning and replacement.\n\n"
4995 "Glk AGiliTy can monitor the game's output, and"
4996 " replace a few selected standard messages with"
4997 " equivalents, printed using a style that stands"
4998 " out better in Glk displays. Use ");
4999 gagt_standout_string ("glk replacements on");
5000 gagt_normal_string (" to turn this feature on, and ");
5001 gagt_standout_string ("glk replacements off");
5002 gagt_normal_string (" to turn it off.\n");
5003 }
5004
5005 else if (matched->handler == gagt_command_statusline)
5006 {
5007 gagt_normal_string ("Controls the Glk AGiliTy status line display.\n\n"
5008 "Use ");
5009 gagt_standout_string ("glk statusline extended");
5010 gagt_normal_string (" to display a full, two line status display, and ");
5011 gagt_standout_string ("glk statusline short");
5012 gagt_normal_string (" for a single line status display.\n");
5013 }
5014
5015 else if (matched->handler == gagt_command_version)
5016 {
5017 gagt_normal_string ("Prints the version numbers of the Glk library"
5018 " and the Glk AGiliTy port.\n");
5019 }
5020
5021 else if (matched->handler == gagt_command_commands)
5022 {
5023 gagt_normal_string ("Turn off Glk commands.\n\nUse ");
5024 gagt_standout_string ("glk commands off");
5025 gagt_normal_string (" to disable all Glk commands, including this one."
5026 " Once turned off, there is no way to turn Glk"
5027 " commands back on while inside the game.\n");
5028 }
5029
5030 else if (matched->handler == gagt_command_license)
5031 {
5032 gagt_normal_string ("Prints Glk AGiliTy's software license.\n");
5033 }
5034
5035 else if (matched->handler == gagt_command_help)
5036 gagt_command_help ("");
5037
5038 else
5039 gagt_normal_string ("There is no help available on that Glk command."
5040 " Sorry.\n");
5041 }
5042
5043
5044 /*
5045 * gagt_command_escape()
5046 *
5047 * This function is handed each input line. If the line contains a specific
5048 * Glk port command, handle it and return TRUE, otherwise return FALSE.
5049 */
5050 static int
5051 gagt_command_escape (const char *string)
5052 {
5053 int posn;
5054 char *string_copy, *command, *argument;
5055 assert (string);
5056
5057 /*
5058 * Return FALSE if the string doesn't begin with the Glk command escape
5059 * introducer.
5060 */
5061 posn = strspn (string, "\t ");
5062 if (gagt_strncasecmp (string + posn, "glk", strlen ("glk")) != 0)
5063 return FALSE;
5064
5065 /* Take a copy of the string, without any leading space or introducer. */
5066 string_copy = gagt_malloc (strlen (string + posn) + 1 - strlen ("glk"));
5067 strcpy (string_copy, string + posn + strlen ("glk"));
5068
5069 /*
5070 * Find the subcommand; the first word in the string copy. Find its end,
5071 * and ensure it terminates with a NUL.
5072 */
5073 posn = strspn (string_copy, "\t ");
5074 command = string_copy + posn;
5075 posn += strcspn (string_copy + posn, "\t ");
5076 if (string_copy[posn] != '\0')
5077 string_copy[posn++] = '\0';
5078
5079 /*
5080 * Now find any argument data for the command, ensuring it too terminates
5081 * with a NUL.
5082 */
5083 posn += strspn (string_copy + posn, "\t ");
5084 argument = string_copy + posn;
5085 posn += strcspn (string_copy + posn, "\t ");
5086 string_copy[posn] = '\0';
5087
5088 /*
5089 * Try to handle the command and argument as a Glk subcommand. If it
5090 * doesn't run unambiguously, print command usage. Treat an empty command
5091 * as "help".
5092 */
5093 if (strlen (command) > 0)
5094 {
5095 gagt_commandref_t entry, matched;
5096 int matches;
5097
5098 /*
5099 * Search for the first unambiguous table command string matching
5100 * the command passed in.
5101 */
5102 matches = 0;
5103 matched = NULL;
5104 for (entry = GAGT_COMMAND_TABLE; entry->command; entry++)
5105 {
5106 if (gagt_strncasecmp (command, entry->command, strlen (command)) == 0)
5107 {
5108 matches++;
5109 matched = entry;
5110 }
5111 }
5112
5113 /* If the match was unambiguous, call the command handler. */
5114 if (matches == 1)
5115 {
5116 gagt_normal_char ('\n');
5117 matched->handler (argument);
5118
5119 if (!matched->takes_argument && strlen (argument) > 0)
5120 {
5121 gagt_normal_string ("[The ");
5122 gagt_standout_string (matched->command);
5123 gagt_normal_string (" command ignores arguments.]\n");
5124 }
5125 }
5126
5127 /* No match, or the command was ambiguous. */
5128 else
5129 {
5130 gagt_normal_string ("\nThe Glk command ");
5131 gagt_standout_string (command);
5132 gagt_normal_string (" is ");
5133 gagt_normal_string (matches == 0 ? "not valid" : "ambiguous");
5134 gagt_normal_string (". Try ");
5135 gagt_standout_string ("glk help");
5136 gagt_normal_string (" for more information.\n");
5137 }
5138 }
5139 else
5140 {
5141 gagt_normal_char ('\n');
5142 gagt_command_help ("");
5143 }
5144
5145 /* The string contained a Glk command; return TRUE. */
5146 free (string_copy);
5147 return TRUE;
5148 }
5149
5150
5151 /*---------------------------------------------------------------------*/
5152 /* Glk port input functions */
5153 /*---------------------------------------------------------------------*/
5154
5155 /* Longest line we're going to buffer for input. */
5156 enum { GAGT_INPUTBUFFER_LENGTH = 256 };
5157
5158 /* Table of single-character command abbreviations. */
5159 typedef const struct
5160 {
5161 const char abbreviation; /* Abbreviation character. */
5162 const char * const expansion; /* Expansion string. */
5163 } gagt_abbreviation_t;
5164 typedef gagt_abbreviation_t *gagt_abbreviationref_t;
5165
5166 static gagt_abbreviation_t GAGT_ABBREVIATIONS[] = {
5167 {'c', "close"}, {'g', "again"}, {'i', "inventory"},
5168 {'k', "attack"}, {'l', "look"}, {'p', "open"},
5169 {'q', "quit"}, {'r', "drop"}, {'t', "take"},
5170 {'x', "examine"}, {'y', "yes"}, {'z', "wait"},
5171 {'\0', NULL}
5172 };
5173
5174
5175 /*
5176 * gagt_expand_abbreviations()
5177 *
5178 * Expand a few common one-character abbreviations commonly found in other
5179 * game systems, but not always normal in AGT games.
5180 */
5181 static void
5182 gagt_expand_abbreviations (char *buffer, int size)
5183 {
5184 char *command, abbreviation;
5185 const char *expansion;
5186 gagt_abbreviationref_t entry;
5187 assert (buffer);
5188
5189 /* Ignore anything that isn't a single letter command. */
5190 command = buffer + strspn (buffer, "\t ");
5191 if (!(strlen (command) == 1
5192 || (strlen (command) > 1 && isspace (command[1]))))
5193 return;
5194
5195 /* Scan the abbreviations table for a match. */
5196 abbreviation = glk_char_to_lower ((unsigned char) command[0]);
5197 expansion = NULL;
5198 for (entry = GAGT_ABBREVIATIONS; entry->expansion; entry++)
5199 {
5200 if (entry->abbreviation == abbreviation)
5201 {
5202 expansion = entry->expansion;
5203 break;
5204 }
5205 }
5206
5207 /*
5208 * If a match found, check for a fit, then replace the character with the
5209 * expansion string.
5210 */
5211 if (expansion)
5212 {
5213 if (strlen (buffer) + strlen (expansion) - 1 >= size)
5214 return;
5215
5216 memmove (command + strlen (expansion) - 1, command, strlen (command) + 1);
5217 memcpy (command, expansion, strlen (expansion));
5218
5219 gagt_standout_string ("[");
5220 gagt_standout_char (abbreviation);
5221 gagt_standout_string (" -> ");
5222 gagt_standout_string (expansion);
5223 gagt_standout_string ("]\n");
5224 }
5225 }
5226
5227
5228 /*
5229 * agt_input()
5230 *
5231 * Read a line from the keyboard, allocating space for it using malloc.
5232 * AGiliTy defines the following for the in_type argument:
5233 *
5234 * in_type: 0=command, 1=number, 2=question, 3=userstr, 4=filename,
5235 * 5=RESTART,RESTORE,UNDO,QUIT
5236 * Negative values are for internal use by the interface (i.e. this module)
5237 * and so are free to be defined by the porter.
5238 *
5239 * Since it's unclear what use we can make of this information in Glk,
5240 * for the moment the argument is ignored. It seems that no-one else
5241 * uses it, either.
5242 */
5243 char *
5244 agt_input (int in_type)
5245 {
5246 event_t event;
5247 int length;
5248 char *buffer;
5249
5250 /*
5251 * Update the current status line display, and flush any pending buffered
5252 * output. Release any suspension of delays.
5253 */
5254 gagt_status_notify ();
5255 gagt_output_flush ();
5256 gagt_delay_resume ();
5257
5258 /* Reset current x, as line input implies a newline. */
5259 curr_x = 0;
5260
5261 /* Allocate a line input buffer, allowing 256 characters and a NUL. */
5262 length = GAGT_INPUTBUFFER_LENGTH + 1;
5263 buffer = gagt_malloc (length);
5264
5265 /*
5266 * If we have an input log to read from, use that until it is exhausted.
5267 * On end of file, close the stream and resume input from line requests.
5268 */
5269 if (gagt_readlog_stream)
5270 {
5271 glui32 chars;
5272
5273 /* Get the next line from the log stream. */
5274 chars = glk_get_line_stream (gagt_readlog_stream, buffer, length);
5275 if (chars > 0)
5276 {
5277 /* Echo the line just read in input style. */
5278 glk_set_style (style_Input);
5279 glk_put_buffer (buffer, chars);
5280 glk_set_style (style_Normal);
5281
5282 /*
5283 * Convert the string from Glk's ISO 8859 Latin-1 to IBM cp 437,
5284 * add to any script, and return it.
5285 */
5286 gagt_iso_to_cp ((unsigned char *)buffer, (unsigned char *)buffer);
5287 if (script_on)
5288 textputs (scriptfile, buffer);
5289 return buffer;
5290 }
5291
5292 /*
5293 * We're at the end of the log stream. Close it, and then continue
5294 * on to request a line from Glk.
5295 */
5296 glk_stream_close (gagt_readlog_stream, NULL);
5297 gagt_readlog_stream = NULL;
5298 }
5299
5300 /* Set this up as a read buffer for the main window, and wait. */
5301 glk_request_line_event (gagt_main_window, buffer, length - 1, 0);
5302 gagt_event_wait (evtype_LineInput, &event);
5303
5304 /* Terminate the input line with a NUL. */
5305 assert (event.val1 < length);
5306 buffer[event.val1] = '\0';
5307
5308 /*
5309 * If neither abbreviations nor local commands are enabled, use the data
5310 * read above without further massaging.
5311 */
5312 if (gagt_abbreviations_enabled || gagt_commands_enabled)
5313 {
5314 char *command;
5315
5316 /*
5317 * If the first non-space input character is a quote, bypass all
5318 * abbreviation expansion and local command recognition, and use the
5319 * unadulterated input, less introductory quote.
5320 */
5321 command = buffer + strspn (buffer, "\t ");
5322 if (command[0] == '\'')
5323 {
5324 /* Delete the quote with memmove(). */
5325 memmove (command, command + 1, strlen (command));
5326 }
5327 else
5328 {
5329 /* Check for, and expand, any abbreviated commands. */
5330 if (gagt_abbreviations_enabled)
5331 gagt_expand_abbreviations (buffer, length);
5332
5333 /*
5334 * Check for standalone "help", then for Glk port special commands;
5335 * suppress the interpreter's use of this input for Glk commands.
5336 */
5337 if (gagt_commands_enabled)
5338 {
5339 int posn;
5340
5341 posn = strspn (buffer, "\t ");
5342 if (gagt_strncasecmp (buffer + posn, "help", strlen ("help"))== 0)
5343 {
5344 if (strspn (buffer + posn + strlen ("help"), "\t ")
5345 == strlen (buffer + posn + strlen ("help")))
5346 {
5347 gagt_display_register_help_request ();
5348 }
5349 }
5350
5351 if (gagt_command_escape (buffer))
5352 {
5353 gagt_display_silence_help_hints ();
5354 buffer[0] = '\0';
5355 return buffer;
5356 }
5357 }
5358 }
5359 }
5360
5361 /*
5362 * If there is an input log active, log this input string to it. Note that
5363 * by logging here we get any abbreviation expansions but we won't log glk
5364 * special commands, nor any input read from a current open input log.
5365 */
5366 if (gagt_inputlog_stream)
5367 {
5368 glk_put_string_stream (gagt_inputlog_stream, buffer);
5369 glk_put_char_stream (gagt_inputlog_stream, '\n');
5370 }
5371
5372 /*
5373 * Convert from Glk's ISO 8859 Latin-1 to IBM cp 437, and add to any script.
5374 */
5375 gagt_iso_to_cp ((unsigned char *)buffer, (unsigned char *)buffer);
5376 if (script_on)
5377 textputs (scriptfile, buffer);
5378
5379 gagt_debug ("agt_input", "in_type=%d -> '%s'", in_type, buffer);
5380 return buffer;
5381 }
5382
5383
5384 /*
5385 * agt_getkey()
5386 *
5387 * Read a single character and return it. AGiliTy defines the echo_char
5388 * argument as:
5389 *
5390 * If echo_char=1, echo character. If 0, then the character is not
5391 * required to be echoed (and ideally shouldn't be).
5392 *
5393 * However, I've found that not all other ports really do this, and in
5394 * practice it doesn't always look right. So for Glk, the character is
5395 * always echoed to the main window.
5396 */
5397 char
5398 agt_getkey (rbool echo_char)
5399 {
5400 event_t event;
5401 char buffer[3];
5402 assert (glk_stream_get_current ());
5403
5404 /*
5405 * Update the current status line display, and flush any pending buffered
5406 * output. Release any suspension of delays.
5407 */
5408 gagt_status_notify ();
5409 gagt_output_flush ();
5410 gagt_delay_resume ();
5411
5412 /* Reset current x, as echoed character input implies a newline. */
5413 curr_x = 0;
5414
5415 /*
5416 * If we have an input log to read from, use that as above until it is
5417 * exhausted. We take just the first character of a given line.
5418 */
5419 if (gagt_readlog_stream)
5420 {
5421 glui32 chars;
5422 char logbuffer[GAGT_INPUTBUFFER_LENGTH + 1];
5423
5424 /* Get the next line from the log stream. */
5425 chars = glk_get_line_stream (gagt_readlog_stream,
5426 logbuffer, sizeof (logbuffer));
5427 if (chars > 0)
5428 {
5429 /* Take just the first character, adding a newline if necessary. */
5430 buffer[0] = logbuffer[0];
5431 buffer[1] = buffer[0] == '\n' ? '\0' : '\n';
5432 buffer[2] = '\0';
5433
5434 /* Echo the character just read in input style. */
5435 glk_set_style (style_Input);
5436 glk_put_string (buffer);
5437 glk_set_style (style_Normal);
5438
5439 /*
5440 * Convert from Glk's ISO 8859 Latin-1 to IBM cp 437, add to any
5441 * script, and return the character.
5442 */
5443 gagt_iso_to_cp ((unsigned char *)buffer, (unsigned char *)buffer);
5444 if (script_on)
5445 textputs (scriptfile, buffer);
5446 return buffer[0];
5447 }
5448
5449 /*
5450 * We're at the end of the log stream. Close it, and then continue
5451 * on to request a character from Glk.
5452 */
5453 glk_stream_close (gagt_readlog_stream, NULL);
5454 gagt_readlog_stream = NULL;
5455 }
5456
5457 /*
5458 * Request a single character from main window, and wait. Ignore non-
5459 * ASCII codes that Glk returns for special function keys; we just want
5460 * one ASCII return value. (Glk does treat Return as a special key,
5461 * though, and we want to pass that back as ASCII return.)
5462 */
5463 do
5464 {
5465 glk_request_char_event (gagt_main_window);
5466 gagt_event_wait (evtype_CharInput, &event);
5467 }
5468 while (event.val1 > UCHAR_MAX && event.val1 != keycode_Return);
5469
5470 /*
5471 * Save the character into a short string buffer, converting Return
5472 * to newline, and adding a newline if not Return.
5473 */
5474 buffer[0] = event.val1 == keycode_Return ? '\n' : event.val1;
5475 buffer[1] = buffer[0] == '\n' ? '\0' : '\n';
5476 buffer[2] = '\0';
5477
5478 /* If there is an input log active, log this input string to it. */
5479 if (gagt_inputlog_stream)
5480 glk_put_string_stream (gagt_inputlog_stream, buffer);
5481
5482 /*
5483 * No matter what echo_char says, as it happens, the output doesn't look
5484 * great if we don't write out the character, and also a newline (c.f.
5485 * the "Yes/No" confirmation of the QUIT command)...
5486 */
5487 glk_set_style (style_Input);
5488 glk_put_string (buffer);
5489 glk_set_style (style_Normal);
5490
5491 /*
5492 * Convert from Glk's ISO 8859 Latin-1 to IBM cp 437, and add to any
5493 * script.
5494 */
5495 gagt_iso_to_cp ((unsigned char *)buffer, (unsigned char *)buffer);
5496 if (script_on)
5497 textputs (scriptfile, buffer);
5498
5499 gagt_debug ("agt_getkey", "echo_char=%d -> '%c'",
5500 echo_char, buffer[0] == '\n' ? '$' : buffer[0]);
5501 return buffer[0];
5502 }
5503
5504
5505 /*---------------------------------------------------------------------*/
5506 /* Glk port event functions */
5507 /*---------------------------------------------------------------------*/
5508
5509 /*
5510 * We have some clever atexit() finalizer handling for exit() calls that
5511 * come from the core interpreter. However, an exit() call could also come
5512 * from Glk; Xkill for example. To tell the difference, we'll have the
5513 * event wait functions set a flag to indicate when glk_select() is active.
5514 */
5515 static int gagt_in_glk_select = FALSE;
5516
5517 /*
5518 * gagt_event_wait_2()
5519 * gagt_event_wait()
5520 *
5521 * Process Glk events until one of the expected type, or types, arrives.
5522 * Return the event of that type.
5523 */
5524 static void
5525 gagt_event_wait_2 (glui32 wait_type_1, glui32 wait_type_2, event_t * event)
5526 {
5527 assert (event);
5528
5529 do
5530 {
5531 gagt_in_glk_select = TRUE;
5532 glk_select (event);
5533 gagt_in_glk_select = FALSE;
5534
5535 switch (event->type)
5536 {
5537 case evtype_Arrange:
5538 case evtype_Redraw:
5539 gagt_status_redraw ();
5540 break;
5541 }
5542 }
5543 while (!(event->type == wait_type_1 || event->type == wait_type_2));
5544 }
5545
5546 static void
5547 gagt_event_wait (glui32 wait_type, event_t * event)
5548 {
5549 assert (event);
5550 gagt_event_wait_2 (wait_type, evtype_None, event);
5551 }
5552
5553
5554 /*
5555 * gagt_event_in_glk_select()
5556 *
5557 * Return TRUE if we're currently awaiting an event in glk_select(). Used
5558 * by the finalizer to distinguish interpreter and glk exit() calls.
5559 */
5560 static int
5561 gagt_event_in_glk_select (void)
5562 {
5563 return gagt_in_glk_select;
5564 }
5565
5566
5567 /*---------------------------------------------------------------------*/
5568 /* Miscellaneous Glk port startup and options functions */
5569 /*---------------------------------------------------------------------*/
5570
5571 /*
5572 * Default screen height and width, and also a default status width for
5573 * use with Glk libraries that don't support separate windows.
5574 */
5575 static const int GAGT_DEFAULT_SCREEN_WIDTH = 80,
5576 GAGT_DEFAULT_SCREEN_HEIGHT = 25,
5577 GAGT_DEFAULT_STATUS_WIDTH = 76;
5578
5579
5580 /*
5581 * agt_option()
5582 *
5583 * Platform-specific setup and options handling. AGiliTy defines the
5584 * arguments and options as:
5585 *
5586 * If setflag is 0, then the option was prefixed with NO_. Return 1 if
5587 * the option is recognized.
5588 *
5589 * The Glk port has no options file handling, so none of this is
5590 * implemented here.
5591 */
5592 rbool
5593 agt_option (int optnum, char *optstr[], rbool setflag)
5594 {
5595 gagt_debug ("agt_option", "optnum=%d, optstr=%s, setflag=%d",
5596 optnum, optstr[0], setflag);
5597 return 0;
5598 }
5599
5600
5601 /*
5602 * agt_globalfile()
5603 *
5604 * Global options file handle handling. For now, this is a stub, since
5605 * there is no .agilrc for this port.
5606 */
5607 genfile
5608 agt_globalfile (int fid)
5609 {
5610 gagt_debug ("agt_globalfile", "fid=%d", fid);
5611 return badfile (fCFG);
5612 }
5613
5614
5615 /*
5616 * init_interface()
5617 *
5618 * General initialization for the module; sets some variables, and creates
5619 * the Glk windows to work in. Called from the AGiliTy main().
5620 */
5621 void
5622 init_interface (int argc, char *argv[])
5623 {
5624 glui32 status_height;
5625
5626 /*
5627 * Begin with some default values for global variables that this module
5628 * is somehow responsible for.
5629 */
5630 script_on = center_on = par_fill_on = FALSE;
5631 scriptfile = badfile (fSCR);
5632 debugfile = stderr;
5633
5634 /*
5635 * Set up AGT-specific Glk styles. This needs to be done before any Glk
5636 * window is opened.
5637 */
5638 gagt_init_user_styles ();
5639
5640 /*
5641 * Create the main game window. The main game window creation must succeed.
5642 * If it fails, we'll return, and the caller can detect this by looking
5643 * for a NULL main window.
5644 */
5645 gagt_main_window = glk_window_open (0, 0, 0, wintype_TextBuffer, 0);
5646 if (!gagt_main_window)
5647 return;
5648
5649 /*
5650 * Set the main window to be the default window, for convenience. We do
5651 * this again in glk_main() -- this call is here just in case this version
5652 * of init_interface() is ever called by AGiliTy's main.
5653 */
5654 glk_set_window (gagt_main_window);
5655
5656 /*
5657 * Screen height is something we don't use. Linux Xglk returns dimensions
5658 * of 0x0 for text buffer windows, so we can't measure the main window
5659 * height anyway. But... the height does come into play in AGiliTy's
5660 * agil.c, when the interpreter is deciding how to output game titles, and
5661 * how much of its own subsequent verbiage to output. This gives us a
5662 * problem, since this "verbiage" is stuff we look for and replace with
5663 * our own special text. So... sigh, set 25, and try to cope in the
5664 * special text we've set up with all the variations that ensue.
5665 *
5666 * Screen width does get used, but so, so many games, and for that matter
5667 * the interpreter itself, assume 80 chars, so it's simplest just to set,
5668 * and keep, this, and put up with the minor odd effects (making it match
5669 * status_width, or making it something like MAX_INT to defeat the game's
5670 * own wrapping, gives a lot of odder effects, trust me on this one...).
5671 */
5672 screen_width = GAGT_DEFAULT_SCREEN_WIDTH;
5673 screen_height = GAGT_DEFAULT_SCREEN_HEIGHT;
5674
5675 /*
5676 * Create a status window, with one or two lines as selected by user
5677 * options or flags. We can live without a status window if we have to.
5678 */
5679 status_height = gagt_extended_status_enabled ? 2 : 1;
5680 glk_stylehint_set (wintype_TextGrid, style_User1, stylehint_ReverseColor, 1);
5681 gagt_status_window = glk_window_open (gagt_main_window,
5682 winmethod_Above | winmethod_Fixed,
5683 status_height, wintype_TextGrid, 0);
5684 if (gagt_status_window)
5685 {
5686 /*
5687 * Call gagt_status_redraw() to set the interpreter's status_width
5688 * variable initial value.
5689 */
5690 gagt_status_redraw ();
5691 }
5692 else
5693 {
5694 /*
5695 * No status window, so set a suitable default status width. In this
5696 * case, we're using a value four characters less than the set screen
5697 * width. AGiliTy's status line code will fill to this width with
5698 * justified text, and we add two characters of bracketing when
5699 * displaying status lines for Glks that don't support separate windows,
5700 * making a total of 78 characters, which should be fairly standard.
5701 */
5702 status_width = GAGT_DEFAULT_STATUS_WIDTH;
5703 }
5704
5705 agt_clrscr ();
5706 gagt_debug ("init_interface", "argc=%d, argv=%p", argc, argv);
5707 }
5708
5709
5710 /*---------------------------------------------------------------------*/
5711 /* Replacement interface.c functions */
5712 /*---------------------------------------------------------------------*/
5713
5714 /* Get_user_file() type codes. */
5715 enum {
5716 AGT_SCRIPT = 0,
5717 AGT_SAVE = 1,
5718 AGT_RESTORE = 2,
5719 AGT_LOG_READ = 3,
5720 AGT_LOG_WRITE = 4
5721 };
5722
5723 /* Longest acceptable filename. */
5724 enum { GAGT_MAX_PATH = 1024 };
5725
5726
5727 #ifdef GLK_ANSI_ONLY
5728 /*
5729 * gagt_confirm()
5730 *
5731 * Print a confirmation prompt, and read a single input character, taking
5732 * only [YyNn] input. If the character is 'Y' or 'y', return TRUE.
5733 *
5734 * This function is only required for the ANSI version of get_user_file().
5735 */
5736 static int
5737 gagt_confirm (const char *prompt)
5738 {
5739 event_t event;
5740 unsigned char response;
5741 assert (prompt);
5742
5743 /*
5744 * Print the confirmation prompt, in a style that hints that it's from the
5745 * interpreter, not the game.
5746 */
5747 gagt_standout_string (prompt);
5748
5749 /* Wait for a single 'Y' or 'N' character response. */
5750 response = ' ';
5751 do
5752 {
5753 glk_request_char_event (gagt_main_window);
5754 gagt_event_wait (evtype_CharInput, &event);
5755
5756 if (event.val1 <= UCHAR_MAX)
5757 response = glk_char_to_upper (event.val1);
5758 }
5759 while (!(response == 'Y' || response == 'N'));
5760
5761 /* Echo the confirmation response, and a blank line. */
5762 glk_set_style (style_Input);
5763 glk_put_string (response == 'Y' ? "Yes" : "No");
5764 glk_set_style (style_Normal);
5765 glk_put_string ("\n");
5766
5767 return response == 'Y';
5768 }
5769 #endif
5770
5771
5772 /*
5773 * gagt_get_user_file()
5774 *
5775 * Alternative versions of functions to get a file name from the user, and
5776 * return a file stream structure. These functions are front-ended by the
5777 * main get_user_file() function, which first converts the AGT file type
5778 * into Glk usage and filemode, and also a mode for fopen()/fdopen().
5779 *
5780 * The ANSI version of the function prompts for the file using the simple
5781 * method of querying the user through input in the main window. It then
5782 * constructs a file stream around the path entered, and returns it.
5783 *
5784 * The non-ANSI, Glk version is more sneaky. It prompts for a file using
5785 * Glk's functions to get filenames by prompt, file selection dialog, or
5786 * whatever. Then it attempts to uncover which file descriptor Glk opened
5787 * its file on, dup's it, closes the Glk stream, and returns a file stream
5788 * built on this file descriptor. This is all highly non-ANSI, requiring
5789 * dup() and fdopen(), and making some assumptions about the way that dup,
5790 * open, and friends work. It works on Linux, and on Mac (CodeWarrior).
5791 * It may also work for you, but if it doesn't, or if your system lacks
5792 * things like dup or fdopen, define GLK_ANSI_ONLY and use the safe version.
5793 *
5794 * If GLKUNIX_FILEREF_GET_FILENAME is defined, non-ansi version calls
5795 * glkunix_fileref_get_filename() instead, and opens a file the highly
5796 * portable way, but still with a Glkily nice prompt dialog.
5797 */
5798 #ifdef GLK_ANSI_ONLY
5799 static genfile
5800 gagt_get_user_file (glui32 usage, glui32 fmode, const char *fdtype)
5801 {
5802 char filepath[GAGT_MAX_PATH];
5803 event_t event;
5804 int index, all_spaces;
5805 genfile retfile;
5806 assert (fdtype);
5807
5808 /* Prompt in a similar way to Glk. */
5809 switch (usage)
5810 {
5811 case fileusage_SavedGame:
5812 gagt_normal_string ("Enter saved game");
5813 break;
5814
5815 case fileusage_Transcript:
5816 gagt_normal_string ("Enter transcript file");
5817 break;
5818
5819 case fileusage_InputRecord:
5820 gagt_normal_string ("Enter command record file");
5821 break;
5822 }
5823 switch (fmode)
5824 {
5825 case filemode_Read:
5826 gagt_normal_string (" to load: ");
5827 break;
5828
5829 case filemode_Write:
5830 gagt_normal_string (" to store: ");
5831 break;
5832 }
5833
5834 /* Get the path to the file from the user. */
5835 glk_request_line_event (gagt_main_window, filepath, sizeof (filepath) - 1, 0);
5836 gagt_event_wait (evtype_LineInput, &event);
5837
5838 /* Terminate the file path with a NUL. */
5839 assert (event.val1 < sizeof (filepath));
5840 filepath[event.val1] = '\0';
5841
5842 /* Reject file paths that only contain any whitespace characters. */
5843 all_spaces = TRUE;
5844 for (index = 0; index < strlen (filepath); index++)
5845 {
5846 if (!isspace (filepath[index]))
5847 {
5848 all_spaces = FALSE;
5849 break;
5850 }
5851 }
5852 if (all_spaces)
5853 return badfile (fSAV);
5854
5855 /* Confirm overwrite of any existing file. */
5856 if (fmode == filemode_Write)
5857 {
5858 genfile file;
5859
5860 file = fopen (filepath, "r");
5861 if (file)
5862 {
5863 fclose (file);
5864
5865 if (!gagt_confirm ("Overwrite existing file? [y/n] "))
5866 return badfile (fSAV);
5867 }
5868 }
5869
5870 /* Open and return a FILE* stream, or badfile if this fails. */
5871 retfile = fopen (filepath, fdtype);
5872 return retfile ? retfile : badfile (fSAV);
5873 }
5874 #endif
5875
5876 #ifndef GLK_ANSI_ONLY
5877 static genfile
5878 gagt_get_user_file (glui32 usage, glui32 fmode, const char *fdtype)
5879 {
5880 frefid_t fileref;
5881 strid_t stream;
5882 int tryfd, glkfd, dupfd, retfd;
5883 genfile retfile;
5884 assert (fdtype);
5885
5886 /* Try to get a Glk file reference with these attributes. */
5887 fileref = glk_fileref_create_by_prompt (usage, fmode, 0);
5888 if (!fileref)
5889 return badfile (fSAV);
5890
5891 /*
5892 * Reject the file reference if we're expecting to read from it,
5893 * and the referenced file doesn't exist.
5894 */
5895 if (fmode == filemode_Read && !glk_fileref_does_file_exist (fileref))
5896 {
5897 glk_fileref_destroy (fileref);
5898 return badfile (fSAV);
5899 }
5900
5901 /*
5902 * Now, it gets ugly. Glk assumes that the interpreter will do all of
5903 * its reading and writing using the Glk streams read/write functions.
5904 * It won't; at least, not without major surgery. So here we're going
5905 * to do some dangerous stuff...
5906 *
5907 * Since a Glk stream is opaque, it's hard to tell what the underlying
5908 * file descriptor is for it. We can get it if we want to play around
5909 * in the internals of the strid_t structure, but it's unpleasant.
5910 * The alternative is, arguably, no more pleasant, but it makes for
5911 * (perhaps) more portable code. What we'll do is to dup a file, then
5912 * immediately close it, and call glk_stream_open_file(). The open()
5913 * in glk_stream_open_file() will return the same file descriptor number
5914 * that we just close()d (in theory...). This makes the following two
5915 * major assumptions:
5916 *
5917 * 1) glk_stream_open_file() opens precisely one file with open()
5918 * 2) open() always uses the lowest available file descriptor number,
5919 * like dup()
5920 *
5921 * Believe it or not, this is better than the alternatives. There is
5922 * no Glk function to return the filename from a frefid_t, and it
5923 * moves about in different Glk libraries so we can't just take it
5924 * from a given offset. And there is no Glk function to return the
5925 * underlying file descriptor or FILE* from a Glk stream either. :-(
5926 */
5927
5928 #ifdef GLKUNIX_FILEREF_GET_FILENAME
5929 retfile = fopen(glkunix_fileref_get_filename(fileref), fdtype);
5930 #else
5931
5932 /* So, start by dup()'ing the first file descriptor we can, ... */
5933 glkfd = -1;
5934 for (tryfd = 0; tryfd < FD_SETSIZE; tryfd++)
5935 {
5936 glkfd = fcntl (tryfd, F_DUPFD, 0);
5937 if (glkfd != -1)
5938 break;
5939 }
5940 if (tryfd >= FD_SETSIZE)
5941 {
5942 glk_fileref_destroy (fileref);
5943 return badfile (fSAV);
5944 }
5945
5946 /* ...then closing it, ... */
5947 close (glkfd);
5948
5949 /* ...now open the Glk stream, assuming it opens on file 'glkfd', ... */
5950 stream = glk_stream_open_file (fileref, fmode, 0);
5951 if (!stream)
5952 {
5953 glk_fileref_destroy (fileref);
5954 return badfile (fSAV);
5955 }
5956
5957 /* ...dup() the Glk file onto another file descriptor, ... */
5958 dupfd = fcntl (glkfd, F_DUPFD, 0);
5959 assert (dupfd != -1);
5960
5961 /* ...close and destroy the Glk edifice for this file, ... */
5962 glk_stream_close (stream, NULL);
5963 glk_fileref_destroy (fileref);
5964
5965 /* ...for neatness, dup() back to the old Glk file descriptor, ... */
5966 retfd = fcntl (dupfd, F_DUPFD, 0);
5967 assert (retfd != -1 && retfd == glkfd);
5968 close (dupfd);
5969
5970 /* ...and finally, open a FILE* stream onto the return descriptor. */
5971 retfile = fdopen (retfd, fdtype);
5972 if (!retfile)
5973 return badfile (fSAV);
5974 #endif /* GLKUNIX_FILEREF_GET_FILENAME */
5975
5976 /*
5977 * The result of all of this should now be that retfile is a FILE* wrapper
5978 * round a file descriptor open on a file indicated by the user through Glk.
5979 * Return it.
5980 */
5981 return retfile;
5982 }
5983 #endif
5984
5985
5986 /*
5987 * get_user_file()
5988 *
5989 * Get a file name from the user, and return the file stream structure.
5990 * This is a front-end to ANSI and non-ANSI variants of the function.
5991 */
5992 genfile
5993 get_user_file (int type)
5994 {
5995 glui32 usage = 0, fmode = 0;
5996 char *fdtype;
5997 genfile retfile;
5998
5999 gagt_output_flush ();
6000
6001 /* Map AGiliTy type to Glk usage and filemode. */
6002 switch (type)
6003 {
6004 case AGT_SCRIPT:
6005 usage = fileusage_Transcript;
6006 fmode = filemode_Write;
6007 break;
6008
6009 case AGT_SAVE:
6010 usage = fileusage_SavedGame;
6011 fmode = filemode_Write;
6012 break;
6013
6014 case AGT_RESTORE:
6015 usage = fileusage_SavedGame;
6016 fmode = filemode_Read;
6017 break;
6018
6019 case AGT_LOG_READ:
6020 usage = fileusage_InputRecord;
6021 fmode = filemode_Read;
6022 break;
6023
6024 case AGT_LOG_WRITE:
6025 usage = fileusage_InputRecord;
6026 fmode = filemode_Write;
6027 break;
6028
6029 default:
6030 gagt_fatal ("GLK: Unknown file type encountered");
6031 gagt_exit ();
6032 }
6033
6034 /* From these, determine a mode type for the f[d]open() call. */
6035 if (fmode == filemode_Write)
6036 fdtype = usage == fileusage_SavedGame ? "wb" : "w";
6037 else
6038 fdtype = usage == fileusage_SavedGame ? "rb" : "r";
6039
6040 /* Get a file stream from these using the appropriate function. */
6041 retfile = gagt_get_user_file (usage, fmode, fdtype);
6042
6043 gagt_debug ("get_user_file", "type=%d -> %p", type, retfile);
6044 return retfile;
6045 }
6046
6047
6048 /*
6049 * set_default_filenames()
6050 *
6051 * Set defaults for last save, log, and script filenames.
6052 */
6053 void
6054 set_default_filenames (fc_type fc)
6055 {
6056 /*
6057 * There is nothing to do in this function, since Glk has its own ideas on
6058 * default names for files obtained with a prompt.
6059 */
6060 gagt_debug ("set_default_filenames", "fc=%p", fc);
6061 }
6062
6063
6064 /*---------------------------------------------------------------------*/
6065 /* Functions intercepted by link-time wrappers */
6066 /*---------------------------------------------------------------------*/
6067
6068 /*
6069 * __wrap_toupper()
6070 * __wrap_tolower()
6071 *
6072 * Wrapper functions around toupper(), tolower(), and fatal(). The Linux
6073 * linker's --wrap option will convert calls to mumble() to __wrap_mumble()
6074 * if we give it the right options. We'll use this feature to translate
6075 * all toupper() and tolower() calls in the interpreter code into calls to
6076 * Glk's versions of these functions.
6077 *
6078 * It's not critical that we do this. If a linker, say a non-Linux one,
6079 * won't do --wrap, then just do without it. It's unlikely that there
6080 * will be much noticeable difference.
6081 */
6082 int
6083 __wrap_toupper (int ch)
6084 {
6085 unsigned char uch;
6086
6087 uch = glk_char_to_upper ((unsigned char) ch);
6088 return (int) uch;
6089 }
6090
6091 int
6092 __wrap_tolower (int ch)
6093 {
6094 unsigned char lch;
6095
6096 lch = glk_char_to_lower ((unsigned char) ch);
6097 return (int) lch;
6098 }
6099
6100
6101 /*---------------------------------------------------------------------*/
6102 /* Replacements for AGiliTy main() and options parsing */
6103 /*---------------------------------------------------------------------*/
6104
6105 /* External declaration of interface.c's set default options function. */
6106 extern void set_default_options (void);
6107
6108 /*
6109 * The following values need to be passed between the startup_code and main
6110 * functions.
6111 */
6112 static int gagt_saved_argc = 0; /* Recorded argc. */
6113 static char **gagt_saved_argv = NULL, /* Recorded argv. */
6114 *gagt_gamefile = NULL, /* Name of game file. */
6115 *gagt_game_message = NULL; /* Error message. */
6116
6117 /*
6118 * Flag to set if we want to test for a clean exit. Without this it's a
6119 * touch tricky sometimes to corner AGiliTy into calling exit() for us; it
6120 * tends to require a broken game file.
6121 */
6122 static int gagt_clean_exit_test = FALSE;
6123
6124
6125 /*
6126 * gagt_parse_option()
6127 *
6128 * Glk-ified version of AGiliTy's parse_options() function. In practice,
6129 * because Glk has got to them first, most options that come in here are
6130 * probably going to be single-character ones, since this is what we told
6131 * Glk in the arguments structure above. The Glk font control and other
6132 * special tweaky flags will probably be the only multiple-character ones.
6133 */
6134 static int
6135 gagt_parse_option (const char *option)
6136 {
6137 unsigned int index;
6138 assert (option);
6139
6140 assert (option[0] == '-');
6141 for (index = 1; option[index]; index++)
6142 {
6143 switch (option[index])
6144 {
6145 case 'g':
6146 switch (option[++index])
6147 {
6148 case 'f':
6149 gagt_font_mode = FONT_FIXED_WIDTH;
6150 break;
6151 case 'p':
6152 gagt_font_mode = FONT_PROPORTIONAL;
6153 break;
6154 case 'a':
6155 gagt_font_mode = FONT_AUTOMATIC;
6156 break;
6157 case 'd':
6158 gagt_delay_mode = DELAY_FULL;
6159 break;
6160 case 'h':
6161 gagt_delay_mode = DELAY_SHORT;
6162 break;
6163 case 'n':
6164 gagt_delay_mode = DELAY_OFF;
6165 break;
6166 case 'r':
6167 gagt_replacement_enabled = FALSE;
6168 break;
6169 case 'x':
6170 gagt_abbreviations_enabled = FALSE;
6171 break;
6172 case 's':
6173 gagt_extended_status_enabled = TRUE;
6174 break;
6175 case 'l':
6176 gagt_extended_status_enabled = FALSE;
6177 break;
6178 case 'c':
6179 gagt_commands_enabled = FALSE;
6180 break;
6181 case 'D':
6182 DEBUG_OUT = TRUE;
6183 break;
6184 case '#':
6185 gagt_clean_exit_test = TRUE;
6186 break;
6187 default:
6188 return FALSE;
6189 }
6190 break;
6191
6192 case 'p':
6193 debug_parse = TRUE;
6194 break;
6195 case 'a':
6196 DEBUG_DISAMBIG = TRUE;
6197 break;
6198 case 'd':
6199 DEBUG_AGT_CMD = TRUE;
6200 break;
6201 case 'x':
6202 DEBUG_EXEC_VERB = TRUE;
6203 break;
6204 case 's':
6205 DEBUG_SMSG = TRUE;
6206 break;
6207 #ifdef MEM_INFO
6208 case 'M':
6209 DEBUG_MEM = TRUE;
6210 break;
6211 #endif
6212 case 'm':
6213 descr_maxmem = 0;
6214 break;
6215 case 't':
6216 BATCH_MODE = TRUE;
6217 break;
6218 case 'c':
6219 make_test = TRUE;
6220 break;
6221 case '1':
6222 irun_mode = TRUE;
6223 break;
6224 #ifdef OPEN_FILE_AS_TEXT
6225 case 'b':
6226 open_as_binary = TRUE;
6227 break;
6228 #endif
6229
6230 case '?':
6231 default:
6232 return FALSE;
6233 }
6234 }
6235
6236 return TRUE;
6237 }
6238
6239
6240 /*
6241 * gagt_startup_code()
6242 * gagt_main()
6243 *
6244 * Together, these functions take the place of the original AGiliTy main().
6245 * The first one is called from glkunix_startup_code(), to parse and
6246 * generally handle options. The second is called from glk_main(), and
6247 * does the real work of running the game.
6248 */
6249 static int
6250 gagt_startup_code (int argc, char *argv[])
6251 {
6252 int argv_index;
6253
6254 /*
6255 * Before doing anything else, stash argc and argv away for use by
6256 * gagt_main() below.
6257 */
6258 gagt_saved_argc = argc;
6259 gagt_saved_argv = argv;
6260
6261 /* Make the mandatory call for initialization. */
6262 set_default_options ();
6263
6264 /* Handle command line arguments. */
6265 for (argv_index = 1;
6266 argv_index < argc && argv[argv_index][0] == '-'; argv_index++)
6267 {
6268 /*
6269 * Handle an option string coming after "-". If the options parse
6270 * fails, return FALSE.
6271 */
6272 if (!gagt_parse_option (argv[argv_index]))
6273 return FALSE;
6274 }
6275
6276 /*
6277 * Get the name of the game file. Since we need this in our call from
6278 * glk_main, we need to keep it in a module static variable. If the game
6279 * file name is omitted, then here we'll set the pointer to NULL, and
6280 * complain about it later in main. Passing the message string around
6281 * like this is a nuisance...
6282 */
6283 if (argv_index == argc - 1)
6284 {
6285 gagt_gamefile = argv[argv_index];
6286 gagt_game_message = NULL;
6287 #ifdef GARGLK
6288 char *s;
6289 s = strrchr(gagt_gamefile, '\\');
6290 if (s) garglk_set_story_name(s+1);
6291 s = strrchr(gagt_gamefile, '/');
6292 if (s) garglk_set_story_name(s+1);
6293 #endif /* GARGLK */
6294 }
6295 else
6296 {
6297 gagt_gamefile = NULL;
6298 if (argv_index < argc - 1)
6299 gagt_game_message = "More than one game file was given"
6300 " on the command line.";
6301 else
6302 gagt_game_message = "No game file was given on the command line.";
6303 }
6304
6305 /* All startup options were handled successfully. */
6306 return TRUE;
6307 }
6308
6309 static void
6310 gagt_main (void)
6311 {
6312 fc_type fc;
6313 assert (gagt_saved_argc != 0 && gagt_saved_argv);
6314
6315 /* Ensure AGiliTy internal types have the right sizes. */
6316 if (sizeof (integer) < 2 || sizeof (int32) < 4 || sizeof (uint32) < 4)
6317 {
6318 gagt_fatal ("GLK: Types sized incorrectly, recompilation is needed");
6319 gagt_exit ();
6320 }
6321
6322 /*
6323 * Initialize the interface. As it happens, init_interface() is in our
6324 * module here (above), and ignores argc and argv, but since the main() in
6325 * AGiliTy passes them, we'll do so here, just in case we ever want to go
6326 * back to using AGiliTy's main() function.
6327 *
6328 * init_interface() can fail if there is a problem creating the main
6329 * window. As it doesn't return status, we have to detect this by checking
6330 * that gagt_main_window is not NULL.
6331 */
6332 init_interface (gagt_saved_argc, gagt_saved_argv);
6333 if (!gagt_main_window)
6334 {
6335 gagt_fatal ("GLK: Can't open main window");
6336 gagt_exit ();
6337 }
6338 glk_window_clear (gagt_main_window);
6339 glk_set_window (gagt_main_window);
6340 glk_set_style (style_Normal);
6341
6342 /* If there's a problem with the game file, complain now. */
6343 if (!gagt_gamefile)
6344 {
6345 assert (gagt_game_message);
6346 if (gagt_status_window)
6347 glk_window_close (gagt_status_window, NULL);
6348 gagt_header_string ("Glk AGiliTy Error\n\n");
6349 gagt_normal_string (gagt_game_message);
6350 gagt_normal_char ('\n');
6351 gagt_exit ();
6352 }
6353
6354 /*
6355 * Create a game file context, and try to ensure it will open successfully
6356 * in run_game().
6357 */
6358 fc = init_file_context (gagt_gamefile, fDA1);
6359 errno = 0;
6360 if (!(gagt_workround_fileexist (fc, fAGX)
6361 || gagt_workround_fileexist (fc, fDA1)))
6362 {
6363 if (gagt_status_window)
6364 glk_window_close (gagt_status_window, NULL);
6365 gagt_header_string ("Glk AGiliTy Error\n\n");
6366 gagt_normal_string ("Can't find or open game '");
6367 gagt_normal_string (gagt_gamefile);
6368 gagt_normal_char ('\'');
6369 if (errno != 0)
6370 {
6371 gagt_normal_string (": ");
6372 gagt_normal_string (strerror (errno));
6373 }
6374 gagt_normal_char ('\n');
6375 gagt_exit ();
6376 }
6377
6378 /*
6379 * Run the game interpreter in AGiliTy. run_game() releases the file
6380 * context, so we don't have to, don't want to, and shouldn't.
6381 */
6382 run_game (fc);
6383
6384 /*
6385 * Handle any updated status, and flush all remaining buffered output;
6386 * this also frees all malloc'ed memory in the buffers.
6387 */
6388 gagt_status_notify ();
6389 gagt_output_flush ();
6390
6391 /*
6392 * Free any temporary memory that may have been used by status line
6393 * functions.
6394 */
6395 gagt_status_cleanup ();
6396
6397 /* Close any open transcript, input log, and/or read log. */
6398 if (gagt_transcript_stream)
6399 {
6400 glk_stream_close (gagt_transcript_stream, NULL);
6401 gagt_transcript_stream = NULL;
6402 }
6403 if (gagt_inputlog_stream)
6404 {
6405 glk_stream_close (gagt_inputlog_stream, NULL);
6406 gagt_inputlog_stream = NULL;
6407 }
6408 if (gagt_readlog_stream)
6409 {
6410 glk_stream_close (gagt_readlog_stream, NULL);
6411 gagt_readlog_stream = NULL;
6412 }
6413 }
6414
6415
6416 /*---------------------------------------------------------------------*/
6417 /* Linkage between Glk entry/exit calls and the AGiliTy interpreter */
6418 /*---------------------------------------------------------------------*/
6419
6420 /*
6421 * Safety flags, to ensure we always get startup before main, and that
6422 * we only get a call to main once.
6423 */
6424 static int gagt_startup_called = FALSE,
6425 gagt_main_called = FALSE;
6426
6427 /*
6428 * We try to catch calls to exit() from the interpreter, and redirect them
6429 * to glk_exit(). To help tell these calls from a call to exit() from
6430 * glk_exit() itself, we need to monitor when interpreter code is running,
6431 * and when not.
6432 */
6433 static int gagt_agility_running = FALSE;
6434
6435
6436 /*
6437 * gagt_finalizer()
6438 *
6439 * ANSI atexit() handler. This is the first part of trying to catch and re-
6440 * direct the calls the core AGiliTy interpreter makes to exit() -- we really
6441 * want it to call glk_exit(), but it's hard to achieve. There are three
6442 * basic approaches possible, and all have drawbacks:
6443 *
6444 * o #define exit to gagt_something, and provide the gagt_something()
6445 * function. This type of macro definition is portable for the most
6446 * part, but tramples the code badly, and messes up the build of the
6447 * non-interpreter "support" binaries.
6448 * o Use ld's --wrap to wrapper exit. This only works with Linux's linker
6449 * and so isn't at all portable.
6450 * o Register an exit handler with atexit(), and try to cope in it after
6451 * exit() has been called.
6452 *
6453 * Here we try the last of these. The one sticky part of it is that in our
6454 * exit handler we'll want to call glk_exit(), which will in all likelihood
6455 * call exit(). And multiple calls to exit() from a program are "undefined".
6456 *
6457 * In practice, C runtimes tend to do one of three things: they treat the
6458 * exit() call from the exit handler as if it was a return; they recurse
6459 * indefinitely through the hander; or they do something ugly (abort, for
6460 * example). The first of these is fine, ideal in fact, and seems to be the
6461 * Linux and SVR4 behavior. The second we can avoid with a flag. The last
6462 * is the problem case, seen only with SVR3 (and even then, it occurs only
6463 * on program exit, after everything's cleaned up, and for that matter only
6464 * on abnormal exit).
6465 *
6466 * Note that here we're not expecting to get a call to this routine, and if
6467 * we do, and interpreter code is still running, it's a sign that we need
6468 * to take actions we'd hoped not to have to take.
6469 */
6470 static void
6471 gagt_finalizer (void)
6472 {
6473 /*
6474 * If interpreter code is still active, and we're not in a glk_select(),
6475 * the core interpreter code called exit(). Handle cleanup.
6476 */
6477 if (gagt_agility_running && !gagt_event_in_glk_select ())
6478 {
6479 event_t event;
6480
6481 /*
6482 * If we have a main window, try to update status (which may go to the
6483 * status window, or to the main window) and flush any pending buffered
6484 * output.
6485 */
6486 if (gagt_main_window)
6487 {
6488 gagt_status_notify ();
6489 gagt_output_flush ();
6490 }
6491
6492 /*
6493 * Clear the flag to avoid recursion, and call glk_exit() to clean up
6494 * Glk and terminate. This is the call that probably re-calls exit(),
6495 * and thus prods "undefined" bits of the C runtime, so we'll make it
6496 * configurable and overrideable for problem cases.
6497 */
6498 gagt_agility_running = FALSE;
6499
6500 #ifdef GARGLK
6501 return;
6502 #endif /* GARGLK */
6503
6504 #ifndef GLK_CLEAN_EXIT
6505 if (!getenv ("GLKAGIL_CLEAN_EXIT"))
6506 {
6507 glk_exit ();
6508 return;
6509 }
6510 #endif
6511
6512 /*
6513 * We've decided not to take the dangerous route.
6514 *
6515 * In that case, providing we have a main window, fake a Glk-like-ish
6516 * hit-any-key-and-wait message using a simple string in the main
6517 * window. Not great, but usable where we're forced into bypassing
6518 * glk_exit(). If we have no main window, there's no point in doing
6519 * anything more.
6520 */
6521 if (gagt_main_window)
6522 {
6523 glk_cancel_char_event (gagt_main_window);
6524 glk_cancel_line_event (gagt_main_window, NULL);
6525
6526 glk_set_style (style_Alert);
6527 glk_put_string ("\n\nHit any key to exit.\n");
6528 glk_request_char_event (gagt_main_window);
6529 gagt_event_wait (evtype_CharInput, &event);
6530 }
6531 }
6532 }
6533
6534
6535 /*
6536 * gagt_exit()
6537 *
6538 * Glk_exit() local wrapper. This is the second part of trying to catch
6539 * and redirect calls to exit(). Glk_finalizer() above needs to know that
6540 * we called glk_exit() already from here, so it doesn't try to do it again.
6541 */
6542 static void
6543 gagt_exit (void)
6544 {
6545 assert (gagt_agility_running);
6546
6547 /*
6548 * Clear the running flag to neutralize gagt_finalizer(), throw out any
6549 * buffered output data, and then call the real glk_exit().
6550 */
6551 gagt_agility_running = FALSE;
6552 gagt_output_delete ();
6553 glk_exit ();
6554 }
6555
6556
6557 /*
6558 * __wrap_exit()
6559 *
6560 * Exit() wrapper where a linker does --wrap. This is the third part of
6561 * trying to catch and redirect calls to exit().
6562 *
6563 * This function is for use only with IFP, and avoids a nasty attempt at
6564 * reusing a longjmp buffer. IFP will redirect calls to exit() into
6565 * glk_exit() as a matter of course. It also handles atexit(), and we've
6566 * registered a function with atexit() that calls glk_exit(), and
6567 * IFP redirects glk_exit() to be an effective return from glk_main(). At
6568 * that point it calls finalizers. So without doing something special for
6569 * IFP, we'll find ourselves calling glk_exit() twice -- once as the IFP
6570 * redirected exit(), and once from our finalizer. Two returns from the
6571 * function glk_main() is a recipe for unpleasantness.
6572 *
6573 * As IFP is Linux-only, at present, --wrap will always be available to IFP
6574 * plugin builds. So here, we'll wrap exit() before IFP can get to it, and
6575 * handle it safely. For non-IFP/non-wrap links, this is just an unused
6576 * function definition, and can be safely ignored...
6577 */
6578 void
6579 __wrap_exit (int status)
6580 {
6581 assert (gagt_agility_running);
6582
6583 /*
6584 * In an IFP plugin, only the core interpreter code could have called exit()
6585 * here -- we don't, and IFP redirects glk_exit(), the only other potential
6586 * caller of exit(). (It also redirects exit() if we don't get to it here
6587 * first.)
6588 *
6589 * So, if we have a main window, flush it. This is the same cleanup as
6590 * done by the finalizer.
6591 */
6592 if (gagt_main_window)
6593 {
6594 gagt_status_notify ();
6595 gagt_output_flush ();
6596 }
6597
6598 /* Clear the running flag, and transform exit() into a glk_exit(). */
6599 gagt_agility_running = FALSE;
6600 glk_exit ();
6601 }
6602
6603
6604 /*
6605 * glk_main()
6606 *
6607 * Main entry point for Glk. Here, all startup is done, and we call our
6608 * function to run the game.
6609 */
6610 void
6611 glk_main (void)
6612 {
6613 assert (gagt_startup_called && !gagt_main_called);
6614 gagt_main_called = TRUE;
6615
6616 /*
6617 * Register gagt_finalizer() with atexit() to cleanup on exit. Note that
6618 * this module doesn't expect the atexit() handler to be called on all
6619 * forms of exit -- see comments in gagt_finalizer() for more.
6620 */
6621 if (atexit (gagt_finalizer) != 0)
6622 {
6623 gagt_fatal ("GLK: Failed to register finalizer");
6624 gagt_exit ();
6625 }
6626
6627 /*
6628 * If we're testing for a clean exit, deliberately call exit() to see what
6629 * happens. We're hoping for a clean process termination, but our exit
6630 * code explores "undefined" ANSI. If we get something ugly, like a core
6631 * dump, we'll want to set GLK[AGIL]_CLEAN_EXIT.
6632 */
6633 if (gagt_clean_exit_test)
6634 {
6635 gagt_agility_running = TRUE;
6636 exit (0);
6637 }
6638
6639 /*
6640 * The final part of trapping exit(). Set the running flag, and call the
6641 * interpreter main function. Clear the flag when the main function returns.
6642 */
6643 gagt_agility_running = TRUE;
6644 gagt_main ();
6645 gagt_agility_running = FALSE;
6646 }
6647
6648
6649 /*---------------------------------------------------------------------*/
6650 /* Glk linkage relevant only to the UNIX platform */
6651 /*---------------------------------------------------------------------*/
6652 #if defined(__unix) || defined(GARGLK)
6653
6654 #include "glkstart.h"
6655
6656 /*
6657 * Glk arguments for UNIX versions of the Glk interpreter.
6658 */
6659 glkunix_argumentlist_t glkunix_arguments[] = {
6660 {(char *) "-gf", glkunix_arg_NoValue,
6661 (char *) "-gf Force Glk to use only a fixed width font"},
6662 {(char *) "-gp", glkunix_arg_NoValue,
6663 (char *) "-gp Allow Glk to use only a proportional font"},
6664 {(char *) "-ga", glkunix_arg_NoValue,
6665 (char *) "-ga Try to use a suitable Glk font automatically"},
6666 {(char *) "-gd", glkunix_arg_NoValue,
6667 (char *) "-gd Delay for the full period in Glk"},
6668 {(char *) "-gh", glkunix_arg_NoValue,
6669 (char *) "-gh Delay for approximately half the period in Glk"},
6670 {(char *) "-gn", glkunix_arg_NoValue,
6671 (char *) "-gn Turn off all game delays in Glk"},
6672 {(char *) "-gr", glkunix_arg_NoValue,
6673 (char *) "-gr Turn off Glk text replacement"},
6674 {(char *) "-gx", glkunix_arg_NoValue,
6675 (char *) "-gx Turn off Glk abbreviation expansions"},
6676 {(char *) "-gs", glkunix_arg_NoValue,
6677 (char *) "-gs Display a short status window in Glk"},
6678 {(char *) "-gl", glkunix_arg_NoValue,
6679 (char *) "-gl Display an extended status window in Glk"},
6680 {(char *) "-gc", glkunix_arg_NoValue,
6681 (char *) "-gc Turn off Glk command escapes in games"},
6682 {(char *) "-gD", glkunix_arg_NoValue,
6683 (char *) "-gD Turn on Glk port module debug tracing"},
6684 {(char *) "-g#", glkunix_arg_NoValue,
6685 (char *) "-g# Test for clean exit (Glk module debugging only)"},
6686 {(char *) "-1", glkunix_arg_NoValue,
6687 (char *) "-1 IRUN Mode: Print messages in first person"},
6688 {(char *) "-d", glkunix_arg_NoValue,
6689 (char *) "-d Debug metacommand execution"},
6690 {(char *) "-t", glkunix_arg_NoValue,
6691 (char *) "-t Test mode"},
6692 {(char *) "-c", glkunix_arg_NoValue,
6693 (char *) "-c Create test file"},
6694 {(char *) "-m", glkunix_arg_NoValue,
6695 (char *) "-m Force descriptions to be loaded from disk"},
6696 #ifdef OPEN_AS_TEXT
6697 {(char *) "-b", glkunix_arg_NoValue,
6698 (char *) "-b Open data files as binary files"},
6699 #endif
6700 {(char *) "-p", glkunix_arg_NoValue,
6701 (char *) "-p Debug parser"},
6702 {(char *) "-x", glkunix_arg_NoValue,
6703 (char *) "-x Debug verb execution loop"},
6704 {(char *) "-a", glkunix_arg_NoValue,
6705 (char *) "-a Debug disambiguation system"},
6706 {(char *) "-s", glkunix_arg_NoValue,
6707 (char *) "-s Debug STANDARD message handler"},
6708 #ifdef MEM_INFO
6709 {(char *) "-M", glkunix_arg_NoValue,
6710 (char *) "-M Debug memory allocation"},
6711 #endif
6712 {(char *) "", glkunix_arg_ValueCanFollow,
6713 (char *) "filename game to run"},
6714 {NULL, glkunix_arg_End, NULL}
6715 };
6716
6717
6718 /*
6719 * glkunix_startup_code()
6720 *
6721 * Startup entry point for UNIX versions of Glk AGiliTy. Glk will call
6722 * glkunix_startup_code() to pass in arguments. On startup, we call our
6723 * function to parse arguments and generally set stuff up.
6724 */
6725 int
6726 glkunix_startup_code (glkunix_startup_t * data)
6727 {
6728 assert (!gagt_startup_called);
6729 gagt_startup_called = TRUE;
6730
6731 #ifdef GARGLK
6732 garglk_set_program_name("Agility 1.1.2");
6733 garglk_set_program_info(
6734 "AGiliTy 1.1.2 by Robert Masenten\n"
6735 "Glk port by Simon Baldwin\n"
6736 );
6737 #endif /* GARGLK */
6738
6739 return gagt_startup_code (data->argc, data->argv);
6740 }
6741 #endif /* _unix */
6742
6743
6744 /*---------------------------------------------------------------------*/
6745 /* Glk linkage relevant only to the Mac platform */
6746 /*---------------------------------------------------------------------*/
6747 #ifndef GARGLK
6748 #if TARGET_OS_MAC
6749
6750 #include "macglk_startup.h"
6751
6752 static strid_t gagt_mac_gamefile = NULL;
6753 static short gagt_savedVRefNum = 0;
6754 static long gagt_savedDirID = 0;
6755
6756
6757 /*
6758 * gagt_mac_whenselected()
6759 * gagt_mac_whenbuiltin()
6760 * macglk_startup_code()
6761 *
6762 * Startup entry points for Mac versions of Glk AGiliTy. Glk will call
6763 * macglk_startup_code() for details on what to do when the application is
6764 * selected. On selection, an argv[] vector is built, and passed to the
6765 * normal AGiliTy startup code, after which, Glk will call glk_main().
6766 */
6767 static Boolean
6768 gagt_mac_whenselected (FSSpec * file, OSType filetype)
6769 {
6770 static char *argv[2];
6771 assert (!gagt_startup_called);
6772 gagt_startup_called = TRUE;
6773
6774 /* Set the WD to where the file is, so later fopens work. */
6775 if (HGetVol (0, &gagt_savedVRefNum, &gagt_savedDirID) != 0)
6776 {
6777 gagt_fatal ("GLK: HGetVol failed");
6778 return FALSE;
6779 }
6780 if (HSetVol (0, file->vRefNum, file->parID) != 0)
6781 {
6782 gagt_fatal ("GLK: HSetVol failed");
6783 return FALSE;
6784 }
6785
6786 /* Put a CString version of the PString name into argv[1]. */
6787 argv[1] = gagt_malloc (file->name[0] + 1);
6788 BlockMoveData (file->name + 1, argv[1], file->name[0]);
6789 argv[1][file->name[0]] = '\0';
6790 argv[2] = NULL;
6791
6792 return gagt_startup_code (2, argv);
6793 }
6794
6795 static Boolean
6796 gagt_mac_whenbuiltin (void)
6797 {
6798 /* Not implemented yet. */
6799 return TRUE;
6800 }
6801
6802 Boolean
6803 macglk_startup_code (macglk_startup_t * data)
6804 {
6805 static OSType gagt_mac_gamefile_types[] = { 'AGTS' };
6806
6807 data->startup_model = macglk_model_ChooseOrBuiltIn;
6808 data->app_creator = 'cAGL';
6809 data->gamefile_types = gagt_mac_gamefile_types;
6810 data->num_gamefile_types = sizeof (gagt_mac_gamefile_types)
6811 / sizeof (*gagt_mac_gamefile_types);
6812 data->savefile_type = 'BINA';
6813 data->datafile_type = 0x3f3f3f3f;
6814 data->gamefile = &gagt_mac_gamefile;
6815 data->when_selected = gagt_mac_whenselected;
6816 data->when_builtin = gagt_mac_whenbuiltin;
6817 /* macglk_setprefs(); */
6818 return TRUE;
6819 }
6820 #endif /* TARGET_OS_MAC */
6821 #endif