OSDN Git Service

BCC++ 5.5.1で警告封じオプション -w- を外した場合のコンパイル警告の除去.
[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         prt("", row, 0);
3553 #ifdef JP
3554         put_str("[ ²¿¤«¥­¡¼¤ò²¡¤·¤Æ²¼¤µ¤¤ ]", row, 26);
3555 #else
3556         put_str("[Press any key to continue]", row, 23);
3557 #endif
3558
3559         (void)inkey();
3560         prt("", row, 0);
3561 }
3562
3563
3564 /*
3565  * Hack -- special buffer to hold the action of the current keymap
3566  */
3567 static char request_command_buffer[256];
3568
3569
3570
3571 typedef struct
3572 {
3573         cptr name;
3574         byte cmd;
3575         bool fin;
3576 } menu_naiyou;
3577
3578 #ifdef JP
3579 menu_naiyou menu_info[10][10] =
3580 {
3581         {
3582                 {"ËâË¡/ÆüìǽÎÏ", 1, FALSE},
3583                 {"¹ÔÆ°", 2, FALSE},
3584                 {"Æ»¶ñ(»ÈÍÑ)", 3, FALSE},
3585                 {"Æ»¶ñ(¤½¤Î¾)", 4, FALSE},
3586                 {"ÁõÈ÷", 5, FALSE},
3587                 {"Èâ/È¢", 6, FALSE},
3588                 {"¾ðÊó", 7, FALSE},
3589                 {"ÀßÄê", 8, FALSE},
3590                 {"¤½¤Î¾", 9, FALSE},
3591                 {"", 0, FALSE},
3592         },
3593
3594         {
3595                 {"»È¤¦(m)", 'm', TRUE},
3596                 {"Ä´¤Ù¤ë(b/P)", 'b', TRUE},
3597                 {"³Ð¤¨¤ë(G)", 'G', TRUE},
3598                 {"ÆüìǽÎϤò»È¤¦(U/O)", 'U', TRUE},
3599                 {"", 0, FALSE},
3600                 {"", 0, FALSE},
3601                 {"", 0, FALSE},
3602                 {"", 0, FALSE},
3603                 {"", 0, FALSE},
3604                 {"", 0, FALSE}
3605         },
3606
3607         {
3608                 {"µÙ©¤¹¤ë(R)", 'R', TRUE},
3609                 {"¥È¥é¥Ã¥×²ò½ü(D)", 'D', TRUE},
3610                 {"õ¤¹(s)", 's', TRUE},
3611                 {"¼þ¤ê¤òÄ´¤Ù¤ë(l/x)", 'l', TRUE},
3612                 {"¥¿¡¼¥²¥Ã¥È»ØÄê(*)", '*', TRUE},
3613                 {"·ê¤ò·¡¤ë(T/^t)", 'T', TRUE},
3614                 {"³¬Ãʤò¾å¤ë(<)", '<', TRUE},
3615                 {"³¬Ãʤò²¼¤ê¤ë(>)", '>', TRUE},
3616                 {"¥Ú¥Ã¥È¤ËÌ¿Î᤹¤ë(p)", 'p', TRUE},
3617                 {"õº÷¥â¡¼¥É¤ÎON/OFF(S/#)", 'S', TRUE}
3618         },
3619
3620         {
3621                 {"Æɤà(r)", 'r', TRUE},
3622                 {"°û¤à(q)", 'q', TRUE},
3623                 {"¾ó¤ò»È¤¦(u/Z)", 'u', TRUE},
3624                 {"ËâË¡ËÀ¤ÇÁÀ¤¦(a/z)", 'a', TRUE},
3625                 {"¥í¥Ã¥É¤ò¿¶¤ë(z/a)", 'z', TRUE},
3626                 {"»ÏÆ°¤¹¤ë(A)", 'A', TRUE},
3627                 {"¿©¤Ù¤ë(E)", 'E', TRUE},
3628                 {"Èô¤ÓÆ»¶ñ¤Ç·â¤Ä(f/t)", 'f', TRUE},
3629                 {"Åꤲ¤ë(v)", 'v', TRUE},
3630                 {"", 0, FALSE}
3631         },
3632
3633         {
3634                 {"½¦¤¦(g)", 'g', TRUE},
3635                 {"Íî¤È¤¹(d)", 'd', TRUE},
3636                 {"²õ¤¹(k/^d)", 'k', TRUE},
3637                 {"Ìäò¹ï¤à({)", '{', TRUE},
3638                 {"Ìäò¾Ã¤¹(})", '}', TRUE},
3639                 {"Ä´ºº(I)", 'I', TRUE},
3640                 {"¥¢¥¤¥Æ¥à°ìÍ÷(i)", 'i', TRUE},
3641                 {"", 0, FALSE},
3642                 {"", 0, FALSE},
3643                 {"", 0, FALSE}
3644         },
3645
3646         {
3647                 {"ÁõÈ÷¤¹¤ë(w)", 'w', TRUE},
3648                 {"ÁõÈ÷¤ò³°¤¹(t/T)", 't', TRUE},
3649                 {"dzÎÁ¤òÊäµë(F)", 'F', TRUE},
3650                 {"ÁõÈ÷°ìÍ÷(e)", 'e', TRUE},
3651                 {"", 0, FALSE},
3652                 {"", 0, FALSE},
3653                 {"", 0, FALSE},
3654                 {"", 0, FALSE},
3655                 {"", 0, FALSE},
3656                 {"", 0, FALSE}
3657         },
3658
3659         {
3660                 {"³«¤±¤ë(o)", 'o', TRUE},
3661                 {"ÊĤ¸¤ë(c)", 'c', TRUE},
3662                 {"ÂÎÅö¤¿¤ê¤¹¤ë(B/f)", 'B', TRUE},
3663                 {"¤¯¤µ¤Ó¤òÂǤÄ(j/S)", 'j', TRUE},
3664                 {"", 0, FALSE},
3665                 {"", 0, FALSE},
3666                 {"", 0, FALSE},
3667                 {"", 0, FALSE},
3668                 {"", 0, FALSE},
3669                 {"", 0, FALSE}
3670         },
3671
3672         {
3673                 {"¥À¥ó¥¸¥ç¥ó¤ÎÁ´ÂοÞ(M)", 'M', TRUE},
3674                 {"°ÌÃÖ¤ò³Îǧ(L/W)", 'L', TRUE},
3675                 {"³¬¤ÎÊ·°Ïµ¤(^f)", KTRL('F'), TRUE},
3676                 {"¥¹¥Æ¡¼¥¿¥¹(C)", 'C', TRUE},
3677                 {"ʸ»ú¤ÎÀâÌÀ(/)", '/', TRUE},
3678                 {"¥á¥Ã¥»¡¼¥¸ÍúÎò(^p)", KTRL('P'), TRUE},
3679                 {"¸½ºß¤Î»þ¹ï(^t/')", KTRL('T'), TRUE},
3680                 {"¸½ºß¤ÎÃμ±(~)", '~', TRUE},
3681                 {"¥×¥ì¥¤µ­Ï¿(|)", '|', TRUE},
3682                 {"", 0, FALSE}
3683         },
3684
3685         {
3686                 {"¥ª¥×¥·¥ç¥ó(=)", '=', TRUE},
3687                 {"¥Þ¥¯¥í(@)", '@', TRUE},
3688                 {"²èÌÌɽ¼¨(%)", '%', TRUE},
3689                 {"¥«¥é¡¼(&)", '&', TRUE},
3690                 {"ÀßÄêÊѹ¹¥³¥Þ¥ó¥É(\")", '\"', TRUE},
3691                 {"¼«Æ°½¦¤¤¤ò¥í¡¼¥É($)", '$', TRUE},
3692                 {"¥·¥¹¥Æ¥à(!)", '!', TRUE},
3693                 {"", 0, FALSE},
3694                 {"", 0, FALSE},
3695                 {"", 0, FALSE}
3696         },
3697
3698         {
3699                 {"¥»¡¼¥Ö&ÃæÃÇ(^x)", KTRL('X'), TRUE},
3700                 {"¥»¡¼¥Ö(^s)", KTRL('S'), TRUE},
3701                 {"¥Ø¥ë¥×(?)", '?', TRUE},
3702                 {"ºÆÉÁ²è(^r)", KTRL('R'), TRUE},
3703                 {"¥á¥â(:)", ':', TRUE},
3704                 {"µ­Ç°»£±Æ())", ')', TRUE},
3705                 {"µ­Ç°»£±Æ¤Îɽ¼¨(()", '(', TRUE},
3706                 {"¥Ð¡¼¥¸¥ç¥ó¾ðÊó(V)", 'V', TRUE},
3707                 {"°úÂह¤ë(Q)", 'Q', TRUE},
3708                 {"", 0, FALSE}
3709         },
3710 };
3711 #else
3712 menu_naiyou menu_info[10][10] =
3713 {
3714         {
3715                 {"Magic/Special", 1, FALSE},
3716                 {"Action", 2, FALSE},
3717                 {"Items(use)", 3, FALSE},
3718                 {"Items(other)", 4, FALSE},
3719                 {"Equip", 5, FALSE},
3720                 {"Door/Box", 6, FALSE},
3721                 {"Infomations", 7, FALSE},
3722                 {"Options", 8, FALSE},
3723                 {"Other commands", 9, FALSE},
3724                 {"", 0, FALSE},
3725         },
3726
3727         {
3728                 {"Use(m)", 'm', TRUE},
3729                 {"See tips(b/P)", 'b', TRUE},
3730                 {"Study(G)", 'G', TRUE},
3731                 {"Special abilities(U/O)", 'U', TRUE},
3732                 {"", 0, FALSE},
3733                 {"", 0, FALSE},
3734                 {"", 0, FALSE},
3735                 {"", 0, FALSE},
3736                 {"", 0, FALSE},
3737                 {"", 0, FALSE}
3738         },
3739
3740         {
3741                 {"Rest(R)", 'R', TRUE},
3742                 {"Disarm a trap(D)", 'D', TRUE},
3743                 {"Search(s)", 's', TRUE},
3744                 {"Look(l/x)", 'l', TRUE},
3745                 {"Target(*)", '*', TRUE},
3746                 {"Dig(T/^t)", 'T', TRUE},
3747                 {"Go up stairs(<)", '<', TRUE},
3748                 {"Go down staies(>)", '>', TRUE},
3749                 {"Command pets(p)", 'p', TRUE},
3750                 {"Search mode ON/OFF(S/#)", 'S', TRUE}
3751         },
3752
3753         {
3754                 {"Read a scroll(r)", 'r', TRUE},
3755                 {"Drink a potion(q)", 'q', TRUE},
3756                 {"Use a staff(u/Z)", 'u', TRUE},
3757                 {"Aim a wand(a/z)", 'a', TRUE},
3758                 {"Zap a rod(z/a)", 'z', TRUE},
3759                 {"Activate an equipment(A)", 'A', TRUE},
3760                 {"Eat(E)", 'E', TRUE},
3761                 {"Fire missile weapon(f/t)", 'f', TRUE},
3762                 {"Throw an item(v)", 'v', TRUE},
3763                 {"", 0, FALSE}
3764         },
3765
3766         {
3767                 {"Get items(g)", 'g', TRUE},
3768                 {"Drop an item(d)", 'd', TRUE},
3769                 {"Destroy an item(k/^d)", 'k', TRUE},
3770                 {"Inscribe an item({)", '{', TRUE},
3771                 {"Uninscribe an item(})", '}', TRUE},
3772                 {"Info about an item(I)", 'I', TRUE},
3773                 {"Inventory list(i)", 'i', TRUE},
3774                 {"", 0, FALSE},
3775                 {"", 0, FALSE},
3776                 {"", 0, FALSE}
3777         },
3778
3779         {
3780                 {"Wear(w)", 'w', TRUE},
3781                 {"Take off(t/T)", 't', TRUE},
3782                 {"Refuel(F)", 'F', TRUE},
3783                 {"Equipment list(e)", 'e', TRUE},
3784                 {"", 0, FALSE},
3785                 {"", 0, FALSE},
3786                 {"", 0, FALSE},
3787                 {"", 0, FALSE},
3788                 {"", 0, FALSE},
3789                 {"", 0, FALSE}
3790         },
3791
3792         {
3793                 {"Open(o)", 'o', TRUE},
3794                 {"Close(c)", 'c', TRUE},
3795                 {"Bash a door(B/f)", 'B', TRUE},
3796                 {"Jam a door(j/S)", 'j', TRUE},
3797                 {"", 0, FALSE},
3798                 {"", 0, FALSE},
3799                 {"", 0, FALSE},
3800                 {"", 0, FALSE},
3801                 {"", 0, FALSE},
3802                 {"", 0, FALSE}
3803         },
3804
3805         {
3806                 {"Full map(M)", 'M', TRUE},
3807                 {"Map(L/W)", 'L', TRUE},
3808                 {"Level feeling(^f)", KTRL('F'), TRUE},
3809                 {"Character status(C)", 'C', TRUE},
3810                 {"Identify symbol(/)", '/', TRUE},
3811                 {"Show prev messages(^p)", KTRL('P'), TRUE},
3812                 {"Current time(^t/')", KTRL('T'), TRUE},
3813                 {"Various infomations(~)", '~', TRUE},
3814                 {"Play record menu(|)", '|', TRUE},
3815                 {"", 0, FALSE}
3816         },
3817
3818         {
3819                 {"Set options(=)", '=', TRUE},
3820                 {"Interact with macros(@)", '@', TRUE},
3821                 {"Interact w/ visuals(%)", '%', TRUE},
3822                 {"Interact with colors(&)", '&', TRUE},
3823                 {"Enter a user pref(\")", '\"', TRUE},
3824                 {"Reload auto-pick pref($)", '$', TRUE},
3825                 {"", 0, FALSE},
3826                 {"", 0, FALSE},
3827                 {"", 0, FALSE},
3828                 {"", 0, FALSE}
3829         },
3830
3831         {
3832                 {"Save and quit(^x)", KTRL('X'), TRUE},
3833                 {"Save(^s)", KTRL('S'), TRUE},
3834                 {"Help(obsoleted)(?)", '?', TRUE},
3835                 {"Redraw(^r)", KTRL('R'), TRUE},
3836                 {"Take note(:)", ':', TRUE},
3837                 {"Dump screen dump(()", ')', TRUE},
3838                 {"Load screen dump())", '(', TRUE},
3839                 {"Version info(V)", 'V', TRUE},
3840                 {"Quit(Q)", 'Q', TRUE},
3841                 {"", 0, FALSE}
3842         },
3843 };
3844 #endif
3845
3846 typedef struct
3847 {
3848         cptr name;
3849         byte window;
3850         byte number;
3851         byte jouken;
3852         byte jouken_naiyou;
3853 } special_menu_naiyou;
3854
3855 #define MENU_CLASS 1
3856 #define MENU_WILD 2
3857
3858 #ifdef JP
3859 special_menu_naiyou special_menu_info[] =
3860 {
3861         {"ĶǽÎÏ/ÆüìǽÎÏ", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
3862         {"¤â¤Î¤Þ¤Í/ÆüìǽÎÏ", 0, 0, MENU_CLASS, CLASS_IMITATOR},
3863         {"ɬ»¦µ»/ÆüìǽÎÏ", 0, 0, MENU_CLASS, CLASS_SAMURAI},
3864         {"Îýµ¤½Ñ/ËâË¡/ÆüìǽÎÏ", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
3865         {"¶ÀËâË¡/ÆüìǽÎÏ", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
3866         {"¹­°è¥Þ¥Ã¥×(<)", 2, 6, MENU_WILD, FALSE},
3867         {"Ä̾ï¥Þ¥Ã¥×(>)", 2, 7, MENU_WILD, TRUE},
3868         {"", 0, 0, 0, 0},
3869 };
3870 #else
3871 special_menu_naiyou special_menu_info[] =
3872 {
3873         {"MindCraft/Special", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
3874         {"Imitation/Special", 0, 0, MENU_CLASS, CLASS_IMITATOR},
3875         {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SAMURAI},
3876         {"Mind/Magic/Special", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
3877         {"MirrorMagic/Special", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
3878         {"Enter global map(<)", 2, 6, MENU_WILD, FALSE},
3879         {"Enter local map(>)", 2, 7, MENU_WILD, TRUE},
3880         {"", 0, 0, 0, 0},
3881 };
3882 #endif
3883
3884 static char inkey_from_menu(void)
3885 {
3886         char cmd;
3887         int basey, basex;
3888         int num = 0, max_num, old_num = 0;
3889         int menu = 0;
3890         bool kisuu;
3891
3892         if (py - panel_row_min > 10) basey = 2;
3893         else basey = 13;
3894         basex = 15;
3895
3896         /* Clear top line */
3897         prt("", 0, 0);
3898
3899         screen_save();
3900
3901         while(1)
3902         {
3903                 int i;
3904                 char sub_cmd;
3905                 cptr menu_name;
3906                 if (!menu) old_num = num;
3907                 put_str("+----------------------------------------------------+", basey, basex);
3908                 put_str("|                                                    |", basey+1, basex);
3909                 put_str("|                                                    |", basey+2, basex);
3910                 put_str("|                                                    |", basey+3, basex);
3911                 put_str("|                                                    |", basey+4, basex);
3912                 put_str("|                                                    |", basey+5, basex);
3913                 put_str("+----------------------------------------------------+", basey+6, basex);
3914
3915                 for(i = 0; i < 10; i++)
3916                 {
3917                         int hoge;
3918                         if (!menu_info[menu][i].cmd) break;
3919                         menu_name = menu_info[menu][i].name;
3920                         for(hoge = 0; ; hoge++)
3921                         {
3922                                 if (!special_menu_info[hoge].name[0]) break;
3923                                 if ((menu != special_menu_info[hoge].window) || (i != special_menu_info[hoge].number)) continue;
3924                                 switch(special_menu_info[hoge].jouken)
3925                                 {
3926                                 case MENU_CLASS:
3927                                         if (p_ptr->pclass == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
3928                                         break;
3929                                 case MENU_WILD:
3930                                         if (!dun_level && !p_ptr->inside_arena && !p_ptr->inside_quest)
3931                                         {
3932                                                 if ((byte)p_ptr->wild_mode == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
3933                                         }
3934                                         break;
3935                                 default:
3936                                         break;
3937                                 }
3938                         }
3939                         put_str(menu_name, basey + 1 + i / 2, basex + 4 + (i % 2) * 24);
3940                 }
3941                 max_num = i;
3942                 kisuu = max_num % 2;
3943 #ifdef JP
3944                 put_str("¡Õ",basey + 1 + num / 2, basex + 2 + (num % 2) * 24);
3945 #else
3946                 put_str("> ",basey + 1 + num / 2, basex + 2 + (num % 2) * 24);
3947 #endif
3948
3949                 /* Place the cursor on the player */
3950                 move_cursor_relative(py, px);
3951
3952                 /* Get a command */
3953                 sub_cmd = inkey();
3954                 if ((sub_cmd == ' ') || (sub_cmd == 'x') || (sub_cmd == 'X') || (sub_cmd == '\r') || (sub_cmd == '\n'))
3955                 {
3956                         if (menu_info[menu][num].fin)
3957                         {
3958                                 cmd = menu_info[menu][num].cmd;
3959                                 use_menu = TRUE;
3960                                 break;
3961                         }
3962                         else
3963                         {
3964                                 menu = menu_info[menu][num].cmd;
3965                                 num = 0;
3966                                 basey += 2;
3967                                 basex += 8;
3968                         }
3969                 }
3970                 else if ((sub_cmd == ESCAPE) || (sub_cmd == 'z') || (sub_cmd == 'Z') || (sub_cmd == '0'))
3971                 {
3972                         if (!menu)
3973                         {
3974                                 cmd = ESCAPE;
3975                                 break;
3976                         }
3977                         else
3978                         {
3979                                 menu = 0;
3980                                 num = old_num;
3981                                 basey -= 2;
3982                                 basex -= 8;
3983                                 screen_load();
3984                                 screen_save();
3985                         }
3986                 }
3987                 else if ((sub_cmd == '2') || (sub_cmd == 'j') || (sub_cmd == 'J'))
3988                 {
3989                         if (kisuu)
3990                         {
3991                                 if (num % 2)
3992                                         num = (num + 2) % (max_num - 1);
3993                                 else
3994                                         num = (num + 2) % (max_num + 1);
3995                         }
3996                         else num = (num + 2) % max_num;
3997                 }
3998                 else if ((sub_cmd == '8') || (sub_cmd == 'k') || (sub_cmd == 'K'))
3999                 {
4000                         if (kisuu)
4001                         {
4002                                 if (num % 2)
4003                                         num = (num + max_num - 3) % (max_num - 1);
4004                                 else
4005                                         num = (num + max_num - 1) % (max_num + 1);
4006                         }
4007                         else num = (num + max_num - 2) % max_num;
4008                 }
4009                 else if ((sub_cmd == '4') || (sub_cmd == '6') || (sub_cmd == 'h') || (sub_cmd == 'H') || (sub_cmd == 'l') || (sub_cmd == 'L'))
4010                 {
4011                         if ((num % 2) || (num == max_num - 1))
4012                         {
4013                                 num--;
4014                         }
4015                         else if (num < max_num - 1)
4016                         {
4017                                 num++;
4018                         }
4019                 }
4020         }
4021
4022         screen_load();
4023         if (!inkey_next) inkey_next = "";
4024
4025         return (cmd);
4026 }
4027
4028 /*
4029  * Request a command from the user.
4030  *
4031  * Sets p_ptr->command_cmd, p_ptr->command_dir, p_ptr->command_rep,
4032  * p_ptr->command_arg.  May modify p_ptr->command_new.
4033  *
4034  * Note that "caret" ("^") is treated specially, and is used to
4035  * allow manual input of control characters.  This can be used
4036  * on many machines to request repeated tunneling (Ctrl-H) and
4037  * on the Macintosh to request "Control-Caret".
4038  *
4039  * Note that "backslash" is treated specially, and is used to bypass any
4040  * keymap entry for the following character.  This is useful for macros.
4041  *
4042  * Note that this command is used both in the dungeon and in
4043  * stores, and must be careful to work in both situations.
4044  *
4045  * Note that "p_ptr->command_new" may not work any more.  XXX XXX XXX
4046  */
4047 void request_command(int shopping)
4048 {
4049         int i;
4050
4051         char cmd;
4052         int mode;
4053
4054         cptr act;
4055
4056 #ifdef JP
4057         int caretcmd = 0;
4058 #endif
4059         /* Roguelike */
4060         if (rogue_like_commands)
4061         {
4062                 mode = KEYMAP_MODE_ROGUE;
4063         }
4064
4065         /* Original */
4066         else
4067         {
4068                 mode = KEYMAP_MODE_ORIG;
4069         }
4070
4071
4072         /* No command yet */
4073         command_cmd = 0;
4074
4075         /* No "argument" yet */
4076         command_arg = 0;
4077
4078         /* No "direction" yet */
4079         command_dir = 0;
4080
4081         use_menu = FALSE;
4082
4083
4084         /* Get command */
4085         while (1)
4086         {
4087                 /* Hack -- auto-commands */
4088                 if (command_new)
4089                 {
4090                         /* Flush messages */
4091                         msg_print(NULL);
4092
4093                         /* Use auto-command */
4094                         cmd = command_new;
4095
4096                         /* Forget it */
4097                         command_new = 0;
4098                 }
4099
4100                 /* Get a keypress in "command" mode */
4101                 else
4102                 {
4103                         /* Hack -- no flush needed */
4104                         msg_flag = FALSE;
4105                         num_more = 0;
4106
4107                         /* Activate "command mode" */
4108                         inkey_flag = TRUE;
4109
4110                         /* Get a command */
4111                         cmd = inkey();
4112
4113                         if (!shopping && command_menu && ((cmd == '\r') || (cmd == '\n') || (cmd == 'x') || (cmd == 'X'))
4114                             && !keymap_act[mode][(byte)(cmd)])
4115                                 cmd = inkey_from_menu();
4116                 }
4117
4118                 /* Clear top line */
4119                 prt("", 0, 0);
4120
4121
4122                 /* Command Count */
4123                 if (cmd == '0')
4124                 {
4125                         int old_arg = command_arg;
4126
4127                         /* Reset */
4128                         command_arg = 0;
4129
4130                         /* Begin the input */
4131 #ifdef JP
4132                         prt("²ó¿ô: ", 0, 0);
4133 #else
4134                         prt("Count: ", 0, 0);
4135 #endif
4136
4137
4138                         /* Get a command count */
4139                         while (1)
4140                         {
4141                                 /* Get a new keypress */
4142                                 cmd = inkey();
4143
4144                                 /* Simple editing (delete or backspace) */
4145                                 if ((cmd == 0x7F) || (cmd == KTRL('H')))
4146                                 {
4147                                         /* Delete a digit */
4148                                         command_arg = command_arg / 10;
4149
4150                                         /* Show current count */
4151 #ifdef JP
4152                                         prt(format("²ó¿ô: %d", command_arg), 0, 0);
4153 #else
4154                                         prt(format("Count: %d", command_arg), 0, 0);
4155 #endif
4156
4157                                 }
4158
4159                                 /* Actual numeric data */
4160                                 else if (cmd >= '0' && cmd <= '9')
4161                                 {
4162                                         /* Stop count at 9999 */
4163                                         if (command_arg >= 1000)
4164                                         {
4165                                                 /* Warn */
4166                                                 bell();
4167
4168                                                 /* Limit */
4169                                                 command_arg = 9999;
4170                                         }
4171
4172                                         /* Increase count */
4173                                         else
4174                                         {
4175                                                 /* Incorporate that digit */
4176                                                 command_arg = command_arg * 10 + D2I(cmd);
4177                                         }
4178
4179                                         /* Show current count */
4180 #ifdef JP
4181                                         prt(format("²ó¿ô: %d", command_arg), 0, 0);
4182 #else
4183                                         prt(format("Count: %d", command_arg), 0, 0);
4184 #endif
4185
4186                                 }
4187
4188                                 /* Exit on "unusable" input */
4189                                 else
4190                                 {
4191                                         break;
4192                                 }
4193                         }
4194
4195                         /* Hack -- Handle "zero" */
4196                         if (command_arg == 0)
4197                         {
4198                                 /* Default to 99 */
4199                                 command_arg = 99;
4200
4201                                 /* Show current count */
4202 #ifdef JP
4203                                 prt(format("²ó¿ô: %d", command_arg), 0, 0);
4204 #else
4205                                 prt(format("Count: %d", command_arg), 0, 0);
4206 #endif
4207
4208                         }
4209
4210                         /* Hack -- Handle "old_arg" */
4211                         if (old_arg != 0)
4212                         {
4213                                 /* Restore old_arg */
4214                                 command_arg = old_arg;
4215
4216                                 /* Show current count */
4217 #ifdef JP
4218 prt(format("²ó¿ô: %d", command_arg), 0, 0);
4219 #else
4220                                 prt(format("Count: %d", command_arg), 0, 0);
4221 #endif
4222
4223                         }
4224
4225                         /* Hack -- white-space means "enter command now" */
4226                         if ((cmd == ' ') || (cmd == '\n') || (cmd == '\r'))
4227                         {
4228                                 /* Get a real command */
4229 #ifdef JP
4230                                 if (!get_com("¥³¥Þ¥ó¥É: ", (char *)&cmd, FALSE))
4231 #else
4232                                 if (!get_com("Command: ", (char *)&cmd, FALSE))
4233 #endif
4234
4235                                 {
4236                                         /* Clear count */
4237                                         command_arg = 0;
4238
4239                                         /* Continue */
4240                                         continue;
4241                                 }
4242                         }
4243                 }
4244
4245
4246                 /* Allow "keymaps" to be bypassed */
4247                 if (cmd == '\\')
4248                 {
4249                         /* Get a real command */
4250 #ifdef JP
4251                         (void)get_com("¥³¥Þ¥ó¥É: ", (char *)&cmd, FALSE);
4252 #else
4253                         (void)get_com("Command: ", (char *)&cmd, FALSE);
4254 #endif
4255
4256
4257                         /* Hack -- bypass keymaps */
4258                         if (!inkey_next) inkey_next = "";
4259                 }
4260
4261
4262                 /* Allow "control chars" to be entered */
4263                 if (cmd == '^')
4264                 {
4265                         /* Get a new command and controlify it */
4266 #ifdef JP
4267                         if (get_com("CTRL: ", (char *)&cmd, FALSE)) cmd = KTRL(cmd);
4268 #else
4269                         if (get_com("Control: ", (char *)&cmd, FALSE)) cmd = KTRL(cmd);
4270 #endif
4271
4272                 }
4273
4274
4275                 /* Look up applicable keymap */
4276                 act = keymap_act[mode][(byte)(cmd)];
4277
4278                 /* Apply keymap if not inside a keymap already */
4279                 if (act && !inkey_next)
4280                 {
4281                         /* Install the keymap (limited buffer size) */
4282                         (void)strnfmt(request_command_buffer, 256, "%s", act);
4283
4284                         /* Start using the buffer */
4285                         inkey_next = request_command_buffer;
4286
4287                         /* Continue */
4288                         continue;
4289                 }
4290
4291
4292                 /* Paranoia */
4293                 if (!cmd) continue;
4294
4295
4296                 /* Use command */
4297                 command_cmd = (byte)cmd;
4298
4299                 /* Done */
4300                 break;
4301         }
4302
4303         /* Hack -- Auto-repeat certain commands */
4304         if (always_repeat && (command_arg <= 0))
4305         {
4306                 /* Hack -- auto repeat certain commands */
4307                 if (strchr("TBDoc+", command_cmd))
4308                 {
4309                         /* Repeat 99 times */
4310                         command_arg = 99;
4311                 }
4312         }
4313
4314         /* Shopping */
4315         if (shopping == 1)
4316         {
4317                 /* Convert */
4318                 switch (command_cmd)
4319                 {
4320                         /* Command "p" -> "purchase" (get) */
4321                 case 'p': command_cmd = 'g'; break;
4322
4323                         /* Command "m" -> "purchase" (get) */
4324                 case 'm': command_cmd = 'g'; break;
4325
4326                         /* Command "s" -> "sell" (drop) */
4327                 case 's': command_cmd = 'd'; break;
4328                 }
4329         }
4330
4331 #ifdef JP
4332         for (i = 0; i < 256; i++)
4333         {
4334                 cptr s;
4335                 if ((s = keymap_act[mode][i]) != NULL)
4336                 {
4337                         if (*s == command_cmd && *(s+1) == 0)
4338                         {
4339                                 caretcmd = i;
4340                                 break;
4341                         }
4342                 }
4343         }
4344         if (!caretcmd)
4345                 caretcmd = command_cmd;
4346 #endif
4347         /* Hack -- Scan equipment */
4348         for (i = INVEN_RARM; i < INVEN_TOTAL; i++)
4349         {
4350                 cptr s;
4351
4352                 object_type *o_ptr = &inventory[i];
4353
4354                 /* Skip non-objects */
4355                 if (!o_ptr->k_idx) continue;
4356
4357                 /* No inscription */
4358                 if (!o_ptr->inscription) continue;
4359
4360                 /* Obtain the inscription */
4361                 s = quark_str(o_ptr->inscription);
4362
4363                 /* Find a '^' */
4364                 s = strchr(s, '^');
4365
4366                 /* Process preventions */
4367                 while (s)
4368                 {
4369                         /* Check the "restriction" character */
4370 #ifdef JP
4371                         if ((s[1] == caretcmd) || (s[1] == '*'))
4372 #else
4373                         if ((s[1] == command_cmd) || (s[1] == '*'))
4374 #endif
4375
4376                         {
4377                                 /* Hack -- Verify command */
4378 #ifdef JP
4379                                 if (!get_check("ËÜÅö¤Ç¤¹¤«? "))
4380 #else
4381                                 if (!get_check("Are you sure? "))
4382 #endif
4383
4384                                 {
4385                                         /* Hack -- Use space */
4386                                         command_cmd = ' ';
4387                                 }
4388                         }
4389
4390                         /* Find another '^' */
4391                         s = strchr(s + 1, '^');
4392                 }
4393         }
4394
4395
4396         /* Hack -- erase the message line. */
4397         prt("", 0, 0);
4398 }
4399
4400
4401
4402 /*
4403  * Check a char for "vowel-hood"
4404  */
4405 bool is_a_vowel(int ch)
4406 {
4407         switch (ch)
4408         {
4409         case 'a':
4410         case 'e':
4411         case 'i':
4412         case 'o':
4413         case 'u':
4414         case 'A':
4415         case 'E':
4416         case 'I':
4417         case 'O':
4418         case 'U':
4419                 return (TRUE);
4420         }
4421
4422         return (FALSE);
4423 }
4424
4425
4426
4427 #if 0
4428
4429 /*
4430  * Replace the first instance of "target" in "buf" with "insert"
4431  * If "insert" is NULL, just remove the first instance of "target"
4432  * In either case, return TRUE if "target" is found.
4433  *
4434  * XXX Could be made more efficient, especially in the
4435  * case where "insert" is smaller than "target".
4436  */
4437 static bool insert_str(char *buf, cptr target, cptr insert)
4438 {
4439         int   i, len;
4440         int                b_len, t_len, i_len;
4441
4442         /* Attempt to find the target (modify "buf") */
4443         buf = strstr(buf, target);
4444
4445         /* No target found */
4446         if (!buf) return (FALSE);
4447
4448         /* Be sure we have an insertion string */
4449         if (!insert) insert = "";
4450
4451         /* Extract some lengths */
4452         t_len = strlen(target);
4453         i_len = strlen(insert);
4454         b_len = strlen(buf);
4455
4456         /* How much "movement" do we need? */
4457         len = i_len - t_len;
4458
4459         /* We need less space (for insert) */
4460         if (len < 0)
4461         {
4462                 for (i = t_len; i < b_len; ++i) buf[i+len] = buf[i];
4463         }
4464
4465         /* We need more space (for insert) */
4466         else if (len > 0)
4467         {
4468                 for (i = b_len-1; i >= t_len; --i) buf[i+len] = buf[i];
4469         }
4470
4471         /* If movement occured, we need a new terminator */
4472         if (len) buf[b_len+len] = '\0';
4473
4474         /* Now copy the insertion string */
4475         for (i = 0; i < i_len; ++i) buf[i] = insert[i];
4476
4477         /* Successful operation */
4478         return (TRUE);
4479 }
4480
4481
4482 #endif
4483
4484
4485 /*
4486  * GH
4487  * Called from cmd4.c and a few other places. Just extracts
4488  * a direction from the keymap for ch (the last direction,
4489  * in fact) byte or char here? I'm thinking that keymaps should
4490  * generally only apply to single keys, which makes it no more
4491  * than 128, so a char should suffice... but keymap_act is 256...
4492  */
4493 int get_keymap_dir(char ch)
4494 {
4495         int d = 0;
4496
4497         /* Already a direction? */
4498         if (isdigit(ch))
4499         {
4500                 d = D2I(ch);
4501         }
4502         else
4503         {
4504                 int mode;
4505                 cptr act, s;
4506
4507                 /* Roguelike */
4508                 if (rogue_like_commands)
4509                 {
4510                         mode = KEYMAP_MODE_ROGUE;
4511                 }
4512
4513                 /* Original */
4514                 else
4515                 {
4516                         mode = KEYMAP_MODE_ORIG;
4517                 }
4518
4519                 /* Extract the action (if any) */
4520                 act = keymap_act[mode][(byte)(ch)];
4521
4522                 /* Analyze */
4523                 if (act)
4524                 {
4525                         /* Convert to a direction */
4526                         for (s = act; *s; ++s)
4527                         {
4528                                 /* Use any digits in keymap */
4529                                 if (isdigit(*s)) d = D2I(*s);
4530                         }
4531                 }
4532         }
4533
4534         /* Paranoia */
4535         if (d == 5) d = 0;
4536
4537         /* Return direction */
4538         return (d);
4539 }
4540
4541
4542 #ifdef ALLOW_REPEAT /* TNB */
4543
4544 #define REPEAT_MAX              20
4545
4546 /* Number of chars saved */
4547 static int repeat__cnt = 0;
4548
4549 /* Current index */
4550 static int repeat__idx = 0;
4551
4552 /* Saved "stuff" */
4553 static int repeat__key[REPEAT_MAX];
4554
4555
4556 void repeat_push(int what)
4557 {
4558         /* Too many keys */
4559         if (repeat__cnt == REPEAT_MAX) return;
4560
4561         /* Push the "stuff" */
4562         repeat__key[repeat__cnt++] = what;
4563
4564         /* Prevents us from pulling keys */
4565         ++repeat__idx;
4566 }
4567
4568
4569 bool repeat_pull(int *what)
4570 {
4571         /* All out of keys */
4572         if (repeat__idx == repeat__cnt) return (FALSE);
4573
4574         /* Grab the next key, advance */
4575         *what = repeat__key[repeat__idx++];
4576
4577         /* Success */
4578         return (TRUE);
4579 }
4580
4581 void repeat_check(void)
4582 {
4583         int             what;
4584
4585         /* Ignore some commands */
4586         if (command_cmd == ESCAPE) return;
4587         if (command_cmd == ' ') return;
4588         if (command_cmd == '\r') return;
4589         if (command_cmd == '\n') return;
4590
4591         /* Repeat Last Command */
4592         if (command_cmd == 'n')
4593         {
4594                 /* Reset */
4595                 repeat__idx = 0;
4596
4597                 /* Get the command */
4598                 if (repeat_pull(&what))
4599                 {
4600                         /* Save the command */
4601                         command_cmd = what;
4602                 }
4603         }
4604
4605         /* Start saving new command */
4606         else
4607         {
4608                 /* Reset */
4609                 repeat__cnt = 0;
4610                 repeat__idx = 0;
4611
4612                 what = command_cmd;
4613
4614                 /* Save this command */
4615                 repeat_push(what);
4616         }
4617 }
4618
4619 #endif /* ALLOW_REPEAT -- TNB */
4620
4621
4622 #ifdef SORT_R_INFO
4623
4624 /*
4625  * Array size for which InsertionSort
4626  * is used instead of QuickSort
4627  */
4628 #define CUTOFF 4
4629
4630
4631 /*
4632  * Exchange two sort-entries
4633  * (should probably be coded inline
4634  * for speed increase)
4635  */
4636 static void swap(tag_type *a, tag_type *b)
4637 {
4638         tag_type temp;
4639
4640         temp.tag = a->tag;
4641         temp.pointer = a->pointer;
4642
4643         a->tag = b->tag;
4644         a->pointer = b->pointer;
4645
4646         b->tag = temp.tag;
4647         b->pointer = temp.pointer;
4648 }
4649
4650
4651 /*
4652  * Insertion-Sort algorithm
4653  * (used by the Quicksort algorithm)
4654  */
4655 static void InsertionSort(tag_type elements[], int number)
4656 {
4657         int j, P;
4658
4659         tag_type tmp;
4660
4661         for (P = 1; P < number; P++)
4662         {
4663                 tmp = elements[P];
4664                 for (j = P; (j > 0) && (elements[j - 1].tag > tmp.tag); j--)
4665                         elements[j] = elements[j - 1];
4666                 elements[j] = tmp;
4667         }
4668 }
4669
4670
4671 /*
4672  * Helper function for Quicksort
4673  */
4674 static tag_type median3(tag_type elements[], int left, int right)
4675 {
4676         int center = (left + right) / 2;
4677
4678         if (elements[left].tag > elements[center].tag)
4679                 swap(&elements[left], &elements[center]);
4680         if (elements[left].tag > elements[right].tag)
4681                 swap(&elements[left], &elements[right]);
4682         if (elements[center].tag > elements[right].tag)
4683                 swap(&elements[center], &elements[right]);
4684
4685         swap(&elements[center], &elements[right - 1]);
4686         return (elements[right - 1]);
4687 }
4688
4689
4690 /*
4691  * Quicksort algorithm
4692  *
4693  * The "median of three" pivot selection eliminates
4694  * the bad case of already sorted input.
4695  *
4696  * We use InsertionSort for smaller sub-arrays,
4697  * because it is faster in this case.
4698  *
4699  * For details see: "Data Structures and Algorithm
4700  * Analysis in C" by Mark Allen Weiss.
4701  */
4702 static void quicksort(tag_type elements[], int left, int right)
4703 {
4704         int i, j;
4705         tag_type pivot;
4706
4707         if (left + CUTOFF <= right)
4708         {
4709                 pivot = median3(elements, left, right);
4710
4711                 i = left; j = right -1;
4712
4713                 while (TRUE)
4714                 {
4715                         while (elements[++i].tag < pivot.tag);
4716                         while (elements[--j].tag > pivot.tag);
4717
4718                         if (i < j)
4719                                 swap(&elements[i], &elements[j]);
4720                         else
4721                                 break;
4722                 }
4723
4724                 /* Restore pivot */
4725                 swap(&elements[i], &elements[right - 1]);
4726
4727                 quicksort(elements, left, i - 1);
4728                 quicksort(elements, i + 1, right);
4729         }
4730         else
4731         {
4732                 /* Use InsertionSort on small arrays */
4733                 InsertionSort(elements + left, right - left + 1);
4734         }
4735 }
4736
4737
4738 /*
4739  * Frontend for the sorting algorithm
4740  *
4741  * Sorts an array of tagged pointers
4742  * with <number> elements.
4743  */
4744 void tag_sort(tag_type elements[], int number)
4745 {
4746         quicksort(elements, 0, number - 1);
4747 }
4748
4749 #endif /* SORT_R_INFO */
4750
4751 #ifdef SUPPORT_GAMMA
4752
4753 /* Table of gamma values */
4754 byte gamma_table[256];
4755
4756 /* Table of ln(x/256) * 256 for x going from 0 -> 255 */
4757 static s16b gamma_helper[256] =
4758 {
4759 0,-1420,-1242,-1138,-1065,-1007,-961,-921,-887,-857,-830,-806,-783,-762,-744,-726,
4760 -710,-694,-679,-666,-652,-640,-628,-617,-606,-596,-586,-576,-567,-577,-549,-541,
4761 -532,-525,-517,-509,-502,-495,-488,-482,-475,-469,-463,-457,-451,-455,-439,-434,
4762 -429,-423,-418,-413,-408,-403,-398,-394,-389,-385,-380,-376,-371,-367,-363,-359,
4763 -355,-351,-347,-343,-339,-336,-332,-328,-325,-321,-318,-314,-311,-308,-304,-301,
4764 -298,-295,-291,-288,-285,-282,-279,-276,-273,-271,-268,-265,-262,-259,-257,-254,
4765 -251,-248,-246,-243,-241,-238,-236,-233,-231,-228,-226,-223,-221,-219,-216,-214,
4766 -212,-209,-207,-205,-203,-200,-198,-196,-194,-192,-190,-188,-186,-184,-182,-180,
4767 -178,-176,-174,-172,-170,-168,-166,-164,-162,-160,-158,-156,-155,-153,-151,-149,
4768 -147,-146,-144,-142,-140,-139,-137,-135,-134,-132,-130,-128,-127,-125,-124,-122,
4769 -120,-119,-117,-116,-114,-112,-111,-109,-108,-106,-105,-103,-102,-100,-99,-97,
4770 -96,-95,-93,-92,-90,-89,-87,-86,-85,-83,-82,-80,-79,-78,-76,-75,
4771 -74,-72,-71,-70,-68,-67,-66,-65,-63,-62,-61,-59,-58,-57,-56,-54,
4772 -53,-52,-51,-50,-48,-47,-46,-45,-44,-42,-41,-40,-39,-38,-37,-35,
4773 -34,-33,-32,-31,-30,-29,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,
4774 -17,-16,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1
4775 };
4776
4777
4778 /* 
4779  * Build the gamma table so that floating point isn't needed.
4780  * 
4781  * Note gamma goes from 0->256.  The old value of 100 is now 128.
4782  */
4783 void build_gamma_table(int gamma)
4784 {
4785         int i, n;
4786         
4787         /*
4788          * value is the current sum.
4789          * diff is the new term to add to the series.
4790          */
4791         long value, diff;
4792         
4793         /* Hack - convergence is bad in these cases. */
4794         gamma_table[0] = 0;
4795         gamma_table[255] = 255;
4796         
4797         for (i = 1; i < 255; i++)
4798         {
4799                 /* 
4800                  * Initialise the Taylor series
4801                  *
4802                  * value and diff have been scaled by 256
4803                  */
4804                 
4805                 n = 1;
4806                 value = 256 * 256;
4807                 diff = ((long)gamma_helper[i]) * (gamma - 256);
4808                 
4809                 while (diff)
4810                 {
4811                         value += diff;
4812                         n++;
4813                         
4814                         
4815                         /*
4816                          * Use the following identiy to calculate the gamma table.
4817                          * exp(x) = 1 + x + x^2/2 + x^3/(2*3) + x^4/(2*3*4) +...
4818                          *
4819                          * n is the current term number.
4820                          * 
4821                          * The gamma_helper array contains a table of
4822                          * ln(x/256) * 256
4823                          * This is used because a^b = exp(b*ln(a))
4824                          *
4825                          * In this case:
4826                          * a is i / 256
4827                          * b is gamma.
4828                          *
4829                          * Note that everything is scaled by 256 for accuracy,
4830                          * plus another factor of 256 for the final result to
4831                          * be from 0-255.  Thus gamma_helper[] * gamma must be
4832                          * divided by 256*256 each itteration, to get back to
4833                          * the original power series.
4834                          */
4835                         diff = (((diff / 256) * gamma_helper[i]) * (gamma - 256)) / (256 * n);
4836                 }
4837                 
4838                 /* 
4839                  * Store the value in the table so that the
4840                  * floating point pow function isn't needed .
4841                  */
4842                 gamma_table[i] = ((long)(value / 256) * i) / 256;
4843         }
4844 }
4845
4846 #endif /* SUPPORT_GAMMA */
4847
4848 void roff_to_buf(cptr str, int maxlen, char *tbuf, size_t bufsize)
4849 {
4850         int read_pt = 0;
4851         int write_pt = 0;
4852         int line_len = 0;
4853         int word_punct = 0;
4854         char ch[3];
4855         ch[2] = '\0';
4856
4857         while (str[read_pt])
4858         {
4859 #ifdef JP
4860                 bool kinsoku = FALSE;
4861                 bool kanji;
4862 #endif
4863                 int ch_len = 1;
4864
4865                 /* Prepare one character */
4866                 ch[0] = str[read_pt];
4867                 ch[1] = '\0';
4868 #ifdef JP
4869                 kanji  = iskanji(ch[0]);
4870
4871                 if (kanji)
4872                 {
4873                         ch[1] = str[read_pt+1];
4874                         ch_len = 2;
4875
4876                         if (strcmp(ch, "¡£") == 0 ||
4877                             strcmp(ch, "¡¢") == 0 ||
4878                             strcmp(ch, "¥£") == 0 ||
4879                             strcmp(ch, "¡¼") == 0)
4880                                 kinsoku = TRUE;
4881                 }
4882                 else if (!isprint(ch[0]))
4883                         ch[0] = ' ';
4884 #else
4885                 if (!isprint(ch[0]))
4886                         ch[0] = ' ';
4887 #endif
4888
4889                 if (line_len + ch_len > maxlen - 1 || str[read_pt] == '\n')
4890                 {
4891                         int word_len;
4892
4893                         /* return to better wrapping point. */
4894                         /* Space character at the end of the line need not to be printed. */
4895                         word_len = read_pt - word_punct;
4896 #ifdef JP
4897                         if (kanji && !kinsoku)
4898                                 /* nothing */ ;
4899                         else
4900 #endif
4901                         if (ch[0] == ' ' || word_len >= line_len/2)
4902                                 read_pt++;
4903                         else
4904                         {
4905                                 read_pt = word_punct;
4906                                 if (str[word_punct] == ' ')
4907                                         read_pt++;
4908                                 write_pt -= word_len;
4909                         }
4910
4911                         tbuf[write_pt++] = '\0';
4912                         line_len = 0;
4913                         word_punct = read_pt;
4914                         continue;
4915                 }
4916                 if (ch[0] == ' ')
4917                         word_punct = read_pt;
4918 #ifdef JP
4919                 if (!kinsoku) word_punct = read_pt;
4920 #endif
4921
4922                 /* Not enough buffer size */
4923                 if ((size_t)(write_pt + 3) >= bufsize) break;
4924
4925                 tbuf[write_pt++] = ch[0];
4926                 line_len++;
4927                 read_pt++;
4928 #ifdef JP
4929                 if (kanji)
4930                 {
4931                         tbuf[write_pt++] = ch[1];
4932                         line_len++;
4933                         read_pt++;
4934                 }
4935 #endif
4936         }
4937         tbuf[write_pt] = '\0';
4938         tbuf[write_pt+1] = '\0';
4939
4940         return;
4941 }
4942
4943
4944 /*
4945  * The my_strcpy() function copies up to 'bufsize'-1 characters from 'src'
4946  * to 'buf' and NUL-terminates the result.  The 'buf' and 'src' strings may
4947  * not overlap.
4948  *
4949  * my_strcpy() returns strlen(src).  This makes checking for truncation
4950  * easy.  Example: if (my_strcpy(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
4951  *
4952  * This function should be equivalent to the strlcpy() function in BSD.
4953  */
4954 size_t my_strcpy(char *buf, const char *src, size_t bufsize)
4955 {
4956 #ifdef JP
4957
4958         char *d = buf;
4959         const char *s = src;
4960         size_t len = 0;
4961
4962         /* reserve for NUL termination */
4963         bufsize--;
4964
4965         /* Copy as many bytes as will fit */
4966         while (len < bufsize)
4967         {
4968                 if (iskanji(*s))
4969                 {
4970                         if (len + 1 >= bufsize || !*(s+1)) break;
4971                         *d++ = *s++;
4972                         *d++ = *s++;
4973                         len += 2;
4974                 }
4975                 else
4976                 {
4977                         *d++ = *s++;
4978                         len++;
4979                 }
4980         }
4981         *d = '\0';
4982         while(*s++) len++;
4983
4984         return len;
4985
4986 #else
4987
4988         size_t len = strlen(src);
4989         size_t ret = len;
4990
4991         /* Paranoia */
4992         if (bufsize == 0) return ret;
4993
4994         /* Truncate */
4995         if (len >= bufsize) len = bufsize - 1;
4996
4997         /* Copy the string and terminate it */
4998         (void)memcpy(buf, src, len);
4999         buf[len] = '\0';
5000
5001         /* Return strlen(src) */
5002         return ret;
5003
5004 #endif
5005 }
5006
5007
5008 /*
5009  * The my_strcat() tries to append a string to an existing NUL-terminated string.
5010  * It never writes more characters into the buffer than indicated by 'bufsize' and
5011  * NUL-terminates the buffer.  The 'buf' and 'src' strings may not overlap.
5012  *
5013  * my_strcat() returns strlen(buf) + strlen(src).  This makes checking for
5014  * truncation easy.  Example:
5015  * if (my_strcat(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
5016  *
5017  * This function should be equivalent to the strlcat() function in BSD.
5018  */
5019 size_t my_strcat(char *buf, const char *src, size_t bufsize)
5020 {
5021         size_t dlen = strlen(buf);
5022
5023         /* Is there room left in the buffer? */
5024         if (dlen < bufsize - 1)
5025         {
5026                 /* Append as much as possible  */
5027                 return (dlen + my_strcpy(buf + dlen, src, bufsize - dlen));
5028         }
5029         else
5030         {
5031                 /* Return without appending */
5032                 return (dlen + strlen(src));
5033         }
5034 }