OSDN Git Service

unsigned charの取り扱いのミスで、inkey_special()が漢字入力に対応していなかったので修正。
[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();
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[next_pos])) 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                         /* Now on insert mode */
3267                         color = TERM_WHITE;
3268
3269                         /* No move at biggining of line */
3270                         if (!pos) break;
3271
3272                         /* Go left 1 unit */
3273                         pos--;
3274
3275                         /* Fall through to 'Delete key' */
3276
3277                 case 0x7F:
3278                 case KTRL('d'):
3279                         /* Delete key */
3280                 {
3281                         int dst, src;
3282
3283                         /* Now on insert mode */
3284                         color = TERM_WHITE;
3285
3286                         /* Position of next character */
3287                         src = pos + 1;
3288
3289 #ifdef JP
3290                         /* Next character is one more byte away */
3291                         if (iskanji(src)) src++;
3292 #endif
3293
3294                         dst = pos;
3295
3296                         /* Move characters at src to dst */
3297                         while ('\0' != (buf[dst++] = buf[src++]))
3298                                 /* loop */;
3299
3300                         break;
3301                 }
3302
3303                 default:
3304                 {
3305                         /* Insert a character */
3306
3307                         char tmp[100];
3308                         char c;
3309
3310                         /* Ignore special keys */
3311                         if (skey & SKEY_MASK) break;
3312
3313                         /* Get a character code */
3314                         c = (char)skey;
3315
3316                         if (color == TERM_YELLOW)
3317                         {
3318                                 /* Overwrite default string */
3319                                 buf[0] = '\0';
3320
3321                                 /* Go to insert mode */
3322                                 color = TERM_WHITE;
3323                         }
3324
3325                         /* Save right part of string */
3326                         strcpy(tmp, buf + pos);
3327 #ifdef JP
3328                         if (iskanji(c))
3329                         {
3330                                 char next;
3331
3332                                 /* Bypass macro processing */
3333                                 inkey_base = TRUE;
3334                                 next = inkey();
3335
3336                                 if (pos + 1 < len)
3337                                 {
3338                                         buf[pos++] = c;
3339                                         buf[pos++] = next;
3340                                 }
3341                                 else
3342                                 {
3343                                         bell();
3344                                 }
3345                         }
3346                         else
3347 #endif
3348                         {
3349 #ifdef JP
3350                                 if (pos < len && (isprint(c) || iskana(c)))
3351 #else
3352                                 if (pos < len && isprint(c))
3353 #endif
3354                                 {
3355                                         buf[pos++] = c;
3356                                 }
3357                                 else
3358                                 {
3359                                         bell();
3360                                 }
3361                         }
3362
3363                         /* Terminate */
3364                         buf[pos] = '\0';
3365
3366                         /* Write back the left part of string */
3367                         my_strcat(buf, tmp, len + 1);
3368
3369                         break;
3370                 } /* default: */
3371
3372                 }
3373
3374         } /* while (TRUE) */
3375 }
3376
3377
3378 /*
3379  * Get a string from the user
3380  *
3381  * The "prompt" should take the form "Prompt: "
3382  *
3383  * Note that the initial contents of the string is used as
3384  * the default response, so be sure to "clear" it if needed.
3385  *
3386  * We clear the input, and return FALSE, on "ESCAPE".
3387  */
3388 bool get_string(cptr prompt, char *buf, int len)
3389 {
3390         bool res;
3391
3392         /* Paranoia XXX XXX XXX */
3393         msg_print(NULL);
3394
3395         /* Display prompt */
3396         prt(prompt, 0, 0);
3397
3398         /* Ask the user for a string */
3399         res = askfor_aux(buf, len);
3400
3401         /* Clear prompt */
3402         prt("", 0, 0);
3403
3404         /* Result */
3405         return (res);
3406 }
3407
3408
3409 /*
3410  * Verify something with the user
3411  *
3412  * The "prompt" should take the form "Query? "
3413  *
3414  * Note that "[y/n]" is appended to the prompt.
3415  */
3416 bool get_check(cptr prompt)
3417 {
3418         return get_check_strict(prompt, 0);
3419 }
3420
3421 /*
3422  * Verify something with the user strictly
3423  *
3424  * mode & CHECK_OKAY_CANCEL : force user to answer 'O'kay or 'C'ancel
3425  * mode & CHECK_NO_ESCAPE   : don't allow ESCAPE key
3426  * mode & CHECK_NO_HISTORY  : no message_add
3427  * mode & CHECK_DEFAULT_Y   : accept any key as y, except n and Esc.
3428  */
3429 bool get_check_strict(cptr prompt, int mode)
3430 {
3431         int i;
3432         char buf[80];
3433         bool flag = FALSE;
3434
3435         if (auto_more)
3436         {
3437                 p_ptr->window |= PW_MESSAGE;
3438                 window_stuff();
3439                 num_more = 0;
3440         }
3441
3442         /* Paranoia XXX XXX XXX */
3443         msg_print(NULL);
3444
3445         if (!rogue_like_commands)
3446                 mode &= ~CHECK_OKAY_CANCEL;
3447
3448
3449         /* Hack -- Build a "useful" prompt */
3450         if (mode & CHECK_OKAY_CANCEL)
3451         {
3452                 my_strcpy(buf, prompt, sizeof(buf)-15);
3453                 strcat(buf, "[(O)k/(C)ancel]");
3454         }
3455         else if (mode & CHECK_DEFAULT_Y)
3456         {
3457                 my_strcpy(buf, prompt, sizeof(buf)-5);
3458                 strcat(buf, "[Y/n]");
3459         }
3460         else
3461         {
3462                 my_strcpy(buf, prompt, sizeof(buf)-5);
3463                 strcat(buf, "[y/n]");
3464         }
3465
3466         /* Prompt for it */
3467         prt(buf, 0, 0);
3468
3469         if (!(mode & CHECK_NO_HISTORY) && p_ptr->playing)
3470         {
3471                 /* HACK : Add the line to message buffer */
3472                 message_add(buf);
3473                 p_ptr->window |= (PW_MESSAGE);
3474                 window_stuff();
3475         }
3476
3477         /* Get an acceptable answer */
3478         while (TRUE)
3479         {
3480                 i = inkey();
3481
3482                 if (!(mode & CHECK_NO_ESCAPE))
3483                 {
3484                         if (i == ESCAPE)
3485                         {
3486                                 flag = FALSE;
3487                                 break;
3488                         }
3489                 }
3490
3491                 if (mode & CHECK_OKAY_CANCEL)
3492                 {
3493                         if (i == 'o' || i == 'O')
3494                         {
3495                                 flag = TRUE;
3496                                 break;
3497                         }
3498                         else if (i == 'c' || i == 'C')
3499                         {
3500                                 flag = FALSE;
3501                                 break;
3502                         }
3503                 }
3504                 else
3505                 {
3506                         if (i == 'y' || i == 'Y')
3507                         {
3508                                 flag = TRUE;
3509                                 break;
3510                         }
3511                         else if (i == 'n' || i == 'N')
3512                         {
3513                                 flag = FALSE;
3514                                 break;
3515                         }
3516                 }
3517
3518                 if (mode & CHECK_DEFAULT_Y)
3519                 {
3520                         flag = TRUE;
3521                         break;
3522                 }
3523
3524                 bell();
3525         }
3526
3527         /* Erase the prompt */
3528         prt("", 0, 0);
3529
3530         /* Return the flag */
3531         return flag;
3532 }
3533
3534
3535 /*
3536  * Prompts for a keypress
3537  *
3538  * The "prompt" should take the form "Command: "
3539  *
3540  * Returns TRUE unless the character is "Escape"
3541  */
3542 bool get_com(cptr prompt, char *command, bool z_escape)
3543 {
3544         /* Paranoia XXX XXX XXX */
3545         msg_print(NULL);
3546
3547         /* Display a prompt */
3548         prt(prompt, 0, 0);
3549
3550         /* Get a key */
3551         *command = inkey();
3552
3553         /* Clear the prompt */
3554         prt("", 0, 0);
3555
3556         /* Handle "cancel" */
3557         if (*command == ESCAPE) return (FALSE);
3558         if (z_escape && ((*command == 'z') || (*command == 'Z'))) return (FALSE);
3559
3560         /* Success */
3561         return (TRUE);
3562 }
3563
3564
3565 /*
3566  * Request a "quantity" from the user
3567  *
3568  * Hack -- allow "command_arg" to specify a quantity
3569  */
3570 s16b get_quantity(cptr prompt, int max)
3571 {
3572         int amt;
3573
3574         char tmp[80];
3575
3576         char buf[80];
3577
3578
3579         /* Use "command_arg" */
3580         if (command_arg)
3581         {
3582                 /* Extract a number */
3583                 amt = command_arg;
3584
3585                 /* Clear "command_arg" */
3586                 command_arg = 0;
3587
3588                 /* Enforce the maximum */
3589                 if (amt > max) amt = max;
3590
3591                 /* Use it */
3592                 return (amt);
3593         }
3594
3595 #ifdef ALLOW_REPEAT /* TNB */
3596
3597         /* Get the item index */
3598         if ((max != 1) && repeat_pull(&amt))
3599         {
3600                 /* Enforce the maximum */
3601                 if (amt > max) amt = max;
3602
3603                 /* Enforce the minimum */
3604                 if (amt < 0) amt = 0;
3605
3606                 /* Use it */
3607                 return (amt);
3608         }
3609
3610 #endif /* ALLOW_REPEAT -- TNB */
3611
3612         /* Build a prompt if needed */
3613         if (!prompt)
3614         {
3615                 /* Build a prompt */
3616 #ifdef JP
3617                         sprintf(tmp, "¤¤¤¯¤Ä¤Ç¤¹¤« (1-%d): ", max);
3618 #else
3619                 sprintf(tmp, "Quantity (1-%d): ", max);
3620 #endif
3621
3622
3623                 /* Use that prompt */
3624                 prompt = tmp;
3625         }
3626
3627
3628         /* Default to one */
3629         amt = 1;
3630
3631         /* Build the default */
3632         sprintf(buf, "%d", amt);
3633
3634         /* Ask for a quantity */
3635         if (!get_string(prompt, buf, 6)) return (0);
3636
3637         /* Extract a number */
3638         amt = atoi(buf);
3639
3640         /* A letter means "all" */
3641         if (isalpha(buf[0])) amt = max;
3642
3643         /* Enforce the maximum */
3644         if (amt > max) amt = max;
3645
3646         /* Enforce the minimum */
3647         if (amt < 0) amt = 0;
3648
3649 #ifdef ALLOW_REPEAT /* TNB */
3650
3651         if (amt) repeat_push(amt);
3652
3653 #endif /* ALLOW_REPEAT -- TNB */
3654
3655         /* Return the result */
3656         return (amt);
3657 }
3658
3659
3660 /*
3661  * Pause for user response XXX XXX XXX
3662  */
3663 void pause_line(int row)
3664 {
3665         prt("", row, 0);
3666 #ifdef JP
3667         put_str("[ ²¿¤«¥­¡¼¤ò²¡¤·¤Æ²¼¤µ¤¤ ]", row, 26);
3668 #else
3669         put_str("[Press any key to continue]", row, 23);
3670 #endif
3671
3672         (void)inkey();
3673         prt("", row, 0);
3674 }
3675
3676
3677 /*
3678  * Hack -- special buffer to hold the action of the current keymap
3679  */
3680 static char request_command_buffer[256];
3681
3682
3683
3684 typedef struct
3685 {
3686         cptr name;
3687         byte cmd;
3688         bool fin;
3689 } menu_naiyou;
3690
3691 #ifdef JP
3692 menu_naiyou menu_info[10][10] =
3693 {
3694         {
3695                 {"ËâË¡/ÆüìǽÎÏ", 1, FALSE},
3696                 {"¹ÔÆ°", 2, FALSE},
3697                 {"Æ»¶ñ(»ÈÍÑ)", 3, FALSE},
3698                 {"Æ»¶ñ(¤½¤Î¾)", 4, FALSE},
3699                 {"ÁõÈ÷", 5, FALSE},
3700                 {"Èâ/È¢", 6, FALSE},
3701                 {"¾ðÊó", 7, FALSE},
3702                 {"ÀßÄê", 8, FALSE},
3703                 {"¤½¤Î¾", 9, FALSE},
3704                 {"", 0, FALSE},
3705         },
3706
3707         {
3708                 {"»È¤¦(m)", 'm', TRUE},
3709                 {"Ä´¤Ù¤ë(b/P)", 'b', TRUE},
3710                 {"³Ð¤¨¤ë(G)", 'G', TRUE},
3711                 {"ÆüìǽÎϤò»È¤¦(U/O)", 'U', TRUE},
3712                 {"", 0, FALSE},
3713                 {"", 0, FALSE},
3714                 {"", 0, FALSE},
3715                 {"", 0, FALSE},
3716                 {"", 0, FALSE},
3717                 {"", 0, FALSE}
3718         },
3719
3720         {
3721                 {"µÙ©¤¹¤ë(R)", 'R', TRUE},
3722                 {"¥È¥é¥Ã¥×²ò½ü(D)", 'D', TRUE},
3723                 {"õ¤¹(s)", 's', TRUE},
3724                 {"¼þ¤ê¤òÄ´¤Ù¤ë(l/x)", 'l', TRUE},
3725                 {"¥¿¡¼¥²¥Ã¥È»ØÄê(*)", '*', TRUE},
3726                 {"·ê¤ò·¡¤ë(T/^t)", 'T', TRUE},
3727                 {"³¬Ãʤò¾å¤ë(<)", '<', TRUE},
3728                 {"³¬Ãʤò²¼¤ê¤ë(>)", '>', TRUE},
3729                 {"¥Ú¥Ã¥È¤ËÌ¿Î᤹¤ë(p)", 'p', TRUE},
3730                 {"õº÷¥â¡¼¥É¤ÎON/OFF(S/#)", 'S', TRUE}
3731         },
3732
3733         {
3734                 {"Æɤà(r)", 'r', TRUE},
3735                 {"°û¤à(q)", 'q', TRUE},
3736                 {"¾ó¤ò»È¤¦(u/Z)", 'u', TRUE},
3737                 {"ËâË¡ËÀ¤ÇÁÀ¤¦(a/z)", 'a', TRUE},
3738                 {"¥í¥Ã¥É¤ò¿¶¤ë(z/a)", 'z', TRUE},
3739                 {"»ÏÆ°¤¹¤ë(A)", 'A', TRUE},
3740                 {"¿©¤Ù¤ë(E)", 'E', TRUE},
3741                 {"Èô¤ÓÆ»¶ñ¤Ç·â¤Ä(f/t)", 'f', TRUE},
3742                 {"Åꤲ¤ë(v)", 'v', TRUE},
3743                 {"", 0, FALSE}
3744         },
3745
3746         {
3747                 {"½¦¤¦(g)", 'g', TRUE},
3748                 {"Íî¤È¤¹(d)", 'd', TRUE},
3749                 {"²õ¤¹(k/^d)", 'k', TRUE},
3750                 {"Ìäò¹ï¤à({)", '{', TRUE},
3751                 {"Ìäò¾Ã¤¹(})", '}', TRUE},
3752                 {"Ä´ºº(I)", 'I', TRUE},
3753                 {"¥¢¥¤¥Æ¥à°ìÍ÷(i)", 'i', TRUE},
3754                 {"", 0, FALSE},
3755                 {"", 0, FALSE},
3756                 {"", 0, FALSE}
3757         },
3758
3759         {
3760                 {"ÁõÈ÷¤¹¤ë(w)", 'w', TRUE},
3761                 {"ÁõÈ÷¤ò³°¤¹(t/T)", 't', TRUE},
3762                 {"dzÎÁ¤òÊäµë(F)", 'F', TRUE},
3763                 {"ÁõÈ÷°ìÍ÷(e)", 'e', TRUE},
3764                 {"", 0, FALSE},
3765                 {"", 0, FALSE},
3766                 {"", 0, FALSE},
3767                 {"", 0, FALSE},
3768                 {"", 0, FALSE},
3769                 {"", 0, FALSE}
3770         },
3771
3772         {
3773                 {"³«¤±¤ë(o)", 'o', TRUE},
3774                 {"ÊĤ¸¤ë(c)", 'c', TRUE},
3775                 {"ÂÎÅö¤¿¤ê¤¹¤ë(B/f)", 'B', TRUE},
3776                 {"¤¯¤µ¤Ó¤òÂǤÄ(j/S)", 'j', TRUE},
3777                 {"", 0, FALSE},
3778                 {"", 0, FALSE},
3779                 {"", 0, FALSE},
3780                 {"", 0, FALSE},
3781                 {"", 0, FALSE},
3782                 {"", 0, FALSE}
3783         },
3784
3785         {
3786                 {"¥À¥ó¥¸¥ç¥ó¤ÎÁ´ÂοÞ(M)", 'M', TRUE},
3787                 {"°ÌÃÖ¤ò³Îǧ(L/W)", 'L', TRUE},
3788                 {"³¬¤ÎÊ·°Ïµ¤(^f)", KTRL('F'), TRUE},
3789                 {"¥¹¥Æ¡¼¥¿¥¹(C)", 'C', TRUE},
3790                 {"ʸ»ú¤ÎÀâÌÀ(/)", '/', TRUE},
3791                 {"¥á¥Ã¥»¡¼¥¸ÍúÎò(^p)", KTRL('P'), TRUE},
3792                 {"¸½ºß¤Î»þ¹ï(^t/')", KTRL('T'), TRUE},
3793                 {"¸½ºß¤ÎÃμ±(~)", '~', TRUE},
3794                 {"¥×¥ì¥¤µ­Ï¿(|)", '|', TRUE},
3795                 {"", 0, FALSE}
3796         },
3797
3798         {
3799                 {"¥ª¥×¥·¥ç¥ó(=)", '=', TRUE},
3800                 {"¥Þ¥¯¥í(@)", '@', TRUE},
3801                 {"²èÌÌɽ¼¨(%)", '%', TRUE},
3802                 {"¥«¥é¡¼(&)", '&', TRUE},
3803                 {"ÀßÄêÊѹ¹¥³¥Þ¥ó¥É(\")", '\"', TRUE},
3804                 {"¼«Æ°½¦¤¤¤ò¥í¡¼¥É($)", '$', TRUE},
3805                 {"¥·¥¹¥Æ¥à(!)", '!', TRUE},
3806                 {"", 0, FALSE},
3807                 {"", 0, FALSE},
3808                 {"", 0, FALSE}
3809         },
3810
3811         {
3812                 {"¥»¡¼¥Ö&ÃæÃÇ(^x)", KTRL('X'), TRUE},
3813                 {"¥»¡¼¥Ö(^s)", KTRL('S'), TRUE},
3814                 {"¥Ø¥ë¥×(?)", '?', TRUE},
3815                 {"ºÆÉÁ²è(^r)", KTRL('R'), TRUE},
3816                 {"¥á¥â(:)", ':', TRUE},
3817                 {"µ­Ç°»£±Æ())", ')', TRUE},
3818                 {"µ­Ç°»£±Æ¤Îɽ¼¨(()", '(', TRUE},
3819                 {"¥Ð¡¼¥¸¥ç¥ó¾ðÊó(V)", 'V', TRUE},
3820                 {"°úÂह¤ë(Q)", 'Q', TRUE},
3821                 {"", 0, FALSE}
3822         },
3823 };
3824 #else
3825 menu_naiyou menu_info[10][10] =
3826 {
3827         {
3828                 {"Magic/Special", 1, FALSE},
3829                 {"Action", 2, FALSE},
3830                 {"Items(use)", 3, FALSE},
3831                 {"Items(other)", 4, FALSE},
3832                 {"Equip", 5, FALSE},
3833                 {"Door/Box", 6, FALSE},
3834                 {"Infomations", 7, FALSE},
3835                 {"Options", 8, FALSE},
3836                 {"Other commands", 9, FALSE},
3837                 {"", 0, FALSE},
3838         },
3839
3840         {
3841                 {"Use(m)", 'm', TRUE},
3842                 {"See tips(b/P)", 'b', TRUE},
3843                 {"Study(G)", 'G', TRUE},
3844                 {"Special abilities(U/O)", 'U', TRUE},
3845                 {"", 0, FALSE},
3846                 {"", 0, FALSE},
3847                 {"", 0, FALSE},
3848                 {"", 0, FALSE},
3849                 {"", 0, FALSE},
3850                 {"", 0, FALSE}
3851         },
3852
3853         {
3854                 {"Rest(R)", 'R', TRUE},
3855                 {"Disarm a trap(D)", 'D', TRUE},
3856                 {"Search(s)", 's', TRUE},
3857                 {"Look(l/x)", 'l', TRUE},
3858                 {"Target(*)", '*', TRUE},
3859                 {"Dig(T/^t)", 'T', TRUE},
3860                 {"Go up stairs(<)", '<', TRUE},
3861                 {"Go down staies(>)", '>', TRUE},
3862                 {"Command pets(p)", 'p', TRUE},
3863                 {"Search mode ON/OFF(S/#)", 'S', TRUE}
3864         },
3865
3866         {
3867                 {"Read a scroll(r)", 'r', TRUE},
3868                 {"Drink a potion(q)", 'q', TRUE},
3869                 {"Use a staff(u/Z)", 'u', TRUE},
3870                 {"Aim a wand(a/z)", 'a', TRUE},
3871                 {"Zap a rod(z/a)", 'z', TRUE},
3872                 {"Activate an equipment(A)", 'A', TRUE},
3873                 {"Eat(E)", 'E', TRUE},
3874                 {"Fire missile weapon(f/t)", 'f', TRUE},
3875                 {"Throw an item(v)", 'v', TRUE},
3876                 {"", 0, FALSE}
3877         },
3878
3879         {
3880                 {"Get items(g)", 'g', TRUE},
3881                 {"Drop an item(d)", 'd', TRUE},
3882                 {"Destroy an item(k/^d)", 'k', TRUE},
3883                 {"Inscribe an item({)", '{', TRUE},
3884                 {"Uninscribe an item(})", '}', TRUE},
3885                 {"Info about an item(I)", 'I', TRUE},
3886                 {"Inventory list(i)", 'i', TRUE},
3887                 {"", 0, FALSE},
3888                 {"", 0, FALSE},
3889                 {"", 0, FALSE}
3890         },
3891
3892         {
3893                 {"Wear(w)", 'w', TRUE},
3894                 {"Take off(t/T)", 't', TRUE},
3895                 {"Refuel(F)", 'F', TRUE},
3896                 {"Equipment list(e)", 'e', TRUE},
3897                 {"", 0, FALSE},
3898                 {"", 0, FALSE},
3899                 {"", 0, FALSE},
3900                 {"", 0, FALSE},
3901                 {"", 0, FALSE},
3902                 {"", 0, FALSE}
3903         },
3904
3905         {
3906                 {"Open(o)", 'o', TRUE},
3907                 {"Close(c)", 'c', TRUE},
3908                 {"Bash a door(B/f)", 'B', TRUE},
3909                 {"Jam a door(j/S)", 'j', TRUE},
3910                 {"", 0, FALSE},
3911                 {"", 0, FALSE},
3912                 {"", 0, FALSE},
3913                 {"", 0, FALSE},
3914                 {"", 0, FALSE},
3915                 {"", 0, FALSE}
3916         },
3917
3918         {
3919                 {"Full map(M)", 'M', TRUE},
3920                 {"Map(L/W)", 'L', TRUE},
3921                 {"Level feeling(^f)", KTRL('F'), TRUE},
3922                 {"Character status(C)", 'C', TRUE},
3923                 {"Identify symbol(/)", '/', TRUE},
3924                 {"Show prev messages(^p)", KTRL('P'), TRUE},
3925                 {"Current time(^t/')", KTRL('T'), TRUE},
3926                 {"Various infomations(~)", '~', TRUE},
3927                 {"Play record menu(|)", '|', TRUE},
3928                 {"", 0, FALSE}
3929         },
3930
3931         {
3932                 {"Set options(=)", '=', TRUE},
3933                 {"Interact with macros(@)", '@', TRUE},
3934                 {"Interact w/ visuals(%)", '%', TRUE},
3935                 {"Interact with colors(&)", '&', TRUE},
3936                 {"Enter a user pref(\")", '\"', TRUE},
3937                 {"Reload auto-pick pref($)", '$', TRUE},
3938                 {"", 0, FALSE},
3939                 {"", 0, FALSE},
3940                 {"", 0, FALSE},
3941                 {"", 0, FALSE}
3942         },
3943
3944         {
3945                 {"Save and quit(^x)", KTRL('X'), TRUE},
3946                 {"Save(^s)", KTRL('S'), TRUE},
3947                 {"Help(obsoleted)(?)", '?', TRUE},
3948                 {"Redraw(^r)", KTRL('R'), TRUE},
3949                 {"Take note(:)", ':', TRUE},
3950                 {"Dump screen dump(()", ')', TRUE},
3951                 {"Load screen dump())", '(', TRUE},
3952                 {"Version info(V)", 'V', TRUE},
3953                 {"Quit(Q)", 'Q', TRUE},
3954                 {"", 0, FALSE}
3955         },
3956 };
3957 #endif
3958
3959 typedef struct
3960 {
3961         cptr name;
3962         byte window;
3963         byte number;
3964         byte jouken;
3965         byte jouken_naiyou;
3966 } special_menu_naiyou;
3967
3968 #define MENU_CLASS 1
3969 #define MENU_WILD 2
3970
3971 #ifdef JP
3972 special_menu_naiyou special_menu_info[] =
3973 {
3974         {"ĶǽÎÏ/ÆüìǽÎÏ", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
3975         {"¤â¤Î¤Þ¤Í/ÆüìǽÎÏ", 0, 0, MENU_CLASS, CLASS_IMITATOR},
3976         {"ɬ»¦µ»/ÆüìǽÎÏ", 0, 0, MENU_CLASS, CLASS_SAMURAI},
3977         {"Îýµ¤½Ñ/ËâË¡/ÆüìǽÎÏ", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
3978         {"¶ÀËâË¡/ÆüìǽÎÏ", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
3979         {"¹­°è¥Þ¥Ã¥×(<)", 2, 6, MENU_WILD, FALSE},
3980         {"Ä̾ï¥Þ¥Ã¥×(>)", 2, 7, MENU_WILD, TRUE},
3981         {"", 0, 0, 0, 0},
3982 };
3983 #else
3984 special_menu_naiyou special_menu_info[] =
3985 {
3986         {"MindCraft/Special", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
3987         {"Imitation/Special", 0, 0, MENU_CLASS, CLASS_IMITATOR},
3988         {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SAMURAI},
3989         {"Mind/Magic/Special", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
3990         {"MirrorMagic/Special", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
3991         {"Enter global map(<)", 2, 6, MENU_WILD, FALSE},
3992         {"Enter local map(>)", 2, 7, MENU_WILD, TRUE},
3993         {"", 0, 0, 0, 0},
3994 };
3995 #endif
3996
3997 static char inkey_from_menu(void)
3998 {
3999         char cmd;
4000         int basey, basex;
4001         int num = 0, max_num, old_num = 0;
4002         int menu = 0;
4003         bool kisuu;
4004
4005         if (py - panel_row_min > 10) basey = 2;
4006         else basey = 13;
4007         basex = 15;
4008
4009         /* Clear top line */
4010         prt("", 0, 0);
4011
4012         screen_save();
4013
4014         while(1)
4015         {
4016                 int i;
4017                 char sub_cmd;
4018                 cptr menu_name;
4019                 if (!menu) old_num = num;
4020                 put_str("+----------------------------------------------------+", basey, basex);
4021                 put_str("|                                                    |", basey+1, basex);
4022                 put_str("|                                                    |", basey+2, basex);
4023                 put_str("|                                                    |", basey+3, basex);
4024                 put_str("|                                                    |", basey+4, basex);
4025                 put_str("|                                                    |", basey+5, basex);
4026                 put_str("+----------------------------------------------------+", basey+6, basex);
4027
4028                 for(i = 0; i < 10; i++)
4029                 {
4030                         int hoge;
4031                         if (!menu_info[menu][i].cmd) break;
4032                         menu_name = menu_info[menu][i].name;
4033                         for(hoge = 0; ; hoge++)
4034                         {
4035                                 if (!special_menu_info[hoge].name[0]) break;
4036                                 if ((menu != special_menu_info[hoge].window) || (i != special_menu_info[hoge].number)) continue;
4037                                 switch(special_menu_info[hoge].jouken)
4038                                 {
4039                                 case MENU_CLASS:
4040                                         if (p_ptr->pclass == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
4041                                         break;
4042                                 case MENU_WILD:
4043                                         if (!dun_level && !p_ptr->inside_arena && !p_ptr->inside_quest)
4044                                         {
4045                                                 if ((byte)p_ptr->wild_mode == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
4046                                         }
4047                                         break;
4048                                 default:
4049                                         break;
4050                                 }
4051                         }
4052                         put_str(menu_name, basey + 1 + i / 2, basex + 4 + (i % 2) * 24);
4053                 }
4054                 max_num = i;
4055                 kisuu = max_num % 2;
4056 #ifdef JP
4057                 put_str("¡Õ",basey + 1 + num / 2, basex + 2 + (num % 2) * 24);
4058 #else
4059                 put_str("> ",basey + 1 + num / 2, basex + 2 + (num % 2) * 24);
4060 #endif
4061
4062                 /* Place the cursor on the player */
4063                 move_cursor_relative(py, px);
4064
4065                 /* Get a command */
4066                 sub_cmd = inkey();
4067                 if ((sub_cmd == ' ') || (sub_cmd == 'x') || (sub_cmd == 'X') || (sub_cmd == '\r') || (sub_cmd == '\n'))
4068                 {
4069                         if (menu_info[menu][num].fin)
4070                         {
4071                                 cmd = menu_info[menu][num].cmd;
4072                                 use_menu = TRUE;
4073                                 break;
4074                         }
4075                         else
4076                         {
4077                                 menu = menu_info[menu][num].cmd;
4078                                 num = 0;
4079                                 basey += 2;
4080                                 basex += 8;
4081                         }
4082                 }
4083                 else if ((sub_cmd == ESCAPE) || (sub_cmd == 'z') || (sub_cmd == 'Z') || (sub_cmd == '0'))
4084                 {
4085                         if (!menu)
4086                         {
4087                                 cmd = ESCAPE;
4088                                 break;
4089                         }
4090                         else
4091                         {
4092                                 menu = 0;
4093                                 num = old_num;
4094                                 basey -= 2;
4095                                 basex -= 8;
4096                                 screen_load();
4097                                 screen_save();
4098                         }
4099                 }
4100                 else if ((sub_cmd == '2') || (sub_cmd == 'j') || (sub_cmd == 'J'))
4101                 {
4102                         if (kisuu)
4103                         {
4104                                 if (num % 2)
4105                                         num = (num + 2) % (max_num - 1);
4106                                 else
4107                                         num = (num + 2) % (max_num + 1);
4108                         }
4109                         else num = (num + 2) % max_num;
4110                 }
4111                 else if ((sub_cmd == '8') || (sub_cmd == 'k') || (sub_cmd == 'K'))
4112                 {
4113                         if (kisuu)
4114                         {
4115                                 if (num % 2)
4116                                         num = (num + max_num - 3) % (max_num - 1);
4117                                 else
4118                                         num = (num + max_num - 1) % (max_num + 1);
4119                         }
4120                         else num = (num + max_num - 2) % max_num;
4121                 }
4122                 else if ((sub_cmd == '4') || (sub_cmd == '6') || (sub_cmd == 'h') || (sub_cmd == 'H') || (sub_cmd == 'l') || (sub_cmd == 'L'))
4123                 {
4124                         if ((num % 2) || (num == max_num - 1))
4125                         {
4126                                 num--;
4127                         }
4128                         else if (num < max_num - 1)
4129                         {
4130                                 num++;
4131                         }
4132                 }
4133         }
4134
4135         screen_load();
4136         if (!inkey_next) inkey_next = "";
4137
4138         return (cmd);
4139 }
4140
4141 /*
4142  * Request a command from the user.
4143  *
4144  * Sets p_ptr->command_cmd, p_ptr->command_dir, p_ptr->command_rep,
4145  * p_ptr->command_arg.  May modify p_ptr->command_new.
4146  *
4147  * Note that "caret" ("^") is treated specially, and is used to
4148  * allow manual input of control characters.  This can be used
4149  * on many machines to request repeated tunneling (Ctrl-H) and
4150  * on the Macintosh to request "Control-Caret".
4151  *
4152  * Note that "backslash" is treated specially, and is used to bypass any
4153  * keymap entry for the following character.  This is useful for macros.
4154  *
4155  * Note that this command is used both in the dungeon and in
4156  * stores, and must be careful to work in both situations.
4157  *
4158  * Note that "p_ptr->command_new" may not work any more.  XXX XXX XXX
4159  */
4160 void request_command(int shopping)
4161 {
4162         int i;
4163
4164         char cmd;
4165         int mode;
4166
4167         cptr act;
4168
4169 #ifdef JP
4170         int caretcmd = 0;
4171 #endif
4172         /* Roguelike */
4173         if (rogue_like_commands)
4174         {
4175                 mode = KEYMAP_MODE_ROGUE;
4176         }
4177
4178         /* Original */
4179         else
4180         {
4181                 mode = KEYMAP_MODE_ORIG;
4182         }
4183
4184
4185         /* No command yet */
4186         command_cmd = 0;
4187
4188         /* No "argument" yet */
4189         command_arg = 0;
4190
4191         /* No "direction" yet */
4192         command_dir = 0;
4193
4194         use_menu = FALSE;
4195
4196
4197         /* Get command */
4198         while (1)
4199         {
4200                 /* Hack -- auto-commands */
4201                 if (command_new)
4202                 {
4203                         /* Flush messages */
4204                         msg_print(NULL);
4205
4206                         /* Use auto-command */
4207                         cmd = command_new;
4208
4209                         /* Forget it */
4210                         command_new = 0;
4211                 }
4212
4213                 /* Get a keypress in "command" mode */
4214                 else
4215                 {
4216                         /* Hack -- no flush needed */
4217                         msg_flag = FALSE;
4218                         num_more = 0;
4219
4220                         /* Activate "command mode" */
4221                         inkey_flag = TRUE;
4222
4223                         /* Get a command */
4224                         cmd = inkey();
4225
4226                         if (!shopping && command_menu && ((cmd == '\r') || (cmd == '\n') || (cmd == 'x') || (cmd == 'X'))
4227                             && !keymap_act[mode][(byte)(cmd)])
4228                                 cmd = inkey_from_menu();
4229                 }
4230
4231                 /* Clear top line */
4232                 prt("", 0, 0);
4233
4234
4235                 /* Command Count */
4236                 if (cmd == '0')
4237                 {
4238                         int old_arg = command_arg;
4239
4240                         /* Reset */
4241                         command_arg = 0;
4242
4243                         /* Begin the input */
4244 #ifdef JP
4245                         prt("²ó¿ô: ", 0, 0);
4246 #else
4247                         prt("Count: ", 0, 0);
4248 #endif
4249
4250
4251                         /* Get a command count */
4252                         while (1)
4253                         {
4254                                 /* Get a new keypress */
4255                                 cmd = inkey();
4256
4257                                 /* Simple editing (delete or backspace) */
4258                                 if ((cmd == 0x7F) || (cmd == KTRL('H')))
4259                                 {
4260                                         /* Delete a digit */
4261                                         command_arg = command_arg / 10;
4262
4263                                         /* Show current count */
4264 #ifdef JP
4265                                         prt(format("²ó¿ô: %d", command_arg), 0, 0);
4266 #else
4267                                         prt(format("Count: %d", command_arg), 0, 0);
4268 #endif
4269
4270                                 }
4271
4272                                 /* Actual numeric data */
4273                                 else if (cmd >= '0' && cmd <= '9')
4274                                 {
4275                                         /* Stop count at 9999 */
4276                                         if (command_arg >= 1000)
4277                                         {
4278                                                 /* Warn */
4279                                                 bell();
4280
4281                                                 /* Limit */
4282                                                 command_arg = 9999;
4283                                         }
4284
4285                                         /* Increase count */
4286                                         else
4287                                         {
4288                                                 /* Incorporate that digit */
4289                                                 command_arg = command_arg * 10 + D2I(cmd);
4290                                         }
4291
4292                                         /* Show current count */
4293 #ifdef JP
4294                                         prt(format("²ó¿ô: %d", command_arg), 0, 0);
4295 #else
4296                                         prt(format("Count: %d", command_arg), 0, 0);
4297 #endif
4298
4299                                 }
4300
4301                                 /* Exit on "unusable" input */
4302                                 else
4303                                 {
4304                                         break;
4305                                 }
4306                         }
4307
4308                         /* Hack -- Handle "zero" */
4309                         if (command_arg == 0)
4310                         {
4311                                 /* Default to 99 */
4312                                 command_arg = 99;
4313
4314                                 /* Show current count */
4315 #ifdef JP
4316                                 prt(format("²ó¿ô: %d", command_arg), 0, 0);
4317 #else
4318                                 prt(format("Count: %d", command_arg), 0, 0);
4319 #endif
4320
4321                         }
4322
4323                         /* Hack -- Handle "old_arg" */
4324                         if (old_arg != 0)
4325                         {
4326                                 /* Restore old_arg */
4327                                 command_arg = old_arg;
4328
4329                                 /* Show current count */
4330 #ifdef JP
4331 prt(format("²ó¿ô: %d", command_arg), 0, 0);
4332 #else
4333                                 prt(format("Count: %d", command_arg), 0, 0);
4334 #endif
4335
4336                         }
4337
4338                         /* Hack -- white-space means "enter command now" */
4339                         if ((cmd == ' ') || (cmd == '\n') || (cmd == '\r'))
4340                         {
4341                                 /* Get a real command */
4342 #ifdef JP
4343                                 if (!get_com("¥³¥Þ¥ó¥É: ", (char *)&cmd, FALSE))
4344 #else
4345                                 if (!get_com("Command: ", (char *)&cmd, FALSE))
4346 #endif
4347
4348                                 {
4349                                         /* Clear count */
4350                                         command_arg = 0;
4351
4352                                         /* Continue */
4353                                         continue;
4354                                 }
4355                         }
4356                 }
4357
4358
4359                 /* Allow "keymaps" to be bypassed */
4360                 if (cmd == '\\')
4361                 {
4362                         /* Get a real command */
4363 #ifdef JP
4364                         (void)get_com("¥³¥Þ¥ó¥É: ", (char *)&cmd, FALSE);
4365 #else
4366                         (void)get_com("Command: ", (char *)&cmd, FALSE);
4367 #endif
4368
4369
4370                         /* Hack -- bypass keymaps */
4371                         if (!inkey_next) inkey_next = "";
4372                 }
4373
4374
4375                 /* Allow "control chars" to be entered */
4376                 if (cmd == '^')
4377                 {
4378                         /* Get a new command and controlify it */
4379 #ifdef JP
4380                         if (get_com("CTRL: ", (char *)&cmd, FALSE)) cmd = KTRL(cmd);
4381 #else
4382                         if (get_com("Control: ", (char *)&cmd, FALSE)) cmd = KTRL(cmd);
4383 #endif
4384
4385                 }
4386
4387
4388                 /* Look up applicable keymap */
4389                 act = keymap_act[mode][(byte)(cmd)];
4390
4391                 /* Apply keymap if not inside a keymap already */
4392                 if (act && !inkey_next)
4393                 {
4394                         /* Install the keymap (limited buffer size) */
4395                         (void)strnfmt(request_command_buffer, 256, "%s", act);
4396
4397                         /* Start using the buffer */
4398                         inkey_next = request_command_buffer;
4399
4400                         /* Continue */
4401                         continue;
4402                 }
4403
4404
4405                 /* Paranoia */
4406                 if (!cmd) continue;
4407
4408
4409                 /* Use command */
4410                 command_cmd = (byte)cmd;
4411
4412                 /* Done */
4413                 break;
4414         }
4415
4416         /* Hack -- Auto-repeat certain commands */
4417         if (always_repeat && (command_arg <= 0))
4418         {
4419                 /* Hack -- auto repeat certain commands */
4420                 if (strchr("TBDoc+", command_cmd))
4421                 {
4422                         /* Repeat 99 times */
4423                         command_arg = 99;
4424                 }
4425         }
4426
4427         /* Shopping */
4428         if (shopping == 1)
4429         {
4430                 /* Convert */
4431                 switch (command_cmd)
4432                 {
4433                         /* Command "p" -> "purchase" (get) */
4434                 case 'p': command_cmd = 'g'; break;
4435
4436                         /* Command "m" -> "purchase" (get) */
4437                 case 'm': command_cmd = 'g'; break;
4438
4439                         /* Command "s" -> "sell" (drop) */
4440                 case 's': command_cmd = 'd'; break;
4441                 }
4442         }
4443
4444 #ifdef JP
4445         for (i = 0; i < 256; i++)
4446         {
4447                 cptr s;
4448                 if ((s = keymap_act[mode][i]) != NULL)
4449                 {
4450                         if (*s == command_cmd && *(s+1) == 0)
4451                         {
4452                                 caretcmd = i;
4453                                 break;
4454                         }
4455                 }
4456         }
4457         if (!caretcmd)
4458                 caretcmd = command_cmd;
4459 #endif
4460
4461 #ifdef JP
4462 #undef strchr
4463 #define strchr strchr_j
4464 #endif
4465
4466         /* Hack -- Scan equipment */
4467         for (i = INVEN_RARM; i < INVEN_TOTAL; i++)
4468         {
4469                 cptr s;
4470
4471                 object_type *o_ptr = &inventory[i];
4472
4473                 /* Skip non-objects */
4474                 if (!o_ptr->k_idx) continue;
4475
4476                 /* No inscription */
4477                 if (!o_ptr->inscription) continue;
4478
4479                 /* Obtain the inscription */
4480                 s = quark_str(o_ptr->inscription);
4481
4482                 /* Find a '^' */
4483                 s = strchr(s, '^');
4484
4485                 /* Process preventions */
4486                 while (s)
4487                 {
4488                         /* Check the "restriction" character */
4489 #ifdef JP
4490                         if ((s[1] == caretcmd) || (s[1] == '*'))
4491 #else
4492                         if ((s[1] == command_cmd) || (s[1] == '*'))
4493 #endif
4494
4495                         {
4496                                 /* Hack -- Verify command */
4497 #ifdef JP
4498                                 if (!get_check("ËÜÅö¤Ç¤¹¤«? "))
4499 #else
4500                                 if (!get_check("Are you sure? "))
4501 #endif
4502
4503                                 {
4504                                         /* Hack -- Use space */
4505                                         command_cmd = ' ';
4506                                 }
4507                         }
4508
4509                         /* Find another '^' */
4510                         s = strchr(s + 1, '^');
4511                 }
4512         }
4513
4514
4515         /* Hack -- erase the message line. */
4516         prt("", 0, 0);
4517 }
4518
4519
4520
4521 /*
4522  * Check a char for "vowel-hood"
4523  */
4524 bool is_a_vowel(int ch)
4525 {
4526         switch (ch)
4527         {
4528         case 'a':
4529         case 'e':
4530         case 'i':
4531         case 'o':
4532         case 'u':
4533         case 'A':
4534         case 'E':
4535         case 'I':
4536         case 'O':
4537         case 'U':
4538                 return (TRUE);
4539         }
4540
4541         return (FALSE);
4542 }
4543
4544
4545
4546 #if 0
4547
4548 /*
4549  * Replace the first instance of "target" in "buf" with "insert"
4550  * If "insert" is NULL, just remove the first instance of "target"
4551  * In either case, return TRUE if "target" is found.
4552  *
4553  * XXX Could be made more efficient, especially in the
4554  * case where "insert" is smaller than "target".
4555  */
4556 static bool insert_str(char *buf, cptr target, cptr insert)
4557 {
4558         int   i, len;
4559         int                b_len, t_len, i_len;
4560
4561         /* Attempt to find the target (modify "buf") */
4562         buf = strstr(buf, target);
4563
4564         /* No target found */
4565         if (!buf) return (FALSE);
4566
4567         /* Be sure we have an insertion string */
4568         if (!insert) insert = "";
4569
4570         /* Extract some lengths */
4571         t_len = strlen(target);
4572         i_len = strlen(insert);
4573         b_len = strlen(buf);
4574
4575         /* How much "movement" do we need? */
4576         len = i_len - t_len;
4577
4578         /* We need less space (for insert) */
4579         if (len < 0)
4580         {
4581                 for (i = t_len; i < b_len; ++i) buf[i+len] = buf[i];
4582         }
4583
4584         /* We need more space (for insert) */
4585         else if (len > 0)
4586         {
4587                 for (i = b_len-1; i >= t_len; --i) buf[i+len] = buf[i];
4588         }
4589
4590         /* If movement occured, we need a new terminator */
4591         if (len) buf[b_len+len] = '\0';
4592
4593         /* Now copy the insertion string */
4594         for (i = 0; i < i_len; ++i) buf[i] = insert[i];
4595
4596         /* Successful operation */
4597         return (TRUE);
4598 }
4599
4600
4601 #endif
4602
4603
4604 /*
4605  * GH
4606  * Called from cmd4.c and a few other places. Just extracts
4607  * a direction from the keymap for ch (the last direction,
4608  * in fact) byte or char here? I'm thinking that keymaps should
4609  * generally only apply to single keys, which makes it no more
4610  * than 128, so a char should suffice... but keymap_act is 256...
4611  */
4612 int get_keymap_dir(char ch)
4613 {
4614         int d = 0;
4615
4616         /* Already a direction? */
4617         if (isdigit(ch))
4618         {
4619                 d = D2I(ch);
4620         }
4621         else
4622         {
4623                 int mode;
4624                 cptr act, s;
4625
4626                 /* Roguelike */
4627                 if (rogue_like_commands)
4628                 {
4629                         mode = KEYMAP_MODE_ROGUE;
4630                 }
4631
4632                 /* Original */
4633                 else
4634                 {
4635                         mode = KEYMAP_MODE_ORIG;
4636                 }
4637
4638                 /* Extract the action (if any) */
4639                 act = keymap_act[mode][(byte)(ch)];
4640
4641                 /* Analyze */
4642                 if (act)
4643                 {
4644                         /* Convert to a direction */
4645                         for (s = act; *s; ++s)
4646                         {
4647                                 /* Use any digits in keymap */
4648                                 if (isdigit(*s)) d = D2I(*s);
4649                         }
4650                 }
4651         }
4652
4653         /* Paranoia */
4654         if (d == 5) d = 0;
4655
4656         /* Return direction */
4657         return (d);
4658 }
4659
4660
4661 #ifdef ALLOW_REPEAT /* TNB */
4662
4663 #define REPEAT_MAX              20
4664
4665 /* Number of chars saved */
4666 static int repeat__cnt = 0;
4667
4668 /* Current index */
4669 static int repeat__idx = 0;
4670
4671 /* Saved "stuff" */
4672 static int repeat__key[REPEAT_MAX];
4673
4674
4675 void repeat_push(int what)
4676 {
4677         /* Too many keys */
4678         if (repeat__cnt == REPEAT_MAX) return;
4679
4680         /* Push the "stuff" */
4681         repeat__key[repeat__cnt++] = what;
4682
4683         /* Prevents us from pulling keys */
4684         ++repeat__idx;
4685 }
4686
4687
4688 bool repeat_pull(int *what)
4689 {
4690         /* All out of keys */
4691         if (repeat__idx == repeat__cnt) return (FALSE);
4692
4693         /* Grab the next key, advance */
4694         *what = repeat__key[repeat__idx++];
4695
4696         /* Success */
4697         return (TRUE);
4698 }
4699
4700 void repeat_check(void)
4701 {
4702         int             what;
4703
4704         /* Ignore some commands */
4705         if (command_cmd == ESCAPE) return;
4706         if (command_cmd == ' ') return;
4707         if (command_cmd == '\r') return;
4708         if (command_cmd == '\n') return;
4709
4710         /* Repeat Last Command */
4711         if (command_cmd == 'n')
4712         {
4713                 /* Reset */
4714                 repeat__idx = 0;
4715
4716                 /* Get the command */
4717                 if (repeat_pull(&what))
4718                 {
4719                         /* Save the command */
4720                         command_cmd = what;
4721                 }
4722         }
4723
4724         /* Start saving new command */
4725         else
4726         {
4727                 /* Reset */
4728                 repeat__cnt = 0;
4729                 repeat__idx = 0;
4730
4731                 what = command_cmd;
4732
4733                 /* Save this command */
4734                 repeat_push(what);
4735         }
4736 }
4737
4738 #endif /* ALLOW_REPEAT -- TNB */
4739
4740
4741 #ifdef SORT_R_INFO
4742
4743 /*
4744  * Array size for which InsertionSort
4745  * is used instead of QuickSort
4746  */
4747 #define CUTOFF 4
4748
4749
4750 /*
4751  * Exchange two sort-entries
4752  * (should probably be coded inline
4753  * for speed increase)
4754  */
4755 static void swap(tag_type *a, tag_type *b)
4756 {
4757         tag_type temp;
4758
4759         temp.tag = a->tag;
4760         temp.pointer = a->pointer;
4761
4762         a->tag = b->tag;
4763         a->pointer = b->pointer;
4764
4765         b->tag = temp.tag;
4766         b->pointer = temp.pointer;
4767 }
4768
4769
4770 /*
4771  * Insertion-Sort algorithm
4772  * (used by the Quicksort algorithm)
4773  */
4774 static void InsertionSort(tag_type elements[], int number)
4775 {
4776         int j, P;
4777
4778         tag_type tmp;
4779
4780         for (P = 1; P < number; P++)
4781         {
4782                 tmp = elements[P];
4783                 for (j = P; (j > 0) && (elements[j - 1].tag > tmp.tag); j--)
4784                         elements[j] = elements[j - 1];
4785                 elements[j] = tmp;
4786         }
4787 }
4788
4789
4790 /*
4791  * Helper function for Quicksort
4792  */
4793 static tag_type median3(tag_type elements[], int left, int right)
4794 {
4795         int center = (left + right) / 2;
4796
4797         if (elements[left].tag > elements[center].tag)
4798                 swap(&elements[left], &elements[center]);
4799         if (elements[left].tag > elements[right].tag)
4800                 swap(&elements[left], &elements[right]);
4801         if (elements[center].tag > elements[right].tag)
4802                 swap(&elements[center], &elements[right]);
4803
4804         swap(&elements[center], &elements[right - 1]);
4805         return (elements[right - 1]);
4806 }
4807
4808
4809 /*
4810  * Quicksort algorithm
4811  *
4812  * The "median of three" pivot selection eliminates
4813  * the bad case of already sorted input.
4814  *
4815  * We use InsertionSort for smaller sub-arrays,
4816  * because it is faster in this case.
4817  *
4818  * For details see: "Data Structures and Algorithm
4819  * Analysis in C" by Mark Allen Weiss.
4820  */
4821 static void quicksort(tag_type elements[], int left, int right)
4822 {
4823         int i, j;
4824         tag_type pivot;
4825
4826         if (left + CUTOFF <= right)
4827         {
4828                 pivot = median3(elements, left, right);
4829
4830                 i = left; j = right -1;
4831
4832                 while (TRUE)
4833                 {
4834                         while (elements[++i].tag < pivot.tag);
4835                         while (elements[--j].tag > pivot.tag);
4836
4837                         if (i < j)
4838                                 swap(&elements[i], &elements[j]);
4839                         else
4840                                 break;
4841                 }
4842
4843                 /* Restore pivot */
4844                 swap(&elements[i], &elements[right - 1]);
4845
4846                 quicksort(elements, left, i - 1);
4847                 quicksort(elements, i + 1, right);
4848         }
4849         else
4850         {
4851                 /* Use InsertionSort on small arrays */
4852                 InsertionSort(elements + left, right - left + 1);
4853         }
4854 }
4855
4856
4857 /*
4858  * Frontend for the sorting algorithm
4859  *
4860  * Sorts an array of tagged pointers
4861  * with <number> elements.
4862  */
4863 void tag_sort(tag_type elements[], int number)
4864 {
4865         quicksort(elements, 0, number - 1);
4866 }
4867
4868 #endif /* SORT_R_INFO */
4869
4870 #ifdef SUPPORT_GAMMA
4871
4872 /* Table of gamma values */
4873 byte gamma_table[256];
4874
4875 /* Table of ln(x/256) * 256 for x going from 0 -> 255 */
4876 static s16b gamma_helper[256] =
4877 {
4878 0,-1420,-1242,-1138,-1065,-1007,-961,-921,-887,-857,-830,-806,-783,-762,-744,-726,
4879 -710,-694,-679,-666,-652,-640,-628,-617,-606,-596,-586,-576,-567,-577,-549,-541,
4880 -532,-525,-517,-509,-502,-495,-488,-482,-475,-469,-463,-457,-451,-455,-439,-434,
4881 -429,-423,-418,-413,-408,-403,-398,-394,-389,-385,-380,-376,-371,-367,-363,-359,
4882 -355,-351,-347,-343,-339,-336,-332,-328,-325,-321,-318,-314,-311,-308,-304,-301,
4883 -298,-295,-291,-288,-285,-282,-279,-276,-273,-271,-268,-265,-262,-259,-257,-254,
4884 -251,-248,-246,-243,-241,-238,-236,-233,-231,-228,-226,-223,-221,-219,-216,-214,
4885 -212,-209,-207,-205,-203,-200,-198,-196,-194,-192,-190,-188,-186,-184,-182,-180,
4886 -178,-176,-174,-172,-170,-168,-166,-164,-162,-160,-158,-156,-155,-153,-151,-149,
4887 -147,-146,-144,-142,-140,-139,-137,-135,-134,-132,-130,-128,-127,-125,-124,-122,
4888 -120,-119,-117,-116,-114,-112,-111,-109,-108,-106,-105,-103,-102,-100,-99,-97,
4889 -96,-95,-93,-92,-90,-89,-87,-86,-85,-83,-82,-80,-79,-78,-76,-75,
4890 -74,-72,-71,-70,-68,-67,-66,-65,-63,-62,-61,-59,-58,-57,-56,-54,
4891 -53,-52,-51,-50,-48,-47,-46,-45,-44,-42,-41,-40,-39,-38,-37,-35,
4892 -34,-33,-32,-31,-30,-29,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,
4893 -17,-16,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1
4894 };
4895
4896
4897 /* 
4898  * Build the gamma table so that floating point isn't needed.
4899  * 
4900  * Note gamma goes from 0->256.  The old value of 100 is now 128.
4901  */
4902 void build_gamma_table(int gamma)
4903 {
4904         int i, n;
4905         
4906         /*
4907          * value is the current sum.
4908          * diff is the new term to add to the series.
4909          */
4910         long value, diff;
4911         
4912         /* Hack - convergence is bad in these cases. */
4913         gamma_table[0] = 0;
4914         gamma_table[255] = 255;
4915         
4916         for (i = 1; i < 255; i++)
4917         {
4918                 /* 
4919                  * Initialise the Taylor series
4920                  *
4921                  * value and diff have been scaled by 256
4922                  */
4923                 
4924                 n = 1;
4925                 value = 256 * 256;
4926                 diff = ((long)gamma_helper[i]) * (gamma - 256);
4927                 
4928                 while (diff)
4929                 {
4930                         value += diff;
4931                         n++;
4932                         
4933                         
4934                         /*
4935                          * Use the following identiy to calculate the gamma table.
4936                          * exp(x) = 1 + x + x^2/2 + x^3/(2*3) + x^4/(2*3*4) +...
4937                          *
4938                          * n is the current term number.
4939                          * 
4940                          * The gamma_helper array contains a table of
4941                          * ln(x/256) * 256
4942                          * This is used because a^b = exp(b*ln(a))
4943                          *
4944                          * In this case:
4945                          * a is i / 256
4946                          * b is gamma.
4947                          *
4948                          * Note that everything is scaled by 256 for accuracy,
4949                          * plus another factor of 256 for the final result to
4950                          * be from 0-255.  Thus gamma_helper[] * gamma must be
4951                          * divided by 256*256 each itteration, to get back to
4952                          * the original power series.
4953                          */
4954                         diff = (((diff / 256) * gamma_helper[i]) * (gamma - 256)) / (256 * n);
4955                 }
4956                 
4957                 /* 
4958                  * Store the value in the table so that the
4959                  * floating point pow function isn't needed .
4960                  */
4961                 gamma_table[i] = ((long)(value / 256) * i) / 256;
4962         }
4963 }
4964
4965 #endif /* SUPPORT_GAMMA */
4966
4967
4968 /*
4969  * Add a series of keypresses to the "queue".
4970  *
4971  * Return any errors generated by Term_keypress() in doing so, or SUCCESS
4972  * if there are none.
4973  *
4974  * Catch the "out of space" error before anything is printed.
4975  *
4976  * NB: The keys added here will be interpreted by any macros or keymaps.
4977  */
4978 errr type_string(cptr str, uint len)
4979 {
4980         errr err = 0;
4981         cptr s;
4982
4983         term *old = Term;
4984
4985         /* Paranoia - no string. */
4986         if (!str) return -1;
4987
4988         /* Hack - calculate the string length here if none given. */
4989         if (!len) len = strlen(str);
4990
4991         /* Activate the main window, as all pastes go there. */
4992         Term_activate(term_screen);
4993
4994         for (s = str; s < str+len; s++)
4995         {
4996                 /* Catch end of string */
4997                 if (*s == '\0') break;
4998
4999                 err = Term_keypress(*s);
5000
5001                 /* Catch errors */
5002                 if (err) break;
5003         }
5004
5005         /* Activate the original window. */
5006         Term_activate(old);
5007
5008         return err;
5009 }
5010
5011
5012
5013 void roff_to_buf(cptr str, int maxlen, char *tbuf, size_t bufsize)
5014 {
5015         int read_pt = 0;
5016         int write_pt = 0;
5017         int line_len = 0;
5018         int word_punct = 0;
5019         char ch[3];
5020         ch[2] = '\0';
5021
5022         while (str[read_pt])
5023         {
5024 #ifdef JP
5025                 bool kinsoku = FALSE;
5026                 bool kanji;
5027 #endif
5028                 int ch_len = 1;
5029
5030                 /* Prepare one character */
5031                 ch[0] = str[read_pt];
5032                 ch[1] = '\0';
5033 #ifdef JP
5034                 kanji  = iskanji(ch[0]);
5035
5036                 if (kanji)
5037                 {
5038                         ch[1] = str[read_pt+1];
5039                         ch_len = 2;
5040
5041                         if (strcmp(ch, "¡£") == 0 ||
5042                             strcmp(ch, "¡¢") == 0 ||
5043                             strcmp(ch, "¥£") == 0 ||
5044                             strcmp(ch, "¡¼") == 0)
5045                                 kinsoku = TRUE;
5046                 }
5047                 else if (!isprint(ch[0]))
5048                         ch[0] = ' ';
5049 #else
5050                 if (!isprint(ch[0]))
5051                         ch[0] = ' ';
5052 #endif
5053
5054                 if (line_len + ch_len > maxlen - 1 || str[read_pt] == '\n')
5055                 {
5056                         int word_len;
5057
5058                         /* return to better wrapping point. */
5059                         /* Space character at the end of the line need not to be printed. */
5060                         word_len = read_pt - word_punct;
5061 #ifdef JP
5062                         if (kanji && !kinsoku)
5063                                 /* nothing */ ;
5064                         else
5065 #endif
5066                         if (ch[0] == ' ' || word_len >= line_len/2)
5067                                 read_pt++;
5068                         else
5069                         {
5070                                 read_pt = word_punct;
5071                                 if (str[word_punct] == ' ')
5072                                         read_pt++;
5073                                 write_pt -= word_len;
5074                         }
5075
5076                         tbuf[write_pt++] = '\0';
5077                         line_len = 0;
5078                         word_punct = read_pt;
5079                         continue;
5080                 }
5081                 if (ch[0] == ' ')
5082                         word_punct = read_pt;
5083 #ifdef JP
5084                 if (!kinsoku) word_punct = read_pt;
5085 #endif
5086
5087                 /* Not enough buffer size */
5088                 if ((size_t)(write_pt + 3) >= bufsize) break;
5089
5090                 tbuf[write_pt++] = ch[0];
5091                 line_len++;
5092                 read_pt++;
5093 #ifdef JP
5094                 if (kanji)
5095                 {
5096                         tbuf[write_pt++] = ch[1];
5097                         line_len++;
5098                         read_pt++;
5099                 }
5100 #endif
5101         }
5102         tbuf[write_pt] = '\0';
5103         tbuf[write_pt+1] = '\0';
5104
5105         return;
5106 }
5107
5108
5109 /*
5110  * The my_strcpy() function copies up to 'bufsize'-1 characters from 'src'
5111  * to 'buf' and NUL-terminates the result.  The 'buf' and 'src' strings may
5112  * not overlap.
5113  *
5114  * my_strcpy() returns strlen(src).  This makes checking for truncation
5115  * easy.  Example: if (my_strcpy(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
5116  *
5117  * This function should be equivalent to the strlcpy() function in BSD.
5118  */
5119 size_t my_strcpy(char *buf, const char *src, size_t bufsize)
5120 {
5121 #ifdef JP
5122
5123         char *d = buf;
5124         const char *s = src;
5125         size_t len = 0;
5126
5127         /* reserve for NUL termination */
5128         bufsize--;
5129
5130         /* Copy as many bytes as will fit */
5131         while (len < bufsize)
5132         {
5133                 if (iskanji(*s))
5134                 {
5135                         if (len + 1 >= bufsize || !*(s+1)) break;
5136                         *d++ = *s++;
5137                         *d++ = *s++;
5138                         len += 2;
5139                 }
5140                 else
5141                 {
5142                         *d++ = *s++;
5143                         len++;
5144                 }
5145         }
5146         *d = '\0';
5147         while(*s++) len++;
5148
5149         return len;
5150
5151 #else
5152
5153         size_t len = strlen(src);
5154         size_t ret = len;
5155
5156         /* Paranoia */
5157         if (bufsize == 0) return ret;
5158
5159         /* Truncate */
5160         if (len >= bufsize) len = bufsize - 1;
5161
5162         /* Copy the string and terminate it */
5163         (void)memcpy(buf, src, len);
5164         buf[len] = '\0';
5165
5166         /* Return strlen(src) */
5167         return ret;
5168
5169 #endif
5170 }
5171
5172
5173 /*
5174  * The my_strcat() tries to append a string to an existing NUL-terminated string.
5175  * It never writes more characters into the buffer than indicated by 'bufsize' and
5176  * NUL-terminates the buffer.  The 'buf' and 'src' strings may not overlap.
5177  *
5178  * my_strcat() returns strlen(buf) + strlen(src).  This makes checking for
5179  * truncation easy.  Example:
5180  * if (my_strcat(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
5181  *
5182  * This function should be equivalent to the strlcat() function in BSD.
5183  */
5184 size_t my_strcat(char *buf, const char *src, size_t bufsize)
5185 {
5186         size_t dlen = strlen(buf);
5187
5188         /* Is there room left in the buffer? */
5189         if (dlen < bufsize - 1)
5190         {
5191                 /* Append as much as possible  */
5192                 return (dlen + my_strcpy(buf + dlen, src, bufsize - dlen));
5193         }
5194         else
5195         {
5196                 /* Return without appending */
5197                 return (dlen + strlen(src));
5198         }
5199 }
5200
5201
5202 /*
5203  * Get a keypress from the user.
5204  * And interpret special keys as internal code.
5205  *
5206  * This function is a Mega-Hack and depend on pref-xxx.prf's.
5207  * Currently works on Linux(UNIX), Windows, and Macintosh only.
5208  */
5209 int inkey_special(void)
5210 {
5211         static const struct {
5212                 cptr keyname;
5213                 int keyflag;
5214         } modifier_key_list[] = {
5215                 {"shift-", SKEY_MOD_SHIFT},
5216                 {"control-", SKEY_MOD_CONTROL},
5217                 {NULL, 0},
5218         };
5219
5220         static const struct {
5221                 cptr keyname;
5222                 int keycode;
5223         } special_key_list[] = {
5224                 {"Down]", SKEY_DOWN},
5225                 {"Left]", SKEY_LEFT},
5226                 {"Right]", SKEY_RIGHT},
5227                 {"Up]", SKEY_UP},
5228                 {"Page_Up]", SKEY_PGUP},
5229                 {"Page_Down]", SKEY_PGDOWN},
5230                 {"Home]", SKEY_TOP},
5231                 {"End]", SKEY_BOTTOM},
5232                 {"KP_Down]", SKEY_DOWN},
5233                 {"KP_Left]", SKEY_LEFT},
5234                 {"KP_Right]", SKEY_RIGHT},
5235                 {"KP_Up]", SKEY_UP},
5236                 {"KP_Page_Up]", SKEY_PGUP},
5237                 {"KP_Page_Down]", SKEY_PGDOWN},
5238                 {"KP_Home]", SKEY_TOP},
5239                 {"KP_End]", SKEY_BOTTOM},
5240                 {"KP_2]", SKEY_DOWN},
5241                 {"KP_4]", SKEY_LEFT},
5242                 {"KP_6]", SKEY_RIGHT},
5243                 {"KP_8]", SKEY_UP},
5244                 {"KP_9]", SKEY_PGUP},
5245                 {"KP_3]", SKEY_PGDOWN},
5246                 {"KP_7]", SKEY_TOP},
5247                 {"KP_1]", SKEY_BOTTOM},
5248                 {NULL, 0},
5249         };
5250         char buf[1024];
5251         cptr str = buf;
5252         char key;
5253         int skey = 0;
5254         int modifier = 0;
5255         int i;
5256         size_t trig_len;
5257
5258         /* Get a keypress */
5259         key = inkey();
5260
5261         /* Examine trigger string */
5262         trig_len = strlen(inkey_macro_trigger_string);
5263
5264         /* No special key */
5265         if (!trig_len) return (0xff & (int)key);
5266
5267         /*
5268          * Mega Hack -- ignore macro defined on ASCII keys
5269          *
5270          * When this function is used, all ASCII keys are used as
5271          * themselfs instead of macro triggers for command macro's.
5272          */
5273         if (trig_len == 1)
5274         {
5275                 /* Get original key */
5276                 key = inkey_macro_trigger_string[0];
5277
5278 #ifdef JP
5279                 if (!iskanji(key))
5280 #endif
5281                 {
5282                         /* Kill further macro expansion */
5283                         flush();
5284                 }
5285
5286                 /* Return the originaly pressed key */
5287                 return (0xff & (int)key);
5288         }
5289
5290         /* Convert the trigger */
5291         ascii_to_text(buf, inkey_macro_trigger_string);
5292
5293         /* Check the prefix "\[" */
5294         if (!prefix(str, "\\[")) return 0;
5295
5296         /* Skip "\[" */
5297         str += 2;
5298
5299         /* Examine modifier keys */
5300         while (TRUE)
5301         {
5302                 for (i = 0; modifier_key_list[i].keyname; i++)
5303                 {
5304                         if (prefix(str, modifier_key_list[i].keyname))
5305                         {
5306                                 /* Get modifier key flag */
5307                                 str += strlen(modifier_key_list[i].keyname);
5308                                 modifier |= modifier_key_list[i].keyflag;
5309                         }
5310                 }
5311
5312                 /* No more modifier key found */
5313                 if (!modifier_key_list[i].keyname) break;
5314         }
5315
5316         /* Get a special key code */
5317         for (i = 0; special_key_list[i].keyname; i++)
5318         {
5319                 if (streq(str, special_key_list[i].keyname))
5320                 {
5321                         skey = special_key_list[i].keycode;
5322                         break;
5323                 }
5324         }
5325
5326         /* No special key found? */
5327         if (!skey)
5328         {
5329                 /* Don't bother with this trigger no more */
5330                 inkey_macro_trigger_string[0] = '\0';
5331
5332                 /* Return normal keycode */
5333                 return (0xff & (int)key);
5334         }
5335
5336         /* A special key found */
5337
5338         /* Kill further macro expansion */
5339         flush();
5340
5341         /* Return special key code and modifier flags */
5342         return (skey | modifier);
5343 }