OSDN Git Service

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