OSDN Git Service

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