1 /* File: main-x11.c */
4 * Copyright (c) 1997 Ben Harrison, and others
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.
13 * This file helps Angband work with UNIX/X11 computers.
15 * To use this file, compile with "USE_X11" defined, and link against all
16 * the various "X11" libraries which may be needed.
18 * See also "main-xaw.c".
20 * Part of this file provides a user interface package composed of several
21 * pseudo-objects, including "metadpy" (a display), "infowin" (a window),
22 * "infoclr" (a color), and "infofnt" (a font). Actually, the package was
23 * originally much more interesting, but it was bastardized to keep this
26 * The rest of this file is an implementation of "main-xxx.c" for X11.
28 * Most of this file is by Ben Harrison (benh@phial.com).
32 * The following shell script can be used to launch Angband, assuming that
33 * it was extracted into "~/Angband", and compiled using "USE_X11", on a
34 * Linux machine, with a 1280x1024 screen, using 6 windows (with the given
35 * characteristics), with gamma correction of 1.8 -> (1 / 1.8) * 256 = 142,
36 * and without graphics (add "-g" for graphics). Just copy this comment
37 * into a file, remove the leading " * " characters (and the head/tail of
38 * this comment), and make the file executable.
44 * echo "Launching angband..."
48 * setenv ANGBAND_X11_FONT_0 10x20
49 * setenv ANGBAND_X11_AT_X_0 5
50 * setenv ANGBAND_X11_AT_Y_0 510
53 * setenv ANGBAND_X11_FONT_1 8x13
54 * setenv ANGBAND_X11_AT_X_1 5
55 * setenv ANGBAND_X11_AT_Y_1 22
56 * setenv ANGBAND_X11_ROWS_1 35
59 * setenv ANGBAND_X11_FONT_2 8x13
60 * setenv ANGBAND_X11_AT_X_2 635
61 * setenv ANGBAND_X11_AT_Y_2 182
62 * setenv ANGBAND_X11_ROWS_3 23
65 * setenv ANGBAND_X11_FONT_3 8x13
66 * setenv ANGBAND_X11_AT_X_3 635
67 * setenv ANGBAND_X11_AT_Y_3 22
68 * setenv ANGBAND_X11_ROWS_3 12
70 * # Monster recall window
71 * setenv ANGBAND_X11_FONT_4 6x13
72 * setenv ANGBAND_X11_AT_X_4 817
73 * setenv ANGBAND_X11_AT_Y_4 847
74 * setenv ANGBAND_X11_COLS_4 76
75 * setenv ANGBAND_X11_ROWS_4 11
77 * # Object recall window
78 * setenv ANGBAND_X11_FONT_5 6x13
79 * setenv ANGBAND_X11_AT_X_5 817
80 * setenv ANGBAND_X11_AT_Y_5 520
81 * setenv ANGBAND_X11_COLS_5 76
82 * setenv ANGBAND_X11_ROWS_5 24
84 * # The build directory
88 * setenv ANGBAND_X11_GAMMA 142
91 * ./src/angband -mx11 -- -n6 &
97 #include "main/sound-definitions-table.h"
100 #include "gameterm.h"
104 * Available graphic modes
106 #define GRAPHICS_NONE 0
107 #define GRAPHICS_ORIGINAL 1
108 #define GRAPHICS_ADAM_BOLT 2
109 #define GRAPHICS_HENGBAND 3
113 #ifndef __MAKEDEPEND__
114 #include <X11/Xlib.h>
115 #include <X11/Xutil.h>
116 #include <X11/keysym.h>
117 #include <X11/keysymdef.h>
119 #include <X11/Xlocale.h>
121 #include <X11/Xatom.h>
122 #endif /* __MAKEDEPEND__ */
126 #include <X11/Xft/Xft.h>
130 * Include some helpful X11 code.
132 #include "maid-x11.c"
138 * 1) On a monochrome (or "fake-monochrome") display, all colors
139 * will be "cast" to "fg," except for the bg color, which is,
140 * obviously, cast to "bg". Thus, one can ignore this setting.
142 * 2) Because of the inner functioning of the color allocation
143 * routines, colors may be specified as (a) a typical color name,
144 * (b) a hexidecimal color specification (preceded by a pound sign),
145 * or (c) by strings such as "fg", "bg", "zg".
147 * 3) Due to the workings of the init routines, many colors
148 * may also be dealt with by their actual pixel values. Note that
149 * the pixel with all bits set is "zg = (1<<metadpy->depth)-1", which
150 * is not necessarily either black or white.
153 /**** Generic Types ****/
156 * An X11 pixell specifier
159 typedef XftColor Pixell;
161 typedef unsigned long Pixell;
165 * The structures defined below
167 typedef struct metadpy metadpy;
168 typedef struct infowin infowin;
169 typedef struct infoclr infoclr;
170 typedef struct infofnt infofnt;
174 * A structure summarizing a given Display.
176 * - The Display itself
177 * - The default Screen for the display
178 * - The virtual root (usually just the root)
179 * - The default colormap (from a macro)
181 * - The "name" of the display
183 * - The socket to listen to for events
185 * - The width of the display screen (from a macro)
186 * - The height of the display screen (from a macro)
187 * - The bit depth of the display screen (from a macro)
189 * - The black Pixell (from a macro)
190 * - The white Pixell (from a macro)
192 * - The background Pixell (default: black)
193 * - The foreground Pixell (default: white)
194 * - The maximal Pixell (Equals: ((2 ^ depth)-1), is usually ugly)
196 * - Bit Flag: Force all colors to black and white (default: !color)
197 * - Bit Flag: Allow the use of color (default: depth > 1)
198 * - Bit Flag: We created 'dpy', and so should nuke it when done.
235 * A Structure summarizing Window Information.
237 * I assume that a window is at most 30000 pixels on a side.
238 * I assume that the root windw is also at most 30000 square.
241 * - The current Input Event Mask
243 * - The location of the window
244 * - The width, height of the window
245 * - The border width of this window
247 * - Byte: 1st Extra byte
249 * - Bit Flag: This window is currently Mapped
250 * - Bit Flag: This window needs to be redrawn
251 * - Bit Flag: This window has been resized
253 * - Bit Flag: We should nuke 'win' when done with it
255 * - Bit Flag: 1st extra flag
256 * - Bit Flag: 2nd extra flag
257 * - Bit Flag: 3rd extra flag
258 * - Bit Flag: 4th extra flag
299 * A Structure summarizing Operation+Color Information
301 * - The actual GC corresponding to this info
303 * - The Foreground Pixell Value
304 * - The Background Pixell Value
306 * - Num (0-15): The operation code (As in Clear, Xor, etc)
307 * - Bit Flag: The GC is in stipple mode
308 * - Bit Flag: Destroy 'gc' at Nuke time.
327 * A Structure to Hold Font Information
329 * - The 'XFontStruct*' (yields the 'Font')
333 * - The default character width
334 * - The default character height
335 * - The default character ascent
337 * - Byte: Pixel offset used during fake mono
339 * - Flag: Force monospacing via 'wid'
340 * - Flag: Nuke info when done
365 /**** Generic Macros ****/
369 /* Set current metadpy (Metadpy) to 'M' */
370 #define Metadpy_set(M) \
374 /* Initialize 'M' using Display 'D' */
375 #define Metadpy_init_dpy(D) \
376 Metadpy_init_2(D,cNULL)
378 /* Initialize 'M' using a Display named 'N' */
379 #define Metadpy_init_name(N) \
380 Metadpy_init_2((Display*)(NULL),N)
382 /* Initialize 'M' using the standard Display */
383 #define Metadpy_init() \
384 Metadpy_init_name("")
387 /* Init an infowin by giving father as an (info_win*) (or NULL), and data */
388 #define Infowin_init_dad(D,X,Y,W,H,B,FG,BG) \
389 Infowin_init_data(((D) ? ((D)->win) : (Window)(None)), \
393 /* Init a top level infowin by pos,size,bord,Colors */
394 #define Infowin_init_top(X,Y,W,H,B,FG,BG) \
395 Infowin_init_data(None,X,Y,W,H,B,FG,BG)
398 /* Request a new standard window by giving Dad infowin and X,Y,W,H */
399 #define Infowin_init_std(D,X,Y,W,H,B) \
400 Infowin_init_dad(D,X,Y,W,H,B,Metadpy->fg,Metadpy->bg)
403 /* Set the current Infowin */
404 #define Infowin_set(I) \
408 /* Set the current Infoclr */
409 #define Infoclr_set(C) \
413 #define Infoclr_init_ppo(F,B,O,M) \
414 Infoclr_init_data(F,B,O,M)
416 #define Infoclr_init_cco(F,B,O,M) \
417 Infoclr_init_ppo(Infoclr_Pixell(F),Infoclr_Pixell(B),O,M)
419 #define Infoclr_init_ppn(F,B,O,M) \
420 Infoclr_init_ppo(F,B,Infoclr_Opcode(O),M)
422 #define Infoclr_init_ccn(F,B,O,M) \
423 Infoclr_init_cco(F,B,Infoclr_Opcode(O),M)
426 /* Set the current infofnt */
427 #define Infofnt_set(I) \
431 /* Errr: Expose Infowin */
432 #define Infowin_expose() \
433 (!(Infowin->redraw = 1))
435 /* Errr: Unxpose Infowin */
436 #define Infowin_unexpose() \
437 (Infowin->redraw = 0)
441 /**** Generic Globals ****/
445 * The "default" values
447 static metadpy metadpy_default;
451 * The "current" variables
453 static metadpy *Metadpy = &metadpy_default;
454 static infowin *Infowin = (infowin*)(NULL);
456 static infowin *Focuswin = (infowin*)(NULL);
458 static infoclr *Infoclr = (infoclr*)(NULL);
459 static infofnt *Infofnt = (infofnt*)(NULL);
461 /**** Generic code ****/
464 * Init the current metadpy, with various initialization stuff.
467 * dpy: The Display* to use (if NULL, create it)
468 * name: The name of the Display (if NULL, the current)
471 * If 'name' is NULL, but 'dpy' is set, extract name from dpy
472 * If 'dpy' is NULL, then Create the named Display
473 * If 'name' is NULL, and so is 'dpy', use current Display
475 * Return -1 if no Display given, and none can be opened.
477 static errr Metadpy_init_2(Display *dpy, concptr name)
479 metadpy *m = Metadpy;
481 /*** Open the display if needed ***/
483 /* If no Display given, attempt to Create one */
486 /* Attempt to open the display */
487 dpy = XOpenDisplay(name);
490 if (!dpy) return (-1);
492 /* We will have to nuke it when done */
496 /* Since the Display was given, use it */
499 /* We will not have to nuke it when done */
504 /*** Save some information ***/
506 /* Save the Display itself */
509 /* Get the Screen and Virtual Root Window */
510 m->screen = DefaultScreenOfDisplay(dpy);
511 m->root = RootWindowOfScreen(m->screen);
513 /* Get the default colormap */
514 m->cmap = DefaultColormapOfScreen(m->screen);
516 /* Extract the true name of the display */
517 m->name = DisplayString(dpy);
520 m->fd = ConnectionNumber(Metadpy->dpy);
522 /* Save the Size and Depth of the screen */
523 m->width = WidthOfScreen(m->screen);
524 m->height = HeightOfScreen(m->screen);
525 m->depth = DefaultDepthOfScreen(m->screen);
527 /* Save the Standard Colors */
529 Visual *vis = DefaultVisual(dpy, 0);
530 XftColorAllocName(dpy, vis, m->cmap, "black", &m->black);
531 XftColorAllocName(dpy, vis, m->cmap, "white", &m->white);
533 m->black = BlackPixelOfScreen(m->screen);
534 m->white = WhitePixelOfScreen(m->screen);
537 /*** Make some clever Guesses ***/
539 /* Guess at the desired 'fg' and 'bg' Pixell's */
544 /* Calculate the Maximum allowed Pixel value. */
545 m->zg = (1 << m->depth) - 1;
548 /* Save various default Flag Settings */
549 m->color = ((m->depth > 1) ? 1 : 0);
550 m->mono = ((m->color) ? 0 : 1);
552 /* Return "success" */
558 * General Flush/ Sync/ Discard routine
560 static errr Metadpy_update(int flush, int sync, int discard)
562 /* Flush if desired */
563 if (flush) XFlush(Metadpy->dpy);
565 /* Sync if desired, using 'discard' */
566 if (sync) XSync(Metadpy->dpy, discard);
576 static errr Metadpy_do_beep(void)
578 /* Make a simple beep */
579 XBell(Metadpy->dpy, 100);
587 * Set the name (in the title bar) of Infowin
589 static errr Infowin_set_name(concptr name)
596 st = XStringListToTextProperty(&bp, 1, &tp);
597 if (st) XSetWMName(Metadpy->dpy, Infowin->win, &tp);
603 * Prepare a new 'infowin'.
605 static errr Infowin_prepare(Window xid)
607 infowin *iwin = Infowin;
610 XWindowAttributes xwa;
612 unsigned int w, h, b, d;
617 /* Check For Error XXX Extract some ACTUAL data from 'xid' */
618 XGetGeometry(Metadpy->dpy, xid, &tmp_win, &x, &y, &w, &h, &b, &d);
621 Visual *vis = DefaultVisual(Metadpy->dpy, 0);
622 if (vis->class != TrueColor) {
623 quit_fmt("Display does not support truecolor.\n");
625 iwin->draw = XftDrawCreate(Metadpy->dpy, iwin->win, vis, Metadpy->cmap);
628 /* Apply the above info */
635 /* Check Error XXX Extract some more ACTUAL data */
636 XGetWindowAttributes(Metadpy->dpy, xid, &xwa);
638 /* Apply the above info */
639 iwin->mask = xwa.your_event_mask;
640 iwin->mapped = ((xwa.map_state == IsUnmapped) ? 0 : 1);
642 /* And assume that we are exposed */
651 * Init an infowin by giving some data.
654 * dad: The Window that should own this Window (if any)
655 * x,y: The position of this Window
656 * w,h: The size of this Window
657 * b,d: The border width and pixel depth
660 * If 'dad == None' assume 'dad == root'
662 static errr Infowin_init_data(Window dad, int x, int y, int w, int h,
663 int b, Pixell fg, Pixell bg)
668 (void)WIPE(Infowin, infowin);
671 /*** Error Check XXX ***/
674 /*** Create the Window 'xid' from data ***/
676 /* What happened here? XXX XXX XXX */
678 /* If no parent given, depend on root */
679 if (dad == None) dad = Metadpy->root;
681 /* Create the Window XXX Error Check */
683 xid = XCreateSimpleWindow(Metadpy->dpy, dad, x, y, w, h, b, fg.pixel, bg.pixel);
685 xid = XCreateSimpleWindow(Metadpy->dpy, dad, x, y, w, h, b, fg, bg);
688 /* Start out selecting No events */
689 XSelectInput(Metadpy->dpy, xid, 0L);
692 /*** Prepare the new infowin ***/
694 /* Mark it as nukable */
697 /* Attempt to Initialize the infowin */
698 return (Infowin_prepare(xid));
704 * Modify the event mask of an Infowin
706 static errr Infowin_set_mask(long mask)
708 /* Save the new setting */
709 Infowin->mask = mask;
711 /* Execute the Mapping */
712 XSelectInput(Metadpy->dpy, Infowin->win, Infowin->mask);
720 * Request that Infowin be mapped
722 static errr Infowin_map(void)
724 /* Execute the Mapping */
725 XMapWindow(Metadpy->dpy, Infowin->win);
733 * Request that Infowin be raised
735 static errr Infowin_raise(void)
737 /* Raise towards visibility */
738 XRaiseWindow(Metadpy->dpy, Infowin->win);
746 * Request that Infowin be moved to a new location
748 static errr Infowin_impell(int x, int y)
750 /* Execute the request */
751 XMoveWindow(Metadpy->dpy, Infowin->win, x, y);
761 static errr Infowin_resize(int w, int h)
763 /* Execute the request */
764 XResizeWindow(Metadpy->dpy, Infowin->win, w, h);
772 * Visually clear Infowin
774 static errr Infowin_wipe(void)
776 /* Execute the request */
777 XClearWindow(Metadpy->dpy, Infowin->win);
785 * A NULL terminated pair list of legal "operation names"
787 * Pairs of values, first is texttual name, second is the string
788 * holding the decimal value that the operation corresponds to.
790 static concptr opcode_pairs[] =
809 "+copyInverted", "12",
817 * Parse a word into an operation "code"
820 * str: A string, hopefully representing an Operation
823 * 0-15: if 'str' is a valid Operation
824 * -1: if 'str' could not be parsed
826 static int Infoclr_Opcode(concptr str)
830 /* Scan through all legal operation names */
831 for (i = 0; opcode_pairs[i*2]; ++i)
833 /* Is this the right oprname? */
834 if (streq(opcode_pairs[i*2], str))
836 /* Convert the second element in the pair into a Code */
837 return (atoi(opcode_pairs[i*2+1]));
841 /* The code was not found, return -1 */
847 * Initialize an infoclr with some data
850 * fg: The Pixell for the requested Foreground (see above)
851 * bg: The Pixell for the requested Background (see above)
852 * op: The Opcode for the requested Operation (see above)
853 * stip: The stipple mode
855 static errr Infoclr_init_data(Pixell fg, Pixell bg, int op, int stip)
857 infoclr *iclr = Infoclr;
862 unsigned long gc_mask;
867 /*** Simple error checking of opr and clr ***/
869 /* Check the 'Pixells' for realism */
871 if (bg > Metadpy->zg) return (-1);
872 if (fg > Metadpy->zg) return (-1);
874 /* Check the data for trueness */
875 if ((op < 0) || (op > 15)) return (-1);
878 /*** Create the requested 'GC' ***/
880 /* Assign the proper GC function */
883 /* Assign the proper GC background */
886 /* Assign the proper GC foreground */
889 /* Hack -- Handle XOR (xor is code 6) by hacking bg and fg */
890 if (op == 6) gcv.background = 0;
891 if (op == 6) gcv.foreground = (bg ^ fg);
893 /* Assign the proper GC Fill Style */
894 gcv.fill_style = (stip ? FillStippled : FillSolid);
896 /* Turn off 'Give exposure events for pixmap copying' */
897 gcv.graphics_exposures = False;
899 /* Set up the GC mask */
900 gc_mask = (GCFunction | GCBackground | GCForeground |
901 GCFillStyle | GCGraphicsExposures);
903 /* Create the GC detailed above */
904 gc = XCreateGC(Metadpy->dpy, Metadpy->root, gc_mask, &gcv);
910 /* Wipe the iclr clean */
911 (void)WIPE(iclr, infoclr);
918 /* Nuke it when done */
921 /* Assign the parms */
925 iclr->stip = stip ? 1 : 0;
934 * Change the 'fg' for an infoclr
937 * fg: The Pixell for the requested Foreground (see above)
939 static errr Infoclr_change_fg(Pixell fg)
941 infoclr *iclr = Infoclr;
947 /*** Simple error checking of opr and clr ***/
949 /* Check the 'Pixells' for realism */
950 if (fg > Metadpy->zg) return (-1);
956 XSetForeground(Metadpy->dpy, iclr->gc, fg);
965 * Prepare a new 'infofnt'
968 static errr Infofnt_prepare(XftFont *info)
970 static errr Infofnt_prepare(XFontSet info)
973 infofnt *ifnt = Infofnt;
977 XFontStruct **fontinfo;
980 int ascent, descent, width;
983 /* Assign the struct */
988 ifnt->asc = info->ascent;
989 ifnt->hgt = info->ascent + info->descent;
990 const char *text = "A";
992 XftTextExtentsUtf8(Metadpy->dpy, info, (FcChar8*)text, strlen(text), &extent);
993 ifnt->wid = extent.xOff;
995 n_fonts = XFontsOfFontSet(info, &fontinfo, &fontname);
997 ascent = descent = width = 0;
998 while(n_fonts-- > 0){
999 cs = &((*fontinfo)->max_bounds);
1000 if(ascent < (*fontinfo)->ascent) ascent = (*fontinfo)->ascent;
1001 if(descent < (*fontinfo)->descent) descent = (*fontinfo)->descent;
1002 if(((*fontinfo)->max_byte1) > 0){
1003 /* 多バイト文字の場合は幅半分(端数切り上げ)で評価する */
1004 if(width < (cs->width+1)/2) width = (cs->width+1)/2;
1006 if(width < cs->width) width = cs->width;
1012 ifnt->hgt = ascent + descent;
1017 ifnt->twid = 2 * ifnt->wid;
1019 ifnt->twid = ifnt->wid;
1026 * Init an infofnt by its Name
1029 * name: The name of the requested Font
1031 static void Infofnt_init_data(concptr name)
1038 char **missing_list;
1043 /*** Load the info Fresh, using the name ***/
1045 /* If the name is not given, report an error */
1046 if (!name || !*name) quit("Missing font!");
1048 /* Attempt to load the font */
1050 info = XftFontOpenName(Metadpy->dpy, 0, name);
1051 /* TODO: error handling */
1053 info = XCreateFontSet(Metadpy->dpy, name, &missing_list, &missing_count, &default_font);
1054 if(missing_count > 0){
1055 printf("missing font(s): \n");
1056 while(missing_count-- > 0){
1057 printf("\t%s\n", missing_list[missing_count]);
1059 XFreeStringList(missing_list);
1063 /* The load failed, try to recover */
1064 if (!info) quit_fmt("Failed to find font:\"%s\"", name);
1066 /*** Init the font ***/
1068 /* Wipe the thing */
1069 (void)WIPE(Infofnt, infofnt);
1071 /* Attempt to prepare it */
1072 if (Infofnt_prepare(info))
1076 XftFontClose(Metadpy->dpy, info);
1078 XFreeFontSet(Metadpy->dpy, info);
1082 quit_fmt("Failed to prepare font:\"%s\"", name);
1085 /* Save a copy of the font name */
1086 Infofnt->name = string_make(name);
1088 /* Mark it as nukable */
1096 static errr Infofnt_text_std(int x, int y, concptr str, int len)
1098 /*** Do a brief info analysis ***/
1100 /* Do nothing if the string is null */
1101 if (!str || !*str) return (-1);
1103 /* Get the length of the string */
1104 if (len < 0) len = strlen(str);
1106 /*** Decide where to place the string, vertically ***/
1108 /* Ignore Vertical Justifications */
1109 y = (y * Infofnt->hgt) + Infofnt->asc + Infowin->oy;
1112 /*** Decide where to place the string, horizontally ***/
1114 /* Line up with x at left edge of column 'x' */
1115 x = (x * Infofnt->wid) + Infowin->ox;
1118 /*** Actually draw 'str' onto the infowin ***/
1120 /*** Handle the fake mono we can enforce on fonts ***/
1122 /* Monotize the font */
1128 /* Do each character */
1129 for (i = 0; i < len; ++i)
1131 /* Note that the Infoclr is set up to contain the Infofnt */
1132 XDrawImageString(Metadpy->dpy, Infowin->win, Infoclr->gc,
1133 x + i * Infofnt->wid + Infofnt->off, y, str + i, 1);
1138 /* Assume monoospaced font */
1141 /* Note that the Infoclr is set up to contain the Infofnt */
1142 iconv_t cd = iconv_open("UTF-8", "EUC-JP");
1144 size_t outlen = len * 2;
1145 char *kanji = malloc(outlen);
1146 char *sp; char *kp = kanji;
1148 my_strcpy(sbuf, str, sizeof(sbuf));
1150 iconv(cd, &sp, &inlen, &kp, &outlen);
1154 XftDraw* draw = Infowin->draw;
1159 r.width = Infofnt->wid*len;
1160 r.height = Infofnt->hgt;
1161 XftDrawSetClipRectangles(draw, x, y-Infofnt->asc, &r, 1);
1162 XftDrawRect(draw, &Infoclr->bg, x, y-Infofnt->asc, Infofnt->wid*len, Infofnt->hgt);
1163 XftDrawStringUtf8(draw, &Infoclr->fg, Infofnt->info, x, y,
1164 (FcChar8*)kanji, kp - kanji);
1165 XftDrawSetClip(draw, 0);
1167 XmbDrawImageString(Metadpy->dpy, Infowin->win, Infofnt->info,
1168 Infoclr->gc, x, y, kanji, kp-kanji);
1179 * Painting where text would be
1181 static errr Infofnt_text_non(int x, int y, concptr str, int len)
1186 /*** Find the width ***/
1188 /* Negative length is a flag to count the characters in str */
1189 if (len < 0) len = strlen(str);
1191 /* The total width will be 'len' chars * standard width */
1192 w = len * Infofnt->wid;
1195 /*** Find the X dimensions ***/
1197 /* Line up with x at left edge of column 'x' */
1198 x = x * Infofnt->wid + Infowin->ox;
1201 /*** Find other dimensions ***/
1203 /* Simply do 'Infofnt->hgt' (a single row) high */
1206 /* Simply do "at top" in row 'y' */
1207 y = y * h + Infowin->oy;
1210 /*** Actually 'paint' the area ***/
1212 /* Just do a Fill Rectangle */
1214 XftDrawRect(Infowin->draw, &Infoclr->fg, x, y, w, h);
1216 XFillRectangle(Metadpy->dpy, Infowin->win, Infoclr->gc, x, y, w, h);
1225 /*************************************************************************/
1229 * Angband specific code follows... (ANGBAND)
1234 * Hack -- cursor color
1236 static infoclr *xor;
1239 * Actual color table
1241 static infoclr *clr[256];
1244 * Color info (unused, red, green, blue).
1246 static byte color_table[256][4];
1251 typedef struct term_data term_data;
1254 * A structure for each "term"
1266 /* Tempory storage for overlaying tiles. */
1273 * The number of term data structures
1275 #define MAX_TERM_DATA 8
1278 * The array of term data structures
1280 static term_data data[MAX_TERM_DATA];
1283 /* Use short names for the most commonly used elements of various structures. */
1284 #define DPY (Metadpy->dpy)
1285 #define WIN (Infowin->win)
1288 /* Describe a set of co-ordinates. */
1289 typedef struct co_ord co_ord;
1298 * A special structure to store information about the text currently
1301 typedef struct x11_selection_type x11_selection_type;
1302 struct x11_selection_type
1304 bool select; /* The selection is currently in use. */
1305 bool drawn; /* The selection is currently displayed. */
1306 term *t; /* The window where the selection is found. */
1307 co_ord init; /* The starting co-ordinates. */
1308 co_ord cur; /* The end co-ordinates (the current ones if still copying). */
1309 co_ord old; /* The previous end co-ordinates. */
1310 Time time; /* The time at which the selection was finalised. */
1313 static x11_selection_type s_ptr[1];
1317 * Process a keypress event
1319 * Also appears in "main-xaw.c".
1321 static void react_keypress(XKeyEvent *xev)
1323 int i, n, mc, ms, mo, mx;
1327 XKeyEvent *ev = (XKeyEvent*)(xev);
1335 int valid_keysym = TRUE;
1338 /* Check for "normal" keypresses */
1340 if(Focuswin && Focuswin->xic){
1342 n = XmbLookupString(Focuswin->xic, ev, buf, 125, &ks, &status);
1343 if(status == XBufferOverflow){
1344 printf("Input is too long, and dropped\n");
1347 if(status != XLookupKeySym && status != XLookupBoth){
1348 valid_keysym = FALSE;
1351 n = XLookupString(ev, buf, 125, &ks, NULL);
1354 n = XLookupString(ev, buf, 125, &ks, NULL);
1362 /* Enqueue the normal key(s) */
1363 for (i = 0; buf[i]; i++) Term_keypress(buf[i]);
1370 /* Hack -- Ignore "modifier keys" */
1371 if (IsModifierKey(ks)) return;
1374 /* Hack -- convert into an unsigned int */
1377 /* Extract four "modifier flags" */
1378 mc = (ev->state & ControlMask) ? TRUE : FALSE;
1379 ms = (ev->state & ShiftMask) ? TRUE : FALSE;
1380 mo = (ev->state & Mod1Mask) ? TRUE : FALSE;
1381 mx = (ev->state & Mod2Mask) ? TRUE : FALSE;
1384 /* Normal keys with no modifiers */
1385 if (n && !mo && !mx && !IsSpecialKey(ks))
1387 /* Enqueue the normal key(s) */
1388 for (i = 0; buf[i]; i++) Term_keypress(buf[i]);
1395 /* Handle a few standard keys (bypass modifiers) XXX XXX XXX */
1400 Term_keypress(ESCAPE);
1406 Term_keypress('\r');
1412 Term_keypress('\t');
1418 Term_keypress(0x7f);
1423 Term_keypress('\010');
1429 /* Hack -- Use the KeySym */
1432 sprintf(msg, "%c%s%s%s%s_%lX%c", 31,
1433 mc ? "N" : "", ms ? "S" : "",
1434 mo ? "O" : "", mx ? "M" : "",
1435 (unsigned long)(ks), 13);
1438 /* Hack -- Use the Keycode */
1441 sprintf(msg, "%c%s%s%s%sK_%X%c", 31,
1442 mc ? "N" : "", ms ? "S" : "",
1443 mo ? "O" : "", mx ? "M" : "",
1447 /* Enqueue the "macro trigger" string */
1448 for (i = 0; msg[i]; i++) Term_keypress(msg[i]);
1451 /* Hack -- auto-define macros as needed */
1452 if (n && (macro_find_exact(msg) < 0))
1454 /* Create a macro */
1455 macro_add(msg, buf);
1461 * Find the square a particular pixel is part of.
1463 static void pixel_to_square(int * const x, int * const y,
1464 const int ox, const int oy)
1466 (*x) = (ox - Infowin->ox) / Infofnt->wid;
1467 (*y) = (oy - Infowin->oy) / Infofnt->hgt;
1471 * Find the pixel at the top-left corner of a square.
1473 static void square_to_pixel(int * const x, int * const y,
1474 const int ox, const int oy)
1476 (*x) = ox * Infofnt->wid + Infowin->ox;
1477 (*y) = oy * Infofnt->hgt + Infowin->oy;
1481 * Convert co-ordinates from starting corner/opposite corner to minimum/maximum.
1483 static void sort_co_ord(co_ord *min, co_ord *max,
1484 const co_ord *b, const co_ord *a)
1486 min->x = MIN(a->x, b->x);
1487 min->y = MIN(a->y, b->y);
1488 max->x = MAX(a->x, b->x);
1489 max->y = MAX(a->y, b->y);
1493 * Remove the selection by redrawing it.
1495 static void mark_selection_clear(int x1, int y1, int x2, int y2)
1497 Term_redraw_section(x1,y1,x2,y2);
1501 * Select an area by drawing a grey box around it.
1502 * NB. These two functions can cause flicker as the selection is modified,
1503 * as the game redraws the entire marked section.
1505 static void mark_selection_mark(int x1, int y1, int x2, int y2)
1507 square_to_pixel(&x1, &y1, x1, y1);
1508 square_to_pixel(&x2, &y2, x2, y2);
1510 XftDrawRect(Infowin->draw, &clr[2]->fg, x1, y1, x2-x1+Infofnt->wid - 1, y2-y1+Infofnt->hgt - 1);
1512 XDrawRectangle(Metadpy->dpy, Infowin->win, clr[2]->gc, x1, y1,
1513 x2-x1+Infofnt->wid - 1, y2-y1+Infofnt->hgt - 1);
1518 * Mark a selection by drawing boxes around it (for now).
1520 static void mark_selection(void)
1524 bool draw = s_ptr->select;
1525 bool clear = s_ptr->drawn;
1527 /* Open the correct term if necessary. */
1528 if (s_ptr->t != old) Term_activate(s_ptr->t);
1532 sort_co_ord(&min, &max, &s_ptr->init, &s_ptr->old);
1533 mark_selection_clear(min.x, min.y, max.x, max.y);
1537 sort_co_ord(&min, &max, &s_ptr->init, &s_ptr->cur);
1538 mark_selection_mark(min.x, min.y, max.x, max.y);
1541 /* Finish on the current term. */
1542 if (s_ptr->t != old) Term_activate(old);
1544 s_ptr->old.x = s_ptr->cur.x;
1545 s_ptr->old.y = s_ptr->cur.y;
1546 s_ptr->drawn = s_ptr->select;
1550 * Forget a selection for one reason or another.
1552 static void copy_x11_release(void)
1554 /* Deselect the current selection. */
1555 s_ptr->select = FALSE;
1557 /* Remove its graphical represesntation. */
1562 * Start to select some text on the screen.
1564 static void copy_x11_start(int x, int y)
1566 if (s_ptr->select) copy_x11_release();
1568 /* Remember where the selection started. */
1570 s_ptr->init.x = s_ptr->cur.x = s_ptr->old.x = x;
1571 s_ptr->init.y = s_ptr->cur.y = s_ptr->old.y = y;
1575 * Respond to movement of the mouse when selecting text.
1577 static void copy_x11_cont(int x, int y, unsigned int buttons)
1579 /* Use the nearest square within bounds if the mouse is outside. */
1580 x = MIN(MAX(x, 0), Term->wid-1);
1581 y = MIN(MAX(y, 0), Term->hgt-1);
1583 /* The left mouse button isn't pressed. */
1584 if (~buttons & Button1Mask) return;
1586 /* Not a selection in this window. */
1587 if (s_ptr->t != Term) return;
1589 /* Not enough movement. */
1590 if (x == s_ptr->old.x && y == s_ptr->old.y && s_ptr->select) return;
1592 /* Something is being selected. */
1593 s_ptr->select = TRUE;
1595 /* Track the selection. */
1599 /* Hack - display it inefficiently. */
1604 * Respond to release of the left mouse button by putting the selected text in
1605 * the primary buffer.
1607 static void copy_x11_end(const Time time)
1610 if (!s_ptr->select) return;
1612 /* Not a selection in this window. */
1613 if (s_ptr->t != Term) return;
1615 /* Remember when the selection was finalised. */
1618 /* Acquire the primary selection. */
1619 XSetSelectionOwner(Metadpy->dpy, XA_PRIMARY, Infowin->win, time);
1620 if (XGetSelectionOwner(Metadpy->dpy, XA_PRIMARY) != Infowin->win)
1622 /* Failed to acquire the selection, so forget it. */
1623 /* bell("Failed to acquire primary buffer."); */
1624 s_ptr->select = FALSE;
1630 static Atom xa_targets, xa_timestamp, xa_text, xa_compound_text;
1633 * Set the required variable atoms at start-up to avoid errors later.
1635 static void set_atoms(void)
1637 xa_targets = XInternAtom(DPY, "TARGETS", False);
1638 xa_timestamp = XInternAtom(DPY, "TIMESTAMP", False);
1639 xa_text = XInternAtom(DPY, "TEXT", False);
1640 xa_compound_text = XInternAtom(DPY, "COMPOUND_TEXT", False);
1644 static Atom request_target = 0;
1647 * Send a message to request that the PRIMARY buffer be sent here.
1649 static void paste_x11_request(Atom target, const Time time)
1652 * It's from some sample programs on the web.
1653 * What does it mean? -- XXX
1655 Atom property = XInternAtom(DPY, "__COPY_TEXT", False);
1657 /* Check the owner. */
1658 if (XGetSelectionOwner(DPY, XA_PRIMARY) == None)
1661 /* bell("No selection found."); */
1665 request_target = target;
1667 /* Request the event */
1668 XConvertSelection(DPY, XA_PRIMARY, target, property, WIN, time);
1673 * Add the contents of the PRIMARY buffer to the input queue.
1675 * Hack - This doesn't use the "time" of the event, and so accepts anything a
1676 * client tries to send it.
1678 static void paste_x11_accept(const XSelectionEvent *ptr)
1681 const long offset = 0;
1682 const long length = 32000;
1683 XTextProperty xtextproperty;
1687 * It's from some sample programs on the web.
1688 * What does it mean? -- XXX
1690 Atom property = XInternAtom(DPY, "__COPY_TEXT", False);
1694 if (ptr->property == None)
1696 if (request_target == xa_compound_text)
1698 /* Re-request as STRING */
1699 paste_x11_request(XA_STRING, ptr->time);
1704 plog("Paste failure (remote client could not send).");
1709 if (ptr->selection != XA_PRIMARY)
1711 plog("Paste failure (remote client did not send primary selection).");
1715 if (ptr->target != request_target)
1717 plog("Paste failure (selection in unknown format).");
1722 if (XGetWindowProperty(Metadpy->dpy, Infowin->win, property, offset,
1723 length, TRUE, request_target,
1724 &xtextproperty.encoding,
1725 &xtextproperty.format,
1726 &xtextproperty.nitems,
1728 &xtextproperty.value)
1735 if (request_target == xa_compound_text)
1740 XmbTextPropertyToTextList(DPY, &xtextproperty, &list, &count);
1746 for (i = 0; i < count; i++)
1748 /* Paste the text. */
1749 err = type_string(list[i], 0);
1754 /* Free the string */
1755 XFreeStringList(list);
1758 else /* if (request_target == XA_STRING) */
1760 /* Paste the text. */
1761 err = type_string((char *)xtextproperty.value, xtextproperty.nitems);
1764 /* Free the data pasted. */
1765 XFree(xtextproperty.value);
1770 plog("Paste failure (too much text selected).");
1776 * Add a character to a string in preparation for sending it to another
1777 * client as a STRING.
1778 * This doesn't change anything, as clients tend not to have difficulty in
1779 * receiving this format (although the standard specifies a restricted set).
1780 * Strings do not have a colour.
1782 static bool paste_x11_send_text(XSelectionRequestEvent *rq)
1792 /* Too old, or incorrect call. */
1793 if (rq->time < s_ptr->time) return FALSE;
1795 /* Work out which way around to paste. */
1796 sort_co_ord(&min, &max, &s_ptr->init, &s_ptr->cur);
1799 if (XGetSelectionOwner(DPY, XA_PRIMARY) != WIN)
1801 /* bell("Someone stole my selection!"); */
1805 /* Delete the old value of the property. */
1806 XDeleteProperty(DPY, rq->requestor, rq->property);
1808 for (n = 0, y = 0; y < Term->hgt; y++)
1813 if (y < min.y) continue;
1814 if (y > max.y) break;
1816 for (l = 0, x = 0; x < Term->wid; x++)
1819 if (x > max.x) break;
1821 /* Find the character. */
1822 Term_what(x, y, &a, &c);
1824 if (1 == kanji) kanji = 2;
1825 else if (iskanji(c)) kanji = 1;
1828 if (x < min.x) continue;
1831 * A single kanji character was divided in two...
1832 * Delete the garbage.
1834 if ((2 == kanji && x == min.x) ||
1835 (1 == kanji && x == max.x))
1838 if (x > max.x) break;
1839 if (x < min.x) continue;
1841 /* Find the character. */
1842 Term_what(x, y, &a, &c);
1850 /* Ignore trailing spaces */
1851 while (buf[l-1] == ' ') l--;
1853 /* Terminate all line unless it's single line. */
1863 list[n++] = (char *)string_make(buf);
1866 /* End of the list */
1870 if (rq->target == XA_STRING)
1872 for (n = 0; list[n]; n++)
1874 /* Send the (non-empty) string. */
1875 XChangeProperty(DPY, rq->requestor, rq->property, rq->target, 8,
1876 PropModeAppend, (unsigned char *)list[n], strlen(list[n]));
1880 else if (rq->target == xa_text ||
1881 rq->target == xa_compound_text)
1883 XTextProperty text_prop;
1884 XICCEncodingStyle style;
1886 if (rq->target == xa_text)
1887 style = XStdICCTextStyle;
1888 else /* if (rq->target == xa_compound_text) */
1889 style = XCompoundTextStyle;
1892 XmbTextListToTextProperty(DPY, list, n, style, &text_prop))
1894 /* Send the compound text */
1895 XChangeProperty(DPY,
1904 /* Free the data. */
1905 XFree(text_prop.value);
1909 /* Free the list of strings */
1910 for (n = 0; list[n]; n++)
1912 string_free(list[n]);
1919 * Send some text requested by another X client.
1921 static void paste_x11_send(XSelectionRequestEvent *rq)
1924 XSelectionEvent *ptr = &(event.xselection);
1926 /* Set the event parameters. */
1927 ptr->type = SelectionNotify;
1928 ptr->property = rq->property;
1929 ptr->display = rq->display;
1930 ptr->requestor = rq->requestor;
1931 ptr->selection = rq->selection;
1932 ptr->target = rq->target;
1933 ptr->time = rq->time;
1935 /* Paste the appropriate information for each target type.
1936 * Note that this currently rejects MULTIPLE targets.
1939 if (rq->target == XA_STRING ||
1940 rq->target == xa_text ||
1941 rq->target == xa_compound_text)
1943 if (!paste_x11_send_text(rq))
1944 ptr->property = None;
1946 else if (rq->target == xa_targets)
1948 Atom target_list[4];
1949 target_list[0] = XA_STRING;
1950 target_list[1] = xa_text;
1951 target_list[2] = xa_compound_text;
1952 target_list[3] = xa_targets;
1953 XChangeProperty(DPY, rq->requestor, rq->property, rq->target,
1954 (8 * sizeof(target_list[0])), PropModeReplace,
1955 (unsigned char *)target_list,
1956 (sizeof(target_list) / sizeof(target_list[0])));
1958 else if (rq->target == xa_timestamp)
1960 XChangeProperty(DPY, rq->requestor, rq->property, rq->target,
1961 (8 * sizeof(Time)), PropModeReplace,
1962 (unsigned char *)s_ptr->time, 1);
1966 ptr->property = None;
1969 /* Send whatever event we're left with. */
1970 XSendEvent(DPY, rq->requestor, FALSE, NoEventMask, &event);
1975 * Handle various events conditional on presses of a mouse button.
1977 static void handle_button(Time time, int x, int y, int button,
1980 /* The co-ordinates are only used in Angband format. */
1981 pixel_to_square(&x, &y, x, y);
1983 if (press && button == 1) copy_x11_start(x, y);
1984 if (!press && button == 1) copy_x11_end(time);
1985 if (!press && button == 2) paste_x11_request(xa_compound_text, time);
1992 static errr CheckEvent(bool wait)
1994 term_data *old_td = (term_data*)(Term->data);
1996 XEvent xev_body, *xev = &xev_body;
1998 term_data *td = NULL;
1999 infowin *iwin = NULL;
2008 /* Do not wait unless requested */
2009 if (!wait && !XPending(Metadpy->dpy)) return (1);
2012 * Hack - redraw the selection, if needed.
2013 * This doesn't actually check that one of its squares was drawn to,
2014 * only that this may have happened.
2016 if (s_ptr->select && !s_ptr->drawn) mark_selection();
2018 /* Load the Event */
2019 XNextEvent(Metadpy->dpy, xev);
2022 } while (XFilterEvent(xev, xev->xany.window));
2025 /* Notice new keymaps */
2026 if (xev->type == MappingNotify)
2028 XRefreshKeyboardMapping(&xev->xmapping);
2033 /* Scan the windows */
2034 for (i = 0; i < MAX_TERM_DATA; i++)
2036 if (!data[i].win) continue;
2037 if (xev->xany.window == data[i].win->win)
2045 /* Unknown window */
2046 if (!td || !iwin) return (0);
2049 /* Hack -- activate the Term */
2050 Term_activate(&td->t);
2052 /* Hack -- activate the window */
2056 /* Switch on the Type */
2062 bool press = (xev->type == ButtonPress);
2064 /* Where is the mouse */
2065 int x = xev->xbutton.x;
2066 int y = xev->xbutton.y;
2070 /* Which button is involved */
2071 if (xev->xbutton.button == Button1) z = 1;
2072 else if (xev->xbutton.button == Button2) z = 2;
2073 else if (xev->xbutton.button == Button3) z = 3;
2074 else if (xev->xbutton.button == Button4) z = 4;
2075 else if (xev->xbutton.button == Button5) z = 5;
2079 handle_button(xev->xbutton.time, x, y, z, press);
2094 /* Where is the mouse */
2095 int x = xev->xmotion.x;
2096 int y = xev->xmotion.y;
2097 unsigned int z = xev->xmotion.state;
2099 /* Convert to co-ordinates Angband understands. */
2100 pixel_to_square(&x, &y, x, y);
2102 /* Highlight the current square, if appropriate. */
2103 /* highlight_square(window, y, x); */
2105 /* Alter the selection if appropriate. */
2106 copy_x11_cont(x, y, z);
2113 case SelectionNotify:
2115 paste_x11_accept(&(xev->xselection));
2119 case SelectionRequest:
2121 paste_x11_send(&(xev->xselectionrequest));
2125 case SelectionClear:
2127 s_ptr->select = FALSE;
2140 /* Hack -- use "old" term */
2141 Term_activate(&old_td->t);
2143 /* Process the key */
2144 react_keypress(&(xev->xkey));
2153 /* Ignore "extra" exposes */
2154 /*if (xev->xexpose.count) break;*/
2156 /* Clear the window */
2159 x1 = (xev->xexpose.x - Infowin->ox)/Infofnt->wid;
2160 x2 = (xev->xexpose.x + xev->xexpose.width -
2161 Infowin->ox)/Infofnt->wid;
2163 y1 = (xev->xexpose.y - Infowin->oy)/Infofnt->hgt;
2164 y2 = (xev->xexpose.y + xev->xexpose.height -
2165 Infowin->oy)/Infofnt->hgt;
2167 Term_redraw_section(x1, y1, x2, y2);
2177 Infowin->mapped = 1;
2178 Term->mapped_flag = TRUE;
2184 Infowin->mapped = 0;
2185 Term->mapped_flag = FALSE;
2189 /* Move and/or Resize */
2190 case ConfigureNotify:
2192 int cols, rows, wid, hgt;
2194 int ox = Infowin->ox;
2195 int oy = Infowin->oy;
2197 /* Save the new Window Parms */
2198 Infowin->x = xev->xconfigure.x;
2199 Infowin->y = xev->xconfigure.y;
2200 Infowin->w = xev->xconfigure.width;
2201 Infowin->h = xev->xconfigure.height;
2203 /* Determine "proper" number of rows/cols */
2204 cols = ((Infowin->w - (ox + ox)) / td->fnt->wid);
2205 rows = ((Infowin->h - (oy + oy)) / td->fnt->hgt);
2207 /* Hack -- minimal size */
2208 if (cols < 1) cols = 1;
2209 if (rows < 1) rows = 1;
2213 /* Hack the main window must be at least 80x24 */
2214 if (cols < 80) cols = 80;
2215 if (rows < 24) rows = 24;
2218 /* Desired size of window */
2219 wid = cols * td->fnt->wid + (ox + ox);
2220 hgt = rows * td->fnt->hgt + (oy + oy);
2222 /* Resize the Term (if needed) */
2223 Term_resize(cols, rows);
2225 /* Resize the windows if any "change" is needed */
2226 if ((Infowin->w != wid) || (Infowin->h != hgt))
2229 Infowin_set(td->win);
2230 Infowin_resize(wid, hgt);
2239 XSetICFocus(iwin->xic);
2247 XUnsetICFocus(iwin->xic);
2249 /* Focuswin = NULL;*/
2256 /* Hack -- Activate the old term */
2257 Term_activate(&old_td->t);
2259 /* Hack -- Activate the proper window */
2260 Infowin_set(old_td->win);
2269 * An array of sound file names
2271 static concptr sound_file[SOUND_MAX];
2274 * Check for existance of a file
2276 static bool check_file(concptr s)
2280 fff = fopen(s, "r");
2281 if (!fff) return (FALSE);
2290 static void init_sound(void)
2295 char dir_xtra_sound[1024];
2297 /* Build the "sound" path */
2298 path_build(dir_xtra_sound, sizeof(dir_xtra_sound), ANGBAND_DIR_XTRA, "sound");
2300 /* Prepare the sounds */
2301 for (i = 1; i < SOUND_MAX; i++)
2303 /* Extract name of sound file */
2304 sprintf(wav, "%s.wav", angband_sound_name[i]);
2306 /* Access the sound */
2307 path_build(buf, sizeof(buf), dir_xtra_sound, wav);
2309 /* Save the sound filename, if it exists */
2310 if (check_file(buf)) sound_file[i] = string_make(buf);
2317 * Hack -- make a sound
2319 static errr Term_xtra_x11_sound(int v)
2323 /* Sound disabled */
2324 if (!use_sound) return (1);
2327 if ((v < 0) || (v >= SOUND_MAX)) return (1);
2330 if (!sound_file[v]) return (1);
2332 sprintf(buf,"./playwave.sh %s\n", sound_file[v]);
2334 return (system(buf) < 0);
2340 * Handle "activation" of a term
2342 static errr Term_xtra_x11_level(int v)
2344 term_data *td = (term_data*)(Term->data);
2346 /* Handle "activate" */
2349 /* Activate the window */
2350 Infowin_set(td->win);
2352 /* Activate the font */
2353 Infofnt_set(td->fnt);
2364 static errr Term_xtra_x11_react(void)
2370 /* Check the colors */
2371 for (i = 0; i < 256; i++)
2373 if ((color_table[i][0] != angband_color_table[i][0]) ||
2374 (color_table[i][1] != angband_color_table[i][1]) ||
2375 (color_table[i][2] != angband_color_table[i][2]) ||
2376 (color_table[i][3] != angband_color_table[i][3]))
2380 /* Save new values */
2381 color_table[i][0] = angband_color_table[i][0];
2382 color_table[i][1] = angband_color_table[i][1];
2383 color_table[i][2] = angband_color_table[i][2];
2384 color_table[i][3] = angband_color_table[i][3];
2387 pixel = create_pixel(Metadpy->dpy,
2392 /* Change the foreground */
2393 Infoclr_set(clr[i]);
2394 Infoclr_change_fg(pixel);
2405 * Handle a "special request"
2407 static errr Term_xtra_x11(int n, int v)
2409 /* Handle a subset of the legal requests */
2413 case TERM_XTRA_NOISE: Metadpy_do_beep(); return (0);
2415 /* Make a special sound */
2416 case TERM_XTRA_SOUND: return (Term_xtra_x11_sound(v));
2418 /* Flush the output XXX XXX */
2420 case TERM_XTRA_FRESH: Metadpy_update(1, 1, 0); return (0);
2422 case TERM_XTRA_FRESH: Metadpy_update(1, 0, 0); return (0);
2425 /* Process random events XXX */
2426 case TERM_XTRA_BORED: return (CheckEvent(0));
2428 /* Process Events XXX */
2429 case TERM_XTRA_EVENT: return (CheckEvent(v));
2431 /* Flush the events XXX */
2432 case TERM_XTRA_FLUSH: while (!CheckEvent(FALSE)); return (0);
2434 /* Handle change in the "level" */
2435 case TERM_XTRA_LEVEL: return (Term_xtra_x11_level(v));
2437 /* Clear the screen */
2438 case TERM_XTRA_CLEAR: Infowin_wipe(); s_ptr->drawn = FALSE; return (0);
2440 /* Delay for some milliseconds */
2441 case TERM_XTRA_DELAY: usleep(1000 * v); return (0);
2443 /* React to changes */
2444 case TERM_XTRA_REACT: return (Term_xtra_x11_react());
2453 * Draw the cursor as an inverted rectangle.
2455 * Consider a rectangular outline like "main-mac.c". XXX XXX
2457 static errr Term_curs_x11(int x, int y)
2462 XftDrawRect(Infowin->draw, &xor->fg,
2463 x * Infofnt->wid + Infowin->ox,
2464 y * Infofnt->hgt + Infowin->oy,
2465 Infofnt->wid - 1, Infofnt->hgt - 1);
2466 XftDrawRect(Infowin->draw, &xor->fg,
2467 x * Infofnt->wid + Infowin->ox + 1,
2468 y * Infofnt->hgt + Infowin->oy + 1,
2469 Infofnt->wid - 3, Infofnt->hgt - 3);
2471 XDrawRectangle(Metadpy->dpy, Infowin->win, xor->gc,
2472 x * Infofnt->wid + Infowin->ox,
2473 y * Infofnt->hgt + Infowin->oy,
2474 Infofnt->wid - 1, Infofnt->hgt - 1);
2475 XDrawRectangle(Metadpy->dpy, Infowin->win, xor->gc,
2476 x * Infofnt->wid + Infowin->ox + 1,
2477 y * Infofnt->hgt + Infowin->oy + 1,
2478 Infofnt->wid - 3, Infofnt->hgt - 3);
2483 /* Draw the cursor */
2486 /* Hilite the cursor character */
2487 Infofnt_text_non(x, y, " ", 1);
2496 * Draw the double width cursor
2498 static errr Term_bigcurs_x11(int x, int y)
2503 XftDrawRect(Infowin->draw, &xor->fg,
2504 x * Infofnt->wid + Infowin->ox,
2505 y * Infofnt->hgt + Infowin->oy,
2506 Infofnt->twid - 1, Infofnt->hgt - 1);
2507 XftDrawRect(Infowin->draw, &xor->fg,
2508 x * Infofnt->wid + Infowin->ox + 1,
2509 y * Infofnt->hgt + Infowin->oy + 1,
2510 Infofnt->twid - 3, Infofnt->hgt - 3);
2512 XDrawRectangle(Metadpy->dpy, Infowin->win, xor->gc,
2513 x * Infofnt->wid + Infowin->ox,
2514 y * Infofnt->hgt + Infowin->oy,
2515 Infofnt->twid - 1, Infofnt->hgt - 1);
2516 XDrawRectangle(Metadpy->dpy, Infowin->win, xor->gc,
2517 x * Infofnt->wid + Infowin->ox + 1,
2518 y * Infofnt->hgt + Infowin->oy + 1,
2519 Infofnt->twid - 3, Infofnt->hgt - 3);
2524 /* Draw the cursor */
2527 /* Hilite the cursor character */
2528 Infofnt_text_non(x, y, " ", 2);
2536 * Erase some characters.
2538 static errr Term_wipe_x11(int x, int y, int n)
2540 /* Erase (use black) */
2541 Infoclr_set(clr[TERM_DARK]);
2543 /* Mega-Hack -- Erase some space */
2544 Infofnt_text_non(x, y, "", n);
2546 /* Redraw the selection if any, as it may have been obscured. (later) */
2547 s_ptr->drawn = FALSE;
2555 * Draw some textual characters.
2557 static errr Term_text_x11(TERM_LEN x, TERM_LEN y, int n, TERM_COLOR a, concptr s)
2560 Infoclr_set(clr[a]);
2563 Infofnt_text_std(x, y, s, n);
2565 /* Redraw the selection if any, as it may have been obscured. (later) */
2566 s_ptr->drawn = FALSE;
2575 * Draw some graphical characters.
2577 static errr Term_pict_x11(TERM_LEN x, TERM_LEN y, int n, const TERM_COLOR *ap, const char *cp, const TERM_COLOR *tap, const char *tcp)
2590 unsigned long pixel, blank;
2592 term_data *td = (term_data*)(Term->data);
2597 /* Add in affect of window boundaries */
2601 for (i = 0; i < n; ++i, x += td->fnt->wid)
2606 /* For extra speed - cache these values */
2607 x1 = (c&0x7F) * td->fnt->twid;
2608 y1 = (a&0x7F) * td->fnt->hgt;
2610 /* Illegal tile index */
2611 if (td->tiles->width < x1 + td->fnt->wid ||
2612 td->tiles->height < y1 + td->fnt->hgt)
2614 /* Draw black square */
2615 XFillRectangle(Metadpy->dpy, td->win->win, clr[0]->gc,
2617 td->fnt->twid, td->fnt->hgt);
2619 /* Skip drawing tile */
2626 /* For extra speed - cache these values */
2627 x2 = (tc&0x7F) * td->fnt->twid;
2628 y2 = (ta&0x7F) * td->fnt->hgt;
2630 /* Optimise the common case */
2631 if (((x1 == x2) && (y1 == y2)) ||
2632 !(((byte)ta & 0x80) && ((byte)tc & 0x80)) ||
2633 td->tiles->width < x2 + td->fnt->wid ||
2634 td->tiles->height < y2 + td->fnt->hgt)
2636 /* Draw object / terrain */
2637 XPutImage(Metadpy->dpy, td->win->win,
2642 td->fnt->twid, td->fnt->hgt);
2647 /* Mega Hack^2 - assume the top left corner is "black" */
2648 blank = XGetPixel(td->tiles, 0, td->fnt->hgt * 6);
2650 for (k = 0; k < td->fnt->twid; k++)
2652 for (l = 0; l < td->fnt->hgt; l++)
2654 /* If mask set... */
2655 if ((pixel = XGetPixel(td->tiles, x1 + k, y1 + l)) == blank)
2657 /* Output from the terrain */
2658 pixel = XGetPixel(td->tiles, x2 + k, y2 + l);
2661 /* Store into the temp storage. */
2662 XPutPixel(td->TmpImage, k, l, pixel);
2667 /* Draw to screen */
2669 XPutImage(Metadpy->dpy, td->win->win,
2673 td->fnt->twid, td->fnt->hgt);
2677 /* Redraw the selection if any, as it may have been obscured. (later) */
2678 s_ptr->drawn = FALSE;
2686 static void IMDestroyCallback(XIM, XPointer, XPointer);
2689 IMInstantiateCallback(Display *display, XPointer unused1, XPointer unused2)
2692 XIMCallback ximcallback;
2693 XIMStyles *xim_styles = NULL;
2700 xim = XOpenIM(display, NULL, NULL, NULL);
2702 printf("can't open IM\n");
2706 /* initialize destroy callback */
2707 ximcallback.callback = IMDestroyCallback;
2708 ximcallback.client_data = NULL;
2709 XSetIMValues(xim, XNDestroyCallback, &ximcallback, NULL);
2711 /* set style (only "Root" is supported yet...) */
2712 XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL);
2713 for (i = 0; i < xim_styles->count_styles; i++){
2714 if(xim_styles->supported_styles[i] == (XIMPreeditNothing | XIMStatusNothing)) break;
2716 if(i >= xim_styles->count_styles){
2717 printf("Sorry, your IM does not support 'Root' preedit style...\n");
2725 for (i = 0; i < MAX_TERM_DATA; i++)
2727 infowin *iwin = data[i].win;
2728 if (!iwin) continue;
2729 iwin->xic = XCreateIC(xim, XNInputStyle, (XIMPreeditNothing | XIMStatusNothing), XNClientWindow, iwin->win, XNFocusWindow, iwin->win, NULL);
2731 printf("Can't create input context for Term%d\n", i);
2734 if(XGetICValues(iwin->xic, XNFilterEvents, &iwin->xic_mask, NULL) != NULL){
2735 /* printf("Can't get XNFilterEvents\n"); */
2736 iwin->xic_mask = 0L;
2738 XSelectInput(Metadpy->dpy, iwin->win, iwin->mask | iwin->xic_mask);
2744 static void IMDestroyCallback(XIM xim, XPointer client_data, XPointer call_data)
2752 if (call_data == NULL){
2753 XRegisterIMInstantiateCallback(Metadpy->dpy, NULL, NULL, NULL, IMInstantiateCallback, NULL);
2756 for(i = 0; i < MAX_TERM_DATA; i++)
2758 infowin *iwin = data[i].win;
2761 XSelectInput(Metadpy->dpy, iwin->win, iwin->mask);
2762 iwin->xic_mask = 0L;
2767 Metadpy->xim = NULL;
2772 * Initialize a term_data
2774 static errr term_data_init(term_data *td, int i)
2778 concptr name = angband_term_name[i];
2808 /* Window specific font name */
2809 sprintf(buf, "ANGBAND_X11_FONT_%d", i);
2811 /* Check environment for that font */
2814 /* Check environment for "base" font */
2815 if (!font) font = getenv("ANGBAND_X11_FONT");
2817 /* No environment variables, use default font */
2824 font = DEFAULT_X11_FONT_0;
2829 font = DEFAULT_X11_FONT_1;
2834 font = DEFAULT_X11_FONT_2;
2839 font = DEFAULT_X11_FONT_3;
2844 font = DEFAULT_X11_FONT_4;
2849 font = DEFAULT_X11_FONT_5;
2854 font = DEFAULT_X11_FONT_6;
2859 font = DEFAULT_X11_FONT_7;
2864 font = DEFAULT_X11_FONT;
2869 /* Window specific location (x) */
2870 sprintf(buf, "ANGBAND_X11_AT_X_%d", i);
2872 x = (str != NULL) ? atoi(str) : -1;
2874 /* Window specific location (y) */
2875 sprintf(buf, "ANGBAND_X11_AT_Y_%d", i);
2877 y = (str != NULL) ? atoi(str) : -1;
2880 /* Window specific cols */
2881 sprintf(buf, "ANGBAND_X11_COLS_%d", i);
2883 val = (str != NULL) ? atoi(str) : -1;
2884 if (val > 0) cols = val;
2886 /* Window specific rows */
2887 sprintf(buf, "ANGBAND_X11_ROWS_%d", i);
2889 val = (str != NULL) ? atoi(str) : -1;
2890 if (val > 0) rows = val;
2892 /* Hack the main window must be at least 80x24 */
2895 if (cols < 80) cols = 80;
2896 if (rows < 24) rows = 24;
2899 /* Window specific inner border offset (ox) */
2900 sprintf(buf, "ANGBAND_X11_IBOX_%d", i);
2902 val = (str != NULL) ? atoi(str) : -1;
2903 if (val > 0) ox = val;
2905 /* Window specific inner border offset (oy) */
2906 sprintf(buf, "ANGBAND_X11_IBOY_%d", i);
2908 val = (str != NULL) ? atoi(str) : -1;
2909 if (val > 0) oy = val;
2912 /* Prepare the standard font */
2913 MAKE(td->fnt, infofnt);
2914 Infofnt_set(td->fnt);
2915 Infofnt_init_data(font);
2917 /* Hack -- key buffer size */
2918 num = ((i == 0) ? 1024 : 16);
2920 /* Assume full size windows */
2921 wid = cols * td->fnt->wid + (ox + ox);
2922 hgt = rows * td->fnt->hgt + (oy + oy);
2924 /* Create a top-window */
2925 MAKE(td->win, infowin);
2926 Infowin_set(td->win);
2927 Infowin_init_top(x, y, wid, hgt, 0,
2928 Metadpy->fg, Metadpy->bg);
2930 /* Ask for certain events */
2931 #if defined(USE_XIM)
2932 Infowin_set_mask(ExposureMask | StructureNotifyMask | KeyPressMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask | FocusChangeMask);
2934 Infowin_set_mask(ExposureMask | StructureNotifyMask | KeyPressMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask);
2937 /* Set the window name */
2938 Infowin_set_name(name);
2940 /* Save the inner border */
2944 /* Make Class Hints */
2945 ch = XAllocClassHint();
2947 if (ch == NULL) quit("XAllocClassHint failed");
2949 strcpy(res_name, name);
2950 res_name[0] = FORCELOWER(res_name[0]);
2951 ch->res_name = res_name;
2953 strcpy(res_class, "Angband");
2954 ch->res_class = res_class;
2956 XSetClassHint(Metadpy->dpy, Infowin->win, ch);
2958 /* Make Size Hints */
2959 sh = XAllocSizeHints();
2962 if (sh == NULL) quit("XAllocSizeHints failed");
2964 /* Main window has a differing minimum size */
2967 /* Main window min size is 80x24 */
2968 sh->flags = PMinSize | PMaxSize;
2969 sh->min_width = 80 * td->fnt->wid + (ox + ox);
2970 sh->min_height = 24 * td->fnt->hgt + (oy + oy);
2971 sh->max_width = 255 * td->fnt->wid + (ox + ox);
2972 sh->max_height = 255 * td->fnt->hgt + (oy + oy);
2975 /* Other windows can be shrunk to 1x1 */
2979 sh->flags = PMinSize | PMaxSize;
2980 sh->min_width = td->fnt->wid + (ox + ox);
2981 sh->min_height = td->fnt->hgt + (oy + oy);
2982 sh->max_width = 256 * td->fnt->wid + (ox + ox);
2983 sh->max_height = 256 * td->fnt->hgt + (oy + oy);
2986 /* Resize increment */
2987 sh->flags |= PResizeInc;
2988 sh->width_inc = td->fnt->wid;
2989 sh->height_inc = td->fnt->hgt;
2991 /* Base window size */
2992 sh->flags |= PBaseSize;
2993 sh->base_width = (ox + ox);
2994 sh->base_height = (oy + oy);
2996 /* Use the size hints */
2997 XSetWMNormalHints(Metadpy->dpy, Infowin->win, sh);
2999 /* Map the window */
3004 wh = XAllocWMHints();
3005 if(wh == NULL) quit("XAllocWMHints failed");
3006 wh->flags = InputHint;
3008 XSetWMHints(Metadpy->dpy, Infowin->win, wh);
3011 /* Move the window to requested location */
3012 if ((x >= 0) && (y >= 0)) Infowin_impell(x, y);
3015 /* Initialize the term */
3016 term_init(t, cols, rows, num);
3018 /* Use a "soft" cursor */
3019 t->soft_cursor = TRUE;
3021 /* Erase with "white space" */
3022 t->attr_blank = TERM_WHITE;
3023 t->char_blank = ' ';
3026 t->xtra_hook = Term_xtra_x11;
3027 t->curs_hook = Term_curs_x11;
3028 t->bigcurs_hook = Term_bigcurs_x11;
3029 t->wipe_hook = Term_wipe_x11;
3030 t->text_hook = Term_text_x11;
3035 /* Activate (important) */
3044 * Initialization function for an "X11" module to Angband
3046 errr init_x11(int argc, char *argv[])
3050 concptr dpy_name = "";
3055 char filename[1024];
3064 for (i = 1; i < argc; i++)
3066 if (prefix(argv[i], "-d"))
3068 dpy_name = &argv[i][2];
3073 if (prefix(argv[i], "-s"))
3075 smoothRescaling = FALSE;
3079 if (prefix(argv[i], "-a"))
3081 arg_graphics = GRAPHICS_ADAM_BOLT;
3085 if (prefix(argv[i], "-o"))
3087 arg_graphics = GRAPHICS_ORIGINAL;
3092 if (prefix(argv[i], "-b"))
3094 arg_bigtile = use_bigtile = TRUE;
3098 if (prefix(argv[i], "-n"))
3100 num_term = atoi(&argv[i][2]);
3101 if (num_term > MAX_TERM_DATA) num_term = MAX_TERM_DATA;
3102 else if (num_term < 1) num_term = 1;
3106 if (prefix(argv[i], "--"))
3112 plog_fmt("Ignoring option: %s", argv[i]);
3118 /* Get locale information from environment variables */
3119 setlocale(LC_ALL, "");
3121 #ifdef DEFAULT_LOCALE
3122 if(!strcmp(setlocale(LC_ALL, NULL), "C")){
3123 printf("try default locale \"%s\"\n", DEFAULT_LOCALE);
3124 setlocale(LC_ALL, DEFAULT_LOCALE);
3128 if(!strcmp(setlocale(LC_ALL, NULL), "C"))
3130 printf("WARNING: Locale is not supported. Non-english font may be displayed incorrectly.\n");
3133 if(!XSupportsLocale()){
3134 printf("can't support locale in X\n");
3135 setlocale(LC_ALL, "C");
3138 /* Set locale to "C" without using environment variables */
3139 setlocale(LC_ALL, "C");
3142 #endif /* USE_LOCALE */
3145 /* Init the Metadpy if possible */
3146 if (Metadpy_init_name(dpy_name)) return (-1);
3149 /* Prepare cursor color */
3152 Infoclr_init_ppn(Metadpy->fg, Metadpy->bg, "xor", 0);
3155 /* Prepare normal colors */
3156 for (i = 0; i < 256; ++i)
3160 MAKE(clr[i], infoclr);
3162 Infoclr_set(clr[i]);
3164 /* Acquire Angband colors */
3165 color_table[i][0] = angband_color_table[i][0];
3166 color_table[i][1] = angband_color_table[i][1];
3167 color_table[i][2] = angband_color_table[i][2];
3168 color_table[i][3] = angband_color_table[i][3];
3170 /* Default to monochrome */
3171 pixel = ((i == 0) ? Metadpy->bg : Metadpy->fg);
3177 pixel = create_pixel(Metadpy->dpy,
3183 /* Initialize the color */
3184 Infoclr_init_ppn(pixel, Metadpy->bg, "cpy", 0);
3188 /* Prepare required atoms. */
3192 /* Initialize the windows */
3193 for (i = 0; i < num_term; i++)
3195 term_data *td = &data[i];
3197 /* Initialize the term_data */
3198 term_data_init(td, i);
3200 /* Save global entry */
3201 angband_term[i] = Term;
3204 /* Raise the "Angband" window */
3205 Infowin_set(data[0].win);
3208 /* Activate the "Angband" window screen */
3209 Term_activate(&data[0].t);
3214 p = XSetLocaleModifiers("");
3216 p = XSetLocaleModifiers("@im=");
3218 /* printf("XMODIFIERS=\"%s\"\n", p); */
3220 XRegisterIMInstantiateCallback(Metadpy->dpy, NULL, NULL, NULL, IMInstantiateCallback, NULL);
3223 /* initialize sound */
3224 if (arg_sound) init_sound();
3228 switch (arg_graphics)
3230 case GRAPHICS_ORIGINAL:
3231 /* Try the "8x8.bmp" file */
3232 path_build(filename, sizeof(filename), ANGBAND_DIR_XTRA, "graf/8x8.bmp");
3234 /* Use the "8x8.bmp" file if it exists */
3235 if (0 == fd_close(fd_open(filename, O_RDONLY)))
3238 use_graphics = TRUE;
3240 pict_wid = pict_hgt = 8;
3242 ANGBAND_GRAF = "old";
3247 case GRAPHICS_ADAM_BOLT:
3248 /* Try the "16x16.bmp" file */
3249 path_build(filename, sizeof(filename), ANGBAND_DIR_XTRA, "graf/16x16.bmp");
3251 /* Use the "16x16.bmp" file if it exists */
3252 if (0 == fd_close(fd_open(filename, O_RDONLY)))
3255 use_graphics = TRUE;
3257 pict_wid = pict_hgt = 16;
3259 ANGBAND_GRAF = "new";
3268 Display *dpy = Metadpy->dpy;
3272 /* Load the graphical tiles */
3273 tiles_raw = ReadBMP(dpy, filename);
3275 /* Initialize the windows */
3276 for (i = 0; i < num_term; i++)
3278 term_data *td = &data[i];
3283 t->pict_hook = Term_pict_x11;
3285 /* Use graphics sometimes */
3286 t->higher_pict = TRUE;
3290 ResizeImage(dpy, tiles_raw,
3292 td->fnt->twid, td->fnt->hgt);
3295 /* Initialize the transparency masks */
3296 for (i = 0; i < num_term; i++)
3298 term_data *td = &data[i];
3300 int depth = DefaultDepth(dpy, DefaultScreen(dpy));
3301 Visual *visual = DefaultVisual(dpy, DefaultScreen(dpy));
3305 /* Determine total bytes needed for image */
3307 jj = (depth - 1) >> 2;
3308 while (jj >>= 1) ii <<= 1;
3309 total = td->fnt->twid * td->fnt->hgt * ii;
3312 TmpData = (char *)malloc(total);
3314 td->TmpImage = XCreateImage(dpy,visual,depth,
3315 ZPixmap, 0, TmpData,
3316 td->fnt->twid, td->fnt->hgt, 8, 0);
3320 /* Free tiles_raw? XXX XXX */
3322 #endif /* ! USE_XFT */
3328 #endif /* USE_X11 */