4 * Copyright (c) 1997 Ben Harrison, James E. Wilson, Robert A. Koeneke
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.
11 /* Purpose: Angband utilities -BEN- */
14 #include "monsterrace-hook.h"
17 static int num_more = 0;
19 /* Save macro trigger string for use in inkey_special() */
20 static char inkey_macro_trigger_string[1024];
26 * For those systems that don't have "stricmp()"
28 * Compare the two strings "a" and "b" ala "strcmp()" ignoring case.
30 int stricmp(concptr a, concptr b)
35 /* Scan the strings */
36 for (s1 = a, s2 = b; TRUE; s1++, s2++)
40 if (z1 < z2) return (-1);
41 if (z1 > z2) return (1);
46 #endif /* HAS_STRICMP */
54 * For those systems that don't have "usleep()" but need it.
56 * Fake "usleep()" function grabbed from the inl netrek server -cba
58 int usleep(huge usecs)
65 fd_set *no_fds = NULL;
71 /* Was: int readfds, writefds, exceptfds; */
72 /* Was: readfds = writefds = exceptfds = 0; */
75 /* Paranoia -- No excessive sleeping */
76 if (usecs > 4000000L) core(_("不当な usleep() 呼び出し", "Illegal usleep() call"));
79 Timer.tv_sec = (usecs / 1000000L);
80 Timer.tv_usec = (usecs % 1000000L);
83 if (select(nfds, no_fds, no_fds, no_fds, &Timer) < 0)
85 /* Hack -- ignore interrupts */
86 if (errno != EINTR) return -1;
97 * Hack -- External functions
100 extern struct passwd *getpwuid(uid_t uid);
101 extern struct passwd *getpwnam(concptr name);
106 * Find a default user name from the system.
108 void user_name(char *buf, int id)
112 /* Look up the user name */
113 if ((pw = getpwuid(id)))
115 (void)strcpy(buf, pw->pw_name);
118 #ifdef CAPITALIZE_USER_NAME
119 /* Hack -- capitalize the user name */
121 if (!iskanji(buf[0]))
124 buf[0] = toupper(buf[0]);
125 #endif /* CAPITALIZE_USER_NAME */
130 /* Oops. Hack -- default to "PLAYER" */
131 strcpy(buf, "PLAYER");
140 * The concept of the "file" routines below (and elsewhere) is that all
141 * file handling should be done using as few routines as possible, since
142 * every machine is slightly different, but these routines always have the
145 * In fact, perhaps we should use the "path_parse()" routine below to convert
146 * from "canonical" filenames (optional leading tilde's, internal wildcards,
147 * slash as the path seperator, etc) to "system" filenames (no special symbols,
148 * system-specific path seperator, etc). This would allow the program itself
149 * to assume that all filenames are "Unix" filenames, and explicitly "extract"
150 * such filenames if needed (by "path_parse()", or perhaps "path_canon()").
152 * Note that "path_temp" should probably return a "canonical" filename.
154 * Note that "my_fopen()" and "my_open()" and "my_make()" and "my_kill()"
155 * and "my_move()" and "my_copy()" should all take "canonical" filenames.
157 * Note that "canonical" filenames use a leading "slash" to indicate an absolute
158 * path, and a leading "tilde" to indicate a special directory, and default to a
159 * relative path, but MSDOS uses a leading "drivename plus colon" to indicate the
160 * use of a "special drive", and then the rest of the path is parsed "normally",
161 * and MACINTOSH uses a leading colon to indicate a relative path, and an embedded
162 * colon to indicate a "drive plus absolute path", and finally defaults to a file
163 * in the current working directory, which may or may not be defined.
165 * We should probably parse a leading "~~/" as referring to "ANGBAND_DIR". (?)
173 * Most of the "file" routines for "ACORN" should be in "main-acn.c"
183 * Extract a "parsed" path from an initial filename
184 * Normally, we simply copy the filename into the buffer
185 * But leading tilde symbols must be handled in a special way
186 * Replace "~user/" by the home directory of the user named "user"
187 * Replace "~/" by the home directory of the current user
189 errr path_parse(char *buf, int max, concptr file)
196 /* Assume no result */
200 if (!file) return (-1);
202 /* File needs no parsing */
205 (void)strnfmt(buf, max, "%s", file);
209 /* Point at the user */
212 /* Look for non-user portion of the file */
213 s = my_strstr(u, PATH_SEP);
215 /* Hack -- no long user names */
216 if (s && (s >= u + sizeof(user))) return (1);
218 /* Extract a user name */
222 for (i = 0; u < s; ++i) user[i] = *u++;
227 /* Look up the "current" user */
228 if (u[0] == '\0') u = getlogin();
230 /* Look up a user (or "current" user) */
231 if (u) pw = getpwnam(u);
232 else pw = getpwuid(getuid());
237 /* Make use of the info */
238 if (s) strnfmt(buf, max, "%s%s", pw->pw_dir, s);
239 else strnfmt(buf, max, "%s", pw->pw_dir);
250 * Extract a "parsed" path from an initial filename
252 * This requires no special processing on simple machines,
253 * except for verifying the size of the filename.
255 errr path_parse(char *buf, int max, concptr file)
257 /* Accept the filename */
258 (void)strnfmt(buf, max, "%s", file);
260 #if defined(MAC_MPW) && defined(CARBON)
261 /* Fix it according to the current operating system */
262 convert_pathname(buf);
263 #endif /* MAC_MPW && CARBON */
276 * Hack -- acquire a "temporary" file name if possible
278 * This filename is always in "system-specific" form.
280 static errr path_temp(char *buf, int max)
289 /* Format to length */
290 #if !defined(WIN32) || (defined(_MSC_VER) && (_MSC_VER >= 1900))
291 (void)strnfmt(buf, max, "%s", s);
293 (void)strnfmt(buf, max, ".%s", s);
303 * Create a new path by appending a file (or directory) to a path.
305 * This requires no special processing on simple machines, except
306 * for verifying the size of the filename, but note the ability to
307 * bypass the given "path" with certain special file-names.
309 * Note that the "file" may actually be a "sub-path", including
312 * Note that this function yields a path which must be "parsed"
313 * using the "parse" function above.
315 errr path_build(char *buf, int max, concptr path, concptr file)
320 /* Use the file itself */
321 (void)strnfmt(buf, max, "%s", file);
324 /* Absolute file, on "normal" systems */
325 else if (prefix(file, PATH_SEP) && !streq(PATH_SEP, ""))
327 /* Use the file itself */
328 (void)strnfmt(buf, max, "%s", file);
334 /* Use the file itself */
335 (void)strnfmt(buf, max, "%s", file);
341 /* Build the new path */
342 (void)strnfmt(buf, max, "%s%s%s", path, PATH_SEP, file);
351 * Hack -- replacement for "fopen()"
353 FILE *my_fopen(concptr file, concptr mode)
357 #if defined(MAC_MPW) || defined(MACH_O_CARBON)
361 /* Hack -- Try to parse the path */
362 if (path_parse(buf, 1024, file)) return (NULL);
364 #if defined(MAC_MPW) || defined(MACH_O_CARBON)
365 if (my_strchr(mode, 'w'))
367 /* setting file type/creator */
368 tempfff = fopen(buf, mode);
369 fsetfileinfo(buf, _fcreator, _ftype);
374 /* Attempt to fopen the file anyway */
375 return (fopen(buf, mode));
380 * Hack -- replacement for "fclose()"
382 errr my_fclose(FILE *fff)
385 if (!fff) return (-1);
387 /* Close, check for error */
388 if (fclose(fff) == EOF) return (1);
400 FILE *my_fopen_temp(char *buf, int max)
404 /* Prepare the buffer for mkstemp */
405 strncpy(buf, "/tmp/anXXXXXX", max);
407 /* Secure creation of a temporary file */
410 /* Check the file-descriptor */
411 if (fd < 0) return (NULL);
413 /* Return a file stream */
414 return (fdopen(fd, "w"));
417 #else /* HAVE_MKSTEMP */
419 FILE *my_fopen_temp(char *buf, int max)
421 /* Generate a temporary filename */
422 if (path_temp(buf, max)) return (NULL);
425 return (my_fopen(buf, "w"));
428 #endif /* HAVE_MKSTEMP */
432 * Hack -- replacement for "fgets()"
434 * Read a string, without a newline, to a file
436 * Process tabs, strip internal non-printables
438 errr my_fgets(FILE *fff, char *buf, huge n)
445 if (fgets(tmp, 1024, fff))
448 guess_convert_to_system_encoding(tmp, sizeof(tmp));
451 /* Convert weirdness */
452 for (s = tmp; *s; s++)
454 #if defined(MACINTOSH) || defined(MACH_O_CARBON) || defined(MACH_O_COCOA)
457 * Be nice to the Macintosh, where a file can have Mac or Unix
458 * end of line, especially since the introduction of OS X.
459 * MPW tools were also very tolerant to the Unix EOL.
461 if (*s == '\r') *s = '\n';
463 #endif /* MACINTOSH || MACH_O_CARBON || MACH_O_COCOA */
478 /* Hack -- require room */
479 if (i + 8 >= n) break;
484 /* Append some more spaces */
485 while (0 != (i % 8)) buf[i++] = ' ';
489 else if (iskanji(*s))
503 /* Handle printables */
504 else if (isprint((unsigned char)*s))
513 /* No newline character, but terminate */
529 * Hack -- replacement for "fputs()"
530 * Dump a string, plus a newline, to a file
531 * Process internal weirdness?
533 errr my_fputs(FILE *fff, concptr buf, huge n)
538 /* Dump, ignore errors */
539 (void)fprintf(fff, "%s\n", buf);
550 * Most of the "file" routines for "ACORN" should be in "main-acn.c"
552 * Many of them can be rewritten now that only "fd_open()" and "fd_make()"
553 * and "my_fopen()" should ever create files.
561 * The Macintosh is a little bit brain-dead sometimes
564 # define open(N,F,M) \
565 ((M), open((char*)(N),F))
566 # define write(F,B,S) \
567 write(F,(char*)(B),S)
568 #endif /* MACINTOSH */
572 * Several systems have no "O_BINARY" flag
576 #endif /* O_BINARY */
580 * Hack -- attempt to delete a file
582 errr fd_kill(concptr file)
586 /* Hack -- Try to parse the path */
587 if (path_parse(buf, 1024, file)) return (-1);
597 * Hack -- attempt to move a file
599 errr fd_move(concptr file, concptr what)
604 /* Hack -- Try to parse the path */
605 if (path_parse(buf, 1024, file)) return (-1);
607 /* Hack -- Try to parse the path */
608 if (path_parse(aux, 1024, what)) return (-1);
611 (void)rename(buf, aux);
618 * Hack -- attempt to copy a file
620 errr fd_copy(concptr file, concptr what)
627 /* Hack -- Try to parse the path */
628 if (path_parse(buf, 1024, file)) return (-1);
630 /* Hack -- Try to parse the path */
631 if (path_parse(aux, 1024, what)) return (-1);
633 /* Open source file */
634 src_fd = fd_open(buf, O_RDONLY);
635 if (src_fd < 0) return (-1);
637 /* Open destination file */
638 dst_fd = fd_open(aux, O_WRONLY|O_TRUNC|O_CREAT);
639 if (dst_fd < 0) return (-1);
642 while ((read_num = read(src_fd, buf, 1024)) > 0)
645 while (write_num < read_num)
647 int ret = write(dst_fd, buf + write_num, read_num - write_num);
667 * Hack -- attempt to open a file descriptor (create file)
668 * This function should fail if the file already exists
669 * Note that we assume that the file should be "binary"
671 int fd_make(concptr file, BIT_FLAGS mode)
675 /* Hack -- Try to parse the path */
676 if (path_parse(buf, 1024, file)) return (-1);
678 #if defined(MAC_MPW) || defined(MACH_O_CARBON)
681 /* Create the file, fail if exists, write-only, binary */
682 fdes = open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, mode);
683 /* Set creator and type if the file is successfully opened */
684 if (fdes >= 0) fsetfileinfo(buf, _fcreator, _ftype);
685 /* Return the descriptor */
689 /* Create the file, fail if exists, write-only, binary */
690 return (open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, mode));
697 * Hack -- attempt to open a file descriptor (existing file)
699 * Note that we assume that the file should be "binary"
701 int fd_open(concptr file, int flags)
705 /* Hack -- Try to parse the path */
706 if (path_parse(buf, 1024, file)) return (-1);
708 /* Attempt to open the file */
709 return (open(buf, flags | O_BINARY, 0));
714 * Hack -- attempt to lock a file descriptor
716 * Legal lock types -- F_UNLCK, F_RDLCK, F_WRLCK
718 errr fd_lock(int fd, int what)
721 what = what ? what : 0;
724 if (fd < 0) return (-1);
730 # if defined(F_ULOCK) && defined(F_LOCK)
735 /* Unlock it, Ignore errors */
736 lockf(fd, F_ULOCK, 0);
742 /* Lock the score file */
743 if (lockf(fd, F_LOCK, 0) != 0) return (1);
750 # if defined(LOCK_UN) && defined(LOCK_EX)
755 /* Unlock it, Ignore errors */
756 (void)flock(fd, LOCK_UN);
762 /* Lock the score file */
763 if (flock(fd, LOCK_EX) != 0) return (1);
778 * Hack -- attempt to seek on a file descriptor
780 errr fd_seek(int fd, huge n)
785 if (fd < 0) return (-1);
787 /* Seek to the given position */
788 p = lseek(fd, n, SEEK_SET);
791 if (p != n) return (1);
799 * Hack -- attempt to truncate a file descriptor
801 errr fd_chop(int fd, huge n)
807 if (fd < 0) return (-1);
809 #if defined(ULTRIX) || defined(NeXT)
820 * Hack -- attempt to read data from a file descriptor
822 errr fd_read(int fd, char *buf, huge n)
825 if (fd < 0) return (-1);
833 if (read(fd, buf, 16384) != 16384) return (1);
835 /* Shorten the task */
838 /* Shorten the task */
844 /* Read the final piece */
845 if (read(fd, buf, n) != (int)n) return (1);
853 * Hack -- Attempt to write data to a file descriptor
855 errr fd_write(int fd, concptr buf, huge n)
858 if (fd < 0) return (-1);
866 if (write(fd, buf, 16384) != 16384) return (1);
868 /* Shorten the task */
871 /* Shorten the task */
877 /* Write the final piece */
878 if (write(fd, buf, n) != (int)n) return (1);
886 * Hack -- attempt to close a file descriptor
888 errr fd_close(int fd)
891 if (fd < 0) return (-1);
906 * Important note about "colors"
908 * The "TERM_*" color definitions list the "composition" of each
909 * "Angband color" in terms of "quarters" of each of the three color
910 * components (Red, Green, Blue), for example, TERM_UMBER is defined
911 * as 2/4 Red, 1/4 Green, 0/4 Blue.
913 * The following info is from "Torbjorn Lindgren" (see "main-xaw.c").
915 * These values are NOT gamma-corrected. On most machines (with the
916 * Macintosh being an important exception), you must "gamma-correct"
917 * the given values, that is, "correct for the intrinsic non-linearity
918 * of the phosphor", by converting the given intensity levels based
919 * on the "gamma" of the target screen, which is usually 1.7 (or 1.5).
921 * The actual formula for conversion is unknown to me at this time,
922 * but you can use the table below for the most common gamma values.
924 * So, on most machines, simply convert the values based on the "gamma"
925 * of the target screen, which is usually in the range 1.5 to 1.7, and
926 * usually is closest to 1.7. The converted value for each of the five
927 * different "quarter" values is given below:
929 * Given Gamma 1.0 Gamma 1.5 Gamma 1.7 Hex 1.7
930 * ----- ---- ---- ---- ---
931 * 0/4 0.00 0.00 0.00 #00
932 * 1/4 0.25 0.27 0.28 #47
933 * 2/4 0.50 0.55 0.56 #8f
934 * 3/4 0.75 0.82 0.84 #d7
935 * 4/4 1.00 1.00 1.00 #ff
937 * Note that some machines (i.e. most IBM machines) are limited to a
938 * hard-coded set of colors, and so the information above is useless.
940 * Also, some machines are limited to a pre-determined set of colors,
941 * for example, the IBM can only display 16 colors, and only 14 of
942 * those colors resemble colors used by Angband, and then only when
943 * you ignore the fact that "Slate" and "cyan" are not really matches,
944 * so on the IBM, we use "orange" for both "Umber", and "Light Umber"
945 * in addition to the obvious "Orange", since by combining all of the
946 * "indeterminate" colors into a single color, the rest of the colors
947 * are left with "meaningful" values.
954 void move_cursor(int row, int col)
956 Term_gotoxy(col, row);
962 * Convert a decimal to a single digit octal number
964 static char octify(uint i)
966 return (hexsym[i%8]);
970 * Convert a decimal to a single digit hex number
972 static char hexify(uint i)
974 return (hexsym[i%16]);
979 * Convert a octal-digit into a decimal
981 static int deoct(char c)
983 if (isdigit(c)) return (D2I(c));
988 * Convert a hexidecimal-digit into a decimal
990 static int dehex(char c)
992 if (isdigit(c)) return (D2I(c));
993 if (islower(c)) return (A2I(c) + 10);
994 if (isupper(c)) return (A2I(tolower(c)) + 10);
999 static int my_stricmp(concptr a, concptr b)
1004 /* Scan the strings */
1005 for (s1 = a, s2 = b; TRUE; s1++, s2++)
1007 z1 = FORCEUPPER(*s1);
1008 z2 = FORCEUPPER(*s2);
1009 if (z1 < z2) return (-1);
1010 if (z1 > z2) return (1);
1011 if (!z1) return (0);
1015 static int my_strnicmp(concptr a, concptr b, int n)
1020 /* Scan the strings */
1021 for (s1 = a, s2 = b; n > 0; s1++, s2++, n--)
1023 z1 = FORCEUPPER(*s1);
1024 z2 = FORCEUPPER(*s2);
1025 if (z1 < z2) return (-1);
1026 if (z1 > z2) return (1);
1027 if (!z1) return (0);
1033 static void trigger_text_to_ascii(char **bufptr, concptr *strptr)
1036 concptr str = *strptr;
1037 bool mod_status[MAX_MACRO_MOD];
1040 int shiftstatus = 0;
1043 if (macro_template == NULL)
1046 for (i = 0; macro_modifier_chr[i]; i++)
1047 mod_status[i] = FALSE;
1050 /* Examine modifier keys */
1053 for (i=0; macro_modifier_chr[i]; i++)
1055 len = strlen(macro_modifier_name[i]);
1057 if(!my_strnicmp(str, macro_modifier_name[i], len))
1060 if (!macro_modifier_chr[i]) break;
1062 mod_status[i] = TRUE;
1063 if ('S' == macro_modifier_chr[i])
1066 for (i = 0; i < max_macrotrigger; i++)
1068 len = strlen(macro_trigger_name[i]);
1069 if (!my_strnicmp(str, macro_trigger_name[i], len) && ']' == str[len])
1071 /* a trigger name found */
1076 /* Invalid trigger name? */
1077 if (i == max_macrotrigger)
1079 str = my_strchr(str, ']');
1085 *strptr = str; /* where **strptr == ']' */
1089 key_code = macro_trigger_keycode[shiftstatus][i];
1093 for (i = 0; macro_template[i]; i++)
1095 char ch = macro_template[i];
1101 for (j = 0; macro_modifier_chr[j]; j++) {
1103 *s++ = macro_modifier_chr[j];
1107 strcpy(s, key_code);
1108 s += strlen(key_code);
1118 *strptr = str; /* where **strptr == ']' */
1124 * Hack -- convert a printable string into real ascii
1126 * I have no clue if this function correctly handles, for example,
1127 * parsing "\xFF" into a (signed) char. Whoever thought of making
1128 * the "sign" of a "char" undefined is a complete moron. Oh well.
1130 void text_to_ascii(char *buf, concptr str)
1134 /* Analyze the "ascii" string */
1137 /* Backslash codes */
1140 /* Skip the backslash */
1147 trigger_text_to_ascii(&s, &str);
1154 *s = 16 * (char)dehex(*++str);
1155 *s++ += (char)dehex(*++str);
1158 /* Hack -- simple way to specify "backslash" */
1159 else if (*str == '\\')
1164 /* Hack -- simple way to specify "caret" */
1165 else if (*str == '^')
1170 /* Hack -- simple way to specify "space" */
1171 else if (*str == 's')
1176 /* Hack -- simple way to specify Escape */
1177 else if (*str == 'e')
1183 else if (*str == 'b')
1189 else if (*str == 'n')
1195 else if (*str == 'r')
1201 else if (*str == 't')
1207 else if (*str == '0')
1209 *s = 8 * (char)deoct(*++str);
1210 *s++ += (char)deoct(*++str);
1214 else if (*str == '1')
1216 *s = 64 + 8 * (char)deoct(*++str);
1217 *s++ += (char)deoct(*++str);
1221 else if (*str == '2')
1223 *s = 64 * 2 + 8 * (char)deoct(*++str);
1224 *s++ += (char)deoct(*++str);
1228 else if (*str == '3')
1230 *s = 64 * 3 + 8 * (char)deoct(*++str);
1231 *s++ += (char)deoct(*++str);
1234 /* Skip the final char */
1238 /* Normal Control codes */
1239 else if (*str == '^')
1242 *s++ = (*str++ & 037);
1257 static bool trigger_ascii_to_text(char **bufptr, concptr *strptr)
1260 concptr str = *strptr;
1265 if (macro_template == NULL)
1271 for (i = 0; macro_template[i]; i++)
1274 char ch = macro_template[i];
1279 while ((tmp = my_strchr(macro_modifier_chr, *str)) != 0)
1281 j = (int)(tmp - macro_modifier_chr);
1282 tmp = macro_modifier_name[j];
1283 while(*tmp) *s++ = *tmp++;
1288 for (j = 0; *str && *str != '\r'; j++)
1289 key_code[j] = *str++;
1293 if (ch != *str) return FALSE;
1297 if (*str++ != '\r') return FALSE;
1299 for (i = 0; i < max_macrotrigger; i++)
1301 if (!my_stricmp(key_code, macro_trigger_keycode[0][i])
1302 || !my_stricmp(key_code, macro_trigger_keycode[1][i]))
1305 if (i == max_macrotrigger)
1308 tmp = macro_trigger_name[i];
1309 while (*tmp) *s++ = *tmp++;
1320 * Hack -- convert a string into a printable form
1322 void ascii_to_text(char *buf, concptr str)
1326 /* Analyze the "ascii" string */
1329 byte i = (byte)(*str++);
1334 if(!trigger_ascii_to_text(&s, &str))
1395 *s++ = octify(i / 8);
1396 *s++ = octify(i % 8);
1402 *s++ = hexify(i / 16);
1403 *s++ = hexify(i % 16);
1414 * The "macro" package
1416 * Functions are provided to manipulate a collection of macros, each
1417 * of which has a trigger pattern string and a resulting action string
1418 * and a small set of flags.
1424 * Determine if any macros have ever started with a given character.
1426 static bool macro__use[256];
1430 * Find the macro (if any) which exactly matches the given pattern
1432 sint macro_find_exact(concptr pat)
1436 /* Nothing possible */
1437 if (!macro__use[(byte)(pat[0])])
1442 /* Scan the macros */
1443 for (i = 0; i < macro__num; ++i)
1445 /* Skip macros which do not match the pattern */
1446 if (!streq(macro__pat[i], pat)) continue;
1458 * Find the first macro (if any) which contains the given pattern
1460 static sint macro_find_check(concptr pat)
1464 /* Nothing possible */
1465 if (!macro__use[(byte)(pat[0])])
1470 /* Scan the macros */
1471 for (i = 0; i < macro__num; ++i)
1473 /* Skip macros which do not contain the pattern */
1474 if (!prefix(macro__pat[i], pat)) continue;
1486 * Find the first macro (if any) which contains the given pattern and more
1488 static sint macro_find_maybe(concptr pat)
1492 /* Nothing possible */
1493 if (!macro__use[(byte)(pat[0])])
1498 /* Scan the macros */
1499 for (i = 0; i < macro__num; ++i)
1501 /* Skip macros which do not contain the pattern */
1502 if (!prefix(macro__pat[i], pat)) continue;
1504 /* Skip macros which exactly match the pattern XXX XXX */
1505 if (streq(macro__pat[i], pat)) continue;
1517 * Find the longest macro (if any) which starts with the given pattern
1519 static sint macro_find_ready(concptr pat)
1521 int i, t, n = -1, s = -1;
1523 /* Nothing possible */
1524 if (!macro__use[(byte)(pat[0])])
1529 /* Scan the macros */
1530 for (i = 0; i < macro__num; ++i)
1532 /* Skip macros which are not contained by the pattern */
1533 if (!prefix(pat, macro__pat[i])) continue;
1535 /* Obtain the length of this macro */
1536 t = strlen(macro__pat[i]);
1538 /* Only track the "longest" pattern */
1539 if ((n >= 0) && (s > t)) continue;
1541 /* Track the entry */
1550 * Add a macro definition (or redefinition).
1552 * We should use "act == NULL" to "remove" a macro, but this might make it
1553 * impossible to save the "removal" of a macro definition.
1555 * We should consider refusing to allow macros which contain existing macros,
1556 * or which are contained in existing macros, because this would simplify the
1557 * macro analysis code.
1559 * We should consider removing the "command macro" crap, and replacing it
1560 * with some kind of "powerful keymap" ability, but this might make it hard
1561 * to change the "roguelike" option from inside the game.
1563 errr macro_add(concptr pat, concptr act)
1568 /* Paranoia -- require data */
1569 if (!pat || !act) return (-1);
1572 /* Look for any existing macro */
1573 n = macro_find_exact(pat);
1575 /* Replace existing macro */
1578 /* Free the old macro action */
1579 string_free(macro__act[n]);
1582 /* Create a new macro */
1585 /* Acquire a new index */
1588 /* Save the pattern */
1589 macro__pat[n] = string_make(pat);
1592 /* Save the action */
1593 macro__act[n] = string_make(act);
1596 macro__use[(byte)(pat[0])] = TRUE;
1605 * Local variable -- we are inside a "macro action"
1607 * Do not match any macros until "ascii 30" is found.
1609 static bool parse_macro = FALSE;
1612 * Local variable -- we are inside a "macro trigger"
1614 * Strip all keypresses until a low ascii value is found.
1616 static bool parse_under = FALSE;
1620 * Flush all input chars. Actually, remember the flush,
1621 * and do a "special flush" before the next "inkey()".
1623 * This is not only more efficient, but also necessary to make sure
1624 * that various "inkey()" codes are not "lost" along the way.
1634 * Flush the screen, make a noise
1638 /* Mega-Hack -- Flush the output */
1641 /* Make a bell noise (if allowed) */
1642 if (ring_bell) Term_xtra(TERM_XTRA_NOISE, 0);
1644 /* Flush the input (later!) */
1650 * Hack -- Make a (relevant?) sound
1655 if (!use_sound) return;
1657 /* Make a sound (if allowed) */
1658 Term_xtra(TERM_XTRA_SOUND, val);
1662 * Hack -- Play a music
1664 errr play_music(int type, int val)
1667 if (!use_music) return 1;
1669 /* Make a sound (if allowed) */
1670 return Term_xtra(type, val);
1674 * Hack -- Select floor music.
1676 void select_floor_music(void)
1680 if (!use_music) return;
1682 if(p_ptr->ambush_flag)
1684 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_AMBUSH);
1688 if(p_ptr->wild_mode)
1690 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_WILD);
1694 if(p_ptr->inside_arena)
1696 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_ARENA);
1700 if(p_ptr->inside_battle)
1702 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_BATTLE);
1706 if(p_ptr->inside_quest)
1708 if(play_music(TERM_XTRA_MUSIC_QUEST, p_ptr->inside_quest))
1710 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_QUEST);
1715 for(i = 0; i < max_q_idx; i++)
1716 { // TODO マクロで類似条件を統合すること
1717 if(quest[i].status == QUEST_STATUS_TAKEN &&
1718 (quest[i].type == QUEST_TYPE_KILL_LEVEL || quest[i].type == QUEST_TYPE_RANDOM) &&
1719 quest[i].level == current_floor_ptr->dun_level && p_ptr->dungeon_idx == quest[i].dungeon)
1721 if(play_music(TERM_XTRA_MUSIC_QUEST, i))
1723 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_QUEST);
1729 if(p_ptr->dungeon_idx)
1731 if(p_ptr->feeling == 2) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_FEEL2);
1732 else if(p_ptr->feeling >= 3 && p_ptr->feeling <= 5) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_FEEL1);
1735 if(play_music(TERM_XTRA_MUSIC_DUNGEON, p_ptr->dungeon_idx))
1737 if(current_floor_ptr->dun_level < 40) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_LOW);
1738 else if(current_floor_ptr->dun_level < 80) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_MED);
1739 else play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_HIGH);
1747 if(play_music(TERM_XTRA_MUSIC_TOWN, p_ptr->town_num))
1749 play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_TOWN);
1754 if(!current_floor_ptr->dun_level)
1756 if(p_ptr->lev >= 45) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD3);
1757 else if(p_ptr->lev >= 25) play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD2);
1758 else play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD1);
1767 * Helper function called only from "inkey()"
1769 * This function does almost all of the "macro" processing.
1771 * We use the "Term_key_push()" function to handle "failed" macros, as well
1772 * as "extra" keys read in while choosing the proper macro, and also to hold
1773 * the action for the macro, plus a special "ascii 30" character indicating
1774 * that any macro action in progress is complete. Embedded macros are thus
1775 * illegal, unless a macro action includes an explicit "ascii 30" character,
1776 * which would probably be a massive hack, and might break things.
1778 * Only 500 (0+1+2+...+29+30) milliseconds may elapse between each key in
1779 * the macro trigger sequence. If a key sequence forms the "prefix" of a
1780 * macro trigger, 500 milliseconds must pass before the key sequence is
1781 * known not to be that macro trigger.
1783 static char inkey_aux(void)
1785 int k = 0, n, p = 0, w = 0;
1791 char *buf = inkey_macro_trigger_string;
1793 /* Hack : キー入力待ちで止まっているので、流れた行の記憶は不要。 */
1798 /* Scan next keypress from macro action */
1799 if (Term_inkey(&ch, FALSE, TRUE))
1801 /* Over-flowed? Cancel macro action */
1802 parse_macro = FALSE;
1807 /* Wait for a keypress */
1808 (void) (Term_inkey(&ch, TRUE, TRUE));
1812 /* End "macro action" */
1813 if (ch == 30) parse_macro = FALSE;
1815 /* Inside "macro action" */
1816 if (ch == 30) return (ch);
1818 /* Inside "macro action" */
1819 if (parse_macro) return (ch);
1821 /* Inside "macro trigger" */
1822 if (parse_under) return (ch);
1824 /* Save the first key, advance */
1829 /* Check for possible macro */
1830 k = macro_find_check(buf);
1832 /* No macro pending */
1833 if (k < 0) return (ch);
1836 /* Wait for a macro, or a timeout */
1839 /* Check for pending macro */
1840 k = macro_find_maybe(buf);
1842 /* No macro pending */
1845 /* Check for (and remove) a pending key */
1846 if (0 == Term_inkey(&ch, FALSE, TRUE))
1848 /* Append the key */
1859 /* Increase "wait" */
1862 /* Excessive delay */
1865 Term_xtra(TERM_XTRA_DELAY, w);
1870 /* Check for available macro */
1871 k = macro_find_ready(buf);
1873 /* No macro available */
1876 /* Push all the keys back on the queue */
1879 /* Push the key, notice over-flow */
1880 if (Term_key_push(buf[--p])) return (0);
1883 /* Wait for (and remove) a pending key */
1884 (void)Term_inkey(&ch, TRUE, TRUE);
1886 /* Return the key */
1891 /* Get the pattern */
1892 pat = macro__pat[k];
1894 /* Get the length of the pattern */
1897 /* Push the "extra" keys back on the queue */
1900 /* Push the key, notice over-flow */
1901 if (Term_key_push(buf[--p])) return (0);
1905 /* Begin "macro action" */
1908 /* Push the "end of macro action" key */
1909 if (Term_key_push(30)) return (0);
1912 /* Access the macro action */
1913 act = macro__act[k];
1915 /* Get the length of the action */
1918 /* Push the macro "action" onto the key queue */
1921 /* Push the key, notice over-flow */
1922 if (Term_key_push(act[--n])) return (0);
1926 /* Hack -- Force "inkey()" to call us again */
1932 * Cancel macro action on the queue
1934 static void forget_macro_action(void)
1936 if (!parse_macro) return;
1938 /* Drop following macro action string */
1943 /* End loop if no key ready */
1944 if (Term_inkey(&ch, FALSE, TRUE)) break;
1946 /* End loop if no key ready */
1949 /* End of "macro action" */
1950 if (ch == 30) break;
1953 /* No longer inside "macro action" */
1954 parse_macro = FALSE;
1959 * Mega-Hack -- special "inkey_next" pointer.
1961 * This special pointer allows a sequence of keys to be "inserted" into
1962 * the stream of keys returned by "inkey()". This key sequence will not
1963 * trigger any macros, and cannot be bypassed by the Borg. It is used
1964 * in Angband to handle "keymaps".
1966 static concptr inkey_next = NULL;
1972 * Mega-Hack -- special "inkey_hack" hook.
1974 * This special function hook allows the "Borg" (see elsewhere) to take
1975 * control of the "inkey()" function, and substitute in fake keypresses.
1977 char (*inkey_hack)(int flush_first) = NULL;
1979 #endif /* ALLOW_BORG */
1984 * Get a keypress from the user.
1986 * This function recognizes a few "global parameters". These are variables
1987 * which, if set to TRUE before calling this function, will have an effect
1988 * on this function, and which are always reset to FALSE by this function
1989 * before this function returns. Thus they function just like normal
1990 * parameters, except that most calls to this function can ignore them.
1992 * If "inkey_xtra" is TRUE, then all pending keypresses will be flushed,
1993 * and any macro processing in progress will be aborted. This flag is
1994 * set by the "flush()" function, which does not actually flush anything
1995 * itself, but rather, triggers delayed input flushing via "inkey_xtra".
1997 * If "inkey_scan" is TRUE, then we will immediately return "zero" if no
1998 * keypress is available, instead of waiting for a keypress.
2000 * If "inkey_base" is TRUE, then all macro processing will be bypassed.
2001 * If "inkey_base" and "inkey_scan" are both TRUE, then this function will
2002 * not return immediately, but will wait for a keypress for as long as the
2003 * normal macro matching code would, allowing the direct entry of macro
2004 * triggers. The "inkey_base" flag is extremely dangerous!
2006 * If "inkey_flag" is TRUE, then we will assume that we are waiting for a
2007 * normal command, and we will only show the cursor if "hilite_player" is
2008 * TRUE (or if the player is in a store), instead of always showing the
2009 * cursor. The various "main-xxx.c" files should avoid saving the game
2010 * in response to a "menu item" request unless "inkey_flag" is TRUE, to
2011 * prevent savefile corruption.
2013 * If we are waiting for a keypress, and no keypress is ready, then we will
2014 * refresh (once) the window which was active when this function was called.
2016 * Note that "back-quote" is automatically converted into "escape" for
2017 * convenience on machines with no "escape" key. This is done after the
2018 * macro matching, so the user can still make a macro for "backquote".
2020 * Note the special handling of "ascii 30" (ctrl-caret, aka ctrl-shift-six)
2021 * and "ascii 31" (ctrl-underscore, aka ctrl-shift-minus), which are used to
2022 * provide support for simple keyboard "macros". These keys are so strange
2023 * that their loss as normal keys will probably be noticed by nobody. The
2024 * "ascii 30" key is used to indicate the "end" of a macro action, which
2025 * allows recursive macros to be avoided. The "ascii 31" key is used by
2026 * some of the "main-xxx.c" files to introduce macro trigger sequences.
2028 * Hack -- we use "ascii 29" (ctrl-right-bracket) as a special "magic" key,
2029 * which can be used to give a variety of "sub-commands" which can be used
2030 * any time. These sub-commands could include commands to take a picture of
2031 * the current screen, to start/stop recording a macro action, etc.
2033 * If "angband_term[0]" is not active, we will make it active during this
2034 * function, so that the various "main-xxx.c" files can assume that input
2035 * is only requested (via "Term_inkey()") when "angband_term[0]" is active.
2037 * Mega-Hack -- This function is used as the entry point for clearing the
2038 * "signal_count" variable, and of the "character_saved" variable.
2040 * Hack -- Note the use of "inkey_next" to allow "keymaps" to be processed.
2042 * Mega-Hack -- Note the use of "inkey_hack" to allow the "Borg" to steal
2043 * control of the keyboard from the user.
2053 /* Hack -- Use the "inkey_next" pointer */
2054 if (inkey_next && *inkey_next && !inkey_xtra)
2056 /* Get next character, and advance */
2059 /* Cancel the various "global parameters" */
2060 inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
2066 /* Forget pointer */
2072 /* Mega-Hack -- Use the special hook */
2073 if (inkey_hack && ((ch = (*inkey_hack)(inkey_xtra)) != 0))
2075 /* Cancel the various "global parameters" */
2076 inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
2082 #endif /* ALLOW_BORG */
2085 /* Hack -- handle delayed "flush()" */
2088 /* End "macro action" */
2089 parse_macro = FALSE;
2091 /* End "macro trigger" */
2092 parse_under = FALSE;
2094 /* Forget old keypresses */
2099 /* Access cursor state */
2100 (void)Term_get_cursor(&v);
2102 /* Show the cursor if waiting, except sometimes in "command" mode */
2103 if (!inkey_scan && (!inkey_flag || hilite_player || character_icky))
2105 /* Show the cursor */
2106 (void)Term_set_cursor(1);
2110 /* Hack -- Activate main screen */
2111 Term_activate(angband_term[0]);
2117 /* Hack -- Handle "inkey_scan" */
2118 if (!inkey_base && inkey_scan &&
2119 (0 != Term_inkey(&kk, FALSE, FALSE)))
2125 /* Hack -- Flush output once when no key ready */
2126 if (!done && (0 != Term_inkey(&kk, FALSE, FALSE)))
2128 /* Hack -- activate proper term */
2134 /* Hack -- activate main screen */
2135 Term_activate(angband_term[0]);
2137 /* Mega-Hack -- reset saved flag */
2138 character_saved = FALSE;
2140 /* Mega-Hack -- reset signal counter */
2148 /* Hack -- Handle "inkey_base" */
2156 /* Wait for (and remove) a pending key */
2157 if (0 == Term_inkey(&ch, TRUE, TRUE))
2168 /* Check for (and remove) a pending key */
2169 if (0 == Term_inkey(&ch, FALSE, TRUE))
2177 /* Increase "wait" */
2180 /* Excessive delay */
2181 if (w >= 100) break;
2183 Term_xtra(TERM_XTRA_DELAY, w);
2191 /* Get a key (see above) */
2195 /* Handle "control-right-bracket" */
2198 /* Strip this key */
2204 /* Treat back-quote as escape */
2205 /* if (ch == '`') ch = ESCAPE; */
2208 /* End "macro trigger" */
2209 if (parse_under && (ch <= 32))
2211 /* Strip this key */
2214 /* End "macro trigger" */
2215 parse_under = FALSE;
2219 /* Handle "control-caret" */
2222 /* Strip this key */
2226 /* Handle "control-underscore" */
2229 /* Strip this key */
2232 /* Begin "macro trigger" */
2236 /* Inside "macro trigger" */
2237 else if (parse_under)
2239 /* Strip this key */
2245 /* Hack -- restore the term */
2249 /* Restore the cursor */
2253 /* Cancel the various "global parameters" */
2254 inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
2256 /* Return the keypress */
2264 * We use a global array for all inscriptions to reduce the memory
2265 * spent maintaining inscriptions. Of course, it is still possible
2266 * to run out of inscription memory, especially if too many different
2267 * inscriptions are used, but hopefully this will be rare.
2269 * We use dynamic string allocation because otherwise it is necessary
2270 * to pre-guess the amount of quark activity. We limit the total
2271 * number of quarks, but this is much easier to "expand" as needed.
2273 * Any two items with the same inscription will have the same "quark"
2274 * index, which should greatly reduce the need for inscription space.
2276 * Note that "quark zero" is NULL and should not be "dereferenced".
2280 * Initialize the quark array
2282 void quark_init(void)
2284 /* Quark variables */
2285 C_MAKE(quark__str, QUARK_MAX, concptr);
2287 /* Prepare first quark, which is used when quark_add() is failed */
2288 quark__str[1] = string_make("");
2290 /* There is one quark (+ NULL) */
2296 * Add a new "quark" to the set of quarks.
2298 u16b quark_add(concptr str)
2302 /* Look for an existing quark */
2303 for (i = 1; i < quark__num; i++)
2305 /* Check for equality */
2306 if (streq(quark__str[i], str)) return (i);
2309 /* Return "" when no room is available */
2310 if (quark__num == QUARK_MAX) return 1;
2312 /* New maximal quark */
2315 /* Add a new quark */
2316 quark__str[i] = string_make(str);
2318 /* Return the index */
2324 * This function looks up a quark
2326 concptr quark_str(STR_OFFSET i)
2330 /* Return NULL for an invalid index */
2331 if ((i < 1) || (i >= quark__num)) return NULL;
2333 /* Access the quark */
2336 /* Return the quark */
2344 * Second try for the "message" handling routines.
2346 * Each call to "message_add(s)" will add a new "most recent" message
2347 * to the "message recall list", using the contents of the string "s".
2349 * The messages will be stored in such a way as to maximize "efficiency",
2350 * that is, we attempt to maximize the number of sequential messages that
2351 * can be retrieved, given a limited amount of storage space.
2353 * We keep a buffer of chars to hold the "text" of the messages, not
2354 * necessarily in "order", and an array of offsets into that buffer,
2355 * representing the actual messages. This is made more complicated
2356 * by the fact that both the array of indexes, and the buffer itself,
2357 * are both treated as "circular arrays" for efficiency purposes, but
2358 * the strings may not be "broken" across the ends of the array.
2360 * The "message_add()" function is rather "complex", because it must be
2361 * extremely efficient, both in space and time, for use with the Borg.
2367 * @brief 保存中の過去ゲームメッセージの数を返す。 / How many messages are "available"?
2368 * @return 残っているメッセージの数
2370 s32b message_num(void)
2374 /* Extract the indexes */
2375 last = message__last;
2376 next = message__next;
2379 if (next < last) next += MESSAGE_MAX;
2381 /* Extract the space */
2384 /* Return the result */
2390 * @brief 過去のゲームメッセージを返す。 / Recall the "text" of a saved message
2391 * @params age メッセージの世代
2392 * @return メッセージの文字列ポインタ
2394 concptr message_str(int age)
2400 /* Forgotten messages have no text */
2401 if ((age < 0) || (age >= message_num())) return ("");
2403 /* Acquire the "logical" index */
2404 x = (message__next + MESSAGE_MAX - (age + 1)) % MESSAGE_MAX;
2406 /* Get the "offset" for the message */
2407 o = message__ptr[x];
2409 /* Access the message text */
2410 s = &message__buf[o];
2412 /* Return the message text */
2418 * @brief ゲームメッセージをログに追加する。 / Add a new message, with great efficiency
2419 * @params str 保存したいメッセージ
2422 void message_add(concptr str)
2431 /*** Step 1 -- Analyze the message ***/
2433 /* Hack -- Ignore "non-messages" */
2436 /* Message length */
2439 /* Important Hack -- Ignore "long" messages */
2440 if (n >= MESSAGE_BUF / 4) return;
2442 /* extra step -- split the message if n>80.(added by Mogami) */
2447 for (n = 0; n < 80; n++, t++)
2454 if (n == 81) n = 79; /* 最後の文字が漢字半分 */
2456 for (n = 80; n > 60; n--)
2457 if (str[n] == ' ') break;
2458 if (n == 60) n = 80;
2460 splitted2 = str + n;
2461 strncpy(splitted1, str ,n);
2462 splitted1[n] = '\0';
2468 /*** Step 2 -- 最適化の試行 / Attempt to optimize ***/
2470 /* Limit number of messages to check */
2473 if (k > MESSAGE_MAX / 32) k = MESSAGE_MAX / 32;
2475 /* Check previous message */
2476 for (i = message__next; m; m--)
2485 /* Back up and wrap if needed */
2486 if (i-- == 0) i = MESSAGE_MAX - 1;
2488 /* Access the old string */
2489 old = &message__buf[message__ptr[i]];
2491 /* Skip small messages */
2498 for (t = buf; *t && (*t != '<' || (*(t+1) != 'x' )); t++)
2501 for (t = buf; *t && (*t != '<'); t++);
2506 /* Message is too small */
2507 if (strlen(buf) < A_MAX) break;
2509 /* Drop the space */
2512 /* Get multiplier */
2516 /* Limit the multiplier to 1000 */
2517 if (streq(buf, str) && (j < 1000))
2527 sprintf(u, "%s <x%d>", buf, j);
2529 /* Message length */
2532 if (!now_message) now_message++;
2536 num_more++;/*流れた行の数を数えておく */
2543 /* Check the last few messages (if any to count) */
2544 for (i = message__next; k; k--)
2549 /* Back up and wrap if needed */
2550 if (i-- == 0) i = MESSAGE_MAX - 1;
2552 /* Stop before oldest message */
2553 if (i == message__last) break;
2555 /* Extract "distance" from "head" */
2556 q = (message__head + MESSAGE_BUF - message__ptr[i]) % MESSAGE_BUF;
2558 /* Do not optimize over large distance */
2559 if (q > MESSAGE_BUF / 2) continue;
2561 /* Access the old string */
2562 old = &message__buf[message__ptr[i]];
2565 if (!streq(old, str)) continue;
2567 /* Get the next message index, advance */
2568 x = message__next++;
2571 if (message__next == MESSAGE_MAX) message__next = 0;
2573 /* Kill last message if needed */
2574 if (message__next == message__last) message__last++;
2577 if (message__last == MESSAGE_MAX) message__last = 0;
2579 /* Assign the starting address */
2580 message__ptr[x] = message__ptr[i];
2584 goto end_of_message_add;
2589 /*** Step 3 -- Ensure space before end of buffer ***/
2591 /* Kill messages and Wrap if needed */
2592 if (message__head + n + 1 >= MESSAGE_BUF)
2594 /* Kill all "dead" messages */
2595 for (i = message__last; TRUE; i++)
2597 /* Wrap if needed */
2598 if (i == MESSAGE_MAX) i = 0;
2600 /* Stop before the new message */
2601 if (i == message__next) break;
2603 /* Kill "dead" messages */
2604 if (message__ptr[i] >= message__head)
2606 /* Track oldest message */
2607 message__last = i + 1;
2611 /* Wrap "tail" if needed */
2612 if (message__tail >= message__head) message__tail = 0;
2619 /*** Step 4 -- Ensure space before next message ***/
2621 /* Kill messages if needed */
2622 if (message__head + n + 1 > message__tail)
2624 /* Grab new "tail" */
2625 message__tail = message__head + n + 1;
2627 /* Advance tail while possible past first "nul" */
2628 while (message__buf[message__tail-1]) message__tail++;
2630 /* Kill all "dead" messages */
2631 for (i = message__last; TRUE; i++)
2633 /* Wrap if needed */
2634 if (i == MESSAGE_MAX) i = 0;
2636 /* Stop before the new message */
2637 if (i == message__next) break;
2639 /* Kill "dead" messages */
2640 if ((message__ptr[i] >= message__head) &&
2641 (message__ptr[i] < message__tail))
2643 /* Track oldest message */
2644 message__last = i + 1;
2650 /*** Step 5 -- Grab a new message index ***/
2652 /* Get the next message index, advance */
2653 x = message__next++;
2656 if (message__next == MESSAGE_MAX) message__next = 0;
2658 /* Kill last message if needed */
2659 if (message__next == message__last) message__last++;
2662 if (message__last == MESSAGE_MAX) message__last = 0;
2666 /*** Step 6 -- Insert the message text ***/
2668 /* Assign the starting address */
2669 message__ptr[x] = message__head;
2671 /* Append the new part of the message */
2672 for (i = 0; i < n; i++)
2674 /* Copy the message */
2675 message__buf[message__head + i] = str[i];
2679 message__buf[message__head + i] = '\0';
2681 /* Advance the "head" pointer */
2682 message__head += n + 1;
2684 /* recursively add splitted message (added by Mogami) */
2686 if (splitted2 != NULL)
2687 message_add(splitted2);
2695 static void msg_flush(int x)
2697 byte a = TERM_L_BLUE;
2698 bool nagasu = FALSE;
2700 if ((auto_more && !p_ptr->now_damaged) || num_more < 0){
2702 for (i = 0; i < 8; i++)
2704 if (angband_term[i] && (window_flag[i] & PW_MESSAGE)) break;
2708 if (num_more < angband_term[i]->hgt) nagasu = TRUE;
2715 p_ptr->now_damaged = FALSE;
2717 if (!p_ptr->playing || !nagasu)
2719 /* Pause for response */
2720 Term_putstr(x, 0, -1, a, _("-続く-", "-more-"));
2722 /* Get an acceptable keypress */
2726 if (cmd == ESCAPE) {
2727 num_more = -9999; /*auto_moreのとき、全て流す。 */
2729 } else if (cmd == ' ') {
2730 num_more = 0; /*1画面だけ流す。 */
2732 } else if ((cmd == '\n') || (cmd == '\r')) {
2733 num_more--; /*1行だけ流す。 */
2736 if (quick_messages) break;
2741 /* Clear the line */
2742 Term_erase(0, 0, 255);
2746 void msg_erase(void)
2753 * Output a message to the top line of the screen.
2755 * Break long messages into multiple pieces (40-72 chars).
2757 * Allow multiple short messages to "share" the top line.
2759 * Prompt the user to make sure he has a chance to read them.
2761 * These messages are memorized for later reference (see above).
2763 * We could do "Term_fresh()" to provide "flicker" if needed.
2765 * The global "msg_flag" variable can be cleared to tell us to
2766 * "erase" any "pending" messages still on the screen.
2768 * Note that we must be very careful about using the
2769 * "msg_print()" functions without explicitly calling the special
2770 * "msg_print(NULL)" function, since this may result in the loss
2771 * of information if the screen is cleared, or if anything is
2772 * displayed on the top line.
2774 * Note that "msg_print(NULL)" will clear the top line
2775 * even if no messages are pending. This is probably a hack.
2777 void msg_print(concptr msg)
2784 if (current_world_ptr->timewalk_m_idx) return;
2788 /* Clear the line */
2789 Term_erase(0, 0, 255);
2793 /* Original Message Length */
2794 n = (msg ? strlen(msg) : 0);
2796 /* Hack -- flush when requested or needed */
2797 if (p && (!msg || ((p + n) > 72)))
2810 if (n > 1000) return;
2819 sprintf(buf, ("T:%d - %s"), (int)current_world_ptr->game_turn, msg);
2822 /* New Message Length */
2825 /* Memorize the message */
2826 if (character_generated) message_add(buf);
2828 /* Analyze the buffer */
2835 int check, split = 72;
2838 bool k_flag = FALSE;
2841 /* Find the "best" split point */
2842 for (check = 0; check < 72; check++)
2850 /* Found a valid split point */
2851 if (iskanji(t[check]))
2856 else if (t[check] == ' ')
2869 /* Find the "best" split point */
2870 for (check = 40; check < 72; check++)
2872 /* Found a valid split point */
2873 if (t[check] == ' ') split = check;
2877 /* Save the split character */
2880 /* Split the message */
2883 /* Display part of the message */
2884 Term_putstr(0, 0, split, TERM_WHITE, t);
2887 msg_flush(split + 1);
2889 /* Memorize the piece */
2890 /* if (character_generated) message_add(t); */
2892 /* Restore the split character */
2895 /* Insert a space */
2898 /* Prepare to recurse on the rest of "buf" */
2899 t += split; n -= split;
2902 /* Display the tail of the message */
2903 Term_putstr(p, 0, n, TERM_WHITE, t);
2905 /* Memorize the tail */
2906 /* if (character_generated) message_add(t); */
2908 p_ptr->window |= (PW_MESSAGE);
2911 /* Remember the message */
2914 /* Remember the position */
2921 /* Optional refresh */
2922 if (fresh_message) Term_fresh();
2925 void msg_print_wizard(int cheat_type, concptr msg)
2927 if (!cheat_room && cheat_type == CHEAT_DUNGEON) return;
2928 if (!cheat_peek && cheat_type == CHEAT_OBJECT) return;
2929 if (!cheat_hear && cheat_type == CHEAT_MONSTER) return;
2930 if (!cheat_xtra && cheat_type == CHEAT_MISC) return;
2932 concptr cheat_mes[] = {"ITEM", "MONS", "DUNG", "MISC"};
2934 sprintf(buf, "WIZ-%s:%s", cheat_mes[cheat_type], msg);
2937 if (cheat_diary_output)
2939 do_cmd_write_nikki(NIKKI_WIZARD_LOG, 0, buf);
2945 * Hack -- prevent "accidents" in "screen_save()" or "screen_load()"
2947 static int screen_depth = 0;
2951 * Save the screen, and increase the "icky" depth.
2953 * This function must match exactly one call to "screen_load()".
2955 void screen_save(void)
2957 /* Hack -- Flush messages */
2960 /* Save the screen (if legal) */
2961 if (screen_depth++ == 0) Term_save();
2963 /* Increase "icky" depth */
2969 * Load the screen, and decrease the "icky" depth.
2971 * This function must match exactly one call to "screen_save()".
2973 void screen_load(void)
2975 /* Hack -- Flush messages */
2978 /* Load the screen (if legal) */
2979 if (--screen_depth == 0) Term_load();
2981 /* Decrease "icky" depth */
2987 * Display a formatted message, using "vstrnfmt()" and "msg_print()".
2989 void msg_format(concptr fmt, ...)
2995 /* Begin the Varargs Stuff */
2998 /* Format the args, save the length */
2999 (void)vstrnfmt(buf, 1024, fmt, vp);
3001 /* End the Varargs Stuff */
3009 * Display a formatted message, using "vstrnfmt()" and "msg_print()".
3011 void msg_format_wizard(int cheat_type, concptr fmt, ...)
3013 if(!cheat_room && cheat_type == CHEAT_DUNGEON) return;
3014 if(!cheat_peek && cheat_type == CHEAT_OBJECT) return;
3015 if(!cheat_hear && cheat_type == CHEAT_MONSTER) return;
3016 if(!cheat_xtra && cheat_type == CHEAT_MISC) return;
3021 /* Begin the Varargs Stuff */
3024 /* Format the args, save the length */
3025 (void)vstrnfmt(buf, 1024, fmt, vp);
3027 /* End the Varargs Stuff */
3031 msg_print_wizard(cheat_type, buf);
3037 * Display a string on the screen using an attribute.
3039 * At the given location, using the given attribute, if allowed,
3040 * add the given string. Do not clear the line.
3042 void c_put_str(TERM_COLOR attr, concptr str, TERM_LEN row, TERM_LEN col)
3044 /* Position cursor, Dump the attr/text */
3045 Term_putstr(col, row, -1, attr, str);
3049 * As above, but in "white"
3051 void put_str(concptr str, TERM_LEN row, TERM_LEN col)
3054 Term_putstr(col, row, -1, TERM_WHITE, str);
3060 * Display a string on the screen using an attribute, and clear
3061 * to the end of the line.
3063 void c_prt(TERM_COLOR attr, concptr str, TERM_LEN row, TERM_LEN col)
3065 /* Clear line, position cursor */
3066 Term_erase(col, row, 255);
3068 /* Dump the attr/text */
3069 Term_addstr(-1, attr, str);
3073 * As above, but in "white"
3075 void prt(concptr str, TERM_LEN row, TERM_LEN col)
3078 c_prt(TERM_WHITE, str, row, col);
3085 * Print some (colored) text to the screen at the current cursor position,
3086 * automatically "wrapping" existing text (at spaces) when necessary to
3087 * avoid placing any text into the last column, and clearing every line
3088 * before placing any text in that line. Also, allow "newline" to force
3089 * a "wrap" to the next line. Advance the cursor as needed so sequential
3090 * calls to this function will work correctly.
3092 * Once this function has been called, the cursor should not be moved
3093 * until all the related "c_roff()" calls to the window are complete.
3095 * This function will correctly handle any width up to the maximum legal
3096 * value of 256, though it works best for a standard 80 character width.
3098 void c_roff(byte a, concptr str)
3106 /* Obtain the size */
3107 (void)Term_get_size(&w, &h);
3109 /* Obtain the cursor */
3110 (void)Term_locate(&x, &y);
3112 /* Hack -- No more space */
3113 if( y == h - 1 && x > w - 3) return;
3115 /* Process the string */
3116 for (s = str; *s; s++)
3121 int k_flag = iskanji(*s);
3133 /* Clear line, move cursor */
3134 Term_erase(x, y, 255);
3139 /* Clean up the char */
3141 ch = ((k_flag || isprint(*s)) ? *s : ' ');
3143 ch = (isprint(*s) ? *s : ' ');
3147 /* Wrap words as needed */
3149 if (( x >= ( (k_flag) ? w - 2 : w - 1 ) ) && (ch != ' '))
3151 if ((x >= w - 1) && (ch != ' '))
3168 /* Scan existing text */
3169 for (i = w - 2; i >= 0; i--)
3171 /* Grab existing attr/char */
3172 Term_what(i, y, &av[i], &cv[i]);
3174 /* Break on space */
3175 if (cv[i] == ' ') break;
3177 /* Track current word */
3180 if (cv[i] == '(') break;
3189 /* 文頭が「。」「、」等になるときは、その1つ前の語で改行 */
3190 if (strncmp(s, "。", 2) == 0 || strncmp(s, "、", 2) == 0
3191 #if 0 /* 一般的には「ィ」「ー」は禁則の対象外 */
3192 || strncmp(s, "ィ", 2) == 0 || strncmp(s, "ー", 2) == 0
3195 Term_what(x , y, &av[x ], &cv[x ]);
3196 Term_what(x-1, y, &av[x-1], &cv[x-1]);
3197 Term_what(x-2, y, &av[x-2], &cv[x-2]);
3208 Term_erase(n, y, 255);
3217 /* Clear line, move cursor */
3218 Term_erase(x, y, 255);
3220 /* Wrap the word (if any) */
3221 for (i = n; i < w - 1; i++)
3224 if( cv[i] == '\0' ) break;
3227 Term_addch(av[i], cv[i]);
3229 /* Advance (no wrap) */
3236 Term_addch((byte)(a|0x10), ch);
3248 Term_addch((byte)(a|0x20), ch);
3257 * As above, but in "white"
3259 void roff(concptr str)
3262 c_roff(TERM_WHITE, str);
3269 * Clear part of the screen
3271 void clear_from(int row)
3275 /* Erase requested rows */
3276 for (y = row; y < Term->hgt; y++)
3278 /* Erase part of the screen */
3279 Term_erase(0, y, 255);
3287 * Get some string input at the cursor location.
3288 * Assume the buffer is initialized to a default string.
3290 * The default buffer is in Overwrite mode and displayed in yellow at
3291 * first. Normal chars clear the yellow text and append the char in
3294 * LEFT (^B) and RIGHT (^F) movement keys move the cursor position.
3295 * If the text is still displayed in yellow (Overwite mode), it will
3296 * turns into white (Insert mode) when cursor moves.
3298 * DELETE (^D) deletes a char at the cursor position.
3299 * BACKSPACE (^H) deletes a char at the left of cursor position.
3300 * ESCAPE clears the buffer and the window and returns FALSE.
3301 * RETURN accepts the current buffer contents and returns TRUE.
3303 bool askfor_aux(char *buf, int len, bool numpad_cursor)
3310 * TERM_YELLOW : Overwrite mode
3311 * TERM_WHITE : Insert mode
3313 byte color = TERM_YELLOW;
3315 /* Locate the cursor position */
3316 Term_locate(&x, &y);
3318 /* Paranoia -- check len */
3319 if (len < 1) len = 1;
3321 /* Paranoia -- check column */
3322 if ((x < 0) || (x >= 80)) x = 0;
3324 /* Restrict the length */
3325 if (x + len > 80) len = 80 - x;
3327 /* Paranoia -- Clip the default entry */
3336 /* Display the string */
3337 Term_erase(x, y, len);
3338 Term_putstr(x, y, -1, color, buf);
3341 Term_gotoxy(x + pos, y);
3343 /* Get a special key code */
3344 skey = inkey_special(numpad_cursor);
3346 /* Analyze the key */
3354 /* Now on insert mode */
3357 /* No move at beginning of line */
3358 if (0 == pos) break;
3362 int next_pos = i + 1;
3365 if (iskanji(buf[i])) next_pos++;
3368 /* Is there the cursor at next position? */
3369 if (next_pos >= pos) break;
3375 /* Get previous position */
3383 /* Now on insert mode */
3386 /* No move at end of line */
3387 if ('\0' == buf[pos]) break;
3391 if (iskanji(buf[pos])) pos += 2;
3414 /* Now on insert mode */
3417 /* No move at beginning of line */
3418 if (0 == pos) break;
3422 int next_pos = i + 1;
3425 if (iskanji(buf[i])) next_pos++;
3428 /* Is there the cursor at next position? */
3429 if (next_pos >= pos) break;
3435 /* Get previous position */
3438 /* Fall through to 'Delete key' */
3447 /* Now on insert mode */
3450 /* No move at end of line */
3451 if ('\0' == buf[pos]) break;
3453 /* Position of next character */
3457 /* Next character is one more byte away */
3458 if (iskanji(buf[pos])) src++;
3463 /* Move characters at src to dst */
3464 while ('\0' != (buf[dst++] = buf[src++]))
3472 /* Insert a character */
3477 /* Ignore special keys */
3478 if (skey & SKEY_MASK) break;
3480 /* Get a character code */
3483 if (color == TERM_YELLOW)
3485 /* Overwrite default string */
3488 /* Go to insert mode */
3492 /* Save right part of string */
3493 strcpy(tmp, buf + pos);
3499 /* Bypass macro processing */
3517 if (pos < len && (isprint(c) || iskana(c)))
3519 if (pos < len && isprint(c))
3533 /* Write back the left part of string */
3534 my_strcat(buf, tmp, len + 1);
3541 } /* while (TRUE) */
3546 * Get some string input at the cursor location.
3548 * Allow to use numpad keys as cursor keys.
3550 bool askfor(char *buf, int len)
3552 return askfor_aux(buf, len, TRUE);
3557 * Get a string from the user
3559 * The "prompt" should take the form "Prompt: "
3561 * Note that the initial contents of the string is used as
3562 * the default response, so be sure to "clear" it if needed.
3564 * We clear the input, and return FALSE, on "ESCAPE".
3566 bool get_string(concptr prompt, char *buf, int len)
3571 /* Display prompt */
3574 /* Ask the user for a string */
3575 res = askfor(buf, len);
3584 * Verify something with the user
3586 * The "prompt" should take the form "Query? "
3588 * Note that "[y/n]" is appended to the prompt.
3590 bool get_check(concptr prompt)
3592 return get_check_strict(prompt, 0);
3596 * Verify something with the user strictly
3598 * mode & CHECK_OKAY_CANCEL : force user to answer 'O'kay or 'C'ancel
3599 * mode & CHECK_NO_ESCAPE : don't allow ESCAPE key
3600 * mode & CHECK_NO_HISTORY : no message_add
3601 * mode & CHECK_DEFAULT_Y : accept any key as y, except n and Esc.
3603 bool get_check_strict(concptr prompt, BIT_FLAGS mode)
3611 p_ptr->window |= PW_MESSAGE;
3617 if (!rogue_like_commands)
3618 mode &= ~CHECK_OKAY_CANCEL;
3621 /* Hack -- Build a "useful" prompt */
3622 if (mode & CHECK_OKAY_CANCEL)
3624 my_strcpy(buf, prompt, sizeof(buf)-15);
3625 strcat(buf, "[(O)k/(C)ancel]");
3627 else if (mode & CHECK_DEFAULT_Y)
3629 my_strcpy(buf, prompt, sizeof(buf)-5);
3630 strcat(buf, "[Y/n]");
3634 my_strcpy(buf, prompt, sizeof(buf)-5);
3635 strcat(buf, "[y/n]");
3641 if (!(mode & CHECK_NO_HISTORY) && p_ptr->playing)
3643 /* HACK : Add the line to message buffer */
3645 p_ptr->window |= (PW_MESSAGE);
3649 /* Get an acceptable answer */
3654 if (!(mode & CHECK_NO_ESCAPE))
3663 if (mode & CHECK_OKAY_CANCEL)
3665 if (i == 'o' || i == 'O')
3670 else if (i == 'c' || i == 'C')
3678 if (i == 'y' || i == 'Y')
3683 else if (i == 'n' || i == 'N')
3690 if (mode & CHECK_DEFAULT_Y)
3699 /* Erase the prompt */
3702 /* Return the flag */
3708 * Prompts for a keypress
3710 * The "prompt" should take the form "Command: "
3712 * Returns TRUE unless the character is "Escape"
3714 bool get_com(concptr prompt, char *command, bool z_escape)
3718 /* Display a prompt */
3722 if (get_com_no_macros)
3723 *command = (char)inkey_special(FALSE);
3727 /* Clear the prompt */
3730 /* Handle "cancel" */
3731 if (*command == ESCAPE) return (FALSE);
3732 if (z_escape && ((*command == 'z') || (*command == 'Z'))) return (FALSE);
3740 * Request a "quantity" from the user
3742 * Hack -- allow "command_arg" to specify a quantity
3744 QUANTITY get_quantity(concptr prompt, QUANTITY max)
3753 /* Use "command_arg" */
3756 /* Extract a number */
3759 /* Clear "command_arg" */
3762 /* Enforce the maximum */
3763 if (amt > max) amt = max;
3769 /* Get the item index */
3770 result = repeat_pull(&code);
3771 amt = (QUANTITY)code;
3772 if ((max != 1) && result)
3774 /* Enforce the maximum */
3775 if (amt > max) amt = max;
3777 /* Enforce the minimum */
3778 if (amt < 0) amt = 0;
3784 /* Build a prompt if needed */
3787 /* Build a prompt */
3788 sprintf(tmp, _("いくつですか (1-%d): ", "Quantity (1-%d): "), max);
3790 /* Use that prompt */
3795 /* Display prompt */
3798 /* Default to one */
3801 /* Build the default */
3802 sprintf(buf, "%d", amt);
3805 * Ask for a quantity
3806 * Don't allow to use numpad as cursor key.
3808 res = askfor_aux(buf, 6, FALSE);
3816 /* Extract a number */
3817 amt = (COMMAND_CODE)atoi(buf);
3819 /* A letter means "all" */
3820 if (isalpha(buf[0])) amt = max;
3822 /* Enforce the maximum */
3823 if (amt > max) amt = max;
3825 /* Enforce the minimum */
3826 if (amt < 0) amt = 0;
3828 if (amt) repeat_push((COMMAND_CODE)amt);
3830 /* Return the result */
3836 * Pause for user response
3838 void pause_line(int row)
3841 put_str(_("[ 何かキーを押して下さい ]", "[Press any key to continue]"), row, _(26, 23));
3849 * Hack -- special buffer to hold the action of the current keymap
3851 static char request_command_buffer[256];
3863 menu_naiyou menu_info[10][10] =
3866 {"魔法/特殊能力", 1, FALSE},
3868 {"道具(使用)", 3, FALSE},
3869 {"道具(その他)", 4, FALSE},
3879 {"使う(m)", 'm', TRUE},
3880 {"調べる(b/P)", 'b', TRUE},
3881 {"覚える(G)", 'G', TRUE},
3882 {"特殊能力を使う(U/O)", 'U', TRUE},
3892 {"休息する(R)", 'R', TRUE},
3893 {"トラップ解除(D)", 'D', TRUE},
3894 {"探す(s)", 's', TRUE},
3895 {"周りを調べる(l/x)", 'l', TRUE},
3896 {"ターゲット指定(*)", '*', TRUE},
3897 {"穴を掘る(T/^t)", 'T', TRUE},
3898 {"階段を上る(<)", '<', TRUE},
3899 {"階段を下りる(>)", '>', TRUE},
3900 {"ペットに命令する(p)", 'p', TRUE},
3901 {"探索モードのON/OFF(S/#)", 'S', TRUE}
3905 {"読む(r)", 'r', TRUE},
3906 {"飲む(q)", 'q', TRUE},
3907 {"杖を使う(u/Z)", 'u', TRUE},
3908 {"魔法棒で狙う(a/z)", 'a', TRUE},
3909 {"ロッドを振る(z/a)", 'z', TRUE},
3910 {"始動する(A)", 'A', TRUE},
3911 {"食べる(E)", 'E', TRUE},
3912 {"飛び道具で撃つ(f/t)", 'f', TRUE},
3913 {"投げる(v)", 'v', TRUE},
3918 {"拾う(g)", 'g', TRUE},
3919 {"落とす(d)", 'd', TRUE},
3920 {"壊す(k/^d)", 'k', TRUE},
3921 {"銘を刻む({)", '{', TRUE},
3922 {"銘を消す(})", '}', TRUE},
3923 {"調査(I)", 'I', TRUE},
3924 {"アイテム一覧(i)", 'i', TRUE},
3931 {"装備する(w)", 'w', TRUE},
3932 {"装備を外す(t/T)", 't', TRUE},
3933 {"燃料を補給(F)", 'F', TRUE},
3934 {"装備一覧(e)", 'e', TRUE},
3944 {"開ける(o)", 'o', TRUE},
3945 {"閉じる(c)", 'c', TRUE},
3946 {"体当たりする(B/f)", 'B', TRUE},
3947 {"くさびを打つ(j/S)", 'j', TRUE},
3957 {"ダンジョンの全体図(M)", 'M', TRUE},
3958 {"位置を確認(L/W)", 'L', TRUE},
3959 {"階の雰囲気(^f)", KTRL('F'), TRUE},
3960 {"ステータス(C)", 'C', TRUE},
3961 {"文字の説明(/)", '/', TRUE},
3962 {"メッセージ履歴(^p)", KTRL('P'), TRUE},
3963 {"現在の時刻(^t/')", KTRL('T'), TRUE},
3964 {"現在の知識(~)", '~', TRUE},
3965 {"プレイ記録(|)", '|', TRUE},
3970 {"オプション(=)", '=', TRUE},
3971 {"マクロ(@)", '@', TRUE},
3972 {"画面表示(%)", '%', TRUE},
3973 {"カラー(&)", '&', TRUE},
3974 {"設定変更コマンド(\")", '\"', TRUE},
3975 {"自動拾いをロード($)", '$', TRUE},
3976 {"システム(!)", '!', TRUE},
3983 {"セーブ&中断(^x)", KTRL('X'), TRUE},
3984 {"セーブ(^s)", KTRL('S'), TRUE},
3985 {"ヘルプ(?)", '?', TRUE},
3986 {"再描画(^r)", KTRL('R'), TRUE},
3987 {"メモ(:)", ':', TRUE},
3988 {"記念撮影())", ')', TRUE},
3989 {"記念撮影の表示(()", '(', TRUE},
3990 {"バージョン情報(V)", 'V', TRUE},
3991 {"引退する(Q)", 'Q', TRUE},
3996 menu_naiyou menu_info[10][10] =
3999 {"Magic/Special", 1, FALSE},
4000 {"Action", 2, FALSE},
4001 {"Items(use)", 3, FALSE},
4002 {"Items(other)", 4, FALSE},
4003 {"Equip", 5, FALSE},
4004 {"Door/Box", 6, FALSE},
4005 {"Information", 7, FALSE},
4006 {"Options", 8, FALSE},
4007 {"Other commands", 9, FALSE},
4012 {"Use(m)", 'm', TRUE},
4013 {"See tips(b/P)", 'b', TRUE},
4014 {"Study(G)", 'G', TRUE},
4015 {"Special abilities(U/O)", 'U', TRUE},
4025 {"Rest(R)", 'R', TRUE},
4026 {"Disarm a trap(D)", 'D', TRUE},
4027 {"Search(s)", 's', TRUE},
4028 {"Look(l/x)", 'l', TRUE},
4029 {"Target(*)", '*', TRUE},
4030 {"Dig(T/^t)", 'T', TRUE},
4031 {"Go up stairs(<)", '<', TRUE},
4032 {"Go down stairs(>)", '>', TRUE},
4033 {"Command pets(p)", 'p', TRUE},
4034 {"Search mode ON/OFF(S/#)", 'S', TRUE}
4038 {"Read a scroll(r)", 'r', TRUE},
4039 {"Drink a potion(q)", 'q', TRUE},
4040 {"Use a staff(u/Z)", 'u', TRUE},
4041 {"Aim a wand(a/z)", 'a', TRUE},
4042 {"Zap a rod(z/a)", 'z', TRUE},
4043 {"Activate an equipment(A)", 'A', TRUE},
4044 {"Eat(E)", 'E', TRUE},
4045 {"Fire missile weapon(f/t)", 'f', TRUE},
4046 {"Throw an item(v)", 'v', TRUE},
4051 {"Get items(g)", 'g', TRUE},
4052 {"Drop an item(d)", 'd', TRUE},
4053 {"Destroy an item(k/^d)", 'k', TRUE},
4054 {"Inscribe an item({)", '{', TRUE},
4055 {"Uninscribe an item(})", '}', TRUE},
4056 {"Info about an item(I)", 'I', TRUE},
4057 {"Inventory list(i)", 'i', TRUE},
4064 {"Wear(w)", 'w', TRUE},
4065 {"Take off(t/T)", 't', TRUE},
4066 {"Refuel(F)", 'F', TRUE},
4067 {"Equipment list(e)", 'e', TRUE},
4077 {"Open(o)", 'o', TRUE},
4078 {"Close(c)", 'c', TRUE},
4079 {"Bash a door(B/f)", 'B', TRUE},
4080 {"Jam a door(j/S)", 'j', TRUE},
4090 {"Full map(M)", 'M', TRUE},
4091 {"Map(L/W)", 'L', TRUE},
4092 {"Level feeling(^f)", KTRL('F'), TRUE},
4093 {"Character status(C)", 'C', TRUE},
4094 {"Identify symbol(/)", '/', TRUE},
4095 {"Show prev messages(^p)", KTRL('P'), TRUE},
4096 {"Current time(^t/')", KTRL('T'), TRUE},
4097 {"Various information(~)", '~', TRUE},
4098 {"Play record menu(|)", '|', TRUE},
4103 {"Set options(=)", '=', TRUE},
4104 {"Interact with macros(@)", '@', TRUE},
4105 {"Interact w/ visuals(%)", '%', TRUE},
4106 {"Interact with colors(&)", '&', TRUE},
4107 {"Enter a user pref(\")", '\"', TRUE},
4108 {"Reload auto-pick pref($)", '$', TRUE},
4116 {"Save and quit(^x)", KTRL('X'), TRUE},
4117 {"Save(^s)", KTRL('S'), TRUE},
4118 {"Help(obsoleted)(?)", '?', TRUE},
4119 {"Redraw(^r)", KTRL('R'), TRUE},
4120 {"Take note(:)", ':', TRUE},
4121 {"Dump screen dump(()", ')', TRUE},
4122 {"Load screen dump())", '(', TRUE},
4123 {"Version info(V)", 'V', TRUE},
4124 {"Quit(Q)", 'Q', TRUE},
4137 } special_menu_naiyou;
4139 #define MENU_CLASS 1
4143 special_menu_naiyou special_menu_info[] =
4145 {"超能力/特殊能力", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
4146 {"ものまね/特殊能力", 0, 0, MENU_CLASS, CLASS_IMITATOR},
4147 {"歌/特殊能力", 0, 0, MENU_CLASS, CLASS_BARD},
4148 {"必殺技/特殊能力", 0, 0, MENU_CLASS, CLASS_SAMURAI},
4149 {"練気術/魔法/特殊能力", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
4150 {"技/特殊能力", 0, 0, MENU_CLASS, CLASS_BERSERKER},
4151 {"技術/特殊能力", 0, 0, MENU_CLASS, CLASS_SMITH},
4152 {"鏡魔法/特殊能力", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
4153 {"忍術/特殊能力", 0, 0, MENU_CLASS, CLASS_NINJA},
4154 {"広域マップ(<)", 2, 6, MENU_WILD, FALSE},
4155 {"通常マップ(>)", 2, 7, MENU_WILD, TRUE},
4159 special_menu_naiyou special_menu_info[] =
4161 {"MindCraft/Special", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
4162 {"Imitation/Special", 0, 0, MENU_CLASS, CLASS_IMITATOR},
4163 {"Song/Special", 0, 0, MENU_CLASS, CLASS_BARD},
4164 {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SAMURAI},
4165 {"Mind/Magic/Special", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
4166 {"BrutalPower/Special", 0, 0, MENU_CLASS, CLASS_BERSERKER},
4167 {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SMITH},
4168 {"MirrorMagic/Special", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
4169 {"Ninjutsu/Special", 0, 0, MENU_CLASS, CLASS_NINJA},
4170 {"Enter global map(<)", 2, 6, MENU_WILD, FALSE},
4171 {"Enter local map(>)", 2, 7, MENU_WILD, TRUE},
4176 static char inkey_from_menu(void)
4180 int num = 0, max_num, old_num = 0;
4184 if (p_ptr->y - panel_row_min > 10) basey = 2;
4188 /* Clear top line */
4198 if (!menu) old_num = num;
4199 put_str("+----------------------------------------------------+", basey, basex);
4200 put_str("| |", basey+1, basex);
4201 put_str("| |", basey+2, basex);
4202 put_str("| |", basey+3, basex);
4203 put_str("| |", basey+4, basex);
4204 put_str("| |", basey+5, basex);
4205 put_str("+----------------------------------------------------+", basey+6, basex);
4207 for(i = 0; i < 10; i++)
4210 if (!menu_info[menu][i].cmd) break;
4211 menu_name = menu_info[menu][i].name;
4212 for(hoge = 0; ; hoge++)
4214 if (!special_menu_info[hoge].name[0]) break;
4215 if ((menu != special_menu_info[hoge].window) || (i != special_menu_info[hoge].number)) continue;
4216 switch(special_menu_info[hoge].jouken)
4219 if (p_ptr->pclass == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
4222 if (!current_floor_ptr->dun_level && !p_ptr->inside_arena && !p_ptr->inside_quest)
4224 if ((byte)p_ptr->wild_mode == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
4231 put_str(menu_name, basey + 1 + i / 2, basex + 4 + (i % 2) * 24);
4234 kisuu = max_num % 2;
4235 put_str(_("》", "> "),basey + 1 + num / 2, basex + 2 + (num % 2) * 24);
4237 /* Place the cursor on the player */
4238 move_cursor_relative(p_ptr->y, p_ptr->x);
4241 if ((sub_cmd == ' ') || (sub_cmd == 'x') || (sub_cmd == 'X') || (sub_cmd == '\r') || (sub_cmd == '\n'))
4243 if (menu_info[menu][num].fin)
4245 cmd = menu_info[menu][num].cmd;
4251 menu = menu_info[menu][num].cmd;
4257 else if ((sub_cmd == ESCAPE) || (sub_cmd == 'z') || (sub_cmd == 'Z') || (sub_cmd == '0'))
4274 else if ((sub_cmd == '2') || (sub_cmd == 'j') || (sub_cmd == 'J'))
4279 num = (num + 2) % (max_num - 1);
4281 num = (num + 2) % (max_num + 1);
4283 else num = (num + 2) % max_num;
4285 else if ((sub_cmd == '8') || (sub_cmd == 'k') || (sub_cmd == 'K'))
4290 num = (num + max_num - 3) % (max_num - 1);
4292 num = (num + max_num - 1) % (max_num + 1);
4294 else num = (num + max_num - 2) % max_num;
4296 else if ((sub_cmd == '4') || (sub_cmd == '6') || (sub_cmd == 'h') || (sub_cmd == 'H') || (sub_cmd == 'l') || (sub_cmd == 'L'))
4298 if ((num % 2) || (num == max_num - 1))
4302 else if (num < max_num - 1)
4310 if (!inkey_next) inkey_next = "";
4316 * Request a command from the user.
4318 * Sets p_ptr->command_cmd, p_ptr->command_dir, p_ptr->command_rep,
4319 * p_ptr->command_arg. May modify p_ptr->command_new.
4321 * Note that "caret" ("^") is treated specially, and is used to
4322 * allow manual input of control characters. This can be used
4323 * on many machines to request repeated tunneling (Ctrl-H) and
4324 * on the Macintosh to request "Control-Caret".
4326 * Note that "backslash" is treated specially, and is used to bypass any
4327 * keymap entry for the following character. This is useful for macros.
4329 * Note that this command is used both in the dungeon and in
4330 * stores, and must be careful to work in both situations.
4332 * Note that "p_ptr->command_new" may not work any more.
4334 void request_command(int shopping)
4347 if (rogue_like_commands)
4349 mode = KEYMAP_MODE_ROGUE;
4355 mode = KEYMAP_MODE_ORIG;
4359 /* No command yet */
4362 /* No "argument" yet */
4365 /* No "direction" yet */
4374 /* Hack -- auto-commands */
4379 /* Use auto-command */
4386 /* Get a keypress in "command" mode */
4389 /* Hack -- no flush needed */
4393 /* Activate "command mode" */
4398 if (!shopping && command_menu && ((cmd == '\r') || (cmd == '\n') || (cmd == 'x') || (cmd == 'X'))
4399 && !keymap_act[mode][(byte)(cmd)])
4400 cmd = inkey_from_menu();
4403 /* Clear top line */
4410 COMMAND_ARG old_arg = command_arg;
4415 /* Begin the input */
4416 prt(_("回数: ", "Count: "), 0, 0);
4418 /* Get a command count */
4421 /* Get a new keypress */
4424 /* Simple editing (delete or backspace) */
4425 if ((cmd == 0x7F) || (cmd == KTRL('H')))
4427 /* Delete a digit */
4428 command_arg = command_arg / 10;
4430 /* Show current count */
4431 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
4434 /* Actual numeric data */
4435 else if (cmd >= '0' && cmd <= '9')
4437 /* Stop count at 9999 */
4438 if (command_arg >= 1000)
4447 /* Increase count */
4450 /* Incorporate that digit */
4451 command_arg = command_arg * 10 + D2I(cmd);
4454 /* Show current count */
4455 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
4458 /* Exit on "unusable" input */
4465 /* Hack -- Handle "zero" */
4466 if (command_arg == 0)
4471 /* Show current count */
4472 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
4475 /* Hack -- Handle "old_arg" */
4478 /* Restore old_arg */
4479 command_arg = old_arg;
4481 /* Show current count */
4482 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
4485 /* Hack -- white-space means "enter command now" */
4486 if ((cmd == ' ') || (cmd == '\n') || (cmd == '\r'))
4488 /* Get a real command */
4489 if (!get_com(_("コマンド: ", "Command: "), (char *)&cmd, FALSE))
4499 /* Allow "keymaps" to be bypassed */
4502 /* Get a real command */
4503 (void)get_com(_("コマンド: ", "Command: "), (char *)&cmd, FALSE);
4505 /* Hack -- bypass keymaps */
4506 if (!inkey_next) inkey_next = "";
4510 /* Allow "control chars" to be entered */
4513 /* Get a new command and controlify it */
4514 if (get_com(_("CTRL: ", "Control: "), (char *)&cmd, FALSE)) cmd = KTRL(cmd);
4518 /* Look up applicable keymap */
4519 act = keymap_act[mode][(byte)(cmd)];
4521 /* Apply keymap if not inside a keymap already */
4522 if (act && !inkey_next)
4524 /* Install the keymap (limited buffer size) */
4525 (void)strnfmt(request_command_buffer, 256, "%s", act);
4527 /* Start using the buffer */
4528 inkey_next = request_command_buffer;
4536 command_cmd = (byte)cmd;
4541 /* Hack -- Auto-repeat certain commands */
4542 if (always_repeat && (command_arg <= 0))
4544 /* Hack -- auto repeat certain commands */
4545 if (my_strchr("TBDoc+", (char)command_cmd))
4547 /* Repeat 99 times */
4556 switch (command_cmd)
4558 /* Command "p" -> "purchase" (get) */
4559 case 'p': command_cmd = 'g'; break;
4561 /* Command "m" -> "purchase" (get) */
4562 case 'm': command_cmd = 'g'; break;
4564 /* Command "s" -> "sell" (drop) */
4565 case 's': command_cmd = 'd'; break;
4570 for (i = 0; i < 256; i++)
4573 if ((s = keymap_act[mode][i]) != NULL)
4575 if (*s == command_cmd && *(s+1) == 0)
4583 caretcmd = command_cmd;
4586 /* Hack -- Scan equipment */
4587 for (i = INVEN_RARM; i < INVEN_TOTAL; i++)
4591 object_type *o_ptr = &inventory[i];
4593 /* Skip non-objects */
4594 if (!o_ptr->k_idx) continue;
4596 /* No inscription */
4597 if (!o_ptr->inscription) continue;
4599 /* Obtain the inscription */
4600 s = quark_str(o_ptr->inscription);
4603 s = my_strchr(s, '^');
4605 /* Process preventions */
4608 /* Check the "restriction" character */
4610 if ((s[1] == caretcmd) || (s[1] == '*'))
4612 if ((s[1] == command_cmd) || (s[1] == '*'))
4616 /* Hack -- Verify command */
4617 if (!get_check(_("本当ですか? ", "Are you sure? ")))
4619 /* Hack -- Use space */
4624 /* Find another '^' */
4625 s = my_strchr(s + 1, '^');
4630 /* Hack -- erase the message line. */
4637 * Check a char for "vowel-hood"
4639 bool is_a_vowel(int ch)
4664 * Replace the first instance of "target" in "buf" with "insert"
4665 * If "insert" is NULL, just remove the first instance of "target"
4666 * In either case, return TRUE if "target" is found.
4668 * XXX Could be made more efficient, especially in the
4669 * case where "insert" is smaller than "target".
4671 static bool insert_str(char *buf, concptr target, concptr insert)
4674 int b_len, t_len, i_len;
4676 /* Attempt to find the target (modify "buf") */
4677 buf = my_strstr(buf, target);
4679 /* No target found */
4680 if (!buf) return (FALSE);
4682 /* Be sure we have an insertion string */
4683 if (!insert) insert = "";
4685 /* Extract some lengths */
4686 t_len = strlen(target);
4687 i_len = strlen(insert);
4688 b_len = strlen(buf);
4690 /* How much "movement" do we need? */
4691 len = i_len - t_len;
4693 /* We need less space (for insert) */
4696 for (i = t_len; i < b_len; ++i) buf[i+len] = buf[i];
4699 /* We need more space (for insert) */
4702 for (i = b_len-1; i >= t_len; --i) buf[i+len] = buf[i];
4705 /* If movement occured, we need a new terminator */
4706 if (len) buf[b_len+len] = '\0';
4708 /* Now copy the insertion string */
4709 for (i = 0; i < i_len; ++i) buf[i] = insert[i];
4711 /* Successful operation */
4721 * Called from cmd4.c and a few other places. Just extracts
4722 * a direction from the keymap for ch (the last direction,
4723 * in fact) byte or char here? I'm thinking that keymaps should
4724 * generally only apply to single keys, which makes it no more
4725 * than 128, so a char should suffice... but keymap_act is 256...
4727 int get_keymap_dir(char ch)
4731 /* Already a direction? */
4742 if (rogue_like_commands)
4744 mode = KEYMAP_MODE_ROGUE;
4750 mode = KEYMAP_MODE_ORIG;
4753 /* Extract the action (if any) */
4754 act = keymap_act[mode][(byte)(ch)];
4759 /* Convert to a direction */
4760 for (s = act; *s; ++s)
4762 /* Use any digits in keymap */
4763 if (isdigit(*s)) d = D2I(*s);
4769 /* Return direction */
4774 #define REPEAT_MAX 20
4776 /* Number of chars saved */
4777 static int repeat__cnt = 0;
4780 static int repeat__idx = 0;
4783 static COMMAND_CODE repeat__key[REPEAT_MAX];
4786 void repeat_push(COMMAND_CODE what)
4789 if (repeat__cnt == REPEAT_MAX) return;
4791 /* Push the "stuff" */
4792 repeat__key[repeat__cnt++] = what;
4794 /* Prevents us from pulling keys */
4799 bool repeat_pull(COMMAND_CODE *what)
4801 /* All out of keys */
4802 if (repeat__idx == repeat__cnt) return (FALSE);
4804 /* Grab the next key, advance */
4805 *what = repeat__key[repeat__idx++];
4811 void repeat_check(void)
4815 /* Ignore some commands */
4816 if (command_cmd == ESCAPE) return;
4817 if (command_cmd == ' ') return;
4818 if (command_cmd == '\r') return;
4819 if (command_cmd == '\n') return;
4821 /* Repeat Last Command */
4822 if (command_cmd == 'n')
4827 /* Get the command */
4828 if (repeat_pull(&what))
4830 /* Save the command */
4835 /* Start saving new command */
4844 /* Save this command */
4853 * Array size for which InsertionSort
4854 * is used instead of QuickSort
4860 * Exchange two sort-entries
4861 * (should probably be coded inline
4862 * for speed increase)
4864 static void swap(tag_type *a, tag_type *b)
4875 * Insertion-Sort algorithm
4876 * (used by the Quicksort algorithm)
4878 static void InsertionSort(tag_type elements[], int number)
4884 for (P = 1; P < number; P++)
4887 for (j = P; (j > 0) && (elements[j - 1].tag > tmp.tag); j--)
4888 elements[j] = elements[j - 1];
4895 * Helper function for Quicksort
4897 static tag_type median3(tag_type elements[], int left, int right)
4899 int center = (left + right) / 2;
4901 if (elements[left].tag > elements[center].tag)
4902 swap(&elements[left], &elements[center]);
4903 if (elements[left].tag > elements[right].tag)
4904 swap(&elements[left], &elements[right]);
4905 if (elements[center].tag > elements[right].tag)
4906 swap(&elements[center], &elements[right]);
4908 swap(&elements[center], &elements[right - 1]);
4909 return (elements[right - 1]);
4914 * Quicksort algorithm
4916 * The "median of three" pivot selection eliminates
4917 * the bad case of already sorted input.
4919 * We use InsertionSort for smaller sub-arrays,
4920 * because it is faster in this case.
4922 * For details see: "Data Structures and Algorithm
4923 * Analysis in C" by Mark Allen Weiss.
4925 static void quicksort(tag_type elements[], int left, int right)
4930 if (left + CUTOFF <= right)
4932 pivot = median3(elements, left, right);
4934 i = left; j = right -1;
4938 while (elements[++i].tag < pivot.tag);
4939 while (elements[--j].tag > pivot.tag);
4942 swap(&elements[i], &elements[j]);
4948 swap(&elements[i], &elements[right - 1]);
4950 quicksort(elements, left, i - 1);
4951 quicksort(elements, i + 1, right);
4955 /* Use InsertionSort on small arrays */
4956 InsertionSort(elements + left, right - left + 1);
4962 * Frontend for the sorting algorithm
4964 * Sorts an array of tagged pointers
4965 * with <number> elements.
4967 void tag_sort(tag_type elements[], int number)
4969 quicksort(elements, 0, number - 1);
4972 #endif /* SORT_R_INFO */
4974 #ifdef SUPPORT_GAMMA
4976 /* Table of gamma values */
4977 byte gamma_table[256];
4979 /* Table of ln(x/256) * 256 for x going from 0 -> 255 */
4980 static s16b gamma_helper[256] =
4982 0,-1420,-1242,-1138,-1065,-1007,-961,-921,-887,-857,-830,-806,-783,-762,-744,-726,
4983 -710,-694,-679,-666,-652,-640,-628,-617,-606,-596,-586,-576,-567,-577,-549,-541,
4984 -532,-525,-517,-509,-502,-495,-488,-482,-475,-469,-463,-457,-451,-455,-439,-434,
4985 -429,-423,-418,-413,-408,-403,-398,-394,-389,-385,-380,-376,-371,-367,-363,-359,
4986 -355,-351,-347,-343,-339,-336,-332,-328,-325,-321,-318,-314,-311,-308,-304,-301,
4987 -298,-295,-291,-288,-285,-282,-279,-276,-273,-271,-268,-265,-262,-259,-257,-254,
4988 -251,-248,-246,-243,-241,-238,-236,-233,-231,-228,-226,-223,-221,-219,-216,-214,
4989 -212,-209,-207,-205,-203,-200,-198,-196,-194,-192,-190,-188,-186,-184,-182,-180,
4990 -178,-176,-174,-172,-170,-168,-166,-164,-162,-160,-158,-156,-155,-153,-151,-149,
4991 -147,-146,-144,-142,-140,-139,-137,-135,-134,-132,-130,-128,-127,-125,-124,-122,
4992 -120,-119,-117,-116,-114,-112,-111,-109,-108,-106,-105,-103,-102,-100,-99,-97,
4993 -96,-95,-93,-92,-90,-89,-87,-86,-85,-83,-82,-80,-79,-78,-76,-75,
4994 -74,-72,-71,-70,-68,-67,-66,-65,-63,-62,-61,-59,-58,-57,-56,-54,
4995 -53,-52,-51,-50,-48,-47,-46,-45,-44,-42,-41,-40,-39,-38,-37,-35,
4996 -34,-33,-32,-31,-30,-29,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,
4997 -17,-16,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1
5002 * Build the gamma table so that floating point isn't needed.
5004 * Note gamma goes from 0->256. The old value of 100 is now 128.
5006 void build_gamma_table(int gamma)
5011 * value is the current sum.
5012 * diff is the new term to add to the series.
5016 /* Hack - convergence is bad in these cases. */
5018 gamma_table[255] = 255;
5020 for (i = 1; i < 255; i++)
5023 * Initialise the Taylor series
5025 * value and diff have been scaled by 256
5030 diff = ((long)gamma_helper[i]) * (gamma - 256);
5039 * Use the following identiy to calculate the gamma table.
5040 * exp(x) = 1 + x + x^2/2 + x^3/(2*3) + x^4/(2*3*4) +...
5042 * n is the current term number.
5044 * The gamma_helper array contains a table of
5046 * This is used because a^b = exp(b*ln(a))
5052 * Note that everything is scaled by 256 for accuracy,
5053 * plus another factor of 256 for the final result to
5054 * be from 0-255. Thus gamma_helper[] * gamma must be
5055 * divided by 256*256 each itteration, to get back to
5056 * the original power series.
5058 diff = (((diff / 256) * gamma_helper[i]) * (gamma - 256)) / (256 * n);
5062 * Store the value in the table so that the
5063 * floating point pow function isn't needed .
5065 gamma_table[i] = ((long)(value / 256) * i) / 256;
5069 #endif /* SUPPORT_GAMMA */
5073 * Add a series of keypresses to the "queue".
5075 * Return any errors generated by Term_keypress() in doing so, or SUCCESS
5076 * if there are none.
5078 * Catch the "out of space" error before anything is printed.
5080 * NB: The keys added here will be interpreted by any macros or keymaps.
5082 errr type_string(concptr str, uint len)
5089 /* Paranoia - no string. */
5090 if (!str) return -1;
5092 /* Hack - calculate the string length here if none given. */
5093 if (!len) len = strlen(str);
5095 /* Activate the main window, as all pastes go there. */
5096 Term_activate(term_screen);
5098 for (s = str; s < str+len; s++)
5100 /* Catch end of string */
5101 if (*s == '\0') break;
5103 err = Term_keypress(*s);
5109 /* Activate the original window. */
5117 void roff_to_buf(concptr str, int maxlen, char *tbuf, size_t bufsize)
5126 while (str[read_pt])
5129 bool kinsoku = FALSE;
5134 /* Prepare one character */
5135 ch[0] = str[read_pt];
5138 kanji = iskanji(ch[0]);
5142 ch[1] = str[read_pt+1];
5145 if (strcmp(ch, "。") == 0 ||
5146 strcmp(ch, "、") == 0 ||
5147 strcmp(ch, "ィ") == 0 ||
5148 strcmp(ch, "ー") == 0)
5151 else if (!isprint(ch[0]))
5154 if (!isprint(ch[0]))
5158 if (line_len + ch_len > maxlen - 1 || str[read_pt] == '\n')
5162 /* return to better wrapping point. */
5163 /* Space character at the end of the line need not to be printed. */
5164 word_len = read_pt - word_punct;
5166 if (kanji && !kinsoku)
5170 if (ch[0] == ' ' || word_len >= line_len/2)
5174 read_pt = word_punct;
5175 if (str[word_punct] == ' ')
5177 write_pt -= word_len;
5180 tbuf[write_pt++] = '\0';
5182 word_punct = read_pt;
5186 word_punct = read_pt;
5188 if (!kinsoku) word_punct = read_pt;
5191 /* Not enough buffer size */
5192 if ((size_t)(write_pt + 3) >= bufsize) break;
5194 tbuf[write_pt++] = ch[0];
5200 tbuf[write_pt++] = ch[1];
5206 tbuf[write_pt] = '\0';
5207 tbuf[write_pt+1] = '\0';
5214 * The my_strcpy() function copies up to 'bufsize'-1 characters from 'src'
5215 * to 'buf' and NUL-terminates the result. The 'buf' and 'src' strings may
5218 * my_strcpy() returns strlen(src). This makes checking for truncation
5219 * easy. Example: if (my_strcpy(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
5221 * This function should be equivalent to the strlcpy() function in BSD.
5223 size_t my_strcpy(char *buf, concptr src, size_t bufsize)
5232 /* reserve for NUL termination */
5235 /* Copy as many bytes as will fit */
5236 while (*s && (len < bufsize))
5240 if (len + 1 >= bufsize || !*(s+1)) break;
5260 size_t len = strlen(src);
5262 if (bufsize == 0) return ret;
5265 if (len >= bufsize) len = bufsize - 1;
5267 /* Copy the string and terminate it */
5268 (void)memcpy(buf, src, len);
5271 /* Return strlen(src) */
5279 * The my_strcat() tries to append a string to an existing NUL-terminated string.
5280 * It never writes more characters into the buffer than indicated by 'bufsize' and
5281 * NUL-terminates the buffer. The 'buf' and 'src' strings may not overlap.
5283 * my_strcat() returns strlen(buf) + strlen(src). This makes checking for
5284 * truncation easy. Example:
5285 * if (my_strcat(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
5287 * This function should be equivalent to the strlcat() function in BSD.
5289 size_t my_strcat(char *buf, concptr src, size_t bufsize)
5291 size_t dlen = strlen(buf);
5293 /* Is there room left in the buffer? */
5294 if (dlen < bufsize - 1)
5296 /* Append as much as possible */
5297 return (dlen + my_strcpy(buf + dlen, src, bufsize - dlen));
5301 /* Return without appending */
5302 return (dlen + strlen(src));
5308 * A copy of ANSI strstr()
5310 * my_strstr() can handle Kanji strings correctly.
5312 char *my_strstr(concptr haystack, concptr needle)
5315 int l1 = strlen(haystack);
5316 int l2 = strlen(needle);
5320 for(i = 0; i <= l1 - l2; i++)
5322 if(!strncmp(haystack + i, needle, l2))
5323 return (char *)haystack + i;
5326 if (iskanji(*(haystack + i))) i++;
5336 * A copy of ANSI strchr()
5338 * my_strchr() can handle Kanji strings correctly.
5340 char *my_strchr(concptr ptr, char ch)
5342 for ( ; *ptr != '\0'; ptr++)
5344 if (*ptr == ch) return (char *)ptr;
5347 if (iskanji(*ptr)) ptr++;
5356 * Convert string to lower case
5358 void str_tolower(char *str)
5360 /* Force to be lower case string */
5370 *str = (char)tolower(*str);
5376 * Get a keypress from the user.
5377 * And interpret special keys as internal code.
5379 * This function is a Mega-Hack and depend on pref-xxx.prf's.
5380 * Currently works on Linux(UNIX), Windows, and Macintosh only.
5382 int inkey_special(bool numpad_cursor)
5384 static const struct {
5387 } modifier_key_list[] = {
5388 {"shift-", SKEY_MOD_SHIFT},
5389 {"control-", SKEY_MOD_CONTROL},
5393 static const struct {
5397 } special_key_list[] = {
5398 {FALSE, "Down]", SKEY_DOWN},
5399 {FALSE, "Left]", SKEY_LEFT},
5400 {FALSE, "Right]", SKEY_RIGHT},
5401 {FALSE, "Up]", SKEY_UP},
5402 {FALSE, "Page_Up]", SKEY_PGUP},
5403 {FALSE, "Page_Down]", SKEY_PGDOWN},
5404 {FALSE, "Home]", SKEY_TOP},
5405 {FALSE, "End]", SKEY_BOTTOM},
5406 {TRUE, "KP_Down]", SKEY_DOWN},
5407 {TRUE, "KP_Left]", SKEY_LEFT},
5408 {TRUE, "KP_Right]", SKEY_RIGHT},
5409 {TRUE, "KP_Up]", SKEY_UP},
5410 {TRUE, "KP_Page_Up]", SKEY_PGUP},
5411 {TRUE, "KP_Page_Down]", SKEY_PGDOWN},
5412 {TRUE, "KP_Home]", SKEY_TOP},
5413 {TRUE, "KP_End]", SKEY_BOTTOM},
5414 {TRUE, "KP_2]", SKEY_DOWN},
5415 {TRUE, "KP_4]", SKEY_LEFT},
5416 {TRUE, "KP_6]", SKEY_RIGHT},
5417 {TRUE, "KP_8]", SKEY_UP},
5418 {TRUE, "KP_9]", SKEY_PGUP},
5419 {TRUE, "KP_3]", SKEY_PGDOWN},
5420 {TRUE, "KP_7]", SKEY_TOP},
5421 {TRUE, "KP_1]", SKEY_BOTTOM},
5425 static const struct {
5428 } gcu_special_key_list[] = {
5434 {"4~", SKEY_BOTTOM},
5436 {"6~", SKEY_PGDOWN},
5449 * Forget macro trigger ----
5450 * It's important if we are already expanding macro action
5452 inkey_macro_trigger_string[0] = '\0';
5454 /* Get a keypress */
5457 /* Examine trigger string */
5458 trig_len = strlen(inkey_macro_trigger_string);
5460 /* Already known that no special key */
5461 if (!trig_len) return (int)((unsigned char)key);
5464 * Hack -- Ignore macro defined on ASCII characters.
5466 if (trig_len == 1 && parse_macro)
5468 char c = inkey_macro_trigger_string[0];
5470 /* Cancel macro action on the queue */
5471 forget_macro_action();
5473 /* Return the originaly pressed key */
5474 return (int)((unsigned char)c);
5477 /* Convert the trigger */
5478 ascii_to_text(buf, inkey_macro_trigger_string);
5480 /* Check the prefix "\[" */
5481 if (prefix(str, "\\["))
5486 /* Examine modifier keys */
5489 for (i = 0; modifier_key_list[i].keyname; i++)
5491 if (prefix(str, modifier_key_list[i].keyname))
5493 /* Get modifier key flag */
5494 str += strlen(modifier_key_list[i].keyname);
5495 modifier |= modifier_key_list[i].keyflag;
5499 /* No more modifier key found */
5500 if (!modifier_key_list[i].keyname) break;
5503 /* numpad_as_cursorkey option force numpad keys to input numbers */
5504 if (!numpad_as_cursorkey) numpad_cursor = FALSE;
5506 /* Get a special key code */
5507 for (i = 0; special_key_list[i].keyname; i++)
5509 if ((!special_key_list[i].numpad || numpad_cursor) &&
5510 streq(str, special_key_list[i].keyname))
5512 skey = special_key_list[i].keycode;
5517 /* A special key found */
5520 /* Cancel macro action on the queue */
5521 forget_macro_action();
5523 /* Return special key code and modifier flags */
5524 return (skey | modifier);
5528 if (prefix(str, "\\e["))
5532 for (i = 0; gcu_special_key_list[i].keyname; i++)
5534 if (streq(str, gcu_special_key_list[i].keyname))
5536 return gcu_special_key_list[i].keycode;
5541 /* No special key found? */
5543 /* Don't bother with this trigger no more */
5544 inkey_macro_trigger_string[0] = '\0';
5546 /* Return normal keycode */
5547 return (int)((unsigned char)key);