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 &
103 * Available graphic modes
105 #define GRAPHICS_NONE 0
106 #define GRAPHICS_ORIGINAL 1
107 #define GRAPHICS_ADAM_BOLT 2
108 #define GRAPHICS_HENGBAND 3
112 #ifndef __MAKEDEPEND__
113 #include <X11/Xlib.h>
114 #include <X11/Xutil.h>
115 #include <X11/keysym.h>
116 #include <X11/keysymdef.h>
118 #include <X11/Xlocale.h>
120 #include <X11/Xatom.h>
121 #endif /* __MAKEDEPEND__ */
125 * Include some helpful X11 code.
127 #include "maid-x11.c"
133 * 1) On a monochrome (or "fake-monochrome") display, all colors
134 * will be "cast" to "fg," except for the bg color, which is,
135 * obviously, cast to "bg". Thus, one can ignore this setting.
137 * 2) Because of the inner functioning of the color allocation
138 * routines, colors may be specified as (a) a typical color name,
139 * (b) a hexidecimal color specification (preceded by a pound sign),
140 * or (c) by strings such as "fg", "bg", "zg".
142 * 3) Due to the workings of the init routines, many colors
143 * may also be dealt with by their actual pixel values. Note that
144 * the pixel with all bits set is "zg = (1<<metadpy->depth)-1", which
145 * is not necessarily either black or white.
148 /**** Generic Types ****/
151 * An X11 pixell specifier
153 typedef unsigned long Pixell;
156 * The structures defined below
158 typedef struct metadpy metadpy;
159 typedef struct infowin infowin;
160 typedef struct infoclr infoclr;
161 typedef struct infofnt infofnt;
165 * A structure summarizing a given Display.
167 * - The Display itself
168 * - The default Screen for the display
169 * - The virtual root (usually just the root)
170 * - The default colormap (from a macro)
172 * - The "name" of the display
174 * - The socket to listen to for events
176 * - The width of the display screen (from a macro)
177 * - The height of the display screen (from a macro)
178 * - The bit depth of the display screen (from a macro)
180 * - The black Pixell (from a macro)
181 * - The white Pixell (from a macro)
183 * - The background Pixell (default: black)
184 * - The foreground Pixell (default: white)
185 * - The maximal Pixell (Equals: ((2 ^ depth)-1), is usually ugly)
187 * - Bit Flag: Force all colors to black and white (default: !color)
188 * - Bit Flag: Allow the use of color (default: depth > 1)
189 * - Bit Flag: We created 'dpy', and so should nuke it when done.
224 * A Structure summarizing Window Information.
226 * I assume that a window is at most 30000 pixels on a side.
227 * I assume that the root windw is also at most 30000 square.
230 * - The current Input Event Mask
232 * - The location of the window
233 * - The width, height of the window
234 * - The border width of this window
236 * - Byte: 1st Extra byte
238 * - Bit Flag: This window is currently Mapped
239 * - Bit Flag: This window needs to be redrawn
240 * - Bit Flag: This window has been resized
242 * - Bit Flag: We should nuke 'win' when done with it
244 * - Bit Flag: 1st extra flag
245 * - Bit Flag: 2nd extra flag
246 * - Bit Flag: 3rd extra flag
247 * - Bit Flag: 4th extra flag
285 * A Structure summarizing Operation+Color Information
287 * - The actual GC corresponding to this info
289 * - The Foreground Pixell Value
290 * - The Background Pixell Value
292 * - Num (0-15): The operation code (As in Clear, Xor, etc)
293 * - Bit Flag: The GC is in stipple mode
294 * - Bit Flag: Destroy 'gc' at Nuke time.
311 * A Structure to Hold Font Information
313 * - The 'XFontStruct*' (yields the 'Font')
317 * - The default character width
318 * - The default character height
319 * - The default character ascent
321 * - Byte: Pixel offset used during fake mono
323 * - Flag: Force monospacing via 'wid'
324 * - Flag: Nuke info when done
345 /**** Generic Macros ****/
349 /* Set current metadpy (Metadpy) to 'M' */
350 #define Metadpy_set(M) \
354 /* Initialize 'M' using Display 'D' */
355 #define Metadpy_init_dpy(D) \
356 Metadpy_init_2(D,cNULL)
358 /* Initialize 'M' using a Display named 'N' */
359 #define Metadpy_init_name(N) \
360 Metadpy_init_2((Display*)(NULL),N)
362 /* Initialize 'M' using the standard Display */
363 #define Metadpy_init() \
364 Metadpy_init_name("")
367 /* Init an infowin by giving father as an (info_win*) (or NULL), and data */
368 #define Infowin_init_dad(D,X,Y,W,H,B,FG,BG) \
369 Infowin_init_data(((D) ? ((D)->win) : (Window)(None)), \
373 /* Init a top level infowin by pos,size,bord,Colors */
374 #define Infowin_init_top(X,Y,W,H,B,FG,BG) \
375 Infowin_init_data(None,X,Y,W,H,B,FG,BG)
378 /* Request a new standard window by giving Dad infowin and X,Y,W,H */
379 #define Infowin_init_std(D,X,Y,W,H,B) \
380 Infowin_init_dad(D,X,Y,W,H,B,Metadpy->fg,Metadpy->bg)
383 /* Set the current Infowin */
384 #define Infowin_set(I) \
388 /* Set the current Infoclr */
389 #define Infoclr_set(C) \
393 #define Infoclr_init_ppo(F,B,O,M) \
394 Infoclr_init_data(F,B,O,M)
396 #define Infoclr_init_cco(F,B,O,M) \
397 Infoclr_init_ppo(Infoclr_Pixell(F),Infoclr_Pixell(B),O,M)
399 #define Infoclr_init_ppn(F,B,O,M) \
400 Infoclr_init_ppo(F,B,Infoclr_Opcode(O),M)
402 #define Infoclr_init_ccn(F,B,O,M) \
403 Infoclr_init_cco(F,B,Infoclr_Opcode(O),M)
406 /* Set the current infofnt */
407 #define Infofnt_set(I) \
411 /* Errr: Expose Infowin */
412 #define Infowin_expose() \
413 (!(Infowin->redraw = 1))
415 /* Errr: Unxpose Infowin */
416 #define Infowin_unexpose() \
417 (Infowin->redraw = 0)
421 /**** Generic Globals ****/
425 * The "default" values
427 static metadpy metadpy_default;
431 * The "current" variables
433 static metadpy *Metadpy = &metadpy_default;
434 static infowin *Infowin = (infowin*)(NULL);
436 static infowin *Focuswin = (infowin*)(NULL);
438 static infoclr *Infoclr = (infoclr*)(NULL);
439 static infofnt *Infofnt = (infofnt*)(NULL);
441 /**** Generic code ****/
444 * Init the current metadpy, with various initialization stuff.
447 * dpy: The Display* to use (if NULL, create it)
448 * name: The name of the Display (if NULL, the current)
451 * If 'name' is NULL, but 'dpy' is set, extract name from dpy
452 * If 'dpy' is NULL, then Create the named Display
453 * If 'name' is NULL, and so is 'dpy', use current Display
455 * Return -1 if no Display given, and none can be opened.
457 static errr Metadpy_init_2(Display *dpy, concptr name)
459 metadpy *m = Metadpy;
461 /*** Open the display if needed ***/
463 /* If no Display given, attempt to Create one */
466 /* Attempt to open the display */
467 dpy = XOpenDisplay(name);
470 if (!dpy) return (-1);
472 /* We will have to nuke it when done */
476 /* Since the Display was given, use it */
479 /* We will not have to nuke it when done */
484 /*** Save some information ***/
486 /* Save the Display itself */
489 /* Get the Screen and Virtual Root Window */
490 m->screen = DefaultScreenOfDisplay(dpy);
491 m->root = RootWindowOfScreen(m->screen);
493 /* Get the default colormap */
494 m->cmap = DefaultColormapOfScreen(m->screen);
496 /* Extract the true name of the display */
497 m->name = DisplayString(dpy);
500 m->fd = ConnectionNumber(Metadpy->dpy);
502 /* Save the Size and Depth of the screen */
503 m->width = WidthOfScreen(m->screen);
504 m->height = HeightOfScreen(m->screen);
505 m->depth = DefaultDepthOfScreen(m->screen);
507 /* Save the Standard Colors */
508 m->black = BlackPixelOfScreen(m->screen);
509 m->white = WhitePixelOfScreen(m->screen);
511 /*** Make some clever Guesses ***/
513 /* Guess at the desired 'fg' and 'bg' Pixell's */
517 /* Calculate the Maximum allowed Pixel value. */
518 m->zg = (1 << m->depth) - 1;
520 /* Save various default Flag Settings */
521 m->color = ((m->depth > 1) ? 1 : 0);
522 m->mono = ((m->color) ? 0 : 1);
524 /* Return "success" */
530 * General Flush/ Sync/ Discard routine
532 static errr Metadpy_update(int flush, int sync, int discard)
534 /* Flush if desired */
535 if (flush) XFlush(Metadpy->dpy);
537 /* Sync if desired, using 'discard' */
538 if (sync) XSync(Metadpy->dpy, discard);
548 static errr Metadpy_do_beep(void)
550 /* Make a simple beep */
551 XBell(Metadpy->dpy, 100);
559 * Set the name (in the title bar) of Infowin
561 static errr Infowin_set_name(concptr name)
568 st = XStringListToTextProperty(&bp, 1, &tp);
569 if (st) XSetWMName(Metadpy->dpy, Infowin->win, &tp);
575 * Prepare a new 'infowin'.
577 static errr Infowin_prepare(Window xid)
579 infowin *iwin = Infowin;
582 XWindowAttributes xwa;
584 unsigned int w, h, b, d;
589 /* Check For Error XXX Extract some ACTUAL data from 'xid' */
590 XGetGeometry(Metadpy->dpy, xid, &tmp_win, &x, &y, &w, &h, &b, &d);
592 /* Apply the above info */
599 /* Check Error XXX Extract some more ACTUAL data */
600 XGetWindowAttributes(Metadpy->dpy, xid, &xwa);
602 /* Apply the above info */
603 iwin->mask = xwa.your_event_mask;
604 iwin->mapped = ((xwa.map_state == IsUnmapped) ? 0 : 1);
606 /* And assume that we are exposed */
615 * Init an infowin by giving some data.
618 * dad: The Window that should own this Window (if any)
619 * x,y: The position of this Window
620 * w,h: The size of this Window
621 * b,d: The border width and pixel depth
624 * If 'dad == None' assume 'dad == root'
626 static errr Infowin_init_data(Window dad, int x, int y, int w, int h,
627 int b, Pixell fg, Pixell bg)
632 (void)WIPE(Infowin, infowin);
635 /*** Error Check XXX ***/
638 /*** Create the Window 'xid' from data ***/
640 /* What happened here? XXX XXX XXX */
642 /* If no parent given, depend on root */
645 /* Create the Window XXX Error Check */
646 xid = XCreateSimpleWindow(Metadpy->dpy, dad, x, y, w, h, b, fg, bg);
648 /* Start out selecting No events */
649 XSelectInput(Metadpy->dpy, xid, 0L);
652 /*** Prepare the new infowin ***/
654 /* Mark it as nukable */
657 /* Attempt to Initialize the infowin */
658 return (Infowin_prepare(xid));
664 * Modify the event mask of an Infowin
666 static errr Infowin_set_mask(long mask)
668 /* Save the new setting */
669 Infowin->mask = mask;
671 /* Execute the Mapping */
672 XSelectInput(Metadpy->dpy, Infowin->win, Infowin->mask);
680 * Request that Infowin be mapped
682 static errr Infowin_map(void)
684 /* Execute the Mapping */
685 XMapWindow(Metadpy->dpy, Infowin->win);
693 * Request that Infowin be raised
695 static errr Infowin_raise(void)
697 /* Raise towards visibility */
698 XRaiseWindow(Metadpy->dpy, Infowin->win);
706 * Request that Infowin be moved to a new location
708 static errr Infowin_impell(int x, int y)
710 /* Execute the request */
711 XMoveWindow(Metadpy->dpy, Infowin->win, x, y);
721 static errr Infowin_resize(int w, int h)
723 /* Execute the request */
724 XResizeWindow(Metadpy->dpy, Infowin->win, w, h);
732 * Visually clear Infowin
734 static errr Infowin_wipe(void)
736 /* Execute the request */
737 XClearWindow(Metadpy->dpy, Infowin->win);
745 * A NULL terminated pair list of legal "operation names"
747 * Pairs of values, first is texttual name, second is the string
748 * holding the decimal value that the operation corresponds to.
750 static concptr opcode_pairs[] =
769 "+copyInverted", "12",
777 * Parse a word into an operation "code"
780 * str: A string, hopefully representing an Operation
783 * 0-15: if 'str' is a valid Operation
784 * -1: if 'str' could not be parsed
786 static int Infoclr_Opcode(concptr str)
790 /* Scan through all legal operation names */
791 for (i = 0; opcode_pairs[i*2]; ++i)
793 /* Is this the right oprname? */
794 if (streq(opcode_pairs[i*2], str))
796 /* Convert the second element in the pair into a Code */
797 return (atoi(opcode_pairs[i*2+1]));
801 /* The code was not found, return -1 */
807 * Initialize an infoclr with some data
810 * fg: The Pixell for the requested Foreground (see above)
811 * bg: The Pixell for the requested Background (see above)
812 * op: The Opcode for the requested Operation (see above)
813 * stip: The stipple mode
815 static errr Infoclr_init_data(Pixell fg, Pixell bg, int op, int stip)
817 infoclr *iclr = Infoclr;
821 unsigned long gc_mask;
825 /*** Simple error checking of opr and clr ***/
827 /* Check the 'Pixells' for realism */
828 if (bg > Metadpy->zg) return (-1);
829 if (fg > Metadpy->zg) return (-1);
831 /* Check the data for trueness */
832 if ((op < 0) || (op > 15)) return (-1);
835 /*** Create the requested 'GC' ***/
837 /* Assign the proper GC function */
840 /* Assign the proper GC background */
843 /* Assign the proper GC foreground */
846 /* Hack -- Handle XOR (xor is code 6) by hacking bg and fg */
847 if (op == 6) gcv.background = 0;
848 if (op == 6) gcv.foreground = (bg ^ fg);
850 /* Assign the proper GC Fill Style */
851 gcv.fill_style = (stip ? FillStippled : FillSolid);
853 /* Turn off 'Give exposure events for pixmap copying' */
854 gcv.graphics_exposures = False;
856 /* Set up the GC mask */
857 gc_mask = (GCFunction | GCBackground | GCForeground |
858 GCFillStyle | GCGraphicsExposures);
860 /* Create the GC detailed above */
861 gc = XCreateGC(Metadpy->dpy, Metadpy->root, gc_mask, &gcv);
866 /* Wipe the iclr clean */
867 (void)WIPE(iclr, infoclr);
872 /* Nuke it when done */
875 /* Assign the parms */
879 iclr->stip = stip ? 1 : 0;
888 * Change the 'fg' for an infoclr
891 * fg: The Pixell for the requested Foreground (see above)
893 static errr Infoclr_change_fg(Pixell fg)
895 infoclr *iclr = Infoclr;
898 /*** Simple error checking of opr and clr ***/
900 /* Check the 'Pixells' for realism */
901 if (fg > Metadpy->zg) return (-1);
907 XSetForeground(Metadpy->dpy, iclr->gc, fg);
915 * Prepare a new 'infofnt'
917 static errr Infofnt_prepare(XFontSet info)
919 infofnt *ifnt = Infofnt;
922 XFontStruct **fontinfo;
925 int ascent, descent, width;
927 /* Assign the struct */
930 n_fonts = XFontsOfFontSet(info, &fontinfo, &fontname);
932 ascent = descent = width = 0;
933 while(n_fonts-- > 0){
934 cs = &((*fontinfo)->max_bounds);
935 if(ascent < (*fontinfo)->ascent) ascent = (*fontinfo)->ascent;
936 if(descent < (*fontinfo)->descent) descent = (*fontinfo)->descent;
937 if(((*fontinfo)->max_byte1) > 0){
938 /* 多バイト文字の場合は幅半分(端数切り上げ)で評価する */
939 if(width < (cs->width+1)/2) width = (cs->width+1)/2;
941 if(width < cs->width) width = cs->width;
947 ifnt->hgt = ascent + descent;
951 ifnt->twid = 2 * ifnt->wid;
953 ifnt->twid = ifnt->wid;
964 * Init an infofnt by its Name
967 * name: The name of the requested Font
969 static void Infofnt_init_data(concptr name)
977 /*** Load the info Fresh, using the name ***/
979 /* If the name is not given, report an error */
980 if (!name || !*name) quit("Missing font!");
982 /* Attempt to load the font */
983 info = XCreateFontSet(Metadpy->dpy, name, &missing_list, &missing_count, &default_font);
984 if(missing_count > 0){
985 printf("missing font(s): \n");
986 while(missing_count-- > 0){
987 printf("\t%s\n", missing_list[missing_count]);
989 XFreeStringList(missing_list);
992 /* The load failed, try to recover */
993 if (!info) quit_fmt("Failed to find font:\"%s\"", name);
995 /*** Init the font ***/
998 (void)WIPE(Infofnt, infofnt);
1000 /* Attempt to prepare it */
1001 if (Infofnt_prepare(info))
1004 XFreeFontSet(Metadpy->dpy, info);
1007 quit_fmt("Failed to prepare font:\"%s\"", name);
1010 /* Save a copy of the font name */
1011 Infofnt->name = string_make(name);
1013 /* Mark it as nukable */
1021 static errr Infofnt_text_std(int x, int y, concptr str, int len)
1026 /*** Do a brief info analysis ***/
1028 /* Do nothing if the string is null */
1029 if (!str || !*str) return (-1);
1031 /* Get the length of the string */
1032 if (len < 0) len = strlen(str);
1034 /*** Decide where to place the string, vertically ***/
1036 /* Ignore Vertical Justifications */
1037 y = (y * Infofnt->hgt) + Infofnt->asc + Infowin->oy;
1040 /*** Decide where to place the string, horizontally ***/
1042 /* Line up with x at left edge of column 'x' */
1043 x = (x * Infofnt->wid) + Infowin->ox;
1046 /*** Actually draw 'str' onto the infowin ***/
1048 /*** Handle the fake mono we can enforce on fonts ***/
1050 /* Monotize the font */
1053 /* Do each character */
1054 for (i = 0; i < len; ++i)
1056 /* Note that the Infoclr is set up to contain the Infofnt */
1057 XDrawImageString(Metadpy->dpy, Infowin->win, Infoclr->gc,
1058 x + i * Infofnt->wid + Infofnt->off, y, str + i, 1);
1062 /* Assume monoospaced font */
1065 /* Note that the Infoclr is set up to contain the Infofnt */
1066 iconv_t cd = iconv_open("UTF-8", "EUC-JP");
1068 size_t outlen = len * 2;
1069 char *kanji = malloc(outlen);
1070 char *sp; char *kp = kanji;
1072 my_strcpy(sbuf, str, sizeof(sbuf));
1074 iconv(cd, &sp, &inlen, &kp, &outlen);
1077 XmbDrawImageString(Metadpy->dpy, Infowin->win, Infofnt->info,
1078 Infoclr->gc, x, y, kanji, kp-kanji);
1088 * Painting where text would be
1090 static errr Infofnt_text_non(int x, int y, concptr str, int len)
1095 /*** Find the width ***/
1097 /* Negative length is a flag to count the characters in str */
1098 if (len < 0) len = strlen(str);
1100 /* The total width will be 'len' chars * standard width */
1101 w = len * Infofnt->wid;
1104 /*** Find the X dimensions ***/
1106 /* Line up with x at left edge of column 'x' */
1107 x = x * Infofnt->wid + Infowin->ox;
1110 /*** Find other dimensions ***/
1112 /* Simply do 'Infofnt->hgt' (a single row) high */
1115 /* Simply do "at top" in row 'y' */
1116 y = y * h + Infowin->oy;
1119 /*** Actually 'paint' the area ***/
1121 /* Just do a Fill Rectangle */
1122 XFillRectangle(Metadpy->dpy, Infowin->win, Infoclr->gc, x, y, w, h);
1130 /*************************************************************************/
1134 * Angband specific code follows... (ANGBAND)
1139 * Hack -- cursor color
1141 static infoclr *xor;
1144 * Actual color table
1146 static infoclr *clr[256];
1149 * Color info (unused, red, green, blue).
1151 static byte color_table[256][4];
1156 typedef struct term_data term_data;
1159 * A structure for each "term"
1170 /* Tempory storage for overlaying tiles. */
1176 * The number of term data structures
1178 #define MAX_TERM_DATA 8
1181 * The array of term data structures
1183 static term_data data[MAX_TERM_DATA];
1186 /* Use short names for the most commonly used elements of various structures. */
1187 #define DPY (Metadpy->dpy)
1188 #define WIN (Infowin->win)
1191 /* Describe a set of co-ordinates. */
1192 typedef struct co_ord co_ord;
1201 * A special structure to store information about the text currently
1204 typedef struct x11_selection_type x11_selection_type;
1205 struct x11_selection_type
1207 bool select; /* The selection is currently in use. */
1208 bool drawn; /* The selection is currently displayed. */
1209 term *t; /* The window where the selection is found. */
1210 co_ord init; /* The starting co-ordinates. */
1211 co_ord cur; /* The end co-ordinates (the current ones if still copying). */
1212 co_ord old; /* The previous end co-ordinates. */
1213 Time time; /* The time at which the selection was finalised. */
1216 static x11_selection_type s_ptr[1];
1220 * Process a keypress event
1222 * Also appears in "main-xaw.c".
1224 static void react_keypress(XKeyEvent *xev)
1226 int i, n, mc, ms, mo, mx;
1230 XKeyEvent *ev = (XKeyEvent*)(xev);
1238 int valid_keysym = TRUE;
1241 /* Check for "normal" keypresses */
1243 if(Focuswin && Focuswin->xic){
1245 n = XmbLookupString(Focuswin->xic, ev, buf, 125, &ks, &status);
1246 if(status == XBufferOverflow){
1247 printf("Input is too long, and dropped\n");
1250 if(status != XLookupKeySym && status != XLookupBoth){
1251 valid_keysym = FALSE;
1254 n = XLookupString(ev, buf, 125, &ks, NULL);
1257 n = XLookupString(ev, buf, 125, &ks, NULL);
1265 /* Enqueue the normal key(s) */
1266 for (i = 0; buf[i]; i++) Term_keypress(buf[i]);
1273 /* Hack -- Ignore "modifier keys" */
1274 if (IsModifierKey(ks)) return;
1277 /* Hack -- convert into an unsigned int */
1280 /* Extract four "modifier flags" */
1281 mc = (ev->state & ControlMask) ? TRUE : FALSE;
1282 ms = (ev->state & ShiftMask) ? TRUE : FALSE;
1283 mo = (ev->state & Mod1Mask) ? TRUE : FALSE;
1284 mx = (ev->state & Mod2Mask) ? TRUE : FALSE;
1287 /* Normal keys with no modifiers */
1288 if (n && !mo && !mx && !IsSpecialKey(ks))
1290 /* Enqueue the normal key(s) */
1291 for (i = 0; buf[i]; i++) Term_keypress(buf[i]);
1298 /* Handle a few standard keys (bypass modifiers) XXX XXX XXX */
1303 Term_keypress(ESCAPE);
1309 Term_keypress('\r');
1315 Term_keypress('\t');
1321 Term_keypress(0x7f);
1326 Term_keypress('\010');
1332 /* Hack -- Use the KeySym */
1335 sprintf(msg, "%c%s%s%s%s_%lX%c", 31,
1336 mc ? "N" : "", ms ? "S" : "",
1337 mo ? "O" : "", mx ? "M" : "",
1338 (unsigned long)(ks), 13);
1341 /* Hack -- Use the Keycode */
1344 sprintf(msg, "%c%s%s%s%sK_%X%c", 31,
1345 mc ? "N" : "", ms ? "S" : "",
1346 mo ? "O" : "", mx ? "M" : "",
1350 /* Enqueue the "macro trigger" string */
1351 for (i = 0; msg[i]; i++) Term_keypress(msg[i]);
1354 /* Hack -- auto-define macros as needed */
1355 if (n && (macro_find_exact(msg) < 0))
1357 /* Create a macro */
1358 macro_add(msg, buf);
1364 * Find the square a particular pixel is part of.
1366 static void pixel_to_square(int * const x, int * const y,
1367 const int ox, const int oy)
1369 (*x) = (ox - Infowin->ox) / Infofnt->wid;
1370 (*y) = (oy - Infowin->oy) / Infofnt->hgt;
1374 * Find the pixel at the top-left corner of a square.
1376 static void square_to_pixel(int * const x, int * const y,
1377 const int ox, const int oy)
1379 (*x) = ox * Infofnt->wid + Infowin->ox;
1380 (*y) = oy * Infofnt->hgt + Infowin->oy;
1384 * Convert co-ordinates from starting corner/opposite corner to minimum/maximum.
1386 static void sort_co_ord(co_ord *min, co_ord *max,
1387 const co_ord *b, const co_ord *a)
1389 min->x = MIN(a->x, b->x);
1390 min->y = MIN(a->y, b->y);
1391 max->x = MAX(a->x, b->x);
1392 max->y = MAX(a->y, b->y);
1396 * Remove the selection by redrawing it.
1398 static void mark_selection_clear(int x1, int y1, int x2, int y2)
1400 Term_redraw_section(x1,y1,x2,y2);
1404 * Select an area by drawing a grey box around it.
1405 * NB. These two functions can cause flicker as the selection is modified,
1406 * as the game redraws the entire marked section.
1408 static void mark_selection_mark(int x1, int y1, int x2, int y2)
1410 square_to_pixel(&x1, &y1, x1, y1);
1411 square_to_pixel(&x2, &y2, x2, y2);
1412 XDrawRectangle(Metadpy->dpy, Infowin->win, clr[2]->gc, x1, y1,
1413 x2-x1+Infofnt->wid - 1, y2-y1+Infofnt->hgt - 1);
1417 * Mark a selection by drawing boxes around it (for now).
1419 static void mark_selection(void)
1423 bool draw = s_ptr->select;
1424 bool clear = s_ptr->drawn;
1426 /* Open the correct term if necessary. */
1427 if (s_ptr->t != old) Term_activate(s_ptr->t);
1431 sort_co_ord(&min, &max, &s_ptr->init, &s_ptr->old);
1432 mark_selection_clear(min.x, min.y, max.x, max.y);
1436 sort_co_ord(&min, &max, &s_ptr->init, &s_ptr->cur);
1437 mark_selection_mark(min.x, min.y, max.x, max.y);
1440 /* Finish on the current term. */
1441 if (s_ptr->t != old) Term_activate(old);
1443 s_ptr->old.x = s_ptr->cur.x;
1444 s_ptr->old.y = s_ptr->cur.y;
1445 s_ptr->drawn = s_ptr->select;
1449 * Forget a selection for one reason or another.
1451 static void copy_x11_release(void)
1453 /* Deselect the current selection. */
1454 s_ptr->select = FALSE;
1456 /* Remove its graphical represesntation. */
1461 * Start to select some text on the screen.
1463 static void copy_x11_start(int x, int y)
1465 if (s_ptr->select) copy_x11_release();
1467 /* Remember where the selection started. */
1469 s_ptr->init.x = s_ptr->cur.x = s_ptr->old.x = x;
1470 s_ptr->init.y = s_ptr->cur.y = s_ptr->old.y = y;
1474 * Respond to movement of the mouse when selecting text.
1476 static void copy_x11_cont(int x, int y, unsigned int buttons)
1478 /* Use the nearest square within bounds if the mouse is outside. */
1479 x = MIN(MAX(x, 0), Term->wid-1);
1480 y = MIN(MAX(y, 0), Term->hgt-1);
1482 /* The left mouse button isn't pressed. */
1483 if (~buttons & Button1Mask) return;
1485 /* Not a selection in this window. */
1486 if (s_ptr->t != Term) return;
1488 /* Not enough movement. */
1489 if (x == s_ptr->old.x && y == s_ptr->old.y && s_ptr->select) return;
1491 /* Something is being selected. */
1492 s_ptr->select = TRUE;
1494 /* Track the selection. */
1498 /* Hack - display it inefficiently. */
1503 * Respond to release of the left mouse button by putting the selected text in
1504 * the primary buffer.
1506 static void copy_x11_end(const Time time)
1509 if (!s_ptr->select) return;
1511 /* Not a selection in this window. */
1512 if (s_ptr->t != Term) return;
1514 /* Remember when the selection was finalised. */
1517 /* Acquire the primary selection. */
1518 XSetSelectionOwner(Metadpy->dpy, XA_PRIMARY, Infowin->win, time);
1519 if (XGetSelectionOwner(Metadpy->dpy, XA_PRIMARY) != Infowin->win)
1521 /* Failed to acquire the selection, so forget it. */
1522 /* bell("Failed to acquire primary buffer."); */
1523 s_ptr->select = FALSE;
1529 static Atom xa_targets, xa_timestamp, xa_text, xa_compound_text;
1532 * Set the required variable atoms at start-up to avoid errors later.
1534 static void set_atoms(void)
1536 xa_targets = XInternAtom(DPY, "TARGETS", False);
1537 xa_timestamp = XInternAtom(DPY, "TIMESTAMP", False);
1538 xa_text = XInternAtom(DPY, "TEXT", False);
1539 xa_compound_text = XInternAtom(DPY, "COMPOUND_TEXT", False);
1543 static Atom request_target = 0;
1546 * Send a message to request that the PRIMARY buffer be sent here.
1548 static void paste_x11_request(Atom target, const Time time)
1551 * It's from some sample programs on the web.
1552 * What does it mean? -- XXX
1554 Atom property = XInternAtom(DPY, "__COPY_TEXT", False);
1556 /* Check the owner. */
1557 if (XGetSelectionOwner(DPY, XA_PRIMARY) == None)
1560 /* bell("No selection found."); */
1564 request_target = target;
1566 /* Request the event */
1567 XConvertSelection(DPY, XA_PRIMARY, target, property, WIN, time);
1572 * Add the contents of the PRIMARY buffer to the input queue.
1574 * Hack - This doesn't use the "time" of the event, and so accepts anything a
1575 * client tries to send it.
1577 static void paste_x11_accept(const XSelectionEvent *ptr)
1580 const long offset = 0;
1581 const long length = 32000;
1582 XTextProperty xtextproperty;
1586 * It's from some sample programs on the web.
1587 * What does it mean? -- XXX
1589 Atom property = XInternAtom(DPY, "__COPY_TEXT", False);
1593 if (ptr->property == None)
1595 if (request_target == xa_compound_text)
1597 /* Re-request as STRING */
1598 paste_x11_request(XA_STRING, ptr->time);
1603 plog("Paste failure (remote client could not send).");
1608 if (ptr->selection != XA_PRIMARY)
1610 plog("Paste failure (remote client did not send primary selection).");
1614 if (ptr->target != request_target)
1616 plog("Paste failure (selection in unknown format).");
1621 if (XGetWindowProperty(Metadpy->dpy, Infowin->win, property, offset,
1622 length, TRUE, request_target,
1623 &xtextproperty.encoding,
1624 &xtextproperty.format,
1625 &xtextproperty.nitems,
1627 &xtextproperty.value)
1634 if (request_target == xa_compound_text)
1639 XmbTextPropertyToTextList(DPY, &xtextproperty, &list, &count);
1645 for (i = 0; i < count; i++)
1647 /* Paste the text. */
1648 err = type_string(list[i], 0);
1653 /* Free the string */
1654 XFreeStringList(list);
1657 else /* if (request_target == XA_STRING) */
1659 /* Paste the text. */
1660 err = type_string((char *)xtextproperty.value, xtextproperty.nitems);
1663 /* Free the data pasted. */
1664 XFree(xtextproperty.value);
1669 plog("Paste failure (too much text selected).");
1675 * Add a character to a string in preparation for sending it to another
1676 * client as a STRING.
1677 * This doesn't change anything, as clients tend not to have difficulty in
1678 * receiving this format (although the standard specifies a restricted set).
1679 * Strings do not have a colour.
1681 static bool paste_x11_send_text(XSelectionRequestEvent *rq)
1691 /* Too old, or incorrect call. */
1692 if (rq->time < s_ptr->time) return FALSE;
1694 /* Work out which way around to paste. */
1695 sort_co_ord(&min, &max, &s_ptr->init, &s_ptr->cur);
1698 if (XGetSelectionOwner(DPY, XA_PRIMARY) != WIN)
1700 /* bell("Someone stole my selection!"); */
1704 /* Delete the old value of the property. */
1705 XDeleteProperty(DPY, rq->requestor, rq->property);
1707 for (n = 0, y = 0; y < Term->hgt; y++)
1712 if (y < min.y) continue;
1713 if (y > max.y) break;
1715 for (l = 0, x = 0; x < Term->wid; x++)
1718 if (x > max.x) break;
1720 /* Find the character. */
1721 Term_what(x, y, &a, &c);
1723 if (1 == kanji) kanji = 2;
1724 else if (iskanji(c)) kanji = 1;
1727 if (x < min.x) continue;
1730 * A single kanji character was divided in two...
1731 * Delete the garbage.
1733 if ((2 == kanji && x == min.x) ||
1734 (1 == kanji && x == max.x))
1737 if (x > max.x) break;
1738 if (x < min.x) continue;
1740 /* Find the character. */
1741 Term_what(x, y, &a, &c);
1749 /* Ignore trailing spaces */
1750 while (buf[l-1] == ' ') l--;
1752 /* Terminate all line unless it's single line. */
1762 list[n++] = (char *)string_make(buf);
1765 /* End of the list */
1769 if (rq->target == XA_STRING)
1771 for (n = 0; list[n]; n++)
1773 /* Send the (non-empty) string. */
1774 XChangeProperty(DPY, rq->requestor, rq->property, rq->target, 8,
1775 PropModeAppend, (unsigned char *)list[n], strlen(list[n]));
1779 else if (rq->target == xa_text ||
1780 rq->target == xa_compound_text)
1782 XTextProperty text_prop;
1783 XICCEncodingStyle style;
1785 if (rq->target == xa_text)
1786 style = XStdICCTextStyle;
1787 else /* if (rq->target == xa_compound_text) */
1788 style = XCompoundTextStyle;
1791 XmbTextListToTextProperty(DPY, list, n, style, &text_prop))
1793 /* Send the compound text */
1794 XChangeProperty(DPY,
1803 /* Free the data. */
1804 XFree(text_prop.value);
1808 /* Free the list of strings */
1809 for (n = 0; list[n]; n++)
1811 string_free(list[n]);
1818 * Send some text requested by another X client.
1820 static void paste_x11_send(XSelectionRequestEvent *rq)
1823 XSelectionEvent *ptr = &(event.xselection);
1825 /* Set the event parameters. */
1826 ptr->type = SelectionNotify;
1827 ptr->property = rq->property;
1828 ptr->display = rq->display;
1829 ptr->requestor = rq->requestor;
1830 ptr->selection = rq->selection;
1831 ptr->target = rq->target;
1832 ptr->time = rq->time;
1834 /* Paste the appropriate information for each target type.
1835 * Note that this currently rejects MULTIPLE targets.
1838 if (rq->target == XA_STRING ||
1839 rq->target == xa_text ||
1840 rq->target == xa_compound_text)
1842 if (!paste_x11_send_text(rq))
1843 ptr->property = None;
1845 else if (rq->target == xa_targets)
1847 Atom target_list[4];
1848 target_list[0] = XA_STRING;
1849 target_list[1] = xa_text;
1850 target_list[2] = xa_compound_text;
1851 target_list[3] = xa_targets;
1852 XChangeProperty(DPY, rq->requestor, rq->property, rq->target,
1853 (8 * sizeof(target_list[0])), PropModeReplace,
1854 (unsigned char *)target_list,
1855 (sizeof(target_list) / sizeof(target_list[0])));
1857 else if (rq->target == xa_timestamp)
1859 XChangeProperty(DPY, rq->requestor, rq->property, rq->target,
1860 (8 * sizeof(Time)), PropModeReplace,
1861 (unsigned char *)s_ptr->time, 1);
1865 ptr->property = None;
1868 /* Send whatever event we're left with. */
1869 XSendEvent(DPY, rq->requestor, FALSE, NoEventMask, &event);
1874 * Handle various events conditional on presses of a mouse button.
1876 static void handle_button(Time time, int x, int y, int button,
1879 /* The co-ordinates are only used in Angband format. */
1880 pixel_to_square(&x, &y, x, y);
1882 if (press && button == 1) copy_x11_start(x, y);
1883 if (!press && button == 1) copy_x11_end(time);
1884 if (!press && button == 2) paste_x11_request(xa_compound_text, time);
1891 static errr CheckEvent(bool wait)
1893 term_data *old_td = (term_data*)(Term->data);
1895 XEvent xev_body, *xev = &xev_body;
1897 term_data *td = NULL;
1898 infowin *iwin = NULL;
1906 /* Do not wait unless requested */
1907 if (!wait && !XPending(Metadpy->dpy)) return (1);
1910 * Hack - redraw the selection, if needed.
1911 * This doesn't actually check that one of its squares was drawn to,
1912 * only that this may have happened.
1914 if (s_ptr->select && !s_ptr->drawn) mark_selection();
1916 /* Load the Event */
1917 XNextEvent(Metadpy->dpy, xev);
1920 if (XFilterEvent(xev, xev->xany.window)
1922 goto redo_checkevent;
1926 /* Notice new keymaps */
1927 if (xev->type == MappingNotify)
1929 XRefreshKeyboardMapping(&xev->xmapping);
1934 /* Scan the windows */
1935 for (i = 0; i < MAX_TERM_DATA; i++)
1937 if (!data[i].win) continue;
1938 if (xev->xany.window == data[i].win->win)
1946 /* Unknown window */
1947 if (!td || !iwin) return (0);
1950 /* Hack -- activate the Term */
1951 Term_activate(&td->t);
1953 /* Hack -- activate the window */
1957 /* Switch on the Type */
1963 bool press = (xev->type == ButtonPress);
1965 /* Where is the mouse */
1966 int x = xev->xbutton.x;
1967 int y = xev->xbutton.y;
1971 /* Which button is involved */
1972 if (xev->xbutton.button == Button1) z = 1;
1973 else if (xev->xbutton.button == Button2) z = 2;
1974 else if (xev->xbutton.button == Button3) z = 3;
1975 else if (xev->xbutton.button == Button4) z = 4;
1976 else if (xev->xbutton.button == Button5) z = 5;
1980 handle_button(xev->xbutton.time, x, y, z, press);
1995 /* Where is the mouse */
1996 int x = xev->xmotion.x;
1997 int y = xev->xmotion.y;
1998 unsigned int z = xev->xmotion.state;
2000 /* Convert to co-ordinates Angband understands. */
2001 pixel_to_square(&x, &y, x, y);
2003 /* Highlight the current square, if appropriate. */
2004 /* highlight_square(window, y, x); */
2006 /* Alter the selection if appropriate. */
2007 copy_x11_cont(x, y, z);
2014 case SelectionNotify:
2016 paste_x11_accept(&(xev->xselection));
2020 case SelectionRequest:
2022 paste_x11_send(&(xev->xselectionrequest));
2026 case SelectionClear:
2028 s_ptr->select = FALSE;
2041 /* Hack -- use "old" term */
2042 Term_activate(&old_td->t);
2044 /* Process the key */
2045 react_keypress(&(xev->xkey));
2054 /* Ignore "extra" exposes */
2055 /*if (xev->xexpose.count) break;*/
2057 /* Clear the window */
2060 x1 = (xev->xexpose.x - Infowin->ox)/Infofnt->wid;
2061 x2 = (xev->xexpose.x + xev->xexpose.width -
2062 Infowin->ox)/Infofnt->wid;
2064 y1 = (xev->xexpose.y - Infowin->oy)/Infofnt->hgt;
2065 y2 = (xev->xexpose.y + xev->xexpose.height -
2066 Infowin->oy)/Infofnt->hgt;
2068 Term_redraw_section(x1, y1, x2, y2);
2078 Infowin->mapped = 1;
2079 Term->mapped_flag = TRUE;
2085 Infowin->mapped = 0;
2086 Term->mapped_flag = FALSE;
2090 /* Move and/or Resize */
2091 case ConfigureNotify:
2093 int cols, rows, wid, hgt;
2095 int ox = Infowin->ox;
2096 int oy = Infowin->oy;
2098 /* Save the new Window Parms */
2099 Infowin->x = xev->xconfigure.x;
2100 Infowin->y = xev->xconfigure.y;
2101 Infowin->w = xev->xconfigure.width;
2102 Infowin->h = xev->xconfigure.height;
2104 /* Determine "proper" number of rows/cols */
2105 cols = ((Infowin->w - (ox + ox)) / td->fnt->wid);
2106 rows = ((Infowin->h - (oy + oy)) / td->fnt->hgt);
2108 /* Hack -- minimal size */
2109 if (cols < 1) cols = 1;
2110 if (rows < 1) rows = 1;
2114 /* Hack the main window must be at least 80x24 */
2115 if (cols < 80) cols = 80;
2116 if (rows < 24) rows = 24;
2119 /* Desired size of window */
2120 wid = cols * td->fnt->wid + (ox + ox);
2121 hgt = rows * td->fnt->hgt + (oy + oy);
2123 /* Resize the Term (if needed) */
2124 Term_resize(cols, rows);
2126 /* Resize the windows if any "change" is needed */
2127 if ((Infowin->w != wid) || (Infowin->h != hgt))
2130 Infowin_set(td->win);
2131 Infowin_resize(wid, hgt);
2140 XSetICFocus(iwin->xic);
2148 XUnsetICFocus(iwin->xic);
2150 /* Focuswin = NULL;*/
2157 /* Hack -- Activate the old term */
2158 Term_activate(&old_td->t);
2160 /* Hack -- Activate the proper window */
2161 Infowin_set(old_td->win);
2170 * Standard sound names
2172 static const concptr angband_sound_name[SOUND_MAX] =
2244 * An array of sound file names
2246 static concptr sound_file[SOUND_MAX];
2249 * Check for existance of a file
2251 static bool check_file(concptr s)
2255 fff = fopen(s, "r");
2256 if (!fff) return (FALSE);
2265 static void init_sound(void)
2270 char dir_xtra_sound[1024];
2272 /* Build the "sound" path */
2273 path_build(dir_xtra_sound, sizeof(dir_xtra_sound), ANGBAND_DIR_XTRA, "sound");
2275 /* Prepare the sounds */
2276 for (i = 1; i < SOUND_MAX; i++)
2278 /* Extract name of sound file */
2279 sprintf(wav, "%s.wav", angband_sound_name[i]);
2281 /* Access the sound */
2282 path_build(buf, sizeof(buf), dir_xtra_sound, wav);
2284 /* Save the sound filename, if it exists */
2285 if (check_file(buf)) sound_file[i] = string_make(buf);
2292 * Hack -- make a sound
2294 static errr Term_xtra_x11_sound(int v)
2298 /* Sound disabled */
2299 if (!use_sound) return (1);
2302 if ((v < 0) || (v >= SOUND_MAX)) return (1);
2305 if (!sound_file[v]) return (1);
2307 sprintf(buf,"./playwave.sh %s\n", sound_file[v]);
2309 return (system(buf) < 0);
2315 * Handle "activation" of a term
2317 static errr Term_xtra_x11_level(int v)
2319 term_data *td = (term_data*)(Term->data);
2321 /* Handle "activate" */
2324 /* Activate the window */
2325 Infowin_set(td->win);
2327 /* Activate the font */
2328 Infofnt_set(td->fnt);
2339 static errr Term_xtra_x11_react(void)
2345 /* Check the colors */
2346 for (i = 0; i < 256; i++)
2348 if ((color_table[i][0] != angband_color_table[i][0]) ||
2349 (color_table[i][1] != angband_color_table[i][1]) ||
2350 (color_table[i][2] != angband_color_table[i][2]) ||
2351 (color_table[i][3] != angband_color_table[i][3]))
2355 /* Save new values */
2356 color_table[i][0] = angband_color_table[i][0];
2357 color_table[i][1] = angband_color_table[i][1];
2358 color_table[i][2] = angband_color_table[i][2];
2359 color_table[i][3] = angband_color_table[i][3];
2362 pixel = create_pixel(Metadpy->dpy,
2367 /* Change the foreground */
2368 Infoclr_set(clr[i]);
2369 Infoclr_change_fg(pixel);
2380 * Handle a "special request"
2382 static errr Term_xtra_x11(int n, int v)
2384 /* Handle a subset of the legal requests */
2388 case TERM_XTRA_NOISE: Metadpy_do_beep(); return (0);
2390 /* Make a special sound */
2391 case TERM_XTRA_SOUND: return (Term_xtra_x11_sound(v));
2393 /* Flush the output XXX XXX */
2394 case TERM_XTRA_FRESH: Metadpy_update(1, 0, 0); return (0);
2396 /* Process random events XXX */
2397 case TERM_XTRA_BORED: return (CheckEvent(0));
2399 /* Process Events XXX */
2400 case TERM_XTRA_EVENT: return (CheckEvent(v));
2402 /* Flush the events XXX */
2403 case TERM_XTRA_FLUSH: while (!CheckEvent(FALSE)); return (0);
2405 /* Handle change in the "level" */
2406 case TERM_XTRA_LEVEL: return (Term_xtra_x11_level(v));
2408 /* Clear the screen */
2409 case TERM_XTRA_CLEAR: Infowin_wipe(); s_ptr->drawn = FALSE; return (0);
2411 /* Delay for some milliseconds */
2412 case TERM_XTRA_DELAY: usleep(1000 * v); return (0);
2414 /* React to changes */
2415 case TERM_XTRA_REACT: return (Term_xtra_x11_react());
2424 * Draw the cursor as an inverted rectangle.
2426 * Consider a rectangular outline like "main-mac.c". XXX XXX
2428 static errr Term_curs_x11(int x, int y)
2432 XDrawRectangle(Metadpy->dpy, Infowin->win, xor->gc,
2433 x * Infofnt->wid + Infowin->ox,
2434 y * Infofnt->hgt + Infowin->oy,
2435 Infofnt->wid - 1, Infofnt->hgt - 1);
2436 XDrawRectangle(Metadpy->dpy, Infowin->win, xor->gc,
2437 x * Infofnt->wid + Infowin->ox + 1,
2438 y * Infofnt->hgt + Infowin->oy + 1,
2439 Infofnt->wid - 3, Infofnt->hgt - 3);
2443 /* Draw the cursor */
2446 /* Hilite the cursor character */
2447 Infofnt_text_non(x, y, " ", 1);
2456 * Draw the double width cursor
2458 static errr Term_bigcurs_x11(int x, int y)
2462 XDrawRectangle(Metadpy->dpy, Infowin->win, xor->gc,
2463 x * Infofnt->wid + Infowin->ox,
2464 y * Infofnt->hgt + Infowin->oy,
2465 Infofnt->twid - 1, Infofnt->hgt - 1);
2466 XDrawRectangle(Metadpy->dpy, Infowin->win, xor->gc,
2467 x * Infofnt->wid + Infowin->ox + 1,
2468 y * Infofnt->hgt + Infowin->oy + 1,
2469 Infofnt->twid - 3, Infofnt->hgt - 3);
2473 /* Draw the cursor */
2476 /* Hilite the cursor character */
2477 Infofnt_text_non(x, y, " ", 2);
2485 * Erase some characters.
2487 static errr Term_wipe_x11(int x, int y, int n)
2489 /* Erase (use black) */
2490 Infoclr_set(clr[TERM_DARK]);
2492 /* Mega-Hack -- Erase some space */
2493 Infofnt_text_non(x, y, "", n);
2495 /* Redraw the selection if any, as it may have been obscured. (later) */
2496 s_ptr->drawn = FALSE;
2504 * Draw some textual characters.
2506 static errr Term_text_x11(TERM_LEN x, TERM_LEN y, int n, TERM_COLOR a, concptr s)
2509 Infoclr_set(clr[a]);
2512 Infofnt_text_std(x, y, s, n);
2514 /* Redraw the selection if any, as it may have been obscured. (later) */
2515 s_ptr->drawn = FALSE;
2523 * Draw some graphical characters.
2525 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)
2538 unsigned long pixel, blank;
2540 term_data *td = (term_data*)(Term->data);
2545 /* Add in affect of window boundaries */
2549 for (i = 0; i < n; ++i, x += td->fnt->wid)
2554 /* For extra speed - cache these values */
2555 x1 = (c&0x7F) * td->fnt->twid;
2556 y1 = (a&0x7F) * td->fnt->hgt;
2558 /* Illegal tile index */
2559 if (td->tiles->width < x1 + td->fnt->wid ||
2560 td->tiles->height < y1 + td->fnt->hgt)
2562 /* Draw black square */
2563 XFillRectangle(Metadpy->dpy, td->win->win, clr[0]->gc,
2565 td->fnt->twid, td->fnt->hgt);
2567 /* Skip drawing tile */
2574 /* For extra speed - cache these values */
2575 x2 = (tc&0x7F) * td->fnt->twid;
2576 y2 = (ta&0x7F) * td->fnt->hgt;
2578 /* Optimise the common case */
2579 if (((x1 == x2) && (y1 == y2)) ||
2580 !(((byte)ta & 0x80) && ((byte)tc & 0x80)) ||
2581 td->tiles->width < x2 + td->fnt->wid ||
2582 td->tiles->height < y2 + td->fnt->hgt)
2584 /* Draw object / terrain */
2585 XPutImage(Metadpy->dpy, td->win->win,
2590 td->fnt->twid, td->fnt->hgt);
2595 /* Mega Hack^2 - assume the top left corner is "black" */
2596 blank = XGetPixel(td->tiles, 0, td->fnt->hgt * 6);
2598 for (k = 0; k < td->fnt->twid; k++)
2600 for (l = 0; l < td->fnt->hgt; l++)
2602 /* If mask set... */
2603 if ((pixel = XGetPixel(td->tiles, x1 + k, y1 + l)) == blank)
2605 /* Output from the terrain */
2606 pixel = XGetPixel(td->tiles, x2 + k, y2 + l);
2609 /* Store into the temp storage. */
2610 XPutPixel(td->TmpImage, k, l, pixel);
2615 /* Draw to screen */
2617 XPutImage(Metadpy->dpy, td->win->win,
2621 td->fnt->twid, td->fnt->hgt);
2625 /* Redraw the selection if any, as it may have been obscured. (later) */
2626 s_ptr->drawn = FALSE;
2633 static void IMDestroyCallback(XIM, XPointer, XPointer);
2636 IMInstantiateCallback(Display *display, XPointer unused1, XPointer unused2)
2639 XIMCallback ximcallback;
2640 XIMStyles *xim_styles = NULL;
2647 xim = XOpenIM(display, NULL, NULL, NULL);
2649 printf("can't open IM\n");
2653 /* initialize destroy callback */
2654 ximcallback.callback = IMDestroyCallback;
2655 ximcallback.client_data = NULL;
2656 XSetIMValues(xim, XNDestroyCallback, &ximcallback, NULL);
2658 /* set style (only "Root" is supported yet...) */
2659 XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL);
2660 for (i = 0; i < xim_styles->count_styles; i++){
2661 if(xim_styles->supported_styles[i] == (XIMPreeditNothing | XIMStatusNothing)) break;
2663 if(i >= xim_styles->count_styles){
2664 printf("Sorry, your IM does not support 'Root' preedit style...\n");
2672 for (i = 0; i < MAX_TERM_DATA; i++)
2674 infowin *iwin = data[i].win;
2675 if (!iwin) continue;
2676 iwin->xic = XCreateIC(xim, XNInputStyle, (XIMPreeditNothing | XIMStatusNothing), XNClientWindow, iwin->win, XNFocusWindow, iwin->win, NULL);
2678 printf("Can't create input context for Term%d\n", i);
2681 if(XGetICValues(iwin->xic, XNFilterEvents, &iwin->xic_mask, NULL) != NULL){
2682 /* printf("Can't get XNFilterEvents\n"); */
2683 iwin->xic_mask = 0L;
2685 XSelectInput(Metadpy->dpy, iwin->win, iwin->mask | iwin->xic_mask);
2691 static void IMDestroyCallback(XIM xim, XPointer client_data, XPointer call_data)
2699 if (call_data == NULL){
2700 XRegisterIMInstantiateCallback(Metadpy->dpy, NULL, NULL, NULL, IMInstantiateCallback, NULL);
2703 for(i = 0; i < MAX_TERM_DATA; i++)
2705 infowin *iwin = data[i].win;
2708 XSelectInput(Metadpy->dpy, iwin->win, iwin->mask);
2709 iwin->xic_mask = 0L;
2714 Metadpy->xim = NULL;
2719 * Initialize a term_data
2721 static errr term_data_init(term_data *td, int i)
2725 concptr name = angband_term_name[i];
2755 /* Window specific font name */
2756 sprintf(buf, "ANGBAND_X11_FONT_%d", i);
2758 /* Check environment for that font */
2761 /* Check environment for "base" font */
2762 if (!font) font = getenv("ANGBAND_X11_FONT");
2764 /* No environment variables, use default font */
2771 font = DEFAULT_X11_FONT_0;
2776 font = DEFAULT_X11_FONT_1;
2781 font = DEFAULT_X11_FONT_2;
2786 font = DEFAULT_X11_FONT_3;
2791 font = DEFAULT_X11_FONT_4;
2796 font = DEFAULT_X11_FONT_5;
2801 font = DEFAULT_X11_FONT_6;
2806 font = DEFAULT_X11_FONT_7;
2811 font = DEFAULT_X11_FONT;
2816 /* Window specific location (x) */
2817 sprintf(buf, "ANGBAND_X11_AT_X_%d", i);
2819 x = (str != NULL) ? atoi(str) : -1;
2821 /* Window specific location (y) */
2822 sprintf(buf, "ANGBAND_X11_AT_Y_%d", i);
2824 y = (str != NULL) ? atoi(str) : -1;
2827 /* Window specific cols */
2828 sprintf(buf, "ANGBAND_X11_COLS_%d", i);
2830 val = (str != NULL) ? atoi(str) : -1;
2831 if (val > 0) cols = val;
2833 /* Window specific rows */
2834 sprintf(buf, "ANGBAND_X11_ROWS_%d", i);
2836 val = (str != NULL) ? atoi(str) : -1;
2837 if (val > 0) rows = val;
2839 /* Hack the main window must be at least 80x24 */
2842 if (cols < 80) cols = 80;
2843 if (rows < 24) rows = 24;
2846 /* Window specific inner border offset (ox) */
2847 sprintf(buf, "ANGBAND_X11_IBOX_%d", i);
2849 val = (str != NULL) ? atoi(str) : -1;
2850 if (val > 0) ox = val;
2852 /* Window specific inner border offset (oy) */
2853 sprintf(buf, "ANGBAND_X11_IBOY_%d", i);
2855 val = (str != NULL) ? atoi(str) : -1;
2856 if (val > 0) oy = val;
2859 /* Prepare the standard font */
2860 MAKE(td->fnt, infofnt);
2861 Infofnt_set(td->fnt);
2862 Infofnt_init_data(font);
2864 /* Hack -- key buffer size */
2865 num = ((i == 0) ? 1024 : 16);
2867 /* Assume full size windows */
2868 wid = cols * td->fnt->wid + (ox + ox);
2869 hgt = rows * td->fnt->hgt + (oy + oy);
2871 /* Create a top-window */
2872 MAKE(td->win, infowin);
2873 Infowin_set(td->win);
2874 Infowin_init_top(x, y, wid, hgt, 0,
2875 Metadpy->fg, Metadpy->bg);
2877 /* Ask for certain events */
2878 #if defined(USE_XIM)
2879 Infowin_set_mask(ExposureMask | StructureNotifyMask | KeyPressMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask | FocusChangeMask);
2881 Infowin_set_mask(ExposureMask | StructureNotifyMask | KeyPressMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask);
2884 /* Set the window name */
2885 Infowin_set_name(name);
2887 /* Save the inner border */
2891 /* Make Class Hints */
2892 ch = XAllocClassHint();
2894 if (ch == NULL) quit("XAllocClassHint failed");
2896 strcpy(res_name, name);
2897 res_name[0] = FORCELOWER(res_name[0]);
2898 ch->res_name = res_name;
2900 strcpy(res_class, "Angband");
2901 ch->res_class = res_class;
2903 XSetClassHint(Metadpy->dpy, Infowin->win, ch);
2905 /* Make Size Hints */
2906 sh = XAllocSizeHints();
2909 if (sh == NULL) quit("XAllocSizeHints failed");
2911 /* Main window has a differing minimum size */
2914 /* Main window min size is 80x24 */
2915 sh->flags = PMinSize | PMaxSize;
2916 sh->min_width = 80 * td->fnt->wid + (ox + ox);
2917 sh->min_height = 24 * td->fnt->hgt + (oy + oy);
2918 sh->max_width = 255 * td->fnt->wid + (ox + ox);
2919 sh->max_height = 255 * td->fnt->hgt + (oy + oy);
2922 /* Other windows can be shrunk to 1x1 */
2926 sh->flags = PMinSize | PMaxSize;
2927 sh->min_width = td->fnt->wid + (ox + ox);
2928 sh->min_height = td->fnt->hgt + (oy + oy);
2929 sh->max_width = 256 * td->fnt->wid + (ox + ox);
2930 sh->max_height = 256 * td->fnt->hgt + (oy + oy);
2933 /* Resize increment */
2934 sh->flags |= PResizeInc;
2935 sh->width_inc = td->fnt->wid;
2936 sh->height_inc = td->fnt->hgt;
2938 /* Base window size */
2939 sh->flags |= PBaseSize;
2940 sh->base_width = (ox + ox);
2941 sh->base_height = (oy + oy);
2943 /* Use the size hints */
2944 XSetWMNormalHints(Metadpy->dpy, Infowin->win, sh);
2946 /* Map the window */
2951 wh = XAllocWMHints();
2952 if(wh == NULL) quit("XAllocWMHints failed");
2953 wh->flags = InputHint;
2955 XSetWMHints(Metadpy->dpy, Infowin->win, wh);
2958 /* Move the window to requested location */
2959 if ((x >= 0) && (y >= 0)) Infowin_impell(x, y);
2962 /* Initialize the term */
2963 term_init(t, cols, rows, num);
2965 /* Use a "soft" cursor */
2966 t->soft_cursor = TRUE;
2968 /* Erase with "white space" */
2969 t->attr_blank = TERM_WHITE;
2970 t->char_blank = ' ';
2973 t->xtra_hook = Term_xtra_x11;
2974 t->curs_hook = Term_curs_x11;
2975 t->bigcurs_hook = Term_bigcurs_x11;
2976 t->wipe_hook = Term_wipe_x11;
2977 t->text_hook = Term_text_x11;
2982 /* Activate (important) */
2991 * Initialization function for an "X11" module to Angband
2993 errr init_x11(int argc, char *argv[])
2997 concptr dpy_name = "";
3001 char filename[1024];
3009 for (i = 1; i < argc; i++)
3011 if (prefix(argv[i], "-d"))
3013 dpy_name = &argv[i][2];
3017 if (prefix(argv[i], "-s"))
3019 smoothRescaling = FALSE;
3023 if (prefix(argv[i], "-a"))
3025 arg_graphics = GRAPHICS_ADAM_BOLT;
3029 if (prefix(argv[i], "-o"))
3031 arg_graphics = GRAPHICS_ORIGINAL;
3035 if (prefix(argv[i], "-b"))
3037 arg_bigtile = use_bigtile = TRUE;
3041 if (prefix(argv[i], "-n"))
3043 num_term = atoi(&argv[i][2]);
3044 if (num_term > MAX_TERM_DATA) num_term = MAX_TERM_DATA;
3045 else if (num_term < 1) num_term = 1;
3049 if (prefix(argv[i], "--"))
3055 plog_fmt("Ignoring option: %s", argv[i]);
3061 /* Get locale information from environment variables */
3062 setlocale(LC_ALL, "");
3064 #ifdef DEFAULT_LOCALE
3065 if(!strcmp(setlocale(LC_ALL, NULL), "C")){
3066 printf("try default locale \"%s\"\n", DEFAULT_LOCALE);
3067 setlocale(LC_ALL, DEFAULT_LOCALE);
3071 if(!strcmp(setlocale(LC_ALL, NULL), "C"))
3073 printf("WARNING: Locale is not supported. Non-english font may be displayed incorrectly.\n");
3076 if(!XSupportsLocale()){
3077 printf("can't support locale in X\n");
3078 setlocale(LC_ALL, "C");
3081 /* Set locale to "C" without using environment variables */
3082 setlocale(LC_ALL, "C");
3085 #endif /* USE_LOCALE */
3088 /* Init the Metadpy if possible */
3089 if (Metadpy_init_name(dpy_name)) return (-1);
3092 /* Prepare cursor color */
3095 Infoclr_init_ppn(Metadpy->fg, Metadpy->bg, "xor", 0);
3098 /* Prepare normal colors */
3099 for (i = 0; i < 256; ++i)
3103 MAKE(clr[i], infoclr);
3105 Infoclr_set(clr[i]);
3107 /* Acquire Angband colors */
3108 color_table[i][0] = angband_color_table[i][0];
3109 color_table[i][1] = angband_color_table[i][1];
3110 color_table[i][2] = angband_color_table[i][2];
3111 color_table[i][3] = angband_color_table[i][3];
3113 /* Default to monochrome */
3114 pixel = ((i == 0) ? Metadpy->bg : Metadpy->fg);
3120 pixel = create_pixel(Metadpy->dpy,
3126 /* Initialize the color */
3127 Infoclr_init_ppn(pixel, Metadpy->bg, "cpy", 0);
3131 /* Prepare required atoms. */
3135 /* Initialize the windows */
3136 for (i = 0; i < num_term; i++)
3138 term_data *td = &data[i];
3140 /* Initialize the term_data */
3141 term_data_init(td, i);
3143 /* Save global entry */
3144 angband_term[i] = Term;
3147 /* Raise the "Angband" window */
3148 Infowin_set(data[0].win);
3151 /* Activate the "Angband" window screen */
3152 Term_activate(&data[0].t);
3157 p = XSetLocaleModifiers("");
3159 p = XSetLocaleModifiers("@im=");
3161 /* printf("XMODIFIERS=\"%s\"\n", p); */
3163 XRegisterIMInstantiateCallback(Metadpy->dpy, NULL, NULL, NULL, IMInstantiateCallback, NULL);
3166 /* initialize sound */
3167 if (arg_sound) init_sound();
3170 switch (arg_graphics)
3172 case GRAPHICS_ORIGINAL:
3173 /* Try the "8x8.bmp" file */
3174 path_build(filename, sizeof(filename), ANGBAND_DIR_XTRA, "graf/8x8.bmp");
3176 /* Use the "8x8.bmp" file if it exists */
3177 if (0 == fd_close(fd_open(filename, O_RDONLY)))
3180 use_graphics = TRUE;
3182 pict_wid = pict_hgt = 8;
3184 ANGBAND_GRAF = "old";
3189 case GRAPHICS_ADAM_BOLT:
3190 /* Try the "16x16.bmp" file */
3191 path_build(filename, sizeof(filename), ANGBAND_DIR_XTRA, "graf/16x16.bmp");
3193 /* Use the "16x16.bmp" file if it exists */
3194 if (0 == fd_close(fd_open(filename, O_RDONLY)))
3197 use_graphics = TRUE;
3199 pict_wid = pict_hgt = 16;
3201 ANGBAND_GRAF = "new";
3210 Display *dpy = Metadpy->dpy;
3214 /* Load the graphical tiles */
3215 tiles_raw = ReadBMP(dpy, filename);
3217 /* Initialize the windows */
3218 for (i = 0; i < num_term; i++)
3220 term_data *td = &data[i];
3225 t->pict_hook = Term_pict_x11;
3227 /* Use graphics sometimes */
3228 t->higher_pict = TRUE;
3232 ResizeImage(dpy, tiles_raw,
3234 td->fnt->twid, td->fnt->hgt);
3237 /* Initialize the transparency masks */
3238 for (i = 0; i < num_term; i++)
3240 term_data *td = &data[i];
3242 int depth = DefaultDepth(dpy, DefaultScreen(dpy));
3243 Visual *visual = DefaultVisual(dpy, DefaultScreen(dpy));
3247 /* Determine total bytes needed for image */
3249 jj = (depth - 1) >> 2;
3250 while (jj >>= 1) ii <<= 1;
3251 total = td->fnt->twid * td->fnt->hgt * ii;
3254 TmpData = (char *)malloc(total);
3256 td->TmpImage = XCreateImage(dpy,visual,depth,
3257 ZPixmap, 0, TmpData,
3258 td->fnt->twid, td->fnt->hgt, 8, 0);
3262 /* Free tiles_raw? XXX XXX */
3269 #endif /* USE_X11 */