OSDN Git Service

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