OSDN Git Service

[Refactor] #39970 Renamed core.c/h to system-variables.c/h
[hengband/hengband.git] / src / util.c
1 /* File: util.c */
2
3 /*
4  * Copyright (c) 1997 Ben Harrison, James E. Wilson, Robert A. Koeneke
5  *
6  * This software may be copied and distributed for educational, research,
7  * and not for profit purposes provided that this copyright and statement
8  * are included in all such copies.  Other copyrights may also apply.
9  */
10
11  /* Purpose: Angband utilities -BEN- */
12
13 #include "angband.h"
14 #include "main/music-definitions-table.h"
15 #include "io/signal-handlers.h"
16 #include "core/system-variables.h"
17 #include "core/stuff-handler.h"
18 #include "gameterm.h"
19 #include "util.h"
20 #include "files.h"
21 #include "monsterrace-hook.h"
22 #include "view/display-main-window.h"
23 #include "quest.h"
24 #include "floor.h"
25 #include "world/world.h"
26 #include "io/write-diary.h"
27 #include "cmd/cmd-dump.h"
28 #include "japanese.h"
29 #include "player-class.h"
30 #include "core/output-updater.h"
31 #include "io/input-key-processor.h"
32
33 /*!
34  * 10進数から16進数への変換テーブル /
35  * Global array for converting numbers to uppercase hecidecimal digit
36  * This array can also be used to convert a number to an octal digit
37  */
38 const char hexsym[16] =
39 {
40         '0', '1', '2', '3', '4', '5', '6', '7',
41         '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
42 };
43
44 /*
45  * Keymaps for each "mode" associated with each keypress.
46  */
47 concptr keymap_act[KEYMAP_MODES][256];
48
49 /*
50  * The next "free" index to use
51  */
52 u32b message__next;
53
54 /*
55  * The index of the oldest message (none yet)
56  */
57 u32b message__last;
58
59 /*
60  * The next "free" offset
61  */
62 u32b message__head;
63
64 /*
65  * The offset to the oldest used char (none yet)
66  */
67 u32b message__tail;
68
69 /*
70  * The array of offsets, by index [MESSAGE_MAX]
71  */
72 u32b *message__ptr;
73
74 /*
75  * The array of chars, by offset [MESSAGE_BUF]
76  */
77 char *message__buf;
78
79 bool msg_flag;                  /* Used in msg_print() for "buffering" */
80
81 /*
82  * Number of active macros.
83  */
84 s16b macro__num;
85
86 /*
87  * Array of macro patterns [MACRO_MAX]
88  */
89 concptr *macro__pat;
90
91 /*
92  * Array of macro actions [MACRO_MAX]
93  */
94 concptr *macro__act;
95
96 /*
97  * Array of macro types [MACRO_MAX]
98  */
99 bool *macro__cmd;
100
101 /*
102  * Current macro action [1024]
103  */
104 char *macro__buf;
105
106 bool get_com_no_macros = FALSE; /* Expand macros in "get_com" or not */
107
108 bool inkey_base;                /* See the "inkey()" function */
109 bool inkey_xtra;                /* See the "inkey()" function */
110 bool inkey_scan;                /* See the "inkey()" function */
111 bool inkey_flag;                /* See the "inkey()" function */
112
113 bool use_menu;
114
115 pos_list tmp_pos;
116
117 /*
118  * The number of quarks
119  */
120 STR_OFFSET quark__num;
121
122 /*
123  * The pointers to the quarks [QUARK_MAX]
124  */
125 concptr *quark__str;
126
127 static int num_more = 0;
128
129 /* Save macro trigger string for use in inkey_special() */
130 static char inkey_macro_trigger_string[1024];
131
132 int max_macrotrigger = 0; /*!< 現在登録中のマクロ(トリガー)の数 */
133 concptr macro_template = NULL; /*!< Angband設定ファイルのT: タグ情報から読み込んだ長いTコードを処理するために利用する文字列ポインタ */
134 concptr macro_modifier_chr; /*!< &x# で指定されるマクロトリガーに関する情報を記録する文字列ポインタ */
135 concptr macro_modifier_name[MAX_MACRO_MOD]; /*!< マクロ上で取り扱う特殊キーを文字列上で表現するためのフォーマットを記録した文字列ポインタ配列 */
136 concptr macro_trigger_name[MAX_MACRO_TRIG]; /*!< マクロのトリガーコード */
137 concptr macro_trigger_keycode[2][MAX_MACRO_TRIG];  /*!< マクロの内容 */
138
139 s16b command_cmd;               /* Current "Angband Command" */
140 COMMAND_ARG command_arg;        /*!< 各種コマンドの汎用的な引数として扱う / Gives argument of current command */
141 COMMAND_NUM command_rep;        /*!< 各種コマンドの汎用的なリピート数として扱う / Gives repetition of current command */
142 DIRECTION command_dir;          /*!< 各種コマンドの汎用的な方向値処理として扱う/ Gives direction of current command */
143 s16b command_see;               /* See "object1.c" */
144 s16b command_wrk;               /* See "object1.c" */
145 TERM_LEN command_gap = 999;         /* See "object1.c" */
146 s16b command_new;               /* Command chaining from inven/equip view */
147
148 #ifdef SET_UID
149
150 # ifndef HAVE_USLEEP
151
152 /*
153  * For those systems that don't have "usleep()" but need it.
154  *
155  * Fake "usleep()" function grabbed from the inl netrek server -cba
156  */
157 int usleep(huge usecs)
158 {
159         struct timeval timer;
160
161         int nfds = 0;
162
163 #ifdef FD_SET
164         fd_set          *no_fds = NULL;
165 #else
166         int                     *no_fds = NULL;
167 #endif
168         if (usecs > 4000000L) core(_("不当な usleep() 呼び出し", "Illegal usleep() call"));
169
170         timer.tv_sec = (usecs / 1000000L);
171         timer.tv_usec = (usecs % 1000000L);
172         if (select(nfds, no_fds, no_fds, no_fds, &timer) < 0)
173         {
174                 if (errno != EINTR) return -1;
175         }
176
177         return 0;
178 }
179 # endif
180
181 /*
182  * Hack -- External functions
183  */
184 #ifdef SET_UID
185 extern struct passwd *getpwuid(uid_t uid);
186 extern struct passwd *getpwnam(concptr name);
187 #endif
188
189 /*
190  * Find a default user name from the system.
191  */
192 void user_name(char *buf, int id)
193 {
194         struct passwd *pw;
195         if ((pw = getpwuid(id)))
196         {
197                 (void)strcpy(buf, pw->pw_name);
198                 buf[16] = '\0';
199
200 #ifdef JP
201                 if (!iskanji(buf[0]))
202 #endif
203                         if (islower(buf[0]))
204                                 buf[0] = toupper(buf[0]);
205
206                 return;
207         }
208
209         strcpy(buf, "PLAYER");
210 }
211
212 #endif /* SET_UID */
213
214
215 /*
216  * The concept of the "file" routines below (and elsewhere) is that all
217  * file handling should be done using as few routines as possible, since
218  * every machine is slightly different, but these routines always have the
219  * same semantics.
220  *
221  * In fact, perhaps we should use the "path_parse()" routine below to convert
222  * from "canonical" filenames (optional leading tilde's, internal wildcards,
223  * slash as the path seperator, etc) to "system" filenames (no special symbols,
224  * system-specific path seperator, etc).  This would allow the program itself
225  * to assume that all filenames are "Unix" filenames, and explicitly "extract"
226  * such filenames if needed (by "path_parse()", or perhaps "path_canon()").
227  *
228  * Note that "path_temp" should probably return a "canonical" filename.
229  *
230  * Note that "my_fopen()" and "my_open()" and "my_make()" and "my_kill()"
231  * and "my_move()" and "my_copy()" should all take "canonical" filenames.
232  *
233  * Note that "canonical" filenames use a leading "slash" to indicate an absolute
234  * path, and a leading "tilde" to indicate a special directory, and default to a
235  * relative path, but MSDOS uses a leading "drivename plus colon" to indicate the
236  * use of a "special drive", and then the rest of the path is parsed "normally",
237  * and an embedded colon to indicate a "drive plus absolute path", and finally
238  * defaults to a file in the current working directory, which may or may not be defined.
239  *
240  * We should probably parse a leading "~~/" as referring to "ANGBAND_DIR". (?)
241  */
242
243 #ifdef SET_UID
244  /*
245   * Extract a "parsed" path from an initial filename
246   * Normally, we simply copy the filename into the buffer
247   * But leading tilde symbols must be handled in a special way
248   * Replace "~user/" by the home directory of the user named "user"
249   * Replace "~/" by the home directory of the current user
250   */
251 errr path_parse(char *buf, int max, concptr file)
252 {
253         buf[0] = '\0';
254         if (!file) return -1;
255
256         if (file[0] != '~')
257         {
258                 (void)strnfmt(buf, max, "%s", file);
259                 return 0;
260         }
261
262         concptr u = file + 1;
263         concptr s = my_strstr(u, PATH_SEP);
264         char user[128];
265         if (s && (s >= u + sizeof(user))) return 1;
266
267         if (s)
268         {
269                 int i;
270                 for (i = 0; u < s; ++i) user[i] = *u++;
271                 user[i] = '\0';
272                 u = user;
273         }
274
275         if (u[0] == '\0') u = getlogin();
276
277         struct passwd *pw;
278         if (u) pw = getpwnam(u);
279         else pw = getpwuid(getuid());
280
281         if (!pw) return 1;
282
283         if (s) strnfmt(buf, max, "%s%s", pw->pw_dir, s);
284         else strnfmt(buf, max, "%s", pw->pw_dir);
285
286         return 0;
287 }
288 #else /* SET_UID */
289  /*
290   * Extract a "parsed" path from an initial filename
291   *
292   * This requires no special processing on simple machines,
293   * except for verifying the size of the filename.
294   */
295 errr path_parse(char *buf, int max, concptr file)
296 {
297         (void)strnfmt(buf, max, "%s", file);
298         return 0;
299 }
300 #endif /* SET_UID */
301
302
303 #ifndef HAVE_MKSTEMP
304
305 /*
306  * Hack -- acquire a "temporary" file name if possible
307  *
308  * This filename is always in "system-specific" form.
309  */
310 static errr path_temp(char *buf, int max)
311 {
312         concptr s = tmpnam(NULL);
313         if (!s) return -1;
314
315 #if !defined(WIN32) || (defined(_MSC_VER) && (_MSC_VER >= 1900))
316         (void)strnfmt(buf, max, "%s", s);
317 #else
318         (void)strnfmt(buf, max, ".%s", s);
319 #endif
320
321         return 0;
322 }
323 #endif
324
325
326 /*!
327  * @brief ファイル入出力のためのパス生成する。/ Create a new path by appending a file (or directory) to a path.
328  * @param buf ファイルのフルを返すバッファ
329  * @param max bufのサイズ
330  * @param path ファイルパス
331  * @param file ファイル名
332  * @return エラーコード(ただし常に0を返す)
333  *
334  * This requires no special processing on simple machines, except
335  * for verifying the size of the filename, but note the ability to
336  * bypass the given "path" with certain special file-names.
337  *
338  * Note that the "file" may actually be a "sub-path", including
339  * a path and a file.
340  *
341  * Note that this function yields a path which must be "parsed"
342  * using the "parse" function above.
343  */
344 errr path_build(char *buf, int max, concptr path, concptr file)
345 {
346         if (file[0] == '~')
347         {
348                 (void)strnfmt(buf, max, "%s", file);
349         }
350         else if (prefix(file, PATH_SEP) && !streq(PATH_SEP, ""))
351         {
352                 (void)strnfmt(buf, max, "%s", file);
353         }
354         else if (!path[0])
355         {
356                 (void)strnfmt(buf, max, "%s", file);
357         }
358         else
359         {
360                 (void)strnfmt(buf, max, "%s%s%s", path, PATH_SEP, file);
361         }
362
363         return 0;
364 }
365
366
367 /*
368  * Hack -- replacement for "fopen()"
369  */
370 FILE *my_fopen(concptr file, concptr mode)
371 {
372 #if defined(MACH_O_CARBON)
373         FILE *tempfff;
374 #endif
375         char buf[1024];
376         if (path_parse(buf, 1024, file)) return (NULL);
377 #if defined(MACH_O_CARBON)
378         if (my_strchr(mode, 'w'))
379         {
380                 tempfff = fopen(buf, mode);
381                 fsetfileinfo(buf, _fcreator, _ftype);
382                 fclose(tempfff);
383         }
384 #endif
385
386         return (fopen(buf, mode));
387 }
388
389
390 /*
391  * Hack -- replacement for "fclose()"
392  */
393 errr my_fclose(FILE *fff)
394 {
395         if (!fff) return -1;
396         if (fclose(fff) == EOF) return 1;
397         return 0;
398 }
399
400
401 #ifdef HAVE_MKSTEMP
402 FILE *my_fopen_temp(char *buf, int max)
403 {
404         strncpy(buf, "/tmp/anXXXXXX", max);
405         int fd = mkstemp(buf);
406         if (fd < 0) return (NULL);
407
408         return (fdopen(fd, "w"));
409 }
410 #else /* HAVE_MKSTEMP */
411 FILE *my_fopen_temp(char *buf, int max)
412 {
413         if (path_temp(buf, max)) return (NULL);
414         return (my_fopen(buf, "w"));
415 }
416 #endif /* HAVE_MKSTEMP */
417
418
419 /*
420  * Hack -- replacement for "fgets()"
421  *
422  * Read a string, without a newline, to a file
423  *
424  * Process tabs, strip internal non-printables
425  */
426 errr my_fgets(FILE *fff, char *buf, huge n)
427 {
428         huge i = 0;
429         char *s;
430         char tmp[1024];
431
432         if (fgets(tmp, 1024, fff))
433         {
434 #ifdef JP
435                 guess_convert_to_system_encoding(tmp, sizeof(tmp));
436 #endif
437                 for (s = tmp; *s; s++)
438                 {
439 #if defined(MACH_O_CARBON)
440
441                         /*
442                          * Be nice to the Macintosh, where a file can have Mac or Unix
443                          * end of line, especially since the introduction of OS X.
444                          * MPW tools were also very tolerant to the Unix EOL.
445                          */
446                         if (*s == '\r') *s = '\n';
447
448 #endif /* MACH_O_CARBON */
449                         if (*s == '\n')
450                         {
451                                 buf[i] = '\0';
452                                 return 0;
453                         }
454                         else if (*s == '\t')
455                         {
456                                 if (i + 8 >= n) break;
457
458                                 buf[i++] = ' ';
459                                 while (0 != (i % 8))
460                                         buf[i++] = ' ';
461                         }
462 #ifdef JP
463                         else if (iskanji(*s))
464                         {
465                                 if (!s[1]) break;
466                                 buf[i++] = *s++;
467                                 buf[i++] = *s;
468                         }
469                         else if (iskana(*s))
470                         {
471                                 /* 半角かなに対応 */
472                                 buf[i++] = *s;
473                                 if (i >= n) break;
474                         }
475 #endif
476                         else if (isprint((unsigned char)*s))
477                         {
478                                 buf[i++] = *s;
479                                 if (i >= n) break;
480                         }
481                 }
482
483                 buf[i] = '\0';
484                 return 0;
485         }
486
487         buf[0] = '\0';
488         return 1;
489 }
490
491
492 /*
493  * Hack -- replacement for "fputs()"
494  * Dump a string, plus a newline, to a file
495  * Process internal weirdness?
496  */
497 errr my_fputs(FILE *fff, concptr buf, huge n)
498 {
499         n = n ? n : 0;
500         (void)fprintf(fff, "%s\n", buf);
501         return 0;
502 }
503
504
505  /*
506   * Several systems have no "O_BINARY" flag
507   */
508 #ifndef O_BINARY
509 # define O_BINARY 0
510 #endif /* O_BINARY */
511
512
513 /*
514  * Hack -- attempt to delete a file
515  */
516 errr fd_kill(concptr file)
517 {
518         char buf[1024];
519         if (path_parse(buf, 1024, file)) return -1;
520
521         (void)remove(buf);
522         return 0;
523 }
524
525
526 /*
527  * Hack -- attempt to move a file
528  */
529 errr fd_move(concptr file, concptr what)
530 {
531         char buf[1024];
532         char aux[1024];
533         if (path_parse(buf, 1024, file)) return -1;
534         if (path_parse(aux, 1024, what)) return -1;
535
536         (void)rename(buf, aux);
537         return 0;
538 }
539
540
541 /*
542  * Hack -- attempt to copy a file
543  */
544 errr fd_copy(concptr file, concptr what)
545 {
546         char buf[1024];
547         char aux[1024];
548         int read_num;
549         int src_fd, dst_fd;
550
551         if (path_parse(buf, 1024, file)) return -1;
552         if (path_parse(aux, 1024, what)) return -1;
553
554         src_fd = fd_open(buf, O_RDONLY);
555         if (src_fd < 0) return -1;
556
557         dst_fd = fd_open(aux, O_WRONLY | O_TRUNC | O_CREAT);
558         if (dst_fd < 0) return -1;
559
560         while ((read_num = read(src_fd, buf, 1024)) > 0)
561         {
562                 int write_num = 0;
563                 while (write_num < read_num)
564                 {
565                         int ret = write(dst_fd, buf + write_num, read_num - write_num);
566                         if (ret < 0)
567                         {
568                                 fd_close(src_fd);
569                                 fd_close(dst_fd);
570
571                                 return ret;
572                         }
573
574                         write_num += ret;
575                 }
576         }
577
578         fd_close(src_fd);
579         fd_close(dst_fd);
580         return 0;
581 }
582
583
584 /*
585  * Hack -- attempt to open a file descriptor (create file)
586  * This function should fail if the file already exists
587  * Note that we assume that the file should be "binary"
588  */
589 int fd_make(concptr file, BIT_FLAGS mode)
590 {
591         char buf[1024];
592         if (path_parse(buf, 1024, file)) return -1;
593
594 #if defined(MACH_O_CARBON)
595         {
596                 int fdes;
597                 fdes = open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, mode);
598                 if (fdes >= 0) fsetfileinfo(buf, _fcreator, _ftype);
599                 return (fdes);
600         }
601
602 #else
603         return (open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, mode));
604 #endif
605 }
606
607
608 /*
609  * Hack -- attempt to open a file descriptor (existing file)
610  *
611  * Note that we assume that the file should be "binary"
612  */
613 int fd_open(concptr file, int flags)
614 {
615         char buf[1024];
616         if (path_parse(buf, 1024, file)) return -1;
617
618         return (open(buf, flags | O_BINARY, 0));
619 }
620
621
622 /*
623  * Hack -- attempt to lock a file descriptor
624  *
625  * Legal lock types -- F_UNLCK, F_RDLCK, F_WRLCK
626  */
627 errr fd_lock(int fd, int what)
628 {
629         what = what ? what : 0;
630         if (fd < 0) return -1;
631
632 #if defined(SET_UID) && defined(LOCK_UN) && defined(LOCK_EX)
633         if (what == F_UNLCK)
634         {
635                 (void)flock(fd, LOCK_UN);
636         }
637         else
638         {
639                 if (flock(fd, LOCK_EX) != 0) return 1;
640         }
641 #endif
642
643         return 0;
644 }
645
646
647 /*
648  * Hack -- attempt to seek on a file descriptor
649  */
650 errr fd_seek(int fd, huge n)
651 {
652         if (fd < 0) return -1;
653
654         huge p = lseek(fd, n, SEEK_SET);
655         if (p != n) return 1;
656
657         return 0;
658 }
659
660
661 /*
662  * Hack -- attempt to truncate a file descriptor
663  */
664 errr fd_chop(int fd, huge n)
665 {
666         n = n ? n : 0;
667         return fd >= 0 ? 0 : -1;
668 }
669
670
671 /*
672  * Hack -- attempt to read data from a file descriptor
673  */
674 errr fd_read(int fd, char *buf, huge n)
675 {
676         if (fd < 0) return -1;
677 #ifndef SET_UID
678         while (n >= 16384)
679         {
680                 if (read(fd, buf, 16384) != 16384) return 1;
681
682                 buf += 16384;
683                 n -= 16384;
684         }
685 #endif
686
687         if (read(fd, buf, n) != (int)n) return 1;
688
689         return 0;
690 }
691
692
693 /*
694  * Hack -- Attempt to write data to a file descriptor
695  */
696 errr fd_write(int fd, concptr buf, huge n)
697 {
698         if (fd < 0) return -1;
699
700 #ifndef SET_UID
701         while (n >= 16384)
702         {
703                 if (write(fd, buf, 16384) != 16384) return 1;
704
705                 buf += 16384;
706                 n -= 16384;
707         }
708 #endif
709
710         if (write(fd, buf, n) != (int)n) return 1;
711
712         return 0;
713 }
714
715
716 /*
717  * Hack -- attempt to close a file descriptor
718  */
719 errr fd_close(int fd)
720 {
721         if (fd < 0) return -1;
722
723         (void)close(fd);
724         return 0;
725 }
726
727
728 /*
729  * Important note about "colors"
730  *
731  * The "TERM_*" color definitions list the "composition" of each
732  * "Angband color" in terms of "quarters" of each of the three color
733  * components (Red, Green, Blue), for example, TERM_UMBER is defined
734  * as 2/4 Red, 1/4 Green, 0/4 Blue.
735  *
736  * The following info is from "Torbjorn Lindgren" (see "main-xaw.c").
737  *
738  * These values are NOT gamma-corrected.  On most machines (with the
739  * Macintosh being an important exception), you must "gamma-correct"
740  * the given values, that is, "correct for the intrinsic non-linearity
741  * of the phosphor", by converting the given intensity levels based
742  * on the "gamma" of the target screen, which is usually 1.7 (or 1.5).
743  *
744  * The actual formula for conversion is unknown to me at this time,
745  * but you can use the table below for the most common gamma values.
746  *
747  * So, on most machines, simply convert the values based on the "gamma"
748  * of the target screen, which is usually in the range 1.5 to 1.7, and
749  * usually is closest to 1.7.  The converted value for each of the five
750  * different "quarter" values is given below:
751  *
752  *  Given     Gamma 1.0       Gamma 1.5       Gamma 1.7     Hex 1.7
753  *  -----       ----            ----            ----          ---
754  *   0/4        0.00            0.00            0.00          #00
755  *   1/4        0.25            0.27            0.28          #47
756  *   2/4        0.50            0.55            0.56          #8f
757  *   3/4        0.75            0.82            0.84          #d7
758  *   4/4        1.00            1.00            1.00          #ff
759  *
760  * Note that some machines (i.e. most IBM machines) are limited to a
761  * hard-coded set of colors, and so the information above is useless.
762  *
763  * Also, some machines are limited to a pre-determined set of colors,
764  * for example, the IBM can only display 16 colors, and only 14 of
765  * those colors resemble colors used by Angband, and then only when
766  * you ignore the fact that "Slate" and "cyan" are not really matches,
767  * so on the IBM, we use "orange" for both "Umber", and "Light Umber"
768  * in addition to the obvious "Orange", since by combining all of the
769  * "indeterminate" colors into a single color, the rest of the colors
770  * are left with "meaningful" values.
771  */
772
773
774  /*
775   * Move the cursor
776   */
777 void move_cursor(int row, int col)
778 {
779         Term_gotoxy(col, row);
780 }
781
782
783 /*
784  * Convert a decimal to a single digit octal number
785  */
786 static char octify(uint i)
787 {
788         return (hexsym[i % 8]);
789 }
790
791
792 /*
793  * Convert a decimal to a single digit hex number
794  */
795 static char hexify(uint i)
796 {
797         return (hexsym[i % 16]);
798 }
799
800
801 /*
802  * Convert a octal-digit into a decimal
803  */
804 static int deoct(char c)
805 {
806         if (isdigit(c)) return (D2I(c));
807         return 0;
808 }
809
810
811 /*
812  * Convert a hexidecimal-digit into a decimal
813  */
814 static int dehex(char c)
815 {
816         if (isdigit(c)) return (D2I(c));
817         if (islower(c)) return (A2I(c) + 10);
818         if (isupper(c)) return (A2I(tolower(c)) + 10);
819         return 0;
820 }
821
822
823 static int my_stricmp(concptr a, concptr b)
824 {
825         for (concptr s1 = a, s2 = b; TRUE; s1++, s2++)
826         {
827                 char z1 = FORCEUPPER(*s1);
828                 char z2 = FORCEUPPER(*s2);
829                 if (z1 < z2) return -1;
830                 if (z1 > z2) return 1;
831                 if (!z1) return 0;
832         }
833 }
834
835 static int my_strnicmp(concptr a, concptr b, int n)
836 {
837         for (concptr s1 = a, s2 = b; n > 0; s1++, s2++, n--)
838         {
839                 char z1 = FORCEUPPER(*s1);
840                 char z2 = FORCEUPPER(*s2);
841                 if (z1 < z2) return -1;
842                 if (z1 > z2) return 1;
843                 if (!z1) return 0;
844         }
845
846         return 0;
847 }
848
849
850 static void trigger_text_to_ascii(char **bufptr, concptr *strptr)
851 {
852         char *s = *bufptr;
853         concptr str = *strptr;
854         bool mod_status[MAX_MACRO_MOD];
855
856         int i, len = 0;
857         int shiftstatus = 0;
858         concptr key_code;
859
860         if (macro_template == NULL)
861                 return;
862
863         for (i = 0; macro_modifier_chr[i]; i++)
864                 mod_status[i] = FALSE;
865         str++;
866
867         /* Examine modifier keys */
868         while (TRUE)
869         {
870                 for (i = 0; macro_modifier_chr[i]; i++)
871                 {
872                         len = strlen(macro_modifier_name[i]);
873
874                         if (!my_strnicmp(str, macro_modifier_name[i], len))
875                                 break;
876                 }
877
878                 if (!macro_modifier_chr[i]) break;
879                 str += len;
880                 mod_status[i] = TRUE;
881                 if ('S' == macro_modifier_chr[i])
882                         shiftstatus = 1;
883         }
884
885         for (i = 0; i < max_macrotrigger; i++)
886         {
887                 len = strlen(macro_trigger_name[i]);
888                 if (!my_strnicmp(str, macro_trigger_name[i], len) && ']' == str[len])
889                 {
890                         break;
891                 }
892         }
893
894         if (i == max_macrotrigger)
895         {
896                 str = my_strchr(str, ']');
897                 if (str)
898                 {
899                         *s++ = (char)31;
900                         *s++ = '\r';
901                         *bufptr = s;
902                         *strptr = str; /* where **strptr == ']' */
903                 }
904
905                 return;
906         }
907
908         key_code = macro_trigger_keycode[shiftstatus][i];
909         str += len;
910
911         *s++ = (char)31;
912         for (i = 0; macro_template[i]; i++)
913         {
914                 char ch = macro_template[i];
915                 switch (ch)
916                 {
917                 case '&':
918                         for (int j = 0; macro_modifier_chr[j]; j++)
919                         {
920                                 if (mod_status[j])
921                                         *s++ = macro_modifier_chr[j];
922                         }
923
924                         break;
925                 case '#':
926                         strcpy(s, key_code);
927                         s += strlen(key_code);
928                         break;
929                 default:
930                         *s++ = ch;
931                         break;
932                 }
933         }
934
935         *s++ = '\r';
936
937         *bufptr = s;
938         *strptr = str; /* where **strptr == ']' */
939         return;
940 }
941
942
943 /*
944  * Hack -- convert a printable string into real ascii
945  *
946  * I have no clue if this function correctly handles, for example,
947  * parsing "\xFF" into a (signed) char.  Whoever thought of making
948  * the "sign" of a "char" undefined is a complete moron.  Oh well.
949  */
950 void text_to_ascii(char *buf, concptr str)
951 {
952         char *s = buf;
953         while (*str)
954         {
955                 if (*str == '\\')
956                 {
957                         str++;
958                         if (!(*str)) break;
959
960                         if (*str == '[')
961                         {
962                                 trigger_text_to_ascii(&s, &str);
963                         }
964                         else
965                         {
966                                 if (*str == 'x')
967                                 {
968                                         *s = 16 * (char)dehex(*++str);
969                                         *s++ += (char)dehex(*++str);
970                                 }
971                                 else if (*str == '\\')
972                                 {
973                                         *s++ = '\\';
974                                 }
975                                 else if (*str == '^')
976                                 {
977                                         *s++ = '^';
978                                 }
979                                 else if (*str == 's')
980                                 {
981                                         *s++ = ' ';
982                                 }
983                                 else if (*str == 'e')
984                                 {
985                                         *s++ = ESCAPE;
986                                 }
987                                 else if (*str == 'b')
988                                 {
989                                         *s++ = '\b';
990                                 }
991                                 else if (*str == 'n')
992                                 {
993                                         *s++ = '\n';
994                                 }
995                                 else if (*str == 'r')
996                                 {
997                                         *s++ = '\r';
998                                 }
999                                 else if (*str == 't')
1000                                 {
1001                                         *s++ = '\t';
1002                                 }
1003                                 else if (*str == '0')
1004                                 {
1005                                         *s = 8 * (char)deoct(*++str);
1006                                         *s++ += (char)deoct(*++str);
1007                                 }
1008                                 else if (*str == '1')
1009                                 {
1010                                         *s = 64 + 8 * (char)deoct(*++str);
1011                                         *s++ += (char)deoct(*++str);
1012                                 }
1013                                 else if (*str == '2')
1014                                 {
1015                                         *s = 64 * 2 + 8 * (char)deoct(*++str);
1016                                         *s++ += (char)deoct(*++str);
1017                                 }
1018                                 else if (*str == '3')
1019                                 {
1020                                         *s = 64 * 3 + 8 * (char)deoct(*++str);
1021                                         *s++ += (char)deoct(*++str);
1022                                 }
1023                         }
1024
1025                         str++;
1026                 }
1027                 else if (*str == '^')
1028                 {
1029                         str++;
1030                         *s++ = (*str++ & 037);
1031                 }
1032                 else
1033                 {
1034                         *s++ = *str++;
1035                 }
1036         }
1037
1038         *s = '\0';
1039 }
1040
1041
1042 static bool trigger_ascii_to_text(char **bufptr, concptr *strptr)
1043 {
1044         char *s = *bufptr;
1045         concptr str = *strptr;
1046         char key_code[100];
1047         int i;
1048         if (macro_template == NULL)
1049                 return FALSE;
1050
1051         *s++ = '\\';
1052         *s++ = '[';
1053
1054         concptr tmp;
1055         for (i = 0; macro_template[i]; i++)
1056         {
1057                 char ch = macro_template[i];
1058
1059                 switch (ch)
1060                 {
1061                 case '&':
1062                         while ((tmp = my_strchr(macro_modifier_chr, *str)) != 0)
1063                         {
1064                                 int j = (int)(tmp - macro_modifier_chr);
1065                                 tmp = macro_modifier_name[j];
1066                                 while (*tmp) *s++ = *tmp++;
1067                                 str++;
1068                         }
1069
1070                         break;
1071                 case '#':
1072                 {
1073                         int j;
1074                         for (j = 0; *str && *str != '\r'; j++)
1075                                 key_code[j] = *str++;
1076                         key_code[j] = '\0';
1077                         break;
1078                 }
1079                 default:
1080                         if (ch != *str) return FALSE;
1081                         str++;
1082                 }
1083         }
1084
1085         if (*str++ != '\r') return FALSE;
1086
1087         for (i = 0; i < max_macrotrigger; i++)
1088         {
1089                 if (!my_stricmp(key_code, macro_trigger_keycode[0][i])
1090                         || !my_stricmp(key_code, macro_trigger_keycode[1][i]))
1091                         break;
1092         }
1093
1094         if (i == max_macrotrigger)
1095                 return FALSE;
1096
1097         tmp = macro_trigger_name[i];
1098         while (*tmp) *s++ = *tmp++;
1099
1100         *s++ = ']';
1101
1102         *bufptr = s;
1103         *strptr = str;
1104         return TRUE;
1105 }
1106
1107
1108 /*
1109  * Hack -- convert a string into a printable form
1110  */
1111 void ascii_to_text(char *buf, concptr str)
1112 {
1113         char *s = buf;
1114         while (*str)
1115         {
1116                 byte i = (byte)(*str++);
1117                 if (i == 31)
1118                 {
1119                         if (!trigger_ascii_to_text(&s, &str))
1120                         {
1121                                 *s++ = '^';
1122                                 *s++ = '_';
1123                         }
1124                 }
1125                 else
1126                 {
1127                         if (i == ESCAPE)
1128                         {
1129                                 *s++ = '\\';
1130                                 *s++ = 'e';
1131                         }
1132                         else if (i == ' ')
1133                         {
1134                                 *s++ = '\\';
1135                                 *s++ = 's';
1136                         }
1137                         else if (i == '\b')
1138                         {
1139                                 *s++ = '\\';
1140                                 *s++ = 'b';
1141                         }
1142                         else if (i == '\t')
1143                         {
1144                                 *s++ = '\\';
1145                                 *s++ = 't';
1146                         }
1147                         else if (i == '\n')
1148                         {
1149                                 *s++ = '\\';
1150                                 *s++ = 'n';
1151                         }
1152                         else if (i == '\r')
1153                         {
1154                                 *s++ = '\\';
1155                                 *s++ = 'r';
1156                         }
1157                         else if (i == '^')
1158                         {
1159                                 *s++ = '\\';
1160                                 *s++ = '^';
1161                         }
1162                         else if (i == '\\')
1163                         {
1164                                 *s++ = '\\';
1165                                 *s++ = '\\';
1166                         }
1167                         else if (i < 32)
1168                         {
1169                                 *s++ = '^';
1170                                 *s++ = i + 64;
1171                         }
1172                         else if (i < 127)
1173                         {
1174                                 *s++ = i;
1175                         }
1176                         else if (i < 64)
1177                         {
1178                                 *s++ = '\\';
1179                                 *s++ = '0';
1180                                 *s++ = octify(i / 8);
1181                                 *s++ = octify(i % 8);
1182                         }
1183                         else
1184                         {
1185                                 *s++ = '\\';
1186                                 *s++ = 'x';
1187                                 *s++ = hexify(i / 16);
1188                                 *s++ = hexify(i % 16);
1189                         }
1190                 }
1191         }
1192
1193         *s = '\0';
1194 }
1195
1196
1197  /*
1198   * Determine if any macros have ever started with a given character.
1199   */
1200 static bool macro__use[256];
1201
1202
1203 /*
1204  * Find the macro (if any) which exactly matches the given pattern
1205  */
1206 sint macro_find_exact(concptr pat)
1207 {
1208         if (!macro__use[(byte)(pat[0])])
1209         {
1210                 return -1;
1211         }
1212
1213         for (int i = 0; i < macro__num; ++i)
1214         {
1215                 if (!streq(macro__pat[i], pat)) continue;
1216
1217                 return (i);
1218         }
1219
1220         return -1;
1221 }
1222
1223
1224 /*
1225  * Find the first macro (if any) which contains the given pattern
1226  */
1227 static sint macro_find_check(concptr pat)
1228 {
1229         if (!macro__use[(byte)(pat[0])])
1230         {
1231                 return -1;
1232         }
1233
1234         for (int i = 0; i < macro__num; ++i)
1235         {
1236                 if (!prefix(macro__pat[i], pat)) continue;
1237
1238                 return (i);
1239         }
1240
1241         return -1;
1242 }
1243
1244
1245 /*
1246  * Find the first macro (if any) which contains the given pattern and more
1247  */
1248 static sint macro_find_maybe(concptr pat)
1249 {
1250         if (!macro__use[(byte)(pat[0])])
1251         {
1252                 return -1;
1253         }
1254
1255         for (int i = 0; i < macro__num; ++i)
1256         {
1257                 if (!prefix(macro__pat[i], pat)) continue;
1258                 if (streq(macro__pat[i], pat)) continue;
1259
1260                 return (i);
1261         }
1262
1263         return -1;
1264 }
1265
1266
1267 /*
1268  * Find the longest macro (if any) which starts with the given pattern
1269  */
1270 static sint macro_find_ready(concptr pat)
1271 {
1272         int t, n = -1, s = -1;
1273
1274         if (!macro__use[(byte)(pat[0])])
1275         {
1276                 return -1;
1277         }
1278
1279         for (int i = 0; i < macro__num; ++i)
1280         {
1281                 if (!prefix(pat, macro__pat[i])) continue;
1282
1283                 t = strlen(macro__pat[i]);
1284                 if ((n >= 0) && (s > t)) continue;
1285
1286                 n = i;
1287                 s = t;
1288         }
1289
1290         return (n);
1291 }
1292
1293
1294 /*
1295  * Add a macro definition (or redefinition).
1296  *
1297  * We should use "act == NULL" to "remove" a macro, but this might make it
1298  * impossible to save the "removal" of a macro definition.
1299  *
1300  * We should consider refusing to allow macros which contain existing macros,
1301  * or which are contained in existing macros, because this would simplify the
1302  * macro analysis code.
1303  *
1304  * We should consider removing the "command macro" crap, and replacing it
1305  * with some kind of "powerful keymap" ability, but this might make it hard
1306  * to change the "roguelike" option from inside the game.
1307  */
1308 errr macro_add(concptr pat, concptr act)
1309 {
1310         if (!pat || !act) return -1;
1311
1312         int n = macro_find_exact(pat);
1313         if (n >= 0)
1314         {
1315                 string_free(macro__act[n]);
1316         }
1317         else
1318         {
1319                 n = macro__num++;
1320                 macro__pat[n] = string_make(pat);
1321         }
1322
1323         macro__act[n] = string_make(act);
1324         macro__use[(byte)(pat[0])] = TRUE;
1325         return 0;
1326 }
1327
1328
1329 /*
1330  * Local variable -- we are inside a "macro action"
1331  *
1332  * Do not match any macros until "ascii 30" is found.
1333  */
1334 static bool parse_macro = FALSE;
1335
1336 /*
1337  * Local variable -- we are inside a "macro trigger"
1338  *
1339  * Strip all keypresses until a low ascii value is found.
1340  */
1341 static bool parse_under = FALSE;
1342
1343 /*
1344  * Flush all input chars.  Actually, remember the flush,
1345  * and do a "special flush" before the next "inkey()".
1346  *
1347  * This is not only more efficient, but also necessary to make sure
1348  * that various "inkey()" codes are not "lost" along the way.
1349  */
1350 void flush(void)
1351 {
1352         inkey_xtra = TRUE;
1353 }
1354
1355
1356 /*
1357  * Flush the screen, make a noise
1358  */
1359 void bell(void)
1360 {
1361         Term_fresh();
1362         if (ring_bell) Term_xtra(TERM_XTRA_NOISE, 0);
1363
1364         flush();
1365 }
1366
1367
1368 /*
1369  * Hack -- Make a (relevant?) sound
1370  */
1371 void sound(int val)
1372 {
1373         if (!use_sound) return;
1374
1375         Term_xtra(TERM_XTRA_SOUND, val);
1376 }
1377
1378
1379 /*
1380  * Hack -- Play a music
1381  */
1382 errr play_music(int type, int val)
1383 {
1384         if (!use_music) return 1;
1385
1386         return Term_xtra(type, val);
1387 }
1388
1389
1390 /*
1391  * Hack -- Select floor music.
1392  */
1393 void select_floor_music(player_type *player_ptr)
1394 {
1395         if (!use_music) return;
1396
1397         if (player_ptr->ambush_flag)
1398         {
1399                 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_AMBUSH)) return;
1400         }
1401
1402         if (player_ptr->wild_mode)
1403         {
1404                 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_WILD)) return;
1405         }
1406
1407         if (player_ptr->current_floor_ptr->inside_arena)
1408         {
1409                 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_ARENA)) return;
1410         }
1411
1412         if (player_ptr->phase_out)
1413         {
1414                 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_BATTLE)) return;
1415         }
1416
1417         if (player_ptr->current_floor_ptr->inside_quest)
1418         {
1419                 if (!play_music(TERM_XTRA_MUSIC_QUEST, player_ptr->current_floor_ptr->inside_quest)) return;
1420                 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_QUEST)) return;
1421         }
1422
1423         if (player_ptr->dungeon_idx)
1424         {
1425                 if (player_ptr->feeling == 2)
1426                 {
1427                         if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_FEEL2)) return;
1428                 }
1429                 else if (player_ptr->feeling >= 3 && player_ptr->feeling <= 5)
1430                 {
1431                         if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_FEEL1)) return;
1432                 }
1433                 else
1434                 {
1435                         if (!play_music(TERM_XTRA_MUSIC_DUNGEON, player_ptr->dungeon_idx)) return;
1436
1437                         if (player_ptr->current_floor_ptr->dun_level < 40)
1438                         {
1439                                 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_LOW)) return;
1440                         }
1441                         else if (player_ptr->current_floor_ptr->dun_level < 80)
1442                         {
1443                                 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_MED)) return;
1444                         }
1445                         else
1446                         {
1447                                 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_HIGH)) return;
1448                         }
1449                 }
1450         }
1451
1452         if (player_ptr->town_num)
1453         {
1454                 if (!play_music(TERM_XTRA_MUSIC_TOWN, player_ptr->town_num)) return;
1455                 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_TOWN)) return;
1456                 return;
1457         }
1458
1459         if (!player_ptr->current_floor_ptr->dun_level)
1460         {
1461                 if (player_ptr->lev >= 45)
1462                 {
1463                         if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD3)) return;
1464                 }
1465                 else if (player_ptr->lev >= 25)
1466                 {
1467                         if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD2)) return;
1468                 }
1469                 else
1470                 {
1471                         if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD1)) return;
1472                 }
1473         }
1474
1475         play_music(TERM_XTRA_MUSIC_MUTE, 0);
1476 }
1477
1478
1479
1480 /*
1481  * Helper function called only from "inkey()"
1482  *
1483  * This function does almost all of the "macro" processing.
1484  *
1485  * We use the "Term_key_push()" function to handle "failed" macros, as well
1486  * as "extra" keys read in while choosing the proper macro, and also to hold
1487  * the action for the macro, plus a special "ascii 30" character indicating
1488  * that any macro action in progress is complete.  Embedded macros are thus
1489  * illegal, unless a macro action includes an explicit "ascii 30" character,
1490  * which would probably be a massive hack, and might break things.
1491  *
1492  * Only 500 (0+1+2+...+29+30) milliseconds may elapse between each key in
1493  * the macro trigger sequence.  If a key sequence forms the "prefix" of a
1494  * macro trigger, 500 milliseconds must pass before the key sequence is
1495  * known not to be that macro trigger.
1496  */
1497 static char inkey_aux(void)
1498 {
1499         int k = 0, n, p = 0, w = 0;
1500         char ch;
1501         char *buf = inkey_macro_trigger_string;
1502
1503         num_more = 0;
1504
1505         if (parse_macro)
1506         {
1507                 if (Term_inkey(&ch, FALSE, TRUE))
1508                 {
1509                         parse_macro = FALSE;
1510                 }
1511         }
1512         else
1513         {
1514                 (void)(Term_inkey(&ch, TRUE, TRUE));
1515         }
1516
1517         if (ch == 30) parse_macro = FALSE;
1518
1519         if (ch == 30) return (ch);
1520         if (parse_macro) return (ch);
1521         if (parse_under) return (ch);
1522
1523         buf[p++] = ch;
1524         buf[p] = '\0';
1525         k = macro_find_check(buf);
1526         if (k < 0) return (ch);
1527
1528         while (TRUE)
1529         {
1530                 k = macro_find_maybe(buf);
1531
1532                 if (k < 0) break;
1533
1534                 if (0 == Term_inkey(&ch, FALSE, TRUE))
1535                 {
1536                         buf[p++] = ch;
1537                         buf[p] = '\0';
1538                         w = 0;
1539                 }
1540                 else
1541                 {
1542                         w += 1;
1543                         if (w >= 10) break;
1544
1545                         Term_xtra(TERM_XTRA_DELAY, w);
1546                 }
1547         }
1548
1549         k = macro_find_ready(buf);
1550         if (k < 0)
1551         {
1552                 while (p > 0)
1553                 {
1554                         if (Term_key_push(buf[--p])) return 0;
1555                 }
1556
1557                 (void)Term_inkey(&ch, TRUE, TRUE);
1558                 return (ch);
1559         }
1560
1561         concptr pat = macro__pat[k];
1562         n = strlen(pat);
1563         while (p > n)
1564         {
1565                 if (Term_key_push(buf[--p])) return 0;
1566         }
1567
1568         parse_macro = TRUE;
1569         if (Term_key_push(30)) return 0;
1570
1571         concptr act = macro__act[k];
1572
1573         n = strlen(act);
1574         while (n > 0)
1575         {
1576                 if (Term_key_push(act[--n])) return 0;
1577         }
1578
1579         return 0;
1580 }
1581
1582
1583 /*
1584  * Cancel macro action on the queue
1585  */
1586 static void forget_macro_action(void)
1587 {
1588         if (!parse_macro) return;
1589
1590         while (TRUE)
1591         {
1592                 char ch;
1593                 if (Term_inkey(&ch, FALSE, TRUE)) break;
1594                 if (ch == 0) break;
1595                 if (ch == 30) break;
1596         }
1597
1598         parse_macro = FALSE;
1599 }
1600
1601 /*
1602  * Mega-Hack -- special "inkey_next" pointer.
1603  *
1604  * This special pointer allows a sequence of keys to be "inserted" into
1605  * the stream of keys returned by "inkey()".  This key sequence will not
1606  * trigger any macros, and cannot be bypassed by the Borg.  It is used
1607  * in Angband to handle "keymaps".
1608  */
1609 static concptr inkey_next = NULL;
1610
1611 /*
1612  * Get a keypress from the user.
1613  *
1614  * This function recognizes a few "global parameters".  These are variables
1615  * which, if set to TRUE before calling this function, will have an effect
1616  * on this function, and which are always reset to FALSE by this function
1617  * before this function returns.  Thus they function just like normal
1618  * parameters, except that most calls to this function can ignore them.
1619  *
1620  * If "inkey_xtra" is TRUE, then all pending keypresses will be flushed,
1621  * and any macro processing in progress will be aborted.  This flag is
1622  * set by the "flush()" function, which does not actually flush anything
1623  * itself, but rather, triggers delayed input flushing via "inkey_xtra".
1624  *
1625  * If "inkey_scan" is TRUE, then we will immediately return "zero" if no
1626  * keypress is available, instead of waiting for a keypress.
1627  *
1628  * If "inkey_base" is TRUE, then all macro processing will be bypassed.
1629  * If "inkey_base" and "inkey_scan" are both TRUE, then this function will
1630  * not return immediately, but will wait for a keypress for as long as the
1631  * normal macro matching code would, allowing the direct entry of macro
1632  * triggers.  The "inkey_base" flag is extremely dangerous!
1633  *
1634  * If "inkey_flag" is TRUE, then we will assume that we are waiting for a
1635  * normal command, and we will only show the cursor if "hilite_player" is
1636  * TRUE (or if the player is in a store), instead of always showing the
1637  * cursor.  The various "main-xxx.c" files should avoid saving the game
1638  * in response to a "menu item" request unless "inkey_flag" is TRUE, to
1639  * prevent savefile corruption.
1640  *
1641  * If we are waiting for a keypress, and no keypress is ready, then we will
1642  * refresh (once) the window which was active when this function was called.
1643  *
1644  * Note that "back-quote" is automatically converted into "escape" for
1645  * convenience on machines with no "escape" key.  This is done after the
1646  * macro matching, so the user can still make a macro for "backquote".
1647  *
1648  * Note the special handling of "ascii 30" (ctrl-caret, aka ctrl-shift-six)
1649  * and "ascii 31" (ctrl-underscore, aka ctrl-shift-minus), which are used to
1650  * provide support for simple keyboard "macros".  These keys are so strange
1651  * that their loss as normal keys will probably be noticed by nobody.  The
1652  * "ascii 30" key is used to indicate the "end" of a macro action, which
1653  * allows recursive macros to be avoided.  The "ascii 31" key is used by
1654  * some of the "main-xxx.c" files to introduce macro trigger sequences.
1655  *
1656  * Hack -- we use "ascii 29" (ctrl-right-bracket) as a special "magic" key,
1657  * which can be used to give a variety of "sub-commands" which can be used
1658  * any time.  These sub-commands could include commands to take a picture of
1659  * the current screen, to start/stop recording a macro action, etc.
1660  *
1661  * If "angband_term[0]" is not active, we will make it active during this
1662  * function, so that the various "main-xxx.c" files can assume that input
1663  * is only requested (via "Term_inkey()") when "angband_term[0]" is active.
1664  *
1665  * Mega-Hack -- This function is used as the entry point for clearing the
1666  * "signal_count" variable, and of the "current_world_ptr->character_saved" variable.
1667  *
1668  * Hack -- Note the use of "inkey_next" to allow "keymaps" to be processed.
1669  *
1670  * Mega-Hack -- Note the use of "inkey_hack" to allow the "Borg" to steal
1671  * control of the keyboard from the user.
1672  */
1673 char inkey(void)
1674 {
1675         char ch = 0;
1676         bool done = FALSE;
1677         term *old = Term;
1678
1679         if (inkey_next && *inkey_next && !inkey_xtra)
1680         {
1681                 ch = *inkey_next++;
1682                 inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
1683                 return (ch);
1684         }
1685
1686         inkey_next = NULL;
1687         if (inkey_xtra)
1688         {
1689                 parse_macro = FALSE;
1690                 parse_under = FALSE;
1691                 Term_flush();
1692         }
1693
1694         int v;
1695         (void)Term_get_cursor(&v);
1696
1697         /* Show the cursor if waiting, except sometimes in "command" mode */
1698         if (!inkey_scan && (!inkey_flag || hilite_player || current_world_ptr->character_icky))
1699         {
1700                 (void)Term_set_cursor(1);
1701         }
1702
1703         Term_activate(angband_term[0]);
1704         char kk;
1705         while (!ch)
1706         {
1707                 if (!inkey_base && inkey_scan &&
1708                         (0 != Term_inkey(&kk, FALSE, FALSE)))
1709                 {
1710                         break;
1711                 }
1712
1713                 if (!done && (0 != Term_inkey(&kk, FALSE, FALSE)))
1714                 {
1715                         Term_activate(old);
1716                         Term_fresh();
1717                         Term_activate(angband_term[0]);
1718                         current_world_ptr->character_saved = FALSE;
1719
1720                         signal_count = 0;
1721                         done = TRUE;
1722                 }
1723
1724                 if (inkey_base)
1725                 {
1726                         int w = 0;
1727                         if (!inkey_scan)
1728                         {
1729                                 if (0 == Term_inkey(&ch, TRUE, TRUE))
1730                                 {
1731                                         break;
1732                                 }
1733
1734                                 break;
1735                         }
1736
1737                         while (TRUE)
1738                         {
1739                                 if (0 == Term_inkey(&ch, FALSE, TRUE))
1740                                 {
1741                                         break;
1742                                 }
1743                                 else
1744                                 {
1745                                         w += 10;
1746                                         if (w >= 100) break;
1747
1748                                         Term_xtra(TERM_XTRA_DELAY, w);
1749                                 }
1750                         }
1751
1752                         break;
1753                 }
1754
1755                 ch = inkey_aux();
1756                 if (ch == 29)
1757                 {
1758                         ch = 0;
1759                         continue;
1760                 }
1761
1762                 if (parse_under && (ch <= 32))
1763                 {
1764                         ch = 0;
1765                         parse_under = FALSE;
1766                 }
1767
1768                 if (ch == 30)
1769                 {
1770                         ch = 0;
1771                 }
1772                 else if (ch == 31)
1773                 {
1774                         ch = 0;
1775                         parse_under = TRUE;
1776                 }
1777                 else if (parse_under)
1778                 {
1779                         ch = 0;
1780                 }
1781         }
1782
1783         Term_activate(old);
1784         Term_set_cursor(v);
1785         inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
1786         return (ch);
1787 }
1788
1789
1790  /*
1791   * Initialize the quark array
1792   */
1793 void quark_init(void)
1794 {
1795         C_MAKE(quark__str, QUARK_MAX, concptr);
1796         quark__str[1] = string_make("");
1797         quark__num = 2;
1798 }
1799
1800
1801 /*
1802  * Add a new "quark" to the set of quarks.
1803  */
1804 u16b quark_add(concptr str)
1805 {
1806         u16b i;
1807         for (i = 1; i < quark__num; i++)
1808         {
1809                 if (streq(quark__str[i], str)) return (i);
1810         }
1811
1812         if (quark__num == QUARK_MAX) return 1;
1813
1814         quark__num = i + 1;
1815         quark__str[i] = string_make(str);
1816         return (i);
1817 }
1818
1819
1820 /*
1821  * This function looks up a quark
1822  */
1823 concptr quark_str(STR_OFFSET i)
1824 {
1825         concptr q;
1826
1827         /* Return NULL for an invalid index */
1828         if ((i < 1) || (i >= quark__num)) return NULL;
1829
1830         /* Access the quark */
1831         q = quark__str[i];
1832
1833         /* Return the quark */
1834         return (q);
1835 }
1836
1837
1838  /*!
1839   * @brief 保存中の過去ゲームメッセージの数を返す。 / How many messages are "available"?
1840   * @return 残っているメッセージの数
1841   */
1842 s32b message_num(void)
1843 {
1844         int n;
1845         int last = message__last;
1846         int next = message__next;
1847
1848         if (next < last) next += MESSAGE_MAX;
1849
1850         n = (next - last);
1851         return (n);
1852 }
1853
1854
1855 /*!
1856  * @brief 過去のゲームメッセージを返す。 / Recall the "text" of a saved message
1857  * @params age メッセージの世代
1858  * @return メッセージの文字列ポインタ
1859  */
1860 concptr message_str(int age)
1861 {
1862         if ((age < 0) || (age >= message_num())) return ("");
1863
1864         s32b x = (message__next + MESSAGE_MAX - (age + 1)) % MESSAGE_MAX;
1865         s32b o = message__ptr[x];
1866         concptr s = &message__buf[o];
1867         return (s);
1868 }
1869
1870
1871 /*!
1872  * @brief ゲームメッセージをログに追加する。 / Add a new message, with great efficiency
1873  * @params str 保存したいメッセージ
1874  * @return なし
1875  */
1876 void message_add(concptr str)
1877 {
1878         u32b i;
1879         int x, m;
1880         char u[4096];
1881         char splitted1[81];
1882         concptr splitted2;
1883
1884         if (!str) return;
1885
1886         u32b n = strlen(str);
1887         if (n >= MESSAGE_BUF / 4) return;
1888
1889         if (n > 80)
1890         {
1891 #ifdef JP
1892                 concptr t = str;
1893                 for (n = 0; n < 80; n++, t++)
1894                 {
1895                         if (iskanji(*t)) {
1896                                 t++;
1897                                 n++;
1898                         }
1899                 }
1900
1901                 /* 最後の文字が漢字半分 */
1902                 if (n == 81) n = 79;
1903 #else
1904                 for (n = 80; n > 60; n--)
1905                         if (str[n] == ' ') break;
1906                 if (n == 60) n = 80;
1907 #endif
1908                 splitted2 = str + n;
1909                 strncpy(splitted1, str, n);
1910                 splitted1[n] = '\0';
1911                 str = splitted1;
1912         }
1913         else
1914         {
1915                 splitted2 = NULL;
1916         }
1917
1918         m = message_num();
1919         int k = m / 4;
1920         if (k > MESSAGE_MAX / 32) k = MESSAGE_MAX / 32;
1921         for (i = message__next; m; m--)
1922         {
1923                 int j = 1;
1924                 char buf[1024];
1925                 char *t;
1926                 concptr old;
1927                 if (i-- == 0) i = MESSAGE_MAX - 1;
1928
1929                 old = &message__buf[message__ptr[i]];
1930                 if (!old) continue;
1931
1932                 strcpy(buf, old);
1933 #ifdef JP
1934                 for (t = buf; *t && (*t != '<' || (*(t + 1) != 'x')); t++)
1935                         if (iskanji(*t))t++;
1936 #else
1937                 for (t = buf; *t && (*t != '<'); t++);
1938 #endif
1939                 if (*t)
1940                 {
1941                         if (strlen(buf) < A_MAX) break;
1942
1943                         *(t - 1) = '\0';
1944                         j = atoi(t + 2);
1945                 }
1946
1947                 if (streq(buf, str) && (j < 1000))
1948                 {
1949                         j++;
1950                         message__next = i;
1951                         str = u;
1952                         sprintf(u, "%s <x%d>", buf, j);
1953                         n = strlen(str);
1954                         if (!now_message) now_message++;
1955                 }
1956                 else
1957                 {
1958                         /*流れた行の数を数えておく */
1959                         num_more++;
1960                         now_message++;
1961                 }
1962
1963                 break;
1964         }
1965
1966         for (i = message__next; k; k--)
1967         {
1968                 int q;
1969                 concptr old;
1970
1971                 if (i-- == 0) i = MESSAGE_MAX - 1;
1972
1973                 if (i == message__last) break;
1974
1975                 q = (message__head + MESSAGE_BUF - message__ptr[i]) % MESSAGE_BUF;
1976
1977                 if (q > MESSAGE_BUF / 2) continue;
1978
1979                 old = &message__buf[message__ptr[i]];
1980                 if (!streq(old, str)) continue;
1981
1982                 x = message__next++;
1983                 if (message__next == MESSAGE_MAX) message__next = 0;
1984                 if (message__next == message__last) message__last++;
1985                 if (message__last == MESSAGE_MAX) message__last = 0;
1986
1987                 message__ptr[x] = message__ptr[i];
1988                 if (splitted2 != NULL)
1989                 {
1990                         message_add(splitted2);
1991                 }
1992
1993                 return;
1994         }
1995
1996         if (message__head + n + 1 >= MESSAGE_BUF)
1997         {
1998                 for (i = message__last; TRUE; i++)
1999                 {
2000                         if (i == MESSAGE_MAX) i = 0;
2001                         if (i == message__next) break;
2002                         if (message__ptr[i] >= message__head)
2003                         {
2004                                 message__last = i + 1;
2005                         }
2006                 }
2007
2008                 if (message__tail >= message__head) message__tail = 0;
2009
2010                 message__head = 0;
2011         }
2012
2013         if (message__head + n + 1 > message__tail)
2014         {
2015                 message__tail = message__head + n + 1;
2016                 while (message__buf[message__tail - 1]) message__tail++;
2017
2018                 for (i = message__last; TRUE; i++)
2019                 {
2020                         if (i == MESSAGE_MAX) i = 0;
2021                         if (i == message__next) break;
2022                         if ((message__ptr[i] >= message__head) &&
2023                                 (message__ptr[i] < message__tail))
2024                         {
2025                                 message__last = i + 1;
2026                         }
2027                 }
2028         }
2029
2030
2031         x = message__next++;
2032         if (message__next == MESSAGE_MAX) message__next = 0;
2033         if (message__next == message__last) message__last++;
2034         if (message__last == MESSAGE_MAX) message__last = 0;
2035
2036         message__ptr[x] = message__head;
2037         for (i = 0; i < n; i++)
2038         {
2039                 message__buf[message__head + i] = str[i];
2040         }
2041
2042         message__buf[message__head + i] = '\0';
2043         message__head += n + 1;
2044
2045         if (splitted2 != NULL)
2046         {
2047                 message_add(splitted2);
2048         }
2049 }
2050
2051
2052 /*
2053  * Hack -- flush
2054  */
2055 static void msg_flush(player_type *player_ptr, int x)
2056 {
2057         byte a = TERM_L_BLUE;
2058         bool nagasu = FALSE;
2059         if ((auto_more && !player_ptr->now_damaged) || num_more < 0) {
2060                 int i;
2061                 for (i = 0; i < 8; i++)
2062                 {
2063                         if (angband_term[i] && (window_flag[i] & PW_MESSAGE)) break;
2064                 }
2065                 if (i < 8)
2066                 {
2067                         if (num_more < angband_term[i]->hgt) nagasu = TRUE;
2068                 }
2069                 else
2070                 {
2071                         nagasu = TRUE;
2072                 }
2073         }
2074
2075         player_ptr->now_damaged = FALSE;
2076         if (!player_ptr->playing || !nagasu)
2077         {
2078                 Term_putstr(x, 0, -1, a, _("-続く-", "-more-"));
2079                 while (TRUE)
2080                 {
2081                         int cmd = inkey();
2082                         if (cmd == ESCAPE)
2083                         {
2084                                 /* auto_moreのとき、全て流す */
2085                                 num_more = -9999;
2086                                 break;
2087                         }
2088                         else if (cmd == ' ')
2089                         {
2090                                 /* 1画面だけ流す */
2091                                 num_more = 0;
2092                                 break;
2093                         }
2094                         else if ((cmd == '\n') || (cmd == '\r'))
2095                         {
2096                                 /* 1行だけ流す */
2097                                 num_more--;
2098                                 break;
2099                         }
2100
2101                         if (quick_messages) break;
2102                         bell();
2103                 }
2104         }
2105
2106         Term_erase(0, 0, 255);
2107 }
2108
2109
2110 void msg_erase(void)
2111 {
2112         msg_print(NULL);
2113 }
2114
2115
2116 /*
2117  * todo ここのp_ptrを削除するのは破滅的に作業が増えるので保留
2118  * Output a message to the top line of the screen.
2119  *
2120  * Break long messages into multiple pieces (40-72 chars).
2121  *
2122  * Allow multiple short messages to "share" the top line.
2123  *
2124  * Prompt the user to make sure he has a chance to read them.
2125  *
2126  * These messages are memorized for later reference (see above).
2127  *
2128  * We could do "Term_fresh()" to provide "flicker" if needed.
2129  *
2130  * The global "msg_flag" variable can be cleared to tell us to
2131  * "erase" any "pending" messages still on the screen.
2132  *
2133  * Note that we must be very careful about using the
2134  * "msg_print()" functions without explicitly calling the special
2135  * "msg_print(NULL)" function, since this may result in the loss
2136  * of information if the screen is cleared, or if anything is
2137  * displayed on the top line.
2138  *
2139  * Note that "msg_print(NULL)" will clear the top line
2140  * even if no messages are pending.  This is probably a hack.
2141  */
2142 void msg_print(concptr msg)
2143 {
2144         static int p = 0;
2145         char *t;
2146         char buf[1024];
2147
2148         if (current_world_ptr->timewalk_m_idx) return;
2149
2150         if (!msg_flag)
2151         {
2152                 Term_erase(0, 0, 255);
2153                 p = 0;
2154         }
2155
2156         int n = (msg ? strlen(msg) : 0);
2157         if (p && (!msg || ((p + n) > 72)))
2158         {
2159                 msg_flush(p_ptr, p);
2160                 msg_flag = FALSE;
2161                 p = 0;
2162         }
2163
2164         if (!msg) return;
2165         if (n > 1000) return;
2166
2167         if (!cheat_turn)
2168         {
2169                 strcpy(buf, msg);
2170         }
2171         else
2172         {
2173                 sprintf(buf, ("T:%d - %s"), (int)current_world_ptr->game_turn, msg);
2174         }
2175
2176         n = strlen(buf);
2177         if (current_world_ptr->character_generated) message_add(buf);
2178
2179         t = buf;
2180         while (n > 72)
2181         {
2182                 int check, split = 72;
2183 #ifdef JP
2184                 bool k_flag = FALSE;
2185                 int wordlen = 0;
2186                 for (check = 0; check < 72; check++)
2187                 {
2188                         if (k_flag)
2189                         {
2190                                 k_flag = FALSE;
2191                                 continue;
2192                         }
2193
2194                         if (iskanji(t[check]))
2195                         {
2196                                 k_flag = TRUE;
2197                                 split = check;
2198                         }
2199                         else if (t[check] == ' ')
2200                         {
2201                                 split = check;
2202                                 wordlen = 0;
2203                         }
2204                         else
2205                         {
2206                                 wordlen++;
2207                                 if (wordlen > 20)
2208                                         split = check;
2209                         }
2210                 }
2211
2212 #else
2213                 for (check = 40; check < 72; check++)
2214                 {
2215                         if (t[check] == ' ') split = check;
2216                 }
2217 #endif
2218
2219                 char oops = t[split];
2220                 t[split] = '\0';
2221                 Term_putstr(0, 0, split, TERM_WHITE, t);
2222                 msg_flush(p_ptr, split + 1);
2223                 t[split] = oops;
2224                 t[--split] = ' ';
2225                 t += split; n -= split;
2226         }
2227
2228         Term_putstr(p, 0, n, TERM_WHITE, t);
2229         p_ptr->window |= (PW_MESSAGE);
2230         update_output(p_ptr);
2231
2232         msg_flag = TRUE;
2233 #ifdef JP
2234         p += n;
2235 #else
2236         p += n + 1;
2237 #endif
2238
2239         if (fresh_message) Term_fresh();
2240 }
2241
2242
2243 void msg_print_wizard(int cheat_type, concptr msg)
2244 {
2245         if (!cheat_room && cheat_type == CHEAT_DUNGEON) return;
2246         if (!cheat_peek && cheat_type == CHEAT_OBJECT) return;
2247         if (!cheat_hear && cheat_type == CHEAT_MONSTER) return;
2248         if (!cheat_xtra && cheat_type == CHEAT_MISC) return;
2249
2250         concptr cheat_mes[] = { "ITEM", "MONS", "DUNG", "MISC" };
2251         char buf[1024];
2252         sprintf(buf, "WIZ-%s:%s", cheat_mes[cheat_type], msg);
2253         msg_print(buf);
2254
2255         if (cheat_diary_output)
2256         {
2257                 exe_write_diary(p_ptr, DIARY_WIZARD_LOG, 0, buf);
2258         }
2259
2260 }
2261
2262
2263 /*
2264  * Hack -- prevent "accidents" in "screen_save()" or "screen_load()"
2265  */
2266 static int screen_depth = 0;
2267
2268
2269 /*
2270  * Save the screen, and increase the "icky" depth.
2271  *
2272  * This function must match exactly one call to "screen_load()".
2273  */
2274 void screen_save()
2275 {
2276         msg_print(NULL);
2277         if (screen_depth++ == 0) Term_save();
2278
2279         current_world_ptr->character_icky++;
2280 }
2281
2282
2283 /*
2284  * Load the screen, and decrease the "icky" depth.
2285  *
2286  * This function must match exactly one call to "screen_save()".
2287  */
2288 void screen_load()
2289 {
2290         msg_print(NULL);
2291         if (--screen_depth == 0) Term_load();
2292
2293         current_world_ptr->character_icky--;
2294 }
2295
2296
2297 /*
2298  * Display a formatted message, using "vstrnfmt()" and "msg_print()".
2299  */
2300 void msg_format(concptr fmt, ...)
2301 {
2302         va_list vp;
2303         char buf[1024];
2304         va_start(vp, fmt);
2305         (void)vstrnfmt(buf, 1024, fmt, vp);
2306         va_end(vp);
2307         msg_print(buf);
2308 }
2309
2310
2311 /*
2312  * Display a formatted message, using "vstrnfmt()" and "msg_print()".
2313  */
2314 void msg_format_wizard(int cheat_type, concptr fmt, ...)
2315 {
2316         if (!cheat_room && cheat_type == CHEAT_DUNGEON) return;
2317         if (!cheat_peek && cheat_type == CHEAT_OBJECT) return;
2318         if (!cheat_hear && cheat_type == CHEAT_MONSTER) return;
2319         if (!cheat_xtra && cheat_type == CHEAT_MISC) return;
2320
2321         va_list vp;
2322         char buf[1024];
2323         va_start(vp, fmt);
2324         (void)vstrnfmt(buf, 1024, fmt, vp);
2325         va_end(vp);
2326         msg_print_wizard(cheat_type, buf);
2327 }
2328
2329
2330 /*
2331  * Display a string on the screen using an attribute.
2332  *
2333  * At the given location, using the given attribute, if allowed,
2334  * add the given string.  Do not clear the line.
2335  */
2336 void c_put_str(TERM_COLOR attr, concptr str, TERM_LEN row, TERM_LEN col)
2337 {
2338         Term_putstr(col, row, -1, attr, str);
2339 }
2340
2341
2342 /*
2343  * As above, but in "white"
2344  */
2345 void put_str(concptr str, TERM_LEN row, TERM_LEN col)
2346 {
2347         Term_putstr(col, row, -1, TERM_WHITE, str);
2348 }
2349
2350
2351 /*
2352  * Display a string on the screen using an attribute, and clear
2353  * to the end of the line.
2354  */
2355 void c_prt(TERM_COLOR attr, concptr str, TERM_LEN row, TERM_LEN col)
2356 {
2357         Term_erase(col, row, 255);
2358         Term_addstr(-1, attr, str);
2359 }
2360
2361
2362 /*
2363  * As above, but in "white"
2364  */
2365 void prt(concptr str, TERM_LEN row, TERM_LEN col)
2366 {
2367         /* Spawn */
2368         c_prt(TERM_WHITE, str, row, col);
2369 }
2370
2371
2372 /*
2373  * Print some (colored) text to the screen at the current cursor position,
2374  * automatically "wrapping" existing text (at spaces) when necessary to
2375  * avoid placing any text into the last column, and clearing every line
2376  * before placing any text in that line.  Also, allow "newline" to force
2377  * a "wrap" to the next line.  Advance the cursor as needed so sequential
2378  * calls to this function will work correctly.
2379  *
2380  * Once this function has been called, the cursor should not be moved
2381  * until all the related "c_roff()" calls to the window are complete.
2382  *
2383  * This function will correctly handle any width up to the maximum legal
2384  * value of 256, though it works best for a standard 80 character width.
2385  */
2386 void c_roff(TERM_COLOR a, concptr str)
2387 {
2388         int w, h;
2389         (void)Term_get_size(&w, &h);
2390
2391         int x, y;
2392         (void)Term_locate(&x, &y);
2393
2394         if (y == h - 1 && x > w - 3) return;
2395
2396         for (concptr s = str; *s; s++)
2397         {
2398                 char ch;
2399 #ifdef JP
2400                 int k_flag = iskanji(*s);
2401 #endif
2402                 if (*s == '\n')
2403                 {
2404                         x = 0;
2405                         y++;
2406                         if (y == h) break;
2407
2408                         Term_erase(x, y, 255);
2409                         break;
2410                 }
2411
2412 #ifdef JP
2413                 ch = ((k_flag || isprint(*s)) ? *s : ' ');
2414 #else
2415                 ch = (isprint(*s) ? *s : ' ');
2416 #endif
2417
2418 #ifdef JP
2419                 if ((x >= ((k_flag) ? w - 2 : w - 1)) && (ch != ' '))
2420 #else
2421                 if ((x >= w - 1) && (ch != ' '))
2422 #endif
2423                 {
2424                         int i, n = 0;
2425
2426                         TERM_COLOR av[256];
2427                         char cv[256];
2428                         if (x < w)
2429 #ifdef JP
2430                         {
2431                                 /* 現在が半角文字の場合 */
2432                                 if (!k_flag)
2433 #endif
2434                                 {
2435                                         for (i = w - 2; i >= 0; i--)
2436                                         {
2437                                                 Term_what(i, y, &av[i], &cv[i]);
2438                                                 if (cv[i] == ' ') break;
2439
2440                                                 n = i;
2441 #ifdef JP
2442                                                 if (cv[i] == '(') break;
2443 #endif
2444                                         }
2445                                 }
2446 #ifdef JP
2447                                 else
2448                                 {
2449                                         /* 現在が全角文字のとき */
2450                                         /* 文頭が「。」「、」等になるときは、その1つ前の語で改行 */
2451                                         if (strncmp(s, "。", 2) == 0 || strncmp(s, "、", 2) == 0)
2452                                         {
2453                                                 Term_what(x, y, &av[x], &cv[x]);
2454                                                 Term_what(x - 1, y, &av[x - 1], &cv[x - 1]);
2455                                                 Term_what(x - 2, y, &av[x - 2], &cv[x - 2]);
2456                                                 n = x - 2;
2457                                                 cv[x] = '\0';
2458                                         }
2459                                 }
2460                         }
2461 #endif
2462                         if (n == 0) n = w;
2463
2464                         Term_erase(n, y, 255);
2465                         x = 0;
2466                         y++;
2467                         if (y == h) break;
2468
2469                         Term_erase(x, y, 255);
2470                         for (i = n; i < w - 1; i++)
2471                         {
2472 #ifdef JP
2473                                 if (cv[i] == '\0') break;
2474 #endif
2475                                 Term_addch(av[i], cv[i]);
2476                                 if (++x > w) x = w;
2477                         }
2478                 }
2479
2480 #ifdef JP
2481                 Term_addch((byte)(a | 0x10), ch);
2482 #else
2483                 Term_addch(a, ch);
2484 #endif
2485
2486 #ifdef JP
2487                 if (k_flag)
2488                 {
2489                         s++;
2490                         x++;
2491                         ch = *s;
2492                         Term_addch((byte)(a | 0x20), ch);
2493                 }
2494 #endif
2495
2496                 if (++x > w) x = w;
2497         }
2498 }
2499
2500
2501 /*
2502  * As above, but in "white"
2503  */
2504 void roff(concptr str)
2505 {
2506         /* Spawn */
2507         c_roff(TERM_WHITE, str);
2508 }
2509
2510
2511 /*
2512  * Clear part of the screen
2513  */
2514 void clear_from(int row)
2515 {
2516         for (int y = row; y < Term->hgt; y++)
2517         {
2518                 Term_erase(0, y, 255);
2519         }
2520 }
2521
2522
2523 /*
2524  * Get some string input at the cursor location.
2525  * Assume the buffer is initialized to a default string.
2526  *
2527  * The default buffer is in Overwrite mode and displayed in yellow at
2528  * first.  Normal chars clear the yellow text and append the char in
2529  * white text.
2530  *
2531  * LEFT (^B) and RIGHT (^F) movement keys move the cursor position.
2532  * If the text is still displayed in yellow (Overwite mode), it will
2533  * turns into white (Insert mode) when cursor moves.
2534  *
2535  * DELETE (^D) deletes a char at the cursor position.
2536  * BACKSPACE (^H) deletes a char at the left of cursor position.
2537  * ESCAPE clears the buffer and the window and returns FALSE.
2538  * RETURN accepts the current buffer contents and returns TRUE.
2539  */
2540 bool askfor_aux(char *buf, int len, bool numpad_cursor)
2541 {
2542         /*
2543          * Text color
2544          * TERM_YELLOW : Overwrite mode
2545          * TERM_WHITE : Insert mode
2546          */
2547         byte color = TERM_YELLOW;
2548
2549         int y, x;
2550         Term_locate(&x, &y);
2551         if (len < 1) len = 1;
2552         if ((x < 0) || (x >= 80)) x = 0;
2553         if (x + len > 80) len = 80 - x;
2554
2555         buf[len] = '\0';
2556
2557         int pos = 0;
2558         while (TRUE)
2559         {
2560                 Term_erase(x, y, len);
2561                 Term_putstr(x, y, -1, color, buf);
2562
2563                 Term_gotoxy(x + pos, y);
2564                 int skey = inkey_special(numpad_cursor);
2565
2566                 switch (skey)
2567                 {
2568                 case SKEY_LEFT:
2569                 case KTRL('b'):
2570                 {
2571                         int i = 0;
2572                         color = TERM_WHITE;
2573
2574                         if (0 == pos) break;
2575                         while (TRUE)
2576                         {
2577                                 int next_pos = i + 1;
2578 #ifdef JP
2579                                 if (iskanji(buf[i])) next_pos++;
2580 #endif
2581                                 if (next_pos >= pos) break;
2582
2583                                 i = next_pos;
2584                         }
2585
2586                         pos = i;
2587                         break;
2588                 }
2589
2590                 case SKEY_RIGHT:
2591                 case KTRL('f'):
2592                         color = TERM_WHITE;
2593                         if ('\0' == buf[pos]) break;
2594
2595 #ifdef JP
2596                         if (iskanji(buf[pos])) pos += 2;
2597                         else pos++;
2598 #else
2599                         pos++;
2600 #endif
2601                         break;
2602
2603                 case ESCAPE:
2604                         buf[0] = '\0';
2605                         return FALSE;
2606
2607                 case '\n':
2608                 case '\r':
2609                         return TRUE;
2610
2611                 case '\010':
2612                 {
2613                         int i = 0;
2614                         color = TERM_WHITE;
2615                         if (0 == pos) break;
2616                         while (TRUE)
2617                         {
2618                                 int next_pos = i + 1;
2619 #ifdef JP
2620                                 if (iskanji(buf[i])) next_pos++;
2621 #endif
2622                                 if (next_pos >= pos) break;
2623
2624                                 i = next_pos;
2625                         }
2626
2627                         pos = i;
2628                 }
2629                         /* Fall through */
2630
2631                 case 0x7F:
2632                 case KTRL('d'):
2633                 {
2634                         color = TERM_WHITE;
2635                         if ('\0' == buf[pos]) break;
2636                         int src = pos + 1;
2637 #ifdef JP
2638                         if (iskanji(buf[pos])) src++;
2639 #endif
2640
2641                         int dst = pos;
2642                         while ('\0' != (buf[dst++] = buf[src++]));
2643                         break;
2644                 }
2645
2646                 default:
2647                 {
2648                         char tmp[100];
2649                         if (skey & SKEY_MASK) break;
2650                         char c = (char)skey;
2651
2652                         if (color == TERM_YELLOW)
2653                         {
2654                                 buf[0] = '\0';
2655                                 color = TERM_WHITE;
2656                         }
2657
2658                         strcpy(tmp, buf + pos);
2659 #ifdef JP
2660                         if (iskanji(c))
2661                         {
2662                                 inkey_base = TRUE;
2663                                 char next = inkey();
2664                                 if (pos + 1 < len)
2665                                 {
2666                                         buf[pos++] = c;
2667                                         buf[pos++] = next;
2668                                 }
2669                                 else
2670                                 {
2671                                         bell();
2672                                 }
2673                         }
2674                         else
2675 #endif
2676                         {
2677 #ifdef JP
2678                                 if (pos < len && (isprint(c) || iskana(c)))
2679 #else
2680                                 if (pos < len && isprint(c))
2681 #endif
2682                                 {
2683                                         buf[pos++] = c;
2684                                 }
2685                                 else
2686                                 {
2687                                         bell();
2688                                 }
2689                         }
2690
2691                         buf[pos] = '\0';
2692                         my_strcat(buf, tmp, len + 1);
2693
2694                         break;
2695                 }
2696                 }
2697
2698         }
2699 }
2700
2701
2702 /*
2703  * Get some string input at the cursor location.
2704  *
2705  * Allow to use numpad keys as cursor keys.
2706  */
2707 bool askfor(char *buf, int len)
2708 {
2709         return askfor_aux(buf, len, TRUE);
2710 }
2711
2712
2713 /*
2714  * Get a string from the user
2715  *
2716  * The "prompt" should take the form "Prompt: "
2717  *
2718  * Note that the initial contents of the string is used as
2719  * the default response, so be sure to "clear" it if needed.
2720  *
2721  * We clear the input, and return FALSE, on "ESCAPE".
2722  */
2723 bool get_string(concptr prompt, char *buf, int len)
2724 {
2725         bool res;
2726         msg_print(NULL);
2727         prt(prompt, 0, 0);
2728         res = askfor(buf, len);
2729         prt("", 0, 0);
2730         return (res);
2731 }
2732
2733
2734 /*
2735  * Verify something with the user
2736  *
2737  * The "prompt" should take the form "Query? "
2738  *
2739  * Note that "[y/n]" is appended to the prompt.
2740  */
2741 bool get_check(concptr prompt)
2742 {
2743         return get_check_strict(prompt, 0);
2744 }
2745
2746
2747 /*
2748  * Verify something with the user strictly
2749  *
2750  * mode & CHECK_OKAY_CANCEL : force user to answer 'O'kay or 'C'ancel
2751  * mode & CHECK_NO_ESCAPE   : don't allow ESCAPE key
2752  * mode & CHECK_NO_HISTORY  : no message_add
2753  * mode & CHECK_DEFAULT_Y   : accept any key as y, except n and Esc.
2754  */
2755 bool get_check_strict(concptr prompt, BIT_FLAGS mode)
2756 {
2757         char buf[80];
2758         if (auto_more)
2759         {
2760                 p_ptr->window |= PW_MESSAGE;
2761                 handle_stuff(p_ptr);
2762                 num_more = 0;
2763         }
2764
2765         msg_print(NULL);
2766         if (!rogue_like_commands)
2767                 mode &= ~CHECK_OKAY_CANCEL;
2768
2769         if (mode & CHECK_OKAY_CANCEL)
2770         {
2771                 my_strcpy(buf, prompt, sizeof(buf) - 15);
2772                 strcat(buf, "[(O)k/(C)ancel]");
2773         }
2774         else if (mode & CHECK_DEFAULT_Y)
2775         {
2776                 my_strcpy(buf, prompt, sizeof(buf) - 5);
2777                 strcat(buf, "[Y/n]");
2778         }
2779         else
2780         {
2781                 my_strcpy(buf, prompt, sizeof(buf) - 5);
2782                 strcat(buf, "[y/n]");
2783         }
2784
2785         prt(buf, 0, 0);
2786         if (!(mode & CHECK_NO_HISTORY) && p_ptr->playing)
2787         {
2788                 message_add(buf);
2789                 p_ptr->window |= (PW_MESSAGE);
2790                 handle_stuff(p_ptr);
2791         }
2792
2793         bool flag = FALSE;
2794         while (TRUE)
2795         {
2796                 int i = inkey();
2797
2798                 if (!(mode & CHECK_NO_ESCAPE))
2799                 {
2800                         if (i == ESCAPE)
2801                         {
2802                                 flag = FALSE;
2803                                 break;
2804                         }
2805                 }
2806
2807                 if (mode & CHECK_OKAY_CANCEL)
2808                 {
2809                         if (i == 'o' || i == 'O')
2810                         {
2811                                 flag = TRUE;
2812                                 break;
2813                         }
2814                         else if (i == 'c' || i == 'C')
2815                         {
2816                                 flag = FALSE;
2817                                 break;
2818                         }
2819                 }
2820                 else
2821                 {
2822                         if (i == 'y' || i == 'Y')
2823                         {
2824                                 flag = TRUE;
2825                                 break;
2826                         }
2827                         else if (i == 'n' || i == 'N')
2828                         {
2829                                 flag = FALSE;
2830                                 break;
2831                         }
2832                 }
2833
2834                 if (mode & CHECK_DEFAULT_Y)
2835                 {
2836                         flag = TRUE;
2837                         break;
2838                 }
2839
2840                 bell();
2841         }
2842
2843         prt("", 0, 0);
2844         return flag;
2845 }
2846
2847
2848 /*
2849  * Prompts for a keypress
2850  *
2851  * The "prompt" should take the form "Command: "
2852  *
2853  * Returns TRUE unless the character is "Escape"
2854  */
2855 bool get_com(concptr prompt, char *command, bool z_escape)
2856 {
2857         msg_print(NULL);
2858         prt(prompt, 0, 0);
2859         if (get_com_no_macros)
2860                 *command = (char)inkey_special(FALSE);
2861         else
2862                 *command = inkey();
2863
2864         prt("", 0, 0);
2865         if (*command == ESCAPE) return FALSE;
2866         if (z_escape && ((*command == 'z') || (*command == 'Z'))) return FALSE;
2867
2868         return TRUE;
2869 }
2870
2871
2872 /*
2873  * Request a "quantity" from the user
2874  *
2875  * Hack -- allow "command_arg" to specify a quantity
2876  */
2877 QUANTITY get_quantity(concptr prompt, QUANTITY max)
2878 {
2879         bool res;
2880         char tmp[80];
2881         char buf[80];
2882
2883         QUANTITY amt;
2884         if (command_arg)
2885         {
2886                 amt = command_arg;
2887                 command_arg = 0;
2888                 if (amt > max) amt = max;
2889
2890                 return (amt);
2891         }
2892
2893         COMMAND_CODE code;
2894         bool result = repeat_pull(&code);
2895         amt = (QUANTITY)code;
2896         if ((max != 1) && result)
2897         {
2898                 if (amt > max) amt = max;
2899                 if (amt < 0) amt = 0;
2900
2901                 return (amt);
2902         }
2903
2904         if (!prompt)
2905         {
2906                 sprintf(tmp, _("いくつですか (1-%d): ", "Quantity (1-%d): "), max);
2907                 prompt = tmp;
2908         }
2909
2910         msg_print(NULL);
2911         prt(prompt, 0, 0);
2912         amt = 1;
2913         sprintf(buf, "%d", amt);
2914
2915         /*
2916          * Ask for a quantity
2917          * Don't allow to use numpad as cursor key.
2918          */
2919         res = askfor_aux(buf, 6, FALSE);
2920
2921         prt("", 0, 0);
2922         if (!res) return 0;
2923
2924         amt = (COMMAND_CODE)atoi(buf);
2925         if (isalpha(buf[0])) amt = max;
2926         if (amt > max) amt = max;
2927         if (amt < 0) amt = 0;
2928         if (amt) repeat_push((COMMAND_CODE)amt);
2929
2930         return (amt);
2931 }
2932
2933
2934 /*
2935  * Pause for user response
2936  */
2937 void pause_line(int row)
2938 {
2939         prt("", row, 0);
2940         put_str(_("[ 何かキーを押して下さい ]", "[Press any key to continue]"), row, _(26, 23));
2941
2942         (void)inkey();
2943         prt("", row, 0);
2944 }
2945
2946 /*
2947  * Hack -- special buffer to hold the action of the current keymap
2948  */
2949 static char request_command_buffer[256];
2950
2951 typedef struct
2952 {
2953         concptr name;
2954         byte cmd;
2955         bool fin;
2956 } menu_naiyou;
2957
2958 #ifdef JP
2959 menu_naiyou menu_info[10][10] =
2960 {
2961         {
2962                 {"魔法/特殊能力", 1, FALSE},
2963                 {"行動", 2, FALSE},
2964                 {"道具(使用)", 3, FALSE},
2965                 {"道具(その他)", 4, FALSE},
2966                 {"装備", 5, FALSE},
2967                 {"扉/箱", 6, FALSE},
2968                 {"情報", 7, FALSE},
2969                 {"設定", 8, FALSE},
2970                 {"その他", 9, FALSE},
2971                 {"", 0, FALSE},
2972         },
2973
2974         {
2975                 {"使う(m)", 'm', TRUE},
2976                 {"調べる(b/P)", 'b', TRUE},
2977                 {"覚える(G)", 'G', TRUE},
2978                 {"特殊能力を使う(U/O)", 'U', TRUE},
2979                 {"", 0, FALSE},
2980                 {"", 0, FALSE},
2981                 {"", 0, FALSE},
2982                 {"", 0, FALSE},
2983                 {"", 0, FALSE},
2984                 {"", 0, FALSE}
2985         },
2986
2987         {
2988                 {"休息する(R)", 'R', TRUE},
2989                 {"トラップ解除(D)", 'D', TRUE},
2990                 {"探す(s)", 's', TRUE},
2991                 {"周りを調べる(l/x)", 'l', TRUE},
2992                 {"ターゲット指定(*)", '*', TRUE},
2993                 {"穴を掘る(T/^t)", 'T', TRUE},
2994                 {"階段を上る(<)", '<', TRUE},
2995                 {"階段を下りる(>)", '>', TRUE},
2996                 {"ペットに命令する(p)", 'p', TRUE},
2997                 {"探索モードのON/OFF(S/#)", 'S', TRUE}
2998         },
2999
3000         {
3001                 {"読む(r)", 'r', TRUE},
3002                 {"飲む(q)", 'q', TRUE},
3003                 {"杖を使う(u/Z)", 'u', TRUE},
3004                 {"魔法棒で狙う(a/z)", 'a', TRUE},
3005                 {"ロッドを振る(z/a)", 'z', TRUE},
3006                 {"始動する(A)", 'A', TRUE},
3007                 {"食べる(E)", 'E', TRUE},
3008                 {"飛び道具で撃つ(f/t)", 'f', TRUE},
3009                 {"投げる(v)", 'v', TRUE},
3010                 {"", 0, FALSE}
3011         },
3012
3013         {
3014                 {"拾う(g)", 'g', TRUE},
3015                 {"落とす(d)", 'd', TRUE},
3016                 {"壊す(k/^d)", 'k', TRUE},
3017                 {"銘を刻む({)", '{', TRUE},
3018                 {"銘を消す(})", '}', TRUE},
3019                 {"調査(I)", 'I', TRUE},
3020                 {"アイテム一覧(i)", 'i', TRUE},
3021                 {"", 0, FALSE},
3022                 {"", 0, FALSE},
3023                 {"", 0, FALSE}
3024         },
3025
3026         {
3027                 {"装備する(w)", 'w', TRUE},
3028                 {"装備を外す(t/T)", 't', TRUE},
3029                 {"燃料を補給(F)", 'F', TRUE},
3030                 {"装備一覧(e)", 'e', TRUE},
3031                 {"", 0, FALSE},
3032                 {"", 0, FALSE},
3033                 {"", 0, FALSE},
3034                 {"", 0, FALSE},
3035                 {"", 0, FALSE},
3036                 {"", 0, FALSE}
3037         },
3038
3039         {
3040                 {"開ける(o)", 'o', TRUE},
3041                 {"閉じる(c)", 'c', TRUE},
3042                 {"体当たりする(B/f)", 'B', TRUE},
3043                 {"くさびを打つ(j/S)", 'j', TRUE},
3044                 {"", 0, FALSE},
3045                 {"", 0, FALSE},
3046                 {"", 0, FALSE},
3047                 {"", 0, FALSE},
3048                 {"", 0, FALSE},
3049                 {"", 0, FALSE}
3050         },
3051
3052         {
3053                 {"ダンジョンの全体図(M)", 'M', TRUE},
3054                 {"位置を確認(L/W)", 'L', TRUE},
3055                 {"階の雰囲気(^f)", KTRL('F'), TRUE},
3056                 {"ステータス(C)", 'C', TRUE},
3057                 {"文字の説明(/)", '/', TRUE},
3058                 {"メッセージ履歴(^p)", KTRL('P'), TRUE},
3059                 {"現在の時刻(^t/')", KTRL('T'), TRUE},
3060                 {"現在の知識(~)", '~', TRUE},
3061                 {"プレイ記録(|)", '|', TRUE},
3062                 {"", 0, FALSE}
3063         },
3064
3065         {
3066                 {"オプション(=)", '=', TRUE},
3067                 {"マクロ(@)", '@', TRUE},
3068                 {"画面表示(%)", '%', TRUE},
3069                 {"カラー(&)", '&', TRUE},
3070                 {"設定変更コマンド(\")", '\"', TRUE},
3071                 {"自動拾いをロード($)", '$', TRUE},
3072                 {"システム(!)", '!', TRUE},
3073                 {"", 0, FALSE},
3074                 {"", 0, FALSE},
3075                 {"", 0, FALSE}
3076         },
3077
3078         {
3079                 {"セーブ&中断(^x)", KTRL('X'), TRUE},
3080                 {"セーブ(^s)", KTRL('S'), TRUE},
3081                 {"ヘルプ(?)", '?', TRUE},
3082                 {"再描画(^r)", KTRL('R'), TRUE},
3083                 {"メモ(:)", ':', TRUE},
3084                 {"記念撮影())", ')', TRUE},
3085                 {"記念撮影の表示(()", '(', TRUE},
3086                 {"バージョン情報(V)", 'V', TRUE},
3087                 {"引退する(Q)", 'Q', TRUE},
3088                 {"", 0, FALSE}
3089         },
3090 };
3091 #else
3092 menu_naiyou menu_info[10][10] =
3093 {
3094         {
3095                 {"Magic/Special", 1, FALSE},
3096                 {"Action", 2, FALSE},
3097                 {"Items(use)", 3, FALSE},
3098                 {"Items(other)", 4, FALSE},
3099                 {"Equip", 5, FALSE},
3100                 {"Door/Box", 6, FALSE},
3101                 {"Information", 7, FALSE},
3102                 {"Options", 8, FALSE},
3103                 {"Other commands", 9, FALSE},
3104                 {"", 0, FALSE},
3105         },
3106
3107         {
3108                 {"Use(m)", 'm', TRUE},
3109                 {"See tips(b/P)", 'b', TRUE},
3110                 {"Study(G)", 'G', TRUE},
3111                 {"Special abilities(U/O)", 'U', TRUE},
3112                 {"", 0, FALSE},
3113                 {"", 0, FALSE},
3114                 {"", 0, FALSE},
3115                 {"", 0, FALSE},
3116                 {"", 0, FALSE},
3117                 {"", 0, FALSE}
3118         },
3119
3120         {
3121                 {"Rest(R)", 'R', TRUE},
3122                 {"Disarm a trap(D)", 'D', TRUE},
3123                 {"Search(s)", 's', TRUE},
3124                 {"Look(l/x)", 'l', TRUE},
3125                 {"Target(*)", '*', TRUE},
3126                 {"Dig(T/^t)", 'T', TRUE},
3127                 {"Go up stairs(<)", '<', TRUE},
3128                 {"Go down stairs(>)", '>', TRUE},
3129                 {"Command pets(p)", 'p', TRUE},
3130                 {"Search mode ON/OFF(S/#)", 'S', TRUE}
3131         },
3132
3133         {
3134                 {"Read a scroll(r)", 'r', TRUE},
3135                 {"Drink a potion(q)", 'q', TRUE},
3136                 {"Use a staff(u/Z)", 'u', TRUE},
3137                 {"Aim a wand(a/z)", 'a', TRUE},
3138                 {"Zap a rod(z/a)", 'z', TRUE},
3139                 {"Activate an equipment(A)", 'A', TRUE},
3140                 {"Eat(E)", 'E', TRUE},
3141                 {"Fire missile weapon(f/t)", 'f', TRUE},
3142                 {"Throw an item(v)", 'v', TRUE},
3143                 {"", 0, FALSE}
3144         },
3145
3146         {
3147                 {"Get items(g)", 'g', TRUE},
3148                 {"Drop an item(d)", 'd', TRUE},
3149                 {"Destroy an item(k/^d)", 'k', TRUE},
3150                 {"Inscribe an item({)", '{', TRUE},
3151                 {"Uninscribe an item(})", '}', TRUE},
3152                 {"Info about an item(I)", 'I', TRUE},
3153                 {"Inventory list(i)", 'i', TRUE},
3154                 {"", 0, FALSE},
3155                 {"", 0, FALSE},
3156                 {"", 0, FALSE}
3157         },
3158
3159         {
3160                 {"Wear(w)", 'w', TRUE},
3161                 {"Take off(t/T)", 't', TRUE},
3162                 {"Refuel(F)", 'F', TRUE},
3163                 {"Equipment list(e)", 'e', TRUE},
3164                 {"", 0, FALSE},
3165                 {"", 0, FALSE},
3166                 {"", 0, FALSE},
3167                 {"", 0, FALSE},
3168                 {"", 0, FALSE},
3169                 {"", 0, FALSE}
3170         },
3171
3172         {
3173                 {"Open(o)", 'o', TRUE},
3174                 {"Close(c)", 'c', TRUE},
3175                 {"Bash a door(B/f)", 'B', TRUE},
3176                 {"Jam a door(j/S)", 'j', TRUE},
3177                 {"", 0, FALSE},
3178                 {"", 0, FALSE},
3179                 {"", 0, FALSE},
3180                 {"", 0, FALSE},
3181                 {"", 0, FALSE},
3182                 {"", 0, FALSE}
3183         },
3184
3185         {
3186                 {"Full map(M)", 'M', TRUE},
3187                 {"Map(L/W)", 'L', TRUE},
3188                 {"Level feeling(^f)", KTRL('F'), TRUE},
3189                 {"Character status(C)", 'C', TRUE},
3190                 {"Identify symbol(/)", '/', TRUE},
3191                 {"Show prev messages(^p)", KTRL('P'), TRUE},
3192                 {"Current time(^t/')", KTRL('T'), TRUE},
3193                 {"Various information(~)", '~', TRUE},
3194                 {"Play record menu(|)", '|', TRUE},
3195                 {"", 0, FALSE}
3196         },
3197
3198         {
3199                 {"Set options(=)", '=', TRUE},
3200                 {"Interact with macros(@)", '@', TRUE},
3201                 {"Interact w/ visuals(%)", '%', TRUE},
3202                 {"Interact with colors(&)", '&', TRUE},
3203                 {"Enter a user pref(\")", '\"', TRUE},
3204                 {"Reload auto-pick pref($)", '$', TRUE},
3205                 {"", 0, FALSE},
3206                 {"", 0, FALSE},
3207                 {"", 0, FALSE},
3208                 {"", 0, FALSE}
3209         },
3210
3211         {
3212                 {"Save and quit(^x)", KTRL('X'), TRUE},
3213                 {"Save(^s)", KTRL('S'), TRUE},
3214                 {"Help(obsoleted)(?)", '?', TRUE},
3215                 {"Redraw(^r)", KTRL('R'), TRUE},
3216                 {"Take note(:)", ':', TRUE},
3217                 {"Dump screen dump(()", ')', TRUE},
3218                 {"Load screen dump())", '(', TRUE},
3219                 {"Version info(V)", 'V', TRUE},
3220                 {"Quit(Q)", 'Q', TRUE},
3221                 {"", 0, FALSE}
3222         },
3223 };
3224 #endif
3225
3226 typedef struct
3227 {
3228         concptr name;
3229         byte window;
3230         byte number;
3231         byte jouken;
3232         byte jouken_naiyou;
3233 } special_menu_naiyou;
3234
3235 #define MENU_CLASS 1
3236 #define MENU_WILD 2
3237
3238 #ifdef JP
3239 special_menu_naiyou special_menu_info[] =
3240 {
3241         {"超能力/特殊能力", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
3242         {"ものまね/特殊能力", 0, 0, MENU_CLASS, CLASS_IMITATOR},
3243         {"歌/特殊能力", 0, 0, MENU_CLASS, CLASS_BARD},
3244         {"必殺技/特殊能力", 0, 0, MENU_CLASS, CLASS_SAMURAI},
3245         {"練気術/魔法/特殊能力", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
3246         {"技/特殊能力", 0, 0, MENU_CLASS, CLASS_BERSERKER},
3247         {"技術/特殊能力", 0, 0, MENU_CLASS, CLASS_SMITH},
3248         {"鏡魔法/特殊能力", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
3249         {"忍術/特殊能力", 0, 0, MENU_CLASS, CLASS_NINJA},
3250         {"広域マップ(<)", 2, 6, MENU_WILD, FALSE},
3251         {"通常マップ(>)", 2, 7, MENU_WILD, TRUE},
3252         {"", 0, 0, 0, 0},
3253 };
3254 #else
3255 special_menu_naiyou special_menu_info[] =
3256 {
3257         {"MindCraft/Special", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
3258         {"Imitation/Special", 0, 0, MENU_CLASS, CLASS_IMITATOR},
3259         {"Song/Special", 0, 0, MENU_CLASS, CLASS_BARD},
3260         {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SAMURAI},
3261         {"Mind/Magic/Special", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
3262         {"BrutalPower/Special", 0, 0, MENU_CLASS, CLASS_BERSERKER},
3263         {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SMITH},
3264         {"MirrorMagic/Special", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
3265         {"Ninjutsu/Special", 0, 0, MENU_CLASS, CLASS_NINJA},
3266         {"Enter global map(<)", 2, 6, MENU_WILD, FALSE},
3267         {"Enter local map(>)", 2, 7, MENU_WILD, TRUE},
3268         {"", 0, 0, 0, 0},
3269 };
3270 #endif
3271
3272 static char inkey_from_menu(player_type *player_ptr)
3273 {
3274         char cmd;
3275         int basey, basex;
3276         int num = 0, max_num, old_num = 0;
3277         int menu = 0;
3278         bool kisuu;
3279
3280         if (player_ptr->y - panel_row_min > 10) basey = 2;
3281         else basey = 13;
3282         basex = 15;
3283
3284         prt("", 0, 0);
3285         screen_save();
3286
3287         floor_type* floor_ptr = player_ptr->current_floor_ptr;
3288         while (TRUE)
3289         {
3290                 int i;
3291                 char sub_cmd;
3292                 concptr menu_name;
3293                 if (!menu) old_num = num;
3294                 put_str("+----------------------------------------------------+", basey, basex);
3295                 put_str("|                                                    |", basey + 1, basex);
3296                 put_str("|                                                    |", basey + 2, basex);
3297                 put_str("|                                                    |", basey + 3, basex);
3298                 put_str("|                                                    |", basey + 4, basex);
3299                 put_str("|                                                    |", basey + 5, basex);
3300                 put_str("+----------------------------------------------------+", basey + 6, basex);
3301
3302                 for (i = 0; i < 10; i++)
3303                 {
3304                         int hoge;
3305                         if (!menu_info[menu][i].cmd) break;
3306                         menu_name = menu_info[menu][i].name;
3307                         for (hoge = 0; ; hoge++)
3308                         {
3309                                 if (!special_menu_info[hoge].name[0]) break;
3310                                 if ((menu != special_menu_info[hoge].window) || (i != special_menu_info[hoge].number)) continue;
3311                                 switch (special_menu_info[hoge].jouken)
3312                                 {
3313                                 case MENU_CLASS:
3314                                         if (player_ptr->pclass == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
3315                                         break;
3316                                 case MENU_WILD:
3317                                         if (!floor_ptr->dun_level && !floor_ptr->inside_arena && !floor_ptr->inside_quest)
3318                                         {
3319                                                 if ((byte)player_ptr->wild_mode == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
3320                                         }
3321                                         break;
3322                                 default:
3323                                         break;
3324                                 }
3325                         }
3326
3327                         put_str(menu_name, basey + 1 + i / 2, basex + 4 + (i % 2) * 24);
3328                 }
3329
3330                 max_num = i;
3331                 kisuu = max_num % 2;
3332                 put_str(_("》", "> "), basey + 1 + num / 2, basex + 2 + (num % 2) * 24);
3333
3334                 move_cursor_relative(player_ptr->y, player_ptr->x);
3335                 sub_cmd = inkey();
3336                 if ((sub_cmd == ' ') || (sub_cmd == 'x') || (sub_cmd == 'X') || (sub_cmd == '\r') || (sub_cmd == '\n'))
3337                 {
3338                         if (menu_info[menu][num].fin)
3339                         {
3340                                 cmd = menu_info[menu][num].cmd;
3341                                 use_menu = TRUE;
3342                                 break;
3343                         }
3344                         else
3345                         {
3346                                 menu = menu_info[menu][num].cmd;
3347                                 num = 0;
3348                                 basey += 2;
3349                                 basex += 8;
3350                         }
3351                 }
3352                 else if ((sub_cmd == ESCAPE) || (sub_cmd == 'z') || (sub_cmd == 'Z') || (sub_cmd == '0'))
3353                 {
3354                         if (!menu)
3355                         {
3356                                 cmd = ESCAPE;
3357                                 break;
3358                         }
3359                         else
3360                         {
3361                                 menu = 0;
3362                                 num = old_num;
3363                                 basey -= 2;
3364                                 basex -= 8;
3365                                 screen_load();
3366                                 screen_save();
3367                         }
3368                 }
3369                 else if ((sub_cmd == '2') || (sub_cmd == 'j') || (sub_cmd == 'J'))
3370                 {
3371                         if (kisuu)
3372                         {
3373                                 if (num % 2)
3374                                         num = (num + 2) % (max_num - 1);
3375                                 else
3376                                         num = (num + 2) % (max_num + 1);
3377                         }
3378                         else num = (num + 2) % max_num;
3379                 }
3380                 else if ((sub_cmd == '8') || (sub_cmd == 'k') || (sub_cmd == 'K'))
3381                 {
3382                         if (kisuu)
3383                         {
3384                                 if (num % 2)
3385                                         num = (num + max_num - 3) % (max_num - 1);
3386                                 else
3387                                         num = (num + max_num - 1) % (max_num + 1);
3388                         }
3389                         else num = (num + max_num - 2) % max_num;
3390                 }
3391                 else if ((sub_cmd == '4') || (sub_cmd == '6') || (sub_cmd == 'h') || (sub_cmd == 'H') || (sub_cmd == 'l') || (sub_cmd == 'L'))
3392                 {
3393                         if ((num % 2) || (num == max_num - 1))
3394                         {
3395                                 num--;
3396                         }
3397                         else if (num < max_num - 1)
3398                         {
3399                                 num++;
3400                         }
3401                 }
3402         }
3403
3404         screen_load();
3405         if (!inkey_next) inkey_next = "";
3406
3407         return (cmd);
3408 }
3409
3410
3411 /*
3412  * Request a command from the user.
3413  *
3414  * Sets player_ptr->command_cmd, player_ptr->command_dir, player_ptr->command_rep,
3415  * player_ptr->command_arg.  May modify player_ptr->command_new.
3416  *
3417  * Note that "caret" ("^") is treated specially, and is used to
3418  * allow manual input of control characters.  This can be used
3419  * on many machines to request repeated tunneling (Ctrl-H) and
3420  * on the Macintosh to request "Control-Caret".
3421  *
3422  * Note that "backslash" is treated specially, and is used to bypass any
3423  * keymap entry for the following character.  This is useful for macros.
3424  *
3425  * Note that this command is used both in the dungeon and in
3426  * stores, and must be careful to work in both situations.
3427  *
3428  * Note that "player_ptr->command_new" may not work any more.
3429  */
3430 void request_command(player_type *player_ptr, int shopping)
3431 {
3432         s16b cmd;
3433         int mode;
3434
3435         concptr act;
3436
3437 #ifdef JP
3438         int caretcmd = 0;
3439 #endif
3440         if (rogue_like_commands)
3441         {
3442                 mode = KEYMAP_MODE_ROGUE;
3443         }
3444         else
3445         {
3446                 mode = KEYMAP_MODE_ORIG;
3447         }
3448
3449         command_cmd = 0;
3450         command_arg = 0;
3451         command_dir = 0;
3452         use_menu = FALSE;
3453
3454         while (TRUE)
3455         {
3456                 if (command_new)
3457                 {
3458                         msg_erase();
3459                         cmd = command_new;
3460                         command_new = 0;
3461                 }
3462                 else
3463                 {
3464                         msg_flag = FALSE;
3465                         num_more = 0;
3466                         inkey_flag = TRUE;
3467                         cmd = inkey();
3468                         if (!shopping && command_menu && ((cmd == '\r') || (cmd == '\n') || (cmd == 'x') || (cmd == 'X'))
3469                                 && !keymap_act[mode][(byte)(cmd)])
3470                                 cmd = inkey_from_menu(player_ptr);
3471                 }
3472
3473                 prt("", 0, 0);
3474                 if (cmd == '0')
3475                 {
3476                         COMMAND_ARG old_arg = command_arg;
3477                         command_arg = 0;
3478                         prt(_("回数: ", "Count: "), 0, 0);
3479                         while (TRUE)
3480                         {
3481                                 cmd = inkey();
3482                                 if ((cmd == 0x7F) || (cmd == KTRL('H')))
3483                                 {
3484                                         command_arg = command_arg / 10;
3485                                         prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
3486                                 }
3487                                 else if (cmd >= '0' && cmd <= '9')
3488                                 {
3489                                         if (command_arg >= 1000)
3490                                         {
3491                                                 bell();
3492                                                 command_arg = 9999;
3493                                         }
3494                                         else
3495                                         {
3496                                                 command_arg = command_arg * 10 + D2I(cmd);
3497                                         }
3498
3499                                         prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
3500                                 }
3501                                 else
3502                                 {
3503                                         break;
3504                                 }
3505                         }
3506
3507                         if (command_arg == 0)
3508                         {
3509                                 command_arg = 99;
3510                                 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
3511                         }
3512
3513                         if (old_arg != 0)
3514                         {
3515                                 command_arg = old_arg;
3516                                 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
3517                         }
3518
3519                         if ((cmd == ' ') || (cmd == '\n') || (cmd == '\r'))
3520                         {
3521                                 if (!get_com(_("コマンド: ", "Command: "), (char *)&cmd, FALSE))
3522                                 {
3523                                         command_arg = 0;
3524                                         continue;
3525                                 }
3526                         }
3527                 }
3528
3529                 if (cmd == '\\')
3530                 {
3531                         (void)get_com(_("コマンド: ", "Command: "), (char *)&cmd, FALSE);
3532                         if (!inkey_next) inkey_next = "";
3533                 }
3534
3535                 if (cmd == '^')
3536                 {
3537                         if (get_com(_("CTRL: ", "Control: "), (char *)&cmd, FALSE)) cmd = KTRL(cmd);
3538                 }
3539
3540                 act = keymap_act[mode][(byte)(cmd)];
3541                 if (act && !inkey_next)
3542                 {
3543                         (void)strnfmt(request_command_buffer, 256, "%s", act);
3544                         inkey_next = request_command_buffer;
3545                         continue;
3546                 }
3547
3548                 if (!cmd) continue;
3549
3550                 command_cmd = (byte)cmd;
3551                 break;
3552         }
3553
3554         if (always_repeat && (command_arg <= 0))
3555         {
3556                 if (my_strchr("TBDoc+", (char)command_cmd))
3557                 {
3558                         command_arg = 99;
3559                 }
3560         }
3561
3562         if (shopping == 1)
3563         {
3564                 switch (command_cmd)
3565                 {
3566                 case 'p': command_cmd = 'g'; break;
3567
3568                 case 'm': command_cmd = 'g'; break;
3569
3570                 case 's': command_cmd = 'd'; break;
3571                 }
3572         }
3573
3574 #ifdef JP
3575         for (int i = 0; i < 256; i++)
3576         {
3577                 concptr s;
3578                 if ((s = keymap_act[mode][i]) != NULL)
3579                 {
3580                         if (*s == command_cmd && *(s + 1) == 0)
3581                         {
3582                                 caretcmd = i;
3583                                 break;
3584                         }
3585                 }
3586         }
3587
3588         if (!caretcmd)
3589                 caretcmd = command_cmd;
3590 #endif
3591
3592         for (int i = INVEN_RARM; i < INVEN_TOTAL; i++)
3593         {
3594                 object_type *o_ptr = &player_ptr->inventory_list[i];
3595                 if (!o_ptr->k_idx) continue;
3596
3597                 if (!o_ptr->inscription) continue;
3598
3599                 concptr s = quark_str(o_ptr->inscription);
3600                 s = my_strchr(s, '^');
3601                 while (s)
3602                 {
3603 #ifdef JP
3604                         if ((s[1] == caretcmd) || (s[1] == '*'))
3605 #else
3606                         if ((s[1] == command_cmd) || (s[1] == '*'))
3607 #endif
3608                         {
3609                                 if (!get_check(_("本当ですか? ", "Are you sure? ")))
3610                                 {
3611                                         command_cmd = ' ';
3612                                 }
3613                         }
3614
3615                         s = my_strchr(s + 1, '^');
3616                 }
3617         }
3618
3619         prt("", 0, 0);
3620 }
3621
3622
3623 /*
3624  * Check a char for "vowel-hood"
3625  */
3626 bool is_a_vowel(int ch)
3627 {
3628         switch (ch)
3629         {
3630         case 'a':
3631         case 'e':
3632         case 'i':
3633         case 'o':
3634         case 'u':
3635         case 'A':
3636         case 'E':
3637         case 'I':
3638         case 'O':
3639         case 'U':
3640                 return TRUE;
3641         }
3642
3643         return FALSE;
3644 }
3645
3646
3647 /*
3648  * GH
3649  * Called from cmd4.c and a few other places. Just extracts
3650  * a direction from the keymap for ch (the last direction,
3651  * in fact) byte or char here? I'm thinking that keymaps should
3652  * generally only apply to single keys, which makes it no more
3653  * than 128, so a char should suffice... but keymap_act is 256...
3654  */
3655 int get_keymap_dir(char ch)
3656 {
3657         int d = 0;
3658
3659         if (isdigit(ch))
3660         {
3661                 d = D2I(ch);
3662         }
3663         else
3664         {
3665                 BIT_FLAGS mode;
3666                 if (rogue_like_commands)
3667                 {
3668                         mode = KEYMAP_MODE_ROGUE;
3669                 }
3670                 else
3671                 {
3672                         mode = KEYMAP_MODE_ORIG;
3673                 }
3674
3675                 concptr act = keymap_act[mode][(byte)(ch)];
3676                 if (act)
3677                 {
3678                         for (concptr s = act; *s; ++s)
3679                         {
3680                                 if (isdigit(*s)) d = D2I(*s);
3681                         }
3682                 }
3683         }
3684
3685         if (d == 5) d = 0;
3686
3687         return (d);
3688 }
3689
3690
3691 #define REPEAT_MAX              20
3692
3693 /* Number of chars saved */
3694 static int repeat__cnt = 0;
3695
3696 /* Current index */
3697 static int repeat__idx = 0;
3698
3699 /* Saved "stuff" */
3700 static COMMAND_CODE repeat__key[REPEAT_MAX];
3701
3702 void repeat_push(COMMAND_CODE what)
3703 {
3704         if (repeat__cnt == REPEAT_MAX) return;
3705
3706         repeat__key[repeat__cnt++] = what;
3707         ++repeat__idx;
3708 }
3709
3710
3711 bool repeat_pull(COMMAND_CODE *what)
3712 {
3713         if (repeat__idx == repeat__cnt) return FALSE;
3714
3715         *what = repeat__key[repeat__idx++];
3716         return TRUE;
3717 }
3718
3719 void repeat_check(void)
3720 {
3721         if (command_cmd == ESCAPE) return;
3722         if (command_cmd == ' ') return;
3723         if (command_cmd == '\r') return;
3724         if (command_cmd == '\n') return;
3725
3726         COMMAND_CODE what;
3727         if (command_cmd == 'n')
3728         {
3729                 repeat__idx = 0;
3730                 if (repeat_pull(&what))
3731                 {
3732                         command_cmd = what;
3733                 }
3734         }
3735         else
3736         {
3737                 repeat__cnt = 0;
3738                 repeat__idx = 0;
3739                 what = command_cmd;
3740                 repeat_push(what);
3741         }
3742 }
3743
3744
3745 /*
3746  * Array size for which InsertionSort
3747  * is used instead of QuickSort
3748  */
3749 #define CUTOFF 4
3750
3751
3752  /*
3753   * Exchange two sort-entries
3754   * (should probably be coded inline
3755   * for speed increase)
3756   */
3757 static void swap(tag_type *a, tag_type *b)
3758 {
3759         tag_type temp;
3760
3761         temp = *a;
3762         *a = *b;
3763         *b = temp;
3764 }
3765
3766
3767 /*
3768  * Insertion-Sort algorithm
3769  * (used by the Quicksort algorithm)
3770  */
3771 static void InsertionSort(tag_type elements[], int number)
3772 {
3773         tag_type tmp;
3774         for (int i = 1; i < number; i++)
3775         {
3776                 tmp = elements[i];
3777                 int j;
3778                 for (j = i; (j > 0) && (elements[j - 1].tag > tmp.tag); j--)
3779                         elements[j] = elements[j - 1];
3780                 elements[j] = tmp;
3781         }
3782 }
3783
3784
3785 /*
3786  * Helper function for Quicksort
3787  */
3788 static tag_type median3(tag_type elements[], int left, int right)
3789 {
3790         int center = (left + right) / 2;
3791
3792         if (elements[left].tag > elements[center].tag)
3793                 swap(&elements[left], &elements[center]);
3794         if (elements[left].tag > elements[right].tag)
3795                 swap(&elements[left], &elements[right]);
3796         if (elements[center].tag > elements[right].tag)
3797                 swap(&elements[center], &elements[right]);
3798
3799         swap(&elements[center], &elements[right - 1]);
3800         return (elements[right - 1]);
3801 }
3802
3803
3804 /*
3805  * Quicksort algorithm
3806  *
3807  * The "median of three" pivot selection eliminates
3808  * the bad case of already sorted input.
3809  *
3810  * We use InsertionSort for smaller sub-arrays,
3811  * because it is faster in this case.
3812  *
3813  * For details see: "Data Structures and Algorithm
3814  * Analysis in C" by Mark Allen Weiss.
3815  */
3816 static void quicksort(tag_type elements[], int left, int right)
3817 {
3818         tag_type pivot;
3819         if (left + CUTOFF <= right)
3820         {
3821                 pivot = median3(elements, left, right);
3822
3823                 int i = left;
3824                 int j = right - 1;
3825
3826                 while (TRUE)
3827                 {
3828                         while (elements[++i].tag < pivot.tag);
3829                         while (elements[--j].tag > pivot.tag);
3830
3831                         if (i < j)
3832                                 swap(&elements[i], &elements[j]);
3833                         else
3834                                 break;
3835                 }
3836
3837                 swap(&elements[i], &elements[right - 1]);
3838
3839                 quicksort(elements, left, i - 1);
3840                 quicksort(elements, i + 1, right);
3841         }
3842         else
3843         {
3844                 InsertionSort(elements + left, right - left + 1);
3845         }
3846 }
3847
3848
3849 /*
3850  * Frontend for the sorting algorithm
3851  *
3852  * Sorts an array of tagged pointers
3853  * with <number> elements.
3854  */
3855 void tag_sort(tag_type elements[], int number)
3856 {
3857         quicksort(elements, 0, number - 1);
3858 }
3859
3860 /* Table of gamma values */
3861 byte gamma_table[256];
3862
3863 /* Table of ln(x/256) * 256 for x going from 0 -> 255 */
3864 static s16b gamma_helper[256] =
3865 {
3866 0,-1420,-1242,-1138,-1065,-1007,-961,-921,-887,-857,-830,-806,-783,-762,-744,-726,
3867 -710,-694,-679,-666,-652,-640,-628,-617,-606,-596,-586,-576,-567,-577,-549,-541,
3868 -532,-525,-517,-509,-502,-495,-488,-482,-475,-469,-463,-457,-451,-455,-439,-434,
3869 -429,-423,-418,-413,-408,-403,-398,-394,-389,-385,-380,-376,-371,-367,-363,-359,
3870 -355,-351,-347,-343,-339,-336,-332,-328,-325,-321,-318,-314,-311,-308,-304,-301,
3871 -298,-295,-291,-288,-285,-282,-279,-276,-273,-271,-268,-265,-262,-259,-257,-254,
3872 -251,-248,-246,-243,-241,-238,-236,-233,-231,-228,-226,-223,-221,-219,-216,-214,
3873 -212,-209,-207,-205,-203,-200,-198,-196,-194,-192,-190,-188,-186,-184,-182,-180,
3874 -178,-176,-174,-172,-170,-168,-166,-164,-162,-160,-158,-156,-155,-153,-151,-149,
3875 -147,-146,-144,-142,-140,-139,-137,-135,-134,-132,-130,-128,-127,-125,-124,-122,
3876 -120,-119,-117,-116,-114,-112,-111,-109,-108,-106,-105,-103,-102,-100,-99,-97,
3877 -96,-95,-93,-92,-90,-89,-87,-86,-85,-83,-82,-80,-79,-78,-76,-75,
3878 -74,-72,-71,-70,-68,-67,-66,-65,-63,-62,-61,-59,-58,-57,-56,-54,
3879 -53,-52,-51,-50,-48,-47,-46,-45,-44,-42,-41,-40,-39,-38,-37,-35,
3880 -34,-33,-32,-31,-30,-29,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,
3881 -17,-16,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1
3882 };
3883
3884
3885 /*
3886  * Build the gamma table so that floating point isn't needed.
3887  *
3888  * Note gamma goes from 0->256.  The old value of 100 is now 128.
3889  */
3890 void build_gamma_table(int gamma)
3891 {
3892         gamma_table[0] = 0;
3893         gamma_table[255] = 255;
3894         for (int i = 1; i < 255; i++)
3895         {
3896                 /*
3897                  * Initialise the Taylor series
3898                  *
3899                  * value and diff have been scaled by 256
3900                  */
3901                 int n = 1;
3902                 long value = 256 * 256;
3903                 long diff = ((long)gamma_helper[i]) * (gamma - 256);
3904
3905                 while (diff)
3906                 {
3907                         value += diff;
3908                         n++;
3909
3910
3911                         /*
3912                          * Use the following identiy to calculate the gamma table.
3913                          * exp(x) = 1 + x + x^2/2 + x^3/(2*3) + x^4/(2*3*4) +...
3914                          *
3915                          * n is the current term number.
3916                          *
3917                          * The gamma_helper array contains a table of
3918                          * ln(x/256) * 256
3919                          * This is used because a^b = exp(b*ln(a))
3920                          *
3921                          * In this case:
3922                          * a is i / 256
3923                          * b is gamma.
3924                          *
3925                          * Note that everything is scaled by 256 for accuracy,
3926                          * plus another factor of 256 for the final result to
3927                          * be from 0-255.  Thus gamma_helper[] * gamma must be
3928                          * divided by 256*256 each itteration, to get back to
3929                          * the original power series.
3930                          */
3931                         diff = (((diff / 256) * gamma_helper[i]) * (gamma - 256)) / (256 * n);
3932                 }
3933
3934                 /*
3935                  * Store the value in the table so that the
3936                  * floating point pow function isn't needed .
3937                  */
3938                 gamma_table[i] = ((long)(value / 256) * i) / 256;
3939         }
3940 }
3941
3942
3943 /*
3944  * Add a series of keypresses to the "queue".
3945  *
3946  * Return any errors generated by Term_keypress() in doing so, or SUCCESS
3947  * if there are none.
3948  *
3949  * Catch the "out of space" error before anything is printed.
3950  *
3951  * NB: The keys added here will be interpreted by any macros or keymaps.
3952  */
3953 errr type_string(concptr str, uint len)
3954 {
3955         errr err = 0;
3956         term *old = Term;
3957         if (!str) return -1;
3958         if (!len) len = strlen(str);
3959
3960         Term_activate(term_screen);
3961         for (concptr s = str; s < str + len; s++)
3962         {
3963                 if (*s == '\0') break;
3964
3965                 err = Term_keypress(*s);
3966                 if (err) break;
3967         }
3968
3969         Term_activate(old);
3970         return err;
3971 }
3972
3973
3974 void roff_to_buf(concptr str, int maxlen, char *tbuf, size_t bufsize)
3975 {
3976         int read_pt = 0;
3977         int write_pt = 0;
3978         int line_len = 0;
3979         int word_punct = 0;
3980         char ch[3];
3981         ch[2] = '\0';
3982
3983         while (str[read_pt])
3984         {
3985 #ifdef JP
3986                 bool kinsoku = FALSE;
3987                 bool kanji;
3988 #endif
3989                 int ch_len = 1;
3990                 ch[0] = str[read_pt];
3991                 ch[1] = '\0';
3992 #ifdef JP
3993                 kanji = iskanji(ch[0]);
3994
3995                 if (kanji)
3996                 {
3997                         ch[1] = str[read_pt + 1];
3998                         ch_len = 2;
3999
4000                         if (strcmp(ch, "。") == 0 ||
4001                                 strcmp(ch, "、") == 0 ||
4002                                 strcmp(ch, "ィ") == 0 ||
4003                                 strcmp(ch, "ー") == 0)
4004                                 kinsoku = TRUE;
4005                 }
4006                 else if (!isprint(ch[0]))
4007                         ch[0] = ' ';
4008 #else
4009                 if (!isprint(ch[0]))
4010                         ch[0] = ' ';
4011 #endif
4012
4013                 if (line_len + ch_len > maxlen - 1 || str[read_pt] == '\n')
4014                 {
4015                         int word_len = read_pt - word_punct;
4016 #ifdef JP
4017                         if (kanji && !kinsoku)
4018                                 /* nothing */;
4019                         else
4020 #endif
4021                                 if (ch[0] == ' ' || word_len >= line_len / 2)
4022                                         read_pt++;
4023                                 else
4024                                 {
4025                                         read_pt = word_punct;
4026                                         if (str[word_punct] == ' ')
4027                                                 read_pt++;
4028                                         write_pt -= word_len;
4029                                 }
4030
4031                         tbuf[write_pt++] = '\0';
4032                         line_len = 0;
4033                         word_punct = read_pt;
4034                         continue;
4035                 }
4036
4037                 if (ch[0] == ' ')
4038                         word_punct = read_pt;
4039
4040 #ifdef JP
4041                 if (!kinsoku) word_punct = read_pt;
4042 #endif
4043
4044                 if ((size_t)(write_pt + 3) >= bufsize) break;
4045
4046                 tbuf[write_pt++] = ch[0];
4047                 line_len++;
4048                 read_pt++;
4049 #ifdef JP
4050                 if (kanji)
4051                 {
4052                         tbuf[write_pt++] = ch[1];
4053                         line_len++;
4054                         read_pt++;
4055                 }
4056 #endif
4057         }
4058
4059         tbuf[write_pt] = '\0';
4060         tbuf[write_pt + 1] = '\0';
4061         return;
4062 }
4063
4064
4065 /*
4066  * The my_strcpy() function copies up to 'bufsize'-1 characters from 'src'
4067  * to 'buf' and NUL-terminates the result.  The 'buf' and 'src' strings may
4068  * not overlap.
4069  *
4070  * my_strcpy() returns strlen(src).  This makes checking for truncation
4071  * easy.  Example: if (my_strcpy(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
4072  *
4073  * This function should be equivalent to the strlcpy() function in BSD.
4074  */
4075 size_t my_strcpy(char *buf, concptr src, size_t bufsize)
4076 {
4077 #ifdef JP
4078         char *d = buf;
4079         concptr s = src;
4080         size_t len = 0;
4081
4082         if (bufsize > 0) {
4083                 /* reserve for NUL termination */
4084                 bufsize--;
4085
4086                 /* Copy as many bytes as will fit */
4087                 while (*s && (len < bufsize))
4088                 {
4089                         if (iskanji(*s))
4090                         {
4091                                 if (len + 1 >= bufsize || !*(s + 1)) break;
4092                                 *d++ = *s++;
4093                                 *d++ = *s++;
4094                                 len += 2;
4095                         }
4096                         else
4097                         {
4098                                 *d++ = *s++;
4099                                 len++;
4100                         }
4101                 }
4102                 *d = '\0';
4103         }
4104
4105         while (*s++) len++;
4106         return len;
4107
4108 #else
4109         size_t len = strlen(src);
4110         size_t ret = len;
4111         if (bufsize == 0) return ret;
4112
4113         if (len >= bufsize) len = bufsize - 1;
4114
4115         (void)memcpy(buf, src, len);
4116         buf[len] = '\0';
4117         return ret;
4118 #endif
4119 }
4120
4121
4122 /*
4123  * The my_strcat() tries to append a string to an existing NUL-terminated string.
4124  * It never writes more characters into the buffer than indicated by 'bufsize' and
4125  * NUL-terminates the buffer.  The 'buf' and 'src' strings may not overlap.
4126  *
4127  * my_strcat() returns strlen(buf) + strlen(src).  This makes checking for
4128  * truncation easy.  Example:
4129  * if (my_strcat(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
4130  *
4131  * This function should be equivalent to the strlcat() function in BSD.
4132  */
4133 size_t my_strcat(char *buf, concptr src, size_t bufsize)
4134 {
4135         size_t dlen = strlen(buf);
4136         if (dlen < bufsize - 1)
4137         {
4138                 return (dlen + my_strcpy(buf + dlen, src, bufsize - dlen));
4139         }
4140         else
4141         {
4142                 return (dlen + strlen(src));
4143         }
4144 }
4145
4146
4147 /*
4148  * A copy of ANSI strstr()
4149  *
4150  * my_strstr() can handle Kanji strings correctly.
4151  */
4152 char *my_strstr(concptr haystack, concptr needle)
4153 {
4154         int l1 = strlen(haystack);
4155         int l2 = strlen(needle);
4156
4157         if (l1 >= l2)
4158         {
4159                 for (int i = 0; i <= l1 - l2; i++)
4160                 {
4161                         if (!strncmp(haystack + i, needle, l2))
4162                                 return (char *)haystack + i;
4163
4164 #ifdef JP
4165                         if (iskanji(*(haystack + i))) i++;
4166 #endif
4167                 }
4168         }
4169
4170         return NULL;
4171 }
4172
4173
4174 /*
4175  * A copy of ANSI strchr()
4176  *
4177  * my_strchr() can handle Kanji strings correctly.
4178  */
4179 char *my_strchr(concptr ptr, char ch)
4180 {
4181         for (; *ptr != '\0'; ptr++)
4182         {
4183                 if (*ptr == ch) return (char *)ptr;
4184
4185 #ifdef JP
4186                 if (iskanji(*ptr)) ptr++;
4187 #endif
4188         }
4189
4190         return NULL;
4191 }
4192
4193
4194 /*
4195  * Convert string to lower case
4196  */
4197 void str_tolower(char *str)
4198 {
4199         for (; *str; str++)
4200         {
4201 #ifdef JP
4202                 if (iskanji(*str))
4203                 {
4204                         str++;
4205                         continue;
4206                 }
4207 #endif
4208                 *str = (char)tolower(*str);
4209         }
4210 }
4211
4212
4213 /*
4214  * Get a keypress from the user.
4215  * And interpret special keys as internal code.
4216  *
4217  * This function is a Mega-Hack and depend on pref-xxx.prf's.
4218  * Currently works on Linux(UNIX), Windows, and Macintosh only.
4219  */
4220 int inkey_special(bool numpad_cursor)
4221 {
4222         static const struct {
4223                 concptr keyname;
4224                 int keyflag;
4225         } modifier_key_list[] = {
4226                 {"shift-", SKEY_MOD_SHIFT},
4227                 {"control-", SKEY_MOD_CONTROL},
4228                 {NULL, 0},
4229         };
4230
4231         static const struct {
4232                 bool numpad;
4233                 concptr keyname;
4234                 int keycode;
4235         } special_key_list[] = {
4236                 {FALSE, "Down]", SKEY_DOWN},
4237                 {FALSE, "Left]", SKEY_LEFT},
4238                 {FALSE, "Right]", SKEY_RIGHT},
4239                 {FALSE, "Up]", SKEY_UP},
4240                 {FALSE, "Page_Up]", SKEY_PGUP},
4241                 {FALSE, "Page_Down]", SKEY_PGDOWN},
4242                 {FALSE, "Home]", SKEY_TOP},
4243                 {FALSE, "End]", SKEY_BOTTOM},
4244                 {TRUE, "KP_Down]", SKEY_DOWN},
4245                 {TRUE, "KP_Left]", SKEY_LEFT},
4246                 {TRUE, "KP_Right]", SKEY_RIGHT},
4247                 {TRUE, "KP_Up]", SKEY_UP},
4248                 {TRUE, "KP_Page_Up]", SKEY_PGUP},
4249                 {TRUE, "KP_Page_Down]", SKEY_PGDOWN},
4250                 {TRUE, "KP_Home]", SKEY_TOP},
4251                 {TRUE, "KP_End]", SKEY_BOTTOM},
4252                 {TRUE, "KP_2]", SKEY_DOWN},
4253                 {TRUE, "KP_4]", SKEY_LEFT},
4254                 {TRUE, "KP_6]", SKEY_RIGHT},
4255                 {TRUE, "KP_8]", SKEY_UP},
4256                 {TRUE, "KP_9]", SKEY_PGUP},
4257                 {TRUE, "KP_3]", SKEY_PGDOWN},
4258                 {TRUE, "KP_7]", SKEY_TOP},
4259                 {TRUE, "KP_1]", SKEY_BOTTOM},
4260                 {FALSE, NULL, 0},
4261         };
4262
4263         static const struct {
4264                 concptr keyname;
4265                 int keycode;
4266         } gcu_special_key_list[] = {
4267                 {"A", SKEY_UP},
4268                 {"B", SKEY_DOWN},
4269                 {"C", SKEY_RIGHT},
4270                 {"D", SKEY_LEFT},
4271                 {"1~", SKEY_TOP},
4272                 {"4~", SKEY_BOTTOM},
4273                 {"5~", SKEY_PGUP},
4274                 {"6~", SKEY_PGDOWN},
4275                 {NULL, 0},
4276         };
4277
4278         char buf[1024];
4279         concptr str = buf;
4280         char key;
4281         int skey = 0;
4282         int modifier = 0;
4283         int i;
4284         size_t trig_len;
4285
4286         /*
4287          * Forget macro trigger ----
4288          * It's important if we are already expanding macro action
4289          */
4290         inkey_macro_trigger_string[0] = '\0';
4291
4292         key = inkey();
4293         trig_len = strlen(inkey_macro_trigger_string);
4294         if (!trig_len) return (int)((unsigned char)key);
4295         if (trig_len == 1 && parse_macro)
4296         {
4297                 char c = inkey_macro_trigger_string[0];
4298                 forget_macro_action();
4299                 return (int)((unsigned char)c);
4300         }
4301
4302         ascii_to_text(buf, inkey_macro_trigger_string);
4303         if (prefix(str, "\\["))
4304         {
4305                 str += 2;
4306                 while (TRUE)
4307                 {
4308                         for (i = 0; modifier_key_list[i].keyname; i++)
4309                         {
4310                                 if (prefix(str, modifier_key_list[i].keyname))
4311                                 {
4312                                         str += strlen(modifier_key_list[i].keyname);
4313                                         modifier |= modifier_key_list[i].keyflag;
4314                                 }
4315                         }
4316
4317                         if (!modifier_key_list[i].keyname) break;
4318                 }
4319
4320                 if (!numpad_as_cursorkey) numpad_cursor = FALSE;
4321
4322                 for (i = 0; special_key_list[i].keyname; i++)
4323                 {
4324                         if ((!special_key_list[i].numpad || numpad_cursor) &&
4325                                 streq(str, special_key_list[i].keyname))
4326                         {
4327                                 skey = special_key_list[i].keycode;
4328                                 break;
4329                         }
4330                 }
4331
4332                 if (skey)
4333                 {
4334                         forget_macro_action();
4335                         return (skey | modifier);
4336                 }
4337         }
4338
4339         if (prefix(str, "\\e["))
4340         {
4341                 str += 3;
4342
4343                 for (i = 0; gcu_special_key_list[i].keyname; i++)
4344                 {
4345                         if (streq(str, gcu_special_key_list[i].keyname))
4346                         {
4347                                 return gcu_special_key_list[i].keycode;
4348                         }
4349                 }
4350         }
4351
4352         inkey_macro_trigger_string[0] = '\0';
4353         return (int)((unsigned char)key);
4354 }