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 "main/music-definitions-table.h"
15 #include "signal-handlers.h"
20 #include "monsterrace-hook.h"
21 #include "view-mainwindow.h"
25 #include "io/write-diary.h"
26 #include "cmd/cmd-dump.h"
28 #include "player-class.h"
31 * 10進数から16進数への変換テーブル /
32 * Global array for converting numbers to uppercase hecidecimal digit
33 * This array can also be used to convert a number to an octal digit
35 const char hexsym[16] =
37 '0', '1', '2', '3', '4', '5', '6', '7',
38 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
42 * Keymaps for each "mode" associated with each keypress.
44 concptr keymap_act[KEYMAP_MODES][256];
47 * The next "free" index to use
52 * The index of the oldest message (none yet)
57 * The next "free" offset
62 * The offset to the oldest used char (none yet)
67 * The array of offsets, by index [MESSAGE_MAX]
72 * The array of chars, by offset [MESSAGE_BUF]
76 bool msg_flag; /* Used in msg_print() for "buffering" */
79 * Number of active macros.
84 * Array of macro patterns [MACRO_MAX]
89 * Array of macro actions [MACRO_MAX]
94 * Array of macro types [MACRO_MAX]
99 * Current macro action [1024]
103 bool get_com_no_macros = FALSE; /* Expand macros in "get_com" or not */
105 bool inkey_base; /* See the "inkey()" function */
106 bool inkey_xtra; /* See the "inkey()" function */
107 bool inkey_scan; /* See the "inkey()" function */
108 bool inkey_flag; /* See the "inkey()" function */
115 * The number of quarks
117 STR_OFFSET quark__num;
120 * The pointers to the quarks [QUARK_MAX]
124 static int num_more = 0;
126 /* Save macro trigger string for use in inkey_special() */
127 static char inkey_macro_trigger_string[1024];
129 int max_macrotrigger = 0; /*!< 現在登録中のマクロ(トリガー)の数 */
130 concptr macro_template = NULL; /*!< Angband設定ファイルのT: タグ情報から読み込んだ長いTコードを処理するために利用する文字列ポインタ */
131 concptr macro_modifier_chr; /*!< &x# で指定されるマクロトリガーに関する情報を記録する文字列ポインタ */
132 concptr macro_modifier_name[MAX_MACRO_MOD]; /*!< マクロ上で取り扱う特殊キーを文字列上で表現するためのフォーマットを記録した文字列ポインタ配列 */
133 concptr macro_trigger_name[MAX_MACRO_TRIG]; /*!< マクロのトリガーコード */
134 concptr macro_trigger_keycode[2][MAX_MACRO_TRIG]; /*!< マクロの内容 */
136 s16b command_cmd; /* Current "Angband Command" */
137 COMMAND_ARG command_arg; /*!< 各種コマンドの汎用的な引数として扱う / Gives argument of current command */
138 COMMAND_NUM command_rep; /*!< 各種コマンドの汎用的なリピート数として扱う / Gives repetition of current command */
139 DIRECTION command_dir; /*!< 各種コマンドの汎用的な方向値処理として扱う/ Gives direction of current command */
140 s16b command_see; /* See "object1.c" */
141 s16b command_wrk; /* See "object1.c" */
142 TERM_LEN command_gap = 999; /* See "object1.c" */
143 s16b command_new; /* Command chaining from inven/equip view */
150 * For those systems that don't have "usleep()" but need it.
152 * Fake "usleep()" function grabbed from the inl netrek server -cba
154 int usleep(huge usecs)
156 struct timeval timer;
161 fd_set *no_fds = NULL;
165 if (usecs > 4000000L) core(_("不当な usleep() 呼び出し", "Illegal usleep() call"));
167 timer.tv_sec = (usecs / 1000000L);
168 timer.tv_usec = (usecs % 1000000L);
169 if (select(nfds, no_fds, no_fds, no_fds, &timer) < 0)
171 if (errno != EINTR) return -1;
179 * Hack -- External functions
182 extern struct passwd *getpwuid(uid_t uid);
183 extern struct passwd *getpwnam(concptr name);
187 * Find a default user name from the system.
189 void user_name(char *buf, int id)
192 if ((pw = getpwuid(id)))
194 (void)strcpy(buf, pw->pw_name);
198 if (!iskanji(buf[0]))
201 buf[0] = toupper(buf[0]);
206 strcpy(buf, "PLAYER");
213 * The concept of the "file" routines below (and elsewhere) is that all
214 * file handling should be done using as few routines as possible, since
215 * every machine is slightly different, but these routines always have the
218 * In fact, perhaps we should use the "path_parse()" routine below to convert
219 * from "canonical" filenames (optional leading tilde's, internal wildcards,
220 * slash as the path seperator, etc) to "system" filenames (no special symbols,
221 * system-specific path seperator, etc). This would allow the program itself
222 * to assume that all filenames are "Unix" filenames, and explicitly "extract"
223 * such filenames if needed (by "path_parse()", or perhaps "path_canon()").
225 * Note that "path_temp" should probably return a "canonical" filename.
227 * Note that "my_fopen()" and "my_open()" and "my_make()" and "my_kill()"
228 * and "my_move()" and "my_copy()" should all take "canonical" filenames.
230 * Note that "canonical" filenames use a leading "slash" to indicate an absolute
231 * path, and a leading "tilde" to indicate a special directory, and default to a
232 * relative path, but MSDOS uses a leading "drivename plus colon" to indicate the
233 * use of a "special drive", and then the rest of the path is parsed "normally",
234 * and an embedded colon to indicate a "drive plus absolute path", and finally
235 * defaults to a file in the current working directory, which may or may not be defined.
237 * We should probably parse a leading "~~/" as referring to "ANGBAND_DIR". (?)
242 * Extract a "parsed" path from an initial filename
243 * Normally, we simply copy the filename into the buffer
244 * But leading tilde symbols must be handled in a special way
245 * Replace "~user/" by the home directory of the user named "user"
246 * Replace "~/" by the home directory of the current user
248 errr path_parse(char *buf, int max, concptr file)
251 if (!file) return -1;
255 (void)strnfmt(buf, max, "%s", file);
259 concptr u = file + 1;
260 concptr s = my_strstr(u, PATH_SEP);
262 if (s && (s >= u + sizeof(user))) return 1;
267 for (i = 0; u < s; ++i) user[i] = *u++;
272 if (u[0] == '\0') u = getlogin();
275 if (u) pw = getpwnam(u);
276 else pw = getpwuid(getuid());
280 if (s) strnfmt(buf, max, "%s%s", pw->pw_dir, s);
281 else strnfmt(buf, max, "%s", pw->pw_dir);
287 * Extract a "parsed" path from an initial filename
289 * This requires no special processing on simple machines,
290 * except for verifying the size of the filename.
292 errr path_parse(char *buf, int max, concptr file)
294 (void)strnfmt(buf, max, "%s", file);
303 * Hack -- acquire a "temporary" file name if possible
305 * This filename is always in "system-specific" form.
307 static errr path_temp(char *buf, int max)
309 concptr s = tmpnam(NULL);
312 #if !defined(WIN32) || (defined(_MSC_VER) && (_MSC_VER >= 1900))
313 (void)strnfmt(buf, max, "%s", s);
315 (void)strnfmt(buf, max, ".%s", s);
324 * @brief ファイル入出力のためのパス生成する。/ Create a new path by appending a file (or directory) to a path.
325 * @param buf ファイルのフルを返すバッファ
329 * @return エラーコード(ただし常に0を返す)
331 * This requires no special processing on simple machines, except
332 * for verifying the size of the filename, but note the ability to
333 * bypass the given "path" with certain special file-names.
335 * Note that the "file" may actually be a "sub-path", including
338 * Note that this function yields a path which must be "parsed"
339 * using the "parse" function above.
341 errr path_build(char *buf, int max, concptr path, concptr file)
345 (void)strnfmt(buf, max, "%s", file);
347 else if (prefix(file, PATH_SEP) && !streq(PATH_SEP, ""))
349 (void)strnfmt(buf, max, "%s", file);
353 (void)strnfmt(buf, max, "%s", file);
357 (void)strnfmt(buf, max, "%s%s%s", path, PATH_SEP, file);
365 * Hack -- replacement for "fopen()"
367 FILE *my_fopen(concptr file, concptr mode)
369 #if defined(MACH_O_CARBON)
373 if (path_parse(buf, 1024, file)) return (NULL);
374 #if defined(MACH_O_CARBON)
375 if (my_strchr(mode, 'w'))
377 tempfff = fopen(buf, mode);
378 fsetfileinfo(buf, _fcreator, _ftype);
383 return (fopen(buf, mode));
388 * Hack -- replacement for "fclose()"
390 errr my_fclose(FILE *fff)
393 if (fclose(fff) == EOF) return 1;
399 FILE *my_fopen_temp(char *buf, int max)
401 strncpy(buf, "/tmp/anXXXXXX", max);
402 int fd = mkstemp(buf);
403 if (fd < 0) return (NULL);
405 return (fdopen(fd, "w"));
407 #else /* HAVE_MKSTEMP */
408 FILE *my_fopen_temp(char *buf, int max)
410 if (path_temp(buf, max)) return (NULL);
411 return (my_fopen(buf, "w"));
413 #endif /* HAVE_MKSTEMP */
417 * Hack -- replacement for "fgets()"
419 * Read a string, without a newline, to a file
421 * Process tabs, strip internal non-printables
423 errr my_fgets(FILE *fff, char *buf, huge n)
429 if (fgets(tmp, 1024, fff))
432 guess_convert_to_system_encoding(tmp, sizeof(tmp));
434 for (s = tmp; *s; s++)
436 #if defined(MACH_O_CARBON)
439 * Be nice to the Macintosh, where a file can have Mac or Unix
440 * end of line, especially since the introduction of OS X.
441 * MPW tools were also very tolerant to the Unix EOL.
443 if (*s == '\r') *s = '\n';
445 #endif /* MACH_O_CARBON */
453 if (i + 8 >= n) break;
460 else if (iskanji(*s))
473 else if (isprint((unsigned char)*s))
490 * Hack -- replacement for "fputs()"
491 * Dump a string, plus a newline, to a file
492 * Process internal weirdness?
494 errr my_fputs(FILE *fff, concptr buf, huge n)
497 (void)fprintf(fff, "%s\n", buf);
503 * Several systems have no "O_BINARY" flag
507 #endif /* O_BINARY */
511 * Hack -- attempt to delete a file
513 errr fd_kill(concptr file)
516 if (path_parse(buf, 1024, file)) return -1;
524 * Hack -- attempt to move a file
526 errr fd_move(concptr file, concptr what)
530 if (path_parse(buf, 1024, file)) return -1;
531 if (path_parse(aux, 1024, what)) return -1;
533 (void)rename(buf, aux);
539 * Hack -- attempt to copy a file
541 errr fd_copy(concptr file, concptr what)
548 if (path_parse(buf, 1024, file)) return -1;
549 if (path_parse(aux, 1024, what)) return -1;
551 src_fd = fd_open(buf, O_RDONLY);
552 if (src_fd < 0) return -1;
554 dst_fd = fd_open(aux, O_WRONLY | O_TRUNC | O_CREAT);
555 if (dst_fd < 0) return -1;
557 while ((read_num = read(src_fd, buf, 1024)) > 0)
560 while (write_num < read_num)
562 int ret = write(dst_fd, buf + write_num, read_num - write_num);
582 * Hack -- attempt to open a file descriptor (create file)
583 * This function should fail if the file already exists
584 * Note that we assume that the file should be "binary"
586 int fd_make(concptr file, BIT_FLAGS mode)
589 if (path_parse(buf, 1024, file)) return -1;
591 #if defined(MACH_O_CARBON)
594 fdes = open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, mode);
595 if (fdes >= 0) fsetfileinfo(buf, _fcreator, _ftype);
600 return (open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, mode));
606 * Hack -- attempt to open a file descriptor (existing file)
608 * Note that we assume that the file should be "binary"
610 int fd_open(concptr file, int flags)
613 if (path_parse(buf, 1024, file)) return -1;
615 return (open(buf, flags | O_BINARY, 0));
620 * Hack -- attempt to lock a file descriptor
622 * Legal lock types -- F_UNLCK, F_RDLCK, F_WRLCK
624 errr fd_lock(int fd, int what)
626 what = what ? what : 0;
627 if (fd < 0) return -1;
629 #if defined(SET_UID) && defined(LOCK_UN) && defined(LOCK_EX)
632 (void)flock(fd, LOCK_UN);
636 if (flock(fd, LOCK_EX) != 0) return 1;
645 * Hack -- attempt to seek on a file descriptor
647 errr fd_seek(int fd, huge n)
649 if (fd < 0) return -1;
651 huge p = lseek(fd, n, SEEK_SET);
652 if (p != n) return 1;
659 * Hack -- attempt to truncate a file descriptor
661 errr fd_chop(int fd, huge n)
664 return fd >= 0 ? 0 : -1;
669 * Hack -- attempt to read data from a file descriptor
671 errr fd_read(int fd, char *buf, huge n)
673 if (fd < 0) return -1;
677 if (read(fd, buf, 16384) != 16384) return 1;
684 if (read(fd, buf, n) != (int)n) return 1;
691 * Hack -- Attempt to write data to a file descriptor
693 errr fd_write(int fd, concptr buf, huge n)
695 if (fd < 0) return -1;
700 if (write(fd, buf, 16384) != 16384) return 1;
707 if (write(fd, buf, n) != (int)n) return 1;
714 * Hack -- attempt to close a file descriptor
716 errr fd_close(int fd)
718 if (fd < 0) return -1;
726 * Important note about "colors"
728 * The "TERM_*" color definitions list the "composition" of each
729 * "Angband color" in terms of "quarters" of each of the three color
730 * components (Red, Green, Blue), for example, TERM_UMBER is defined
731 * as 2/4 Red, 1/4 Green, 0/4 Blue.
733 * The following info is from "Torbjorn Lindgren" (see "main-xaw.c").
735 * These values are NOT gamma-corrected. On most machines (with the
736 * Macintosh being an important exception), you must "gamma-correct"
737 * the given values, that is, "correct for the intrinsic non-linearity
738 * of the phosphor", by converting the given intensity levels based
739 * on the "gamma" of the target screen, which is usually 1.7 (or 1.5).
741 * The actual formula for conversion is unknown to me at this time,
742 * but you can use the table below for the most common gamma values.
744 * So, on most machines, simply convert the values based on the "gamma"
745 * of the target screen, which is usually in the range 1.5 to 1.7, and
746 * usually is closest to 1.7. The converted value for each of the five
747 * different "quarter" values is given below:
749 * Given Gamma 1.0 Gamma 1.5 Gamma 1.7 Hex 1.7
750 * ----- ---- ---- ---- ---
751 * 0/4 0.00 0.00 0.00 #00
752 * 1/4 0.25 0.27 0.28 #47
753 * 2/4 0.50 0.55 0.56 #8f
754 * 3/4 0.75 0.82 0.84 #d7
755 * 4/4 1.00 1.00 1.00 #ff
757 * Note that some machines (i.e. most IBM machines) are limited to a
758 * hard-coded set of colors, and so the information above is useless.
760 * Also, some machines are limited to a pre-determined set of colors,
761 * for example, the IBM can only display 16 colors, and only 14 of
762 * those colors resemble colors used by Angband, and then only when
763 * you ignore the fact that "Slate" and "cyan" are not really matches,
764 * so on the IBM, we use "orange" for both "Umber", and "Light Umber"
765 * in addition to the obvious "Orange", since by combining all of the
766 * "indeterminate" colors into a single color, the rest of the colors
767 * are left with "meaningful" values.
774 void move_cursor(int row, int col)
776 Term_gotoxy(col, row);
781 * Convert a decimal to a single digit octal number
783 static char octify(uint i)
785 return (hexsym[i % 8]);
790 * Convert a decimal to a single digit hex number
792 static char hexify(uint i)
794 return (hexsym[i % 16]);
799 * Convert a octal-digit into a decimal
801 static int deoct(char c)
803 if (isdigit(c)) return (D2I(c));
809 * Convert a hexidecimal-digit into a decimal
811 static int dehex(char c)
813 if (isdigit(c)) return (D2I(c));
814 if (islower(c)) return (A2I(c) + 10);
815 if (isupper(c)) return (A2I(tolower(c)) + 10);
820 static int my_stricmp(concptr a, concptr b)
822 for (concptr s1 = a, s2 = b; TRUE; s1++, s2++)
824 char z1 = FORCEUPPER(*s1);
825 char z2 = FORCEUPPER(*s2);
826 if (z1 < z2) return -1;
827 if (z1 > z2) return 1;
832 static int my_strnicmp(concptr a, concptr b, int n)
834 for (concptr s1 = a, s2 = b; n > 0; s1++, s2++, n--)
836 char z1 = FORCEUPPER(*s1);
837 char z2 = FORCEUPPER(*s2);
838 if (z1 < z2) return -1;
839 if (z1 > z2) return 1;
847 static void trigger_text_to_ascii(char **bufptr, concptr *strptr)
850 concptr str = *strptr;
851 bool mod_status[MAX_MACRO_MOD];
857 if (macro_template == NULL)
860 for (i = 0; macro_modifier_chr[i]; i++)
861 mod_status[i] = FALSE;
864 /* Examine modifier keys */
867 for (i = 0; macro_modifier_chr[i]; i++)
869 len = strlen(macro_modifier_name[i]);
871 if (!my_strnicmp(str, macro_modifier_name[i], len))
875 if (!macro_modifier_chr[i]) break;
877 mod_status[i] = TRUE;
878 if ('S' == macro_modifier_chr[i])
882 for (i = 0; i < max_macrotrigger; i++)
884 len = strlen(macro_trigger_name[i]);
885 if (!my_strnicmp(str, macro_trigger_name[i], len) && ']' == str[len])
891 if (i == max_macrotrigger)
893 str = my_strchr(str, ']');
899 *strptr = str; /* where **strptr == ']' */
905 key_code = macro_trigger_keycode[shiftstatus][i];
909 for (i = 0; macro_template[i]; i++)
911 char ch = macro_template[i];
915 for (int j = 0; macro_modifier_chr[j]; j++)
918 *s++ = macro_modifier_chr[j];
924 s += strlen(key_code);
935 *strptr = str; /* where **strptr == ']' */
941 * Hack -- convert a printable string into real ascii
943 * I have no clue if this function correctly handles, for example,
944 * parsing "\xFF" into a (signed) char. Whoever thought of making
945 * the "sign" of a "char" undefined is a complete moron. Oh well.
947 void text_to_ascii(char *buf, concptr str)
959 trigger_text_to_ascii(&s, &str);
965 *s = 16 * (char)dehex(*++str);
966 *s++ += (char)dehex(*++str);
968 else if (*str == '\\')
972 else if (*str == '^')
976 else if (*str == 's')
980 else if (*str == 'e')
984 else if (*str == 'b')
988 else if (*str == 'n')
992 else if (*str == 'r')
996 else if (*str == 't')
1000 else if (*str == '0')
1002 *s = 8 * (char)deoct(*++str);
1003 *s++ += (char)deoct(*++str);
1005 else if (*str == '1')
1007 *s = 64 + 8 * (char)deoct(*++str);
1008 *s++ += (char)deoct(*++str);
1010 else if (*str == '2')
1012 *s = 64 * 2 + 8 * (char)deoct(*++str);
1013 *s++ += (char)deoct(*++str);
1015 else if (*str == '3')
1017 *s = 64 * 3 + 8 * (char)deoct(*++str);
1018 *s++ += (char)deoct(*++str);
1024 else if (*str == '^')
1027 *s++ = (*str++ & 037);
1039 static bool trigger_ascii_to_text(char **bufptr, concptr *strptr)
1042 concptr str = *strptr;
1045 if (macro_template == NULL)
1052 for (i = 0; macro_template[i]; i++)
1054 char ch = macro_template[i];
1059 while ((tmp = my_strchr(macro_modifier_chr, *str)) != 0)
1061 int j = (int)(tmp - macro_modifier_chr);
1062 tmp = macro_modifier_name[j];
1063 while (*tmp) *s++ = *tmp++;
1071 for (j = 0; *str && *str != '\r'; j++)
1072 key_code[j] = *str++;
1077 if (ch != *str) return FALSE;
1082 if (*str++ != '\r') return FALSE;
1084 for (i = 0; i < max_macrotrigger; i++)
1086 if (!my_stricmp(key_code, macro_trigger_keycode[0][i])
1087 || !my_stricmp(key_code, macro_trigger_keycode[1][i]))
1091 if (i == max_macrotrigger)
1094 tmp = macro_trigger_name[i];
1095 while (*tmp) *s++ = *tmp++;
1106 * Hack -- convert a string into a printable form
1108 void ascii_to_text(char *buf, concptr str)
1113 byte i = (byte)(*str++);
1116 if (!trigger_ascii_to_text(&s, &str))
1177 *s++ = octify(i / 8);
1178 *s++ = octify(i % 8);
1184 *s++ = hexify(i / 16);
1185 *s++ = hexify(i % 16);
1195 * Determine if any macros have ever started with a given character.
1197 static bool macro__use[256];
1201 * Find the macro (if any) which exactly matches the given pattern
1203 sint macro_find_exact(concptr pat)
1205 if (!macro__use[(byte)(pat[0])])
1210 for (int i = 0; i < macro__num; ++i)
1212 if (!streq(macro__pat[i], pat)) continue;
1222 * Find the first macro (if any) which contains the given pattern
1224 static sint macro_find_check(concptr pat)
1226 if (!macro__use[(byte)(pat[0])])
1231 for (int i = 0; i < macro__num; ++i)
1233 if (!prefix(macro__pat[i], pat)) continue;
1243 * Find the first macro (if any) which contains the given pattern and more
1245 static sint macro_find_maybe(concptr pat)
1247 if (!macro__use[(byte)(pat[0])])
1252 for (int i = 0; i < macro__num; ++i)
1254 if (!prefix(macro__pat[i], pat)) continue;
1255 if (streq(macro__pat[i], pat)) continue;
1265 * Find the longest macro (if any) which starts with the given pattern
1267 static sint macro_find_ready(concptr pat)
1269 int t, n = -1, s = -1;
1271 if (!macro__use[(byte)(pat[0])])
1276 for (int i = 0; i < macro__num; ++i)
1278 if (!prefix(pat, macro__pat[i])) continue;
1280 t = strlen(macro__pat[i]);
1281 if ((n >= 0) && (s > t)) continue;
1292 * Add a macro definition (or redefinition).
1294 * We should use "act == NULL" to "remove" a macro, but this might make it
1295 * impossible to save the "removal" of a macro definition.
1297 * We should consider refusing to allow macros which contain existing macros,
1298 * or which are contained in existing macros, because this would simplify the
1299 * macro analysis code.
1301 * We should consider removing the "command macro" crap, and replacing it
1302 * with some kind of "powerful keymap" ability, but this might make it hard
1303 * to change the "roguelike" option from inside the game.
1305 errr macro_add(concptr pat, concptr act)
1307 if (!pat || !act) return -1;
1309 int n = macro_find_exact(pat);
1312 string_free(macro__act[n]);
1317 macro__pat[n] = string_make(pat);
1320 macro__act[n] = string_make(act);
1321 macro__use[(byte)(pat[0])] = TRUE;
1327 * Local variable -- we are inside a "macro action"
1329 * Do not match any macros until "ascii 30" is found.
1331 static bool parse_macro = FALSE;
1334 * Local variable -- we are inside a "macro trigger"
1336 * Strip all keypresses until a low ascii value is found.
1338 static bool parse_under = FALSE;
1341 * Flush all input chars. Actually, remember the flush,
1342 * and do a "special flush" before the next "inkey()".
1344 * This is not only more efficient, but also necessary to make sure
1345 * that various "inkey()" codes are not "lost" along the way.
1354 * Flush the screen, make a noise
1359 if (ring_bell) Term_xtra(TERM_XTRA_NOISE, 0);
1366 * Hack -- Make a (relevant?) sound
1370 if (!use_sound) return;
1372 Term_xtra(TERM_XTRA_SOUND, val);
1377 * Hack -- Play a music
1379 errr play_music(int type, int val)
1381 if (!use_music) return 1;
1383 return Term_xtra(type, val);
1388 * Hack -- Select floor music.
1390 void select_floor_music(player_type *player_ptr)
1392 if (!use_music) return;
1394 if (player_ptr->ambush_flag)
1396 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_AMBUSH)) return;
1399 if (player_ptr->wild_mode)
1401 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_WILD)) return;
1404 if (player_ptr->current_floor_ptr->inside_arena)
1406 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_ARENA)) return;
1409 if (player_ptr->phase_out)
1411 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_BATTLE)) return;
1414 if (player_ptr->current_floor_ptr->inside_quest)
1416 if (!play_music(TERM_XTRA_MUSIC_QUEST, player_ptr->current_floor_ptr->inside_quest)) return;
1417 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_QUEST)) return;
1420 if (player_ptr->dungeon_idx)
1422 if (player_ptr->feeling == 2)
1424 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_FEEL2)) return;
1426 else if (player_ptr->feeling >= 3 && player_ptr->feeling <= 5)
1428 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_FEEL1)) return;
1432 if (!play_music(TERM_XTRA_MUSIC_DUNGEON, player_ptr->dungeon_idx)) return;
1434 if (player_ptr->current_floor_ptr->dun_level < 40)
1436 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_LOW)) return;
1438 else if (player_ptr->current_floor_ptr->dun_level < 80)
1440 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_MED)) return;
1444 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_HIGH)) return;
1449 if (player_ptr->town_num)
1451 if (!play_music(TERM_XTRA_MUSIC_TOWN, player_ptr->town_num)) return;
1452 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_TOWN)) return;
1456 if (!player_ptr->current_floor_ptr->dun_level)
1458 if (player_ptr->lev >= 45)
1460 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD3)) return;
1462 else if (player_ptr->lev >= 25)
1464 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD2)) return;
1468 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD1)) return;
1472 play_music(TERM_XTRA_MUSIC_MUTE, 0);
1478 * Helper function called only from "inkey()"
1480 * This function does almost all of the "macro" processing.
1482 * We use the "Term_key_push()" function to handle "failed" macros, as well
1483 * as "extra" keys read in while choosing the proper macro, and also to hold
1484 * the action for the macro, plus a special "ascii 30" character indicating
1485 * that any macro action in progress is complete. Embedded macros are thus
1486 * illegal, unless a macro action includes an explicit "ascii 30" character,
1487 * which would probably be a massive hack, and might break things.
1489 * Only 500 (0+1+2+...+29+30) milliseconds may elapse between each key in
1490 * the macro trigger sequence. If a key sequence forms the "prefix" of a
1491 * macro trigger, 500 milliseconds must pass before the key sequence is
1492 * known not to be that macro trigger.
1494 static char inkey_aux(void)
1496 int k = 0, n, p = 0, w = 0;
1498 char *buf = inkey_macro_trigger_string;
1504 if (Term_inkey(&ch, FALSE, TRUE))
1506 parse_macro = FALSE;
1511 (void)(Term_inkey(&ch, TRUE, TRUE));
1514 if (ch == 30) parse_macro = FALSE;
1516 if (ch == 30) return (ch);
1517 if (parse_macro) return (ch);
1518 if (parse_under) return (ch);
1522 k = macro_find_check(buf);
1523 if (k < 0) return (ch);
1527 k = macro_find_maybe(buf);
1531 if (0 == Term_inkey(&ch, FALSE, TRUE))
1542 Term_xtra(TERM_XTRA_DELAY, w);
1546 k = macro_find_ready(buf);
1551 if (Term_key_push(buf[--p])) return 0;
1554 (void)Term_inkey(&ch, TRUE, TRUE);
1558 concptr pat = macro__pat[k];
1562 if (Term_key_push(buf[--p])) return 0;
1566 if (Term_key_push(30)) return 0;
1568 concptr act = macro__act[k];
1573 if (Term_key_push(act[--n])) return 0;
1581 * Cancel macro action on the queue
1583 static void forget_macro_action(void)
1585 if (!parse_macro) return;
1590 if (Term_inkey(&ch, FALSE, TRUE)) break;
1592 if (ch == 30) break;
1595 parse_macro = FALSE;
1599 * Mega-Hack -- special "inkey_next" pointer.
1601 * This special pointer allows a sequence of keys to be "inserted" into
1602 * the stream of keys returned by "inkey()". This key sequence will not
1603 * trigger any macros, and cannot be bypassed by the Borg. It is used
1604 * in Angband to handle "keymaps".
1606 static concptr inkey_next = NULL;
1609 * Get a keypress from the user.
1611 * This function recognizes a few "global parameters". These are variables
1612 * which, if set to TRUE before calling this function, will have an effect
1613 * on this function, and which are always reset to FALSE by this function
1614 * before this function returns. Thus they function just like normal
1615 * parameters, except that most calls to this function can ignore them.
1617 * If "inkey_xtra" is TRUE, then all pending keypresses will be flushed,
1618 * and any macro processing in progress will be aborted. This flag is
1619 * set by the "flush()" function, which does not actually flush anything
1620 * itself, but rather, triggers delayed input flushing via "inkey_xtra".
1622 * If "inkey_scan" is TRUE, then we will immediately return "zero" if no
1623 * keypress is available, instead of waiting for a keypress.
1625 * If "inkey_base" is TRUE, then all macro processing will be bypassed.
1626 * If "inkey_base" and "inkey_scan" are both TRUE, then this function will
1627 * not return immediately, but will wait for a keypress for as long as the
1628 * normal macro matching code would, allowing the direct entry of macro
1629 * triggers. The "inkey_base" flag is extremely dangerous!
1631 * If "inkey_flag" is TRUE, then we will assume that we are waiting for a
1632 * normal command, and we will only show the cursor if "hilite_player" is
1633 * TRUE (or if the player is in a store), instead of always showing the
1634 * cursor. The various "main-xxx.c" files should avoid saving the game
1635 * in response to a "menu item" request unless "inkey_flag" is TRUE, to
1636 * prevent savefile corruption.
1638 * If we are waiting for a keypress, and no keypress is ready, then we will
1639 * refresh (once) the window which was active when this function was called.
1641 * Note that "back-quote" is automatically converted into "escape" for
1642 * convenience on machines with no "escape" key. This is done after the
1643 * macro matching, so the user can still make a macro for "backquote".
1645 * Note the special handling of "ascii 30" (ctrl-caret, aka ctrl-shift-six)
1646 * and "ascii 31" (ctrl-underscore, aka ctrl-shift-minus), which are used to
1647 * provide support for simple keyboard "macros". These keys are so strange
1648 * that their loss as normal keys will probably be noticed by nobody. The
1649 * "ascii 30" key is used to indicate the "end" of a macro action, which
1650 * allows recursive macros to be avoided. The "ascii 31" key is used by
1651 * some of the "main-xxx.c" files to introduce macro trigger sequences.
1653 * Hack -- we use "ascii 29" (ctrl-right-bracket) as a special "magic" key,
1654 * which can be used to give a variety of "sub-commands" which can be used
1655 * any time. These sub-commands could include commands to take a picture of
1656 * the current screen, to start/stop recording a macro action, etc.
1658 * If "angband_term[0]" is not active, we will make it active during this
1659 * function, so that the various "main-xxx.c" files can assume that input
1660 * is only requested (via "Term_inkey()") when "angband_term[0]" is active.
1662 * Mega-Hack -- This function is used as the entry point for clearing the
1663 * "signal_count" variable, and of the "current_world_ptr->character_saved" variable.
1665 * Hack -- Note the use of "inkey_next" to allow "keymaps" to be processed.
1667 * Mega-Hack -- Note the use of "inkey_hack" to allow the "Borg" to steal
1668 * control of the keyboard from the user.
1676 if (inkey_next && *inkey_next && !inkey_xtra)
1679 inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
1686 parse_macro = FALSE;
1687 parse_under = FALSE;
1692 (void)Term_get_cursor(&v);
1694 /* Show the cursor if waiting, except sometimes in "command" mode */
1695 if (!inkey_scan && (!inkey_flag || hilite_player || current_world_ptr->character_icky))
1697 (void)Term_set_cursor(1);
1700 Term_activate(angband_term[0]);
1704 if (!inkey_base && inkey_scan &&
1705 (0 != Term_inkey(&kk, FALSE, FALSE)))
1710 if (!done && (0 != Term_inkey(&kk, FALSE, FALSE)))
1714 Term_activate(angband_term[0]);
1715 current_world_ptr->character_saved = FALSE;
1726 if (0 == Term_inkey(&ch, TRUE, TRUE))
1736 if (0 == Term_inkey(&ch, FALSE, TRUE))
1743 if (w >= 100) break;
1745 Term_xtra(TERM_XTRA_DELAY, w);
1759 if (parse_under && (ch <= 32))
1762 parse_under = FALSE;
1774 else if (parse_under)
1782 inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
1788 * Initialize the quark array
1790 void quark_init(void)
1792 C_MAKE(quark__str, QUARK_MAX, concptr);
1793 quark__str[1] = string_make("");
1799 * Add a new "quark" to the set of quarks.
1801 u16b quark_add(concptr str)
1804 for (i = 1; i < quark__num; i++)
1806 if (streq(quark__str[i], str)) return (i);
1809 if (quark__num == QUARK_MAX) return 1;
1812 quark__str[i] = string_make(str);
1818 * This function looks up a quark
1820 concptr quark_str(STR_OFFSET i)
1824 /* Return NULL for an invalid index */
1825 if ((i < 1) || (i >= quark__num)) return NULL;
1827 /* Access the quark */
1830 /* Return the quark */
1836 * @brief 保存中の過去ゲームメッセージの数を返す。 / How many messages are "available"?
1837 * @return 残っているメッセージの数
1839 s32b message_num(void)
1842 int last = message__last;
1843 int next = message__next;
1845 if (next < last) next += MESSAGE_MAX;
1853 * @brief 過去のゲームメッセージを返す。 / Recall the "text" of a saved message
1854 * @params age メッセージの世代
1855 * @return メッセージの文字列ポインタ
1857 concptr message_str(int age)
1859 if ((age < 0) || (age >= message_num())) return ("");
1861 s32b x = (message__next + MESSAGE_MAX - (age + 1)) % MESSAGE_MAX;
1862 s32b o = message__ptr[x];
1863 concptr s = &message__buf[o];
1869 * @brief ゲームメッセージをログに追加する。 / Add a new message, with great efficiency
1870 * @params str 保存したいメッセージ
1873 void message_add(concptr str)
1883 u32b n = strlen(str);
1884 if (n >= MESSAGE_BUF / 4) return;
1890 for (n = 0; n < 80; n++, t++)
1899 if (n == 81) n = 79;
1901 for (n = 80; n > 60; n--)
1902 if (str[n] == ' ') break;
1903 if (n == 60) n = 80;
1905 splitted2 = str + n;
1906 strncpy(splitted1, str, n);
1907 splitted1[n] = '\0';
1917 if (k > MESSAGE_MAX / 32) k = MESSAGE_MAX / 32;
1918 for (i = message__next; m; m--)
1924 if (i-- == 0) i = MESSAGE_MAX - 1;
1926 old = &message__buf[message__ptr[i]];
1931 for (t = buf; *t && (*t != '<' || (*(t + 1) != 'x')); t++)
1932 if (iskanji(*t))t++;
1934 for (t = buf; *t && (*t != '<'); t++);
1938 if (strlen(buf) < A_MAX) break;
1944 if (streq(buf, str) && (j < 1000))
1949 sprintf(u, "%s <x%d>", buf, j);
1951 if (!now_message) now_message++;
1963 for (i = message__next; k; k--)
1968 if (i-- == 0) i = MESSAGE_MAX - 1;
1970 if (i == message__last) break;
1972 q = (message__head + MESSAGE_BUF - message__ptr[i]) % MESSAGE_BUF;
1974 if (q > MESSAGE_BUF / 2) continue;
1976 old = &message__buf[message__ptr[i]];
1977 if (!streq(old, str)) continue;
1979 x = message__next++;
1980 if (message__next == MESSAGE_MAX) message__next = 0;
1981 if (message__next == message__last) message__last++;
1982 if (message__last == MESSAGE_MAX) message__last = 0;
1984 message__ptr[x] = message__ptr[i];
1985 if (splitted2 != NULL)
1987 message_add(splitted2);
1993 if (message__head + n + 1 >= MESSAGE_BUF)
1995 for (i = message__last; TRUE; i++)
1997 if (i == MESSAGE_MAX) i = 0;
1998 if (i == message__next) break;
1999 if (message__ptr[i] >= message__head)
2001 message__last = i + 1;
2005 if (message__tail >= message__head) message__tail = 0;
2010 if (message__head + n + 1 > message__tail)
2012 message__tail = message__head + n + 1;
2013 while (message__buf[message__tail - 1]) message__tail++;
2015 for (i = message__last; TRUE; i++)
2017 if (i == MESSAGE_MAX) i = 0;
2018 if (i == message__next) break;
2019 if ((message__ptr[i] >= message__head) &&
2020 (message__ptr[i] < message__tail))
2022 message__last = i + 1;
2028 x = message__next++;
2029 if (message__next == MESSAGE_MAX) message__next = 0;
2030 if (message__next == message__last) message__last++;
2031 if (message__last == MESSAGE_MAX) message__last = 0;
2033 message__ptr[x] = message__head;
2034 for (i = 0; i < n; i++)
2036 message__buf[message__head + i] = str[i];
2039 message__buf[message__head + i] = '\0';
2040 message__head += n + 1;
2042 if (splitted2 != NULL)
2044 message_add(splitted2);
2052 static void msg_flush(player_type *player_ptr, int x)
2054 byte a = TERM_L_BLUE;
2055 bool nagasu = FALSE;
2056 if ((auto_more && !player_ptr->now_damaged) || num_more < 0) {
2058 for (i = 0; i < 8; i++)
2060 if (angband_term[i] && (window_flag[i] & PW_MESSAGE)) break;
2064 if (num_more < angband_term[i]->hgt) nagasu = TRUE;
2072 player_ptr->now_damaged = FALSE;
2073 if (!player_ptr->playing || !nagasu)
2075 Term_putstr(x, 0, -1, a, _("-続く-", "-more-"));
2081 /* auto_moreのとき、全て流す */
2085 else if (cmd == ' ')
2091 else if ((cmd == '\n') || (cmd == '\r'))
2098 if (quick_messages) break;
2103 Term_erase(0, 0, 255);
2107 void msg_erase(void)
2114 * todo ここのp_ptrを削除するのは破滅的に作業が増えるので保留
2115 * Output a message to the top line of the screen.
2117 * Break long messages into multiple pieces (40-72 chars).
2119 * Allow multiple short messages to "share" the top line.
2121 * Prompt the user to make sure he has a chance to read them.
2123 * These messages are memorized for later reference (see above).
2125 * We could do "Term_fresh()" to provide "flicker" if needed.
2127 * The global "msg_flag" variable can be cleared to tell us to
2128 * "erase" any "pending" messages still on the screen.
2130 * Note that we must be very careful about using the
2131 * "msg_print()" functions without explicitly calling the special
2132 * "msg_print(NULL)" function, since this may result in the loss
2133 * of information if the screen is cleared, or if anything is
2134 * displayed on the top line.
2136 * Note that "msg_print(NULL)" will clear the top line
2137 * even if no messages are pending. This is probably a hack.
2139 void msg_print(concptr msg)
2145 if (current_world_ptr->timewalk_m_idx) return;
2149 Term_erase(0, 0, 255);
2153 int n = (msg ? strlen(msg) : 0);
2154 if (p && (!msg || ((p + n) > 72)))
2156 msg_flush(p_ptr, p);
2162 if (n > 1000) return;
2170 sprintf(buf, ("T:%d - %s"), (int)current_world_ptr->game_turn, msg);
2174 if (current_world_ptr->character_generated) message_add(buf);
2179 int check, split = 72;
2181 bool k_flag = FALSE;
2183 for (check = 0; check < 72; check++)
2191 if (iskanji(t[check]))
2196 else if (t[check] == ' ')
2210 for (check = 40; check < 72; check++)
2212 if (t[check] == ' ') split = check;
2216 char oops = t[split];
2218 Term_putstr(0, 0, split, TERM_WHITE, t);
2219 msg_flush(p_ptr, split + 1);
2222 t += split; n -= split;
2225 Term_putstr(p, 0, n, TERM_WHITE, t);
2226 p_ptr->window |= (PW_MESSAGE);
2227 update_output(p_ptr);
2236 if (fresh_message) Term_fresh();
2240 void msg_print_wizard(int cheat_type, concptr msg)
2242 if (!cheat_room && cheat_type == CHEAT_DUNGEON) return;
2243 if (!cheat_peek && cheat_type == CHEAT_OBJECT) return;
2244 if (!cheat_hear && cheat_type == CHEAT_MONSTER) return;
2245 if (!cheat_xtra && cheat_type == CHEAT_MISC) return;
2247 concptr cheat_mes[] = { "ITEM", "MONS", "DUNG", "MISC" };
2249 sprintf(buf, "WIZ-%s:%s", cheat_mes[cheat_type], msg);
2252 if (cheat_diary_output)
2254 exe_write_diary(p_ptr, DIARY_WIZARD_LOG, 0, buf);
2261 * Hack -- prevent "accidents" in "screen_save()" or "screen_load()"
2263 static int screen_depth = 0;
2267 * Save the screen, and increase the "icky" depth.
2269 * This function must match exactly one call to "screen_load()".
2274 if (screen_depth++ == 0) Term_save();
2276 current_world_ptr->character_icky++;
2281 * Load the screen, and decrease the "icky" depth.
2283 * This function must match exactly one call to "screen_save()".
2288 if (--screen_depth == 0) Term_load();
2290 current_world_ptr->character_icky--;
2295 * Display a formatted message, using "vstrnfmt()" and "msg_print()".
2297 void msg_format(concptr fmt, ...)
2302 (void)vstrnfmt(buf, 1024, fmt, vp);
2309 * Display a formatted message, using "vstrnfmt()" and "msg_print()".
2311 void msg_format_wizard(int cheat_type, concptr fmt, ...)
2313 if (!cheat_room && cheat_type == CHEAT_DUNGEON) return;
2314 if (!cheat_peek && cheat_type == CHEAT_OBJECT) return;
2315 if (!cheat_hear && cheat_type == CHEAT_MONSTER) return;
2316 if (!cheat_xtra && cheat_type == CHEAT_MISC) return;
2321 (void)vstrnfmt(buf, 1024, fmt, vp);
2323 msg_print_wizard(cheat_type, buf);
2328 * Display a string on the screen using an attribute.
2330 * At the given location, using the given attribute, if allowed,
2331 * add the given string. Do not clear the line.
2333 void c_put_str(TERM_COLOR attr, concptr str, TERM_LEN row, TERM_LEN col)
2335 Term_putstr(col, row, -1, attr, str);
2340 * As above, but in "white"
2342 void put_str(concptr str, TERM_LEN row, TERM_LEN col)
2344 Term_putstr(col, row, -1, TERM_WHITE, str);
2349 * Display a string on the screen using an attribute, and clear
2350 * to the end of the line.
2352 void c_prt(TERM_COLOR attr, concptr str, TERM_LEN row, TERM_LEN col)
2354 Term_erase(col, row, 255);
2355 Term_addstr(-1, attr, str);
2360 * As above, but in "white"
2362 void prt(concptr str, TERM_LEN row, TERM_LEN col)
2365 c_prt(TERM_WHITE, str, row, col);
2370 * Print some (colored) text to the screen at the current cursor position,
2371 * automatically "wrapping" existing text (at spaces) when necessary to
2372 * avoid placing any text into the last column, and clearing every line
2373 * before placing any text in that line. Also, allow "newline" to force
2374 * a "wrap" to the next line. Advance the cursor as needed so sequential
2375 * calls to this function will work correctly.
2377 * Once this function has been called, the cursor should not be moved
2378 * until all the related "c_roff()" calls to the window are complete.
2380 * This function will correctly handle any width up to the maximum legal
2381 * value of 256, though it works best for a standard 80 character width.
2383 void c_roff(TERM_COLOR a, concptr str)
2386 (void)Term_get_size(&w, &h);
2389 (void)Term_locate(&x, &y);
2391 if (y == h - 1 && x > w - 3) return;
2393 for (concptr s = str; *s; s++)
2397 int k_flag = iskanji(*s);
2405 Term_erase(x, y, 255);
2410 ch = ((k_flag || isprint(*s)) ? *s : ' ');
2412 ch = (isprint(*s) ? *s : ' ');
2416 if ((x >= ((k_flag) ? w - 2 : w - 1)) && (ch != ' '))
2418 if ((x >= w - 1) && (ch != ' '))
2432 for (i = w - 2; i >= 0; i--)
2434 Term_what(i, y, &av[i], &cv[i]);
2435 if (cv[i] == ' ') break;
2439 if (cv[i] == '(') break;
2447 /* 文頭が「。」「、」等になるときは、その1つ前の語で改行 */
2448 if (strncmp(s, "。", 2) == 0 || strncmp(s, "、", 2) == 0)
2450 Term_what(x, y, &av[x], &cv[x]);
2451 Term_what(x - 1, y, &av[x - 1], &cv[x - 1]);
2452 Term_what(x - 2, y, &av[x - 2], &cv[x - 2]);
2461 Term_erase(n, y, 255);
2466 Term_erase(x, y, 255);
2467 for (i = n; i < w - 1; i++)
2470 if (cv[i] == '\0') break;
2472 Term_addch(av[i], cv[i]);
2478 Term_addch((byte)(a | 0x10), ch);
2489 Term_addch((byte)(a | 0x20), ch);
2499 * As above, but in "white"
2501 void roff(concptr str)
2504 c_roff(TERM_WHITE, str);
2509 * Clear part of the screen
2511 void clear_from(int row)
2513 for (int y = row; y < Term->hgt; y++)
2515 Term_erase(0, y, 255);
2521 * Get some string input at the cursor location.
2522 * Assume the buffer is initialized to a default string.
2524 * The default buffer is in Overwrite mode and displayed in yellow at
2525 * first. Normal chars clear the yellow text and append the char in
2528 * LEFT (^B) and RIGHT (^F) movement keys move the cursor position.
2529 * If the text is still displayed in yellow (Overwite mode), it will
2530 * turns into white (Insert mode) when cursor moves.
2532 * DELETE (^D) deletes a char at the cursor position.
2533 * BACKSPACE (^H) deletes a char at the left of cursor position.
2534 * ESCAPE clears the buffer and the window and returns FALSE.
2535 * RETURN accepts the current buffer contents and returns TRUE.
2537 bool askfor_aux(char *buf, int len, bool numpad_cursor)
2541 * TERM_YELLOW : Overwrite mode
2542 * TERM_WHITE : Insert mode
2544 byte color = TERM_YELLOW;
2547 Term_locate(&x, &y);
2548 if (len < 1) len = 1;
2549 if ((x < 0) || (x >= 80)) x = 0;
2550 if (x + len > 80) len = 80 - x;
2557 Term_erase(x, y, len);
2558 Term_putstr(x, y, -1, color, buf);
2560 Term_gotoxy(x + pos, y);
2561 int skey = inkey_special(numpad_cursor);
2571 if (0 == pos) break;
2574 int next_pos = i + 1;
2576 if (iskanji(buf[i])) next_pos++;
2578 if (next_pos >= pos) break;
2590 if ('\0' == buf[pos]) break;
2593 if (iskanji(buf[pos])) pos += 2;
2612 if (0 == pos) break;
2615 int next_pos = i + 1;
2617 if (iskanji(buf[i])) next_pos++;
2619 if (next_pos >= pos) break;
2632 if ('\0' == buf[pos]) break;
2635 if (iskanji(buf[pos])) src++;
2639 while ('\0' != (buf[dst++] = buf[src++]));
2646 if (skey & SKEY_MASK) break;
2647 char c = (char)skey;
2649 if (color == TERM_YELLOW)
2655 strcpy(tmp, buf + pos);
2660 char next = inkey();
2675 if (pos < len && (isprint(c) || iskana(c)))
2677 if (pos < len && isprint(c))
2689 my_strcat(buf, tmp, len + 1);
2700 * Get some string input at the cursor location.
2702 * Allow to use numpad keys as cursor keys.
2704 bool askfor(char *buf, int len)
2706 return askfor_aux(buf, len, TRUE);
2711 * Get a string from the user
2713 * The "prompt" should take the form "Prompt: "
2715 * Note that the initial contents of the string is used as
2716 * the default response, so be sure to "clear" it if needed.
2718 * We clear the input, and return FALSE, on "ESCAPE".
2720 bool get_string(concptr prompt, char *buf, int len)
2725 res = askfor(buf, len);
2732 * Verify something with the user
2734 * The "prompt" should take the form "Query? "
2736 * Note that "[y/n]" is appended to the prompt.
2738 bool get_check(concptr prompt)
2740 return get_check_strict(prompt, 0);
2745 * Verify something with the user strictly
2747 * mode & CHECK_OKAY_CANCEL : force user to answer 'O'kay or 'C'ancel
2748 * mode & CHECK_NO_ESCAPE : don't allow ESCAPE key
2749 * mode & CHECK_NO_HISTORY : no message_add
2750 * mode & CHECK_DEFAULT_Y : accept any key as y, except n and Esc.
2752 bool get_check_strict(concptr prompt, BIT_FLAGS mode)
2757 p_ptr->window |= PW_MESSAGE;
2758 handle_stuff(p_ptr);
2763 if (!rogue_like_commands)
2764 mode &= ~CHECK_OKAY_CANCEL;
2766 if (mode & CHECK_OKAY_CANCEL)
2768 my_strcpy(buf, prompt, sizeof(buf) - 15);
2769 strcat(buf, "[(O)k/(C)ancel]");
2771 else if (mode & CHECK_DEFAULT_Y)
2773 my_strcpy(buf, prompt, sizeof(buf) - 5);
2774 strcat(buf, "[Y/n]");
2778 my_strcpy(buf, prompt, sizeof(buf) - 5);
2779 strcat(buf, "[y/n]");
2783 if (!(mode & CHECK_NO_HISTORY) && p_ptr->playing)
2786 p_ptr->window |= (PW_MESSAGE);
2787 handle_stuff(p_ptr);
2795 if (!(mode & CHECK_NO_ESCAPE))
2804 if (mode & CHECK_OKAY_CANCEL)
2806 if (i == 'o' || i == 'O')
2811 else if (i == 'c' || i == 'C')
2819 if (i == 'y' || i == 'Y')
2824 else if (i == 'n' || i == 'N')
2831 if (mode & CHECK_DEFAULT_Y)
2846 * Prompts for a keypress
2848 * The "prompt" should take the form "Command: "
2850 * Returns TRUE unless the character is "Escape"
2852 bool get_com(concptr prompt, char *command, bool z_escape)
2856 if (get_com_no_macros)
2857 *command = (char)inkey_special(FALSE);
2862 if (*command == ESCAPE) return FALSE;
2863 if (z_escape && ((*command == 'z') || (*command == 'Z'))) return FALSE;
2870 * Request a "quantity" from the user
2872 * Hack -- allow "command_arg" to specify a quantity
2874 QUANTITY get_quantity(concptr prompt, QUANTITY max)
2885 if (amt > max) amt = max;
2891 bool result = repeat_pull(&code);
2892 amt = (QUANTITY)code;
2893 if ((max != 1) && result)
2895 if (amt > max) amt = max;
2896 if (amt < 0) amt = 0;
2903 sprintf(tmp, _("いくつですか (1-%d): ", "Quantity (1-%d): "), max);
2910 sprintf(buf, "%d", amt);
2913 * Ask for a quantity
2914 * Don't allow to use numpad as cursor key.
2916 res = askfor_aux(buf, 6, FALSE);
2921 amt = (COMMAND_CODE)atoi(buf);
2922 if (isalpha(buf[0])) amt = max;
2923 if (amt > max) amt = max;
2924 if (amt < 0) amt = 0;
2925 if (amt) repeat_push((COMMAND_CODE)amt);
2932 * Pause for user response
2934 void pause_line(int row)
2937 put_str(_("[ 何かキーを押して下さい ]", "[Press any key to continue]"), row, _(26, 23));
2944 * Hack -- special buffer to hold the action of the current keymap
2946 static char request_command_buffer[256];
2956 menu_naiyou menu_info[10][10] =
2959 {"魔法/特殊能力", 1, FALSE},
2961 {"道具(使用)", 3, FALSE},
2962 {"道具(その他)", 4, FALSE},
2972 {"使う(m)", 'm', TRUE},
2973 {"調べる(b/P)", 'b', TRUE},
2974 {"覚える(G)", 'G', TRUE},
2975 {"特殊能力を使う(U/O)", 'U', TRUE},
2985 {"休息する(R)", 'R', TRUE},
2986 {"トラップ解除(D)", 'D', TRUE},
2987 {"探す(s)", 's', TRUE},
2988 {"周りを調べる(l/x)", 'l', TRUE},
2989 {"ターゲット指定(*)", '*', TRUE},
2990 {"穴を掘る(T/^t)", 'T', TRUE},
2991 {"階段を上る(<)", '<', TRUE},
2992 {"階段を下りる(>)", '>', TRUE},
2993 {"ペットに命令する(p)", 'p', TRUE},
2994 {"探索モードのON/OFF(S/#)", 'S', TRUE}
2998 {"読む(r)", 'r', TRUE},
2999 {"飲む(q)", 'q', TRUE},
3000 {"杖を使う(u/Z)", 'u', TRUE},
3001 {"魔法棒で狙う(a/z)", 'a', TRUE},
3002 {"ロッドを振る(z/a)", 'z', TRUE},
3003 {"始動する(A)", 'A', TRUE},
3004 {"食べる(E)", 'E', TRUE},
3005 {"飛び道具で撃つ(f/t)", 'f', TRUE},
3006 {"投げる(v)", 'v', TRUE},
3011 {"拾う(g)", 'g', TRUE},
3012 {"落とす(d)", 'd', TRUE},
3013 {"壊す(k/^d)", 'k', TRUE},
3014 {"銘を刻む({)", '{', TRUE},
3015 {"銘を消す(})", '}', TRUE},
3016 {"調査(I)", 'I', TRUE},
3017 {"アイテム一覧(i)", 'i', TRUE},
3024 {"装備する(w)", 'w', TRUE},
3025 {"装備を外す(t/T)", 't', TRUE},
3026 {"燃料を補給(F)", 'F', TRUE},
3027 {"装備一覧(e)", 'e', TRUE},
3037 {"開ける(o)", 'o', TRUE},
3038 {"閉じる(c)", 'c', TRUE},
3039 {"体当たりする(B/f)", 'B', TRUE},
3040 {"くさびを打つ(j/S)", 'j', TRUE},
3050 {"ダンジョンの全体図(M)", 'M', TRUE},
3051 {"位置を確認(L/W)", 'L', TRUE},
3052 {"階の雰囲気(^f)", KTRL('F'), TRUE},
3053 {"ステータス(C)", 'C', TRUE},
3054 {"文字の説明(/)", '/', TRUE},
3055 {"メッセージ履歴(^p)", KTRL('P'), TRUE},
3056 {"現在の時刻(^t/')", KTRL('T'), TRUE},
3057 {"現在の知識(~)", '~', TRUE},
3058 {"プレイ記録(|)", '|', TRUE},
3063 {"オプション(=)", '=', TRUE},
3064 {"マクロ(@)", '@', TRUE},
3065 {"画面表示(%)", '%', TRUE},
3066 {"カラー(&)", '&', TRUE},
3067 {"設定変更コマンド(\")", '\"', TRUE},
3068 {"自動拾いをロード($)", '$', TRUE},
3069 {"システム(!)", '!', TRUE},
3076 {"セーブ&中断(^x)", KTRL('X'), TRUE},
3077 {"セーブ(^s)", KTRL('S'), TRUE},
3078 {"ヘルプ(?)", '?', TRUE},
3079 {"再描画(^r)", KTRL('R'), TRUE},
3080 {"メモ(:)", ':', TRUE},
3081 {"記念撮影())", ')', TRUE},
3082 {"記念撮影の表示(()", '(', TRUE},
3083 {"バージョン情報(V)", 'V', TRUE},
3084 {"引退する(Q)", 'Q', TRUE},
3089 menu_naiyou menu_info[10][10] =
3092 {"Magic/Special", 1, FALSE},
3093 {"Action", 2, FALSE},
3094 {"Items(use)", 3, FALSE},
3095 {"Items(other)", 4, FALSE},
3096 {"Equip", 5, FALSE},
3097 {"Door/Box", 6, FALSE},
3098 {"Information", 7, FALSE},
3099 {"Options", 8, FALSE},
3100 {"Other commands", 9, FALSE},
3105 {"Use(m)", 'm', TRUE},
3106 {"See tips(b/P)", 'b', TRUE},
3107 {"Study(G)", 'G', TRUE},
3108 {"Special abilities(U/O)", 'U', TRUE},
3118 {"Rest(R)", 'R', TRUE},
3119 {"Disarm a trap(D)", 'D', TRUE},
3120 {"Search(s)", 's', TRUE},
3121 {"Look(l/x)", 'l', TRUE},
3122 {"Target(*)", '*', TRUE},
3123 {"Dig(T/^t)", 'T', TRUE},
3124 {"Go up stairs(<)", '<', TRUE},
3125 {"Go down stairs(>)", '>', TRUE},
3126 {"Command pets(p)", 'p', TRUE},
3127 {"Search mode ON/OFF(S/#)", 'S', TRUE}
3131 {"Read a scroll(r)", 'r', TRUE},
3132 {"Drink a potion(q)", 'q', TRUE},
3133 {"Use a staff(u/Z)", 'u', TRUE},
3134 {"Aim a wand(a/z)", 'a', TRUE},
3135 {"Zap a rod(z/a)", 'z', TRUE},
3136 {"Activate an equipment(A)", 'A', TRUE},
3137 {"Eat(E)", 'E', TRUE},
3138 {"Fire missile weapon(f/t)", 'f', TRUE},
3139 {"Throw an item(v)", 'v', TRUE},
3144 {"Get items(g)", 'g', TRUE},
3145 {"Drop an item(d)", 'd', TRUE},
3146 {"Destroy an item(k/^d)", 'k', TRUE},
3147 {"Inscribe an item({)", '{', TRUE},
3148 {"Uninscribe an item(})", '}', TRUE},
3149 {"Info about an item(I)", 'I', TRUE},
3150 {"Inventory list(i)", 'i', TRUE},
3157 {"Wear(w)", 'w', TRUE},
3158 {"Take off(t/T)", 't', TRUE},
3159 {"Refuel(F)", 'F', TRUE},
3160 {"Equipment list(e)", 'e', TRUE},
3170 {"Open(o)", 'o', TRUE},
3171 {"Close(c)", 'c', TRUE},
3172 {"Bash a door(B/f)", 'B', TRUE},
3173 {"Jam a door(j/S)", 'j', TRUE},
3183 {"Full map(M)", 'M', TRUE},
3184 {"Map(L/W)", 'L', TRUE},
3185 {"Level feeling(^f)", KTRL('F'), TRUE},
3186 {"Character status(C)", 'C', TRUE},
3187 {"Identify symbol(/)", '/', TRUE},
3188 {"Show prev messages(^p)", KTRL('P'), TRUE},
3189 {"Current time(^t/')", KTRL('T'), TRUE},
3190 {"Various information(~)", '~', TRUE},
3191 {"Play record menu(|)", '|', TRUE},
3196 {"Set options(=)", '=', TRUE},
3197 {"Interact with macros(@)", '@', TRUE},
3198 {"Interact w/ visuals(%)", '%', TRUE},
3199 {"Interact with colors(&)", '&', TRUE},
3200 {"Enter a user pref(\")", '\"', TRUE},
3201 {"Reload auto-pick pref($)", '$', TRUE},
3209 {"Save and quit(^x)", KTRL('X'), TRUE},
3210 {"Save(^s)", KTRL('S'), TRUE},
3211 {"Help(obsoleted)(?)", '?', TRUE},
3212 {"Redraw(^r)", KTRL('R'), TRUE},
3213 {"Take note(:)", ':', TRUE},
3214 {"Dump screen dump(()", ')', TRUE},
3215 {"Load screen dump())", '(', TRUE},
3216 {"Version info(V)", 'V', TRUE},
3217 {"Quit(Q)", 'Q', TRUE},
3230 } special_menu_naiyou;
3232 #define MENU_CLASS 1
3236 special_menu_naiyou special_menu_info[] =
3238 {"超能力/特殊能力", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
3239 {"ものまね/特殊能力", 0, 0, MENU_CLASS, CLASS_IMITATOR},
3240 {"歌/特殊能力", 0, 0, MENU_CLASS, CLASS_BARD},
3241 {"必殺技/特殊能力", 0, 0, MENU_CLASS, CLASS_SAMURAI},
3242 {"練気術/魔法/特殊能力", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
3243 {"技/特殊能力", 0, 0, MENU_CLASS, CLASS_BERSERKER},
3244 {"技術/特殊能力", 0, 0, MENU_CLASS, CLASS_SMITH},
3245 {"鏡魔法/特殊能力", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
3246 {"忍術/特殊能力", 0, 0, MENU_CLASS, CLASS_NINJA},
3247 {"広域マップ(<)", 2, 6, MENU_WILD, FALSE},
3248 {"通常マップ(>)", 2, 7, MENU_WILD, TRUE},
3252 special_menu_naiyou special_menu_info[] =
3254 {"MindCraft/Special", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
3255 {"Imitation/Special", 0, 0, MENU_CLASS, CLASS_IMITATOR},
3256 {"Song/Special", 0, 0, MENU_CLASS, CLASS_BARD},
3257 {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SAMURAI},
3258 {"Mind/Magic/Special", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
3259 {"BrutalPower/Special", 0, 0, MENU_CLASS, CLASS_BERSERKER},
3260 {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SMITH},
3261 {"MirrorMagic/Special", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
3262 {"Ninjutsu/Special", 0, 0, MENU_CLASS, CLASS_NINJA},
3263 {"Enter global map(<)", 2, 6, MENU_WILD, FALSE},
3264 {"Enter local map(>)", 2, 7, MENU_WILD, TRUE},
3269 static char inkey_from_menu(player_type *player_ptr)
3273 int num = 0, max_num, old_num = 0;
3277 if (player_ptr->y - panel_row_min > 10) basey = 2;
3284 floor_type* floor_ptr = player_ptr->current_floor_ptr;
3290 if (!menu) old_num = num;
3291 put_str("+----------------------------------------------------+", basey, basex);
3292 put_str("| |", basey + 1, basex);
3293 put_str("| |", basey + 2, basex);
3294 put_str("| |", basey + 3, basex);
3295 put_str("| |", basey + 4, basex);
3296 put_str("| |", basey + 5, basex);
3297 put_str("+----------------------------------------------------+", basey + 6, basex);
3299 for (i = 0; i < 10; i++)
3302 if (!menu_info[menu][i].cmd) break;
3303 menu_name = menu_info[menu][i].name;
3304 for (hoge = 0; ; hoge++)
3306 if (!special_menu_info[hoge].name[0]) break;
3307 if ((menu != special_menu_info[hoge].window) || (i != special_menu_info[hoge].number)) continue;
3308 switch (special_menu_info[hoge].jouken)
3311 if (player_ptr->pclass == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
3314 if (!floor_ptr->dun_level && !floor_ptr->inside_arena && !floor_ptr->inside_quest)
3316 if ((byte)player_ptr->wild_mode == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
3324 put_str(menu_name, basey + 1 + i / 2, basex + 4 + (i % 2) * 24);
3328 kisuu = max_num % 2;
3329 put_str(_("》", "> "), basey + 1 + num / 2, basex + 2 + (num % 2) * 24);
3331 move_cursor_relative(player_ptr->y, player_ptr->x);
3333 if ((sub_cmd == ' ') || (sub_cmd == 'x') || (sub_cmd == 'X') || (sub_cmd == '\r') || (sub_cmd == '\n'))
3335 if (menu_info[menu][num].fin)
3337 cmd = menu_info[menu][num].cmd;
3343 menu = menu_info[menu][num].cmd;
3349 else if ((sub_cmd == ESCAPE) || (sub_cmd == 'z') || (sub_cmd == 'Z') || (sub_cmd == '0'))
3366 else if ((sub_cmd == '2') || (sub_cmd == 'j') || (sub_cmd == 'J'))
3371 num = (num + 2) % (max_num - 1);
3373 num = (num + 2) % (max_num + 1);
3375 else num = (num + 2) % max_num;
3377 else if ((sub_cmd == '8') || (sub_cmd == 'k') || (sub_cmd == 'K'))
3382 num = (num + max_num - 3) % (max_num - 1);
3384 num = (num + max_num - 1) % (max_num + 1);
3386 else num = (num + max_num - 2) % max_num;
3388 else if ((sub_cmd == '4') || (sub_cmd == '6') || (sub_cmd == 'h') || (sub_cmd == 'H') || (sub_cmd == 'l') || (sub_cmd == 'L'))
3390 if ((num % 2) || (num == max_num - 1))
3394 else if (num < max_num - 1)
3402 if (!inkey_next) inkey_next = "";
3409 * Request a command from the user.
3411 * Sets player_ptr->command_cmd, player_ptr->command_dir, player_ptr->command_rep,
3412 * player_ptr->command_arg. May modify player_ptr->command_new.
3414 * Note that "caret" ("^") is treated specially, and is used to
3415 * allow manual input of control characters. This can be used
3416 * on many machines to request repeated tunneling (Ctrl-H) and
3417 * on the Macintosh to request "Control-Caret".
3419 * Note that "backslash" is treated specially, and is used to bypass any
3420 * keymap entry for the following character. This is useful for macros.
3422 * Note that this command is used both in the dungeon and in
3423 * stores, and must be careful to work in both situations.
3425 * Note that "player_ptr->command_new" may not work any more.
3427 void request_command(player_type *player_ptr, int shopping)
3437 if (rogue_like_commands)
3439 mode = KEYMAP_MODE_ROGUE;
3443 mode = KEYMAP_MODE_ORIG;
3465 if (!shopping && command_menu && ((cmd == '\r') || (cmd == '\n') || (cmd == 'x') || (cmd == 'X'))
3466 && !keymap_act[mode][(byte)(cmd)])
3467 cmd = inkey_from_menu(player_ptr);
3473 COMMAND_ARG old_arg = command_arg;
3475 prt(_("回数: ", "Count: "), 0, 0);
3479 if ((cmd == 0x7F) || (cmd == KTRL('H')))
3481 command_arg = command_arg / 10;
3482 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
3484 else if (cmd >= '0' && cmd <= '9')
3486 if (command_arg >= 1000)
3493 command_arg = command_arg * 10 + D2I(cmd);
3496 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
3504 if (command_arg == 0)
3507 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
3512 command_arg = old_arg;
3513 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
3516 if ((cmd == ' ') || (cmd == '\n') || (cmd == '\r'))
3518 if (!get_com(_("コマンド: ", "Command: "), (char *)&cmd, FALSE))
3528 (void)get_com(_("コマンド: ", "Command: "), (char *)&cmd, FALSE);
3529 if (!inkey_next) inkey_next = "";
3534 if (get_com(_("CTRL: ", "Control: "), (char *)&cmd, FALSE)) cmd = KTRL(cmd);
3537 act = keymap_act[mode][(byte)(cmd)];
3538 if (act && !inkey_next)
3540 (void)strnfmt(request_command_buffer, 256, "%s", act);
3541 inkey_next = request_command_buffer;
3547 command_cmd = (byte)cmd;
3551 if (always_repeat && (command_arg <= 0))
3553 if (my_strchr("TBDoc+", (char)command_cmd))
3561 switch (command_cmd)
3563 case 'p': command_cmd = 'g'; break;
3565 case 'm': command_cmd = 'g'; break;
3567 case 's': command_cmd = 'd'; break;
3572 for (int i = 0; i < 256; i++)
3575 if ((s = keymap_act[mode][i]) != NULL)
3577 if (*s == command_cmd && *(s + 1) == 0)
3586 caretcmd = command_cmd;
3589 for (int i = INVEN_RARM; i < INVEN_TOTAL; i++)
3591 object_type *o_ptr = &player_ptr->inventory_list[i];
3592 if (!o_ptr->k_idx) continue;
3594 if (!o_ptr->inscription) continue;
3596 concptr s = quark_str(o_ptr->inscription);
3597 s = my_strchr(s, '^');
3601 if ((s[1] == caretcmd) || (s[1] == '*'))
3603 if ((s[1] == command_cmd) || (s[1] == '*'))
3606 if (!get_check(_("本当ですか? ", "Are you sure? ")))
3612 s = my_strchr(s + 1, '^');
3621 * Check a char for "vowel-hood"
3623 bool is_a_vowel(int ch)
3646 * Called from cmd4.c and a few other places. Just extracts
3647 * a direction from the keymap for ch (the last direction,
3648 * in fact) byte or char here? I'm thinking that keymaps should
3649 * generally only apply to single keys, which makes it no more
3650 * than 128, so a char should suffice... but keymap_act is 256...
3652 int get_keymap_dir(char ch)
3663 if (rogue_like_commands)
3665 mode = KEYMAP_MODE_ROGUE;
3669 mode = KEYMAP_MODE_ORIG;
3672 concptr act = keymap_act[mode][(byte)(ch)];
3675 for (concptr s = act; *s; ++s)
3677 if (isdigit(*s)) d = D2I(*s);
3688 #define REPEAT_MAX 20
3690 /* Number of chars saved */
3691 static int repeat__cnt = 0;
3694 static int repeat__idx = 0;
3697 static COMMAND_CODE repeat__key[REPEAT_MAX];
3699 void repeat_push(COMMAND_CODE what)
3701 if (repeat__cnt == REPEAT_MAX) return;
3703 repeat__key[repeat__cnt++] = what;
3708 bool repeat_pull(COMMAND_CODE *what)
3710 if (repeat__idx == repeat__cnt) return FALSE;
3712 *what = repeat__key[repeat__idx++];
3716 void repeat_check(void)
3718 if (command_cmd == ESCAPE) return;
3719 if (command_cmd == ' ') return;
3720 if (command_cmd == '\r') return;
3721 if (command_cmd == '\n') return;
3724 if (command_cmd == 'n')
3727 if (repeat_pull(&what))
3743 * Array size for which InsertionSort
3744 * is used instead of QuickSort
3750 * Exchange two sort-entries
3751 * (should probably be coded inline
3752 * for speed increase)
3754 static void swap(tag_type *a, tag_type *b)
3765 * Insertion-Sort algorithm
3766 * (used by the Quicksort algorithm)
3768 static void InsertionSort(tag_type elements[], int number)
3771 for (int i = 1; i < number; i++)
3775 for (j = i; (j > 0) && (elements[j - 1].tag > tmp.tag); j--)
3776 elements[j] = elements[j - 1];
3783 * Helper function for Quicksort
3785 static tag_type median3(tag_type elements[], int left, int right)
3787 int center = (left + right) / 2;
3789 if (elements[left].tag > elements[center].tag)
3790 swap(&elements[left], &elements[center]);
3791 if (elements[left].tag > elements[right].tag)
3792 swap(&elements[left], &elements[right]);
3793 if (elements[center].tag > elements[right].tag)
3794 swap(&elements[center], &elements[right]);
3796 swap(&elements[center], &elements[right - 1]);
3797 return (elements[right - 1]);
3802 * Quicksort algorithm
3804 * The "median of three" pivot selection eliminates
3805 * the bad case of already sorted input.
3807 * We use InsertionSort for smaller sub-arrays,
3808 * because it is faster in this case.
3810 * For details see: "Data Structures and Algorithm
3811 * Analysis in C" by Mark Allen Weiss.
3813 static void quicksort(tag_type elements[], int left, int right)
3816 if (left + CUTOFF <= right)
3818 pivot = median3(elements, left, right);
3825 while (elements[++i].tag < pivot.tag);
3826 while (elements[--j].tag > pivot.tag);
3829 swap(&elements[i], &elements[j]);
3834 swap(&elements[i], &elements[right - 1]);
3836 quicksort(elements, left, i - 1);
3837 quicksort(elements, i + 1, right);
3841 InsertionSort(elements + left, right - left + 1);
3847 * Frontend for the sorting algorithm
3849 * Sorts an array of tagged pointers
3850 * with <number> elements.
3852 void tag_sort(tag_type elements[], int number)
3854 quicksort(elements, 0, number - 1);
3857 /* Table of gamma values */
3858 byte gamma_table[256];
3860 /* Table of ln(x/256) * 256 for x going from 0 -> 255 */
3861 static s16b gamma_helper[256] =
3863 0,-1420,-1242,-1138,-1065,-1007,-961,-921,-887,-857,-830,-806,-783,-762,-744,-726,
3864 -710,-694,-679,-666,-652,-640,-628,-617,-606,-596,-586,-576,-567,-577,-549,-541,
3865 -532,-525,-517,-509,-502,-495,-488,-482,-475,-469,-463,-457,-451,-455,-439,-434,
3866 -429,-423,-418,-413,-408,-403,-398,-394,-389,-385,-380,-376,-371,-367,-363,-359,
3867 -355,-351,-347,-343,-339,-336,-332,-328,-325,-321,-318,-314,-311,-308,-304,-301,
3868 -298,-295,-291,-288,-285,-282,-279,-276,-273,-271,-268,-265,-262,-259,-257,-254,
3869 -251,-248,-246,-243,-241,-238,-236,-233,-231,-228,-226,-223,-221,-219,-216,-214,
3870 -212,-209,-207,-205,-203,-200,-198,-196,-194,-192,-190,-188,-186,-184,-182,-180,
3871 -178,-176,-174,-172,-170,-168,-166,-164,-162,-160,-158,-156,-155,-153,-151,-149,
3872 -147,-146,-144,-142,-140,-139,-137,-135,-134,-132,-130,-128,-127,-125,-124,-122,
3873 -120,-119,-117,-116,-114,-112,-111,-109,-108,-106,-105,-103,-102,-100,-99,-97,
3874 -96,-95,-93,-92,-90,-89,-87,-86,-85,-83,-82,-80,-79,-78,-76,-75,
3875 -74,-72,-71,-70,-68,-67,-66,-65,-63,-62,-61,-59,-58,-57,-56,-54,
3876 -53,-52,-51,-50,-48,-47,-46,-45,-44,-42,-41,-40,-39,-38,-37,-35,
3877 -34,-33,-32,-31,-30,-29,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,
3878 -17,-16,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1
3883 * Build the gamma table so that floating point isn't needed.
3885 * Note gamma goes from 0->256. The old value of 100 is now 128.
3887 void build_gamma_table(int gamma)
3890 gamma_table[255] = 255;
3891 for (int i = 1; i < 255; i++)
3894 * Initialise the Taylor series
3896 * value and diff have been scaled by 256
3899 long value = 256 * 256;
3900 long diff = ((long)gamma_helper[i]) * (gamma - 256);
3909 * Use the following identiy to calculate the gamma table.
3910 * exp(x) = 1 + x + x^2/2 + x^3/(2*3) + x^4/(2*3*4) +...
3912 * n is the current term number.
3914 * The gamma_helper array contains a table of
3916 * This is used because a^b = exp(b*ln(a))
3922 * Note that everything is scaled by 256 for accuracy,
3923 * plus another factor of 256 for the final result to
3924 * be from 0-255. Thus gamma_helper[] * gamma must be
3925 * divided by 256*256 each itteration, to get back to
3926 * the original power series.
3928 diff = (((diff / 256) * gamma_helper[i]) * (gamma - 256)) / (256 * n);
3932 * Store the value in the table so that the
3933 * floating point pow function isn't needed .
3935 gamma_table[i] = ((long)(value / 256) * i) / 256;
3941 * Add a series of keypresses to the "queue".
3943 * Return any errors generated by Term_keypress() in doing so, or SUCCESS
3944 * if there are none.
3946 * Catch the "out of space" error before anything is printed.
3948 * NB: The keys added here will be interpreted by any macros or keymaps.
3950 errr type_string(concptr str, uint len)
3954 if (!str) return -1;
3955 if (!len) len = strlen(str);
3957 Term_activate(term_screen);
3958 for (concptr s = str; s < str + len; s++)
3960 if (*s == '\0') break;
3962 err = Term_keypress(*s);
3971 void roff_to_buf(concptr str, int maxlen, char *tbuf, size_t bufsize)
3980 while (str[read_pt])
3983 bool kinsoku = FALSE;
3987 ch[0] = str[read_pt];
3990 kanji = iskanji(ch[0]);
3994 ch[1] = str[read_pt + 1];
3997 if (strcmp(ch, "。") == 0 ||
3998 strcmp(ch, "、") == 0 ||
3999 strcmp(ch, "ィ") == 0 ||
4000 strcmp(ch, "ー") == 0)
4003 else if (!isprint(ch[0]))
4006 if (!isprint(ch[0]))
4010 if (line_len + ch_len > maxlen - 1 || str[read_pt] == '\n')
4012 int word_len = read_pt - word_punct;
4014 if (kanji && !kinsoku)
4018 if (ch[0] == ' ' || word_len >= line_len / 2)
4022 read_pt = word_punct;
4023 if (str[word_punct] == ' ')
4025 write_pt -= word_len;
4028 tbuf[write_pt++] = '\0';
4030 word_punct = read_pt;
4035 word_punct = read_pt;
4038 if (!kinsoku) word_punct = read_pt;
4041 if ((size_t)(write_pt + 3) >= bufsize) break;
4043 tbuf[write_pt++] = ch[0];
4049 tbuf[write_pt++] = ch[1];
4056 tbuf[write_pt] = '\0';
4057 tbuf[write_pt + 1] = '\0';
4063 * The my_strcpy() function copies up to 'bufsize'-1 characters from 'src'
4064 * to 'buf' and NUL-terminates the result. The 'buf' and 'src' strings may
4067 * my_strcpy() returns strlen(src). This makes checking for truncation
4068 * easy. Example: if (my_strcpy(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
4070 * This function should be equivalent to the strlcpy() function in BSD.
4072 size_t my_strcpy(char *buf, concptr src, size_t bufsize)
4080 /* reserve for NUL termination */
4083 /* Copy as many bytes as will fit */
4084 while (*s && (len < bufsize))
4088 if (len + 1 >= bufsize || !*(s + 1)) break;
4106 size_t len = strlen(src);
4108 if (bufsize == 0) return ret;
4110 if (len >= bufsize) len = bufsize - 1;
4112 (void)memcpy(buf, src, len);
4120 * The my_strcat() tries to append a string to an existing NUL-terminated string.
4121 * It never writes more characters into the buffer than indicated by 'bufsize' and
4122 * NUL-terminates the buffer. The 'buf' and 'src' strings may not overlap.
4124 * my_strcat() returns strlen(buf) + strlen(src). This makes checking for
4125 * truncation easy. Example:
4126 * if (my_strcat(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
4128 * This function should be equivalent to the strlcat() function in BSD.
4130 size_t my_strcat(char *buf, concptr src, size_t bufsize)
4132 size_t dlen = strlen(buf);
4133 if (dlen < bufsize - 1)
4135 return (dlen + my_strcpy(buf + dlen, src, bufsize - dlen));
4139 return (dlen + strlen(src));
4145 * A copy of ANSI strstr()
4147 * my_strstr() can handle Kanji strings correctly.
4149 char *my_strstr(concptr haystack, concptr needle)
4151 int l1 = strlen(haystack);
4152 int l2 = strlen(needle);
4156 for (int i = 0; i <= l1 - l2; i++)
4158 if (!strncmp(haystack + i, needle, l2))
4159 return (char *)haystack + i;
4162 if (iskanji(*(haystack + i))) i++;
4172 * A copy of ANSI strchr()
4174 * my_strchr() can handle Kanji strings correctly.
4176 char *my_strchr(concptr ptr, char ch)
4178 for (; *ptr != '\0'; ptr++)
4180 if (*ptr == ch) return (char *)ptr;
4183 if (iskanji(*ptr)) ptr++;
4192 * Convert string to lower case
4194 void str_tolower(char *str)
4205 *str = (char)tolower(*str);
4211 * Get a keypress from the user.
4212 * And interpret special keys as internal code.
4214 * This function is a Mega-Hack and depend on pref-xxx.prf's.
4215 * Currently works on Linux(UNIX), Windows, and Macintosh only.
4217 int inkey_special(bool numpad_cursor)
4219 static const struct {
4222 } modifier_key_list[] = {
4223 {"shift-", SKEY_MOD_SHIFT},
4224 {"control-", SKEY_MOD_CONTROL},
4228 static const struct {
4232 } special_key_list[] = {
4233 {FALSE, "Down]", SKEY_DOWN},
4234 {FALSE, "Left]", SKEY_LEFT},
4235 {FALSE, "Right]", SKEY_RIGHT},
4236 {FALSE, "Up]", SKEY_UP},
4237 {FALSE, "Page_Up]", SKEY_PGUP},
4238 {FALSE, "Page_Down]", SKEY_PGDOWN},
4239 {FALSE, "Home]", SKEY_TOP},
4240 {FALSE, "End]", SKEY_BOTTOM},
4241 {TRUE, "KP_Down]", SKEY_DOWN},
4242 {TRUE, "KP_Left]", SKEY_LEFT},
4243 {TRUE, "KP_Right]", SKEY_RIGHT},
4244 {TRUE, "KP_Up]", SKEY_UP},
4245 {TRUE, "KP_Page_Up]", SKEY_PGUP},
4246 {TRUE, "KP_Page_Down]", SKEY_PGDOWN},
4247 {TRUE, "KP_Home]", SKEY_TOP},
4248 {TRUE, "KP_End]", SKEY_BOTTOM},
4249 {TRUE, "KP_2]", SKEY_DOWN},
4250 {TRUE, "KP_4]", SKEY_LEFT},
4251 {TRUE, "KP_6]", SKEY_RIGHT},
4252 {TRUE, "KP_8]", SKEY_UP},
4253 {TRUE, "KP_9]", SKEY_PGUP},
4254 {TRUE, "KP_3]", SKEY_PGDOWN},
4255 {TRUE, "KP_7]", SKEY_TOP},
4256 {TRUE, "KP_1]", SKEY_BOTTOM},
4260 static const struct {
4263 } gcu_special_key_list[] = {
4269 {"4~", SKEY_BOTTOM},
4271 {"6~", SKEY_PGDOWN},
4284 * Forget macro trigger ----
4285 * It's important if we are already expanding macro action
4287 inkey_macro_trigger_string[0] = '\0';
4290 trig_len = strlen(inkey_macro_trigger_string);
4291 if (!trig_len) return (int)((unsigned char)key);
4292 if (trig_len == 1 && parse_macro)
4294 char c = inkey_macro_trigger_string[0];
4295 forget_macro_action();
4296 return (int)((unsigned char)c);
4299 ascii_to_text(buf, inkey_macro_trigger_string);
4300 if (prefix(str, "\\["))
4305 for (i = 0; modifier_key_list[i].keyname; i++)
4307 if (prefix(str, modifier_key_list[i].keyname))
4309 str += strlen(modifier_key_list[i].keyname);
4310 modifier |= modifier_key_list[i].keyflag;
4314 if (!modifier_key_list[i].keyname) break;
4317 if (!numpad_as_cursorkey) numpad_cursor = FALSE;
4319 for (i = 0; special_key_list[i].keyname; i++)
4321 if ((!special_key_list[i].numpad || numpad_cursor) &&
4322 streq(str, special_key_list[i].keyname))
4324 skey = special_key_list[i].keycode;
4331 forget_macro_action();
4332 return (skey | modifier);
4336 if (prefix(str, "\\e["))
4340 for (i = 0; gcu_special_key_list[i].keyname; i++)
4342 if (streq(str, gcu_special_key_list[i].keyname))
4344 return gcu_special_key_list[i].keycode;
4349 inkey_macro_trigger_string[0] = '\0';
4350 return (int)((unsigned char)key);