OSDN Git Service

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