OSDN Git Service

[Refactor] #37353 コメント整理 / Refactor comments.
[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 "monster-hook.h"
15
16
17 static int num_more = 0;
18
19 /* Save macro trigger string for use in inkey_special() */
20 static char inkey_macro_trigger_string[1024];
21
22 #if 0
23 #ifndef HAS_STRICMP
24
25 /*
26  * For those systems that don't have "stricmp()"
27  *
28  * Compare the two strings "a" and "b" ala "strcmp()" ignoring case.
29  */
30 int stricmp(cptr a, cptr b)
31 {
32         cptr s1, s2;
33         char z1, z2;
34
35         /* Scan the strings */
36         for (s1 = a, s2 = b; TRUE; s1++, s2++)
37         {
38                 z1 = FORCEUPPER(*s1);
39                 z2 = FORCEUPPER(*s2);
40                 if (z1 < z2) return (-1);
41                 if (z1 > z2) return (1);
42                 if (!z1) return (0);
43         }
44 }
45
46 #endif /* HAS_STRICMP */
47 #endif /* 0 */
48
49 #ifdef SET_UID
50
51 # ifndef HAVE_USLEEP
52
53 /*
54  * For those systems that don't have "usleep()" but need it.
55  *
56  * Fake "usleep()" function grabbed from the inl netrek server -cba
57  */
58 int usleep(huge usecs)
59 {
60         struct timeval      Timer;
61
62         int                 nfds = 0;
63
64 #ifdef FD_SET
65         fd_set          *no_fds = NULL;
66 #else
67         int                     *no_fds = NULL;
68 #endif
69
70
71         /* Was: int readfds, writefds, exceptfds; */
72         /* Was: readfds = writefds = exceptfds = 0; */
73
74
75         /* Paranoia -- No excessive sleeping */
76         if (usecs > 4000000L) core(_("不当な usleep() 呼び出し", "Illegal usleep() call"));
77
78         /* Wait for it */
79         Timer.tv_sec = (usecs / 1000000L);
80         Timer.tv_usec = (usecs % 1000000L);
81
82         /* Wait for it */
83         if (select(nfds, no_fds, no_fds, no_fds, &Timer) < 0)
84         {
85                 /* Hack -- ignore interrupts */
86                 if (errno != EINTR) return -1;
87         }
88
89         /* Success */
90         return 0;
91 }
92
93 # endif
94
95
96 /*
97  * Hack -- External functions
98  */
99 #ifdef SET_UID
100 extern struct passwd *getpwuid(uid_t uid);
101 extern struct passwd *getpwnam(const char *name);
102 #endif
103
104
105 /*
106  * Find a default user name from the system.
107  */
108 void user_name(char *buf, int id)
109 {
110         struct passwd *pw;
111
112         /* Look up the user name */
113         if ((pw = getpwuid(id)))
114         {
115                 (void)strcpy(buf, pw->pw_name);
116                 buf[16] = '\0';
117
118 #ifdef CAPITALIZE_USER_NAME
119                 /* Hack -- capitalize the user name */
120 #ifdef JP
121                 if (!iskanji(buf[0]))
122 #endif
123                         if (islower(buf[0]))
124                                 buf[0] = toupper(buf[0]);
125 #endif /* CAPITALIZE_USER_NAME */
126
127                 return;
128         }
129
130         /* Oops.  Hack -- default to "PLAYER" */
131         strcpy(buf, "PLAYER");
132 }
133
134 #endif /* SET_UID */
135
136
137
138
139 /*
140  * The concept of the "file" routines below (and elsewhere) is that all
141  * file handling should be done using as few routines as possible, since
142  * every machine is slightly different, but these routines always have the
143  * same semantics.
144  *
145  * In fact, perhaps we should use the "path_parse()" routine below to convert
146  * from "canonical" filenames (optional leading tilde's, internal wildcards,
147  * slash as the path seperator, etc) to "system" filenames (no special symbols,
148  * system-specific path seperator, etc).  This would allow the program itself
149  * to assume that all filenames are "Unix" filenames, and explicitly "extract"
150  * such filenames if needed (by "path_parse()", or perhaps "path_canon()").
151  *
152  * Note that "path_temp" should probably return a "canonical" filename.
153  *
154  * Note that "my_fopen()" and "my_open()" and "my_make()" and "my_kill()"
155  * and "my_move()" and "my_copy()" should all take "canonical" filenames.
156  *
157  * Note that "canonical" filenames use a leading "slash" to indicate an absolute
158  * path, and a leading "tilde" to indicate a special directory, and default to a
159  * relative path, but MSDOS uses a leading "drivename plus colon" to indicate the
160  * use of a "special drive", and then the rest of the path is parsed "normally",
161  * and MACINTOSH uses a leading colon to indicate a relative path, and an embedded
162  * colon to indicate a "drive plus absolute path", and finally defaults to a file
163  * in the current working directory, which may or may not be defined.
164  *
165  * We should probably parse a leading "~~/" as referring to "ANGBAND_DIR". (?)
166  */
167
168
169 #ifdef ACORN
170
171
172 /*
173  * Most of the "file" routines for "ACORN" should be in "main-acn.c"
174  */
175
176
177 #else /* ACORN */
178
179
180 #ifdef SET_UID
181
182 /*
183  * Extract a "parsed" path from an initial filename
184  * Normally, we simply copy the filename into the buffer
185  * But leading tilde symbols must be handled in a special way
186  * Replace "~user/" by the home directory of the user named "user"
187  * Replace "~/" by the home directory of the current user
188  */
189 errr path_parse(char *buf, int max, cptr file)
190 {
191         cptr            u, s;
192         struct passwd   *pw;
193         char            user[128];
194
195
196         /* Assume no result */
197         buf[0] = '\0';
198
199         /* No file? */
200         if (!file) return (-1);
201
202         /* File needs no parsing */
203         if (file[0] != '~')
204         {
205                 (void)strnfmt(buf, max, "%s", file);
206                 return (0);
207         }
208
209         /* Point at the user */
210         u = file+1;
211
212         /* Look for non-user portion of the file */
213         s = my_strstr(u, PATH_SEP);
214
215         /* Hack -- no long user names */
216         if (s && (s >= u + sizeof(user))) return (1);
217
218         /* Extract a user name */
219         if (s)
220         {
221                 int i;
222                 for (i = 0; u < s; ++i) user[i] = *u++;
223                 user[i] = '\0';
224                 u = user;
225         }
226
227         /* Look up the "current" user */
228         if (u[0] == '\0') u = getlogin();
229
230         /* Look up a user (or "current" user) */
231         if (u) pw = getpwnam(u);
232         else pw = getpwuid(getuid());
233
234         /* Nothing found? */
235         if (!pw) return (1);
236
237         /* Make use of the info */
238         if (s) strnfmt(buf, max, "%s%s", pw->pw_dir, s);
239         else strnfmt(buf, max, "%s", pw->pw_dir);
240
241         /* Success */
242         return (0);
243 }
244
245
246 #else /* SET_UID */
247
248
249 /*
250  * Extract a "parsed" path from an initial filename
251  *
252  * This requires no special processing on simple machines,
253  * except for verifying the size of the filename.
254  */
255 errr path_parse(char *buf, int max, cptr file)
256 {
257         /* Accept the filename */
258         (void)strnfmt(buf, max, "%s", file);
259
260 #if defined(MAC_MPW) && defined(CARBON)
261      /* Fix it according to the current operating system */
262     convert_pathname(buf);
263 #endif /* MAC_MPW && CARBON */
264
265         /* Success */
266         return (0);
267 }
268
269
270 #endif /* SET_UID */
271
272
273 #ifndef HAVE_MKSTEMP
274
275 /*
276  * Hack -- acquire a "temporary" file name if possible
277  *
278  * This filename is always in "system-specific" form.
279  */
280 static errr path_temp(char *buf, int max)
281 {
282         cptr s;
283
284         /* Temp file */
285         s = tmpnam(NULL);
286
287         if (!s) return (-1);
288
289         /* Format to length */
290 #if !defined(WIN32) || (defined(_MSC_VER) && (_MSC_VER >= 1900))
291         (void)strnfmt(buf, max, "%s", s);
292 #else
293         (void)strnfmt(buf, max, ".%s", s);
294 #endif
295
296         /* Success */
297         return (0);
298 }
299
300 #endif
301
302 /*
303  * Create a new path by appending a file (or directory) to a path.
304  *
305  * This requires no special processing on simple machines, except
306  * for verifying the size of the filename, but note the ability to
307  * bypass the given "path" with certain special file-names.
308  *
309  * Note that the "file" may actually be a "sub-path", including
310  * a path and a file.
311  *
312  * Note that this function yields a path which must be "parsed"
313  * using the "parse" function above.
314  */
315 errr path_build(char *buf, int max, cptr path, cptr file)
316 {
317         /* Special file */
318         if (file[0] == '~')
319         {
320                 /* Use the file itself */
321                 (void)strnfmt(buf, max, "%s", file);
322         }
323
324         /* Absolute file, on "normal" systems */
325         else if (prefix(file, PATH_SEP) && !streq(PATH_SEP, ""))
326         {
327                 /* Use the file itself */
328                 (void)strnfmt(buf, max, "%s", file);
329         }
330
331         /* No path given */
332         else if (!path[0])
333         {
334                 /* Use the file itself */
335                 (void)strnfmt(buf, max, "%s", file);
336         }
337
338         /* Path and File */
339         else
340         {
341                 /* Build the new path */
342                 (void)strnfmt(buf, max, "%s%s%s", path, PATH_SEP, file);
343         }
344
345         /* Success */
346         return (0);
347 }
348
349
350 /*
351  * Hack -- replacement for "fopen()"
352  */
353 FILE *my_fopen(cptr file, cptr mode)
354 {
355         char buf[1024];
356
357 #if defined(MAC_MPW) || defined(MACH_O_CARBON)
358         FILE *tempfff;
359 #endif
360
361         /* Hack -- Try to parse the path */
362         if (path_parse(buf, 1024, file)) return (NULL);
363
364 #if defined(MAC_MPW) || defined(MACH_O_CARBON)
365         if (my_strchr(mode, 'w'))
366         {
367                 /* setting file type/creator */
368                 tempfff = fopen(buf, mode);
369                 fsetfileinfo(buf, _fcreator, _ftype);
370                 fclose(tempfff);
371         }
372 #endif
373
374         /* Attempt to fopen the file anyway */
375         return (fopen(buf, mode));
376 }
377
378
379 /*
380  * Hack -- replacement for "fclose()"
381  */
382 errr my_fclose(FILE *fff)
383 {
384         /* Require a file */
385         if (!fff) return (-1);
386
387         /* Close, check for error */
388         if (fclose(fff) == EOF) return (1);
389
390         /* Success */
391         return (0);
392 }
393
394
395 #endif /* ACORN */
396
397
398 #ifdef HAVE_MKSTEMP
399
400 FILE *my_fopen_temp(char *buf, int max)
401 {
402         int fd;
403
404         /* Prepare the buffer for mkstemp */
405         strncpy(buf, "/tmp/anXXXXXX", max);
406
407         /* Secure creation of a temporary file */
408         fd = mkstemp(buf);
409
410         /* Check the file-descriptor */
411         if (fd < 0) return (NULL);
412
413         /* Return a file stream */
414         return (fdopen(fd, "w"));
415 }
416
417 #else /* HAVE_MKSTEMP */
418
419 FILE *my_fopen_temp(char *buf, int max)
420 {
421         /* Generate a temporary filename */
422         if (path_temp(buf, max)) return (NULL);
423
424         /* Open the file */
425         return (my_fopen(buf, "w"));
426 }
427
428 #endif /* HAVE_MKSTEMP */
429
430
431 /*
432  * Hack -- replacement for "fgets()"
433  *
434  * Read a string, without a newline, to a file
435  *
436  * Process tabs, strip internal non-printables
437  */
438 errr my_fgets(FILE *fff, char *buf, huge n)
439 {
440         huge i = 0;
441
442         char *s;
443
444         char tmp[1024];
445
446         /* Read a line */
447         if (fgets(tmp, 1024, fff))
448         {
449 #ifdef JP
450                 guess_convert_to_system_encoding(tmp, sizeof(tmp));
451 #endif
452
453                 /* Convert weirdness */
454                 for (s = tmp; *s; s++)
455                 {
456 #if defined(MACINTOSH) || defined(MACH_O_CARBON)
457
458                         /*
459                          * Be nice to the Macintosh, where a file can have Mac or Unix
460                          * end of line, especially since the introduction of OS X.
461                          * MPW tools were also very tolerant to the Unix EOL.
462                          */
463                         if (*s == '\r') *s = '\n';
464
465 #endif /* MACINTOSH || MACH_O_CARBON */
466
467                         /* Handle newline */
468                         if (*s == '\n')
469                         {
470                                 /* Terminate */
471                                 buf[i] = '\0';
472
473                                 /* Success */
474                                 return (0);
475                         }
476
477                         /* Handle tabs */
478                         else if (*s == '\t')
479                         {
480                                 /* Hack -- require room */
481                                 if (i + 8 >= n) break;
482
483                                 /* Append a space */
484                                 buf[i++] = ' ';
485
486                                 /* Append some more spaces */
487                                 while (0 != (i % 8)) buf[i++] = ' ';
488                         }
489
490 #ifdef JP
491                         else if (iskanji(*s))
492                         {
493                                 if (!s[1]) break;
494                                 buf[i++] = *s++;
495                                 buf[i++] = *s;
496                         }
497
498                         /* 半角かなに対応 */
499                         else if (iskana(*s))
500                         {
501                                 buf[i++] = *s;
502                                 if (i >= n) break;
503                         }
504 #endif
505                         /* Handle printables */
506                         else if (isprint((unsigned char)*s))
507                         {
508                                 /* Copy */
509                                 buf[i++] = *s;
510
511                                 /* Check length */
512                                 if (i >= n) break;
513                         }
514                 }
515                 /* No newline character, but terminate */
516                 buf[i] = '\0';
517
518                 /* Success */
519                 return (0);
520         }
521
522         /* Nothing */
523         buf[0] = '\0';
524
525         /* Failure */
526         return (1);
527 }
528
529
530 /*
531  * Hack -- replacement for "fputs()"
532  *
533  * Dump a string, plus a newline, to a file
534  *
535  * Process internal weirdness?
536  */
537 errr my_fputs(FILE *fff, cptr buf, huge n)
538 {
539         /* XXX XXX */
540         n = n ? n : 0;
541
542         /* Dump, ignore errors */
543         (void)fprintf(fff, "%s\n", buf);
544
545         /* Success */
546         return (0);
547 }
548
549
550 #ifdef ACORN
551
552
553 /*
554  * Most of the "file" routines for "ACORN" should be in "main-acn.c"
555  *
556  * Many of them can be rewritten now that only "fd_open()" and "fd_make()"
557  * and "my_fopen()" should ever create files.
558  */
559
560
561 #else /* ACORN */
562
563
564 /*
565  * Code Warrior is a little weird about some functions
566  */
567 #ifdef BEN_HACK
568 extern int open(const char *, int, ...);
569 extern int close(int);
570 extern int read(int, void *, unsigned int);
571 extern int write(int, const void *, unsigned int);
572 extern long lseek(int, long, int);
573 #endif /* BEN_HACK */
574
575
576 /*
577  * The Macintosh is a little bit brain-dead sometimes
578  */
579 #ifdef MACINTOSH
580 # define open(N,F,M) \
581 ((M), open((char*)(N),F))
582 # define write(F,B,S) \
583 write(F,(char*)(B),S)
584 #endif /* MACINTOSH */
585
586
587 /*
588  * Several systems have no "O_BINARY" flag
589  */
590 #ifndef O_BINARY
591 # define O_BINARY 0
592 #endif /* O_BINARY */
593
594
595 /*
596  * Hack -- attempt to delete a file
597  */
598 errr fd_kill(cptr file)
599 {
600         char buf[1024];
601
602         /* Hack -- Try to parse the path */
603         if (path_parse(buf, 1024, file)) return (-1);
604
605         /* Remove */
606         (void)remove(buf);
607
608         return (0);
609 }
610
611
612 /*
613  * Hack -- attempt to move a file
614  */
615 errr fd_move(cptr file, cptr what)
616 {
617         char buf[1024];
618         char aux[1024];
619
620         /* Hack -- Try to parse the path */
621         if (path_parse(buf, 1024, file)) return (-1);
622
623         /* Hack -- Try to parse the path */
624         if (path_parse(aux, 1024, what)) return (-1);
625
626         /* Rename */
627         (void)rename(buf, aux);
628
629         return (0);
630 }
631
632
633 /*
634  * Hack -- attempt to copy a file
635  */
636 errr fd_copy(cptr file, cptr what)
637 {
638         char buf[1024];
639         char aux[1024];
640         int read_num;
641         int src_fd, dst_fd;
642
643         /* Hack -- Try to parse the path */
644         if (path_parse(buf, 1024, file)) return (-1);
645
646         /* Hack -- Try to parse the path */
647         if (path_parse(aux, 1024, what)) return (-1);
648
649         /* Open source file */
650         src_fd = fd_open(buf, O_RDONLY);
651         if (src_fd < 0) return (-1);
652
653         /* Open destination file */
654         dst_fd = fd_open(aux, O_WRONLY|O_TRUNC|O_CREAT);
655         if (dst_fd < 0) return (-1);
656
657         /* Copy */
658         while ((read_num = read(src_fd, buf, 1024)) > 0)
659         {
660                 int write_num = 0;
661                 while (write_num < read_num)
662                 {
663                         int ret = write(dst_fd, buf + write_num, read_num - write_num);
664                         if (ret < 0) {
665                                 /* Close files */
666                                 fd_close(src_fd);
667                                 fd_close(dst_fd);
668
669                                 return ret;
670                         }
671                         write_num += ret;
672                 }
673         }
674
675         /* Close files */
676         fd_close(src_fd);
677         fd_close(dst_fd);
678
679         return (0);
680 }
681
682
683 /*
684  * Hack -- attempt to open a file descriptor (create file)
685  *
686  * This function should fail if the file already exists
687  *
688  * Note that we assume that the file should be "binary"
689  *
690  * The horrible "BEN_HACK" code is for compiling under
691  * the CodeWarrior compiler, in which case, for some reason, none
692  * of the "O_*" flags are defined, and we must fake the definition
693  * of "O_RDONLY", "O_WRONLY", and "O_RDWR" in "A-win-h", and then
694  * we must simulate the effect of the proper "open()" call below.
695  */
696 int fd_make(cptr file, BIT_FLAGS mode)
697 {
698         char buf[1024];
699
700         /* Hack -- Try to parse the path */
701         if (path_parse(buf, 1024, file)) return (-1);
702
703 #ifdef BEN_HACK
704
705         /* Check for existance */
706         /* if (fd_close(fd_open(file, O_RDONLY | O_BINARY))) return (1); */
707
708         /* Mega-Hack -- Create the file */
709         (void)my_fclose(my_fopen(file, "wb"));
710
711         /* Re-open the file for writing */
712         return (open(buf, O_WRONLY | O_BINARY, mode));
713
714 #else /* BEN_HACK */
715
716 #if defined(MAC_MPW) || defined(MACH_O_CARBON)
717         {
718                 int fdes;
719                 /* Create the file, fail if exists, write-only, binary */
720                 fdes = open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, mode);
721                 /* Set creator and type if the file is successfully opened */
722                 if (fdes >= 0) fsetfileinfo(buf, _fcreator, _ftype);
723                 /* Return the descriptor */
724                 return (fdes);
725         }
726 # else
727         /* Create the file, fail if exists, write-only, binary */
728         return (open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, mode));
729 # endif
730
731 #endif /* BEN_HACK */
732
733 }
734
735
736 /*
737  * Hack -- attempt to open a file descriptor (existing file)
738  *
739  * Note that we assume that the file should be "binary"
740  */
741 int fd_open(cptr file, int flags)
742 {
743         char buf[1024];
744
745         /* Hack -- Try to parse the path */
746         if (path_parse(buf, 1024, file)) return (-1);
747
748         /* Attempt to open the file */
749         return (open(buf, flags | O_BINARY, 0));
750 }
751
752
753 /*
754  * Hack -- attempt to lock a file descriptor
755  *
756  * Legal lock types -- F_UNLCK, F_RDLCK, F_WRLCK
757  */
758 errr fd_lock(int fd, int what)
759 {
760         /* XXX XXX */
761         what = what ? what : 0;
762
763         /* Verify the fd */
764         if (fd < 0) return (-1);
765
766 #ifdef SET_UID
767
768 # ifdef USG
769
770 #  if defined(F_ULOCK) && defined(F_LOCK)
771
772         /* Un-Lock */
773         if (what == F_UNLCK)
774         {
775                 /* Unlock it, Ignore errors */
776                 lockf(fd, F_ULOCK, 0);
777         }
778
779         /* Lock */
780         else
781         {
782                 /* Lock the score file */
783                 if (lockf(fd, F_LOCK, 0) != 0) return (1);
784         }
785
786 #  endif
787
788 # else
789
790 #  if defined(LOCK_UN) && defined(LOCK_EX)
791
792         /* Un-Lock */
793         if (what == F_UNLCK)
794         {
795                 /* Unlock it, Ignore errors */
796                 (void)flock(fd, LOCK_UN);
797         }
798
799         /* Lock */
800         else
801         {
802                 /* Lock the score file */
803                 if (flock(fd, LOCK_EX) != 0) return (1);
804         }
805
806 #  endif
807
808 # endif
809
810 #endif
811
812         /* Success */
813         return (0);
814 }
815
816
817 /*
818  * Hack -- attempt to seek on a file descriptor
819  */
820 errr fd_seek(int fd, huge n)
821 {
822         huge p;
823
824         /* Verify fd */
825         if (fd < 0) return (-1);
826
827         /* Seek to the given position */
828         p = lseek(fd, n, SEEK_SET);
829
830         /* Failure */
831         if (p != n) return (1);
832
833         /* Success */
834         return (0);
835 }
836
837
838 /*
839  * Hack -- attempt to truncate a file descriptor
840  */
841 errr fd_chop(int fd, huge n)
842 {
843         /* XXX XXX */
844         n = n ? n : 0;
845
846         /* Verify the fd */
847         if (fd < 0) return (-1);
848
849 #if defined(ULTRIX) || defined(NeXT)
850         /* Truncate */
851         ftruncate(fd, n);
852 #endif
853
854         /* Success */
855         return (0);
856 }
857
858
859 /*
860  * Hack -- attempt to read data from a file descriptor
861  */
862 errr fd_read(int fd, char *buf, huge n)
863 {
864         /* Verify the fd */
865         if (fd < 0) return (-1);
866
867 #ifndef SET_UID
868
869         /* Read pieces */
870         while (n >= 16384)
871         {
872                 /* Read a piece */
873                 if (read(fd, buf, 16384) != 16384) return (1);
874
875                 /* Shorten the task */
876                 buf += 16384;
877
878                 /* Shorten the task */
879                 n -= 16384;
880         }
881
882 #endif
883
884         /* Read the final piece */
885         if (read(fd, buf, n) != (int)n) return (1);
886
887         /* Success */
888         return (0);
889 }
890
891
892 /*
893  * Hack -- Attempt to write data to a file descriptor
894  */
895 errr fd_write(int fd, cptr buf, huge n)
896 {
897         /* Verify the fd */
898         if (fd < 0) return (-1);
899
900 #ifndef SET_UID
901
902         /* Write pieces */
903         while (n >= 16384)
904         {
905                 /* Write a piece */
906                 if (write(fd, buf, 16384) != 16384) return (1);
907
908                 /* Shorten the task */
909                 buf += 16384;
910
911                 /* Shorten the task */
912                 n -= 16384;
913         }
914
915 #endif
916
917         /* Write the final piece */
918         if (write(fd, buf, n) != (int)n) return (1);
919
920         /* Success */
921         return (0);
922 }
923
924
925 /*
926  * Hack -- attempt to close a file descriptor
927  */
928 errr fd_close(int fd)
929 {
930         /* Verify the fd */
931         if (fd < 0) return (-1);
932
933         /* Close */
934         (void)close(fd);
935
936         return (0);
937 }
938
939
940 #endif /* ACORN */
941
942
943
944
945 /*
946  * Important note about "colors" 
947  *
948  * The "TERM_*" color definitions list the "composition" of each
949  * "Angband color" in terms of "quarters" of each of the three color
950  * components (Red, Green, Blue), for example, TERM_UMBER is defined
951  * as 2/4 Red, 1/4 Green, 0/4 Blue.
952  *
953  * The following info is from "Torbjorn Lindgren" (see "main-xaw.c").
954  *
955  * These values are NOT gamma-corrected.  On most machines (with the
956  * Macintosh being an important exception), you must "gamma-correct"
957  * the given values, that is, "correct for the intrinsic non-linearity
958  * of the phosphor", by converting the given intensity levels based
959  * on the "gamma" of the target screen, which is usually 1.7 (or 1.5).
960  *
961  * The actual formula for conversion is unknown to me at this time,
962  * but you can use the table below for the most common gamma values.
963  *
964  * So, on most machines, simply convert the values based on the "gamma"
965  * of the target screen, which is usually in the range 1.5 to 1.7, and
966  * usually is closest to 1.7.  The converted value for each of the five
967  * different "quarter" values is given below:
968  *
969  *  Given     Gamma 1.0       Gamma 1.5       Gamma 1.7     Hex 1.7
970  *  -----       ----            ----            ----          ---
971  *   0/4        0.00            0.00            0.00          #00
972  *   1/4        0.25            0.27            0.28          #47
973  *   2/4        0.50            0.55            0.56          #8f
974  *   3/4        0.75            0.82            0.84          #d7
975  *   4/4        1.00            1.00            1.00          #ff
976  *
977  * Note that some machines (i.e. most IBM machines) are limited to a
978  * hard-coded set of colors, and so the information above is useless.
979  *
980  * Also, some machines are limited to a pre-determined set of colors,
981  * for example, the IBM can only display 16 colors, and only 14 of
982  * those colors resemble colors used by Angband, and then only when
983  * you ignore the fact that "Slate" and "cyan" are not really matches,
984  * so on the IBM, we use "orange" for both "Umber", and "Light Umber"
985  * in addition to the obvious "Orange", since by combining all of the
986  * "indeterminate" colors into a single color, the rest of the colors
987  * are left with "meaningful" values.
988  */
989
990
991 /*
992  * Move the cursor
993  */
994 void move_cursor(int row, int col)
995 {
996         Term_gotoxy(col, row);
997 }
998
999
1000
1001 /*
1002  * Convert a decimal to a single digit octal number
1003  */
1004 static char octify(uint i)
1005 {
1006         return (hexsym[i%8]);
1007 }
1008
1009 /*
1010  * Convert a decimal to a single digit hex number
1011  */
1012 static char hexify(uint i)
1013 {
1014         return (hexsym[i%16]);
1015 }
1016
1017
1018 /*
1019  * Convert a octal-digit into a decimal
1020  */
1021 static int deoct(char c)
1022 {
1023         if (isdigit(c)) return (D2I(c));
1024         return (0);
1025 }
1026
1027 /*
1028  * Convert a hexidecimal-digit into a decimal
1029  */
1030 static int dehex(char c)
1031 {
1032         if (isdigit(c)) return (D2I(c));
1033         if (islower(c)) return (A2I(c) + 10);
1034         if (isupper(c)) return (A2I(tolower(c)) + 10);
1035         return (0);
1036 }
1037
1038
1039 static int my_stricmp(cptr a, cptr b)
1040 {
1041         cptr s1, s2;
1042         char z1, z2;
1043
1044         /* Scan the strings */
1045         for (s1 = a, s2 = b; TRUE; s1++, s2++)
1046         {
1047                 z1 = FORCEUPPER(*s1);
1048                 z2 = FORCEUPPER(*s2);
1049                 if (z1 < z2) return (-1);
1050                 if (z1 > z2) return (1);
1051                 if (!z1) return (0);
1052         }
1053 }
1054
1055 static int my_strnicmp(cptr a, cptr b, int n)
1056 {
1057         cptr s1, s2;
1058         char z1, z2;
1059
1060         /* Scan the strings */
1061         for (s1 = a, s2 = b; n > 0; s1++, s2++, n--)
1062         {
1063                 z1 = FORCEUPPER(*s1);
1064                 z2 = FORCEUPPER(*s2);
1065                 if (z1 < z2) return (-1);
1066                 if (z1 > z2) return (1);
1067                 if (!z1) return (0);
1068         }
1069         return 0;
1070 }
1071
1072
1073 static void trigger_text_to_ascii(char **bufptr, cptr *strptr)
1074 {
1075         char *s = *bufptr;
1076         cptr str = *strptr;
1077         bool mod_status[MAX_MACRO_MOD];
1078
1079         int i, len = 0;
1080         int shiftstatus = 0;
1081         cptr key_code;
1082
1083         if (macro_template == NULL)
1084                 return;
1085         
1086         for (i = 0; macro_modifier_chr[i]; i++)
1087                 mod_status[i] = FALSE;
1088         str++;
1089
1090         /* Examine modifier keys */
1091         while (1)
1092         {
1093                 for (i=0; macro_modifier_chr[i]; i++)
1094                 {
1095                         len = strlen(macro_modifier_name[i]);
1096                         
1097                         if(!my_strnicmp(str, macro_modifier_name[i], len))
1098                                 break;
1099                 }
1100                 if (!macro_modifier_chr[i]) break;
1101                 str += len;
1102                 mod_status[i] = TRUE;
1103                 if ('S' == macro_modifier_chr[i])
1104                         shiftstatus = 1;
1105         }
1106         for (i = 0; i < max_macrotrigger; i++)
1107         {
1108                 len = strlen(macro_trigger_name[i]);
1109                 if (!my_strnicmp(str, macro_trigger_name[i], len) && ']' == str[len])
1110                 {
1111                         /* a trigger name found */
1112                         break;
1113                 }
1114         }
1115
1116         /* Invalid trigger name? */
1117         if (i == max_macrotrigger)
1118         {
1119                 str = my_strchr(str, ']');
1120                 if (str)
1121                 {
1122                         *s++ = (char)31;
1123                         *s++ = '\r';
1124                         *bufptr = s;
1125                         *strptr = str; /* where **strptr == ']' */
1126                 }
1127                 return;
1128         }
1129         key_code = macro_trigger_keycode[shiftstatus][i];
1130         str += len;
1131
1132         *s++ = (char)31;
1133         for (i = 0; macro_template[i]; i++)
1134         {
1135                 char ch = macro_template[i];
1136                 int j;
1137
1138                 switch(ch)
1139                 {
1140                 case '&':
1141                         for (j = 0; macro_modifier_chr[j]; j++) {
1142                                 if (mod_status[j])
1143                                         *s++ = macro_modifier_chr[j];
1144                         }
1145                         break;
1146                 case '#':
1147                         strcpy(s, key_code);
1148                         s += strlen(key_code);
1149                         break;
1150                 default:
1151                         *s++ = ch;
1152                         break;
1153                 }
1154         }
1155         *s++ = '\r';
1156
1157         *bufptr = s;
1158         *strptr = str; /* where **strptr == ']' */
1159         return;
1160 }
1161
1162
1163 /*
1164  * Hack -- convert a printable string into real ascii
1165  *
1166  * I have no clue if this function correctly handles, for example,
1167  * parsing "\xFF" into a (signed) char.  Whoever thought of making
1168  * the "sign" of a "char" undefined is a complete moron.  Oh well.
1169  */
1170 void text_to_ascii(char *buf, cptr str)
1171 {
1172         char *s = buf;
1173
1174         /* Analyze the "ascii" string */
1175         while (*str)
1176         {
1177                 /* Backslash codes */
1178                 if (*str == '\\')
1179                 {
1180                         /* Skip the backslash */
1181                         str++;
1182
1183                         /* Paranoia */
1184                         if (!(*str)) break;
1185
1186                         /* Macro Trigger */
1187                         if (*str == '[')
1188                         {
1189                                 trigger_text_to_ascii(&s, &str);
1190                         }
1191                         else
1192
1193                         /* Hex-mode XXX */
1194                         if (*str == 'x')
1195                         {
1196                                 *s = 16 * (char)dehex(*++str);
1197                                 *s++ += (char)dehex(*++str);
1198                         }
1199
1200                         /* Hack -- simple way to specify "backslash" */
1201                         else if (*str == '\\')
1202                         {
1203                                 *s++ = '\\';
1204                         }
1205
1206                         /* Hack -- simple way to specify "caret" */
1207                         else if (*str == '^')
1208                         {
1209                                 *s++ = '^';
1210                         }
1211
1212                         /* Hack -- simple way to specify "space" */
1213                         else if (*str == 's')
1214                         {
1215                                 *s++ = ' ';
1216                         }
1217
1218                         /* Hack -- simple way to specify Escape */
1219                         else if (*str == 'e')
1220                         {
1221                                 *s++ = ESCAPE;
1222                         }
1223
1224                         /* Backspace */
1225                         else if (*str == 'b')
1226                         {
1227                                 *s++ = '\b';
1228                         }
1229
1230                         /* Newline */
1231                         else if (*str == 'n')
1232                         {
1233                                 *s++ = '\n';
1234                         }
1235
1236                         /* Return */
1237                         else if (*str == 'r')
1238                         {
1239                                 *s++ = '\r';
1240                         }
1241
1242                         /* Tab */
1243                         else if (*str == 't')
1244                         {
1245                                 *s++ = '\t';
1246                         }
1247
1248                         /* Octal-mode */
1249                         else if (*str == '0')
1250                         {
1251                                 *s = 8 * (char)deoct(*++str);
1252                                 *s++ += (char)deoct(*++str);
1253                         }
1254
1255                         /* Octal-mode */
1256                         else if (*str == '1')
1257                         {
1258                                 *s = 64 + 8 * (char)deoct(*++str);
1259                                 *s++ += (char)deoct(*++str);
1260                         }
1261
1262                         /* Octal-mode */
1263                         else if (*str == '2')
1264                         {
1265                                 *s = 64 * 2 + 8 * (char)deoct(*++str);
1266                                 *s++ += (char)deoct(*++str);
1267                         }
1268
1269                         /* Octal-mode */
1270                         else if (*str == '3')
1271                         {
1272                                 *s = 64 * 3 + 8 * (char)deoct(*++str);
1273                                 *s++ += (char)deoct(*++str);
1274                         }
1275
1276                         /* Skip the final char */
1277                         str++;
1278                 }
1279
1280                 /* Normal Control codes */
1281                 else if (*str == '^')
1282                 {
1283                         str++;
1284                         *s++ = (*str++ & 037);
1285                 }
1286
1287                 /* Normal chars */
1288                 else
1289                 {
1290                         *s++ = *str++;
1291                 }
1292         }
1293
1294         /* Terminate */
1295         *s = '\0';
1296 }
1297
1298
1299 static bool trigger_ascii_to_text(char **bufptr, cptr *strptr)
1300 {
1301         char *s = *bufptr;
1302         cptr str = *strptr;
1303         char key_code[100];
1304         int i;
1305         cptr tmp;
1306
1307         if (macro_template == NULL)
1308                 return FALSE;
1309
1310         *s++ = '\\';
1311         *s++ = '[';
1312
1313         for (i = 0; macro_template[i]; i++)
1314         {
1315                 int j;
1316                 char ch = macro_template[i];
1317
1318                 switch(ch)
1319                 {
1320                 case '&':
1321                         while ((tmp = my_strchr(macro_modifier_chr, *str)) != 0)
1322                         {
1323                                 j = (int)(tmp - macro_modifier_chr);
1324                                 tmp = macro_modifier_name[j];
1325                                 while(*tmp) *s++ = *tmp++;
1326                                 str++;
1327                         }
1328                         break;
1329                 case '#':
1330                         for (j = 0; *str && *str != '\r'; j++)
1331                                 key_code[j] = *str++;
1332                         key_code[j] = '\0';
1333                         break;
1334                 default:
1335                         if (ch != *str) return FALSE;
1336                         str++;
1337                 }
1338         }
1339         if (*str++ != '\r') return FALSE;
1340
1341         for (i = 0; i < max_macrotrigger; i++)
1342         {
1343                 if (!my_stricmp(key_code, macro_trigger_keycode[0][i])
1344                     || !my_stricmp(key_code, macro_trigger_keycode[1][i]))
1345                         break;
1346         }
1347         if (i == max_macrotrigger)
1348                 return FALSE;
1349
1350         tmp = macro_trigger_name[i];
1351         while (*tmp) *s++ = *tmp++;
1352
1353         *s++ = ']';
1354         
1355         *bufptr = s;
1356         *strptr = str;
1357         return TRUE;
1358 }
1359
1360
1361 /*
1362  * Hack -- convert a string into a printable form
1363  */
1364 void ascii_to_text(char *buf, cptr str)
1365 {
1366         char *s = buf;
1367
1368         /* Analyze the "ascii" string */
1369         while (*str)
1370         {
1371                 byte i = (byte)(*str++);
1372
1373                 /* Macro Trigger */
1374                 if (i == 31)
1375                 {
1376                         if(!trigger_ascii_to_text(&s, &str))
1377                         {
1378                                 *s++ = '^';
1379                                 *s++ = '_';
1380                         }
1381                 }
1382                 else
1383
1384                 if (i == ESCAPE)
1385                 {
1386                         *s++ = '\\';
1387                         *s++ = 'e';
1388                 }
1389                 else if (i == ' ')
1390                 {
1391                         *s++ = '\\';
1392                         *s++ = 's';
1393                 }
1394                 else if (i == '\b')
1395                 {
1396                         *s++ = '\\';
1397                         *s++ = 'b';
1398                 }
1399                 else if (i == '\t')
1400                 {
1401                         *s++ = '\\';
1402                         *s++ = 't';
1403                 }
1404                 else if (i == '\n')
1405                 {
1406                         *s++ = '\\';
1407                         *s++ = 'n';
1408                 }
1409                 else if (i == '\r')
1410                 {
1411                         *s++ = '\\';
1412                         *s++ = 'r';
1413                 }
1414                 else if (i == '^')
1415                 {
1416                         *s++ = '\\';
1417                         *s++ = '^';
1418                 }
1419                 else if (i == '\\')
1420                 {
1421                         *s++ = '\\';
1422                         *s++ = '\\';
1423                 }
1424                 else if (i < 32)
1425                 {
1426                         *s++ = '^';
1427                         *s++ = i + 64;
1428                 }
1429                 else if (i < 127)
1430                 {
1431                         *s++ = i;
1432                 }
1433                 else if (i < 64)
1434                 {
1435                         *s++ = '\\';
1436                         *s++ = '0';
1437                         *s++ = octify(i / 8);
1438                         *s++ = octify(i % 8);
1439                 }
1440                 else
1441                 {
1442                         *s++ = '\\';
1443                         *s++ = 'x';
1444                         *s++ = hexify(i / 16);
1445                         *s++ = hexify(i % 16);
1446                 }
1447         }
1448
1449         /* Terminate */
1450         *s = '\0';
1451 }
1452
1453
1454
1455 /*
1456  * The "macro" package
1457  *
1458  * Functions are provided to manipulate a collection of macros, each
1459  * of which has a trigger pattern string and a resulting action string
1460  * and a small set of flags.
1461  */
1462
1463
1464
1465 /*
1466  * Determine if any macros have ever started with a given character.
1467  */
1468 static bool macro__use[256];
1469
1470
1471 /*
1472  * Find the macro (if any) which exactly matches the given pattern
1473  */
1474 sint macro_find_exact(cptr pat)
1475 {
1476         int i;
1477
1478         /* Nothing possible */
1479         if (!macro__use[(byte)(pat[0])])
1480         {
1481                 return (-1);
1482         }
1483
1484         /* Scan the macros */
1485         for (i = 0; i < macro__num; ++i)
1486         {
1487                 /* Skip macros which do not match the pattern */
1488                 if (!streq(macro__pat[i], pat)) continue;
1489
1490                 /* Found one */
1491                 return (i);
1492         }
1493
1494         /* No matches */
1495         return (-1);
1496 }
1497
1498
1499 /*
1500  * Find the first macro (if any) which contains the given pattern
1501  */
1502 static sint macro_find_check(cptr pat)
1503 {
1504         int i;
1505
1506         /* Nothing possible */
1507         if (!macro__use[(byte)(pat[0])])
1508         {
1509                 return (-1);
1510         }
1511
1512         /* Scan the macros */
1513         for (i = 0; i < macro__num; ++i)
1514         {
1515                 /* Skip macros which do not contain the pattern */
1516                 if (!prefix(macro__pat[i], pat)) continue;
1517
1518                 /* Found one */
1519                 return (i);
1520         }
1521
1522         /* Nothing */
1523         return (-1);
1524 }
1525
1526
1527 /*
1528  * Find the first macro (if any) which contains the given pattern and more
1529  */
1530 static sint macro_find_maybe(cptr pat)
1531 {
1532         int i;
1533
1534         /* Nothing possible */
1535         if (!macro__use[(byte)(pat[0])])
1536         {
1537                 return (-1);
1538         }
1539
1540         /* Scan the macros */
1541         for (i = 0; i < macro__num; ++i)
1542         {
1543                 /* Skip macros which do not contain the pattern */
1544                 if (!prefix(macro__pat[i], pat)) continue;
1545
1546                 /* Skip macros which exactly match the pattern XXX XXX */
1547                 if (streq(macro__pat[i], pat)) continue;
1548
1549                 /* Found one */
1550                 return (i);
1551         }
1552
1553         /* Nothing */
1554         return (-1);
1555 }
1556
1557
1558 /*
1559  * Find the longest macro (if any) which starts with the given pattern
1560  */
1561 static sint macro_find_ready(cptr pat)
1562 {
1563         int i, t, n = -1, s = -1;
1564
1565         /* Nothing possible */
1566         if (!macro__use[(byte)(pat[0])])
1567         {
1568                 return (-1);
1569         }
1570
1571         /* Scan the macros */
1572         for (i = 0; i < macro__num; ++i)
1573         {
1574                 /* Skip macros which are not contained by the pattern */
1575                 if (!prefix(pat, macro__pat[i])) continue;
1576
1577                 /* Obtain the length of this macro */
1578                 t = strlen(macro__pat[i]);
1579
1580                 /* Only track the "longest" pattern */
1581                 if ((n >= 0) && (s > t)) continue;
1582
1583                 /* Track the entry */
1584                 n = i;
1585                 s = t;
1586         }
1587
1588         /* Result */
1589         return (n);
1590 }
1591
1592
1593 /*
1594  * Add a macro definition (or redefinition).
1595  *
1596  * We should use "act == NULL" to "remove" a macro, but this might make it
1597  * impossible to save the "removal" of a macro definition.  
1598  *
1599  * We should consider refusing to allow macros which contain existing macros,
1600  * or which are contained in existing macros, because this would simplify the
1601  * macro analysis code.  
1602  *
1603  * We should consider removing the "command macro" crap, and replacing it
1604  * with some kind of "powerful keymap" ability, but this might make it hard
1605  * to change the "roguelike" option from inside the game.  
1606  */
1607 errr macro_add(cptr pat, cptr act)
1608 {
1609         int n;
1610
1611
1612         /* Paranoia -- require data */
1613         if (!pat || !act) return (-1);
1614
1615
1616         /* Look for any existing macro */
1617         n = macro_find_exact(pat);
1618
1619         /* Replace existing macro */
1620         if (n >= 0)
1621         {
1622                 /* Free the old macro action */
1623                 string_free(macro__act[n]);
1624         }
1625
1626         /* Create a new macro */
1627         else
1628         {
1629                 /* Acquire a new index */
1630                 n = macro__num++;
1631
1632                 /* Save the pattern */
1633                 macro__pat[n] = string_make(pat);
1634         }
1635
1636         /* Save the action */
1637         macro__act[n] = string_make(act);
1638
1639         /* Efficiency */
1640         macro__use[(byte)(pat[0])] = TRUE;
1641
1642         /* Success */
1643         return (0);
1644 }
1645
1646
1647
1648 /*
1649  * Local variable -- we are inside a "macro action"
1650  *
1651  * Do not match any macros until "ascii 30" is found.
1652  */
1653 static bool parse_macro = FALSE;
1654
1655 /*
1656  * Local variable -- we are inside a "macro trigger"
1657  *
1658  * Strip all keypresses until a low ascii value is found.
1659  */
1660 static bool parse_under = FALSE;
1661
1662
1663 /*
1664  * Flush all input chars.  Actually, remember the flush,
1665  * and do a "special flush" before the next "inkey()".
1666  *
1667  * This is not only more efficient, but also necessary to make sure
1668  * that various "inkey()" codes are not "lost" along the way.
1669  */
1670 void flush(void)
1671 {
1672         /* Do it later */
1673         inkey_xtra = TRUE;
1674 }
1675
1676
1677 /*
1678  * Flush the screen, make a noise
1679  */
1680 void bell(void)
1681 {
1682         /* Mega-Hack -- Flush the output */
1683         Term_fresh();
1684
1685         /* Make a bell noise (if allowed) */
1686         if (ring_bell) Term_xtra(TERM_XTRA_NOISE, 0);
1687
1688         /* Flush the input (later!) */
1689         flush();
1690 }
1691
1692
1693 /*
1694  * Hack -- Make a (relevant?) sound
1695  */
1696 void sound(int val)
1697 {
1698         /* No sound */
1699         if (!use_sound) return;
1700
1701         /* Make a sound (if allowed) */
1702         Term_xtra(TERM_XTRA_SOUND, val);
1703 }
1704
1705 /*
1706  * Hack -- Play a music
1707  */
1708 errr play_music(int type, int val)
1709 {
1710         /* No sound */
1711         if (!use_music) return 1;
1712
1713         /* Make a sound (if allowed) */
1714         return Term_xtra(type, val);
1715 }
1716
1717 /*
1718  * Hack -- Select floor music.
1719  */
1720 void select_floor_music(void)
1721 {
1722         int i;
1723         /* No sound */
1724         if (!use_music) return;
1725
1726         if(ambush_flag)
1727         {
1728                 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_AMBUSH);
1729                 return;
1730         }
1731
1732         if(p_ptr->wild_mode)
1733         {
1734                 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_WILD);
1735                 return;
1736         }
1737
1738         if(p_ptr->inside_arena)
1739         {
1740                 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_ARENA);
1741                 return;
1742         }
1743
1744         if(p_ptr->inside_battle)
1745         {
1746                 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_BATTLE);
1747                 return;
1748         }
1749
1750         if(p_ptr->inside_quest)
1751         {
1752                 if(play_music(TERM_XTRA_MUSIC_QUEST, p_ptr->inside_quest))
1753                 {
1754                         play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_QUEST);
1755                 }
1756                 return;
1757         }
1758
1759         for(i = 0; i < max_q_idx; i++)
1760         { // TODO マクロで類似条件を統合すること
1761                 if(quest[i].status == QUEST_STATUS_TAKEN &&
1762                         (quest[i].type == QUEST_TYPE_KILL_LEVEL || quest[i].type == QUEST_TYPE_RANDOM) &&
1763                          quest[i].level == dun_level && dungeon_type == quest[i].dungeon)
1764                 {
1765                         if(play_music(TERM_XTRA_MUSIC_QUEST, i)) 
1766                         {
1767                                 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_QUEST);
1768                         }
1769                         return;
1770                 }
1771         }
1772
1773         if(dungeon_type)
1774         {
1775                 if(p_ptr->feeling == 2) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_FEEL2);
1776                 else if(p_ptr->feeling >= 3 && p_ptr->feeling <= 5) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_FEEL1);
1777                 else
1778                 {
1779                         if(play_music(TERM_XTRA_MUSIC_DUNGEON, dungeon_type))
1780                         {
1781                                 if(dun_level < 40) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_LOW);
1782                                 else if(dun_level < 80) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_MED);
1783                                 else play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_HIGH);
1784                         }
1785                 }
1786                 return;
1787         }
1788
1789         if(p_ptr->town_num)
1790         {
1791                 if(play_music(TERM_XTRA_MUSIC_TOWN, p_ptr->town_num))
1792                 {
1793                         play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_TOWN);
1794                 }
1795                 return;
1796         }
1797
1798         if(!dun_level)
1799         {
1800                 if(p_ptr->lev >= 45) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD3);
1801                 else if(p_ptr->lev >= 25) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD2);
1802                 else play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD1);
1803                 return;
1804         }
1805         
1806 }
1807
1808
1809
1810 /*
1811  * Helper function called only from "inkey()"
1812  *
1813  * This function does almost all of the "macro" processing.
1814  *
1815  * We use the "Term_key_push()" function to handle "failed" macros, as well
1816  * as "extra" keys read in while choosing the proper macro, and also to hold
1817  * the action for the macro, plus a special "ascii 30" character indicating
1818  * that any macro action in progress is complete.  Embedded macros are thus
1819  * illegal, unless a macro action includes an explicit "ascii 30" character,
1820  * which would probably be a massive hack, and might break things.
1821  *
1822  * Only 500 (0+1+2+...+29+30) milliseconds may elapse between each key in
1823  * the macro trigger sequence.  If a key sequence forms the "prefix" of a
1824  * macro trigger, 500 milliseconds must pass before the key sequence is
1825  * known not to be that macro trigger.  
1826  */
1827 static char inkey_aux(void)
1828 {
1829         int k = 0, n, p = 0, w = 0;
1830
1831         char ch;
1832
1833         cptr pat, act;
1834
1835         char *buf = inkey_macro_trigger_string;
1836
1837         /* Hack : キー入力待ちで止まっているので、流れた行の記憶は不要。 */
1838         num_more = 0;
1839
1840         if (parse_macro)
1841         {
1842                 /* Scan next keypress from macro action */
1843                 if (Term_inkey(&ch, FALSE, TRUE))
1844                 {
1845                         /* Over-flowed? Cancel macro action */
1846                         parse_macro = FALSE;
1847                 }
1848         }
1849         else
1850         {
1851                 /* Wait for a keypress */
1852                 (void) (Term_inkey(&ch, TRUE, TRUE));
1853         }
1854
1855
1856         /* End "macro action" */
1857         if (ch == 30) parse_macro = FALSE;
1858
1859         /* Inside "macro action" */
1860         if (ch == 30) return (ch);
1861
1862         /* Inside "macro action" */
1863         if (parse_macro) return (ch);
1864
1865         /* Inside "macro trigger" */
1866         if (parse_under) return (ch);
1867
1868         /* Save the first key, advance */
1869         buf[p++] = ch;
1870         buf[p] = '\0';
1871
1872
1873         /* Check for possible macro */
1874         k = macro_find_check(buf);
1875
1876         /* No macro pending */
1877         if (k < 0) return (ch);
1878
1879
1880         /* Wait for a macro, or a timeout */
1881         while (TRUE)
1882         {
1883                 /* Check for pending macro */
1884                 k = macro_find_maybe(buf);
1885
1886                 /* No macro pending */
1887                 if (k < 0) break;
1888
1889                 /* Check for (and remove) a pending key */
1890                 if (0 == Term_inkey(&ch, FALSE, TRUE))
1891                 {
1892                         /* Append the key */
1893                         buf[p++] = ch;
1894                         buf[p] = '\0';
1895
1896                         /* Restart wait */
1897                         w = 0;
1898                 }
1899
1900                 /* No key ready */
1901                 else
1902                 {
1903                         /* Increase "wait" */
1904                         w += 1;
1905
1906                         /* Excessive delay */
1907                         if (w >= 10) break;
1908
1909                         /* Delay */
1910                         Term_xtra(TERM_XTRA_DELAY, w);
1911                 }
1912         }
1913
1914
1915         /* Check for available macro */
1916         k = macro_find_ready(buf);
1917
1918         /* No macro available */
1919         if (k < 0)
1920         {
1921                 /* Push all the keys back on the queue */
1922                 while (p > 0)
1923                 {
1924                         /* Push the key, notice over-flow */
1925                         if (Term_key_push(buf[--p])) return (0);
1926                 }
1927
1928                 /* Wait for (and remove) a pending key */
1929                 (void)Term_inkey(&ch, TRUE, TRUE);
1930
1931                 /* Return the key */
1932                 return (ch);
1933         }
1934
1935
1936         /* Get the pattern */
1937         pat = macro__pat[k];
1938
1939         /* Get the length of the pattern */
1940         n = strlen(pat);
1941
1942         /* Push the "extra" keys back on the queue */
1943         while (p > n)
1944         {
1945                 /* Push the key, notice over-flow */
1946                 if (Term_key_push(buf[--p])) return (0);
1947         }
1948
1949
1950         /* Begin "macro action" */
1951         parse_macro = TRUE;
1952
1953         /* Push the "end of macro action" key */
1954         if (Term_key_push(30)) return (0);
1955
1956
1957         /* Access the macro action */
1958         act = macro__act[k];
1959
1960         /* Get the length of the action */
1961         n = strlen(act);
1962
1963         /* Push the macro "action" onto the key queue */
1964         while (n > 0)
1965         {
1966                 /* Push the key, notice over-flow */
1967                 if (Term_key_push(act[--n])) return (0);
1968         }
1969
1970
1971         /* Hack -- Force "inkey()" to call us again */
1972         return (0);
1973 }
1974
1975
1976 /*
1977  * Cancel macro action on the queue
1978  */
1979 static void forget_macro_action(void)
1980 {
1981         if (!parse_macro) return;
1982
1983         /* Drop following macro action string */
1984         while (TRUE)
1985         {
1986                 char ch;
1987
1988                 /* End loop if no key ready */
1989                 if (Term_inkey(&ch, FALSE, TRUE)) break;
1990
1991                 /* End loop if no key ready */
1992                 if (ch == 0) break;
1993
1994                 /* End of "macro action" */
1995                 if (ch == 30) break;
1996         }
1997
1998         /* No longer inside "macro action" */
1999         parse_macro = FALSE;
2000 }
2001
2002
2003 /*
2004  * Mega-Hack -- special "inkey_next" pointer.  
2005  *
2006  * This special pointer allows a sequence of keys to be "inserted" into
2007  * the stream of keys returned by "inkey()".  This key sequence will not
2008  * trigger any macros, and cannot be bypassed by the Borg.  It is used
2009  * in Angband to handle "keymaps".
2010  */
2011 static cptr inkey_next = NULL;
2012
2013
2014 #ifdef ALLOW_BORG
2015
2016 /*
2017  * Mega-Hack -- special "inkey_hack" hook.  
2018  *
2019  * This special function hook allows the "Borg" (see elsewhere) to take
2020  * control of the "inkey()" function, and substitute in fake keypresses.
2021  */
2022 char (*inkey_hack)(int flush_first) = NULL;
2023
2024 #endif /* ALLOW_BORG */
2025
2026
2027
2028 /*
2029  * Get a keypress from the user.
2030  *
2031  * This function recognizes a few "global parameters".  These are variables
2032  * which, if set to TRUE before calling this function, will have an effect
2033  * on this function, and which are always reset to FALSE by this function
2034  * before this function returns.  Thus they function just like normal
2035  * parameters, except that most calls to this function can ignore them.
2036  *
2037  * If "inkey_xtra" is TRUE, then all pending keypresses will be flushed,
2038  * and any macro processing in progress will be aborted.  This flag is
2039  * set by the "flush()" function, which does not actually flush anything
2040  * itself, but rather, triggers delayed input flushing via "inkey_xtra".
2041  *
2042  * If "inkey_scan" is TRUE, then we will immediately return "zero" if no
2043  * keypress is available, instead of waiting for a keypress.
2044  *
2045  * If "inkey_base" is TRUE, then all macro processing will be bypassed.
2046  * If "inkey_base" and "inkey_scan" are both TRUE, then this function will
2047  * not return immediately, but will wait for a keypress for as long as the
2048  * normal macro matching code would, allowing the direct entry of macro
2049  * triggers.  The "inkey_base" flag is extremely dangerous!
2050  *
2051  * If "inkey_flag" is TRUE, then we will assume that we are waiting for a
2052  * normal command, and we will only show the cursor if "hilite_player" is
2053  * TRUE (or if the player is in a store), instead of always showing the
2054  * cursor.  The various "main-xxx.c" files should avoid saving the game
2055  * in response to a "menu item" request unless "inkey_flag" is TRUE, to
2056  * prevent savefile corruption.
2057  *
2058  * If we are waiting for a keypress, and no keypress is ready, then we will
2059  * refresh (once) the window which was active when this function was called.
2060  *
2061  * Note that "back-quote" is automatically converted into "escape" for
2062  * convenience on machines with no "escape" key.  This is done after the
2063  * macro matching, so the user can still make a macro for "backquote".
2064  *
2065  * Note the special handling of "ascii 30" (ctrl-caret, aka ctrl-shift-six)
2066  * and "ascii 31" (ctrl-underscore, aka ctrl-shift-minus), which are used to
2067  * provide support for simple keyboard "macros".  These keys are so strange
2068  * that their loss as normal keys will probably be noticed by nobody.  The
2069  * "ascii 30" key is used to indicate the "end" of a macro action, which
2070  * allows recursive macros to be avoided.  The "ascii 31" key is used by
2071  * some of the "main-xxx.c" files to introduce macro trigger sequences.
2072  *
2073  * Hack -- we use "ascii 29" (ctrl-right-bracket) as a special "magic" key,
2074  * which can be used to give a variety of "sub-commands" which can be used
2075  * any time.  These sub-commands could include commands to take a picture of
2076  * the current screen, to start/stop recording a macro action, etc.
2077  *
2078  * If "angband_term[0]" is not active, we will make it active during this
2079  * function, so that the various "main-xxx.c" files can assume that input
2080  * is only requested (via "Term_inkey()") when "angband_term[0]" is active.
2081  *
2082  * Mega-Hack -- This function is used as the entry point for clearing the
2083  * "signal_count" variable, and of the "character_saved" variable.
2084  *
2085  * Hack -- Note the use of "inkey_next" to allow "keymaps" to be processed.
2086  *
2087  * Mega-Hack -- Note the use of "inkey_hack" to allow the "Borg" to steal
2088  * control of the keyboard from the user.
2089  */
2090 char inkey(void)
2091 {
2092         int v;
2093         char kk;
2094         char ch = 0;
2095         bool done = FALSE;
2096         term *old = Term;
2097
2098         /* Hack -- Use the "inkey_next" pointer */
2099         if (inkey_next && *inkey_next && !inkey_xtra)
2100         {
2101                 /* Get next character, and advance */
2102                 ch = *inkey_next++;
2103
2104                 /* Cancel the various "global parameters" */
2105                 inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
2106
2107                 /* Accept result */
2108                 return (ch);
2109         }
2110
2111         /* Forget pointer */
2112         inkey_next = NULL;
2113
2114
2115 #ifdef ALLOW_BORG
2116
2117         /* Mega-Hack -- Use the special hook */
2118         if (inkey_hack && ((ch = (*inkey_hack)(inkey_xtra)) != 0))
2119         {
2120                 /* Cancel the various "global parameters" */
2121                 inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
2122
2123                 /* Accept result */
2124                 return (ch);
2125         }
2126
2127 #endif /* ALLOW_BORG */
2128
2129
2130         /* Hack -- handle delayed "flush()" */
2131         if (inkey_xtra)
2132         {
2133                 /* End "macro action" */
2134                 parse_macro = FALSE;
2135
2136                 /* End "macro trigger" */
2137                 parse_under = FALSE;
2138
2139                 /* Forget old keypresses */
2140                 Term_flush();
2141         }
2142
2143
2144         /* Access cursor state */
2145         (void)Term_get_cursor(&v);
2146
2147         /* Show the cursor if waiting, except sometimes in "command" mode */
2148         if (!inkey_scan && (!inkey_flag || hilite_player || character_icky))
2149         {
2150                 /* Show the cursor */
2151                 (void)Term_set_cursor(1);
2152         }
2153
2154
2155         /* Hack -- Activate main screen */
2156         Term_activate(angband_term[0]);
2157
2158
2159         /* Get a key */
2160         while (!ch)
2161         {
2162                 /* Hack -- Handle "inkey_scan" */
2163                 if (!inkey_base && inkey_scan &&
2164                         (0 != Term_inkey(&kk, FALSE, FALSE)))
2165                 {
2166                         break;
2167                 }
2168
2169
2170                 /* Hack -- Flush output once when no key ready */
2171                 if (!done && (0 != Term_inkey(&kk, FALSE, FALSE)))
2172                 {
2173                         /* Hack -- activate proper term */
2174                         Term_activate(old);
2175
2176                         /* Flush output */
2177                         Term_fresh();
2178
2179                         /* Hack -- activate main screen */
2180                         Term_activate(angband_term[0]);
2181
2182                         /* Mega-Hack -- reset saved flag */
2183                         character_saved = FALSE;
2184
2185                         /* Mega-Hack -- reset signal counter */
2186                         signal_count = 0;
2187
2188                         /* Only once */
2189                         done = TRUE;
2190                 }
2191
2192
2193                 /* Hack -- Handle "inkey_base" */
2194                 if (inkey_base)
2195                 {
2196                         int w = 0;
2197
2198                         /* Wait forever */
2199                         if (!inkey_scan)
2200                         {
2201                                 /* Wait for (and remove) a pending key */
2202                                 if (0 == Term_inkey(&ch, TRUE, TRUE))
2203                                 {
2204                                         break;
2205                                 }
2206
2207                                 break;
2208                         }
2209
2210                         /* Wait */
2211                         while (TRUE)
2212                         {
2213                                 /* Check for (and remove) a pending key */
2214                                 if (0 == Term_inkey(&ch, FALSE, TRUE))
2215                                 {
2216                                         break;
2217                                 }
2218
2219                                 /* No key ready */
2220                                 else
2221                                 {
2222                                         /* Increase "wait" */
2223                                         w += 10;
2224
2225                                         /* Excessive delay */
2226                                         if (w >= 100) break;
2227
2228                                         /* Delay */
2229                                         Term_xtra(TERM_XTRA_DELAY, w);
2230                                 }
2231                         }
2232
2233                         break;
2234                 }
2235
2236
2237                 /* Get a key (see above) */
2238                 ch = inkey_aux();
2239
2240
2241                 /* Handle "control-right-bracket" */
2242                 if (ch == 29)
2243                 {
2244                         /* Strip this key */
2245                         ch = 0;
2246
2247                         /* Continue */
2248                         continue;
2249                 }
2250
2251
2252                 /* Treat back-quote as escape */
2253 /*              if (ch == '`') ch = ESCAPE; */
2254
2255
2256                 /* End "macro trigger" */
2257                 if (parse_under && (ch <= 32))
2258                 {
2259                         /* Strip this key */
2260                         ch = 0;
2261
2262                         /* End "macro trigger" */
2263                         parse_under = FALSE;
2264                 }
2265
2266
2267                 /* Handle "control-caret" */
2268                 if (ch == 30)
2269                 {
2270                         /* Strip this key */
2271                         ch = 0;
2272                 }
2273
2274                 /* Handle "control-underscore" */
2275                 else if (ch == 31)
2276                 {
2277                         /* Strip this key */
2278                         ch = 0;
2279
2280                         /* Begin "macro trigger" */
2281                         parse_under = TRUE;
2282                 }
2283
2284                 /* Inside "macro trigger" */
2285                 else if (parse_under)
2286                 {
2287                         /* Strip this key */
2288                         ch = 0;
2289                 }
2290         }
2291
2292
2293         /* Hack -- restore the term */
2294         Term_activate(old);
2295
2296
2297         /* Restore the cursor */
2298         Term_set_cursor(v);
2299
2300
2301         /* Cancel the various "global parameters" */
2302         inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
2303
2304         /* Return the keypress */
2305         return (ch);
2306 }
2307
2308
2309
2310
2311 /*
2312  * We use a global array for all inscriptions to reduce the memory
2313  * spent maintaining inscriptions.  Of course, it is still possible
2314  * to run out of inscription memory, especially if too many different
2315  * inscriptions are used, but hopefully this will be rare.
2316  *
2317  * We use dynamic string allocation because otherwise it is necessary
2318  * to pre-guess the amount of quark activity.  We limit the total
2319  * number of quarks, but this is much easier to "expand" as needed.
2320  *
2321  * Any two items with the same inscription will have the same "quark"
2322  * index, which should greatly reduce the need for inscription space.
2323  *
2324  * Note that "quark zero" is NULL and should not be "dereferenced".
2325  */
2326
2327 /*
2328  * Initialize the quark array
2329  */
2330 void quark_init(void)
2331 {
2332         /* Quark variables */
2333         C_MAKE(quark__str, QUARK_MAX, cptr);
2334
2335         /* Prepare first quark, which is used when quark_add() is failed */
2336         quark__str[1] = string_make("");
2337
2338         /* There is one quark (+ NULL) */
2339         quark__num = 2;
2340 }
2341
2342
2343 /*
2344  * Add a new "quark" to the set of quarks.
2345  */
2346 u16b quark_add(cptr str)
2347 {
2348         u16b i;
2349
2350         /* Look for an existing quark */
2351         for (i = 1; i < quark__num; i++)
2352         {
2353                 /* Check for equality */
2354                 if (streq(quark__str[i], str)) return (i);
2355         }
2356
2357         /* Return "" when no room is available */
2358         if (quark__num == QUARK_MAX) return 1;
2359
2360         /* New maximal quark */
2361         quark__num = i + 1;
2362
2363         /* Add a new quark */
2364         quark__str[i] = string_make(str);
2365
2366         /* Return the index */
2367         return (i);
2368 }
2369
2370
2371 /*
2372  * This function looks up a quark
2373  */
2374 cptr quark_str(STR_OFFSET i)
2375 {
2376         cptr q;
2377
2378         /* Return NULL for an invalid index */
2379         if ((i < 1) || (i >= quark__num)) return NULL;
2380
2381         /* Access the quark */
2382         q = quark__str[i];
2383
2384         /* Return the quark */
2385         return (q);
2386 }
2387
2388
2389
2390
2391 /*
2392  * Second try for the "message" handling routines.
2393  *
2394  * Each call to "message_add(s)" will add a new "most recent" message
2395  * to the "message recall list", using the contents of the string "s".
2396  *
2397  * The messages will be stored in such a way as to maximize "efficiency",
2398  * that is, we attempt to maximize the number of sequential messages that
2399  * can be retrieved, given a limited amount of storage space.
2400  *
2401  * We keep a buffer of chars to hold the "text" of the messages, not
2402  * necessarily in "order", and an array of offsets into that buffer,
2403  * representing the actual messages.  This is made more complicated
2404  * by the fact that both the array of indexes, and the buffer itself,
2405  * are both treated as "circular arrays" for efficiency purposes, but
2406  * the strings may not be "broken" across the ends of the array.
2407  *
2408  * The "message_add()" function is rather "complex", because it must be
2409  * extremely efficient, both in space and time, for use with the Borg.
2410  */
2411
2412
2413
2414 /*!
2415  * @brief 保存中の過去ゲームメッセージの数を返す。 / How many messages are "available"?
2416  * @return 残っているメッセージの数
2417  */
2418 s32b message_num(void)
2419 {
2420         int last, next, n;
2421
2422         /* Extract the indexes */
2423         last = message__last;
2424         next = message__next;
2425
2426         /* Handle "wrap" */
2427         if (next < last) next += MESSAGE_MAX;
2428
2429         /* Extract the space */
2430         n = (next - last);
2431
2432         /* Return the result */
2433         return (n);
2434 }
2435
2436
2437 /*!
2438  * @brief 過去のゲームメッセージを返す。 / Recall the "text" of a saved message
2439  * @params age メッセージの世代
2440  * @return メッセージの文字列ポインタ
2441  */
2442 cptr message_str(int age)
2443 {
2444         s32b x;
2445         s32b o;
2446         cptr s;
2447
2448         /* Forgotten messages have no text */
2449         if ((age < 0) || (age >= message_num())) return ("");
2450
2451         /* Acquire the "logical" index */
2452         x = (message__next + MESSAGE_MAX - (age + 1)) % MESSAGE_MAX;
2453
2454         /* Get the "offset" for the message */
2455         o = message__ptr[x];
2456
2457         /* Access the message text */
2458         s = &message__buf[o];
2459
2460         /* Return the message text */
2461         return (s);
2462 }
2463
2464
2465 /*!
2466  * @brief ゲームメッセージをログに追加する。 / Add a new message, with great efficiency
2467  * @params str 保存したいメッセージ
2468  * @return なし
2469  */
2470 void message_add(cptr str)
2471 {
2472         u32b i, n;
2473         int k, x, m;
2474
2475         char u[4096];
2476         char splitted1[81];
2477         cptr splitted2;
2478
2479         /*** Step 1 -- Analyze the message ***/
2480
2481         /* Hack -- Ignore "non-messages" */
2482         if (!str) return;
2483
2484         /* Message length */
2485         n = strlen(str);
2486
2487         /* Important Hack -- Ignore "long" messages */
2488         if (n >= MESSAGE_BUF / 4) return;
2489
2490         /* extra step -- split the message if n>80.(added by Mogami) */
2491         if (n > 80) {
2492 #ifdef JP
2493                 cptr t = str;
2494
2495                 for (n = 0; n < 80; n++, t++)
2496                 {
2497                         if(iskanji(*t)) {
2498                                 t++;
2499                                 n++;
2500                         }
2501                 }
2502                 if (n == 81) n = 79; /* 最後の文字が漢字半分 */
2503 #else
2504                 for (n = 80; n > 60; n--)
2505                         if (str[n] == ' ') break;
2506                 if (n == 60) n = 80;
2507 #endif
2508                 splitted2 = str + n;
2509                 strncpy(splitted1, str ,n);
2510                 splitted1[n] = '\0';
2511                 str = splitted1;
2512         } else {
2513                 splitted2 = NULL;
2514         }
2515
2516         /*** Step 2 -- 最適化の試行 / Attempt to optimize ***/
2517
2518         /* Limit number of messages to check */
2519         m = message_num();
2520         k = m / 4;
2521         if (k > MESSAGE_MAX / 32) k = MESSAGE_MAX / 32;
2522
2523         /* Check previous message */
2524         for (i = message__next; m; m--)
2525         {
2526                 int j = 1;
2527
2528                 char buf[1024];
2529                 char *t;
2530
2531                 cptr old;
2532
2533                 /* Back up and wrap if needed */
2534                 if (i-- == 0) i = MESSAGE_MAX - 1;
2535
2536                 /* Access the old string */
2537                 old = &message__buf[message__ptr[i]];
2538
2539                 /* Skip small messages */
2540                 if (!old) continue;
2541
2542                 strcpy(buf, old);
2543
2544                 /* Find multiple */
2545 #ifdef JP
2546                 for (t = buf; *t && (*t != '<' || (*(t+1) != 'x' )); t++) 
2547                         if(iskanji(*t))t++;
2548 #else
2549                 for (t = buf; *t && (*t != '<'); t++);
2550 #endif
2551
2552                 if (*t)
2553                 {
2554                         /* Message is too small */
2555                         if (strlen(buf) < 6) break;
2556
2557                         /* Drop the space */
2558                         *(t - 1) = '\0';
2559
2560                         /* Get multiplier */
2561                         j = atoi(t+2);
2562                 }
2563
2564                 /* Limit the multiplier to 1000 */
2565                 if (streq(buf, str) && (j < 1000))
2566                 {
2567                         j++;
2568
2569                         /* Overwrite */
2570                         message__next = i;
2571
2572                         str = u;
2573
2574                         /* Write it out */
2575                         sprintf(u, "%s <x%d>", buf, j);
2576
2577                         /* Message length */
2578                         n = strlen(str);
2579
2580                         if (!now_message) now_message++;
2581                 }
2582                 else
2583                 {
2584                         num_more++;/*流れた行の数を数えておく */
2585                         now_message++;
2586                 }
2587
2588                 break;
2589         }
2590
2591         /* Check the last few messages (if any to count) */
2592         for (i = message__next; k; k--)
2593         {
2594                 int q;
2595                 cptr old;
2596
2597                 /* Back up and wrap if needed */
2598                 if (i-- == 0) i = MESSAGE_MAX - 1;
2599
2600                 /* Stop before oldest message */
2601                 if (i == message__last) break;
2602
2603                 /* Extract "distance" from "head" */
2604                 q = (message__head + MESSAGE_BUF - message__ptr[i]) % MESSAGE_BUF;
2605
2606                 /* Do not optimize over large distance */
2607                 if (q > MESSAGE_BUF / 2) continue;
2608
2609                 /* Access the old string */
2610                 old = &message__buf[message__ptr[i]];
2611
2612                 /* Compare */
2613                 if (!streq(old, str)) continue;
2614
2615                 /* Get the next message index, advance */
2616                 x = message__next++;
2617
2618                 /* Handle wrap */
2619                 if (message__next == MESSAGE_MAX) message__next = 0;
2620
2621                 /* Kill last message if needed */
2622                 if (message__next == message__last) message__last++;
2623
2624                 /* Handle wrap */
2625                 if (message__last == MESSAGE_MAX) message__last = 0;
2626
2627                 /* Assign the starting address */
2628                 message__ptr[x] = message__ptr[i];
2629
2630                 /* Success */
2631                 /* return; */
2632                 goto end_of_message_add;
2633
2634         }
2635
2636
2637         /*** Step 3 -- Ensure space before end of buffer ***/
2638
2639         /* Kill messages and Wrap if needed */
2640         if (message__head + n + 1 >= MESSAGE_BUF)
2641         {
2642                 /* Kill all "dead" messages */
2643                 for (i = message__last; TRUE; i++)
2644                 {
2645                         /* Wrap if needed */
2646                         if (i == MESSAGE_MAX) i = 0;
2647
2648                         /* Stop before the new message */
2649                         if (i == message__next) break;
2650
2651                         /* Kill "dead" messages */
2652                         if (message__ptr[i] >= message__head)
2653                         {
2654                                 /* Track oldest message */
2655                                 message__last = i + 1;
2656                         }
2657                 }
2658
2659                 /* Wrap "tail" if needed */
2660                 if (message__tail >= message__head) message__tail = 0;
2661
2662                 /* Start over */
2663                 message__head = 0;
2664         }
2665
2666
2667         /*** Step 4 -- Ensure space before next message ***/
2668
2669         /* Kill messages if needed */
2670         if (message__head + n + 1 > message__tail)
2671         {
2672                 /* Grab new "tail" */
2673                 message__tail = message__head + n + 1;
2674
2675                 /* Advance tail while possible past first "nul" */
2676                 while (message__buf[message__tail-1]) message__tail++;
2677
2678                 /* Kill all "dead" messages */
2679                 for (i = message__last; TRUE; i++)
2680                 {
2681                         /* Wrap if needed */
2682                         if (i == MESSAGE_MAX) i = 0;
2683
2684                         /* Stop before the new message */
2685                         if (i == message__next) break;
2686
2687                         /* Kill "dead" messages */
2688                         if ((message__ptr[i] >= message__head) &&
2689                                 (message__ptr[i] < message__tail))
2690                         {
2691                                 /* Track oldest message */
2692                                 message__last = i + 1;
2693                         }
2694                 }
2695         }
2696
2697
2698         /*** Step 5 -- Grab a new message index ***/
2699
2700         /* Get the next message index, advance */
2701         x = message__next++;
2702
2703         /* Handle wrap */
2704         if (message__next == MESSAGE_MAX) message__next = 0;
2705
2706         /* Kill last message if needed */
2707         if (message__next == message__last) message__last++;
2708
2709         /* Handle wrap */
2710         if (message__last == MESSAGE_MAX) message__last = 0;
2711
2712
2713
2714         /*** Step 6 -- Insert the message text ***/
2715
2716         /* Assign the starting address */
2717         message__ptr[x] = message__head;
2718
2719         /* Append the new part of the message */
2720         for (i = 0; i < n; i++)
2721         {
2722                 /* Copy the message */
2723                 message__buf[message__head + i] = str[i];
2724         }
2725
2726         /* Terminate */
2727         message__buf[message__head + i] = '\0';
2728
2729         /* Advance the "head" pointer */
2730         message__head += n + 1;
2731
2732         /* recursively add splitted message (added by Mogami) */
2733 end_of_message_add:
2734         if (splitted2 != NULL)
2735           message_add(splitted2);
2736 }
2737
2738
2739
2740 /*
2741  * Hack -- flush
2742  */
2743 static void msg_flush(int x)
2744 {
2745         byte a = TERM_L_BLUE;
2746         bool nagasu = FALSE;
2747
2748         if ((auto_more && !now_damaged) || num_more < 0){
2749                 int i;
2750                 for (i = 0; i < 8; i++)
2751                 {
2752                         if (angband_term[i] && (window_flag[i] & PW_MESSAGE)) break;
2753                 }
2754                 if (i < 8)
2755                 {
2756                         if (num_more < angband_term[i]->hgt) nagasu = TRUE;
2757                 }
2758                 else
2759                 {
2760                         nagasu = TRUE;
2761                 }
2762         }
2763         now_damaged = FALSE;
2764
2765         if (!p_ptr->playing || !nagasu)
2766         {
2767                 /* Pause for response */
2768                 Term_putstr(x, 0, -1, a, _("-続く-", "-more-"));
2769
2770                 /* Get an acceptable keypress */
2771                 while (1)
2772                 {
2773                         int cmd = inkey();
2774                         if (cmd == ESCAPE) {
2775                             num_more = -9999; /*auto_moreのとき、全て流す。 */
2776                             break;
2777                         } else if (cmd == ' ') {
2778                             num_more = 0; /*1画面だけ流す。 */
2779                             break;
2780                         } else if ((cmd == '\n') || (cmd == '\r')) {
2781                             num_more--; /*1行だけ流す。 */
2782                             break;
2783                         }
2784                         if (quick_messages) break;
2785                         bell();
2786                 }
2787         }
2788
2789         /* Clear the line */
2790         Term_erase(0, 0, 255);
2791 }
2792
2793
2794 /*
2795  * Output a message to the top line of the screen.
2796  *
2797  * Break long messages into multiple pieces (40-72 chars).
2798  *
2799  * Allow multiple short messages to "share" the top line.
2800  *
2801  * Prompt the user to make sure he has a chance to read them.
2802  *
2803  * These messages are memorized for later reference (see above).
2804  *
2805  * We could do "Term_fresh()" to provide "flicker" if needed.
2806  *
2807  * The global "msg_flag" variable can be cleared to tell us to
2808  * "erase" any "pending" messages still on the screen.
2809  *
2810  * Note that we must be very careful about using the
2811  * "msg_print()" functions without explicitly calling the special
2812  * "msg_print(NULL)" function, since this may result in the loss
2813  * of information if the screen is cleared, or if anything is
2814  * displayed on the top line.
2815  *
2816  * Note that "msg_print(NULL)" will clear the top line
2817  * even if no messages are pending.  This is probably a hack.
2818  */
2819 void msg_print(cptr msg)
2820 {
2821         static int p = 0;
2822         int n;
2823         char *t;
2824         char buf[1024];
2825
2826         if (world_monster) return;
2827
2828         /* Hack -- Reset */
2829         if (!msg_flag) {
2830                 /* Clear the line */
2831                 Term_erase(0, 0, 255);
2832                 p = 0;
2833         }
2834
2835         /* Original Message Length */
2836         n = (msg ? strlen(msg) : 0);
2837
2838         /* Hack -- flush when requested or needed */
2839         if (p && (!msg || ((p + n) > 72)))
2840         {
2841                 /* Flush */
2842                 msg_flush(p);
2843
2844                 /* Forget it */
2845                 msg_flag = FALSE;
2846
2847                 /* Reset */
2848                 p = 0;
2849         }
2850
2851         /* No message */
2852         if (!msg) return;
2853
2854         /* Paranoia */
2855         if (n > 1000) return;
2856
2857         /* Copy it */
2858         if (!cheat_turn)
2859         {
2860                 strcpy(buf, msg);
2861         }
2862         else
2863         {
2864                 sprintf(buf, ("T:%d - %s"), (int)turn, msg);
2865         }
2866
2867         /* New Message Length */
2868         n = strlen(buf);
2869
2870         /* Memorize the message */
2871         if (character_generated) message_add(buf);
2872
2873         /* Analyze the buffer */
2874         t = buf;
2875
2876         /* Split message */
2877         while (n > 72)
2878         {
2879                 char oops;
2880                 int check, split = 72;
2881
2882 #ifdef JP
2883                 bool k_flag = FALSE;
2884                 int wordlen = 0;
2885
2886                 /* Find the "best" split point */
2887                 for (check = 0; check < 72; check++)
2888                 {
2889                         if (k_flag)
2890                         {
2891                                 k_flag = FALSE;
2892                                 continue;
2893                         }
2894
2895                         /* Found a valid split point */
2896                         if (iskanji(t[check]))
2897                         {
2898                                 k_flag = TRUE;
2899                                 split = check;
2900                         }
2901                         else if (t[check] == ' ')
2902                         {
2903                                 split = check;
2904                                 wordlen = 0;
2905                         }
2906                         else
2907                         {
2908                                 wordlen++;
2909                                 if (wordlen > 20)
2910                                         split = check;
2911                         }
2912                 }
2913 #else
2914                 /* Find the "best" split point */
2915                 for (check = 40; check < 72; check++)
2916                 {
2917                         /* Found a valid split point */
2918                         if (t[check] == ' ') split = check;
2919                 }
2920 #endif
2921
2922                 /* Save the split character */
2923                 oops = t[split];
2924
2925                 /* Split the message */
2926                 t[split] = '\0';
2927
2928                 /* Display part of the message */
2929                 Term_putstr(0, 0, split, TERM_WHITE, t);
2930
2931                 /* Flush it */
2932                 msg_flush(split + 1);
2933
2934                 /* Memorize the piece */
2935                 /* if (character_generated) message_add(t); */
2936
2937                 /* Restore the split character */
2938                 t[split] = oops;
2939
2940                 /* Insert a space */
2941                 t[--split] = ' ';
2942
2943                 /* Prepare to recurse on the rest of "buf" */
2944                 t += split; n -= split;
2945         }
2946
2947         /* Display the tail of the message */
2948         Term_putstr(p, 0, n, TERM_WHITE, t);
2949
2950         /* Memorize the tail */
2951         /* if (character_generated) message_add(t); */
2952
2953         p_ptr->window |= (PW_MESSAGE);
2954         window_stuff();
2955
2956         /* Remember the message */
2957         msg_flag = TRUE;
2958
2959         /* Remember the position */
2960 #ifdef JP
2961         p += n;
2962 #else
2963         p += n + 1;
2964 #endif
2965
2966         /* Optional refresh */
2967         if (fresh_message) Term_fresh();
2968 }
2969
2970 void msg_print_wizard(int cheat_type, cptr msg)
2971 {
2972         if (!cheat_room && cheat_type == CHEAT_DUNGEON) return;
2973         if (!cheat_peek && cheat_type == CHEAT_OBJECT) return;
2974         if (!cheat_hear && cheat_type == CHEAT_MONSTER) return;
2975         if (!cheat_xtra && cheat_type == CHEAT_MISC) return;
2976
2977         cptr cheat_mes[] = {"ITEM", "MONS", "DUNG", "MISC"};
2978         char buf[1024];
2979         sprintf(buf, "WIZ-%s:%s", cheat_mes[cheat_type], msg);
2980         msg_print(buf);
2981
2982         if (cheat_diary_output)
2983         {
2984                 do_cmd_write_nikki(NIKKI_WIZARD_LOG, 0, buf);
2985         }
2986
2987 }
2988
2989 /*
2990  * Hack -- prevent "accidents" in "screen_save()" or "screen_load()"
2991  */
2992 static int screen_depth = 0;
2993
2994
2995 /*
2996  * Save the screen, and increase the "icky" depth.
2997  *
2998  * This function must match exactly one call to "screen_load()".
2999  */
3000 void screen_save(void)
3001 {
3002         /* Hack -- Flush messages */
3003         msg_print(NULL);
3004
3005         /* Save the screen (if legal) */
3006         if (screen_depth++ == 0) Term_save();
3007
3008         /* Increase "icky" depth */
3009         character_icky++;
3010 }
3011
3012
3013 /*
3014  * Load the screen, and decrease the "icky" depth.
3015  *
3016  * This function must match exactly one call to "screen_save()".
3017  */
3018 void screen_load(void)
3019 {
3020         /* Hack -- Flush messages */
3021         msg_print(NULL);
3022
3023         /* Load the screen (if legal) */
3024         if (--screen_depth == 0) Term_load();
3025
3026         /* Decrease "icky" depth */
3027         character_icky--;
3028 }
3029
3030
3031 /*
3032  * Display a formatted message, using "vstrnfmt()" and "msg_print()".
3033  */
3034 void msg_format(cptr fmt, ...)
3035 {
3036         va_list vp;
3037
3038         char buf[1024];
3039
3040         /* Begin the Varargs Stuff */
3041         va_start(vp, fmt);
3042
3043         /* Format the args, save the length */
3044         (void)vstrnfmt(buf, 1024, fmt, vp);
3045
3046         /* End the Varargs Stuff */
3047         va_end(vp);
3048
3049         /* Display */
3050         msg_print(buf);
3051 }
3052
3053 /*
3054  * Display a formatted message, using "vstrnfmt()" and "msg_print()".
3055  */
3056 void msg_format_wizard(int cheat_type, cptr fmt, ...)
3057 {
3058         if(!cheat_room && cheat_type == CHEAT_DUNGEON) return;
3059         if(!cheat_peek && cheat_type == CHEAT_OBJECT) return;
3060         if(!cheat_hear && cheat_type == CHEAT_MONSTER) return;
3061         if(!cheat_xtra && cheat_type == CHEAT_MISC) return;
3062
3063         va_list vp;
3064         char buf[1024];
3065
3066         /* Begin the Varargs Stuff */
3067         va_start(vp, fmt);
3068
3069         /* Format the args, save the length */
3070         (void)vstrnfmt(buf, 1024, fmt, vp);
3071
3072         /* End the Varargs Stuff */
3073         va_end(vp);
3074
3075         /* Display */
3076         msg_print_wizard(cheat_type, buf);
3077 }
3078
3079
3080
3081 /*
3082  * Display a string on the screen using an attribute.
3083  *
3084  * At the given location, using the given attribute, if allowed,
3085  * add the given string.  Do not clear the line.
3086  */
3087 void c_put_str(TERM_COLOR attr, cptr str, int row, int col)
3088 {
3089         /* Position cursor, Dump the attr/text */
3090         Term_putstr(col, row, -1, attr, str);
3091 }
3092
3093 /*
3094  * As above, but in "white"
3095  */
3096 void put_str(cptr str, int row, int col)
3097 {
3098         /* Spawn */
3099         Term_putstr(col, row, -1, TERM_WHITE, str);
3100 }
3101
3102
3103
3104 /*
3105  * Display a string on the screen using an attribute, and clear
3106  * to the end of the line.
3107  */
3108 void c_prt(byte attr, cptr str, int row, int col)
3109 {
3110         /* Clear line, position cursor */
3111         Term_erase(col, row, 255);
3112
3113         /* Dump the attr/text */
3114         Term_addstr(-1, attr, str);
3115 }
3116
3117 /*
3118  * As above, but in "white"
3119  */
3120 void prt(cptr str, int row, int col)
3121 {
3122         /* Spawn */
3123         c_prt(TERM_WHITE, str, row, col);
3124 }
3125
3126
3127
3128
3129 /*
3130  * Print some (colored) text to the screen at the current cursor position,
3131  * automatically "wrapping" existing text (at spaces) when necessary to
3132  * avoid placing any text into the last column, and clearing every line
3133  * before placing any text in that line.  Also, allow "newline" to force
3134  * a "wrap" to the next line.  Advance the cursor as needed so sequential
3135  * calls to this function will work correctly.
3136  *
3137  * Once this function has been called, the cursor should not be moved
3138  * until all the related "c_roff()" calls to the window are complete.
3139  *
3140  * This function will correctly handle any width up to the maximum legal
3141  * value of 256, though it works best for a standard 80 character width.
3142  */
3143 void c_roff(byte a, cptr str)
3144 {
3145         int x, y;
3146
3147         int w, h;
3148
3149         cptr s;
3150
3151         /* Obtain the size */
3152         (void)Term_get_size(&w, &h);
3153
3154         /* Obtain the cursor */
3155         (void)Term_locate(&x, &y);
3156
3157         /* Hack -- No more space */
3158         if( y == h - 1 && x > w - 3) return;
3159
3160         /* Process the string */
3161         for (s = str; *s; s++)
3162         {
3163                 char ch;
3164
3165 #ifdef JP
3166                 int k_flag = iskanji(*s);
3167 #endif
3168                 /* Force wrap */
3169                 if (*s == '\n')
3170                 {
3171                         /* Wrap */
3172                         x = 0;
3173                         y++;
3174
3175                         /* No more space */
3176                         if( y == h ) break;
3177
3178                         /* Clear line, move cursor */
3179                         Term_erase(x, y, 255);
3180
3181                         break;
3182                 }
3183
3184                 /* Clean up the char */
3185 #ifdef JP
3186                 ch = ((k_flag || isprint(*s)) ? *s : ' ');
3187 #else
3188                 ch = (isprint(*s) ? *s : ' ');
3189 #endif
3190
3191
3192                 /* Wrap words as needed */
3193 #ifdef JP
3194                 if (( x >= ( (k_flag) ? w - 2 : w - 1 ) ) && (ch != ' '))
3195 #else
3196                 if ((x >= w - 1) && (ch != ' '))
3197 #endif
3198
3199                 {
3200                         int i, n = 0;
3201
3202                         TERM_COLOR av[256];
3203                         char cv[256];
3204
3205                         /* Wrap word */
3206                         if (x < w)
3207 #ifdef JP
3208                         {
3209                         /* 現在が半角文字の場合 */
3210                         if( !k_flag )
3211 #endif
3212                         {
3213                                 /* Scan existing text */
3214                                 for (i = w - 2; i >= 0; i--)
3215                                 {
3216                                         /* Grab existing attr/char */
3217                                         Term_what(i, y, &av[i], &cv[i]);
3218
3219                                         /* Break on space */
3220                                         if (cv[i] == ' ') break;
3221
3222                                         /* Track current word */
3223                                         n = i;
3224 #ifdef JP
3225                                         if (cv[i] == '(') break;
3226 #endif
3227                                 }
3228                         }
3229
3230 #ifdef JP
3231                         else
3232                         {
3233                                 /* 現在が全角文字のとき */
3234                                 /* 文頭が「。」「、」等になるときは、その1つ前の語で改行 */
3235                                 if (strncmp(s, "。", 2) == 0 || strncmp(s, "、", 2) == 0
3236 #if 0                   /* 一般的には「ィ」「ー」は禁則の対象外 */
3237                                         || strncmp(s, "ィ", 2) == 0 || strncmp(s, "ー", 2) == 0
3238 #endif
3239                                ){
3240                                         Term_what(x  , y, &av[x  ], &cv[x  ]);
3241                                         Term_what(x-1, y, &av[x-1], &cv[x-1]);
3242                                         Term_what(x-2, y, &av[x-2], &cv[x-2]);
3243                                         n = x - 2;
3244                                         cv[ x ] = '\0';
3245                                 }
3246                         }
3247                         }
3248 #endif
3249                         /* Special case */
3250                         if (n == 0) n = w;
3251
3252                         /* Clear line */
3253                         Term_erase(n, y, 255);
3254
3255                         /* Wrap */
3256                         x = 0;
3257                         y++;
3258
3259                         /* No more space */
3260                         if( y == h ) break;
3261
3262                         /* Clear line, move cursor */
3263                         Term_erase(x, y, 255);
3264
3265                         /* Wrap the word (if any) */
3266                         for (i = n; i < w - 1; i++)
3267                         {
3268 #ifdef JP
3269                                 if( cv[i] == '\0' ) break;
3270 #endif
3271                                 /* Dump */
3272                                 Term_addch(av[i], cv[i]);
3273
3274                                 /* Advance (no wrap) */
3275                                 if (++x > w) x = w;
3276                         }
3277                 }
3278
3279                 /* Dump */
3280 #ifdef JP
3281                 Term_addch((byte)(a|0x10), ch);
3282 #else
3283                 Term_addch(a, ch);
3284 #endif
3285
3286
3287 #ifdef JP
3288                 if (k_flag)
3289                 {
3290                         s++;
3291                         x++;
3292                         ch = *s;
3293                         Term_addch((byte)(a|0x20), ch);
3294                 }
3295 #endif
3296                 /* Advance */
3297                 if (++x > w) x = w;
3298         }
3299 }
3300
3301 /*
3302  * As above, but in "white"
3303  */
3304 void roff(cptr str)
3305 {
3306         /* Spawn */
3307         c_roff(TERM_WHITE, str);
3308 }
3309
3310
3311
3312
3313 /*
3314  * Clear part of the screen
3315  */
3316 void clear_from(int row)
3317 {
3318         int y;
3319
3320         /* Erase requested rows */
3321         for (y = row; y < Term->hgt; y++)
3322         {
3323                 /* Erase part of the screen */
3324                 Term_erase(0, y, 255);
3325         }
3326 }
3327
3328
3329
3330
3331 /*
3332  * Get some string input at the cursor location.
3333  * Assume the buffer is initialized to a default string.
3334  *
3335  * The default buffer is in Overwrite mode and displayed in yellow at
3336  * first.  Normal chars clear the yellow text and append the char in
3337  * white text.
3338  *
3339  * LEFT (^B) and RIGHT (^F) movement keys move the cursor position.
3340  * If the text is still displayed in yellow (Overwite mode), it will
3341  * turns into white (Insert mode) when cursor moves.
3342  *
3343  * DELETE (^D) deletes a char at the cursor position.
3344  * BACKSPACE (^H) deletes a char at the left of cursor position.
3345  * ESCAPE clears the buffer and the window and returns FALSE.
3346  * RETURN accepts the current buffer contents and returns TRUE.
3347  */
3348 bool askfor_aux(char *buf, int len, bool numpad_cursor)
3349 {
3350         int y, x;
3351         int pos = 0;
3352
3353         /*
3354          * Text color
3355          * TERM_YELLOW : Overwrite mode
3356          * TERM_WHITE : Insert mode
3357          */
3358         byte color = TERM_YELLOW;
3359
3360         /* Locate the cursor position */
3361         Term_locate(&x, &y);
3362
3363         /* Paranoia -- check len */
3364         if (len < 1) len = 1;
3365
3366         /* Paranoia -- check column */
3367         if ((x < 0) || (x >= 80)) x = 0;
3368
3369         /* Restrict the length */
3370         if (x + len > 80) len = 80 - x;
3371
3372         /* Paranoia -- Clip the default entry */
3373         buf[len] = '\0';
3374
3375
3376         /* Process input */
3377         while (TRUE)
3378         {
3379                 int skey;
3380
3381                 /* Display the string */
3382                 Term_erase(x, y, len);
3383                 Term_putstr(x, y, -1, color, buf);
3384
3385                 /* Place cursor */
3386                 Term_gotoxy(x + pos, y);
3387
3388                 /* Get a special key code */
3389                 skey = inkey_special(numpad_cursor);
3390
3391                 /* Analyze the key */
3392                 switch (skey)
3393                 {
3394                 case SKEY_LEFT:
3395                 case KTRL('b'):
3396                 {
3397                         int i = 0;
3398
3399                         /* Now on insert mode */
3400                         color = TERM_WHITE;
3401
3402                         /* No move at beginning of line */
3403                         if (0 == pos) break;
3404
3405                         while (TRUE)
3406                         {
3407                                 int next_pos = i + 1;
3408
3409 #ifdef JP
3410                                 if (iskanji(buf[i])) next_pos++;
3411 #endif
3412
3413                                 /* Is there the cursor at next position? */ 
3414                                 if (next_pos >= pos) break;
3415
3416                                 /* Move to next */
3417                                 i = next_pos;
3418                         }
3419
3420                         /* Get previous position */
3421                         pos = i;
3422
3423                         break;
3424                 }
3425
3426                 case SKEY_RIGHT:
3427                 case KTRL('f'):
3428                         /* Now on insert mode */
3429                         color = TERM_WHITE;
3430
3431                         /* No move at end of line */
3432                         if ('\0' == buf[pos]) break;
3433
3434 #ifdef JP
3435                         /* Move right */
3436                         if (iskanji(buf[pos])) pos += 2;
3437                         else pos++;
3438 #else
3439                         pos++;
3440 #endif
3441
3442                         break;
3443
3444                 case ESCAPE:
3445                         /* Cancel input */
3446                         buf[0] = '\0';
3447                         return FALSE;
3448
3449                 case '\n':
3450                 case '\r':
3451                         /* Success */
3452                         return TRUE;
3453
3454                 case '\010':
3455                         /* Backspace */
3456                 {
3457                         int i = 0;
3458
3459                         /* Now on insert mode */
3460                         color = TERM_WHITE;
3461
3462                         /* No move at beginning of line */
3463                         if (0 == pos) break;
3464
3465                         while (TRUE)
3466                         {
3467                                 int next_pos = i + 1;
3468
3469 #ifdef JP
3470                                 if (iskanji(buf[i])) next_pos++;
3471 #endif
3472
3473                                 /* Is there the cursor at next position? */ 
3474                                 if (next_pos >= pos) break;
3475
3476                                 /* Move to next */
3477                                 i = next_pos;
3478                         }
3479
3480                         /* Get previous position */
3481                         pos = i;
3482
3483                         /* Fall through to 'Delete key' */
3484                 }
3485
3486                 case 0x7F:
3487                 case KTRL('d'):
3488                         /* Delete key */
3489                 {
3490                         int dst, src;
3491
3492                         /* Now on insert mode */
3493                         color = TERM_WHITE;
3494
3495                         /* No move at end of line */
3496                         if ('\0' == buf[pos]) break;
3497
3498                         /* Position of next character */
3499                         src = pos + 1;
3500
3501 #ifdef JP
3502                         /* Next character is one more byte away */
3503                         if (iskanji(buf[pos])) src++;
3504 #endif
3505
3506                         dst = pos;
3507
3508                         /* Move characters at src to dst */
3509                         while ('\0' != (buf[dst++] = buf[src++]))
3510                                 /* loop */;
3511
3512                         break;
3513                 }
3514
3515                 default:
3516                 {
3517                         /* Insert a character */
3518
3519                         char tmp[100];
3520                         char c;
3521
3522                         /* Ignore special keys */
3523                         if (skey & SKEY_MASK) break;
3524
3525                         /* Get a character code */
3526                         c = (char)skey;
3527
3528                         if (color == TERM_YELLOW)
3529                         {
3530                                 /* Overwrite default string */
3531                                 buf[0] = '\0';
3532
3533                                 /* Go to insert mode */
3534                                 color = TERM_WHITE;
3535                         }
3536
3537                         /* Save right part of string */
3538                         strcpy(tmp, buf + pos);
3539 #ifdef JP
3540                         if (iskanji(c))
3541                         {
3542                                 char next;
3543
3544                                 /* Bypass macro processing */
3545                                 inkey_base = TRUE;
3546                                 next = inkey();
3547
3548                                 if (pos + 1 < len)
3549                                 {
3550                                         buf[pos++] = c;
3551                                         buf[pos++] = next;
3552                                 }
3553                                 else
3554                                 {
3555                                         bell();
3556                                 }
3557                         }
3558                         else
3559 #endif
3560                         {
3561 #ifdef JP
3562                                 if (pos < len && (isprint(c) || iskana(c)))
3563 #else
3564                                 if (pos < len && isprint(c))
3565 #endif
3566                                 {
3567                                         buf[pos++] = c;
3568                                 }
3569                                 else
3570                                 {
3571                                         bell();
3572                                 }
3573                         }
3574
3575                         /* Terminate */
3576                         buf[pos] = '\0';
3577
3578                         /* Write back the left part of string */
3579                         my_strcat(buf, tmp, len + 1);
3580
3581                         break;
3582                 } /* default: */
3583
3584                 }
3585
3586         } /* while (TRUE) */
3587 }
3588
3589
3590 /*
3591  * Get some string input at the cursor location.
3592  *
3593  * Allow to use numpad keys as cursor keys.
3594  */
3595 bool askfor(char *buf, int len)
3596 {
3597         return askfor_aux(buf, len, TRUE);
3598 }
3599
3600
3601 /*
3602  * Get a string from the user
3603  *
3604  * The "prompt" should take the form "Prompt: "
3605  *
3606  * Note that the initial contents of the string is used as
3607  * the default response, so be sure to "clear" it if needed.
3608  *
3609  * We clear the input, and return FALSE, on "ESCAPE".
3610  */
3611 bool get_string(cptr prompt, char *buf, int len)
3612 {
3613         bool res;
3614
3615         /* Paranoia */
3616         msg_print(NULL);
3617
3618         /* Display prompt */
3619         prt(prompt, 0, 0);
3620
3621         /* Ask the user for a string */
3622         res = askfor(buf, len);
3623
3624         /* Clear prompt */
3625         prt("", 0, 0);
3626
3627         /* Result */
3628         return (res);
3629 }
3630
3631
3632 /*
3633  * Verify something with the user
3634  *
3635  * The "prompt" should take the form "Query? "
3636  *
3637  * Note that "[y/n]" is appended to the prompt.
3638  */
3639 bool get_check(cptr prompt)
3640 {
3641         return get_check_strict(prompt, 0);
3642 }
3643
3644 /*
3645  * Verify something with the user strictly
3646  *
3647  * mode & CHECK_OKAY_CANCEL : force user to answer 'O'kay or 'C'ancel
3648  * mode & CHECK_NO_ESCAPE   : don't allow ESCAPE key
3649  * mode & CHECK_NO_HISTORY  : no message_add
3650  * mode & CHECK_DEFAULT_Y   : accept any key as y, except n and Esc.
3651  */
3652 bool get_check_strict(cptr prompt, BIT_FLAGS mode)
3653 {
3654         int i;
3655         char buf[80];
3656         bool flag = FALSE;
3657
3658         if (auto_more)
3659         {
3660                 p_ptr->window |= PW_MESSAGE;
3661                 window_stuff();
3662                 num_more = 0;
3663         }
3664
3665         /* Paranoia */
3666         msg_print(NULL);
3667
3668         if (!rogue_like_commands)
3669                 mode &= ~CHECK_OKAY_CANCEL;
3670
3671
3672         /* Hack -- Build a "useful" prompt */
3673         if (mode & CHECK_OKAY_CANCEL)
3674         {
3675                 my_strcpy(buf, prompt, sizeof(buf)-15);
3676                 strcat(buf, "[(O)k/(C)ancel]");
3677         }
3678         else if (mode & CHECK_DEFAULT_Y)
3679         {
3680                 my_strcpy(buf, prompt, sizeof(buf)-5);
3681                 strcat(buf, "[Y/n]");
3682         }
3683         else
3684         {
3685                 my_strcpy(buf, prompt, sizeof(buf)-5);
3686                 strcat(buf, "[y/n]");
3687         }
3688
3689         /* Prompt for it */
3690         prt(buf, 0, 0);
3691
3692         if (!(mode & CHECK_NO_HISTORY) && p_ptr->playing)
3693         {
3694                 /* HACK : Add the line to message buffer */
3695                 message_add(buf);
3696                 p_ptr->window |= (PW_MESSAGE);
3697                 window_stuff();
3698         }
3699
3700         /* Get an acceptable answer */
3701         while (TRUE)
3702         {
3703                 i = inkey();
3704
3705                 if (!(mode & CHECK_NO_ESCAPE))
3706                 {
3707                         if (i == ESCAPE)
3708                         {
3709                                 flag = FALSE;
3710                                 break;
3711                         }
3712                 }
3713
3714                 if (mode & CHECK_OKAY_CANCEL)
3715                 {
3716                         if (i == 'o' || i == 'O')
3717                         {
3718                                 flag = TRUE;
3719                                 break;
3720                         }
3721                         else if (i == 'c' || i == 'C')
3722                         {
3723                                 flag = FALSE;
3724                                 break;
3725                         }
3726                 }
3727                 else
3728                 {
3729                         if (i == 'y' || i == 'Y')
3730                         {
3731                                 flag = TRUE;
3732                                 break;
3733                         }
3734                         else if (i == 'n' || i == 'N')
3735                         {
3736                                 flag = FALSE;
3737                                 break;
3738                         }
3739                 }
3740
3741                 if (mode & CHECK_DEFAULT_Y)
3742                 {
3743                         flag = TRUE;
3744                         break;
3745                 }
3746
3747                 bell();
3748         }
3749
3750         /* Erase the prompt */
3751         prt("", 0, 0);
3752
3753         /* Return the flag */
3754         return flag;
3755 }
3756
3757
3758 /*
3759  * Prompts for a keypress
3760  *
3761  * The "prompt" should take the form "Command: "
3762  *
3763  * Returns TRUE unless the character is "Escape"
3764  */
3765 bool get_com(cptr prompt, char *command, bool z_escape)
3766 {
3767         /* Paranoia */
3768         msg_print(NULL);
3769
3770         /* Display a prompt */
3771         prt(prompt, 0, 0);
3772
3773         /* Get a key */
3774         if (get_com_no_macros)
3775                 *command = inkey_special(FALSE);
3776         else
3777                 *command = inkey();
3778
3779         /* Clear the prompt */
3780         prt("", 0, 0);
3781
3782         /* Handle "cancel" */
3783         if (*command == ESCAPE) return (FALSE);
3784         if (z_escape && ((*command == 'z') || (*command == 'Z'))) return (FALSE);
3785
3786         /* Success */
3787         return (TRUE);
3788 }
3789
3790
3791 /*
3792  * Request a "quantity" from the user
3793  *
3794  * Hack -- allow "command_arg" to specify a quantity
3795  */
3796 QUANTITY get_quantity(cptr prompt, QUANTITY max)
3797 {
3798         bool res, result;
3799         QUANTITY amt;
3800         char tmp[80];
3801         char buf[80];
3802         COMMAND_CODE code;
3803
3804
3805         /* Use "command_arg" */
3806         if (command_arg)
3807         {
3808                 /* Extract a number */
3809                 amt = command_arg;
3810
3811                 /* Clear "command_arg" */
3812                 command_arg = 0;
3813
3814                 /* Enforce the maximum */
3815                 if (amt > max) amt = max;
3816
3817                 /* Use it */
3818                 return (amt);
3819         }
3820
3821 #ifdef ALLOW_REPEAT /* TNB */
3822
3823         /* Get the item index */
3824         result = repeat_pull(&code);
3825         amt = (QUANTITY)code;
3826         if ((max != 1) && result)
3827         {
3828                 /* Enforce the maximum */
3829                 if (amt > max) amt = max;
3830
3831                 /* Enforce the minimum */
3832                 if (amt < 0) amt = 0;
3833
3834                 /* Use it */
3835                 return (amt);
3836         }
3837
3838 #endif /* ALLOW_REPEAT -- TNB */
3839
3840         /* Build a prompt if needed */
3841         if (!prompt)
3842         {
3843                 /* Build a prompt */
3844                 sprintf(tmp, _("いくつですか (1-%d): ", "Quantity (1-%d): "), max);
3845
3846                 /* Use that prompt */
3847                 prompt = tmp;
3848         }
3849
3850         /* Paranoia */
3851         msg_print(NULL);
3852
3853         /* Display prompt */
3854         prt(prompt, 0, 0);
3855
3856         /* Default to one */
3857         amt = 1;
3858
3859         /* Build the default */
3860         sprintf(buf, "%d", amt);
3861
3862         /*
3863          * Ask for a quantity
3864          * Don't allow to use numpad as cursor key.
3865          */
3866         res = askfor_aux(buf, 6, FALSE);
3867
3868         /* Clear prompt */
3869         prt("", 0, 0);
3870
3871         /* Cancelled */
3872         if (!res) return 0;
3873
3874         /* Extract a number */
3875         amt = (COMMAND_CODE)atoi(buf);
3876
3877         /* A letter means "all" */
3878         if (isalpha(buf[0])) amt = max;
3879
3880         /* Enforce the maximum */
3881         if (amt > max) amt = max;
3882
3883         /* Enforce the minimum */
3884         if (amt < 0) amt = 0;
3885
3886 #ifdef ALLOW_REPEAT /* TNB */
3887
3888         if (amt) repeat_push((COMMAND_CODE)amt);
3889
3890 #endif /* ALLOW_REPEAT -- TNB */
3891
3892         /* Return the result */
3893         return (amt);
3894 }
3895
3896
3897 /*
3898  * Pause for user response 
3899  */
3900 void pause_line(int row)
3901 {
3902         prt("", row, 0);
3903         put_str(_("[ 何かキーを押して下さい ]", "[Press any key to continue]"), row, _(26, 23));
3904
3905         (void)inkey();
3906         prt("", row, 0);
3907 }
3908
3909
3910 /*
3911  * Hack -- special buffer to hold the action of the current keymap
3912  */
3913 static char request_command_buffer[256];
3914
3915
3916
3917 typedef struct
3918 {
3919         cptr name;
3920         byte cmd;
3921         bool fin;
3922 } menu_naiyou;
3923
3924 #ifdef JP
3925 menu_naiyou menu_info[10][10] =
3926 {
3927         {
3928                 {"魔法/特殊能力", 1, FALSE},
3929                 {"行動", 2, FALSE},
3930                 {"道具(使用)", 3, FALSE},
3931                 {"道具(その他)", 4, FALSE},
3932                 {"装備", 5, FALSE},
3933                 {"扉/箱", 6, FALSE},
3934                 {"情報", 7, FALSE},
3935                 {"設定", 8, FALSE},
3936                 {"その他", 9, FALSE},
3937                 {"", 0, FALSE},
3938         },
3939
3940         {
3941                 {"使う(m)", 'm', TRUE},
3942                 {"調べる(b/P)", 'b', TRUE},
3943                 {"覚える(G)", 'G', TRUE},
3944                 {"特殊能力を使う(U/O)", 'U', TRUE},
3945                 {"", 0, FALSE},
3946                 {"", 0, FALSE},
3947                 {"", 0, FALSE},
3948                 {"", 0, FALSE},
3949                 {"", 0, FALSE},
3950                 {"", 0, FALSE}
3951         },
3952
3953         {
3954                 {"休息する(R)", 'R', TRUE},
3955                 {"トラップ解除(D)", 'D', TRUE},
3956                 {"探す(s)", 's', TRUE},
3957                 {"周りを調べる(l/x)", 'l', TRUE},
3958                 {"ターゲット指定(*)", '*', TRUE},
3959                 {"穴を掘る(T/^t)", 'T', TRUE},
3960                 {"階段を上る(<)", '<', TRUE},
3961                 {"階段を下りる(>)", '>', TRUE},
3962                 {"ペットに命令する(p)", 'p', TRUE},
3963                 {"探索モードのON/OFF(S/#)", 'S', TRUE}
3964         },
3965
3966         {
3967                 {"読む(r)", 'r', TRUE},
3968                 {"飲む(q)", 'q', TRUE},
3969                 {"杖を使う(u/Z)", 'u', TRUE},
3970                 {"魔法棒で狙う(a/z)", 'a', TRUE},
3971                 {"ロッドを振る(z/a)", 'z', TRUE},
3972                 {"始動する(A)", 'A', TRUE},
3973                 {"食べる(E)", 'E', TRUE},
3974                 {"飛び道具で撃つ(f/t)", 'f', TRUE},
3975                 {"投げる(v)", 'v', TRUE},
3976                 {"", 0, FALSE}
3977         },
3978
3979         {
3980                 {"拾う(g)", 'g', TRUE},
3981                 {"落とす(d)", 'd', TRUE},
3982                 {"壊す(k/^d)", 'k', TRUE},
3983                 {"銘を刻む({)", '{', TRUE},
3984                 {"銘を消す(})", '}', TRUE},
3985                 {"調査(I)", 'I', TRUE},
3986                 {"アイテム一覧(i)", 'i', TRUE},
3987                 {"", 0, FALSE},
3988                 {"", 0, FALSE},
3989                 {"", 0, FALSE}
3990         },
3991
3992         {
3993                 {"装備する(w)", 'w', TRUE},
3994                 {"装備を外す(t/T)", 't', TRUE},
3995                 {"燃料を補給(F)", 'F', TRUE},
3996                 {"装備一覧(e)", 'e', TRUE},
3997                 {"", 0, FALSE},
3998                 {"", 0, FALSE},
3999                 {"", 0, FALSE},
4000                 {"", 0, FALSE},
4001                 {"", 0, FALSE},
4002                 {"", 0, FALSE}
4003         },
4004
4005         {
4006                 {"開ける(o)", 'o', TRUE},
4007                 {"閉じる(c)", 'c', TRUE},
4008                 {"体当たりする(B/f)", 'B', TRUE},
4009                 {"くさびを打つ(j/S)", 'j', TRUE},
4010                 {"", 0, FALSE},
4011                 {"", 0, FALSE},
4012                 {"", 0, FALSE},
4013                 {"", 0, FALSE},
4014                 {"", 0, FALSE},
4015                 {"", 0, FALSE}
4016         },
4017
4018         {
4019                 {"ダンジョンの全体図(M)", 'M', TRUE},
4020                 {"位置を確認(L/W)", 'L', TRUE},
4021                 {"階の雰囲気(^f)", KTRL('F'), TRUE},
4022                 {"ステータス(C)", 'C', TRUE},
4023                 {"文字の説明(/)", '/', TRUE},
4024                 {"メッセージ履歴(^p)", KTRL('P'), TRUE},
4025                 {"現在の時刻(^t/')", KTRL('T'), TRUE},
4026                 {"現在の知識(~)", '~', TRUE},
4027                 {"プレイ記録(|)", '|', TRUE},
4028                 {"", 0, FALSE}
4029         },
4030
4031         {
4032                 {"オプション(=)", '=', TRUE},
4033                 {"マクロ(@)", '@', TRUE},
4034                 {"画面表示(%)", '%', TRUE},
4035                 {"カラー(&)", '&', TRUE},
4036                 {"設定変更コマンド(\")", '\"', TRUE},
4037                 {"自動拾いをロード($)", '$', TRUE},
4038                 {"システム(!)", '!', TRUE},
4039                 {"", 0, FALSE},
4040                 {"", 0, FALSE},
4041                 {"", 0, FALSE}
4042         },
4043
4044         {
4045                 {"セーブ&中断(^x)", KTRL('X'), TRUE},
4046                 {"セーブ(^s)", KTRL('S'), TRUE},
4047                 {"ヘルプ(?)", '?', TRUE},
4048                 {"再描画(^r)", KTRL('R'), TRUE},
4049                 {"メモ(:)", ':', TRUE},
4050                 {"記念撮影())", ')', TRUE},
4051                 {"記念撮影の表示(()", '(', TRUE},
4052                 {"バージョン情報(V)", 'V', TRUE},
4053                 {"引退する(Q)", 'Q', TRUE},
4054                 {"", 0, FALSE}
4055         },
4056 };
4057 #else
4058 menu_naiyou menu_info[10][10] =
4059 {
4060         {
4061                 {"Magic/Special", 1, FALSE},
4062                 {"Action", 2, FALSE},
4063                 {"Items(use)", 3, FALSE},
4064                 {"Items(other)", 4, FALSE},
4065                 {"Equip", 5, FALSE},
4066                 {"Door/Box", 6, FALSE},
4067                 {"Informations", 7, FALSE},
4068                 {"Options", 8, FALSE},
4069                 {"Other commands", 9, FALSE},
4070                 {"", 0, FALSE},
4071         },
4072
4073         {
4074                 {"Use(m)", 'm', TRUE},
4075                 {"See tips(b/P)", 'b', TRUE},
4076                 {"Study(G)", 'G', TRUE},
4077                 {"Special abilities(U/O)", 'U', TRUE},
4078                 {"", 0, FALSE},
4079                 {"", 0, FALSE},
4080                 {"", 0, FALSE},
4081                 {"", 0, FALSE},
4082                 {"", 0, FALSE},
4083                 {"", 0, FALSE}
4084         },
4085
4086         {
4087                 {"Rest(R)", 'R', TRUE},
4088                 {"Disarm a trap(D)", 'D', TRUE},
4089                 {"Search(s)", 's', TRUE},
4090                 {"Look(l/x)", 'l', TRUE},
4091                 {"Target(*)", '*', TRUE},
4092                 {"Dig(T/^t)", 'T', TRUE},
4093                 {"Go up stairs(<)", '<', TRUE},
4094                 {"Go down stairs(>)", '>', TRUE},
4095                 {"Command pets(p)", 'p', TRUE},
4096                 {"Search mode ON/OFF(S/#)", 'S', TRUE}
4097         },
4098
4099         {
4100                 {"Read a scroll(r)", 'r', TRUE},
4101                 {"Drink a potion(q)", 'q', TRUE},
4102                 {"Use a staff(u/Z)", 'u', TRUE},
4103                 {"Aim a wand(a/z)", 'a', TRUE},
4104                 {"Zap a rod(z/a)", 'z', TRUE},
4105                 {"Activate an equipment(A)", 'A', TRUE},
4106                 {"Eat(E)", 'E', TRUE},
4107                 {"Fire missile weapon(f/t)", 'f', TRUE},
4108                 {"Throw an item(v)", 'v', TRUE},
4109                 {"", 0, FALSE}
4110         },
4111
4112         {
4113                 {"Get items(g)", 'g', TRUE},
4114                 {"Drop an item(d)", 'd', TRUE},
4115                 {"Destroy an item(k/^d)", 'k', TRUE},
4116                 {"Inscribe an item({)", '{', TRUE},
4117                 {"Uninscribe an item(})", '}', TRUE},
4118                 {"Info about an item(I)", 'I', TRUE},
4119                 {"Inventory list(i)", 'i', TRUE},
4120                 {"", 0, FALSE},
4121                 {"", 0, FALSE},
4122                 {"", 0, FALSE}
4123         },
4124
4125         {
4126                 {"Wear(w)", 'w', TRUE},
4127                 {"Take off(t/T)", 't', TRUE},
4128                 {"Refuel(F)", 'F', TRUE},
4129                 {"Equipment list(e)", 'e', TRUE},
4130                 {"", 0, FALSE},
4131                 {"", 0, FALSE},
4132                 {"", 0, FALSE},
4133                 {"", 0, FALSE},
4134                 {"", 0, FALSE},
4135                 {"", 0, FALSE}
4136         },
4137
4138         {
4139                 {"Open(o)", 'o', TRUE},
4140                 {"Close(c)", 'c', TRUE},
4141                 {"Bash a door(B/f)", 'B', TRUE},
4142                 {"Jam a door(j/S)", 'j', TRUE},
4143                 {"", 0, FALSE},
4144                 {"", 0, FALSE},
4145                 {"", 0, FALSE},
4146                 {"", 0, FALSE},
4147                 {"", 0, FALSE},
4148                 {"", 0, FALSE}
4149         },
4150
4151         {
4152                 {"Full map(M)", 'M', TRUE},
4153                 {"Map(L/W)", 'L', TRUE},
4154                 {"Level feeling(^f)", KTRL('F'), TRUE},
4155                 {"Character status(C)", 'C', TRUE},
4156                 {"Identify symbol(/)", '/', TRUE},
4157                 {"Show prev messages(^p)", KTRL('P'), TRUE},
4158                 {"Current time(^t/')", KTRL('T'), TRUE},
4159                 {"Various informations(~)", '~', TRUE},
4160                 {"Play record menu(|)", '|', TRUE},
4161                 {"", 0, FALSE}
4162         },
4163
4164         {
4165                 {"Set options(=)", '=', TRUE},
4166                 {"Interact with macros(@)", '@', TRUE},
4167                 {"Interact w/ visuals(%)", '%', TRUE},
4168                 {"Interact with colors(&)", '&', TRUE},
4169                 {"Enter a user pref(\")", '\"', TRUE},
4170                 {"Reload auto-pick pref($)", '$', TRUE},
4171                 {"", 0, FALSE},
4172                 {"", 0, FALSE},
4173                 {"", 0, FALSE},
4174                 {"", 0, FALSE}
4175         },
4176
4177         {
4178                 {"Save and quit(^x)", KTRL('X'), TRUE},
4179                 {"Save(^s)", KTRL('S'), TRUE},
4180                 {"Help(obsoleted)(?)", '?', TRUE},
4181                 {"Redraw(^r)", KTRL('R'), TRUE},
4182                 {"Take note(:)", ':', TRUE},
4183                 {"Dump screen dump(()", ')', TRUE},
4184                 {"Load screen dump())", '(', TRUE},
4185                 {"Version info(V)", 'V', TRUE},
4186                 {"Quit(Q)", 'Q', TRUE},
4187                 {"", 0, FALSE}
4188         },
4189 };
4190 #endif
4191
4192 typedef struct
4193 {
4194         cptr name;
4195         byte window;
4196         byte number;
4197         byte jouken;
4198         byte jouken_naiyou;
4199 } special_menu_naiyou;
4200
4201 #define MENU_CLASS 1
4202 #define MENU_WILD 2
4203
4204 #ifdef JP
4205 special_menu_naiyou special_menu_info[] =
4206 {
4207         {"超能力/特殊能力", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
4208         {"ものまね/特殊能力", 0, 0, MENU_CLASS, CLASS_IMITATOR},
4209         {"歌/特殊能力", 0, 0, MENU_CLASS, CLASS_BARD},
4210         {"必殺技/特殊能力", 0, 0, MENU_CLASS, CLASS_SAMURAI},
4211         {"練気術/魔法/特殊能力", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
4212         {"技/特殊能力", 0, 0, MENU_CLASS, CLASS_BERSERKER},
4213         {"技術/特殊能力", 0, 0, MENU_CLASS, CLASS_SMITH},
4214         {"鏡魔法/特殊能力", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
4215         {"忍術/特殊能力", 0, 0, MENU_CLASS, CLASS_NINJA},
4216         {"広域マップ(<)", 2, 6, MENU_WILD, FALSE},
4217         {"通常マップ(>)", 2, 7, MENU_WILD, TRUE},
4218         {"", 0, 0, 0, 0},
4219 };
4220 #else
4221 special_menu_naiyou special_menu_info[] =
4222 {
4223         {"MindCraft/Special", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
4224         {"Imitation/Special", 0, 0, MENU_CLASS, CLASS_IMITATOR},
4225         {"Song/Special", 0, 0, MENU_CLASS, CLASS_BARD},
4226         {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SAMURAI},
4227         {"Mind/Magic/Special", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
4228         {"BrutalPower/Special", 0, 0, MENU_CLASS, CLASS_BERSERKER},
4229         {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SMITH},
4230         {"MirrorMagic/Special", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
4231         {"Ninjutsu/Special", 0, 0, MENU_CLASS, CLASS_NINJA},
4232         {"Enter global map(<)", 2, 6, MENU_WILD, FALSE},
4233         {"Enter local map(>)", 2, 7, MENU_WILD, TRUE},
4234         {"", 0, 0, 0, 0},
4235 };
4236 #endif
4237
4238 static char inkey_from_menu(void)
4239 {
4240         char cmd;
4241         int basey, basex;
4242         int num = 0, max_num, old_num = 0;
4243         int menu = 0;
4244         bool kisuu;
4245
4246         if (p_ptr->y - panel_row_min > 10) basey = 2;
4247         else basey = 13;
4248         basex = 15;
4249
4250         /* Clear top line */
4251         prt("", 0, 0);
4252
4253         screen_save();
4254
4255         while(1)
4256         {
4257                 int i;
4258                 char sub_cmd;
4259                 cptr menu_name;
4260                 if (!menu) old_num = num;
4261                 put_str("+----------------------------------------------------+", basey, basex);
4262                 put_str("|                                                    |", basey+1, basex);
4263                 put_str("|                                                    |", basey+2, basex);
4264                 put_str("|                                                    |", basey+3, basex);
4265                 put_str("|                                                    |", basey+4, basex);
4266                 put_str("|                                                    |", basey+5, basex);
4267                 put_str("+----------------------------------------------------+", basey+6, basex);
4268
4269                 for(i = 0; i < 10; i++)
4270                 {
4271                         int hoge;
4272                         if (!menu_info[menu][i].cmd) break;
4273                         menu_name = menu_info[menu][i].name;
4274                         for(hoge = 0; ; hoge++)
4275                         {
4276                                 if (!special_menu_info[hoge].name[0]) break;
4277                                 if ((menu != special_menu_info[hoge].window) || (i != special_menu_info[hoge].number)) continue;
4278                                 switch(special_menu_info[hoge].jouken)
4279                                 {
4280                                 case MENU_CLASS:
4281                                         if (p_ptr->pclass == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
4282                                         break;
4283                                 case MENU_WILD:
4284                                         if (!dun_level && !p_ptr->inside_arena && !p_ptr->inside_quest)
4285                                         {
4286                                                 if ((byte)p_ptr->wild_mode == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
4287                                         }
4288                                         break;
4289                                 default:
4290                                         break;
4291                                 }
4292                         }
4293                         put_str(menu_name, basey + 1 + i / 2, basex + 4 + (i % 2) * 24);
4294                 }
4295                 max_num = i;
4296                 kisuu = max_num % 2;
4297                 put_str(_("》", "> "),basey + 1 + num / 2, basex + 2 + (num % 2) * 24);
4298
4299                 /* Place the cursor on the player */
4300                 move_cursor_relative(p_ptr->y, p_ptr->x);
4301
4302                 /* Get a command */
4303                 sub_cmd = inkey();
4304                 if ((sub_cmd == ' ') || (sub_cmd == 'x') || (sub_cmd == 'X') || (sub_cmd == '\r') || (sub_cmd == '\n'))
4305                 {
4306                         if (menu_info[menu][num].fin)
4307                         {
4308                                 cmd = menu_info[menu][num].cmd;
4309                                 use_menu = TRUE;
4310                                 break;
4311                         }
4312                         else
4313                         {
4314                                 menu = menu_info[menu][num].cmd;
4315                                 num = 0;
4316                                 basey += 2;
4317                                 basex += 8;
4318                         }
4319                 }
4320                 else if ((sub_cmd == ESCAPE) || (sub_cmd == 'z') || (sub_cmd == 'Z') || (sub_cmd == '0'))
4321                 {
4322                         if (!menu)
4323                         {
4324                                 cmd = ESCAPE;
4325                                 break;
4326                         }
4327                         else
4328                         {
4329                                 menu = 0;
4330                                 num = old_num;
4331                                 basey -= 2;
4332                                 basex -= 8;
4333                                 screen_load();
4334                                 screen_save();
4335                         }
4336                 }
4337                 else if ((sub_cmd == '2') || (sub_cmd == 'j') || (sub_cmd == 'J'))
4338                 {
4339                         if (kisuu)
4340                         {
4341                                 if (num % 2)
4342                                         num = (num + 2) % (max_num - 1);
4343                                 else
4344                                         num = (num + 2) % (max_num + 1);
4345                         }
4346                         else num = (num + 2) % max_num;
4347                 }
4348                 else if ((sub_cmd == '8') || (sub_cmd == 'k') || (sub_cmd == 'K'))
4349                 {
4350                         if (kisuu)
4351                         {
4352                                 if (num % 2)
4353                                         num = (num + max_num - 3) % (max_num - 1);
4354                                 else
4355                                         num = (num + max_num - 1) % (max_num + 1);
4356                         }
4357                         else num = (num + max_num - 2) % max_num;
4358                 }
4359                 else if ((sub_cmd == '4') || (sub_cmd == '6') || (sub_cmd == 'h') || (sub_cmd == 'H') || (sub_cmd == 'l') || (sub_cmd == 'L'))
4360                 {
4361                         if ((num % 2) || (num == max_num - 1))
4362                         {
4363                                 num--;
4364                         }
4365                         else if (num < max_num - 1)
4366                         {
4367                                 num++;
4368                         }
4369                 }
4370         }
4371
4372         screen_load();
4373         if (!inkey_next) inkey_next = "";
4374
4375         return (cmd);
4376 }
4377
4378 /*
4379  * Request a command from the user.
4380  *
4381  * Sets p_ptr->command_cmd, p_ptr->command_dir, p_ptr->command_rep,
4382  * p_ptr->command_arg.  May modify p_ptr->command_new.
4383  *
4384  * Note that "caret" ("^") is treated specially, and is used to
4385  * allow manual input of control characters.  This can be used
4386  * on many machines to request repeated tunneling (Ctrl-H) and
4387  * on the Macintosh to request "Control-Caret".
4388  *
4389  * Note that "backslash" is treated specially, and is used to bypass any
4390  * keymap entry for the following character.  This is useful for macros.
4391  *
4392  * Note that this command is used both in the dungeon and in
4393  * stores, and must be careful to work in both situations.
4394  *
4395  * Note that "p_ptr->command_new" may not work any more.  
4396  */
4397 void request_command(int shopping)
4398 {
4399         int i;
4400
4401         s16b cmd;
4402         int mode;
4403
4404         cptr act;
4405
4406 #ifdef JP
4407         int caretcmd = 0;
4408 #endif
4409         /* Roguelike */
4410         if (rogue_like_commands)
4411         {
4412                 mode = KEYMAP_MODE_ROGUE;
4413         }
4414
4415         /* Original */
4416         else
4417         {
4418                 mode = KEYMAP_MODE_ORIG;
4419         }
4420
4421
4422         /* No command yet */
4423         command_cmd = 0;
4424
4425         /* No "argument" yet */
4426         command_arg = 0;
4427
4428         /* No "direction" yet */
4429         command_dir = 0;
4430
4431         use_menu = FALSE;
4432
4433
4434         /* Get command */
4435         while (1)
4436         {
4437                 /* Hack -- auto-commands */
4438                 if (command_new)
4439                 {
4440                         /* Flush messages */
4441                         msg_print(NULL);
4442
4443                         /* Use auto-command */
4444                         cmd = command_new;
4445
4446                         /* Forget it */
4447                         command_new = 0;
4448                 }
4449
4450                 /* Get a keypress in "command" mode */
4451                 else
4452                 {
4453                         /* Hack -- no flush needed */
4454                         msg_flag = FALSE;
4455                         num_more = 0;
4456
4457                         /* Activate "command mode" */
4458                         inkey_flag = TRUE;
4459
4460                         /* Get a command */
4461                         cmd = inkey();
4462
4463                         if (!shopping && command_menu && ((cmd == '\r') || (cmd == '\n') || (cmd == 'x') || (cmd == 'X'))
4464                             && !keymap_act[mode][(byte)(cmd)])
4465                                 cmd = inkey_from_menu();
4466                 }
4467
4468                 /* Clear top line */
4469                 prt("", 0, 0);
4470
4471
4472                 /* Command Count */
4473                 if (cmd == '0')
4474                 {
4475                         COMMAND_ARG old_arg = command_arg;
4476
4477                         /* Reset */
4478                         command_arg = 0;
4479
4480                         /* Begin the input */
4481                         prt(_("回数: ", "Count: "), 0, 0);
4482
4483                         /* Get a command count */
4484                         while (1)
4485                         {
4486                                 /* Get a new keypress */
4487                                 cmd = inkey();
4488
4489                                 /* Simple editing (delete or backspace) */
4490                                 if ((cmd == 0x7F) || (cmd == KTRL('H')))
4491                                 {
4492                                         /* Delete a digit */
4493                                         command_arg = command_arg / 10;
4494
4495                                         /* Show current count */
4496                                         prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
4497                                 }
4498
4499                                 /* Actual numeric data */
4500                                 else if (cmd >= '0' && cmd <= '9')
4501                                 {
4502                                         /* Stop count at 9999 */
4503                                         if (command_arg >= 1000)
4504                                         {
4505                                                 /* Warn */
4506                                                 bell();
4507
4508                                                 /* Limit */
4509                                                 command_arg = 9999;
4510                                         }
4511
4512                                         /* Increase count */
4513                                         else
4514                                         {
4515                                                 /* Incorporate that digit */
4516                                                 command_arg = command_arg * 10 + D2I(cmd);
4517                                         }
4518
4519                                         /* Show current count */
4520                                         prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
4521                                 }
4522
4523                                 /* Exit on "unusable" input */
4524                                 else
4525                                 {
4526                                         break;
4527                                 }
4528                         }
4529
4530                         /* Hack -- Handle "zero" */
4531                         if (command_arg == 0)
4532                         {
4533                                 /* Default to 99 */
4534                                 command_arg = 99;
4535
4536                                 /* Show current count */
4537                                 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
4538                         }
4539
4540                         /* Hack -- Handle "old_arg" */
4541                         if (old_arg != 0)
4542                         {
4543                                 /* Restore old_arg */
4544                                 command_arg = old_arg;
4545
4546                                 /* Show current count */
4547                                 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
4548                         }
4549
4550                         /* Hack -- white-space means "enter command now" */
4551                         if ((cmd == ' ') || (cmd == '\n') || (cmd == '\r'))
4552                         {
4553                                 /* Get a real command */
4554                                 if (!get_com(_("コマンド: ", "Command: "), (char *)&cmd, FALSE))
4555                                 {
4556                                         /* Clear count */
4557                                         command_arg = 0;
4558
4559                                         /* Continue */
4560                                         continue;
4561                                 }
4562                         }
4563                 }
4564
4565
4566                 /* Allow "keymaps" to be bypassed */
4567                 if (cmd == '\\')
4568                 {
4569                         /* Get a real command */
4570                         (void)get_com(_("コマンド: ", "Command: "), (char *)&cmd, FALSE);
4571
4572                         /* Hack -- bypass keymaps */
4573                         if (!inkey_next) inkey_next = "";
4574                 }
4575
4576
4577                 /* Allow "control chars" to be entered */
4578                 if (cmd == '^')
4579                 {
4580                         /* Get a new command and controlify it */
4581                         if (get_com(_("CTRL: ", "Control: "), (char *)&cmd, FALSE)) cmd = KTRL(cmd);
4582                 }
4583
4584
4585                 /* Look up applicable keymap */
4586                 act = keymap_act[mode][(byte)(cmd)];
4587
4588                 /* Apply keymap if not inside a keymap already */
4589                 if (act && !inkey_next)
4590                 {
4591                         /* Install the keymap (limited buffer size) */
4592                         (void)strnfmt(request_command_buffer, 256, "%s", act);
4593
4594                         /* Start using the buffer */
4595                         inkey_next = request_command_buffer;
4596
4597                         /* Continue */
4598                         continue;
4599                 }
4600
4601
4602                 /* Paranoia */
4603                 if (!cmd) continue;
4604
4605
4606                 /* Use command */
4607                 command_cmd = (byte)cmd;
4608
4609                 break;
4610         }
4611
4612         /* Hack -- Auto-repeat certain commands */
4613         if (always_repeat && (command_arg <= 0))
4614         {
4615                 /* Hack -- auto repeat certain commands */
4616                 if (my_strchr("TBDoc+", (char)command_cmd))
4617                 {
4618                         /* Repeat 99 times */
4619                         command_arg = 99;
4620                 }
4621         }
4622
4623         /* Shopping */
4624         if (shopping == 1)
4625         {
4626                 /* Convert */
4627                 switch (command_cmd)
4628                 {
4629                         /* Command "p" -> "purchase" (get) */
4630                 case 'p': command_cmd = 'g'; break;
4631
4632                         /* Command "m" -> "purchase" (get) */
4633                 case 'm': command_cmd = 'g'; break;
4634
4635                         /* Command "s" -> "sell" (drop) */
4636                 case 's': command_cmd = 'd'; break;
4637                 }
4638         }
4639
4640 #ifdef JP
4641         for (i = 0; i < 256; i++)
4642         {
4643                 cptr s;
4644                 if ((s = keymap_act[mode][i]) != NULL)
4645                 {
4646                         if (*s == command_cmd && *(s+1) == 0)
4647                         {
4648                                 caretcmd = i;
4649                                 break;
4650                         }
4651                 }
4652         }
4653         if (!caretcmd)
4654                 caretcmd = command_cmd;
4655 #endif
4656
4657         /* Hack -- Scan equipment */
4658         for (i = INVEN_RARM; i < INVEN_TOTAL; i++)
4659         {
4660                 cptr s;
4661
4662                 object_type *o_ptr = &inventory[i];
4663
4664                 /* Skip non-objects */
4665                 if (!o_ptr->k_idx) continue;
4666
4667                 /* No inscription */
4668                 if (!o_ptr->inscription) continue;
4669
4670                 /* Obtain the inscription */
4671                 s = quark_str(o_ptr->inscription);
4672
4673                 /* Find a '^' */
4674                 s = my_strchr(s, '^');
4675
4676                 /* Process preventions */
4677                 while (s)
4678                 {
4679                         /* Check the "restriction" character */
4680 #ifdef JP
4681                         if ((s[1] == caretcmd) || (s[1] == '*'))
4682 #else
4683                         if ((s[1] == command_cmd) || (s[1] == '*'))
4684 #endif
4685
4686                         {
4687                                 /* Hack -- Verify command */
4688                                 if (!get_check(_("本当ですか? ", "Are you sure? ")))
4689                                 {
4690                                         /* Hack -- Use space */
4691                                         command_cmd = ' ';
4692                                 }
4693                         }
4694
4695                         /* Find another '^' */
4696                         s = my_strchr(s + 1, '^');
4697                 }
4698         }
4699
4700
4701         /* Hack -- erase the message line. */
4702         prt("", 0, 0);
4703 }
4704
4705
4706
4707 /*
4708  * Check a char for "vowel-hood"
4709  */
4710 bool is_a_vowel(int ch)
4711 {
4712         switch (ch)
4713         {
4714         case 'a':
4715         case 'e':
4716         case 'i':
4717         case 'o':
4718         case 'u':
4719         case 'A':
4720         case 'E':
4721         case 'I':
4722         case 'O':
4723         case 'U':
4724                 return (TRUE);
4725         }
4726
4727         return (FALSE);
4728 }
4729
4730
4731
4732 #if 0
4733
4734 /*
4735  * Replace the first instance of "target" in "buf" with "insert"
4736  * If "insert" is NULL, just remove the first instance of "target"
4737  * In either case, return TRUE if "target" is found.
4738  *
4739  * XXX Could be made more efficient, especially in the
4740  * case where "insert" is smaller than "target".
4741  */
4742 static bool insert_str(char *buf, cptr target, cptr insert)
4743 {
4744         int   i, len;
4745         int                b_len, t_len, i_len;
4746
4747         /* Attempt to find the target (modify "buf") */
4748         buf = my_strstr(buf, target);
4749
4750         /* No target found */
4751         if (!buf) return (FALSE);
4752
4753         /* Be sure we have an insertion string */
4754         if (!insert) insert = "";
4755
4756         /* Extract some lengths */
4757         t_len = strlen(target);
4758         i_len = strlen(insert);
4759         b_len = strlen(buf);
4760
4761         /* How much "movement" do we need? */
4762         len = i_len - t_len;
4763
4764         /* We need less space (for insert) */
4765         if (len < 0)
4766         {
4767                 for (i = t_len; i < b_len; ++i) buf[i+len] = buf[i];
4768         }
4769
4770         /* We need more space (for insert) */
4771         else if (len > 0)
4772         {
4773                 for (i = b_len-1; i >= t_len; --i) buf[i+len] = buf[i];
4774         }
4775
4776         /* If movement occured, we need a new terminator */
4777         if (len) buf[b_len+len] = '\0';
4778
4779         /* Now copy the insertion string */
4780         for (i = 0; i < i_len; ++i) buf[i] = insert[i];
4781
4782         /* Successful operation */
4783         return (TRUE);
4784 }
4785
4786
4787 #endif
4788
4789
4790 /*
4791  * GH
4792  * Called from cmd4.c and a few other places. Just extracts
4793  * a direction from the keymap for ch (the last direction,
4794  * in fact) byte or char here? I'm thinking that keymaps should
4795  * generally only apply to single keys, which makes it no more
4796  * than 128, so a char should suffice... but keymap_act is 256...
4797  */
4798 int get_keymap_dir(char ch)
4799 {
4800         int d = 0;
4801
4802         /* Already a direction? */
4803         if (isdigit(ch))
4804         {
4805                 d = D2I(ch);
4806         }
4807         else
4808         {
4809                 BIT_FLAGS mode;
4810                 cptr act, s;
4811
4812                 /* Roguelike */
4813                 if (rogue_like_commands)
4814                 {
4815                         mode = KEYMAP_MODE_ROGUE;
4816                 }
4817
4818                 /* Original */
4819                 else
4820                 {
4821                         mode = KEYMAP_MODE_ORIG;
4822                 }
4823
4824                 /* Extract the action (if any) */
4825                 act = keymap_act[mode][(byte)(ch)];
4826
4827                 /* Analyze */
4828                 if (act)
4829                 {
4830                         /* Convert to a direction */
4831                         for (s = act; *s; ++s)
4832                         {
4833                                 /* Use any digits in keymap */
4834                                 if (isdigit(*s)) d = D2I(*s);
4835                         }
4836                 }
4837         }
4838
4839         /* Paranoia */
4840         if (d == 5) d = 0;
4841
4842         /* Return direction */
4843         return (d);
4844 }
4845
4846
4847 #ifdef ALLOW_REPEAT /* TNB */
4848
4849 #define REPEAT_MAX              20
4850
4851 /* Number of chars saved */
4852 static int repeat__cnt = 0;
4853
4854 /* Current index */
4855 static int repeat__idx = 0;
4856
4857 /* Saved "stuff" */
4858 static COMMAND_CODE repeat__key[REPEAT_MAX];
4859
4860
4861 void repeat_push(COMMAND_CODE what)
4862 {
4863         /* Too many keys */
4864         if (repeat__cnt == REPEAT_MAX) return;
4865
4866         /* Push the "stuff" */
4867         repeat__key[repeat__cnt++] = what;
4868
4869         /* Prevents us from pulling keys */
4870         ++repeat__idx;
4871 }
4872
4873
4874 bool repeat_pull(COMMAND_CODE *what)
4875 {
4876         /* All out of keys */
4877         if (repeat__idx == repeat__cnt) return (FALSE);
4878
4879         /* Grab the next key, advance */
4880         *what = repeat__key[repeat__idx++];
4881
4882         /* Success */
4883         return (TRUE);
4884 }
4885
4886 void repeat_check(void)
4887 {
4888         COMMAND_CODE what;
4889
4890         /* Ignore some commands */
4891         if (command_cmd == ESCAPE) return;
4892         if (command_cmd == ' ') return;
4893         if (command_cmd == '\r') return;
4894         if (command_cmd == '\n') return;
4895
4896         /* Repeat Last Command */
4897         if (command_cmd == 'n')
4898         {
4899                 /* Reset */
4900                 repeat__idx = 0;
4901
4902                 /* Get the command */
4903                 if (repeat_pull(&what))
4904                 {
4905                         /* Save the command */
4906                         command_cmd = what;
4907                 }
4908         }
4909
4910         /* Start saving new command */
4911         else
4912         {
4913                 /* Reset */
4914                 repeat__cnt = 0;
4915                 repeat__idx = 0;
4916
4917                 what = command_cmd;
4918
4919                 /* Save this command */
4920                 repeat_push(what);
4921         }
4922 }
4923
4924 #endif /* ALLOW_REPEAT -- TNB */
4925
4926
4927 #ifdef SORT_R_INFO
4928
4929 /*
4930  * Array size for which InsertionSort
4931  * is used instead of QuickSort
4932  */
4933 #define CUTOFF 4
4934
4935
4936 /*
4937  * Exchange two sort-entries
4938  * (should probably be coded inline
4939  * for speed increase)
4940  */
4941 static void swap(tag_type *a, tag_type *b)
4942 {
4943         tag_type temp;
4944
4945         temp = *a;
4946         *a = *b;
4947         *b = temp;
4948 }
4949
4950
4951 /*
4952  * Insertion-Sort algorithm
4953  * (used by the Quicksort algorithm)
4954  */
4955 static void InsertionSort(tag_type elements[], int number)
4956 {
4957         int j, P;
4958
4959         tag_type tmp;
4960
4961         for (P = 1; P < number; P++)
4962         {
4963                 tmp = elements[P];
4964                 for (j = P; (j > 0) && (elements[j - 1].tag > tmp.tag); j--)
4965                         elements[j] = elements[j - 1];
4966                 elements[j] = tmp;
4967         }
4968 }
4969
4970
4971 /*
4972  * Helper function for Quicksort
4973  */
4974 static tag_type median3(tag_type elements[], int left, int right)
4975 {
4976         int center = (left + right) / 2;
4977
4978         if (elements[left].tag > elements[center].tag)
4979                 swap(&elements[left], &elements[center]);
4980         if (elements[left].tag > elements[right].tag)
4981                 swap(&elements[left], &elements[right]);
4982         if (elements[center].tag > elements[right].tag)
4983                 swap(&elements[center], &elements[right]);
4984
4985         swap(&elements[center], &elements[right - 1]);
4986         return (elements[right - 1]);
4987 }
4988
4989
4990 /*
4991  * Quicksort algorithm
4992  *
4993  * The "median of three" pivot selection eliminates
4994  * the bad case of already sorted input.
4995  *
4996  * We use InsertionSort for smaller sub-arrays,
4997  * because it is faster in this case.
4998  *
4999  * For details see: "Data Structures and Algorithm
5000  * Analysis in C" by Mark Allen Weiss.
5001  */
5002 static void quicksort(tag_type elements[], int left, int right)
5003 {
5004         int i, j;
5005         tag_type pivot;
5006
5007         if (left + CUTOFF <= right)
5008         {
5009                 pivot = median3(elements, left, right);
5010
5011                 i = left; j = right -1;
5012
5013                 while (TRUE)
5014                 {
5015                         while (elements[++i].tag < pivot.tag);
5016                         while (elements[--j].tag > pivot.tag);
5017
5018                         if (i < j)
5019                                 swap(&elements[i], &elements[j]);
5020                         else
5021                                 break;
5022                 }
5023
5024                 /* Restore pivot */
5025                 swap(&elements[i], &elements[right - 1]);
5026
5027                 quicksort(elements, left, i - 1);
5028                 quicksort(elements, i + 1, right);
5029         }
5030         else
5031         {
5032                 /* Use InsertionSort on small arrays */
5033                 InsertionSort(elements + left, right - left + 1);
5034         }
5035 }
5036
5037
5038 /*
5039  * Frontend for the sorting algorithm
5040  *
5041  * Sorts an array of tagged pointers
5042  * with <number> elements.
5043  */
5044 void tag_sort(tag_type elements[], int number)
5045 {
5046         quicksort(elements, 0, number - 1);
5047 }
5048
5049 #endif /* SORT_R_INFO */
5050
5051 #ifdef SUPPORT_GAMMA
5052
5053 /* Table of gamma values */
5054 byte gamma_table[256];
5055
5056 /* Table of ln(x/256) * 256 for x going from 0 -> 255 */
5057 static s16b gamma_helper[256] =
5058 {
5059 0,-1420,-1242,-1138,-1065,-1007,-961,-921,-887,-857,-830,-806,-783,-762,-744,-726,
5060 -710,-694,-679,-666,-652,-640,-628,-617,-606,-596,-586,-576,-567,-577,-549,-541,
5061 -532,-525,-517,-509,-502,-495,-488,-482,-475,-469,-463,-457,-451,-455,-439,-434,
5062 -429,-423,-418,-413,-408,-403,-398,-394,-389,-385,-380,-376,-371,-367,-363,-359,
5063 -355,-351,-347,-343,-339,-336,-332,-328,-325,-321,-318,-314,-311,-308,-304,-301,
5064 -298,-295,-291,-288,-285,-282,-279,-276,-273,-271,-268,-265,-262,-259,-257,-254,
5065 -251,-248,-246,-243,-241,-238,-236,-233,-231,-228,-226,-223,-221,-219,-216,-214,
5066 -212,-209,-207,-205,-203,-200,-198,-196,-194,-192,-190,-188,-186,-184,-182,-180,
5067 -178,-176,-174,-172,-170,-168,-166,-164,-162,-160,-158,-156,-155,-153,-151,-149,
5068 -147,-146,-144,-142,-140,-139,-137,-135,-134,-132,-130,-128,-127,-125,-124,-122,
5069 -120,-119,-117,-116,-114,-112,-111,-109,-108,-106,-105,-103,-102,-100,-99,-97,
5070 -96,-95,-93,-92,-90,-89,-87,-86,-85,-83,-82,-80,-79,-78,-76,-75,
5071 -74,-72,-71,-70,-68,-67,-66,-65,-63,-62,-61,-59,-58,-57,-56,-54,
5072 -53,-52,-51,-50,-48,-47,-46,-45,-44,-42,-41,-40,-39,-38,-37,-35,
5073 -34,-33,-32,-31,-30,-29,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,
5074 -17,-16,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1
5075 };
5076
5077
5078 /* 
5079  * Build the gamma table so that floating point isn't needed.
5080  * 
5081  * Note gamma goes from 0->256.  The old value of 100 is now 128.
5082  */
5083 void build_gamma_table(int gamma)
5084 {
5085         int i, n;
5086         
5087         /*
5088          * value is the current sum.
5089          * diff is the new term to add to the series.
5090          */
5091         long value, diff;
5092         
5093         /* Hack - convergence is bad in these cases. */
5094         gamma_table[0] = 0;
5095         gamma_table[255] = 255;
5096         
5097         for (i = 1; i < 255; i++)
5098         {
5099                 /* 
5100                  * Initialise the Taylor series
5101                  *
5102                  * value and diff have been scaled by 256
5103                  */
5104                 
5105                 n = 1;
5106                 value = 256 * 256;
5107                 diff = ((long)gamma_helper[i]) * (gamma - 256);
5108                 
5109                 while (diff)
5110                 {
5111                         value += diff;
5112                         n++;
5113                         
5114                         
5115                         /*
5116                          * Use the following identiy to calculate the gamma table.
5117                          * exp(x) = 1 + x + x^2/2 + x^3/(2*3) + x^4/(2*3*4) +...
5118                          *
5119                          * n is the current term number.
5120                          * 
5121                          * The gamma_helper array contains a table of
5122                          * ln(x/256) * 256
5123                          * This is used because a^b = exp(b*ln(a))
5124                          *
5125                          * In this case:
5126                          * a is i / 256
5127                          * b is gamma.
5128                          *
5129                          * Note that everything is scaled by 256 for accuracy,
5130                          * plus another factor of 256 for the final result to
5131                          * be from 0-255.  Thus gamma_helper[] * gamma must be
5132                          * divided by 256*256 each itteration, to get back to
5133                          * the original power series.
5134                          */
5135                         diff = (((diff / 256) * gamma_helper[i]) * (gamma - 256)) / (256 * n);
5136                 }
5137                 
5138                 /* 
5139                  * Store the value in the table so that the
5140                  * floating point pow function isn't needed .
5141                  */
5142                 gamma_table[i] = ((long)(value / 256) * i) / 256;
5143         }
5144 }
5145
5146 #endif /* SUPPORT_GAMMA */
5147
5148
5149 /*
5150  * Add a series of keypresses to the "queue".
5151  *
5152  * Return any errors generated by Term_keypress() in doing so, or SUCCESS
5153  * if there are none.
5154  *
5155  * Catch the "out of space" error before anything is printed.
5156  *
5157  * NB: The keys added here will be interpreted by any macros or keymaps.
5158  */
5159 errr type_string(cptr str, uint len)
5160 {
5161         errr err = 0;
5162         cptr s;
5163
5164         term *old = Term;
5165
5166         /* Paranoia - no string. */
5167         if (!str) return -1;
5168
5169         /* Hack - calculate the string length here if none given. */
5170         if (!len) len = strlen(str);
5171
5172         /* Activate the main window, as all pastes go there. */
5173         Term_activate(term_screen);
5174
5175         for (s = str; s < str+len; s++)
5176         {
5177                 /* Catch end of string */
5178                 if (*s == '\0') break;
5179
5180                 err = Term_keypress(*s);
5181
5182                 /* Catch errors */
5183                 if (err) break;
5184         }
5185
5186         /* Activate the original window. */
5187         Term_activate(old);
5188
5189         return err;
5190 }
5191
5192
5193
5194 void roff_to_buf(cptr str, int maxlen, char *tbuf, size_t bufsize)
5195 {
5196         int read_pt = 0;
5197         int write_pt = 0;
5198         int line_len = 0;
5199         int word_punct = 0;
5200         char ch[3];
5201         ch[2] = '\0';
5202
5203         while (str[read_pt])
5204         {
5205 #ifdef JP
5206                 bool kinsoku = FALSE;
5207                 bool kanji;
5208 #endif
5209                 int ch_len = 1;
5210
5211                 /* Prepare one character */
5212                 ch[0] = str[read_pt];
5213                 ch[1] = '\0';
5214 #ifdef JP
5215                 kanji  = iskanji(ch[0]);
5216
5217                 if (kanji)
5218                 {
5219                         ch[1] = str[read_pt+1];
5220                         ch_len = 2;
5221
5222                         if (strcmp(ch, "。") == 0 ||
5223                             strcmp(ch, "、") == 0 ||
5224                             strcmp(ch, "ィ") == 0 ||
5225                             strcmp(ch, "ー") == 0)
5226                                 kinsoku = TRUE;
5227                 }
5228                 else if (!isprint(ch[0]))
5229                         ch[0] = ' ';
5230 #else
5231                 if (!isprint(ch[0]))
5232                         ch[0] = ' ';
5233 #endif
5234
5235                 if (line_len + ch_len > maxlen - 1 || str[read_pt] == '\n')
5236                 {
5237                         int word_len;
5238
5239                         /* return to better wrapping point. */
5240                         /* Space character at the end of the line need not to be printed. */
5241                         word_len = read_pt - word_punct;
5242 #ifdef JP
5243                         if (kanji && !kinsoku)
5244                                 /* nothing */ ;
5245                         else
5246 #endif
5247                         if (ch[0] == ' ' || word_len >= line_len/2)
5248                                 read_pt++;
5249                         else
5250                         {
5251                                 read_pt = word_punct;
5252                                 if (str[word_punct] == ' ')
5253                                         read_pt++;
5254                                 write_pt -= word_len;
5255                         }
5256
5257                         tbuf[write_pt++] = '\0';
5258                         line_len = 0;
5259                         word_punct = read_pt;
5260                         continue;
5261                 }
5262                 if (ch[0] == ' ')
5263                         word_punct = read_pt;
5264 #ifdef JP
5265                 if (!kinsoku) word_punct = read_pt;
5266 #endif
5267
5268                 /* Not enough buffer size */
5269                 if ((size_t)(write_pt + 3) >= bufsize) break;
5270
5271                 tbuf[write_pt++] = ch[0];
5272                 line_len++;
5273                 read_pt++;
5274 #ifdef JP
5275                 if (kanji)
5276                 {
5277                         tbuf[write_pt++] = ch[1];
5278                         line_len++;
5279                         read_pt++;
5280                 }
5281 #endif
5282         }
5283         tbuf[write_pt] = '\0';
5284         tbuf[write_pt+1] = '\0';
5285
5286         return;
5287 }
5288
5289
5290 /*
5291  * The my_strcpy() function copies up to 'bufsize'-1 characters from 'src'
5292  * to 'buf' and NUL-terminates the result.  The 'buf' and 'src' strings may
5293  * not overlap.
5294  *
5295  * my_strcpy() returns strlen(src).  This makes checking for truncation
5296  * easy.  Example: if (my_strcpy(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
5297  *
5298  * This function should be equivalent to the strlcpy() function in BSD.
5299  */
5300 size_t my_strcpy(char *buf, const char *src, size_t bufsize)
5301 {
5302 #ifdef JP
5303
5304         char *d = buf;
5305         const char *s = src;
5306         size_t len = 0;
5307
5308         if (bufsize > 0) {
5309                 /* reserve for NUL termination */
5310                 bufsize--;
5311
5312                 /* Copy as many bytes as will fit */
5313                 while (*s && (len < bufsize))
5314                 {
5315                         if (iskanji(*s))
5316                         {
5317                                 if (len + 1 >= bufsize || !*(s+1)) break;
5318                                 *d++ = *s++;
5319                                 *d++ = *s++;
5320                                 len += 2;
5321                         }
5322                         else
5323                         {
5324                                 *d++ = *s++;
5325                                 len++;
5326                         }
5327                 }
5328                 *d = '\0';
5329         }
5330
5331         while(*s++) len++;
5332
5333         return len;
5334
5335 #else
5336
5337         size_t len = strlen(src);
5338         size_t ret = len;
5339
5340         /* Paranoia */
5341         if (bufsize == 0) return ret;
5342
5343         /* Truncate */
5344         if (len >= bufsize) len = bufsize - 1;
5345
5346         /* Copy the string and terminate it */
5347         (void)memcpy(buf, src, len);
5348         buf[len] = '\0';
5349
5350         /* Return strlen(src) */
5351         return ret;
5352
5353 #endif
5354 }
5355
5356
5357 /*
5358  * The my_strcat() tries to append a string to an existing NUL-terminated string.
5359  * It never writes more characters into the buffer than indicated by 'bufsize' and
5360  * NUL-terminates the buffer.  The 'buf' and 'src' strings may not overlap.
5361  *
5362  * my_strcat() returns strlen(buf) + strlen(src).  This makes checking for
5363  * truncation easy.  Example:
5364  * if (my_strcat(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
5365  *
5366  * This function should be equivalent to the strlcat() function in BSD.
5367  */
5368 size_t my_strcat(char *buf, const char *src, size_t bufsize)
5369 {
5370         size_t dlen = strlen(buf);
5371
5372         /* Is there room left in the buffer? */
5373         if (dlen < bufsize - 1)
5374         {
5375                 /* Append as much as possible  */
5376                 return (dlen + my_strcpy(buf + dlen, src, bufsize - dlen));
5377         }
5378         else
5379         {
5380                 /* Return without appending */
5381                 return (dlen + strlen(src));
5382         }
5383 }
5384
5385
5386 /*
5387  * A copy of ANSI strstr()
5388  *
5389  * my_strstr() can handle Kanji strings correctly.
5390  */
5391 char *my_strstr(const char *haystack, const char *needle)
5392 {
5393         int i;
5394         int l1 = strlen(haystack);
5395         int l2 = strlen(needle);
5396
5397         if (l1 >= l2)
5398         {
5399                 for(i = 0; i <= l1 - l2; i++)
5400                 {
5401                         if(!strncmp(haystack + i, needle, l2))
5402                                 return (char *)haystack + i;
5403
5404 #ifdef JP
5405                         if (iskanji(*(haystack + i))) i++;
5406 #endif
5407                 }
5408         }
5409
5410         return NULL;
5411 }
5412
5413
5414 /*
5415  * A copy of ANSI strchr()
5416  *
5417  * my_strchr() can handle Kanji strings correctly.
5418  */
5419 char *my_strchr(const char *ptr, char ch)
5420 {
5421         for ( ; *ptr != '\0'; ptr++)
5422         {
5423                 if (*ptr == ch) return (char *)ptr;
5424
5425 #ifdef JP
5426                 if (iskanji(*ptr)) ptr++;
5427 #endif
5428         }
5429
5430         return NULL;
5431 }
5432
5433
5434 /*
5435  * Convert string to lower case
5436  */
5437 void str_tolower(char *str)
5438 {
5439         /* Force to be lower case string */
5440         for (; *str; str++)
5441         {
5442 #ifdef JP
5443                 if (iskanji(*str))
5444                 {
5445                         str++;
5446                         continue;
5447                 }
5448 #endif
5449                 *str = (char)tolower(*str);
5450         }
5451 }
5452
5453
5454 /*
5455  * Get a keypress from the user.
5456  * And interpret special keys as internal code.
5457  *
5458  * This function is a Mega-Hack and depend on pref-xxx.prf's.
5459  * Currently works on Linux(UNIX), Windows, and Macintosh only.
5460  */
5461 int inkey_special(bool numpad_cursor)
5462 {
5463         static const struct {
5464                 cptr keyname;
5465                 int keyflag;
5466         } modifier_key_list[] = {
5467                 {"shift-", SKEY_MOD_SHIFT},
5468                 {"control-", SKEY_MOD_CONTROL},
5469                 {NULL, 0},
5470         };
5471
5472         static const struct {
5473                 bool numpad;
5474                 cptr keyname;
5475                 int keycode;
5476         } special_key_list[] = {
5477                 {FALSE, "Down]", SKEY_DOWN},
5478                 {FALSE, "Left]", SKEY_LEFT},
5479                 {FALSE, "Right]", SKEY_RIGHT},
5480                 {FALSE, "Up]", SKEY_UP},
5481                 {FALSE, "Page_Up]", SKEY_PGUP},
5482                 {FALSE, "Page_Down]", SKEY_PGDOWN},
5483                 {FALSE, "Home]", SKEY_TOP},
5484                 {FALSE, "End]", SKEY_BOTTOM},
5485                 {TRUE, "KP_Down]", SKEY_DOWN},
5486                 {TRUE, "KP_Left]", SKEY_LEFT},
5487                 {TRUE, "KP_Right]", SKEY_RIGHT},
5488                 {TRUE, "KP_Up]", SKEY_UP},
5489                 {TRUE, "KP_Page_Up]", SKEY_PGUP},
5490                 {TRUE, "KP_Page_Down]", SKEY_PGDOWN},
5491                 {TRUE, "KP_Home]", SKEY_TOP},
5492                 {TRUE, "KP_End]", SKEY_BOTTOM},
5493                 {TRUE, "KP_2]", SKEY_DOWN},
5494                 {TRUE, "KP_4]", SKEY_LEFT},
5495                 {TRUE, "KP_6]", SKEY_RIGHT},
5496                 {TRUE, "KP_8]", SKEY_UP},
5497                 {TRUE, "KP_9]", SKEY_PGUP},
5498                 {TRUE, "KP_3]", SKEY_PGDOWN},
5499                 {TRUE, "KP_7]", SKEY_TOP},
5500                 {TRUE, "KP_1]", SKEY_BOTTOM},
5501                 {FALSE, NULL, 0},
5502         };
5503
5504         static const struct {
5505                 cptr keyname;
5506                 int keycode;
5507         } gcu_special_key_list[] = {
5508                 {"A", SKEY_UP},
5509                 {"B", SKEY_DOWN},
5510                 {"C", SKEY_RIGHT},
5511                 {"D", SKEY_LEFT},
5512                 {"1~", SKEY_TOP},
5513                 {"4~", SKEY_BOTTOM},
5514                 {"5~", SKEY_PGUP},
5515                 {"6~", SKEY_PGDOWN},
5516                 {NULL, 0},
5517         };
5518
5519         char buf[1024];
5520         cptr str = buf;
5521         char key;
5522         int skey = 0;
5523         int modifier = 0;
5524         int i;
5525         size_t trig_len;
5526
5527         /*
5528          * Forget macro trigger ----
5529          * It's important if we are already expanding macro action
5530          */
5531         inkey_macro_trigger_string[0] = '\0';
5532
5533         /* Get a keypress */
5534         key = inkey();
5535
5536         /* Examine trigger string */
5537         trig_len = strlen(inkey_macro_trigger_string);
5538
5539         /* Already known that no special key */
5540         if (!trig_len) return (int)((unsigned char)key);
5541
5542         /*
5543          * Hack -- Ignore macro defined on ASCII characters.
5544          */
5545         if (trig_len == 1 && parse_macro)
5546         {
5547                 char c = inkey_macro_trigger_string[0];
5548
5549                 /* Cancel macro action on the queue */
5550                 forget_macro_action();
5551
5552                 /* Return the originaly pressed key */
5553                 return (int)((unsigned char)c);
5554         }
5555
5556         /* Convert the trigger */
5557         ascii_to_text(buf, inkey_macro_trigger_string);
5558
5559         /* Check the prefix "\[" */
5560         if (prefix(str, "\\["))
5561         {
5562                 /* Skip "\[" */
5563                 str += 2;
5564
5565                 /* Examine modifier keys */
5566                 while (TRUE)
5567                 {
5568                         for (i = 0; modifier_key_list[i].keyname; i++)
5569                         {
5570                                 if (prefix(str, modifier_key_list[i].keyname))
5571                                 {
5572                                         /* Get modifier key flag */
5573                                         str += strlen(modifier_key_list[i].keyname);
5574                                         modifier |= modifier_key_list[i].keyflag;
5575                                 }
5576                         }
5577
5578                         /* No more modifier key found */
5579                         if (!modifier_key_list[i].keyname) break;
5580                 }
5581
5582                 /* numpad_as_cursorkey option force numpad keys to input numbers */
5583                 if (!numpad_as_cursorkey) numpad_cursor = FALSE;
5584
5585                 /* Get a special key code */
5586                 for (i = 0; special_key_list[i].keyname; i++)
5587                 {
5588                         if ((!special_key_list[i].numpad || numpad_cursor) &&
5589                             streq(str, special_key_list[i].keyname))
5590                         {
5591                                 skey = special_key_list[i].keycode;
5592                                 break;
5593                         }
5594                 }
5595
5596                 /* A special key found */
5597                 if (skey)
5598                 {
5599                         /* Cancel macro action on the queue */
5600                         forget_macro_action();
5601
5602                         /* Return special key code and modifier flags */
5603                         return (skey | modifier);
5604                 }
5605         }
5606
5607         if (prefix(str, "\\e["))
5608         {
5609                 str += 3;
5610
5611                 for (i = 0; gcu_special_key_list[i].keyname; i++)
5612                 {
5613                         if (streq(str, gcu_special_key_list[i].keyname))
5614                         {
5615                                 return gcu_special_key_list[i].keycode;
5616                         }
5617                 }
5618         }
5619
5620         /* No special key found? */
5621
5622         /* Don't bother with this trigger no more */
5623         inkey_macro_trigger_string[0] = '\0';
5624
5625         /* Return normal keycode */
5626         return (int)((unsigned char)key);
5627 }