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 */
643 if (dad == None) dad = Metadpy->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;
960 * Init an infofnt by its Name
963 * name: The name of the requested Font
965 static void Infofnt_init_data(concptr name)
973 /*** Load the info Fresh, using the name ***/
975 /* If the name is not given, report an error */
976 if (!name || !*name) quit("Missing font!");
978 /* Attempt to load the font */
979 info = XCreateFontSet(Metadpy->dpy, name, &missing_list, &missing_count, &default_font);
980 if(missing_count > 0){
981 printf("missing font(s): \n");
982 while(missing_count-- > 0){
983 printf("\t%s\n", missing_list[missing_count]);
985 XFreeStringList(missing_list);
988 /* The load failed, try to recover */
989 if (!info) quit_fmt("Failed to find font:\"%s\"", name);
991 /*** Init the font ***/
994 (void)WIPE(Infofnt, infofnt);
996 /* Attempt to prepare it */
997 if (Infofnt_prepare(info))
1000 XFreeFontSet(Metadpy->dpy, info);
1003 quit_fmt("Failed to prepare font:\"%s\"", name);
1006 /* Save a copy of the font name */
1007 Infofnt->name = string_make(name);
1009 /* Mark it as nukable */
1017 static errr Infofnt_text_std(int x, int y, concptr str, int len)
1022 /*** Do a brief info analysis ***/
1024 /* Do nothing if the string is null */
1025 if (!str || !*str) return (-1);
1027 /* Get the length of the string */
1028 if (len < 0) len = strlen(str);
1030 /*** Decide where to place the string, vertically ***/
1032 /* Ignore Vertical Justifications */
1033 y = (y * Infofnt->hgt) + Infofnt->asc + Infowin->oy;
1036 /*** Decide where to place the string, horizontally ***/
1038 /* Line up with x at left edge of column 'x' */
1039 x = (x * Infofnt->wid) + Infowin->ox;
1042 /*** Actually draw 'str' onto the infowin ***/
1044 /*** Handle the fake mono we can enforce on fonts ***/
1046 /* Monotize the font */
1049 /* Do each character */
1050 for (i = 0; i < len; ++i)
1052 /* Note that the Infoclr is set up to contain the Infofnt */
1053 XDrawImageString(Metadpy->dpy, Infowin->win, Infoclr->gc,
1054 x + i * Infofnt->wid + Infofnt->off, y, str + i, 1);
1058 /* Assume monoospaced font */
1061 /* Note that the Infoclr is set up to contain the Infofnt */
1062 iconv_t cd = iconv_open("UTF-8", "EUC-JP");
1064 size_t outlen = len * 2;
1065 char *kanji = malloc(outlen);
1066 char *sp; char *kp = kanji;
1068 my_strcpy(sbuf, str, sizeof(sbuf));
1070 iconv(cd, &sp, &inlen, &kp, &outlen);
1073 XmbDrawImageString(Metadpy->dpy, Infowin->win, Infofnt->info,
1074 Infoclr->gc, x, y, kanji, kp-kanji);
1084 * Painting where text would be
1086 static errr Infofnt_text_non(int x, int y, concptr str, int len)
1091 /*** Find the width ***/
1093 /* Negative length is a flag to count the characters in str */
1094 if (len < 0) len = strlen(str);
1096 /* The total width will be 'len' chars * standard width */
1097 w = len * Infofnt->wid;
1100 /*** Find the X dimensions ***/
1102 /* Line up with x at left edge of column 'x' */
1103 x = x * Infofnt->wid + Infowin->ox;
1106 /*** Find other dimensions ***/
1108 /* Simply do 'Infofnt->hgt' (a single row) high */
1111 /* Simply do "at top" in row 'y' */
1112 y = y * h + Infowin->oy;
1115 /*** Actually 'paint' the area ***/
1117 /* Just do a Fill Rectangle */
1118 XFillRectangle(Metadpy->dpy, Infowin->win, Infoclr->gc, x, y, w, h);
1126 /*************************************************************************/
1130 * Angband specific code follows... (ANGBAND)
1135 * Hack -- cursor color
1137 static infoclr *xor;
1140 * Actual color table
1142 static infoclr *clr[256];
1145 * Color info (unused, red, green, blue).
1147 static byte color_table[256][4];
1152 typedef struct term_data term_data;
1155 * A structure for each "term"
1166 /* Tempory storage for overlaying tiles. */
1172 * The number of term data structures
1174 #define MAX_TERM_DATA 8
1177 * The array of term data structures
1179 static term_data data[MAX_TERM_DATA];
1182 /* Use short names for the most commonly used elements of various structures. */
1183 #define DPY (Metadpy->dpy)
1184 #define WIN (Infowin->win)
1187 /* Describe a set of co-ordinates. */
1188 typedef struct co_ord co_ord;
1197 * A special structure to store information about the text currently
1200 typedef struct x11_selection_type x11_selection_type;
1201 struct x11_selection_type
1203 bool select; /* The selection is currently in use. */
1204 bool drawn; /* The selection is currently displayed. */
1205 term *t; /* The window where the selection is found. */
1206 co_ord init; /* The starting co-ordinates. */
1207 co_ord cur; /* The end co-ordinates (the current ones if still copying). */
1208 co_ord old; /* The previous end co-ordinates. */
1209 Time time; /* The time at which the selection was finalised. */
1212 static x11_selection_type s_ptr[1];
1216 * Process a keypress event
1218 * Also appears in "main-xaw.c".
1220 static void react_keypress(XKeyEvent *xev)
1222 int i, n, mc, ms, mo, mx;
1226 XKeyEvent *ev = (XKeyEvent*)(xev);
1234 int valid_keysym = TRUE;
1237 /* Check for "normal" keypresses */
1239 if(Focuswin && Focuswin->xic){
1241 n = XmbLookupString(Focuswin->xic, ev, buf, 125, &ks, &status);
1242 if(status == XBufferOverflow){
1243 printf("Input is too long, and dropped\n");
1246 if(status != XLookupKeySym && status != XLookupBoth){
1247 valid_keysym = FALSE;
1250 n = XLookupString(ev, buf, 125, &ks, NULL);
1253 n = XLookupString(ev, buf, 125, &ks, NULL);
1261 /* Enqueue the normal key(s) */
1262 for (i = 0; buf[i]; i++) Term_keypress(buf[i]);
1269 /* Hack -- Ignore "modifier keys" */
1270 if (IsModifierKey(ks)) return;
1273 /* Hack -- convert into an unsigned int */
1276 /* Extract four "modifier flags" */
1277 mc = (ev->state & ControlMask) ? TRUE : FALSE;
1278 ms = (ev->state & ShiftMask) ? TRUE : FALSE;
1279 mo = (ev->state & Mod1Mask) ? TRUE : FALSE;
1280 mx = (ev->state & Mod2Mask) ? TRUE : FALSE;
1283 /* Normal keys with no modifiers */
1284 if (n && !mo && !mx && !IsSpecialKey(ks))
1286 /* Enqueue the normal key(s) */
1287 for (i = 0; buf[i]; i++) Term_keypress(buf[i]);
1294 /* Handle a few standard keys (bypass modifiers) XXX XXX XXX */
1299 Term_keypress(ESCAPE);
1305 Term_keypress('\r');
1311 Term_keypress('\t');
1317 Term_keypress(0x7f);
1322 Term_keypress('\010');
1328 /* Hack -- Use the KeySym */
1331 sprintf(msg, "%c%s%s%s%s_%lX%c", 31,
1332 mc ? "N" : "", ms ? "S" : "",
1333 mo ? "O" : "", mx ? "M" : "",
1334 (unsigned long)(ks), 13);
1337 /* Hack -- Use the Keycode */
1340 sprintf(msg, "%c%s%s%s%sK_%X%c", 31,
1341 mc ? "N" : "", ms ? "S" : "",
1342 mo ? "O" : "", mx ? "M" : "",
1346 /* Enqueue the "macro trigger" string */
1347 for (i = 0; msg[i]; i++) Term_keypress(msg[i]);
1350 /* Hack -- auto-define macros as needed */
1351 if (n && (macro_find_exact(msg) < 0))
1353 /* Create a macro */
1354 macro_add(msg, buf);
1360 * Find the square a particular pixel is part of.
1362 static void pixel_to_square(int * const x, int * const y,
1363 const int ox, const int oy)
1365 (*x) = (ox - Infowin->ox) / Infofnt->wid;
1366 (*y) = (oy - Infowin->oy) / Infofnt->hgt;
1370 * Find the pixel at the top-left corner of a square.
1372 static void square_to_pixel(int * const x, int * const y,
1373 const int ox, const int oy)
1375 (*x) = ox * Infofnt->wid + Infowin->ox;
1376 (*y) = oy * Infofnt->hgt + Infowin->oy;
1380 * Convert co-ordinates from starting corner/opposite corner to minimum/maximum.
1382 static void sort_co_ord(co_ord *min, co_ord *max,
1383 const co_ord *b, const co_ord *a)
1385 min->x = MIN(a->x, b->x);
1386 min->y = MIN(a->y, b->y);
1387 max->x = MAX(a->x, b->x);
1388 max->y = MAX(a->y, b->y);
1392 * Remove the selection by redrawing it.
1394 static void mark_selection_clear(int x1, int y1, int x2, int y2)
1396 Term_redraw_section(x1,y1,x2,y2);
1400 * Select an area by drawing a grey box around it.
1401 * NB. These two functions can cause flicker as the selection is modified,
1402 * as the game redraws the entire marked section.
1404 static void mark_selection_mark(int x1, int y1, int x2, int y2)
1406 square_to_pixel(&x1, &y1, x1, y1);
1407 square_to_pixel(&x2, &y2, x2, y2);
1408 XDrawRectangle(Metadpy->dpy, Infowin->win, clr[2]->gc, x1, y1,
1409 x2-x1+Infofnt->wid - 1, y2-y1+Infofnt->hgt - 1);
1413 * Mark a selection by drawing boxes around it (for now).
1415 static void mark_selection(void)
1419 bool draw = s_ptr->select;
1420 bool clear = s_ptr->drawn;
1422 /* Open the correct term if necessary. */
1423 if (s_ptr->t != old) Term_activate(s_ptr->t);
1427 sort_co_ord(&min, &max, &s_ptr->init, &s_ptr->old);
1428 mark_selection_clear(min.x, min.y, max.x, max.y);
1432 sort_co_ord(&min, &max, &s_ptr->init, &s_ptr->cur);
1433 mark_selection_mark(min.x, min.y, max.x, max.y);
1436 /* Finish on the current term. */
1437 if (s_ptr->t != old) Term_activate(old);
1439 s_ptr->old.x = s_ptr->cur.x;
1440 s_ptr->old.y = s_ptr->cur.y;
1441 s_ptr->drawn = s_ptr->select;
1445 * Forget a selection for one reason or another.
1447 static void copy_x11_release(void)
1449 /* Deselect the current selection. */
1450 s_ptr->select = FALSE;
1452 /* Remove its graphical represesntation. */
1457 * Start to select some text on the screen.
1459 static void copy_x11_start(int x, int y)
1461 if (s_ptr->select) copy_x11_release();
1463 /* Remember where the selection started. */
1465 s_ptr->init.x = s_ptr->cur.x = s_ptr->old.x = x;
1466 s_ptr->init.y = s_ptr->cur.y = s_ptr->old.y = y;
1470 * Respond to movement of the mouse when selecting text.
1472 static void copy_x11_cont(int x, int y, unsigned int buttons)
1474 /* Use the nearest square within bounds if the mouse is outside. */
1475 x = MIN(MAX(x, 0), Term->wid-1);
1476 y = MIN(MAX(y, 0), Term->hgt-1);
1478 /* The left mouse button isn't pressed. */
1479 if (~buttons & Button1Mask) return;
1481 /* Not a selection in this window. */
1482 if (s_ptr->t != Term) return;
1484 /* Not enough movement. */
1485 if (x == s_ptr->old.x && y == s_ptr->old.y && s_ptr->select) return;
1487 /* Something is being selected. */
1488 s_ptr->select = TRUE;
1490 /* Track the selection. */
1494 /* Hack - display it inefficiently. */
1499 * Respond to release of the left mouse button by putting the selected text in
1500 * the primary buffer.
1502 static void copy_x11_end(const Time time)
1505 if (!s_ptr->select) return;
1507 /* Not a selection in this window. */
1508 if (s_ptr->t != Term) return;
1510 /* Remember when the selection was finalised. */
1513 /* Acquire the primary selection. */
1514 XSetSelectionOwner(Metadpy->dpy, XA_PRIMARY, Infowin->win, time);
1515 if (XGetSelectionOwner(Metadpy->dpy, XA_PRIMARY) != Infowin->win)
1517 /* Failed to acquire the selection, so forget it. */
1518 /* bell("Failed to acquire primary buffer."); */
1519 s_ptr->select = FALSE;
1525 static Atom xa_targets, xa_timestamp, xa_text, xa_compound_text;
1528 * Set the required variable atoms at start-up to avoid errors later.
1530 static void set_atoms(void)
1532 xa_targets = XInternAtom(DPY, "TARGETS", False);
1533 xa_timestamp = XInternAtom(DPY, "TIMESTAMP", False);
1534 xa_text = XInternAtom(DPY, "TEXT", False);
1535 xa_compound_text = XInternAtom(DPY, "COMPOUND_TEXT", False);
1539 static Atom request_target = 0;
1542 * Send a message to request that the PRIMARY buffer be sent here.
1544 static void paste_x11_request(Atom target, const Time time)
1547 * It's from some sample programs on the web.
1548 * What does it mean? -- XXX
1550 Atom property = XInternAtom(DPY, "__COPY_TEXT", False);
1552 /* Check the owner. */
1553 if (XGetSelectionOwner(DPY, XA_PRIMARY) == None)
1556 /* bell("No selection found."); */
1560 request_target = target;
1562 /* Request the event */
1563 XConvertSelection(DPY, XA_PRIMARY, target, property, WIN, time);
1568 * Add the contents of the PRIMARY buffer to the input queue.
1570 * Hack - This doesn't use the "time" of the event, and so accepts anything a
1571 * client tries to send it.
1573 static void paste_x11_accept(const XSelectionEvent *ptr)
1576 const long offset = 0;
1577 const long length = 32000;
1578 XTextProperty xtextproperty;
1582 * It's from some sample programs on the web.
1583 * What does it mean? -- XXX
1585 Atom property = XInternAtom(DPY, "__COPY_TEXT", False);
1589 if (ptr->property == None)
1591 if (request_target == xa_compound_text)
1593 /* Re-request as STRING */
1594 paste_x11_request(XA_STRING, ptr->time);
1599 plog("Paste failure (remote client could not send).");
1604 if (ptr->selection != XA_PRIMARY)
1606 plog("Paste failure (remote client did not send primary selection).");
1610 if (ptr->target != request_target)
1612 plog("Paste failure (selection in unknown format).");
1617 if (XGetWindowProperty(Metadpy->dpy, Infowin->win, property, offset,
1618 length, TRUE, request_target,
1619 &xtextproperty.encoding,
1620 &xtextproperty.format,
1621 &xtextproperty.nitems,
1623 &xtextproperty.value)
1630 if (request_target == xa_compound_text)
1635 XmbTextPropertyToTextList(DPY, &xtextproperty, &list, &count);
1641 for (i = 0; i < count; i++)
1643 /* Paste the text. */
1644 err = type_string(list[i], 0);
1649 /* Free the string */
1650 XFreeStringList(list);
1653 else /* if (request_target == XA_STRING) */
1655 /* Paste the text. */
1656 err = type_string((char *)xtextproperty.value, xtextproperty.nitems);
1659 /* Free the data pasted. */
1660 XFree(xtextproperty.value);
1665 plog("Paste failure (too much text selected).");
1671 * Add a character to a string in preparation for sending it to another
1672 * client as a STRING.
1673 * This doesn't change anything, as clients tend not to have difficulty in
1674 * receiving this format (although the standard specifies a restricted set).
1675 * Strings do not have a colour.
1677 static bool paste_x11_send_text(XSelectionRequestEvent *rq)
1687 /* Too old, or incorrect call. */
1688 if (rq->time < s_ptr->time) return FALSE;
1690 /* Work out which way around to paste. */
1691 sort_co_ord(&min, &max, &s_ptr->init, &s_ptr->cur);
1694 if (XGetSelectionOwner(DPY, XA_PRIMARY) != WIN)
1696 /* bell("Someone stole my selection!"); */
1700 /* Delete the old value of the property. */
1701 XDeleteProperty(DPY, rq->requestor, rq->property);
1703 for (n = 0, y = 0; y < Term->hgt; y++)
1708 if (y < min.y) continue;
1709 if (y > max.y) break;
1711 for (l = 0, x = 0; x < Term->wid; x++)
1714 if (x > max.x) break;
1716 /* Find the character. */
1717 Term_what(x, y, &a, &c);
1719 if (1 == kanji) kanji = 2;
1720 else if (iskanji(c)) kanji = 1;
1723 if (x < min.x) continue;
1726 * A single kanji character was divided in two...
1727 * Delete the garbage.
1729 if ((2 == kanji && x == min.x) ||
1730 (1 == kanji && x == max.x))
1733 if (x > max.x) break;
1734 if (x < min.x) continue;
1736 /* Find the character. */
1737 Term_what(x, y, &a, &c);
1745 /* Ignore trailing spaces */
1746 while (buf[l-1] == ' ') l--;
1748 /* Terminate all line unless it's single line. */
1758 list[n++] = (char *)string_make(buf);
1761 /* End of the list */
1765 if (rq->target == XA_STRING)
1767 for (n = 0; list[n]; n++)
1769 /* Send the (non-empty) string. */
1770 XChangeProperty(DPY, rq->requestor, rq->property, rq->target, 8,
1771 PropModeAppend, (unsigned char *)list[n], strlen(list[n]));
1775 else if (rq->target == xa_text ||
1776 rq->target == xa_compound_text)
1778 XTextProperty text_prop;
1779 XICCEncodingStyle style;
1781 if (rq->target == xa_text)
1782 style = XStdICCTextStyle;
1783 else /* if (rq->target == xa_compound_text) */
1784 style = XCompoundTextStyle;
1787 XmbTextListToTextProperty(DPY, list, n, style, &text_prop))
1789 /* Send the compound text */
1790 XChangeProperty(DPY,
1799 /* Free the data. */
1800 XFree(text_prop.value);
1804 /* Free the list of strings */
1805 for (n = 0; list[n]; n++)
1807 string_free(list[n]);
1814 * Send some text requested by another X client.
1816 static void paste_x11_send(XSelectionRequestEvent *rq)
1819 XSelectionEvent *ptr = &(event.xselection);
1821 /* Set the event parameters. */
1822 ptr->type = SelectionNotify;
1823 ptr->property = rq->property;
1824 ptr->display = rq->display;
1825 ptr->requestor = rq->requestor;
1826 ptr->selection = rq->selection;
1827 ptr->target = rq->target;
1828 ptr->time = rq->time;
1830 /* Paste the appropriate information for each target type.
1831 * Note that this currently rejects MULTIPLE targets.
1834 if (rq->target == XA_STRING ||
1835 rq->target == xa_text ||
1836 rq->target == xa_compound_text)
1838 if (!paste_x11_send_text(rq))
1839 ptr->property = None;
1841 else if (rq->target == xa_targets)
1843 Atom target_list[4];
1844 target_list[0] = XA_STRING;
1845 target_list[1] = xa_text;
1846 target_list[2] = xa_compound_text;
1847 target_list[3] = xa_targets;
1848 XChangeProperty(DPY, rq->requestor, rq->property, rq->target,
1849 (8 * sizeof(target_list[0])), PropModeReplace,
1850 (unsigned char *)target_list,
1851 (sizeof(target_list) / sizeof(target_list[0])));
1853 else if (rq->target == xa_timestamp)
1855 XChangeProperty(DPY, rq->requestor, rq->property, rq->target,
1856 (8 * sizeof(Time)), PropModeReplace,
1857 (unsigned char *)s_ptr->time, 1);
1861 ptr->property = None;
1864 /* Send whatever event we're left with. */
1865 XSendEvent(DPY, rq->requestor, FALSE, NoEventMask, &event);
1870 * Handle various events conditional on presses of a mouse button.
1872 static void handle_button(Time time, int x, int y, int button,
1875 /* The co-ordinates are only used in Angband format. */
1876 pixel_to_square(&x, &y, x, y);
1878 if (press && button == 1) copy_x11_start(x, y);
1879 if (!press && button == 1) copy_x11_end(time);
1880 if (!press && button == 2) paste_x11_request(xa_compound_text, time);
1887 static errr CheckEvent(bool wait)
1889 term_data *old_td = (term_data*)(Term->data);
1891 XEvent xev_body, *xev = &xev_body;
1893 term_data *td = NULL;
1894 infowin *iwin = NULL;
1903 /* Do not wait unless requested */
1904 if (!wait && !XPending(Metadpy->dpy)) return (1);
1907 * Hack - redraw the selection, if needed.
1908 * This doesn't actually check that one of its squares was drawn to,
1909 * only that this may have happened.
1911 if (s_ptr->select && !s_ptr->drawn) mark_selection();
1913 /* Load the Event */
1914 XNextEvent(Metadpy->dpy, xev);
1917 } while (XFilterEvent(xev, xev->xany.window));
1920 /* Notice new keymaps */
1921 if (xev->type == MappingNotify)
1923 XRefreshKeyboardMapping(&xev->xmapping);
1928 /* Scan the windows */
1929 for (i = 0; i < MAX_TERM_DATA; i++)
1931 if (!data[i].win) continue;
1932 if (xev->xany.window == data[i].win->win)
1940 /* Unknown window */
1941 if (!td || !iwin) return (0);
1944 /* Hack -- activate the Term */
1945 Term_activate(&td->t);
1947 /* Hack -- activate the window */
1951 /* Switch on the Type */
1957 bool press = (xev->type == ButtonPress);
1959 /* Where is the mouse */
1960 int x = xev->xbutton.x;
1961 int y = xev->xbutton.y;
1965 /* Which button is involved */
1966 if (xev->xbutton.button == Button1) z = 1;
1967 else if (xev->xbutton.button == Button2) z = 2;
1968 else if (xev->xbutton.button == Button3) z = 3;
1969 else if (xev->xbutton.button == Button4) z = 4;
1970 else if (xev->xbutton.button == Button5) z = 5;
1974 handle_button(xev->xbutton.time, x, y, z, press);
1989 /* Where is the mouse */
1990 int x = xev->xmotion.x;
1991 int y = xev->xmotion.y;
1992 unsigned int z = xev->xmotion.state;
1994 /* Convert to co-ordinates Angband understands. */
1995 pixel_to_square(&x, &y, x, y);
1997 /* Highlight the current square, if appropriate. */
1998 /* highlight_square(window, y, x); */
2000 /* Alter the selection if appropriate. */
2001 copy_x11_cont(x, y, z);
2008 case SelectionNotify:
2010 paste_x11_accept(&(xev->xselection));
2014 case SelectionRequest:
2016 paste_x11_send(&(xev->xselectionrequest));
2020 case SelectionClear:
2022 s_ptr->select = FALSE;
2035 /* Hack -- use "old" term */
2036 Term_activate(&old_td->t);
2038 /* Process the key */
2039 react_keypress(&(xev->xkey));
2048 /* Ignore "extra" exposes */
2049 /*if (xev->xexpose.count) break;*/
2051 /* Clear the window */
2054 x1 = (xev->xexpose.x - Infowin->ox)/Infofnt->wid;
2055 x2 = (xev->xexpose.x + xev->xexpose.width -
2056 Infowin->ox)/Infofnt->wid;
2058 y1 = (xev->xexpose.y - Infowin->oy)/Infofnt->hgt;
2059 y2 = (xev->xexpose.y + xev->xexpose.height -
2060 Infowin->oy)/Infofnt->hgt;
2062 Term_redraw_section(x1, y1, x2, y2);
2072 Infowin->mapped = 1;
2073 Term->mapped_flag = TRUE;
2079 Infowin->mapped = 0;
2080 Term->mapped_flag = FALSE;
2084 /* Move and/or Resize */
2085 case ConfigureNotify:
2087 int cols, rows, wid, hgt;
2089 int ox = Infowin->ox;
2090 int oy = Infowin->oy;
2092 /* Save the new Window Parms */
2093 Infowin->x = xev->xconfigure.x;
2094 Infowin->y = xev->xconfigure.y;
2095 Infowin->w = xev->xconfigure.width;
2096 Infowin->h = xev->xconfigure.height;
2098 /* Determine "proper" number of rows/cols */
2099 cols = ((Infowin->w - (ox + ox)) / td->fnt->wid);
2100 rows = ((Infowin->h - (oy + oy)) / td->fnt->hgt);
2102 /* Hack -- minimal size */
2103 if (cols < 1) cols = 1;
2104 if (rows < 1) rows = 1;
2108 /* Hack the main window must be at least 80x24 */
2109 if (cols < 80) cols = 80;
2110 if (rows < 24) rows = 24;
2113 /* Desired size of window */
2114 wid = cols * td->fnt->wid + (ox + ox);
2115 hgt = rows * td->fnt->hgt + (oy + oy);
2117 /* Resize the Term (if needed) */
2118 Term_resize(cols, rows);
2120 /* Resize the windows if any "change" is needed */
2121 if ((Infowin->w != wid) || (Infowin->h != hgt))
2124 Infowin_set(td->win);
2125 Infowin_resize(wid, hgt);
2134 XSetICFocus(iwin->xic);
2142 XUnsetICFocus(iwin->xic);
2144 /* Focuswin = NULL;*/
2151 /* Hack -- Activate the old term */
2152 Term_activate(&old_td->t);
2154 /* Hack -- Activate the proper window */
2155 Infowin_set(old_td->win);
2164 * Standard sound names
2166 static const concptr angband_sound_name[SOUND_MAX] =
2238 * An array of sound file names
2240 static concptr sound_file[SOUND_MAX];
2243 * Check for existance of a file
2245 static bool check_file(concptr s)
2249 fff = fopen(s, "r");
2250 if (!fff) return (FALSE);
2259 static void init_sound(void)
2264 char dir_xtra_sound[1024];
2266 /* Build the "sound" path */
2267 path_build(dir_xtra_sound, sizeof(dir_xtra_sound), ANGBAND_DIR_XTRA, "sound");
2269 /* Prepare the sounds */
2270 for (i = 1; i < SOUND_MAX; i++)
2272 /* Extract name of sound file */
2273 sprintf(wav, "%s.wav", angband_sound_name[i]);
2275 /* Access the sound */
2276 path_build(buf, sizeof(buf), dir_xtra_sound, wav);
2278 /* Save the sound filename, if it exists */
2279 if (check_file(buf)) sound_file[i] = string_make(buf);
2286 * Hack -- make a sound
2288 static errr Term_xtra_x11_sound(int v)
2292 /* Sound disabled */
2293 if (!use_sound) return (1);
2296 if ((v < 0) || (v >= SOUND_MAX)) return (1);
2299 if (!sound_file[v]) return (1);
2301 sprintf(buf,"./playwave.sh %s\n", sound_file[v]);
2303 return (system(buf) < 0);
2309 * Handle "activation" of a term
2311 static errr Term_xtra_x11_level(int v)
2313 term_data *td = (term_data*)(Term->data);
2315 /* Handle "activate" */
2318 /* Activate the window */
2319 Infowin_set(td->win);
2321 /* Activate the font */
2322 Infofnt_set(td->fnt);
2333 static errr Term_xtra_x11_react(void)
2339 /* Check the colors */
2340 for (i = 0; i < 256; i++)
2342 if ((color_table[i][0] != angband_color_table[i][0]) ||
2343 (color_table[i][1] != angband_color_table[i][1]) ||
2344 (color_table[i][2] != angband_color_table[i][2]) ||
2345 (color_table[i][3] != angband_color_table[i][3]))
2349 /* Save new values */
2350 color_table[i][0] = angband_color_table[i][0];
2351 color_table[i][1] = angband_color_table[i][1];
2352 color_table[i][2] = angband_color_table[i][2];
2353 color_table[i][3] = angband_color_table[i][3];
2356 pixel = create_pixel(Metadpy->dpy,
2361 /* Change the foreground */
2362 Infoclr_set(clr[i]);
2363 Infoclr_change_fg(pixel);
2374 * Handle a "special request"
2376 static errr Term_xtra_x11(int n, int v)
2378 /* Handle a subset of the legal requests */
2382 case TERM_XTRA_NOISE: Metadpy_do_beep(); return (0);
2384 /* Make a special sound */
2385 case TERM_XTRA_SOUND: return (Term_xtra_x11_sound(v));
2387 /* Flush the output XXX XXX */
2388 case TERM_XTRA_FRESH: Metadpy_update(1, 0, 0); return (0);
2390 /* Process random events XXX */
2391 case TERM_XTRA_BORED: return (CheckEvent(0));
2393 /* Process Events XXX */
2394 case TERM_XTRA_EVENT: return (CheckEvent(v));
2396 /* Flush the events XXX */
2397 case TERM_XTRA_FLUSH: while (!CheckEvent(FALSE)); return (0);
2399 /* Handle change in the "level" */
2400 case TERM_XTRA_LEVEL: return (Term_xtra_x11_level(v));
2402 /* Clear the screen */
2403 case TERM_XTRA_CLEAR: Infowin_wipe(); s_ptr->drawn = FALSE; return (0);
2405 /* Delay for some milliseconds */
2406 case TERM_XTRA_DELAY: usleep(1000 * v); return (0);
2408 /* React to changes */
2409 case TERM_XTRA_REACT: return (Term_xtra_x11_react());
2418 * Draw the cursor as an inverted rectangle.
2420 * Consider a rectangular outline like "main-mac.c". XXX XXX
2422 static errr Term_curs_x11(int x, int y)
2426 XDrawRectangle(Metadpy->dpy, Infowin->win, xor->gc,
2427 x * Infofnt->wid + Infowin->ox,
2428 y * Infofnt->hgt + Infowin->oy,
2429 Infofnt->wid - 1, Infofnt->hgt - 1);
2430 XDrawRectangle(Metadpy->dpy, Infowin->win, xor->gc,
2431 x * Infofnt->wid + Infowin->ox + 1,
2432 y * Infofnt->hgt + Infowin->oy + 1,
2433 Infofnt->wid - 3, Infofnt->hgt - 3);
2437 /* Draw the cursor */
2440 /* Hilite the cursor character */
2441 Infofnt_text_non(x, y, " ", 1);
2450 * Draw the double width cursor
2452 static errr Term_bigcurs_x11(int x, int y)
2456 XDrawRectangle(Metadpy->dpy, Infowin->win, xor->gc,
2457 x * Infofnt->wid + Infowin->ox,
2458 y * Infofnt->hgt + Infowin->oy,
2459 Infofnt->twid - 1, Infofnt->hgt - 1);
2460 XDrawRectangle(Metadpy->dpy, Infowin->win, xor->gc,
2461 x * Infofnt->wid + Infowin->ox + 1,
2462 y * Infofnt->hgt + Infowin->oy + 1,
2463 Infofnt->twid - 3, Infofnt->hgt - 3);
2467 /* Draw the cursor */
2470 /* Hilite the cursor character */
2471 Infofnt_text_non(x, y, " ", 2);
2479 * Erase some characters.
2481 static errr Term_wipe_x11(int x, int y, int n)
2483 /* Erase (use black) */
2484 Infoclr_set(clr[TERM_DARK]);
2486 /* Mega-Hack -- Erase some space */
2487 Infofnt_text_non(x, y, "", n);
2489 /* Redraw the selection if any, as it may have been obscured. (later) */
2490 s_ptr->drawn = FALSE;
2498 * Draw some textual characters.
2500 static errr Term_text_x11(TERM_LEN x, TERM_LEN y, int n, TERM_COLOR a, concptr s)
2503 Infoclr_set(clr[a]);
2506 Infofnt_text_std(x, y, s, n);
2508 /* Redraw the selection if any, as it may have been obscured. (later) */
2509 s_ptr->drawn = FALSE;
2517 * Draw some graphical characters.
2519 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)
2532 unsigned long pixel, blank;
2534 term_data *td = (term_data*)(Term->data);
2539 /* Add in affect of window boundaries */
2543 for (i = 0; i < n; ++i, x += td->fnt->wid)
2548 /* For extra speed - cache these values */
2549 x1 = (c&0x7F) * td->fnt->twid;
2550 y1 = (a&0x7F) * td->fnt->hgt;
2552 /* Illegal tile index */
2553 if (td->tiles->width < x1 + td->fnt->wid ||
2554 td->tiles->height < y1 + td->fnt->hgt)
2556 /* Draw black square */
2557 XFillRectangle(Metadpy->dpy, td->win->win, clr[0]->gc,
2559 td->fnt->twid, td->fnt->hgt);
2561 /* Skip drawing tile */
2568 /* For extra speed - cache these values */
2569 x2 = (tc&0x7F) * td->fnt->twid;
2570 y2 = (ta&0x7F) * td->fnt->hgt;
2572 /* Optimise the common case */
2573 if (((x1 == x2) && (y1 == y2)) ||
2574 !(((byte)ta & 0x80) && ((byte)tc & 0x80)) ||
2575 td->tiles->width < x2 + td->fnt->wid ||
2576 td->tiles->height < y2 + td->fnt->hgt)
2578 /* Draw object / terrain */
2579 XPutImage(Metadpy->dpy, td->win->win,
2584 td->fnt->twid, td->fnt->hgt);
2589 /* Mega Hack^2 - assume the top left corner is "black" */
2590 blank = XGetPixel(td->tiles, 0, td->fnt->hgt * 6);
2592 for (k = 0; k < td->fnt->twid; k++)
2594 for (l = 0; l < td->fnt->hgt; l++)
2596 /* If mask set... */
2597 if ((pixel = XGetPixel(td->tiles, x1 + k, y1 + l)) == blank)
2599 /* Output from the terrain */
2600 pixel = XGetPixel(td->tiles, x2 + k, y2 + l);
2603 /* Store into the temp storage. */
2604 XPutPixel(td->TmpImage, k, l, pixel);
2609 /* Draw to screen */
2611 XPutImage(Metadpy->dpy, td->win->win,
2615 td->fnt->twid, td->fnt->hgt);
2619 /* Redraw the selection if any, as it may have been obscured. (later) */
2620 s_ptr->drawn = FALSE;
2627 static void IMDestroyCallback(XIM, XPointer, XPointer);
2630 IMInstantiateCallback(Display *display, XPointer unused1, XPointer unused2)
2633 XIMCallback ximcallback;
2634 XIMStyles *xim_styles = NULL;
2641 xim = XOpenIM(display, NULL, NULL, NULL);
2643 printf("can't open IM\n");
2647 /* initialize destroy callback */
2648 ximcallback.callback = IMDestroyCallback;
2649 ximcallback.client_data = NULL;
2650 XSetIMValues(xim, XNDestroyCallback, &ximcallback, NULL);
2652 /* set style (only "Root" is supported yet...) */
2653 XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL);
2654 for (i = 0; i < xim_styles->count_styles; i++){
2655 if(xim_styles->supported_styles[i] == (XIMPreeditNothing | XIMStatusNothing)) break;
2657 if(i >= xim_styles->count_styles){
2658 printf("Sorry, your IM does not support 'Root' preedit style...\n");
2666 for (i = 0; i < MAX_TERM_DATA; i++)
2668 infowin *iwin = data[i].win;
2669 if (!iwin) continue;
2670 iwin->xic = XCreateIC(xim, XNInputStyle, (XIMPreeditNothing | XIMStatusNothing), XNClientWindow, iwin->win, XNFocusWindow, iwin->win, NULL);
2672 printf("Can't create input context for Term%d\n", i);
2675 if(XGetICValues(iwin->xic, XNFilterEvents, &iwin->xic_mask, NULL) != NULL){
2676 /* printf("Can't get XNFilterEvents\n"); */
2677 iwin->xic_mask = 0L;
2679 XSelectInput(Metadpy->dpy, iwin->win, iwin->mask | iwin->xic_mask);
2685 static void IMDestroyCallback(XIM xim, XPointer client_data, XPointer call_data)
2693 if (call_data == NULL){
2694 XRegisterIMInstantiateCallback(Metadpy->dpy, NULL, NULL, NULL, IMInstantiateCallback, NULL);
2697 for(i = 0; i < MAX_TERM_DATA; i++)
2699 infowin *iwin = data[i].win;
2702 XSelectInput(Metadpy->dpy, iwin->win, iwin->mask);
2703 iwin->xic_mask = 0L;
2708 Metadpy->xim = NULL;
2713 * Initialize a term_data
2715 static errr term_data_init(term_data *td, int i)
2719 concptr name = angband_term_name[i];
2749 /* Window specific font name */
2750 sprintf(buf, "ANGBAND_X11_FONT_%d", i);
2752 /* Check environment for that font */
2755 /* Check environment for "base" font */
2756 if (!font) font = getenv("ANGBAND_X11_FONT");
2758 /* No environment variables, use default font */
2765 font = DEFAULT_X11_FONT_0;
2770 font = DEFAULT_X11_FONT_1;
2775 font = DEFAULT_X11_FONT_2;
2780 font = DEFAULT_X11_FONT_3;
2785 font = DEFAULT_X11_FONT_4;
2790 font = DEFAULT_X11_FONT_5;
2795 font = DEFAULT_X11_FONT_6;
2800 font = DEFAULT_X11_FONT_7;
2805 font = DEFAULT_X11_FONT;
2810 /* Window specific location (x) */
2811 sprintf(buf, "ANGBAND_X11_AT_X_%d", i);
2813 x = (str != NULL) ? atoi(str) : -1;
2815 /* Window specific location (y) */
2816 sprintf(buf, "ANGBAND_X11_AT_Y_%d", i);
2818 y = (str != NULL) ? atoi(str) : -1;
2821 /* Window specific cols */
2822 sprintf(buf, "ANGBAND_X11_COLS_%d", i);
2824 val = (str != NULL) ? atoi(str) : -1;
2825 if (val > 0) cols = val;
2827 /* Window specific rows */
2828 sprintf(buf, "ANGBAND_X11_ROWS_%d", i);
2830 val = (str != NULL) ? atoi(str) : -1;
2831 if (val > 0) rows = val;
2833 /* Hack the main window must be at least 80x24 */
2836 if (cols < 80) cols = 80;
2837 if (rows < 24) rows = 24;
2840 /* Window specific inner border offset (ox) */
2841 sprintf(buf, "ANGBAND_X11_IBOX_%d", i);
2843 val = (str != NULL) ? atoi(str) : -1;
2844 if (val > 0) ox = val;
2846 /* Window specific inner border offset (oy) */
2847 sprintf(buf, "ANGBAND_X11_IBOY_%d", i);
2849 val = (str != NULL) ? atoi(str) : -1;
2850 if (val > 0) oy = val;
2853 /* Prepare the standard font */
2854 MAKE(td->fnt, infofnt);
2855 Infofnt_set(td->fnt);
2856 Infofnt_init_data(font);
2858 /* Hack -- key buffer size */
2859 num = ((i == 0) ? 1024 : 16);
2861 /* Assume full size windows */
2862 wid = cols * td->fnt->wid + (ox + ox);
2863 hgt = rows * td->fnt->hgt + (oy + oy);
2865 /* Create a top-window */
2866 MAKE(td->win, infowin);
2867 Infowin_set(td->win);
2868 Infowin_init_top(x, y, wid, hgt, 0,
2869 Metadpy->fg, Metadpy->bg);
2871 /* Ask for certain events */
2872 #if defined(USE_XIM)
2873 Infowin_set_mask(ExposureMask | StructureNotifyMask | KeyPressMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask | FocusChangeMask);
2875 Infowin_set_mask(ExposureMask | StructureNotifyMask | KeyPressMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask);
2878 /* Set the window name */
2879 Infowin_set_name(name);
2881 /* Save the inner border */
2885 /* Make Class Hints */
2886 ch = XAllocClassHint();
2888 if (ch == NULL) quit("XAllocClassHint failed");
2890 strcpy(res_name, name);
2891 res_name[0] = FORCELOWER(res_name[0]);
2892 ch->res_name = res_name;
2894 strcpy(res_class, "Angband");
2895 ch->res_class = res_class;
2897 XSetClassHint(Metadpy->dpy, Infowin->win, ch);
2899 /* Make Size Hints */
2900 sh = XAllocSizeHints();
2903 if (sh == NULL) quit("XAllocSizeHints failed");
2905 /* Main window has a differing minimum size */
2908 /* Main window min size is 80x24 */
2909 sh->flags = PMinSize | PMaxSize;
2910 sh->min_width = 80 * td->fnt->wid + (ox + ox);
2911 sh->min_height = 24 * td->fnt->hgt + (oy + oy);
2912 sh->max_width = 255 * td->fnt->wid + (ox + ox);
2913 sh->max_height = 255 * td->fnt->hgt + (oy + oy);
2916 /* Other windows can be shrunk to 1x1 */
2920 sh->flags = PMinSize | PMaxSize;
2921 sh->min_width = td->fnt->wid + (ox + ox);
2922 sh->min_height = td->fnt->hgt + (oy + oy);
2923 sh->max_width = 256 * td->fnt->wid + (ox + ox);
2924 sh->max_height = 256 * td->fnt->hgt + (oy + oy);
2927 /* Resize increment */
2928 sh->flags |= PResizeInc;
2929 sh->width_inc = td->fnt->wid;
2930 sh->height_inc = td->fnt->hgt;
2932 /* Base window size */
2933 sh->flags |= PBaseSize;
2934 sh->base_width = (ox + ox);
2935 sh->base_height = (oy + oy);
2937 /* Use the size hints */
2938 XSetWMNormalHints(Metadpy->dpy, Infowin->win, sh);
2940 /* Map the window */
2945 wh = XAllocWMHints();
2946 if(wh == NULL) quit("XAllocWMHints failed");
2947 wh->flags = InputHint;
2949 XSetWMHints(Metadpy->dpy, Infowin->win, wh);
2952 /* Move the window to requested location */
2953 if ((x >= 0) && (y >= 0)) Infowin_impell(x, y);
2956 /* Initialize the term */
2957 term_init(t, cols, rows, num);
2959 /* Use a "soft" cursor */
2960 t->soft_cursor = TRUE;
2962 /* Erase with "white space" */
2963 t->attr_blank = TERM_WHITE;
2964 t->char_blank = ' ';
2967 t->xtra_hook = Term_xtra_x11;
2968 t->curs_hook = Term_curs_x11;
2969 t->bigcurs_hook = Term_bigcurs_x11;
2970 t->wipe_hook = Term_wipe_x11;
2971 t->text_hook = Term_text_x11;
2976 /* Activate (important) */
2985 * Initialization function for an "X11" module to Angband
2987 errr init_x11(int argc, char *argv[])
2991 concptr dpy_name = "";
2995 char filename[1024];
3003 for (i = 1; i < argc; i++)
3005 if (prefix(argv[i], "-d"))
3007 dpy_name = &argv[i][2];
3011 if (prefix(argv[i], "-s"))
3013 smoothRescaling = FALSE;
3017 if (prefix(argv[i], "-a"))
3019 arg_graphics = GRAPHICS_ADAM_BOLT;
3023 if (prefix(argv[i], "-o"))
3025 arg_graphics = GRAPHICS_ORIGINAL;
3029 if (prefix(argv[i], "-b"))
3031 arg_bigtile = use_bigtile = TRUE;
3035 if (prefix(argv[i], "-n"))
3037 num_term = atoi(&argv[i][2]);
3038 if (num_term > MAX_TERM_DATA) num_term = MAX_TERM_DATA;
3039 else if (num_term < 1) num_term = 1;
3043 if (prefix(argv[i], "--"))
3049 plog_fmt("Ignoring option: %s", argv[i]);
3055 /* Get locale information from environment variables */
3056 setlocale(LC_ALL, "");
3058 #ifdef DEFAULT_LOCALE
3059 if(!strcmp(setlocale(LC_ALL, NULL), "C")){
3060 printf("try default locale \"%s\"\n", DEFAULT_LOCALE);
3061 setlocale(LC_ALL, DEFAULT_LOCALE);
3065 if(!strcmp(setlocale(LC_ALL, NULL), "C"))
3067 printf("WARNING: Locale is not supported. Non-english font may be displayed incorrectly.\n");
3070 if(!XSupportsLocale()){
3071 printf("can't support locale in X\n");
3072 setlocale(LC_ALL, "C");
3075 /* Set locale to "C" without using environment variables */
3076 setlocale(LC_ALL, "C");
3079 #endif /* USE_LOCALE */
3082 /* Init the Metadpy if possible */
3083 if (Metadpy_init_name(dpy_name)) return (-1);
3086 /* Prepare cursor color */
3089 Infoclr_init_ppn(Metadpy->fg, Metadpy->bg, "xor", 0);
3092 /* Prepare normal colors */
3093 for (i = 0; i < 256; ++i)
3097 MAKE(clr[i], infoclr);
3099 Infoclr_set(clr[i]);
3101 /* Acquire Angband colors */
3102 color_table[i][0] = angband_color_table[i][0];
3103 color_table[i][1] = angband_color_table[i][1];
3104 color_table[i][2] = angband_color_table[i][2];
3105 color_table[i][3] = angband_color_table[i][3];
3107 /* Default to monochrome */
3108 pixel = ((i == 0) ? Metadpy->bg : Metadpy->fg);
3114 pixel = create_pixel(Metadpy->dpy,
3120 /* Initialize the color */
3121 Infoclr_init_ppn(pixel, Metadpy->bg, "cpy", 0);
3125 /* Prepare required atoms. */
3129 /* Initialize the windows */
3130 for (i = 0; i < num_term; i++)
3132 term_data *td = &data[i];
3134 /* Initialize the term_data */
3135 term_data_init(td, i);
3137 /* Save global entry */
3138 angband_term[i] = Term;
3141 /* Raise the "Angband" window */
3142 Infowin_set(data[0].win);
3145 /* Activate the "Angband" window screen */
3146 Term_activate(&data[0].t);
3151 p = XSetLocaleModifiers("");
3153 p = XSetLocaleModifiers("@im=");
3155 /* printf("XMODIFIERS=\"%s\"\n", p); */
3157 XRegisterIMInstantiateCallback(Metadpy->dpy, NULL, NULL, NULL, IMInstantiateCallback, NULL);
3160 /* initialize sound */
3161 if (arg_sound) init_sound();
3164 switch (arg_graphics)
3166 case GRAPHICS_ORIGINAL:
3167 /* Try the "8x8.bmp" file */
3168 path_build(filename, sizeof(filename), ANGBAND_DIR_XTRA, "graf/8x8.bmp");
3170 /* Use the "8x8.bmp" file if it exists */
3171 if (0 == fd_close(fd_open(filename, O_RDONLY)))
3174 use_graphics = TRUE;
3176 pict_wid = pict_hgt = 8;
3178 ANGBAND_GRAF = "old";
3183 case GRAPHICS_ADAM_BOLT:
3184 /* Try the "16x16.bmp" file */
3185 path_build(filename, sizeof(filename), ANGBAND_DIR_XTRA, "graf/16x16.bmp");
3187 /* Use the "16x16.bmp" file if it exists */
3188 if (0 == fd_close(fd_open(filename, O_RDONLY)))
3191 use_graphics = TRUE;
3193 pict_wid = pict_hgt = 16;
3195 ANGBAND_GRAF = "new";
3204 Display *dpy = Metadpy->dpy;
3208 /* Load the graphical tiles */
3209 tiles_raw = ReadBMP(dpy, filename);
3211 /* Initialize the windows */
3212 for (i = 0; i < num_term; i++)
3214 term_data *td = &data[i];
3219 t->pict_hook = Term_pict_x11;
3221 /* Use graphics sometimes */
3222 t->higher_pict = TRUE;
3226 ResizeImage(dpy, tiles_raw,
3228 td->fnt->twid, td->fnt->hgt);
3231 /* Initialize the transparency masks */
3232 for (i = 0; i < num_term; i++)
3234 term_data *td = &data[i];
3236 int depth = DefaultDepth(dpy, DefaultScreen(dpy));
3237 Visual *visual = DefaultVisual(dpy, DefaultScreen(dpy));
3241 /* Determine total bytes needed for image */
3243 jj = (depth - 1) >> 2;
3244 while (jj >>= 1) ii <<= 1;
3245 total = td->fnt->twid * td->fnt->hgt * ii;
3248 TmpData = (char *)malloc(total);
3250 td->TmpImage = XCreateImage(dpy,visual,depth,
3251 ZPixmap, 0, TmpData,
3252 td->fnt->twid, td->fnt->hgt, 8, 0);
3256 /* Free tiles_raw? XXX XXX */
3263 #endif /* USE_X11 */