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 "io/signal-handlers.h"
16 #include "core/system-variables.h"
17 #include "core/stuff-handler.h"
21 #include "monsterrace-hook.h"
22 #include "view/display-main-window.h"
25 #include "world/world.h"
26 #include "io/write-diary.h"
27 #include "cmd/cmd-dump.h"
29 #include "player-class.h"
30 #include "core/output-updater.h"
31 #include "io/input-key-processor.h"
34 * 10進数から16進数への変換テーブル /
35 * Global array for converting numbers to uppercase hecidecimal digit
36 * This array can also be used to convert a number to an octal digit
38 const char hexsym[16] =
40 '0', '1', '2', '3', '4', '5', '6', '7',
41 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
45 * Keymaps for each "mode" associated with each keypress.
47 concptr keymap_act[KEYMAP_MODES][256];
50 * The next "free" index to use
55 * The index of the oldest message (none yet)
60 * The next "free" offset
65 * The offset to the oldest used char (none yet)
70 * The array of offsets, by index [MESSAGE_MAX]
75 * The array of chars, by offset [MESSAGE_BUF]
79 bool msg_flag; /* Used in msg_print() for "buffering" */
82 * Number of active macros.
87 * Array of macro patterns [MACRO_MAX]
92 * Array of macro actions [MACRO_MAX]
97 * Array of macro types [MACRO_MAX]
102 * Current macro action [1024]
106 bool get_com_no_macros = FALSE; /* Expand macros in "get_com" or not */
108 bool inkey_base; /* See the "inkey()" function */
109 bool inkey_xtra; /* See the "inkey()" function */
110 bool inkey_scan; /* See the "inkey()" function */
111 bool inkey_flag; /* See the "inkey()" function */
118 * The number of quarks
120 STR_OFFSET quark__num;
123 * The pointers to the quarks [QUARK_MAX]
127 static int num_more = 0;
129 /* Save macro trigger string for use in inkey_special() */
130 static char inkey_macro_trigger_string[1024];
132 int max_macrotrigger = 0; /*!< 現在登録中のマクロ(トリガー)の数 */
133 concptr macro_template = NULL; /*!< Angband設定ファイルのT: タグ情報から読み込んだ長いTコードを処理するために利用する文字列ポインタ */
134 concptr macro_modifier_chr; /*!< &x# で指定されるマクロトリガーに関する情報を記録する文字列ポインタ */
135 concptr macro_modifier_name[MAX_MACRO_MOD]; /*!< マクロ上で取り扱う特殊キーを文字列上で表現するためのフォーマットを記録した文字列ポインタ配列 */
136 concptr macro_trigger_name[MAX_MACRO_TRIG]; /*!< マクロのトリガーコード */
137 concptr macro_trigger_keycode[2][MAX_MACRO_TRIG]; /*!< マクロの内容 */
139 s16b command_cmd; /* Current "Angband Command" */
140 COMMAND_ARG command_arg; /*!< 各種コマンドの汎用的な引数として扱う / Gives argument of current command */
141 COMMAND_NUM command_rep; /*!< 各種コマンドの汎用的なリピート数として扱う / Gives repetition of current command */
142 DIRECTION command_dir; /*!< 各種コマンドの汎用的な方向値処理として扱う/ Gives direction of current command */
143 s16b command_see; /* See "object1.c" */
144 s16b command_wrk; /* See "object1.c" */
145 TERM_LEN command_gap = 999; /* See "object1.c" */
146 s16b command_new; /* Command chaining from inven/equip view */
153 * For those systems that don't have "usleep()" but need it.
155 * Fake "usleep()" function grabbed from the inl netrek server -cba
157 int usleep(huge usecs)
159 struct timeval timer;
164 fd_set *no_fds = NULL;
168 if (usecs > 4000000L) core(_("不当な usleep() 呼び出し", "Illegal usleep() call"));
170 timer.tv_sec = (usecs / 1000000L);
171 timer.tv_usec = (usecs % 1000000L);
172 if (select(nfds, no_fds, no_fds, no_fds, &timer) < 0)
174 if (errno != EINTR) return -1;
182 * Hack -- External functions
185 extern struct passwd *getpwuid(uid_t uid);
186 extern struct passwd *getpwnam(concptr name);
190 * Find a default user name from the system.
192 void user_name(char *buf, int id)
195 if ((pw = getpwuid(id)))
197 (void)strcpy(buf, pw->pw_name);
201 if (!iskanji(buf[0]))
204 buf[0] = toupper(buf[0]);
209 strcpy(buf, "PLAYER");
216 * The concept of the "file" routines below (and elsewhere) is that all
217 * file handling should be done using as few routines as possible, since
218 * every machine is slightly different, but these routines always have the
221 * In fact, perhaps we should use the "path_parse()" routine below to convert
222 * from "canonical" filenames (optional leading tilde's, internal wildcards,
223 * slash as the path seperator, etc) to "system" filenames (no special symbols,
224 * system-specific path seperator, etc). This would allow the program itself
225 * to assume that all filenames are "Unix" filenames, and explicitly "extract"
226 * such filenames if needed (by "path_parse()", or perhaps "path_canon()").
228 * Note that "path_temp" should probably return a "canonical" filename.
230 * Note that "my_fopen()" and "my_open()" and "my_make()" and "my_kill()"
231 * and "my_move()" and "my_copy()" should all take "canonical" filenames.
233 * Note that "canonical" filenames use a leading "slash" to indicate an absolute
234 * path, and a leading "tilde" to indicate a special directory, and default to a
235 * relative path, but MSDOS uses a leading "drivename plus colon" to indicate the
236 * use of a "special drive", and then the rest of the path is parsed "normally",
237 * and an embedded colon to indicate a "drive plus absolute path", and finally
238 * defaults to a file in the current working directory, which may or may not be defined.
240 * We should probably parse a leading "~~/" as referring to "ANGBAND_DIR". (?)
245 * Extract a "parsed" path from an initial filename
246 * Normally, we simply copy the filename into the buffer
247 * But leading tilde symbols must be handled in a special way
248 * Replace "~user/" by the home directory of the user named "user"
249 * Replace "~/" by the home directory of the current user
251 errr path_parse(char *buf, int max, concptr file)
254 if (!file) return -1;
258 (void)strnfmt(buf, max, "%s", file);
262 concptr u = file + 1;
263 concptr s = my_strstr(u, PATH_SEP);
265 if (s && (s >= u + sizeof(user))) return 1;
270 for (i = 0; u < s; ++i) user[i] = *u++;
275 if (u[0] == '\0') u = getlogin();
278 if (u) pw = getpwnam(u);
279 else pw = getpwuid(getuid());
283 if (s) strnfmt(buf, max, "%s%s", pw->pw_dir, s);
284 else strnfmt(buf, max, "%s", pw->pw_dir);
290 * Extract a "parsed" path from an initial filename
292 * This requires no special processing on simple machines,
293 * except for verifying the size of the filename.
295 errr path_parse(char *buf, int max, concptr file)
297 (void)strnfmt(buf, max, "%s", file);
306 * Hack -- acquire a "temporary" file name if possible
308 * This filename is always in "system-specific" form.
310 static errr path_temp(char *buf, int max)
312 concptr s = tmpnam(NULL);
315 #if !defined(WIN32) || (defined(_MSC_VER) && (_MSC_VER >= 1900))
316 (void)strnfmt(buf, max, "%s", s);
318 (void)strnfmt(buf, max, ".%s", s);
327 * @brief ファイル入出力のためのパス生成する。/ Create a new path by appending a file (or directory) to a path.
328 * @param buf ファイルのフルを返すバッファ
332 * @return エラーコード(ただし常に0を返す)
334 * This requires no special processing on simple machines, except
335 * for verifying the size of the filename, but note the ability to
336 * bypass the given "path" with certain special file-names.
338 * Note that the "file" may actually be a "sub-path", including
341 * Note that this function yields a path which must be "parsed"
342 * using the "parse" function above.
344 errr path_build(char *buf, int max, concptr path, concptr file)
348 (void)strnfmt(buf, max, "%s", file);
350 else if (prefix(file, PATH_SEP) && !streq(PATH_SEP, ""))
352 (void)strnfmt(buf, max, "%s", file);
356 (void)strnfmt(buf, max, "%s", file);
360 (void)strnfmt(buf, max, "%s%s%s", path, PATH_SEP, file);
368 * Hack -- replacement for "fopen()"
370 FILE *my_fopen(concptr file, concptr mode)
372 #if defined(MACH_O_CARBON)
376 if (path_parse(buf, 1024, file)) return (NULL);
377 #if defined(MACH_O_CARBON)
378 if (my_strchr(mode, 'w'))
380 tempfff = fopen(buf, mode);
381 fsetfileinfo(buf, _fcreator, _ftype);
386 return (fopen(buf, mode));
391 * Hack -- replacement for "fclose()"
393 errr my_fclose(FILE *fff)
396 if (fclose(fff) == EOF) return 1;
402 FILE *my_fopen_temp(char *buf, int max)
404 strncpy(buf, "/tmp/anXXXXXX", max);
405 int fd = mkstemp(buf);
406 if (fd < 0) return (NULL);
408 return (fdopen(fd, "w"));
410 #else /* HAVE_MKSTEMP */
411 FILE *my_fopen_temp(char *buf, int max)
413 if (path_temp(buf, max)) return (NULL);
414 return (my_fopen(buf, "w"));
416 #endif /* HAVE_MKSTEMP */
420 * Hack -- replacement for "fgets()"
422 * Read a string, without a newline, to a file
424 * Process tabs, strip internal non-printables
426 errr my_fgets(FILE *fff, char *buf, huge n)
432 if (fgets(tmp, 1024, fff))
435 guess_convert_to_system_encoding(tmp, sizeof(tmp));
437 for (s = tmp; *s; s++)
439 #if defined(MACH_O_CARBON)
442 * Be nice to the Macintosh, where a file can have Mac or Unix
443 * end of line, especially since the introduction of OS X.
444 * MPW tools were also very tolerant to the Unix EOL.
446 if (*s == '\r') *s = '\n';
448 #endif /* MACH_O_CARBON */
456 if (i + 8 >= n) break;
463 else if (iskanji(*s))
476 else if (isprint((unsigned char)*s))
493 * Hack -- replacement for "fputs()"
494 * Dump a string, plus a newline, to a file
495 * Process internal weirdness?
497 errr my_fputs(FILE *fff, concptr buf, huge n)
500 (void)fprintf(fff, "%s\n", buf);
506 * Several systems have no "O_BINARY" flag
510 #endif /* O_BINARY */
514 * Hack -- attempt to delete a file
516 errr fd_kill(concptr file)
519 if (path_parse(buf, 1024, file)) return -1;
527 * Hack -- attempt to move a file
529 errr fd_move(concptr file, concptr what)
533 if (path_parse(buf, 1024, file)) return -1;
534 if (path_parse(aux, 1024, what)) return -1;
536 (void)rename(buf, aux);
542 * Hack -- attempt to copy a file
544 errr fd_copy(concptr file, concptr what)
551 if (path_parse(buf, 1024, file)) return -1;
552 if (path_parse(aux, 1024, what)) return -1;
554 src_fd = fd_open(buf, O_RDONLY);
555 if (src_fd < 0) return -1;
557 dst_fd = fd_open(aux, O_WRONLY | O_TRUNC | O_CREAT);
558 if (dst_fd < 0) return -1;
560 while ((read_num = read(src_fd, buf, 1024)) > 0)
563 while (write_num < read_num)
565 int ret = write(dst_fd, buf + write_num, read_num - write_num);
585 * Hack -- attempt to open a file descriptor (create file)
586 * This function should fail if the file already exists
587 * Note that we assume that the file should be "binary"
589 int fd_make(concptr file, BIT_FLAGS mode)
592 if (path_parse(buf, 1024, file)) return -1;
594 #if defined(MACH_O_CARBON)
597 fdes = open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, mode);
598 if (fdes >= 0) fsetfileinfo(buf, _fcreator, _ftype);
603 return (open(buf, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, mode));
609 * Hack -- attempt to open a file descriptor (existing file)
611 * Note that we assume that the file should be "binary"
613 int fd_open(concptr file, int flags)
616 if (path_parse(buf, 1024, file)) return -1;
618 return (open(buf, flags | O_BINARY, 0));
623 * Hack -- attempt to lock a file descriptor
625 * Legal lock types -- F_UNLCK, F_RDLCK, F_WRLCK
627 errr fd_lock(int fd, int what)
629 what = what ? what : 0;
630 if (fd < 0) return -1;
632 #if defined(SET_UID) && defined(LOCK_UN) && defined(LOCK_EX)
635 (void)flock(fd, LOCK_UN);
639 if (flock(fd, LOCK_EX) != 0) return 1;
648 * Hack -- attempt to seek on a file descriptor
650 errr fd_seek(int fd, huge n)
652 if (fd < 0) return -1;
654 huge p = lseek(fd, n, SEEK_SET);
655 if (p != n) return 1;
662 * Hack -- attempt to truncate a file descriptor
664 errr fd_chop(int fd, huge n)
667 return fd >= 0 ? 0 : -1;
672 * Hack -- attempt to read data from a file descriptor
674 errr fd_read(int fd, char *buf, huge n)
676 if (fd < 0) return -1;
680 if (read(fd, buf, 16384) != 16384) return 1;
687 if (read(fd, buf, n) != (int)n) return 1;
694 * Hack -- Attempt to write data to a file descriptor
696 errr fd_write(int fd, concptr buf, huge n)
698 if (fd < 0) return -1;
703 if (write(fd, buf, 16384) != 16384) return 1;
710 if (write(fd, buf, n) != (int)n) return 1;
717 * Hack -- attempt to close a file descriptor
719 errr fd_close(int fd)
721 if (fd < 0) return -1;
729 * Important note about "colors"
731 * The "TERM_*" color definitions list the "composition" of each
732 * "Angband color" in terms of "quarters" of each of the three color
733 * components (Red, Green, Blue), for example, TERM_UMBER is defined
734 * as 2/4 Red, 1/4 Green, 0/4 Blue.
736 * The following info is from "Torbjorn Lindgren" (see "main-xaw.c").
738 * These values are NOT gamma-corrected. On most machines (with the
739 * Macintosh being an important exception), you must "gamma-correct"
740 * the given values, that is, "correct for the intrinsic non-linearity
741 * of the phosphor", by converting the given intensity levels based
742 * on the "gamma" of the target screen, which is usually 1.7 (or 1.5).
744 * The actual formula for conversion is unknown to me at this time,
745 * but you can use the table below for the most common gamma values.
747 * So, on most machines, simply convert the values based on the "gamma"
748 * of the target screen, which is usually in the range 1.5 to 1.7, and
749 * usually is closest to 1.7. The converted value for each of the five
750 * different "quarter" values is given below:
752 * Given Gamma 1.0 Gamma 1.5 Gamma 1.7 Hex 1.7
753 * ----- ---- ---- ---- ---
754 * 0/4 0.00 0.00 0.00 #00
755 * 1/4 0.25 0.27 0.28 #47
756 * 2/4 0.50 0.55 0.56 #8f
757 * 3/4 0.75 0.82 0.84 #d7
758 * 4/4 1.00 1.00 1.00 #ff
760 * Note that some machines (i.e. most IBM machines) are limited to a
761 * hard-coded set of colors, and so the information above is useless.
763 * Also, some machines are limited to a pre-determined set of colors,
764 * for example, the IBM can only display 16 colors, and only 14 of
765 * those colors resemble colors used by Angband, and then only when
766 * you ignore the fact that "Slate" and "cyan" are not really matches,
767 * so on the IBM, we use "orange" for both "Umber", and "Light Umber"
768 * in addition to the obvious "Orange", since by combining all of the
769 * "indeterminate" colors into a single color, the rest of the colors
770 * are left with "meaningful" values.
777 void move_cursor(int row, int col)
779 Term_gotoxy(col, row);
784 * Convert a decimal to a single digit octal number
786 static char octify(uint i)
788 return (hexsym[i % 8]);
793 * Convert a decimal to a single digit hex number
795 static char hexify(uint i)
797 return (hexsym[i % 16]);
802 * Convert a octal-digit into a decimal
804 static int deoct(char c)
806 if (isdigit(c)) return (D2I(c));
812 * Convert a hexidecimal-digit into a decimal
814 static int dehex(char c)
816 if (isdigit(c)) return (D2I(c));
817 if (islower(c)) return (A2I(c) + 10);
818 if (isupper(c)) return (A2I(tolower(c)) + 10);
823 static int my_stricmp(concptr a, concptr b)
825 for (concptr s1 = a, s2 = b; TRUE; s1++, s2++)
827 char z1 = FORCEUPPER(*s1);
828 char z2 = FORCEUPPER(*s2);
829 if (z1 < z2) return -1;
830 if (z1 > z2) return 1;
835 static int my_strnicmp(concptr a, concptr b, int n)
837 for (concptr s1 = a, s2 = b; n > 0; s1++, s2++, n--)
839 char z1 = FORCEUPPER(*s1);
840 char z2 = FORCEUPPER(*s2);
841 if (z1 < z2) return -1;
842 if (z1 > z2) return 1;
850 static void trigger_text_to_ascii(char **bufptr, concptr *strptr)
853 concptr str = *strptr;
854 bool mod_status[MAX_MACRO_MOD];
860 if (macro_template == NULL)
863 for (i = 0; macro_modifier_chr[i]; i++)
864 mod_status[i] = FALSE;
867 /* Examine modifier keys */
870 for (i = 0; macro_modifier_chr[i]; i++)
872 len = strlen(macro_modifier_name[i]);
874 if (!my_strnicmp(str, macro_modifier_name[i], len))
878 if (!macro_modifier_chr[i]) break;
880 mod_status[i] = TRUE;
881 if ('S' == macro_modifier_chr[i])
885 for (i = 0; i < max_macrotrigger; i++)
887 len = strlen(macro_trigger_name[i]);
888 if (!my_strnicmp(str, macro_trigger_name[i], len) && ']' == str[len])
894 if (i == max_macrotrigger)
896 str = my_strchr(str, ']');
902 *strptr = str; /* where **strptr == ']' */
908 key_code = macro_trigger_keycode[shiftstatus][i];
912 for (i = 0; macro_template[i]; i++)
914 char ch = macro_template[i];
918 for (int j = 0; macro_modifier_chr[j]; j++)
921 *s++ = macro_modifier_chr[j];
927 s += strlen(key_code);
938 *strptr = str; /* where **strptr == ']' */
944 * Hack -- convert a printable string into real ascii
946 * I have no clue if this function correctly handles, for example,
947 * parsing "\xFF" into a (signed) char. Whoever thought of making
948 * the "sign" of a "char" undefined is a complete moron. Oh well.
950 void text_to_ascii(char *buf, concptr str)
962 trigger_text_to_ascii(&s, &str);
968 *s = 16 * (char)dehex(*++str);
969 *s++ += (char)dehex(*++str);
971 else if (*str == '\\')
975 else if (*str == '^')
979 else if (*str == 's')
983 else if (*str == 'e')
987 else if (*str == 'b')
991 else if (*str == 'n')
995 else if (*str == 'r')
999 else if (*str == 't')
1003 else if (*str == '0')
1005 *s = 8 * (char)deoct(*++str);
1006 *s++ += (char)deoct(*++str);
1008 else if (*str == '1')
1010 *s = 64 + 8 * (char)deoct(*++str);
1011 *s++ += (char)deoct(*++str);
1013 else if (*str == '2')
1015 *s = 64 * 2 + 8 * (char)deoct(*++str);
1016 *s++ += (char)deoct(*++str);
1018 else if (*str == '3')
1020 *s = 64 * 3 + 8 * (char)deoct(*++str);
1021 *s++ += (char)deoct(*++str);
1027 else if (*str == '^')
1030 *s++ = (*str++ & 037);
1042 static bool trigger_ascii_to_text(char **bufptr, concptr *strptr)
1045 concptr str = *strptr;
1048 if (macro_template == NULL)
1055 for (i = 0; macro_template[i]; i++)
1057 char ch = macro_template[i];
1062 while ((tmp = my_strchr(macro_modifier_chr, *str)) != 0)
1064 int j = (int)(tmp - macro_modifier_chr);
1065 tmp = macro_modifier_name[j];
1066 while (*tmp) *s++ = *tmp++;
1074 for (j = 0; *str && *str != '\r'; j++)
1075 key_code[j] = *str++;
1080 if (ch != *str) return FALSE;
1085 if (*str++ != '\r') return FALSE;
1087 for (i = 0; i < max_macrotrigger; i++)
1089 if (!my_stricmp(key_code, macro_trigger_keycode[0][i])
1090 || !my_stricmp(key_code, macro_trigger_keycode[1][i]))
1094 if (i == max_macrotrigger)
1097 tmp = macro_trigger_name[i];
1098 while (*tmp) *s++ = *tmp++;
1109 * Hack -- convert a string into a printable form
1111 void ascii_to_text(char *buf, concptr str)
1116 byte i = (byte)(*str++);
1119 if (!trigger_ascii_to_text(&s, &str))
1180 *s++ = octify(i / 8);
1181 *s++ = octify(i % 8);
1187 *s++ = hexify(i / 16);
1188 *s++ = hexify(i % 16);
1198 * Determine if any macros have ever started with a given character.
1200 static bool macro__use[256];
1204 * Find the macro (if any) which exactly matches the given pattern
1206 sint macro_find_exact(concptr pat)
1208 if (!macro__use[(byte)(pat[0])])
1213 for (int i = 0; i < macro__num; ++i)
1215 if (!streq(macro__pat[i], pat)) continue;
1225 * Find the first macro (if any) which contains the given pattern
1227 static sint macro_find_check(concptr pat)
1229 if (!macro__use[(byte)(pat[0])])
1234 for (int i = 0; i < macro__num; ++i)
1236 if (!prefix(macro__pat[i], pat)) continue;
1246 * Find the first macro (if any) which contains the given pattern and more
1248 static sint macro_find_maybe(concptr pat)
1250 if (!macro__use[(byte)(pat[0])])
1255 for (int i = 0; i < macro__num; ++i)
1257 if (!prefix(macro__pat[i], pat)) continue;
1258 if (streq(macro__pat[i], pat)) continue;
1268 * Find the longest macro (if any) which starts with the given pattern
1270 static sint macro_find_ready(concptr pat)
1272 int t, n = -1, s = -1;
1274 if (!macro__use[(byte)(pat[0])])
1279 for (int i = 0; i < macro__num; ++i)
1281 if (!prefix(pat, macro__pat[i])) continue;
1283 t = strlen(macro__pat[i]);
1284 if ((n >= 0) && (s > t)) continue;
1295 * Add a macro definition (or redefinition).
1297 * We should use "act == NULL" to "remove" a macro, but this might make it
1298 * impossible to save the "removal" of a macro definition.
1300 * We should consider refusing to allow macros which contain existing macros,
1301 * or which are contained in existing macros, because this would simplify the
1302 * macro analysis code.
1304 * We should consider removing the "command macro" crap, and replacing it
1305 * with some kind of "powerful keymap" ability, but this might make it hard
1306 * to change the "roguelike" option from inside the game.
1308 errr macro_add(concptr pat, concptr act)
1310 if (!pat || !act) return -1;
1312 int n = macro_find_exact(pat);
1315 string_free(macro__act[n]);
1320 macro__pat[n] = string_make(pat);
1323 macro__act[n] = string_make(act);
1324 macro__use[(byte)(pat[0])] = TRUE;
1330 * Local variable -- we are inside a "macro action"
1332 * Do not match any macros until "ascii 30" is found.
1334 static bool parse_macro = FALSE;
1337 * Local variable -- we are inside a "macro trigger"
1339 * Strip all keypresses until a low ascii value is found.
1341 static bool parse_under = FALSE;
1344 * Flush all input chars. Actually, remember the flush,
1345 * and do a "special flush" before the next "inkey()".
1347 * This is not only more efficient, but also necessary to make sure
1348 * that various "inkey()" codes are not "lost" along the way.
1357 * Flush the screen, make a noise
1362 if (ring_bell) Term_xtra(TERM_XTRA_NOISE, 0);
1369 * Hack -- Make a (relevant?) sound
1373 if (!use_sound) return;
1375 Term_xtra(TERM_XTRA_SOUND, val);
1380 * Hack -- Play a music
1382 errr play_music(int type, int val)
1384 if (!use_music) return 1;
1386 return Term_xtra(type, val);
1391 * Hack -- Select floor music.
1393 void select_floor_music(player_type *player_ptr)
1395 if (!use_music) return;
1397 if (player_ptr->ambush_flag)
1399 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_AMBUSH)) return;
1402 if (player_ptr->wild_mode)
1404 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_WILD)) return;
1407 if (player_ptr->current_floor_ptr->inside_arena)
1409 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_ARENA)) return;
1412 if (player_ptr->phase_out)
1414 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_BATTLE)) return;
1417 if (player_ptr->current_floor_ptr->inside_quest)
1419 if (!play_music(TERM_XTRA_MUSIC_QUEST, player_ptr->current_floor_ptr->inside_quest)) return;
1420 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_QUEST)) return;
1423 if (player_ptr->dungeon_idx)
1425 if (player_ptr->feeling == 2)
1427 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_FEEL2)) return;
1429 else if (player_ptr->feeling >= 3 && player_ptr->feeling <= 5)
1431 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_FEEL1)) return;
1435 if (!play_music(TERM_XTRA_MUSIC_DUNGEON, player_ptr->dungeon_idx)) return;
1437 if (player_ptr->current_floor_ptr->dun_level < 40)
1439 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_LOW)) return;
1441 else if (player_ptr->current_floor_ptr->dun_level < 80)
1443 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_MED)) return;
1447 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_DUN_HIGH)) return;
1452 if (player_ptr->town_num)
1454 if (!play_music(TERM_XTRA_MUSIC_TOWN, player_ptr->town_num)) return;
1455 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_TOWN)) return;
1459 if (!player_ptr->current_floor_ptr->dun_level)
1461 if (player_ptr->lev >= 45)
1463 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD3)) return;
1465 else if (player_ptr->lev >= 25)
1467 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD2)) return;
1471 if (!play_music(TERM_XTRA_MUSIC_BASIC, MUSIC_BASIC_FIELD1)) return;
1475 play_music(TERM_XTRA_MUSIC_MUTE, 0);
1481 * Helper function called only from "inkey()"
1483 * This function does almost all of the "macro" processing.
1485 * We use the "Term_key_push()" function to handle "failed" macros, as well
1486 * as "extra" keys read in while choosing the proper macro, and also to hold
1487 * the action for the macro, plus a special "ascii 30" character indicating
1488 * that any macro action in progress is complete. Embedded macros are thus
1489 * illegal, unless a macro action includes an explicit "ascii 30" character,
1490 * which would probably be a massive hack, and might break things.
1492 * Only 500 (0+1+2+...+29+30) milliseconds may elapse between each key in
1493 * the macro trigger sequence. If a key sequence forms the "prefix" of a
1494 * macro trigger, 500 milliseconds must pass before the key sequence is
1495 * known not to be that macro trigger.
1497 static char inkey_aux(void)
1499 int k = 0, n, p = 0, w = 0;
1501 char *buf = inkey_macro_trigger_string;
1507 if (Term_inkey(&ch, FALSE, TRUE))
1509 parse_macro = FALSE;
1514 (void)(Term_inkey(&ch, TRUE, TRUE));
1517 if (ch == 30) parse_macro = FALSE;
1519 if (ch == 30) return (ch);
1520 if (parse_macro) return (ch);
1521 if (parse_under) return (ch);
1525 k = macro_find_check(buf);
1526 if (k < 0) return (ch);
1530 k = macro_find_maybe(buf);
1534 if (0 == Term_inkey(&ch, FALSE, TRUE))
1545 Term_xtra(TERM_XTRA_DELAY, w);
1549 k = macro_find_ready(buf);
1554 if (Term_key_push(buf[--p])) return 0;
1557 (void)Term_inkey(&ch, TRUE, TRUE);
1561 concptr pat = macro__pat[k];
1565 if (Term_key_push(buf[--p])) return 0;
1569 if (Term_key_push(30)) return 0;
1571 concptr act = macro__act[k];
1576 if (Term_key_push(act[--n])) return 0;
1584 * Cancel macro action on the queue
1586 static void forget_macro_action(void)
1588 if (!parse_macro) return;
1593 if (Term_inkey(&ch, FALSE, TRUE)) break;
1595 if (ch == 30) break;
1598 parse_macro = FALSE;
1602 * Mega-Hack -- special "inkey_next" pointer.
1604 * This special pointer allows a sequence of keys to be "inserted" into
1605 * the stream of keys returned by "inkey()". This key sequence will not
1606 * trigger any macros, and cannot be bypassed by the Borg. It is used
1607 * in Angband to handle "keymaps".
1609 static concptr inkey_next = NULL;
1612 * Get a keypress from the user.
1614 * This function recognizes a few "global parameters". These are variables
1615 * which, if set to TRUE before calling this function, will have an effect
1616 * on this function, and which are always reset to FALSE by this function
1617 * before this function returns. Thus they function just like normal
1618 * parameters, except that most calls to this function can ignore them.
1620 * If "inkey_xtra" is TRUE, then all pending keypresses will be flushed,
1621 * and any macro processing in progress will be aborted. This flag is
1622 * set by the "flush()" function, which does not actually flush anything
1623 * itself, but rather, triggers delayed input flushing via "inkey_xtra".
1625 * If "inkey_scan" is TRUE, then we will immediately return "zero" if no
1626 * keypress is available, instead of waiting for a keypress.
1628 * If "inkey_base" is TRUE, then all macro processing will be bypassed.
1629 * If "inkey_base" and "inkey_scan" are both TRUE, then this function will
1630 * not return immediately, but will wait for a keypress for as long as the
1631 * normal macro matching code would, allowing the direct entry of macro
1632 * triggers. The "inkey_base" flag is extremely dangerous!
1634 * If "inkey_flag" is TRUE, then we will assume that we are waiting for a
1635 * normal command, and we will only show the cursor if "hilite_player" is
1636 * TRUE (or if the player is in a store), instead of always showing the
1637 * cursor. The various "main-xxx.c" files should avoid saving the game
1638 * in response to a "menu item" request unless "inkey_flag" is TRUE, to
1639 * prevent savefile corruption.
1641 * If we are waiting for a keypress, and no keypress is ready, then we will
1642 * refresh (once) the window which was active when this function was called.
1644 * Note that "back-quote" is automatically converted into "escape" for
1645 * convenience on machines with no "escape" key. This is done after the
1646 * macro matching, so the user can still make a macro for "backquote".
1648 * Note the special handling of "ascii 30" (ctrl-caret, aka ctrl-shift-six)
1649 * and "ascii 31" (ctrl-underscore, aka ctrl-shift-minus), which are used to
1650 * provide support for simple keyboard "macros". These keys are so strange
1651 * that their loss as normal keys will probably be noticed by nobody. The
1652 * "ascii 30" key is used to indicate the "end" of a macro action, which
1653 * allows recursive macros to be avoided. The "ascii 31" key is used by
1654 * some of the "main-xxx.c" files to introduce macro trigger sequences.
1656 * Hack -- we use "ascii 29" (ctrl-right-bracket) as a special "magic" key,
1657 * which can be used to give a variety of "sub-commands" which can be used
1658 * any time. These sub-commands could include commands to take a picture of
1659 * the current screen, to start/stop recording a macro action, etc.
1661 * If "angband_term[0]" is not active, we will make it active during this
1662 * function, so that the various "main-xxx.c" files can assume that input
1663 * is only requested (via "Term_inkey()") when "angband_term[0]" is active.
1665 * Mega-Hack -- This function is used as the entry point for clearing the
1666 * "signal_count" variable, and of the "current_world_ptr->character_saved" variable.
1668 * Hack -- Note the use of "inkey_next" to allow "keymaps" to be processed.
1670 * Mega-Hack -- Note the use of "inkey_hack" to allow the "Borg" to steal
1671 * control of the keyboard from the user.
1679 if (inkey_next && *inkey_next && !inkey_xtra)
1682 inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
1689 parse_macro = FALSE;
1690 parse_under = FALSE;
1695 (void)Term_get_cursor(&v);
1697 /* Show the cursor if waiting, except sometimes in "command" mode */
1698 if (!inkey_scan && (!inkey_flag || hilite_player || current_world_ptr->character_icky))
1700 (void)Term_set_cursor(1);
1703 Term_activate(angband_term[0]);
1707 if (!inkey_base && inkey_scan &&
1708 (0 != Term_inkey(&kk, FALSE, FALSE)))
1713 if (!done && (0 != Term_inkey(&kk, FALSE, FALSE)))
1717 Term_activate(angband_term[0]);
1718 current_world_ptr->character_saved = FALSE;
1729 if (0 == Term_inkey(&ch, TRUE, TRUE))
1739 if (0 == Term_inkey(&ch, FALSE, TRUE))
1746 if (w >= 100) break;
1748 Term_xtra(TERM_XTRA_DELAY, w);
1762 if (parse_under && (ch <= 32))
1765 parse_under = FALSE;
1777 else if (parse_under)
1785 inkey_base = inkey_xtra = inkey_flag = inkey_scan = FALSE;
1791 * Initialize the quark array
1793 void quark_init(void)
1795 C_MAKE(quark__str, QUARK_MAX, concptr);
1796 quark__str[1] = string_make("");
1802 * Add a new "quark" to the set of quarks.
1804 u16b quark_add(concptr str)
1807 for (i = 1; i < quark__num; i++)
1809 if (streq(quark__str[i], str)) return (i);
1812 if (quark__num == QUARK_MAX) return 1;
1815 quark__str[i] = string_make(str);
1821 * This function looks up a quark
1823 concptr quark_str(STR_OFFSET i)
1827 /* Return NULL for an invalid index */
1828 if ((i < 1) || (i >= quark__num)) return NULL;
1830 /* Access the quark */
1833 /* Return the quark */
1839 * @brief 保存中の過去ゲームメッセージの数を返す。 / How many messages are "available"?
1840 * @return 残っているメッセージの数
1842 s32b message_num(void)
1845 int last = message__last;
1846 int next = message__next;
1848 if (next < last) next += MESSAGE_MAX;
1856 * @brief 過去のゲームメッセージを返す。 / Recall the "text" of a saved message
1857 * @params age メッセージの世代
1858 * @return メッセージの文字列ポインタ
1860 concptr message_str(int age)
1862 if ((age < 0) || (age >= message_num())) return ("");
1864 s32b x = (message__next + MESSAGE_MAX - (age + 1)) % MESSAGE_MAX;
1865 s32b o = message__ptr[x];
1866 concptr s = &message__buf[o];
1872 * @brief ゲームメッセージをログに追加する。 / Add a new message, with great efficiency
1873 * @params str 保存したいメッセージ
1876 void message_add(concptr str)
1886 u32b n = strlen(str);
1887 if (n >= MESSAGE_BUF / 4) return;
1893 for (n = 0; n < 80; n++, t++)
1902 if (n == 81) n = 79;
1904 for (n = 80; n > 60; n--)
1905 if (str[n] == ' ') break;
1906 if (n == 60) n = 80;
1908 splitted2 = str + n;
1909 strncpy(splitted1, str, n);
1910 splitted1[n] = '\0';
1920 if (k > MESSAGE_MAX / 32) k = MESSAGE_MAX / 32;
1921 for (i = message__next; m; m--)
1927 if (i-- == 0) i = MESSAGE_MAX - 1;
1929 old = &message__buf[message__ptr[i]];
1934 for (t = buf; *t && (*t != '<' || (*(t + 1) != 'x')); t++)
1935 if (iskanji(*t))t++;
1937 for (t = buf; *t && (*t != '<'); t++);
1941 if (strlen(buf) < A_MAX) break;
1947 if (streq(buf, str) && (j < 1000))
1952 sprintf(u, "%s <x%d>", buf, j);
1954 if (!now_message) now_message++;
1966 for (i = message__next; k; k--)
1971 if (i-- == 0) i = MESSAGE_MAX - 1;
1973 if (i == message__last) break;
1975 q = (message__head + MESSAGE_BUF - message__ptr[i]) % MESSAGE_BUF;
1977 if (q > MESSAGE_BUF / 2) continue;
1979 old = &message__buf[message__ptr[i]];
1980 if (!streq(old, str)) continue;
1982 x = message__next++;
1983 if (message__next == MESSAGE_MAX) message__next = 0;
1984 if (message__next == message__last) message__last++;
1985 if (message__last == MESSAGE_MAX) message__last = 0;
1987 message__ptr[x] = message__ptr[i];
1988 if (splitted2 != NULL)
1990 message_add(splitted2);
1996 if (message__head + n + 1 >= MESSAGE_BUF)
1998 for (i = message__last; TRUE; i++)
2000 if (i == MESSAGE_MAX) i = 0;
2001 if (i == message__next) break;
2002 if (message__ptr[i] >= message__head)
2004 message__last = i + 1;
2008 if (message__tail >= message__head) message__tail = 0;
2013 if (message__head + n + 1 > message__tail)
2015 message__tail = message__head + n + 1;
2016 while (message__buf[message__tail - 1]) message__tail++;
2018 for (i = message__last; TRUE; i++)
2020 if (i == MESSAGE_MAX) i = 0;
2021 if (i == message__next) break;
2022 if ((message__ptr[i] >= message__head) &&
2023 (message__ptr[i] < message__tail))
2025 message__last = i + 1;
2031 x = message__next++;
2032 if (message__next == MESSAGE_MAX) message__next = 0;
2033 if (message__next == message__last) message__last++;
2034 if (message__last == MESSAGE_MAX) message__last = 0;
2036 message__ptr[x] = message__head;
2037 for (i = 0; i < n; i++)
2039 message__buf[message__head + i] = str[i];
2042 message__buf[message__head + i] = '\0';
2043 message__head += n + 1;
2045 if (splitted2 != NULL)
2047 message_add(splitted2);
2055 static void msg_flush(player_type *player_ptr, int x)
2057 byte a = TERM_L_BLUE;
2058 bool nagasu = FALSE;
2059 if ((auto_more && !player_ptr->now_damaged) || num_more < 0) {
2061 for (i = 0; i < 8; i++)
2063 if (angband_term[i] && (window_flag[i] & PW_MESSAGE)) break;
2067 if (num_more < angband_term[i]->hgt) nagasu = TRUE;
2075 player_ptr->now_damaged = FALSE;
2076 if (!player_ptr->playing || !nagasu)
2078 Term_putstr(x, 0, -1, a, _("-続く-", "-more-"));
2084 /* auto_moreのとき、全て流す */
2088 else if (cmd == ' ')
2094 else if ((cmd == '\n') || (cmd == '\r'))
2101 if (quick_messages) break;
2106 Term_erase(0, 0, 255);
2110 void msg_erase(void)
2117 * todo ここのp_ptrを削除するのは破滅的に作業が増えるので保留
2118 * Output a message to the top line of the screen.
2120 * Break long messages into multiple pieces (40-72 chars).
2122 * Allow multiple short messages to "share" the top line.
2124 * Prompt the user to make sure he has a chance to read them.
2126 * These messages are memorized for later reference (see above).
2128 * We could do "Term_fresh()" to provide "flicker" if needed.
2130 * The global "msg_flag" variable can be cleared to tell us to
2131 * "erase" any "pending" messages still on the screen.
2133 * Note that we must be very careful about using the
2134 * "msg_print()" functions without explicitly calling the special
2135 * "msg_print(NULL)" function, since this may result in the loss
2136 * of information if the screen is cleared, or if anything is
2137 * displayed on the top line.
2139 * Note that "msg_print(NULL)" will clear the top line
2140 * even if no messages are pending. This is probably a hack.
2142 void msg_print(concptr msg)
2148 if (current_world_ptr->timewalk_m_idx) return;
2152 Term_erase(0, 0, 255);
2156 int n = (msg ? strlen(msg) : 0);
2157 if (p && (!msg || ((p + n) > 72)))
2159 msg_flush(p_ptr, p);
2165 if (n > 1000) return;
2173 sprintf(buf, ("T:%d - %s"), (int)current_world_ptr->game_turn, msg);
2177 if (current_world_ptr->character_generated) message_add(buf);
2182 int check, split = 72;
2184 bool k_flag = FALSE;
2186 for (check = 0; check < 72; check++)
2194 if (iskanji(t[check]))
2199 else if (t[check] == ' ')
2213 for (check = 40; check < 72; check++)
2215 if (t[check] == ' ') split = check;
2219 char oops = t[split];
2221 Term_putstr(0, 0, split, TERM_WHITE, t);
2222 msg_flush(p_ptr, split + 1);
2225 t += split; n -= split;
2228 Term_putstr(p, 0, n, TERM_WHITE, t);
2229 p_ptr->window |= (PW_MESSAGE);
2230 update_output(p_ptr);
2239 if (fresh_message) Term_fresh();
2243 void msg_print_wizard(int cheat_type, concptr msg)
2245 if (!cheat_room && cheat_type == CHEAT_DUNGEON) return;
2246 if (!cheat_peek && cheat_type == CHEAT_OBJECT) return;
2247 if (!cheat_hear && cheat_type == CHEAT_MONSTER) return;
2248 if (!cheat_xtra && cheat_type == CHEAT_MISC) return;
2250 concptr cheat_mes[] = { "ITEM", "MONS", "DUNG", "MISC" };
2252 sprintf(buf, "WIZ-%s:%s", cheat_mes[cheat_type], msg);
2255 if (cheat_diary_output)
2257 exe_write_diary(p_ptr, DIARY_WIZARD_LOG, 0, buf);
2264 * Hack -- prevent "accidents" in "screen_save()" or "screen_load()"
2266 static int screen_depth = 0;
2270 * Save the screen, and increase the "icky" depth.
2272 * This function must match exactly one call to "screen_load()".
2277 if (screen_depth++ == 0) Term_save();
2279 current_world_ptr->character_icky++;
2284 * Load the screen, and decrease the "icky" depth.
2286 * This function must match exactly one call to "screen_save()".
2291 if (--screen_depth == 0) Term_load();
2293 current_world_ptr->character_icky--;
2298 * Display a formatted message, using "vstrnfmt()" and "msg_print()".
2300 void msg_format(concptr fmt, ...)
2305 (void)vstrnfmt(buf, 1024, fmt, vp);
2312 * Display a formatted message, using "vstrnfmt()" and "msg_print()".
2314 void msg_format_wizard(int cheat_type, concptr fmt, ...)
2316 if (!cheat_room && cheat_type == CHEAT_DUNGEON) return;
2317 if (!cheat_peek && cheat_type == CHEAT_OBJECT) return;
2318 if (!cheat_hear && cheat_type == CHEAT_MONSTER) return;
2319 if (!cheat_xtra && cheat_type == CHEAT_MISC) return;
2324 (void)vstrnfmt(buf, 1024, fmt, vp);
2326 msg_print_wizard(cheat_type, buf);
2331 * Display a string on the screen using an attribute.
2333 * At the given location, using the given attribute, if allowed,
2334 * add the given string. Do not clear the line.
2336 void c_put_str(TERM_COLOR attr, concptr str, TERM_LEN row, TERM_LEN col)
2338 Term_putstr(col, row, -1, attr, str);
2343 * As above, but in "white"
2345 void put_str(concptr str, TERM_LEN row, TERM_LEN col)
2347 Term_putstr(col, row, -1, TERM_WHITE, str);
2352 * Display a string on the screen using an attribute, and clear
2353 * to the end of the line.
2355 void c_prt(TERM_COLOR attr, concptr str, TERM_LEN row, TERM_LEN col)
2357 Term_erase(col, row, 255);
2358 Term_addstr(-1, attr, str);
2363 * As above, but in "white"
2365 void prt(concptr str, TERM_LEN row, TERM_LEN col)
2368 c_prt(TERM_WHITE, str, row, col);
2373 * Print some (colored) text to the screen at the current cursor position,
2374 * automatically "wrapping" existing text (at spaces) when necessary to
2375 * avoid placing any text into the last column, and clearing every line
2376 * before placing any text in that line. Also, allow "newline" to force
2377 * a "wrap" to the next line. Advance the cursor as needed so sequential
2378 * calls to this function will work correctly.
2380 * Once this function has been called, the cursor should not be moved
2381 * until all the related "c_roff()" calls to the window are complete.
2383 * This function will correctly handle any width up to the maximum legal
2384 * value of 256, though it works best for a standard 80 character width.
2386 void c_roff(TERM_COLOR a, concptr str)
2389 (void)Term_get_size(&w, &h);
2392 (void)Term_locate(&x, &y);
2394 if (y == h - 1 && x > w - 3) return;
2396 for (concptr s = str; *s; s++)
2400 int k_flag = iskanji(*s);
2408 Term_erase(x, y, 255);
2413 ch = ((k_flag || isprint(*s)) ? *s : ' ');
2415 ch = (isprint(*s) ? *s : ' ');
2419 if ((x >= ((k_flag) ? w - 2 : w - 1)) && (ch != ' '))
2421 if ((x >= w - 1) && (ch != ' '))
2435 for (i = w - 2; i >= 0; i--)
2437 Term_what(i, y, &av[i], &cv[i]);
2438 if (cv[i] == ' ') break;
2442 if (cv[i] == '(') break;
2450 /* 文頭が「。」「、」等になるときは、その1つ前の語で改行 */
2451 if (strncmp(s, "。", 2) == 0 || strncmp(s, "、", 2) == 0)
2453 Term_what(x, y, &av[x], &cv[x]);
2454 Term_what(x - 1, y, &av[x - 1], &cv[x - 1]);
2455 Term_what(x - 2, y, &av[x - 2], &cv[x - 2]);
2464 Term_erase(n, y, 255);
2469 Term_erase(x, y, 255);
2470 for (i = n; i < w - 1; i++)
2473 if (cv[i] == '\0') break;
2475 Term_addch(av[i], cv[i]);
2481 Term_addch((byte)(a | 0x10), ch);
2492 Term_addch((byte)(a | 0x20), ch);
2502 * As above, but in "white"
2504 void roff(concptr str)
2507 c_roff(TERM_WHITE, str);
2512 * Clear part of the screen
2514 void clear_from(int row)
2516 for (int y = row; y < Term->hgt; y++)
2518 Term_erase(0, y, 255);
2524 * Get some string input at the cursor location.
2525 * Assume the buffer is initialized to a default string.
2527 * The default buffer is in Overwrite mode and displayed in yellow at
2528 * first. Normal chars clear the yellow text and append the char in
2531 * LEFT (^B) and RIGHT (^F) movement keys move the cursor position.
2532 * If the text is still displayed in yellow (Overwite mode), it will
2533 * turns into white (Insert mode) when cursor moves.
2535 * DELETE (^D) deletes a char at the cursor position.
2536 * BACKSPACE (^H) deletes a char at the left of cursor position.
2537 * ESCAPE clears the buffer and the window and returns FALSE.
2538 * RETURN accepts the current buffer contents and returns TRUE.
2540 bool askfor_aux(char *buf, int len, bool numpad_cursor)
2544 * TERM_YELLOW : Overwrite mode
2545 * TERM_WHITE : Insert mode
2547 byte color = TERM_YELLOW;
2550 Term_locate(&x, &y);
2551 if (len < 1) len = 1;
2552 if ((x < 0) || (x >= 80)) x = 0;
2553 if (x + len > 80) len = 80 - x;
2560 Term_erase(x, y, len);
2561 Term_putstr(x, y, -1, color, buf);
2563 Term_gotoxy(x + pos, y);
2564 int skey = inkey_special(numpad_cursor);
2574 if (0 == pos) break;
2577 int next_pos = i + 1;
2579 if (iskanji(buf[i])) next_pos++;
2581 if (next_pos >= pos) break;
2593 if ('\0' == buf[pos]) break;
2596 if (iskanji(buf[pos])) pos += 2;
2615 if (0 == pos) break;
2618 int next_pos = i + 1;
2620 if (iskanji(buf[i])) next_pos++;
2622 if (next_pos >= pos) break;
2635 if ('\0' == buf[pos]) break;
2638 if (iskanji(buf[pos])) src++;
2642 while ('\0' != (buf[dst++] = buf[src++]));
2649 if (skey & SKEY_MASK) break;
2650 char c = (char)skey;
2652 if (color == TERM_YELLOW)
2658 strcpy(tmp, buf + pos);
2663 char next = inkey();
2678 if (pos < len && (isprint(c) || iskana(c)))
2680 if (pos < len && isprint(c))
2692 my_strcat(buf, tmp, len + 1);
2703 * Get some string input at the cursor location.
2705 * Allow to use numpad keys as cursor keys.
2707 bool askfor(char *buf, int len)
2709 return askfor_aux(buf, len, TRUE);
2714 * Get a string from the user
2716 * The "prompt" should take the form "Prompt: "
2718 * Note that the initial contents of the string is used as
2719 * the default response, so be sure to "clear" it if needed.
2721 * We clear the input, and return FALSE, on "ESCAPE".
2723 bool get_string(concptr prompt, char *buf, int len)
2728 res = askfor(buf, len);
2735 * Verify something with the user
2737 * The "prompt" should take the form "Query? "
2739 * Note that "[y/n]" is appended to the prompt.
2741 bool get_check(concptr prompt)
2743 return get_check_strict(prompt, 0);
2748 * Verify something with the user strictly
2750 * mode & CHECK_OKAY_CANCEL : force user to answer 'O'kay or 'C'ancel
2751 * mode & CHECK_NO_ESCAPE : don't allow ESCAPE key
2752 * mode & CHECK_NO_HISTORY : no message_add
2753 * mode & CHECK_DEFAULT_Y : accept any key as y, except n and Esc.
2755 bool get_check_strict(concptr prompt, BIT_FLAGS mode)
2760 p_ptr->window |= PW_MESSAGE;
2761 handle_stuff(p_ptr);
2766 if (!rogue_like_commands)
2767 mode &= ~CHECK_OKAY_CANCEL;
2769 if (mode & CHECK_OKAY_CANCEL)
2771 my_strcpy(buf, prompt, sizeof(buf) - 15);
2772 strcat(buf, "[(O)k/(C)ancel]");
2774 else if (mode & CHECK_DEFAULT_Y)
2776 my_strcpy(buf, prompt, sizeof(buf) - 5);
2777 strcat(buf, "[Y/n]");
2781 my_strcpy(buf, prompt, sizeof(buf) - 5);
2782 strcat(buf, "[y/n]");
2786 if (!(mode & CHECK_NO_HISTORY) && p_ptr->playing)
2789 p_ptr->window |= (PW_MESSAGE);
2790 handle_stuff(p_ptr);
2798 if (!(mode & CHECK_NO_ESCAPE))
2807 if (mode & CHECK_OKAY_CANCEL)
2809 if (i == 'o' || i == 'O')
2814 else if (i == 'c' || i == 'C')
2822 if (i == 'y' || i == 'Y')
2827 else if (i == 'n' || i == 'N')
2834 if (mode & CHECK_DEFAULT_Y)
2849 * Prompts for a keypress
2851 * The "prompt" should take the form "Command: "
2853 * Returns TRUE unless the character is "Escape"
2855 bool get_com(concptr prompt, char *command, bool z_escape)
2859 if (get_com_no_macros)
2860 *command = (char)inkey_special(FALSE);
2865 if (*command == ESCAPE) return FALSE;
2866 if (z_escape && ((*command == 'z') || (*command == 'Z'))) return FALSE;
2873 * Request a "quantity" from the user
2875 * Hack -- allow "command_arg" to specify a quantity
2877 QUANTITY get_quantity(concptr prompt, QUANTITY max)
2888 if (amt > max) amt = max;
2894 bool result = repeat_pull(&code);
2895 amt = (QUANTITY)code;
2896 if ((max != 1) && result)
2898 if (amt > max) amt = max;
2899 if (amt < 0) amt = 0;
2906 sprintf(tmp, _("いくつですか (1-%d): ", "Quantity (1-%d): "), max);
2913 sprintf(buf, "%d", amt);
2916 * Ask for a quantity
2917 * Don't allow to use numpad as cursor key.
2919 res = askfor_aux(buf, 6, FALSE);
2924 amt = (COMMAND_CODE)atoi(buf);
2925 if (isalpha(buf[0])) amt = max;
2926 if (amt > max) amt = max;
2927 if (amt < 0) amt = 0;
2928 if (amt) repeat_push((COMMAND_CODE)amt);
2935 * Pause for user response
2937 void pause_line(int row)
2940 put_str(_("[ 何かキーを押して下さい ]", "[Press any key to continue]"), row, _(26, 23));
2947 * Hack -- special buffer to hold the action of the current keymap
2949 static char request_command_buffer[256];
2959 menu_naiyou menu_info[10][10] =
2962 {"魔法/特殊能力", 1, FALSE},
2964 {"道具(使用)", 3, FALSE},
2965 {"道具(その他)", 4, FALSE},
2975 {"使う(m)", 'm', TRUE},
2976 {"調べる(b/P)", 'b', TRUE},
2977 {"覚える(G)", 'G', TRUE},
2978 {"特殊能力を使う(U/O)", 'U', TRUE},
2988 {"休息する(R)", 'R', TRUE},
2989 {"トラップ解除(D)", 'D', TRUE},
2990 {"探す(s)", 's', TRUE},
2991 {"周りを調べる(l/x)", 'l', TRUE},
2992 {"ターゲット指定(*)", '*', TRUE},
2993 {"穴を掘る(T/^t)", 'T', TRUE},
2994 {"階段を上る(<)", '<', TRUE},
2995 {"階段を下りる(>)", '>', TRUE},
2996 {"ペットに命令する(p)", 'p', TRUE},
2997 {"探索モードのON/OFF(S/#)", 'S', TRUE}
3001 {"読む(r)", 'r', TRUE},
3002 {"飲む(q)", 'q', TRUE},
3003 {"杖を使う(u/Z)", 'u', TRUE},
3004 {"魔法棒で狙う(a/z)", 'a', TRUE},
3005 {"ロッドを振る(z/a)", 'z', TRUE},
3006 {"始動する(A)", 'A', TRUE},
3007 {"食べる(E)", 'E', TRUE},
3008 {"飛び道具で撃つ(f/t)", 'f', TRUE},
3009 {"投げる(v)", 'v', TRUE},
3014 {"拾う(g)", 'g', TRUE},
3015 {"落とす(d)", 'd', TRUE},
3016 {"壊す(k/^d)", 'k', TRUE},
3017 {"銘を刻む({)", '{', TRUE},
3018 {"銘を消す(})", '}', TRUE},
3019 {"調査(I)", 'I', TRUE},
3020 {"アイテム一覧(i)", 'i', TRUE},
3027 {"装備する(w)", 'w', TRUE},
3028 {"装備を外す(t/T)", 't', TRUE},
3029 {"燃料を補給(F)", 'F', TRUE},
3030 {"装備一覧(e)", 'e', TRUE},
3040 {"開ける(o)", 'o', TRUE},
3041 {"閉じる(c)", 'c', TRUE},
3042 {"体当たりする(B/f)", 'B', TRUE},
3043 {"くさびを打つ(j/S)", 'j', TRUE},
3053 {"ダンジョンの全体図(M)", 'M', TRUE},
3054 {"位置を確認(L/W)", 'L', TRUE},
3055 {"階の雰囲気(^f)", KTRL('F'), TRUE},
3056 {"ステータス(C)", 'C', TRUE},
3057 {"文字の説明(/)", '/', TRUE},
3058 {"メッセージ履歴(^p)", KTRL('P'), TRUE},
3059 {"現在の時刻(^t/')", KTRL('T'), TRUE},
3060 {"現在の知識(~)", '~', TRUE},
3061 {"プレイ記録(|)", '|', TRUE},
3066 {"オプション(=)", '=', TRUE},
3067 {"マクロ(@)", '@', TRUE},
3068 {"画面表示(%)", '%', TRUE},
3069 {"カラー(&)", '&', TRUE},
3070 {"設定変更コマンド(\")", '\"', TRUE},
3071 {"自動拾いをロード($)", '$', TRUE},
3072 {"システム(!)", '!', TRUE},
3079 {"セーブ&中断(^x)", KTRL('X'), TRUE},
3080 {"セーブ(^s)", KTRL('S'), TRUE},
3081 {"ヘルプ(?)", '?', TRUE},
3082 {"再描画(^r)", KTRL('R'), TRUE},
3083 {"メモ(:)", ':', TRUE},
3084 {"記念撮影())", ')', TRUE},
3085 {"記念撮影の表示(()", '(', TRUE},
3086 {"バージョン情報(V)", 'V', TRUE},
3087 {"引退する(Q)", 'Q', TRUE},
3092 menu_naiyou menu_info[10][10] =
3095 {"Magic/Special", 1, FALSE},
3096 {"Action", 2, FALSE},
3097 {"Items(use)", 3, FALSE},
3098 {"Items(other)", 4, FALSE},
3099 {"Equip", 5, FALSE},
3100 {"Door/Box", 6, FALSE},
3101 {"Information", 7, FALSE},
3102 {"Options", 8, FALSE},
3103 {"Other commands", 9, FALSE},
3108 {"Use(m)", 'm', TRUE},
3109 {"See tips(b/P)", 'b', TRUE},
3110 {"Study(G)", 'G', TRUE},
3111 {"Special abilities(U/O)", 'U', TRUE},
3121 {"Rest(R)", 'R', TRUE},
3122 {"Disarm a trap(D)", 'D', TRUE},
3123 {"Search(s)", 's', TRUE},
3124 {"Look(l/x)", 'l', TRUE},
3125 {"Target(*)", '*', TRUE},
3126 {"Dig(T/^t)", 'T', TRUE},
3127 {"Go up stairs(<)", '<', TRUE},
3128 {"Go down stairs(>)", '>', TRUE},
3129 {"Command pets(p)", 'p', TRUE},
3130 {"Search mode ON/OFF(S/#)", 'S', TRUE}
3134 {"Read a scroll(r)", 'r', TRUE},
3135 {"Drink a potion(q)", 'q', TRUE},
3136 {"Use a staff(u/Z)", 'u', TRUE},
3137 {"Aim a wand(a/z)", 'a', TRUE},
3138 {"Zap a rod(z/a)", 'z', TRUE},
3139 {"Activate an equipment(A)", 'A', TRUE},
3140 {"Eat(E)", 'E', TRUE},
3141 {"Fire missile weapon(f/t)", 'f', TRUE},
3142 {"Throw an item(v)", 'v', TRUE},
3147 {"Get items(g)", 'g', TRUE},
3148 {"Drop an item(d)", 'd', TRUE},
3149 {"Destroy an item(k/^d)", 'k', TRUE},
3150 {"Inscribe an item({)", '{', TRUE},
3151 {"Uninscribe an item(})", '}', TRUE},
3152 {"Info about an item(I)", 'I', TRUE},
3153 {"Inventory list(i)", 'i', TRUE},
3160 {"Wear(w)", 'w', TRUE},
3161 {"Take off(t/T)", 't', TRUE},
3162 {"Refuel(F)", 'F', TRUE},
3163 {"Equipment list(e)", 'e', TRUE},
3173 {"Open(o)", 'o', TRUE},
3174 {"Close(c)", 'c', TRUE},
3175 {"Bash a door(B/f)", 'B', TRUE},
3176 {"Jam a door(j/S)", 'j', TRUE},
3186 {"Full map(M)", 'M', TRUE},
3187 {"Map(L/W)", 'L', TRUE},
3188 {"Level feeling(^f)", KTRL('F'), TRUE},
3189 {"Character status(C)", 'C', TRUE},
3190 {"Identify symbol(/)", '/', TRUE},
3191 {"Show prev messages(^p)", KTRL('P'), TRUE},
3192 {"Current time(^t/')", KTRL('T'), TRUE},
3193 {"Various information(~)", '~', TRUE},
3194 {"Play record menu(|)", '|', TRUE},
3199 {"Set options(=)", '=', TRUE},
3200 {"Interact with macros(@)", '@', TRUE},
3201 {"Interact w/ visuals(%)", '%', TRUE},
3202 {"Interact with colors(&)", '&', TRUE},
3203 {"Enter a user pref(\")", '\"', TRUE},
3204 {"Reload auto-pick pref($)", '$', TRUE},
3212 {"Save and quit(^x)", KTRL('X'), TRUE},
3213 {"Save(^s)", KTRL('S'), TRUE},
3214 {"Help(obsoleted)(?)", '?', TRUE},
3215 {"Redraw(^r)", KTRL('R'), TRUE},
3216 {"Take note(:)", ':', TRUE},
3217 {"Dump screen dump(()", ')', TRUE},
3218 {"Load screen dump())", '(', TRUE},
3219 {"Version info(V)", 'V', TRUE},
3220 {"Quit(Q)", 'Q', TRUE},
3233 } special_menu_naiyou;
3235 #define MENU_CLASS 1
3239 special_menu_naiyou special_menu_info[] =
3241 {"超能力/特殊能力", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
3242 {"ものまね/特殊能力", 0, 0, MENU_CLASS, CLASS_IMITATOR},
3243 {"歌/特殊能力", 0, 0, MENU_CLASS, CLASS_BARD},
3244 {"必殺技/特殊能力", 0, 0, MENU_CLASS, CLASS_SAMURAI},
3245 {"練気術/魔法/特殊能力", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
3246 {"技/特殊能力", 0, 0, MENU_CLASS, CLASS_BERSERKER},
3247 {"技術/特殊能力", 0, 0, MENU_CLASS, CLASS_SMITH},
3248 {"鏡魔法/特殊能力", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
3249 {"忍術/特殊能力", 0, 0, MENU_CLASS, CLASS_NINJA},
3250 {"広域マップ(<)", 2, 6, MENU_WILD, FALSE},
3251 {"通常マップ(>)", 2, 7, MENU_WILD, TRUE},
3255 special_menu_naiyou special_menu_info[] =
3257 {"MindCraft/Special", 0, 0, MENU_CLASS, CLASS_MINDCRAFTER},
3258 {"Imitation/Special", 0, 0, MENU_CLASS, CLASS_IMITATOR},
3259 {"Song/Special", 0, 0, MENU_CLASS, CLASS_BARD},
3260 {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SAMURAI},
3261 {"Mind/Magic/Special", 0, 0, MENU_CLASS, CLASS_FORCETRAINER},
3262 {"BrutalPower/Special", 0, 0, MENU_CLASS, CLASS_BERSERKER},
3263 {"Technique/Special", 0, 0, MENU_CLASS, CLASS_SMITH},
3264 {"MirrorMagic/Special", 0, 0, MENU_CLASS, CLASS_MIRROR_MASTER},
3265 {"Ninjutsu/Special", 0, 0, MENU_CLASS, CLASS_NINJA},
3266 {"Enter global map(<)", 2, 6, MENU_WILD, FALSE},
3267 {"Enter local map(>)", 2, 7, MENU_WILD, TRUE},
3272 static char inkey_from_menu(player_type *player_ptr)
3276 int num = 0, max_num, old_num = 0;
3280 if (player_ptr->y - panel_row_min > 10) basey = 2;
3287 floor_type* floor_ptr = player_ptr->current_floor_ptr;
3293 if (!menu) old_num = num;
3294 put_str("+----------------------------------------------------+", basey, basex);
3295 put_str("| |", basey + 1, basex);
3296 put_str("| |", basey + 2, basex);
3297 put_str("| |", basey + 3, basex);
3298 put_str("| |", basey + 4, basex);
3299 put_str("| |", basey + 5, basex);
3300 put_str("+----------------------------------------------------+", basey + 6, basex);
3302 for (i = 0; i < 10; i++)
3305 if (!menu_info[menu][i].cmd) break;
3306 menu_name = menu_info[menu][i].name;
3307 for (hoge = 0; ; hoge++)
3309 if (!special_menu_info[hoge].name[0]) break;
3310 if ((menu != special_menu_info[hoge].window) || (i != special_menu_info[hoge].number)) continue;
3311 switch (special_menu_info[hoge].jouken)
3314 if (player_ptr->pclass == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
3317 if (!floor_ptr->dun_level && !floor_ptr->inside_arena && !floor_ptr->inside_quest)
3319 if ((byte)player_ptr->wild_mode == special_menu_info[hoge].jouken_naiyou) menu_name = special_menu_info[hoge].name;
3327 put_str(menu_name, basey + 1 + i / 2, basex + 4 + (i % 2) * 24);
3331 kisuu = max_num % 2;
3332 put_str(_("》", "> "), basey + 1 + num / 2, basex + 2 + (num % 2) * 24);
3334 move_cursor_relative(player_ptr->y, player_ptr->x);
3336 if ((sub_cmd == ' ') || (sub_cmd == 'x') || (sub_cmd == 'X') || (sub_cmd == '\r') || (sub_cmd == '\n'))
3338 if (menu_info[menu][num].fin)
3340 cmd = menu_info[menu][num].cmd;
3346 menu = menu_info[menu][num].cmd;
3352 else if ((sub_cmd == ESCAPE) || (sub_cmd == 'z') || (sub_cmd == 'Z') || (sub_cmd == '0'))
3369 else if ((sub_cmd == '2') || (sub_cmd == 'j') || (sub_cmd == 'J'))
3374 num = (num + 2) % (max_num - 1);
3376 num = (num + 2) % (max_num + 1);
3378 else num = (num + 2) % max_num;
3380 else if ((sub_cmd == '8') || (sub_cmd == 'k') || (sub_cmd == 'K'))
3385 num = (num + max_num - 3) % (max_num - 1);
3387 num = (num + max_num - 1) % (max_num + 1);
3389 else num = (num + max_num - 2) % max_num;
3391 else if ((sub_cmd == '4') || (sub_cmd == '6') || (sub_cmd == 'h') || (sub_cmd == 'H') || (sub_cmd == 'l') || (sub_cmd == 'L'))
3393 if ((num % 2) || (num == max_num - 1))
3397 else if (num < max_num - 1)
3405 if (!inkey_next) inkey_next = "";
3412 * Request a command from the user.
3414 * Sets player_ptr->command_cmd, player_ptr->command_dir, player_ptr->command_rep,
3415 * player_ptr->command_arg. May modify player_ptr->command_new.
3417 * Note that "caret" ("^") is treated specially, and is used to
3418 * allow manual input of control characters. This can be used
3419 * on many machines to request repeated tunneling (Ctrl-H) and
3420 * on the Macintosh to request "Control-Caret".
3422 * Note that "backslash" is treated specially, and is used to bypass any
3423 * keymap entry for the following character. This is useful for macros.
3425 * Note that this command is used both in the dungeon and in
3426 * stores, and must be careful to work in both situations.
3428 * Note that "player_ptr->command_new" may not work any more.
3430 void request_command(player_type *player_ptr, int shopping)
3440 if (rogue_like_commands)
3442 mode = KEYMAP_MODE_ROGUE;
3446 mode = KEYMAP_MODE_ORIG;
3468 if (!shopping && command_menu && ((cmd == '\r') || (cmd == '\n') || (cmd == 'x') || (cmd == 'X'))
3469 && !keymap_act[mode][(byte)(cmd)])
3470 cmd = inkey_from_menu(player_ptr);
3476 COMMAND_ARG old_arg = command_arg;
3478 prt(_("回数: ", "Count: "), 0, 0);
3482 if ((cmd == 0x7F) || (cmd == KTRL('H')))
3484 command_arg = command_arg / 10;
3485 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
3487 else if (cmd >= '0' && cmd <= '9')
3489 if (command_arg >= 1000)
3496 command_arg = command_arg * 10 + D2I(cmd);
3499 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
3507 if (command_arg == 0)
3510 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
3515 command_arg = old_arg;
3516 prt(format(_("回数: %d", "Count: %d"), command_arg), 0, 0);
3519 if ((cmd == ' ') || (cmd == '\n') || (cmd == '\r'))
3521 if (!get_com(_("コマンド: ", "Command: "), (char *)&cmd, FALSE))
3531 (void)get_com(_("コマンド: ", "Command: "), (char *)&cmd, FALSE);
3532 if (!inkey_next) inkey_next = "";
3537 if (get_com(_("CTRL: ", "Control: "), (char *)&cmd, FALSE)) cmd = KTRL(cmd);
3540 act = keymap_act[mode][(byte)(cmd)];
3541 if (act && !inkey_next)
3543 (void)strnfmt(request_command_buffer, 256, "%s", act);
3544 inkey_next = request_command_buffer;
3550 command_cmd = (byte)cmd;
3554 if (always_repeat && (command_arg <= 0))
3556 if (my_strchr("TBDoc+", (char)command_cmd))
3564 switch (command_cmd)
3566 case 'p': command_cmd = 'g'; break;
3568 case 'm': command_cmd = 'g'; break;
3570 case 's': command_cmd = 'd'; break;
3575 for (int i = 0; i < 256; i++)
3578 if ((s = keymap_act[mode][i]) != NULL)
3580 if (*s == command_cmd && *(s + 1) == 0)
3589 caretcmd = command_cmd;
3592 for (int i = INVEN_RARM; i < INVEN_TOTAL; i++)
3594 object_type *o_ptr = &player_ptr->inventory_list[i];
3595 if (!o_ptr->k_idx) continue;
3597 if (!o_ptr->inscription) continue;
3599 concptr s = quark_str(o_ptr->inscription);
3600 s = my_strchr(s, '^');
3604 if ((s[1] == caretcmd) || (s[1] == '*'))
3606 if ((s[1] == command_cmd) || (s[1] == '*'))
3609 if (!get_check(_("本当ですか? ", "Are you sure? ")))
3615 s = my_strchr(s + 1, '^');
3624 * Check a char for "vowel-hood"
3626 bool is_a_vowel(int ch)
3649 * Called from cmd4.c and a few other places. Just extracts
3650 * a direction from the keymap for ch (the last direction,
3651 * in fact) byte or char here? I'm thinking that keymaps should
3652 * generally only apply to single keys, which makes it no more
3653 * than 128, so a char should suffice... but keymap_act is 256...
3655 int get_keymap_dir(char ch)
3666 if (rogue_like_commands)
3668 mode = KEYMAP_MODE_ROGUE;
3672 mode = KEYMAP_MODE_ORIG;
3675 concptr act = keymap_act[mode][(byte)(ch)];
3678 for (concptr s = act; *s; ++s)
3680 if (isdigit(*s)) d = D2I(*s);
3691 #define REPEAT_MAX 20
3693 /* Number of chars saved */
3694 static int repeat__cnt = 0;
3697 static int repeat__idx = 0;
3700 static COMMAND_CODE repeat__key[REPEAT_MAX];
3702 void repeat_push(COMMAND_CODE what)
3704 if (repeat__cnt == REPEAT_MAX) return;
3706 repeat__key[repeat__cnt++] = what;
3711 bool repeat_pull(COMMAND_CODE *what)
3713 if (repeat__idx == repeat__cnt) return FALSE;
3715 *what = repeat__key[repeat__idx++];
3719 void repeat_check(void)
3721 if (command_cmd == ESCAPE) return;
3722 if (command_cmd == ' ') return;
3723 if (command_cmd == '\r') return;
3724 if (command_cmd == '\n') return;
3727 if (command_cmd == 'n')
3730 if (repeat_pull(&what))
3746 * Array size for which InsertionSort
3747 * is used instead of QuickSort
3753 * Exchange two sort-entries
3754 * (should probably be coded inline
3755 * for speed increase)
3757 static void swap(tag_type *a, tag_type *b)
3768 * Insertion-Sort algorithm
3769 * (used by the Quicksort algorithm)
3771 static void InsertionSort(tag_type elements[], int number)
3774 for (int i = 1; i < number; i++)
3778 for (j = i; (j > 0) && (elements[j - 1].tag > tmp.tag); j--)
3779 elements[j] = elements[j - 1];
3786 * Helper function for Quicksort
3788 static tag_type median3(tag_type elements[], int left, int right)
3790 int center = (left + right) / 2;
3792 if (elements[left].tag > elements[center].tag)
3793 swap(&elements[left], &elements[center]);
3794 if (elements[left].tag > elements[right].tag)
3795 swap(&elements[left], &elements[right]);
3796 if (elements[center].tag > elements[right].tag)
3797 swap(&elements[center], &elements[right]);
3799 swap(&elements[center], &elements[right - 1]);
3800 return (elements[right - 1]);
3805 * Quicksort algorithm
3807 * The "median of three" pivot selection eliminates
3808 * the bad case of already sorted input.
3810 * We use InsertionSort for smaller sub-arrays,
3811 * because it is faster in this case.
3813 * For details see: "Data Structures and Algorithm
3814 * Analysis in C" by Mark Allen Weiss.
3816 static void quicksort(tag_type elements[], int left, int right)
3819 if (left + CUTOFF <= right)
3821 pivot = median3(elements, left, right);
3828 while (elements[++i].tag < pivot.tag);
3829 while (elements[--j].tag > pivot.tag);
3832 swap(&elements[i], &elements[j]);
3837 swap(&elements[i], &elements[right - 1]);
3839 quicksort(elements, left, i - 1);
3840 quicksort(elements, i + 1, right);
3844 InsertionSort(elements + left, right - left + 1);
3850 * Frontend for the sorting algorithm
3852 * Sorts an array of tagged pointers
3853 * with <number> elements.
3855 void tag_sort(tag_type elements[], int number)
3857 quicksort(elements, 0, number - 1);
3860 /* Table of gamma values */
3861 byte gamma_table[256];
3863 /* Table of ln(x/256) * 256 for x going from 0 -> 255 */
3864 static s16b gamma_helper[256] =
3866 0,-1420,-1242,-1138,-1065,-1007,-961,-921,-887,-857,-830,-806,-783,-762,-744,-726,
3867 -710,-694,-679,-666,-652,-640,-628,-617,-606,-596,-586,-576,-567,-577,-549,-541,
3868 -532,-525,-517,-509,-502,-495,-488,-482,-475,-469,-463,-457,-451,-455,-439,-434,
3869 -429,-423,-418,-413,-408,-403,-398,-394,-389,-385,-380,-376,-371,-367,-363,-359,
3870 -355,-351,-347,-343,-339,-336,-332,-328,-325,-321,-318,-314,-311,-308,-304,-301,
3871 -298,-295,-291,-288,-285,-282,-279,-276,-273,-271,-268,-265,-262,-259,-257,-254,
3872 -251,-248,-246,-243,-241,-238,-236,-233,-231,-228,-226,-223,-221,-219,-216,-214,
3873 -212,-209,-207,-205,-203,-200,-198,-196,-194,-192,-190,-188,-186,-184,-182,-180,
3874 -178,-176,-174,-172,-170,-168,-166,-164,-162,-160,-158,-156,-155,-153,-151,-149,
3875 -147,-146,-144,-142,-140,-139,-137,-135,-134,-132,-130,-128,-127,-125,-124,-122,
3876 -120,-119,-117,-116,-114,-112,-111,-109,-108,-106,-105,-103,-102,-100,-99,-97,
3877 -96,-95,-93,-92,-90,-89,-87,-86,-85,-83,-82,-80,-79,-78,-76,-75,
3878 -74,-72,-71,-70,-68,-67,-66,-65,-63,-62,-61,-59,-58,-57,-56,-54,
3879 -53,-52,-51,-50,-48,-47,-46,-45,-44,-42,-41,-40,-39,-38,-37,-35,
3880 -34,-33,-32,-31,-30,-29,-27,-26,-25,-24,-23,-22,-21,-20,-19,-18,
3881 -17,-16,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1
3886 * Build the gamma table so that floating point isn't needed.
3888 * Note gamma goes from 0->256. The old value of 100 is now 128.
3890 void build_gamma_table(int gamma)
3893 gamma_table[255] = 255;
3894 for (int i = 1; i < 255; i++)
3897 * Initialise the Taylor series
3899 * value and diff have been scaled by 256
3902 long value = 256 * 256;
3903 long diff = ((long)gamma_helper[i]) * (gamma - 256);
3912 * Use the following identiy to calculate the gamma table.
3913 * exp(x) = 1 + x + x^2/2 + x^3/(2*3) + x^4/(2*3*4) +...
3915 * n is the current term number.
3917 * The gamma_helper array contains a table of
3919 * This is used because a^b = exp(b*ln(a))
3925 * Note that everything is scaled by 256 for accuracy,
3926 * plus another factor of 256 for the final result to
3927 * be from 0-255. Thus gamma_helper[] * gamma must be
3928 * divided by 256*256 each itteration, to get back to
3929 * the original power series.
3931 diff = (((diff / 256) * gamma_helper[i]) * (gamma - 256)) / (256 * n);
3935 * Store the value in the table so that the
3936 * floating point pow function isn't needed .
3938 gamma_table[i] = ((long)(value / 256) * i) / 256;
3944 * Add a series of keypresses to the "queue".
3946 * Return any errors generated by Term_keypress() in doing so, or SUCCESS
3947 * if there are none.
3949 * Catch the "out of space" error before anything is printed.
3951 * NB: The keys added here will be interpreted by any macros or keymaps.
3953 errr type_string(concptr str, uint len)
3957 if (!str) return -1;
3958 if (!len) len = strlen(str);
3960 Term_activate(term_screen);
3961 for (concptr s = str; s < str + len; s++)
3963 if (*s == '\0') break;
3965 err = Term_keypress(*s);
3974 void roff_to_buf(concptr str, int maxlen, char *tbuf, size_t bufsize)
3983 while (str[read_pt])
3986 bool kinsoku = FALSE;
3990 ch[0] = str[read_pt];
3993 kanji = iskanji(ch[0]);
3997 ch[1] = str[read_pt + 1];
4000 if (strcmp(ch, "。") == 0 ||
4001 strcmp(ch, "、") == 0 ||
4002 strcmp(ch, "ィ") == 0 ||
4003 strcmp(ch, "ー") == 0)
4006 else if (!isprint(ch[0]))
4009 if (!isprint(ch[0]))
4013 if (line_len + ch_len > maxlen - 1 || str[read_pt] == '\n')
4015 int word_len = read_pt - word_punct;
4017 if (kanji && !kinsoku)
4021 if (ch[0] == ' ' || word_len >= line_len / 2)
4025 read_pt = word_punct;
4026 if (str[word_punct] == ' ')
4028 write_pt -= word_len;
4031 tbuf[write_pt++] = '\0';
4033 word_punct = read_pt;
4038 word_punct = read_pt;
4041 if (!kinsoku) word_punct = read_pt;
4044 if ((size_t)(write_pt + 3) >= bufsize) break;
4046 tbuf[write_pt++] = ch[0];
4052 tbuf[write_pt++] = ch[1];
4059 tbuf[write_pt] = '\0';
4060 tbuf[write_pt + 1] = '\0';
4066 * The my_strcpy() function copies up to 'bufsize'-1 characters from 'src'
4067 * to 'buf' and NUL-terminates the result. The 'buf' and 'src' strings may
4070 * my_strcpy() returns strlen(src). This makes checking for truncation
4071 * easy. Example: if (my_strcpy(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
4073 * This function should be equivalent to the strlcpy() function in BSD.
4075 size_t my_strcpy(char *buf, concptr src, size_t bufsize)
4083 /* reserve for NUL termination */
4086 /* Copy as many bytes as will fit */
4087 while (*s && (len < bufsize))
4091 if (len + 1 >= bufsize || !*(s + 1)) break;
4109 size_t len = strlen(src);
4111 if (bufsize == 0) return ret;
4113 if (len >= bufsize) len = bufsize - 1;
4115 (void)memcpy(buf, src, len);
4123 * The my_strcat() tries to append a string to an existing NUL-terminated string.
4124 * It never writes more characters into the buffer than indicated by 'bufsize' and
4125 * NUL-terminates the buffer. The 'buf' and 'src' strings may not overlap.
4127 * my_strcat() returns strlen(buf) + strlen(src). This makes checking for
4128 * truncation easy. Example:
4129 * if (my_strcat(buf, src, sizeof(buf)) >= sizeof(buf)) ...;
4131 * This function should be equivalent to the strlcat() function in BSD.
4133 size_t my_strcat(char *buf, concptr src, size_t bufsize)
4135 size_t dlen = strlen(buf);
4136 if (dlen < bufsize - 1)
4138 return (dlen + my_strcpy(buf + dlen, src, bufsize - dlen));
4142 return (dlen + strlen(src));
4148 * A copy of ANSI strstr()
4150 * my_strstr() can handle Kanji strings correctly.
4152 char *my_strstr(concptr haystack, concptr needle)
4154 int l1 = strlen(haystack);
4155 int l2 = strlen(needle);
4159 for (int i = 0; i <= l1 - l2; i++)
4161 if (!strncmp(haystack + i, needle, l2))
4162 return (char *)haystack + i;
4165 if (iskanji(*(haystack + i))) i++;
4175 * A copy of ANSI strchr()
4177 * my_strchr() can handle Kanji strings correctly.
4179 char *my_strchr(concptr ptr, char ch)
4181 for (; *ptr != '\0'; ptr++)
4183 if (*ptr == ch) return (char *)ptr;
4186 if (iskanji(*ptr)) ptr++;
4195 * Convert string to lower case
4197 void str_tolower(char *str)
4208 *str = (char)tolower(*str);
4214 * Get a keypress from the user.
4215 * And interpret special keys as internal code.
4217 * This function is a Mega-Hack and depend on pref-xxx.prf's.
4218 * Currently works on Linux(UNIX), Windows, and Macintosh only.
4220 int inkey_special(bool numpad_cursor)
4222 static const struct {
4225 } modifier_key_list[] = {
4226 {"shift-", SKEY_MOD_SHIFT},
4227 {"control-", SKEY_MOD_CONTROL},
4231 static const struct {
4235 } special_key_list[] = {
4236 {FALSE, "Down]", SKEY_DOWN},
4237 {FALSE, "Left]", SKEY_LEFT},
4238 {FALSE, "Right]", SKEY_RIGHT},
4239 {FALSE, "Up]", SKEY_UP},
4240 {FALSE, "Page_Up]", SKEY_PGUP},
4241 {FALSE, "Page_Down]", SKEY_PGDOWN},
4242 {FALSE, "Home]", SKEY_TOP},
4243 {FALSE, "End]", SKEY_BOTTOM},
4244 {TRUE, "KP_Down]", SKEY_DOWN},
4245 {TRUE, "KP_Left]", SKEY_LEFT},
4246 {TRUE, "KP_Right]", SKEY_RIGHT},
4247 {TRUE, "KP_Up]", SKEY_UP},
4248 {TRUE, "KP_Page_Up]", SKEY_PGUP},
4249 {TRUE, "KP_Page_Down]", SKEY_PGDOWN},
4250 {TRUE, "KP_Home]", SKEY_TOP},
4251 {TRUE, "KP_End]", SKEY_BOTTOM},
4252 {TRUE, "KP_2]", SKEY_DOWN},
4253 {TRUE, "KP_4]", SKEY_LEFT},
4254 {TRUE, "KP_6]", SKEY_RIGHT},
4255 {TRUE, "KP_8]", SKEY_UP},
4256 {TRUE, "KP_9]", SKEY_PGUP},
4257 {TRUE, "KP_3]", SKEY_PGDOWN},
4258 {TRUE, "KP_7]", SKEY_TOP},
4259 {TRUE, "KP_1]", SKEY_BOTTOM},
4263 static const struct {
4266 } gcu_special_key_list[] = {
4272 {"4~", SKEY_BOTTOM},
4274 {"6~", SKEY_PGDOWN},
4287 * Forget macro trigger ----
4288 * It's important if we are already expanding macro action
4290 inkey_macro_trigger_string[0] = '\0';
4293 trig_len = strlen(inkey_macro_trigger_string);
4294 if (!trig_len) return (int)((unsigned char)key);
4295 if (trig_len == 1 && parse_macro)
4297 char c = inkey_macro_trigger_string[0];
4298 forget_macro_action();
4299 return (int)((unsigned char)c);
4302 ascii_to_text(buf, inkey_macro_trigger_string);
4303 if (prefix(str, "\\["))
4308 for (i = 0; modifier_key_list[i].keyname; i++)
4310 if (prefix(str, modifier_key_list[i].keyname))
4312 str += strlen(modifier_key_list[i].keyname);
4313 modifier |= modifier_key_list[i].keyflag;
4317 if (!modifier_key_list[i].keyname) break;
4320 if (!numpad_as_cursorkey) numpad_cursor = FALSE;
4322 for (i = 0; special_key_list[i].keyname; i++)
4324 if ((!special_key_list[i].numpad || numpad_cursor) &&
4325 streq(str, special_key_list[i].keyname))
4327 skey = special_key_list[i].keycode;
4334 forget_macro_action();
4335 return (skey | modifier);
4339 if (prefix(str, "\\e["))
4343 for (i = 0; gcu_special_key_list[i].keyname; i++)
4345 if (streq(str, gcu_special_key_list[i].keyname))
4347 return gcu_special_key_list[i].keycode;
4352 inkey_macro_trigger_string[0] = '\0';
4353 return (int)((unsigned char)key);