OSDN Git Service

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