OSDN Git Service

Merge pull request #934 from sikabane-works/feature/add-doxygen-artifact
[hengbandforosx/hengbandosx.git] / src / main-gcu.cpp
1 /* File: main-gcu.c */
2
3 /*
4  * Copyright (c) 1997 Ben Harrison, and others
5  *
6  * This software may be copied and distributed for educational, research,
7  * and not for profit purposes provided that this copyright and statement
8  * are included in all such copies.
9  */
10
11 /* Purpose: Allow use of Unix "curses" with Angband -BEN- */
12
13 /*
14  * This file has been modified to use multiple text windows if your screen
15  * is larger than 80x25.  By Keldon Jones (keldon@umr.edu).
16  *
17  * Also included is Keldon Jones patch to get better colors. To switch to
18  * a term that supports this, see this posting:
19  *
20  * From keldon@umr.edu Thu Apr 01 05:40:14 1999
21  * Sender: KELDON JONES <keldon@saucer.cc.umr.edu>
22  * From: Keldon Jones <keldon@umr.edu>
23  * Subject: Re: Linux colour prob (Or: question for Greg)
24  * Newsgroups: rec.games.roguelike.angband
25  * References: <slrn7g1jlp.gj9.scarblac-spamtrap@flits104-37.flits.rug.nl> <3700f96b.1593384@news.polsl.gliwice.pl> <slrn7g36er.fm4.wooledge@jekyll.local>
26  * X-Newsreader: TIN [UNIX 1.3 unoff BETA 970625; 9000/780 HP-UX B.10.20]
27  * NNTP-Posting-Host: saucer.cc.umr.edu
28  * X-NNTP-Posting-Host: saucer.cc.umr.edu
29  * Message-ID: <370306be.0@news.cc.umr.edu>
30  * Date: 1 Apr 99 05:40:14 GMT
31  * Organization: University of Missouri - Rolla
32  * Lines: 199
33  * Path:
34  * xs4all!xs4all!newsfeed.wirehub.nl!news-peer.gip.net!news.gsl.net!gip.net!news.he.net!mercury.cts.com!alpha.sky.net!news.missouri.edu!news.cc.umr.edu!not-for-mail
35  * Xref: xs4all rec.games.roguelike.angband:86332
36  *
37  * Greg Wooledge <wooledge@kellnet.com> wrote:
38  * > Gwidon S. Naskrent (naskrent@artemida.amu.edu.pl) wrote:
39  *
40  * > >On 30 Mar 1999 13:17:18 GMT, scarblac-spamtrap@pino.selwerd.cx (Remco
41  * > >Gerlich) wrote:
42  *
43  * > >>I recently switched to Linux, and *bands work fine. I like
44  * > >>to play them in consoles, not in X. However, colour is wrong.
45  * > >>"Slate" and "light slate" are always light blue, instead
46  * > >>of some shade of grey. Colours are fine in X.
47  *
48  * > I actually noticed the Linux console color issue a very long time ago,
49  * > but since I always play under X, I never really investigated it.
50  *
51  * > You're absolutely right, though -- the Linux console colors are not
52  * > "right" for Angband.
53  *
54  *    I've noticed this myself, so I spent the evening fixing it.
55  * Well, sorta fixing it.  It's not perfect yet, and it may not be
56  * possible to get it perfect with VGA hardware and/or the current
57  * Linux kernel.
58  *
59  * > OK, reading on in terminfo(5):
60  *
61  * >    Color Handling
62  * >        Most color terminals are either `Tektronix-like'  or  `HP-
63  * >        like'.   Tektronix-like terminals have a predefined set of
64  * >        N colors (where N usually 8), and can  set  character-cell
65  * >        foreground and background characters independently, mixing
66  * >        them into N * N color-pairs.  On  HP-like  terminals,  the
67  * >        use must set each color pair up separately (foreground and
68  * >        background are  not  independently  settable).   Up  to  M
69  * >        color-pairs  may  be  set  up  from  2*M different colors.
70  * >        ANSI-compatible terminals are Tektronix-like.
71  *
72  * > The "linux" terminfo entry is definitely in the "Tektronix-like" family.
73  * > It has the "setaf" and "setab" capabilities for setting the foreground
74  * > and background colors to one of 8 basically hard-coded values:
75  *
76  * >              Color       #define       Value       RGB
77  * >              black     COLOR_BLACK       0     0, 0, 0
78  * >              red       COLOR_RED         1     max,0,0
79  * >              green     COLOR_GREEN       2     0,max,0
80  * >              yellow    COLOR_YELLOW      3     max,max,0
81  * >              blue      COLOR_BLUE        4     0,0,max
82  * >              magenta   COLOR_MAGENTA     5     max,0,max
83  * >              cyan      COLOR_CYAN        6     0,max,max
84  * >              white     COLOR_WHITE       7     max,max,max
85  *
86  *    Well, not quite.  Using certain escape sequences, an
87  * application (or better yet, curses) can redefine the colors (at
88  * least some of them) and then those are used.  Read the
89  * curs_color manpage, and the part about "ccc" and "initc" in the
90  * terminfo manpage.  This is what the part of main-gcu inside the
91  * "if (can_fix_color)" code does.
92  *
93  * > So, what does this mean to the Angband player?  Well, it means that
94  * > either there's nothing you can do about the console colors as long as
95  * > straight curses/ncurses is used, or if there is something to be done,
96  * > I'm not clever enough to figure out how to do it.
97  *
98  *    Well, it is possible, though you have to patch main-gcu
99  * and edit a terminfo entry.  Apparently the relevant code in
100  * main-gcu was never tested (it's broken in at least one major
101  * way).  Apply the patch at the end of this message (notice that
102  * we need to define REDEFINE_COLORS at some point near the
103  * beginning of the file).
104  *    Next, write this termcap entry to a file:
105  *
106  * linux-c|linux console 1.3.6+ with private palette for each virtual console,
107  *         ccc,
108  *         colors#16, pairs#64,
109  *         initc=\E]P%x%p1%{16}%/%02x%p1%{16}%/%02x%p1%{16}%/%02x,
110  *         oc=\E]R,
111  *         use=linux,
112  *
113  * and run "tic" on it to produce a new terminfo entry called
114  * "linux-c".  Especially note the "ccc" flag which says that we
115  * can redefine colors.  The ugly "initc" string is what tells
116  * the console how to redefine a color.  Now, just set your TERM
117  * variable to "linux-c" and try Angband again.  If I've
118  * remembered to tell you everything that I've done, you should
119  * get the weird light-blue slate changed to a gray.
120  *    Now, there are still lots of problems with this.
121  * Something (I don't think it's curses, either the kernel or
122  * the hardware itself) seems to be ignoring my color changes to
123  * colors 6 and 7, which is annoying.  Also, the normal "white"
124  * color is now way too bright, but it's now necessary to
125  * distinguish it from the other grays.
126  *    The kernel seems to support 16 colors, but you can
127  * only switch to 8 of those, due to VT102 compatibility, it
128  * seems.  I think it would be possible to patch the kernel and
129  * allow all 16 colors to be used, but I haven't built up the
130  * nerve to try that yet.
131  *    Let me know if you can improve on this any.  Some of
132  * this may actually work differently on other hardware (ugh).
133  *
134  *    Keldon
135  *
136  */
137
138 /*
139  * To use this file, you must define "USE_GCU" in the Makefile.
140  *
141  * Hack -- note that "angband.h" is included AFTER the #ifdef test.
142  * This was necessary because of annoying "curses.h" silliness.
143  *
144  * Note that this file is not "intended" to support non-Unix machines,
145  * nor is it intended to support VMS or other bizarre setups.
146  *
147  * Also, this package assumes that the underlying "curses" handles both
148  * the "nonl()" and "cbreak()" commands correctly, see the "OPTION" below.
149  *
150  * This code should work with most versions of "curses" or "ncurses",
151  * and the "main-ncu.c" file (and USE_NCU define) are no longer used.
152  *
153  * See also "USE_CAP" and "main-cap.c" for code that bypasses "curses"
154  * and uses the "termcap" information directly, or even bypasses the
155  * "termcap" information and sends direct vt100 escape sequences.
156  *
157  * XXX XXX XXX Consider the use of "savetty()" and "resetty()".
158  */
159
160 #include "game-option/runtime-arguments.h"
161 #include "game-option/special-options.h"
162 #include "io/exit-panic.h"
163 #include "io/files-util.h"
164 #include "locale/japanese.h"
165 #include "main/sound-definitions-table.h"
166 #include "main/sound-of-music.h"
167 #include "system/angband.h"
168 #include "system/player-type-definition.h"
169 #include "term/gameterm.h"
170 #include "term/term-color-types.h"
171 #include "util/angband-files.h"
172 #include "view/display-map.h"
173
174 #ifdef USE_GCU
175
176 /*
177  * Hack -- play games with "bool"
178  */
179 #if __STDC_VERSION__ < 199901L
180 #undef bool
181 #endif
182
183 /*
184  * Include the proper "header" file
185  */
186 #include <curses.h>
187
188 typedef struct term_data term_data;
189
190 struct term_data {
191     term_type t;
192
193     WINDOW *win;
194 };
195
196 #define MAX_TERM_DATA 4
197
198 static term_data data[MAX_TERM_DATA];
199
200 /*
201  * Hack -- try to guess which systems use what commands
202  * Hack -- allow one of the "USE_Txxxxx" flags to be pre-set.
203  * Mega-Hack -- try to guess when "POSIX" is available.
204  * If the user defines two of these, we will probably crash.
205  */
206 #if !defined(USE_TCHARS)
207 #if defined(_POSIX_VERSION)
208 #define USE_TPOSIX
209 #else
210 #if defined(linux)
211 #define USE_TERMIO
212 #else
213 #define USE_TCHARS
214 #endif
215 #endif
216 #endif
217
218 /*
219  * Try redefining the colors at startup.
220  */
221 #define REDEFINE_COLORS
222
223 /*
224  * POSIX stuff
225  */
226 #ifdef USE_TPOSIX
227 #include <sys/ioctl.h>
228 #include <termios.h>
229 #endif
230
231 /*
232  * One version needs this file
233  */
234 #ifdef USE_TERMIO
235 #include <sys/ioctl.h>
236 #include <termio.h>
237 #endif
238
239 /*
240  * The other needs this file
241  */
242 #ifdef USE_TCHARS
243 #include <sys/file.h>
244 #include <sys/ioctl.h>
245 #include <sys/param.h>
246 #include <sys/resource.h>
247 #include <sys/types.h>
248 #endif
249
250 #include <locale.h>
251
252 /*
253  * XXX XXX Hack -- POSIX uses "O_NONBLOCK" instead of "O_NDELAY"
254  *
255  * They should both work due to the "(i != 1)" test below.
256  */
257 #ifndef O_NDELAY
258 #define O_NDELAY O_NONBLOCK
259 #endif
260
261 /*
262  * OPTION: some machines lack "cbreak()"
263  * On these machines, we use an older definition
264  */
265 /* #define cbreak() crmode() */
266
267 /*
268  * OPTION: some machines cannot handle "nonl()" and "nl()"
269  * On these machines, we can simply ignore those commands.
270  */
271 /* #define nonl() */
272 /* #define nl() */
273
274 static concptr ANGBAND_DIR_XTRA_SOUND;
275
276 /*
277  * todo 有効活用されていない疑惑
278  * Flag set once "sound" has been initialized
279  */
280 static bool can_use_sound = FALSE;
281
282 /*
283  * An array of sound file names
284  */
285 static concptr sound_file[SOUND_MAX];
286
287 /*
288  * Save the "normal" and "angband" terminal settings
289  */
290
291 #ifdef USE_TPOSIX
292
293 static struct termios norm_termios;
294
295 static struct termios game_termios;
296
297 #endif
298
299 #ifdef USE_TERMIO
300
301 static struct termio norm_termio;
302
303 static struct termio game_termio;
304
305 #endif
306
307 #ifdef USE_TCHARS
308 static struct ltchars norm_speciax_chars;
309 static struct sgttyb norm_ttyb;
310 static struct tchars norm_tchars;
311 static int norm_locax_chars;
312
313 static struct ltchars game_speciax_chars;
314 static struct sgttyb game_ttyb;
315 static struct tchars game_tchars;
316 static int game_locax_chars;
317 #endif
318
319 /*
320  * Hack -- Number of initialized "term" structures
321  */
322 static int active = 0;
323
324 #ifdef A_COLOR
325 /*
326  * Hack -- define "A_BRIGHT" to be "A_BOLD", because on many
327  * machines, "A_BRIGHT" produces ugly "inverse" video.
328  */
329 #ifndef A_BRIGHT
330 #define A_BRIGHT A_BOLD
331 #endif
332
333 /*
334  * Software flag -- we are allowed to use color
335  */
336 static int can_use_color = FALSE;
337
338 /*
339  * Software flag -- we are allowed to change the colors
340  */
341 static int can_fix_color = FALSE;
342
343 /*
344  * Simple Angband to Curses color conversion table
345  */
346 static int colortable[16];
347 #endif
348
349 /*
350  * Place the "keymap" into its "normal" state
351  */
352 static void keymap_norm(void)
353 {
354 #ifdef USE_TPOSIX
355     /* restore the saved values of the special chars */
356     (void)tcsetattr(0, TCSAFLUSH, &norm_termios);
357 #endif
358
359 #ifdef USE_TERMIO
360     /* restore the saved values of the special chars */
361     (void)ioctl(0, TCSETA, (char *)&norm_termio);
362 #endif
363
364 #ifdef USE_TCHARS
365     /* restore the saved values of the special chars */
366     (void)ioctl(0, TIOCSLTC, (char *)&norm_speciax_chars);
367     (void)ioctl(0, TIOCSETP, (char *)&norm_ttyb);
368     (void)ioctl(0, TIOCSETC, (char *)&norm_tchars);
369     (void)ioctl(0, TIOCLSET, (char *)&norm_locax_chars);
370 #endif
371 }
372
373 /*
374  * Place the "keymap" into the "game" state
375  */
376 static void keymap_game(void)
377 {
378 #ifdef USE_TPOSIX
379     /* restore the saved values of the special chars */
380     (void)tcsetattr(0, TCSAFLUSH, &game_termios);
381 #endif
382
383 #ifdef USE_TERMIO
384     /* restore the saved values of the special chars */
385     (void)ioctl(0, TCSETA, (char *)&game_termio);
386 #endif
387
388 #ifdef USE_TCHARS
389     /* restore the saved values of the special chars */
390     (void)ioctl(0, TIOCSLTC, (char *)&game_speciax_chars);
391     (void)ioctl(0, TIOCSETP, (char *)&game_ttyb);
392     (void)ioctl(0, TIOCSETC, (char *)&game_tchars);
393     (void)ioctl(0, TIOCLSET, (char *)&game_locax_chars);
394 #endif
395 }
396
397 /*
398  * Save the normal keymap
399  */
400 static void keymap_norm_prepare(void)
401 {
402 #ifdef USE_TPOSIX
403     /* Get the normal keymap */
404     tcgetattr(0, &norm_termios);
405 #endif
406
407 #ifdef USE_TERMIO
408     /* Get the normal keymap */
409     (void)ioctl(0, TCGETA, (char *)&norm_termio);
410 #endif
411
412 #ifdef USE_TCHARS
413     /* Get the normal keymap */
414     (void)ioctl(0, TIOCGETP, (char *)&norm_ttyb);
415     (void)ioctl(0, TIOCGLTC, (char *)&norm_speciax_chars);
416     (void)ioctl(0, TIOCGETC, (char *)&norm_tchars);
417     (void)ioctl(0, TIOCLGET, (char *)&norm_locax_chars);
418 #endif
419 }
420
421 /*
422  * Save the keymaps (normal and game)
423  */
424 static void keymap_game_prepare(void)
425 {
426 #ifdef USE_TPOSIX
427     /* Acquire the current mapping */
428     tcgetattr(0, &game_termios);
429
430     /* Force "Ctrl-C" to interupt */
431     game_termios.c_cc[VINTR] = (char)3;
432
433     /* Force "Ctrl-Z" to suspend */
434     game_termios.c_cc[VSUSP] = (char)26;
435
436     /* Hack -- Leave "VSTART/VSTOP" alone */
437
438     /* Disable the standard control characters */
439     game_termios.c_cc[VQUIT] = (char)-1;
440     game_termios.c_cc[VERASE] = (char)-1;
441     game_termios.c_cc[VKILL] = (char)-1;
442     game_termios.c_cc[VEOF] = (char)-1;
443     game_termios.c_cc[VEOL] = (char)-1;
444
445     /* Normally, block until a character is read */
446     game_termios.c_cc[VMIN] = 1;
447     game_termios.c_cc[VTIME] = 0;
448 #endif
449
450 #ifdef USE_TERMIO
451     /* Acquire the current mapping */
452     (void)ioctl(0, TCGETA, (char *)&game_termio);
453
454     /* Force "Ctrl-C" to interupt */
455     game_termio.c_cc[VINTR] = (char)3;
456
457     /* Force "Ctrl-Z" to suspend */
458     game_termio.c_cc[VSUSP] = (char)26;
459
460     /* Disable the standard control characters */
461     game_termio.c_cc[VQUIT] = (char)-1;
462     game_termio.c_cc[VERASE] = (char)-1;
463     game_termio.c_cc[VKILL] = (char)-1;
464     game_termio.c_cc[VEOF] = (char)-1;
465     game_termio.c_cc[VEOL] = (char)-1;
466
467     /* Normally, block until a character is read */
468     game_termio.c_cc[VMIN] = 1;
469     game_termio.c_cc[VTIME] = 0;
470 #endif
471
472 #ifdef USE_TCHARS
473     /* Get the default game characters */
474     (void)ioctl(0, TIOCGETP, (char *)&game_ttyb);
475     (void)ioctl(0, TIOCGLTC, (char *)&game_speciax_chars);
476     (void)ioctl(0, TIOCGETC, (char *)&game_tchars);
477     (void)ioctl(0, TIOCLGET, (char *)&game_locax_chars);
478
479     /* Force suspend (^Z) */
480     game_speciax_chars.t_suspc = (char)26;
481
482     /* Cancel some things */
483     game_speciax_chars.t_dsuspc = (char)-1;
484     game_speciax_chars.t_rprntc = (char)-1;
485     game_speciax_chars.t_flushc = (char)-1;
486     game_speciax_chars.t_werasc = (char)-1;
487     game_speciax_chars.t_lnextc = (char)-1;
488
489     /* Force interupt (^C) */
490     game_tchars.t_intrc = (char)3;
491
492     /* Force start/stop (^Q, ^S) */
493     game_tchars.t_startc = (char)17;
494     game_tchars.t_stopc = (char)19;
495
496     /* Cancel some things */
497     game_tchars.t_quitc = (char)-1;
498     game_tchars.t_eofc = (char)-1;
499     game_tchars.t_brkc = (char)-1;
500 #endif
501 }
502
503 /*
504  * Suspend/Resume
505  */
506 static errr Term_xtra_gcu_alive(int v)
507 {
508     if (!v) {
509         /* Go to normal keymap mode */
510         keymap_norm();
511
512         /* Restore modes */
513         nocbreak();
514         echo();
515         nl();
516
517         /* Hack -- make sure the cursor is visible */
518         term_xtra(TERM_XTRA_SHAPE, 1);
519
520         /* Flush the curses buffer */
521         (void)refresh();
522
523         /* this moves curses to bottom right corner */
524         mvcur(getcury(curscr), getcurx(curscr), LINES - 1, 0);
525
526         /* Exit curses */
527         endwin();
528
529         /* Flush the output */
530         (void)fflush(stdout);
531     } else {
532         /* Restore the settings */
533         cbreak();
534         noecho();
535         nonl();
536
537         /* Go to angband keymap mode */
538         keymap_game();
539     }
540
541     return (0);
542 }
543
544 /*
545  * Check for existance of a file
546  */
547 static bool check_file(concptr s)
548 {
549     FILE *fff;
550     fff = fopen(s, "r");
551     if (!fff)
552         return (FALSE);
553
554     fclose(fff);
555     return (TRUE);
556 }
557
558 /*
559  * Initialize sound
560  */
561 static bool init_sound(void)
562 {
563     /* Initialize once */
564     if (can_use_sound)
565         return can_use_sound;
566
567     int i;
568     char wav[128];
569     char buf[1024];
570
571     /* Prepare the sounds */
572     for (i = 1; i < SOUND_MAX; i++) {
573         /* Extract name of sound file */
574         sprintf(wav, "%s.wav", angband_sound_name[i]);
575
576         /* Access the sound */
577         path_build(buf, sizeof(buf), ANGBAND_DIR_XTRA_SOUND, wav);
578
579         /* Save the sound filename, if it exists */
580         if (check_file(buf))
581             sound_file[i] = string_make(buf);
582     }
583
584     /* Sound available */
585     can_use_sound = TRUE;
586     return (can_use_sound);
587 }
588
589 /*
590  * Init the "curses" system
591  */
592 static void Term_init_gcu(term_type *t)
593 {
594     term_data *td = (term_data *)(t->data);
595
596     /* Count init's, handle first */
597     if (active++ != 0)
598         return;
599
600     /* Erase the screen */
601     (void)wclear(td->win);
602
603     /* Reset the cursor */
604     (void)wmove(td->win, 0, 0);
605
606     /* Flush changes */
607     (void)wrefresh(td->win);
608
609     /* Game keymap */
610     keymap_game();
611 }
612
613 /*
614  * Nuke the "curses" system
615  */
616 static void Term_nuke_gcu(term_type *t)
617 {
618     term_data *td = (term_data *)(t->data);
619
620     /* Delete this window */
621     delwin(td->win);
622
623     /* Count nuke's, handle last */
624     if (--active != 0)
625         return;
626
627     /* Hack -- make sure the cursor is visible */
628     term_xtra(TERM_XTRA_SHAPE, 1);
629
630 #ifdef A_COLOR
631     /* Reset colors to defaults */
632     start_color();
633 #endif
634
635     /* This moves curses to bottom right corner */
636     mvcur(getcury(curscr), getcurx(curscr), LINES - 1, 0);
637
638     /* Flush the curses buffer */
639     (void)refresh();
640
641     /* Exit curses */
642     endwin();
643
644     /* Flush the output */
645     (void)fflush(stdout);
646
647     /* Normal keymap */
648     keymap_norm();
649 }
650
651 /*
652  * Push multiple keys reversal
653  */
654 static void term_string_push(char *buf)
655 {
656     int i, l = strlen(buf);
657     for (i = l; i >= 0; i--)
658         term_key_push(buf[i]);
659 }
660
661 #ifdef USE_GETCH
662
663 /*
664  * Process events, with optional wait
665  */
666 static errr Term_xtra_gcu_event(int v)
667 {
668     int i, k;
669
670     /* Wait */
671     if (v) {
672         char buf[256];
673         char *bp = buf;
674
675         /* Paranoia -- Wait for it */
676         nodelay(stdscr, FALSE);
677
678         /* Get a keypress */
679         i = getch();
680
681         /* Broken input is special */
682         if (i == ERR)
683             exit_game_panic(p_ptr);
684         if (i == EOF)
685             exit_game_panic(p_ptr);
686
687         *bp++ = (char)i;
688
689         /* Do not wait for it */
690         nodelay(stdscr, TRUE);
691
692         while ((i = getch()) != EOF) {
693             if (i == ERR)
694                 exit_game_panic(p_ptr);
695             *bp++ = (char)i;
696             if (bp == &buf[255])
697                 break;
698         }
699
700         /* Wait for it next time */
701         nodelay(stdscr, FALSE);
702
703         *bp = '\0';
704 #ifdef JP
705         char eucbuf[sizeof(buf)];
706         /* strlen + 1 を渡して文字列終端('\0')を含めて変換する */
707         if (utf8_to_euc(buf, strlen(buf) + 1, eucbuf, sizeof(eucbuf)) < 0) {
708             return (-1);
709         }
710 #endif
711         term_string_push(_(eucbuf, buf));
712     }
713
714     /* Do not wait */
715     else {
716         /* Do not wait for it */
717         nodelay(stdscr, TRUE);
718
719         /* Check for keypresses */
720         i = getch();
721
722         /* Wait for it next time */
723         nodelay(stdscr, FALSE);
724
725         /* None ready */
726         if (i == ERR)
727             return (1);
728         if (i == EOF)
729             return (1);
730
731         /* Enqueue the keypress */
732         term_key_push(i);
733     }
734
735     /* Success */
736     return (0);
737 }
738
739 #else /* USE_GETCH */
740
741 /*
742  * Process events (with optional wait)
743  */
744 static errr Term_xtra_gcu_event(int v)
745 {
746     int i, k;
747
748     char buf[256];
749
750     /* Wait */
751     if (v) {
752         char *bp = buf;
753
754         /* Wait for one byte */
755         i = read(0, bp++, 1);
756
757         /* Hack -- Handle bizarre "errors" */
758         if ((i <= 0) && (errno != EINTR))
759             exit_game_panic(p_ptr);
760
761         /* Get the current flags for stdin */
762         k = fcntl(0, F_GETFL, 0);
763
764         /* Oops */
765         if (k < 0)
766             return (1);
767
768         /* Tell stdin not to block */
769         if (fcntl(0, F_SETFL, k | O_NDELAY) >= 0) {
770             if ((i = read(0, bp, 254)) > 0) {
771                 bp += i;
772             }
773
774             /* Replace the flags for stdin */
775             if (fcntl(0, F_SETFL, k))
776                 return (1);
777         }
778
779         bp[0] = '\0';
780 #ifdef JP
781         char eucbuf[sizeof(buf)];
782         /* strlen + 1 を渡して文字列終端('\0')を含めて変換する */
783         if (utf8_to_euc(buf, strlen(buf) + 1, eucbuf, sizeof(eucbuf)) < 0) {
784             return (-1);
785         }
786 #endif
787         term_string_push(_(eucbuf, buf));
788     }
789
790     /* Do not wait */
791     else {
792         /* Get the current flags for stdin */
793         k = fcntl(0, F_GETFL, 0);
794
795         /* Oops */
796         if (k < 0)
797             return (1);
798
799         /* Tell stdin not to block */
800         if (fcntl(0, F_SETFL, k | O_NDELAY) < 0)
801             return (1);
802
803         /* Read one byte, if possible */
804         i = read(0, buf, 1);
805
806         /* Replace the flags for stdin */
807         if (fcntl(0, F_SETFL, k))
808             return (1);
809
810         /* Ignore "invalid" keys */
811         if ((i != 1) || (!buf[0]))
812             return (1);
813
814         /* Enqueue the keypress */
815         term_key_push(buf[0]);
816     }
817
818     /* Success */
819     return (0);
820 }
821
822 #endif /* USE_GETCH */
823
824 /*
825  * Hack -- make a sound
826  */
827 static errr Term_xtra_gcu_sound(int v)
828 {
829     char buf[1024];
830
831     /* Sound disabled */
832     if (!use_sound)
833         return (1);
834
835     /* Illegal sound */
836     if ((v < 0) || (v >= SOUND_MAX))
837         return (1);
838
839     /* Unknown sound */
840     if (!sound_file[v])
841         return (1);
842
843     sprintf(buf, "./gcusound.sh %s\n", sound_file[v]);
844
845     return (system(buf) < 0);
846
847     return (0);
848 }
849
850 /*
851  * React to changes
852  */
853 static errr Term_xtra_gcu_react(void)
854 {
855
856 #ifdef A_COLOR
857
858     int i;
859
860     /* Cannot handle color redefinition */
861     if (!can_fix_color)
862         return (0);
863
864     /* Set the colors */
865     for (i = 0; i < 16; i++) {
866         /* Set one color (note scaling) */
867         init_color(i, angband_color_table[i][1] * 1000 / 255, angband_color_table[i][2] * 1000 / 255, angband_color_table[i][3] * 1000 / 255);
868     }
869
870 #endif
871
872     /* Success */
873     return (0);
874 }
875
876 /*
877  * Handle a "special request"
878  */
879 static errr Term_xtra_gcu(int n, int v)
880 {
881     term_data *td = (term_data *)(Term->data);
882
883     /* Analyze the request */
884     switch (n) {
885     /* Clear screen */
886     case TERM_XTRA_CLEAR:
887         touchwin(td->win);
888         (void)wclear(td->win);
889         return (0);
890
891     /* Make a noise */
892     case TERM_XTRA_NOISE:
893         return write(1, "\007", 1) != 1;
894
895     /* Make a special sound */
896     case TERM_XTRA_SOUND:
897         return (Term_xtra_gcu_sound(v));
898
899     /* Flush the Curses buffer */
900     case TERM_XTRA_FRESH:
901         (void)wrefresh(td->win);
902         return (0);
903
904 #ifdef USE_CURS_SET
905
906     /* Change the cursor visibility */
907     case TERM_XTRA_SHAPE:
908         curs_set(v);
909         return (0);
910
911 #endif
912
913     /* Suspend/Resume curses */
914     case TERM_XTRA_ALIVE:
915         return (Term_xtra_gcu_alive(v));
916
917     /* Process events */
918     case TERM_XTRA_EVENT:
919         return (Term_xtra_gcu_event(v));
920
921     /* Flush events */
922     case TERM_XTRA_FLUSH:
923         while (!Term_xtra_gcu_event(FALSE))
924             ;
925         return (0);
926
927     /* Delay */
928     case TERM_XTRA_DELAY:
929         usleep(1000 * v);
930         return (0);
931
932     /* React to events */
933     case TERM_XTRA_REACT:
934         Term_xtra_gcu_react();
935         return (0);
936     }
937
938     /* Unknown */
939     return (1);
940 }
941
942 /*
943  * Actually MOVE the hardware cursor
944  */
945 static errr Term_curs_gcu(int x, int y)
946 {
947     term_data *td = (term_data *)(Term->data);
948
949     /* Literally move the cursor */
950     wmove(td->win, y, x);
951
952     /* Success */
953     return (0);
954 }
955
956 /*
957  * Erase a grid of space
958  * Hack -- try to be "semi-efficient".
959  */
960 static errr Term_wipe_gcu(int x, int y, int n)
961 {
962     term_data *td = (term_data *)(Term->data);
963
964     /* Place cursor */
965     wmove(td->win, y, x);
966
967     /* Clear to end of line */
968     if (x + n >= 80) {
969         wclrtoeol(td->win);
970     }
971
972     /* Clear some characters */
973     else {
974         while (n-- > 0)
975             waddch(td->win, ' ');
976     }
977
978     /* Success */
979     return (0);
980 }
981
982 #ifdef USE_NCURSES_ACS
983 /*
984  * this function draws some ACS characters on the screen
985  * for DOS-based users: these are the graphical chars (blocks, lines etc)
986  *
987  * unix-gurus: before you start adding other attributes like A_REVERSE
988  * think hard about how map_info() in cave.c should handle the color
989  * of something that we here draw in reverse. It's not so simple, alas.
990  */
991 static void Term_acs_text_gcu(int x, int y, int n, byte a, concptr s)
992 {
993     term_data *td = (term_data *)(Term->data);
994     int i;
995
996     /* position the cursor */
997     wmove(td->win, y, x);
998
999 #ifdef A_COLOR
1000     /* Set the color */
1001     wattrset(td->win, colortable[a & 0x0F]);
1002 #endif
1003
1004     for (i = 0; i < n; i++) {
1005         /* add acs_map of a */
1006         waddch(td->win, acs_map[(int)s[i]]);
1007     }
1008     wattrset(td->win, WA_NORMAL);
1009 }
1010 #endif
1011
1012 /*
1013  * Place some text on the screen using an attribute
1014  */
1015 static errr Term_text_gcu(int x, int y, int n, byte a, concptr s)
1016 {
1017     term_data *td = (term_data *)(Term->data);
1018
1019 #ifdef USE_NCURSES_ACS
1020     /* do we have colors + 16 ? */
1021     /* then call special routine for drawing special characters */
1022     if (a & 0x10) {
1023         Term_acs_text_gcu(x, y, n, a, s);
1024         return (0);
1025     }
1026 #endif
1027
1028     /* Move the cursor and dump the string */
1029     wmove(td->win, y, x);
1030
1031 #ifdef A_COLOR
1032     /* Set the color */
1033     if (can_use_color)
1034         wattrset(td->win, colortable[a & 0x0F]);
1035 #endif
1036
1037 #ifdef JP
1038     char text[1024];
1039     int text_len = euc_to_utf8(s, n, text, sizeof(text));
1040     if (text_len < 0) {
1041         return (-1);
1042     }
1043 #endif
1044     /* Add the text */
1045     waddnstr(td->win, _(text, s), _(text_len, n));
1046
1047     /* Success */
1048     return (0);
1049 }
1050
1051 static errr term_data_init(term_data *td, int rows, int cols, int y, int x)
1052 {
1053     term_type *t = &td->t;
1054
1055     /* Make sure the window has a positive size */
1056     if (rows <= 0 || cols <= 0)
1057         return (0);
1058
1059     /* Create a window */
1060     td->win = newwin(rows, cols, y, x);
1061
1062     /* Make sure we succeed */
1063     if (!td->win) {
1064         plog("Failed to setup curses window.");
1065         return (-1);
1066     }
1067
1068     /* Initialize the term */
1069     term_init(t, cols, rows, 256);
1070
1071     /* Avoid the bottom right corner */
1072     t->icky_corner = TRUE;
1073
1074     /* Erase with "white space" */
1075     t->attr_blank = TERM_WHITE;
1076     t->char_blank = ' ';
1077
1078     /* Set some hooks */
1079     t->init_hook = Term_init_gcu;
1080     t->nuke_hook = Term_nuke_gcu;
1081
1082     /* Set some more hooks */
1083     t->text_hook = Term_text_gcu;
1084     t->wipe_hook = Term_wipe_gcu;
1085     t->curs_hook = Term_curs_gcu;
1086     t->xtra_hook = Term_xtra_gcu;
1087
1088     /* Save the data */
1089     t->data = td;
1090
1091     /* Activate it */
1092     term_activate(t);
1093
1094     /* Success */
1095     return (0);
1096 }
1097
1098 static void hook_quit(concptr str)
1099 {
1100     /* Unused */
1101     (void)str;
1102
1103     /* Exit curses */
1104     endwin();
1105 }
1106
1107 /*
1108  * Prepare "curses" for use by the file "term.c"
1109  *
1110  * Installs the "hook" functions defined above, and then activates
1111  * the main screen "term", which clears the screen and such things.
1112  *
1113  * Someone should really check the semantics of "initscr()"
1114  */
1115 errr init_gcu(int argc, char *argv[])
1116 {
1117     int i;
1118
1119     int num_term = 4, next_win = 0;
1120     char path[1024];
1121
1122     /* Unused */
1123     (void)argc;
1124     (void)argv;
1125
1126     setlocale(LC_ALL, "");
1127
1128     /* Build the "sound" path */
1129     path_build(path, sizeof(path), ANGBAND_DIR_XTRA, "sound");
1130
1131     /* Allocate the path */
1132     ANGBAND_DIR_XTRA_SOUND = string_make(path);
1133
1134     /* Extract the normal keymap */
1135     keymap_norm_prepare();
1136
1137     /* Initialize for others systems */
1138     if (initscr() == (WINDOW *)ERR)
1139         return (-1);
1140
1141     /* Activate hooks */
1142     quit_aux = hook_quit;
1143     core_aux = hook_quit;
1144
1145     /* Hack -- Require large screen, or Quit with message */
1146     i = ((LINES < 24) || (COLS < 80));
1147     if (i)
1148         quit("Angband needs an 80x24 'curses' screen");
1149
1150 #ifdef A_COLOR
1151
1152     /*** Init the Color-pairs and set up a translation table ***/
1153
1154     /* Do we have color, and enough color, available? */
1155     can_use_color = ((start_color() != ERR) && has_colors() && (COLORS >= 8) && (COLOR_PAIRS >= 8));
1156
1157 #ifdef REDEFINE_COLORS
1158     /* Can we change colors? */
1159     can_fix_color = (can_use_color && can_change_color() && (COLORS >= 16) && (COLOR_PAIRS > 8));
1160 #endif
1161
1162     /* Attempt to use customized colors */
1163     if (can_fix_color) {
1164         /* Prepare the color pairs */
1165         for (i = 1; i <= 15; i++) {
1166             if (init_pair(i, i, 0) == ERR) {
1167                 quit("Color pair init failed");
1168             }
1169
1170             colortable[i] = COLOR_PAIR(i);
1171             Term_xtra_gcu_react();
1172         }
1173     }
1174     /* Attempt to use colors */
1175     else if (can_use_color) {
1176         /* Color-pair 0 is *always* WHITE on BLACK */
1177
1178         /* Prepare the color pairs */
1179         init_pair(1, COLOR_RED, COLOR_BLACK);
1180         init_pair(2, COLOR_GREEN, COLOR_BLACK);
1181         init_pair(3, COLOR_YELLOW, COLOR_BLACK);
1182         init_pair(4, COLOR_BLUE, COLOR_BLACK);
1183         init_pair(5, COLOR_MAGENTA, COLOR_BLACK);
1184         init_pair(6, COLOR_CYAN, COLOR_BLACK);
1185         init_pair(7, COLOR_BLACK, COLOR_BLACK);
1186
1187         /* Prepare the "Angband Colors" -- Bright white is too bright */
1188         /* Changed in Drangband. Cyan as grey sucks -- -TM- */
1189         colortable[0] = (COLOR_PAIR(7) | A_NORMAL); /* Black */
1190         colortable[1] = (COLOR_PAIR(0) | A_BRIGHT); /* White */
1191         colortable[2] = (COLOR_PAIR(0) | A_NORMAL); /* Grey XXX */
1192         colortable[3] = (COLOR_PAIR(1) | A_BRIGHT); /* Orange XXX */
1193         colortable[4] = (COLOR_PAIR(1) | A_NORMAL); /* Red */
1194         colortable[5] = (COLOR_PAIR(2) | A_NORMAL); /* Green */
1195         colortable[6] = (COLOR_PAIR(4) | A_BRIGHT); /* Blue */
1196         colortable[7] = (COLOR_PAIR(3) | A_NORMAL); /* Umber */
1197         colortable[8] = (COLOR_PAIR(7) | A_BRIGHT); /* Dark-grey XXX */
1198         colortable[9] = (COLOR_PAIR(0) | A_NORMAL); /* Light-grey XXX */
1199         colortable[10] = (COLOR_PAIR(5) | A_BRIGHT); /* Purple */
1200         colortable[11] = (COLOR_PAIR(3) | A_BRIGHT); /* Yellow */
1201         colortable[12] = (COLOR_PAIR(5) | A_NORMAL); /* Light Red XXX */
1202         colortable[13] = (COLOR_PAIR(2) | A_BRIGHT); /* Light Green */
1203         colortable[14] = (COLOR_PAIR(6) | A_BRIGHT); /* Light Blue */
1204         colortable[15] = (COLOR_PAIR(3) | A_NORMAL); /* Light Umber XXX */
1205     }
1206
1207 #endif
1208
1209     /* Handle "arg_sound" */
1210     if (use_sound != arg_sound) {
1211         /* Initialize (if needed) */
1212         if (arg_sound && !init_sound()) {
1213             /* Warning */
1214             plog("Cannot initialize sound!");
1215
1216             /* Cannot enable */
1217             arg_sound = FALSE;
1218         }
1219
1220         /* Change setting */
1221         use_sound = arg_sound;
1222     }
1223
1224     /* Try graphics */
1225     if (arg_graphics) {
1226         /* if USE_NCURSES_ACS is defined, we can do something with graphics in curses! */
1227 #ifdef USE_NCURSES_ACS
1228         use_graphics = TRUE;
1229 #endif
1230     }
1231
1232     /*** Low level preparation ***/
1233
1234 #ifdef USE_GETCH
1235
1236     /* Paranoia -- Assume no waiting */
1237     nodelay(stdscr, FALSE);
1238
1239 #endif
1240
1241     /* Prepare */
1242     cbreak();
1243     noecho();
1244     nonl();
1245     raw();
1246
1247     /* Extract the game keymap */
1248     keymap_game_prepare();
1249
1250     /*** Now prepare the term(s) ***/
1251     for (i = 0; i < num_term; i++) {
1252         int rows, cols;
1253         int y, x;
1254
1255         switch (i) {
1256         /* Upper left */
1257         case 0:
1258             rows = 24;
1259             cols = 80;
1260             y = x = 0;
1261             break;
1262         /* Lower left */
1263         case 1:
1264             rows = LINES - 25;
1265             cols = 80;
1266             y = 24;
1267             x = 0;
1268             break;
1269         /* Upper right */
1270         case 2:
1271             rows = 24;
1272             cols = COLS - 81;
1273             y = 0;
1274             x = 81;
1275             break;
1276         /* Lower right */
1277         case 3:
1278             rows = LINES - 25;
1279             cols = COLS - 81;
1280             y = 24;
1281             x = 81;
1282             break;
1283         /* XXX */
1284         default:
1285             rows = cols = 0;
1286             y = x = 0;
1287             break;
1288         }
1289
1290         /* No non-windows */
1291         if (rows <= 0 || cols <= 0)
1292             continue;
1293
1294         /* Initialize */
1295         term_data_init(&data[next_win], rows, cols, y, x);
1296
1297         /* Store */
1298         angband_term[next_win] = Term;
1299
1300         next_win++;
1301     }
1302
1303     /* Activate the "Angband" window screen */
1304     term_activate(&data[0].t);
1305
1306     /* Store */
1307     term_screen = &data[0].t;
1308
1309     /* Success */
1310     return (0);
1311 }
1312
1313 #endif /* USE_GCU */