Use the raw buffer in tr command structure for editing.
[open-adventure.git] / misc.c
1 #include <unistd.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <stdarg.h>
6 #include <sys/time.h>
7 #include <ctype.h>
8 #include <editline/readline.h>
9
10 #include "advent.h"
11 #include "dungeon.h"
12
13 char* xstrdup(const char* s)
14 {
15     char* ptr = strdup(s);
16     if (ptr == NULL) {
17         // LCOV_EXCL_START
18         // exclude from coverage analysis because we can't simulate an out of memory error in testing
19         fprintf(stderr, "Out of memory!\n");
20         exit(EXIT_FAILURE);
21     }
22     return (ptr);
23 }
24
25 void* xmalloc(size_t size)
26 {
27     void* ptr = malloc(size);
28     if (ptr == NULL) {
29         // LCOV_EXCL_START
30         // exclude from coverage analysis because we can't simulate an out of memory error in testing
31         fprintf(stderr, "Out of memory!\n");
32         exit(EXIT_FAILURE);
33         // LCOV_EXCL_STOP
34     }
35     return (ptr);
36 }
37
38 void packed_to_token(long packed, char token[TOKLEN+1])
39 {
40     // The advent->ascii mapping.
41     const char advent_to_ascii[] = {
42         ' ', '!', '"', '#', '$', '%', '&', '\'',
43         '(', ')', '*', '+', ',', '-', '.', '/',
44         '0', '1', '2', '3', '4', '5', '6', '7',
45         '8', '9', ':', ';', '<', '=', '>', '?',
46         '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
47         'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
48         'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
49         'X', 'Y', 'Z', '\0', '\0', '\0', '\0', '\0',
50     };
51
52     // Unpack and map back to ASCII.
53     for (int i = 0; i < 5; ++i) {
54         char advent = (packed >> i * 6) & 63;
55         token[i] = advent_to_ascii[(int) advent];
56     }
57
58     // Ensure the last character is \0.
59     token[5] = '\0';
60
61     // Replace trailing whitespace with \0.
62     for (int i = 4; i >= 0; --i) {
63         if (token[i] == ' ' ||
64             token[i] == '\t')
65             token[i] = '\0';
66         else
67             break;
68     }
69 }
70
71 long token_to_packed(const char token[TOKLEN+1])
72 {
73     const char ascii_to_advent[] = {
74         63, 63, 63, 63, 63, 63, 63, 63,
75         63, 63, 63, 63, 63, 63, 63, 63,
76         63, 63, 63, 63, 63, 63, 63, 63,
77         63, 63, 63, 63, 63, 63, 63, 63,
78
79         0, 1, 2, 3, 4, 5, 6, 7,
80         8, 9, 10, 11, 12, 13, 14, 15,
81         16, 17, 18, 19, 20, 21, 22, 23,
82         24, 25, 26, 27, 28, 29, 30, 31,
83         32, 33, 34, 35, 36, 37, 38, 39,
84         40, 41, 42, 43, 44, 45, 46, 47,
85         48, 49, 50, 51, 52, 53, 54, 55,
86         56, 57, 58, 59, 60, 61, 62, 63,
87
88         63, 63, 63, 63, 63, 63, 63, 63,
89         63, 63, 63, 63, 63, 63, 63, 63,
90         63, 63, 63, 63, 63, 63, 63, 63,
91         63, 63, 63, 63, 63, 63, 63, 63,
92     };
93
94     size_t t_len = strlen(token);
95     long packed = 0;
96     for (size_t i = 0; i < t_len; ++i) {
97         char mapped = ascii_to_advent[(int) token[i]];
98         packed |= (mapped << (6 * i));
99     }
100     return (packed);
101 }
102
103 void tokenize(char* raw, struct command_t *cmd)
104 {
105     memset(cmd, '\0', sizeof(struct command_t));
106
107     /* FIXME: put a bound prefix on the %s to prevent buffer overflow */
108     int word_count = sscanf(raw, "%s%s", cmd->raw1, cmd->raw2);
109
110     // make space for substrings and zero it out
111     char chunk_data[][TOKLEN+1] = {
112         {"\0\0\0\0\0"},
113         {"\0\0\0\0\0"},
114         {"\0\0\0\0\0"},
115         {"\0\0\0\0\0"},
116     };
117
118     // break the words into up to 4 5-char substrings
119     sscanf(cmd->raw1, "%5s%5s", chunk_data[0], chunk_data[1]);
120     if (word_count == 2)
121         sscanf(cmd->raw2, "%5s%5s", chunk_data[2], chunk_data[3]);
122
123     // uppercase all the substrings
124     for (int i = 0; i < 4; ++i)
125         for (unsigned int j = 0; j < strlen(chunk_data[i]); ++j)
126             chunk_data[i][j] = (char) toupper(chunk_data[i][j]);
127
128     // pack the substrings
129     cmd->wd1  = token_to_packed(chunk_data[0]);
130     cmd->wd2  = token_to_packed(chunk_data[2]);
131 }
132
133 /* Hide the fact that wods are corrently packed longs */
134
135 bool wordeq(token_t a, token_t b)
136 {
137     return a == b;
138 }
139
140 bool wordempty(token_t a)
141 {
142     return a == 0;
143 }
144
145 void wordclear(token_t *v)
146 {
147     *v = 0;
148 }
149
150 /*  I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
151
152 void vspeak(const char* msg, bool blank, va_list ap)
153 {
154     // Do nothing if we got a null pointer.
155     if (msg == NULL)
156         return;
157
158     // Do nothing if we got an empty string.
159     if (strlen(msg) == 0)
160         return;
161
162     if (blank == true)
163         printf("\n");
164
165     int msglen = strlen(msg);
166
167     // Rendered string
168     ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
169     char* rendered = xmalloc(size);
170     char* renderp = rendered;
171
172     // Handle format specifiers (including the custom %C, %L, %S) by
173     // adjusting the parameter accordingly, and replacing the
174     // specifier with %s.
175     long previous_arg = 0;
176     for (int i = 0; i < msglen; i++) {
177         if (msg[i] != '%') {
178             *renderp++ = msg[i];
179             size--;
180         } else {
181             long arg = va_arg(ap, long);
182             if (arg == -1)
183                 arg = 0; // LCOV_EXCL_LINE - don't think we can get here.
184             i++;
185             // Integer specifier. In order to accommodate the fact
186             // that PARMS can have both legitimate integers *and*
187             // packed tokens, stringify everything. Future work may
188             // eliminate the need for this.
189             if (msg[i] == 'd') {
190                 int ret = snprintf(renderp, size, "%ld", arg);
191                 if (ret < size) {
192                     renderp += ret;
193                     size -= ret;
194                 }
195             }
196
197             // Unmodified string specifier.
198             if (msg[i] == 's') {
199                 packed_to_token(arg, renderp); /* unpack directly to destination */
200                 size_t len = strlen(renderp);
201                 renderp += len;
202                 size -= len;
203             }
204
205             // Singular/plural specifier.
206             if (msg[i] == 'S') {
207                 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
208                     *renderp++ = 's';
209                     size--;
210                 }
211             }
212
213             /* Version specifier */
214             if (msg[i] == 'V') {
215                 strcpy(renderp, VERSION);
216                 size_t len = strlen(VERSION);
217                 renderp += len;
218                 size -= len;
219             }
220
221             // All-lowercase specifier.
222             if (msg[i] == 'L' ||
223                 msg[i] == 'C') {
224                 packed_to_token(arg, renderp); /* unpack directly to destination */
225                 int len = strlen(renderp);
226                 for (int j = 0; j < len; ++j) {
227                     renderp[j] = tolower(renderp[j]);
228                 }
229                 if (msg[i] == 'C') // First char uppercase, rest lowercase.
230                     renderp[0] = toupper(renderp[0]);
231                 renderp += len;
232                 size -= len;
233             }
234
235             previous_arg = arg;
236         }
237     }
238     *renderp = 0;
239
240     // Print the message.
241     printf("%s\n", rendered);
242
243     free(rendered);
244 }
245
246 void speak(const char* msg, ...)
247 {
248     va_list ap;
249     va_start(ap, msg);
250     vspeak(msg, true, ap);
251     va_end(ap);
252 }
253
254 void sspeak(const long msg, ...)
255 {
256     va_list ap;
257     va_start(ap, msg);
258     fputc('\n', stdout);
259     vprintf(arbitrary_messages[msg], ap);
260     fputc('\n', stdout);
261     va_end(ap);
262 }
263
264 void pspeak(vocab_t msg, enum speaktype mode, int skip, bool blank, ...)
265 /* Find the skip+1st message from msg and print it.  Modes are:
266  * feel = for inventory, what you can touch
267  * look = the long description for the state the object is in
268  * listen = the sound for the state the object is in
269  * study = text on the object. */
270 {
271     va_list ap;
272     va_start(ap, blank);
273     switch (mode) {
274     case touch:
275         vspeak(objects[msg].inventory, blank, ap);
276         break;
277     case look:
278         vspeak(objects[msg].descriptions[skip], blank, ap);
279         break;
280     case hear:
281         vspeak(objects[msg].sounds[skip], blank, ap);
282         break;
283     case study:
284         vspeak(objects[msg].texts[skip], blank, ap);
285         break;
286     case change:
287         vspeak(objects[msg].changes[skip], blank, ap);
288         break;
289     }
290     va_end(ap);
291 }
292
293 void rspeak(vocab_t i, ...)
294 /* Print the i-th "random" message (section 6 of database). */
295 {
296     va_list ap;
297     va_start(ap, i);
298     vspeak(arbitrary_messages[i], true, ap);
299     va_end(ap);
300 }
301
302 void echo_input(FILE* destination, const char* input_prompt, const char* input)
303 {
304     size_t len = strlen(input_prompt) + strlen(input) + 1;
305     char* prompt_and_input = (char*) xmalloc(len);
306     strcpy(prompt_and_input, input_prompt);
307     strcat(prompt_and_input, input);
308     fprintf(destination, "%s\n", prompt_and_input);
309     free(prompt_and_input);
310 }
311
312 int word_count(char* s)
313 {
314     char* copy = xstrdup(s);
315     char delims[] = " \t";
316     int count = 0;
317     char* word;
318
319     word = strtok(copy, delims);
320     while (word != NULL) {
321         word = strtok(NULL, delims);
322         ++count;
323     }
324     free(copy);
325     return (count);
326 }
327
328 char* get_input()
329 {
330     // Set up the prompt
331     char input_prompt[] = "> ";
332     if (!settings.prompt)
333         input_prompt[0] = '\0';
334
335     // Print a blank line
336     printf("\n");
337
338     char* input;
339     while (true) {
340         input = readline(input_prompt);
341
342         if (input == NULL) // Got EOF; return with it.
343             return (input);
344         else if (input[0] == '#') { // Ignore comments.
345             free(input);
346             continue;
347         } else // We have a 'normal' line; leave the loop.
348             break;
349     }
350
351     // Strip trailing newlines from the input
352     input[strcspn(input, "\n")] = 0;
353
354     add_history(input);
355
356     if (!isatty(0))
357         echo_input(stdout, input_prompt, input);
358
359     if (settings.logfp)
360         echo_input(settings.logfp, "", input);
361
362     return (input);
363 }
364
365 bool silent_yes()
366 {
367     char* reply;
368     bool outcome;
369
370     for (;;) {
371         reply = get_input();
372         if (reply == NULL) {
373             // LCOV_EXCL_START
374             // Should be unreachable. Reply should never be NULL
375             free(reply);
376             exit(EXIT_SUCCESS);
377             // LCOV_EXCL_STOP
378         }
379
380         char* firstword = (char*) xmalloc(strlen(reply) + 1);
381         sscanf(reply, "%s", firstword);
382
383         free(reply);
384
385         for (int i = 0; i < (int)strlen(firstword); ++i)
386             firstword[i] = tolower(firstword[i]);
387
388         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
389         int y = strncmp("y", firstword, sizeof("y") - 1);
390         int no = strncmp("no", firstword, sizeof("no") - 1);
391         int n = strncmp("n", firstword, sizeof("n") - 1);
392
393         free(firstword);
394
395         if (yes == 0 ||
396             y == 0) {
397             outcome = true;
398             break;
399         } else if (no == 0 ||
400                    n == 0) {
401             outcome = false;
402             break;
403         } else
404             rspeak(PLEASE_ANSWER);
405     }
406     return (outcome);
407 }
408
409
410 bool yes(const char* question, const char* yes_response, const char* no_response)
411 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
412  *  if no, print Z and return false. */
413 {
414     char* reply;
415     bool outcome;
416
417     for (;;) {
418         speak(question);
419
420         reply = get_input();
421         if (reply == NULL) {
422             // LCOV_EXCL_START
423             // Should be unreachable. Reply should never be NULL
424             free(reply);
425             exit(EXIT_SUCCESS);
426             // LCOV_EXCL_STOP
427         }
428
429         char* firstword = (char*) xmalloc(strlen(reply) + 1);
430         sscanf(reply, "%s", firstword);
431
432         free(reply);
433
434         for (int i = 0; i < (int)strlen(firstword); ++i)
435             firstword[i] = tolower(firstword[i]);
436
437         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
438         int y = strncmp("y", firstword, sizeof("y") - 1);
439         int no = strncmp("no", firstword, sizeof("no") - 1);
440         int n = strncmp("n", firstword, sizeof("n") - 1);
441
442         free(firstword);
443
444         if (yes == 0 ||
445             y == 0) {
446             speak(yes_response);
447             outcome = true;
448             break;
449         } else if (no == 0 ||
450                    n == 0) {
451             speak(no_response);
452             outcome = false;
453             break;
454         } else
455             rspeak(PLEASE_ANSWER);
456
457     }
458
459     return (outcome);
460 }
461
462 /*  Data structure  routines */
463
464 int get_motion_vocab_id(const char* word)
465 // Return the first motion number that has 'word' as one of its words.
466 {
467     for (int i = 0; i < NMOTIONS; ++i) {
468         for (int j = 0; j < motions[i].words.n; ++j) {
469             if (strcasecmp(word, motions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
470                     strchr(ignore, word[0]) == NULL ||
471                     !settings.oldstyle))
472                 return (i);
473         }
474     }
475     // If execution reaches here, we didn't find the word.
476     return (WORD_NOT_FOUND);
477 }
478
479 int get_object_vocab_id(const char* word)
480 // Return the first object number that has 'word' as one of its words.
481 {
482     for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
483         for (int j = 0; j < objects[i].words.n; ++j) {
484             if (strcasecmp(word, objects[i].words.strs[j]) == 0)
485                 return (i);
486         }
487     }
488     // If execution reaches here, we didn't find the word.
489     return (WORD_NOT_FOUND);
490 }
491
492 int get_action_vocab_id(const char* word)
493 // Return the first motion number that has 'word' as one of its words.
494 {
495     for (int i = 0; i < NACTIONS; ++i) {
496         for (int j = 0; j < actions[i].words.n; ++j) {
497             if (strcasecmp(word, actions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
498                     strchr(ignore, word[0]) == NULL ||
499                     !settings.oldstyle))
500                 return (i);
501         }
502     }
503     // If execution reaches here, we didn't find the word.
504     return (WORD_NOT_FOUND);
505 }
506
507 int get_special_vocab_id(const char* word)
508 // Return the first special number that has 'word' as one of its words.
509 {
510     for (int i = 0; i < NSPECIALS; ++i) {
511         for (int j = 0; j < specials[i].words.n; ++j) {
512             if (strcasecmp(word, specials[i].words.strs[j]) == 0)
513                 return (i);
514         }
515     }
516     // If execution reaches here, we didn't find the word.
517     return (WORD_NOT_FOUND);
518 }
519
520 long get_vocab_id(const char* word)
521 // Search the vocab categories in order for the supplied word.
522 {
523     long ref_num;
524
525     /* FIXME: Magic numbers related to vocabulary */
526     ref_num = get_motion_vocab_id(word);
527     if (ref_num != WORD_NOT_FOUND)
528         return (ref_num + 0); // FIXME: replace with a proper hash
529
530     ref_num = get_object_vocab_id(word);
531     if (ref_num != WORD_NOT_FOUND)
532         return (ref_num + 1000); // FIXME: replace with a proper hash
533
534     ref_num = get_action_vocab_id(word);
535     if (ref_num != WORD_NOT_FOUND)
536         return (ref_num + 2000); // FIXME: replace with a proper hash
537
538     ref_num = get_special_vocab_id(word);
539     if (ref_num != WORD_NOT_FOUND)
540         return (ref_num + 3000); // FIXME: replace with a proper hash
541
542     // Check for the reservoir magic word.
543     if (strcasecmp(word, game.zzword) == 0)
544         return (PART + 2000); // FIXME: replace with a proper hash
545
546     return (WORD_NOT_FOUND);
547 }
548
549 void juggle(long object)
550 /*  Juggle an object by picking it up and putting it down again, the purpose
551  *  being to get the object to the front of the chain of things at its loc. */
552 {
553     long i, j;
554
555     i = game.place[object];
556     j = game.fixed[object];
557     move(object, i);
558     move(object + NOBJECTS, j);
559 }
560
561 void move(long object, long where)
562 /*  Place any object anywhere by picking it up and dropping it.  May
563  *  already be toting, in which case the carry is a no-op.  Mustn't
564  *  pick up objects which are not at any loc, since carry wants to
565  *  remove objects from game.atloc chains. */
566 {
567     long from;
568
569     if (object > NOBJECTS)
570         from = game.fixed[object - NOBJECTS];
571     else
572         from = game.place[object];
573     if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
574         carry(object, from);
575     drop(object, where);
576 }
577
578 long put(long object, long where, long pval)
579 /*  PUT is the same as MOVE, except it returns a value used to set up the
580  *  negated game.prop values for the repository objects. */
581 {
582     move(object, where);
583     return (-1) - pval;;
584 }
585
586 void carry(long object, long where)
587 /*  Start toting an object, removing it from the list of things at its former
588  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
589  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
590 {
591     long temp;
592
593     if (object <= NOBJECTS) {
594         if (game.place[object] == CARRIED)
595             return;
596         game.place[object] = CARRIED;
597         ++game.holdng;
598     }
599     if (game.atloc[where] == object) {
600         game.atloc[where] = game.link[object];
601         return;
602     }
603     temp = game.atloc[where];
604     while (game.link[temp] != object) {
605         temp = game.link[temp];
606     }
607     game.link[temp] = game.link[object];
608 }
609
610 void drop(long object, long where)
611 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
612  *  game.holdng if the object was being toted. */
613 {
614     if (object > NOBJECTS)
615         game.fixed[object - NOBJECTS] = where;
616     else {
617         if (game.place[object] == CARRIED)
618             --game.holdng;
619         game.place[object] = where;
620     }
621     if (where <= 0)
622         return;
623     game.link[object] = game.atloc[where];
624     game.atloc[where] = object;
625 }
626
627 long atdwrf(long where)
628 /*  Return the index of first dwarf at the given location, zero if no dwarf is
629  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
630  *  the pirate (6th dwarf). */
631 {
632     long at;
633
634     at = 0;
635     if (game.dflag < 2)
636         return (at);
637     at = -1;
638     for (long i = 1; i <= NDWARVES - 1; i++) {
639         if (game.dloc[i] == where)
640             return i;
641         if (game.dloc[i] != 0)
642             at = 0;
643     }
644     return (at);
645 }
646
647 /*  Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
648  *  randrange) */
649
650 long setbit(long bit)
651 /*  Returns 2**bit for use in constructing bit-masks. */
652 {
653     return (1L << bit);
654 }
655
656 bool tstbit(long mask, int bit)
657 /*  Returns true if the specified bit is set in the mask. */
658 {
659     return (mask & (1 << bit)) != 0;
660 }
661
662 void set_seed(long seedval)
663 /* Set the LCG seed */
664 {
665     game.lcg_x = (unsigned long) seedval % game.lcg_m;
666
667     // once seed is set, we need to generate the Z`ZZZ word
668     make_zzword(game.zzword);
669 }
670
671 unsigned long get_next_lcg_value(void)
672 /* Return the LCG's current value, and then iterate it. */
673 {
674     unsigned long old_x = game.lcg_x;
675     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
676     return old_x;
677 }
678
679 long randrange(long range)
680 /* Return a random integer from [0, range). */
681 {
682     return range * get_next_lcg_value() / game.lcg_m;
683 }
684
685 void make_zzword(char zzword[TOKLEN+1])
686 {
687     for (int i = 0; i < 5; ++i) {
688         zzword[i] = 'A' + randrange(26);
689     }
690     zzword[1] = '\''; // force second char to apostrophe
691     zzword[5] = '\0';
692 }
693
694 // LCOV_EXCL_START
695 void bug(enum bugtype num, const char *error_string)
696 {
697     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
698     exit(EXIT_FAILURE);
699 }
700 // LCOV_EXCL_STOP
701
702 /* end */