OSDN Git Service

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