]> icculus.org git repositories - dana/openbox.git/blob - src/BaseDisplay.cc
using some references instead of pointers where possible in Screen, ScreenInfo, Slit...
[dana/openbox.git] / src / BaseDisplay.cc
1 // BaseDisplay.cc for Openbox
2 // Copyright (c) 2001 Sean 'Shaleh' Perry <shaleh@debian.org>
3 // Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a
6 // copy of this software and associated documentation files (the "Software"),
7 // to deal in the Software without restriction, including without limitation
8 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 // and/or sell copies of the Software, and to permit persons to whom the
10 // Software is furnished to do so, subject to the following conditions:
11 //
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 // DEALINGS IN THE SOFTWARE.
22
23 // stupid macros needed to access some functions in version 2 of the GNU C
24 // library
25 #ifndef   _GNU_SOURCE
26 #define   _GNU_SOURCE
27 #endif // _GNU_SOURCE
28
29 #ifdef    HAVE_CONFIG_H
30 #  include "../config.h"
31 #endif // HAVE_CONFIG_H
32
33 #include <X11/Xlib.h>
34 #include <X11/Xatom.h>
35 #include <X11/Xutil.h>
36 #include <X11/cursorfont.h>
37 #include <X11/keysym.h>
38
39 #ifdef    SHAPE
40 #  include <X11/extensions/shape.h>
41 #endif // SHAPE
42
43 #ifdef    HAVE_FCNTL_H
44 #  include <fcntl.h>
45 #endif // HAVE_FCNTL_H
46
47 #ifdef    HAVE_STDIO_H
48 #  include <stdio.h>
49 #endif // HAVE_STDIO_H
50
51 #ifdef    STDC_HEADERS
52 #  include <stdlib.h>
53 #  include <string.h>
54 #endif // STDC_HEADERS
55
56 #ifdef    HAVE_UNISTD_H
57 #  include <sys/types.h>
58 #  include <unistd.h>
59 #endif // HAVE_UNISTD_H
60
61 #ifdef    HAVE_SYS_SELECT_H
62 #  include <sys/select.h>
63 #endif // HAVE_SYS_SELECT_H
64
65 #ifdef    HAVE_SIGNAL_H
66 #  include <signal.h>
67 #endif // HAVE_SIGNAL_H
68
69 #ifndef   SA_NODEFER
70 #  ifdef   SA_INTERRUPT
71 #    define SA_NODEFER SA_INTERRUPT
72 #  else // !SA_INTERRUPT
73 #    define SA_NODEFER (0)
74 #  endif // SA_INTERRUPT
75 #endif // SA_NODEFER
76
77 #ifdef    HAVE_SYS_WAIT_H
78 #  include <sys/types.h>
79 #  include <sys/wait.h>
80 #endif // HAVE_SYS_WAIT_H
81
82 #if defined(HAVE_PROCESS_H) && defined(__EMX__)
83 #  include <process.h>
84 #endif //   HAVE_PROCESS_H             __EMX__
85
86 #include "i18n.h"
87 #include "BaseDisplay.h"
88 #include "LinkedList.h"
89 #include "Timer.h"
90
91 // X error handler to handle any and all X errors while the application is
92 // running
93 static Bool internal_error = False;
94 static Window last_bad_window = None;
95
96 BaseDisplay *base_display;
97
98 static int handleXErrors(Display *d, XErrorEvent *e) {
99 #ifdef    DEBUG
100   char errtxt[128];
101
102   XGetErrorText(d, e->error_code, errtxt, 128);
103   fprintf(stderr, i18n->getMessage(BaseDisplaySet, BaseDisplayXError,
104                      "%s:  X error: %s(%d) opcodes %d/%d\n  resource 0x%lx\n"),
105           base_display->getApplicationName(), errtxt, e->error_code,
106           e->request_code, e->minor_code, e->resourceid);
107 #endif // DEBUG
108
109   if (e->error_code == BadWindow) last_bad_window = e->resourceid;
110   if (internal_error) abort();
111
112   return(False);
113 }
114
115
116 // signal handler to allow for proper and gentle shutdown
117
118 #ifndef   HAVE_SIGACTION
119 static RETSIGTYPE signalhandler(int sig) {
120 #else //  HAVE_SIGACTION
121 static void signalhandler(int sig) {
122 #endif // HAVE_SIGACTION
123
124   static int re_enter = 0;
125
126   switch (sig) {
127   case SIGCHLD:
128     int status;
129     waitpid(-1, &status, WNOHANG | WUNTRACED);
130
131 #ifndef   HAVE_SIGACTION
132     // assume broken, braindead sysv signal semantics
133     signal(SIGCHLD, (RETSIGTYPE (*)(int)) signalhandler);
134 #endif // HAVE_SIGACTION
135
136     break;
137
138   default:
139     if (base_display->handleSignal(sig)) {
140
141 #ifndef   HAVE_SIGACTION
142       // assume broken, braindead sysv signal semantics
143       signal(sig, (RETSIGTYPE (*)(int)) signalhandler);
144 #endif // HAVE_SIGACTION
145
146       return;
147     }
148
149     fprintf(stderr, i18n->getMessage(BaseDisplaySet, BaseDisplaySignalCaught,
150                                      "%s:  signal %d caught\n"),
151             base_display->getApplicationName(), sig);
152
153     if (! base_display->isStartup() && ! re_enter) {
154       internal_error = True;
155
156       re_enter = 1;
157       fprintf(stderr, i18n->getMessage(BaseDisplaySet, BaseDisplayShuttingDown,
158                                        "shutting down\n"));
159       base_display->shutdown();
160     }
161
162     if (sig != SIGTERM && sig != SIGINT) {
163       fprintf(stderr, i18n->getMessage(BaseDisplaySet, BaseDisplayAborting,
164                                        "aborting... dumping core\n"));
165       abort();
166     }
167
168     exit(0);
169
170     break;
171   }
172 }
173
174
175 // convenience functions
176 #ifndef    __EMX__
177 void bexec(const char *command, char* displaystring) {
178   if (! fork()) {
179     setsid();
180     putenv(displaystring);
181     execl("/bin/sh", "/bin/sh", "-c", command, NULL);
182     exit(0);
183   }
184 }
185 #endif // !__EMX__
186
187 char *bstrdup(const char *s) {
188   const int l = strlen(s) + 1;
189   char *n = new char[l];
190   strncpy(n, s, l);
191   return n;
192 }
193
194 BaseDisplay::BaseDisplay(char *app_name, char *dpy_name) {
195   application_name = app_name;
196
197   _startup = True;
198   _shutdown = False;
199   server_grabs = 0;
200   last_bad_window = None;
201
202   ::base_display = this;
203
204 #ifdef    HAVE_SIGACTION
205   struct sigaction action;
206
207   action.sa_handler = signalhandler;
208   action.sa_mask = sigset_t();
209   action.sa_flags = SA_NOCLDSTOP | SA_NODEFER;
210
211   sigaction(SIGPIPE, &action, NULL);
212   sigaction(SIGSEGV, &action, NULL);
213   sigaction(SIGFPE, &action, NULL);
214   sigaction(SIGTERM, &action, NULL);
215   sigaction(SIGINT, &action, NULL);
216   sigaction(SIGCHLD, &action, NULL);
217   sigaction(SIGHUP, &action, NULL);
218   sigaction(SIGUSR1, &action, NULL);
219   sigaction(SIGUSR2, &action, NULL);
220 #else // !HAVE_SIGACTION
221   signal(SIGPIPE, (RETSIGTYPE (*)(int)) signalhandler);
222   signal(SIGSEGV, (RETSIGTYPE (*)(int)) signalhandler);
223   signal(SIGFPE, (RETSIGTYPE (*)(int)) signalhandler);
224   signal(SIGTERM, (RETSIGTYPE (*)(int)) signalhandler);
225   signal(SIGINT, (RETSIGTYPE (*)(int)) signalhandler);
226   signal(SIGUSR1, (RETSIGTYPE (*)(int)) signalhandler);
227   signal(SIGUSR2, (RETSIGTYPE (*)(int)) signalhandler);
228   signal(SIGHUP, (RETSIGTYPE (*)(int)) signalhandler);
229   signal(SIGCHLD, (RETSIGTYPE (*)(int)) signalhandler);
230 #endif // HAVE_SIGACTION
231
232   if (! (display = XOpenDisplay(dpy_name))) {
233     fprintf(stderr, i18n->getMessage(BaseDisplaySet, BaseDisplayXConnectFail,
234                "BaseDisplay::BaseDisplay: connection to X server failed.\n"));
235     ::exit(2);
236   } else if (fcntl(ConnectionNumber(display), F_SETFD, 1) == -1) {
237     fprintf(stderr,
238             i18n->getMessage(BaseDisplaySet, BaseDisplayCloseOnExecFail,
239                "BaseDisplay::BaseDisplay: couldn't mark display connection "
240                "as close-on-exec\n"));
241     ::exit(2);
242   }
243
244   number_of_screens = ScreenCount(display);
245   display_name = XDisplayName(dpy_name);
246
247 #ifdef    SHAPE
248   shape.extensions = XShapeQueryExtension(display, &shape.event_basep,
249                                           &shape.error_basep);
250 #else // !SHAPE
251   shape.extensions = False;
252 #endif // SHAPE
253
254   xa_wm_colormap_windows =
255     XInternAtom(display, "WM_COLORMAP_WINDOWS", False);
256   xa_wm_protocols = XInternAtom(display, "WM_PROTOCOLS", False);
257   xa_wm_state = XInternAtom(display, "WM_STATE", False);
258   xa_wm_change_state = XInternAtom(display, "WM_CHANGE_STATE", False);
259   xa_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
260   xa_wm_take_focus = XInternAtom(display, "WM_TAKE_FOCUS", False);
261   motif_wm_hints = XInternAtom(display, "_MOTIF_WM_HINTS", False);
262
263   openbox_hints = XInternAtom(display, "_BLACKBOX_HINTS", False);
264   openbox_attributes = XInternAtom(display, "_BLACKBOX_ATTRIBUTES", False);
265   openbox_change_attributes =
266     XInternAtom(display, "_BLACKBOX_CHANGE_ATTRIBUTES", False);
267
268   openbox_structure_messages =
269     XInternAtom(display, "_BLACKBOX_STRUCTURE_MESSAGES", False);
270   openbox_notify_startup =
271     XInternAtom(display, "_BLACKBOX_NOTIFY_STARTUP", False);
272   openbox_notify_window_add =
273     XInternAtom(display, "_BLACKBOX_NOTIFY_WINDOW_ADD", False);
274   openbox_notify_window_del =
275     XInternAtom(display, "_BLACKBOX_NOTIFY_WINDOW_DEL", False);
276   openbox_notify_current_workspace =
277     XInternAtom(display, "_BLACKBOX_NOTIFY_CURRENT_WORKSPACE", False);
278   openbox_notify_workspace_count =
279     XInternAtom(display, "_BLACKBOX_NOTIFY_WORKSPACE_COUNT", False);
280   openbox_notify_window_focus =
281     XInternAtom(display, "_BLACKBOX_NOTIFY_WINDOW_FOCUS", False);
282   openbox_notify_window_raise =
283     XInternAtom(display, "_BLACKBOX_NOTIFY_WINDOW_RAISE", False);
284   openbox_notify_window_lower =
285     XInternAtom(display, "_BLACKBOX_NOTIFY_WINDOW_LOWER", False);
286
287   openbox_change_workspace =
288     XInternAtom(display, "_BLACKBOX_CHANGE_WORKSPACE", False);
289   openbox_change_window_focus =
290     XInternAtom(display, "_BLACKBOX_CHANGE_WINDOW_FOCUS", False);
291   openbox_cycle_window_focus =
292     XInternAtom(display, "_BLACKBOX_CYCLE_WINDOW_FOCUS", False);
293
294 #ifdef    NEWWMSPEC
295
296   net_supported = XInternAtom(display, "_NET_SUPPORTED", False);
297   net_client_list = XInternAtom(display, "_NET_CLIENT_LIST", False);
298   net_client_list_stacking = XInternAtom(display, "_NET_CLIENT_LIST_STACKING", False);
299   net_number_of_desktops = XInternAtom(display, "_NET_NUMBER_OF_DESKTOPS", False);
300   net_desktop_geometry = XInternAtom(display, "_NET_DESKTOP_GEOMETRY", False);
301   net_desktop_viewport = XInternAtom(display, "_NET_DESKTOP_VIEWPORT", False);
302   net_current_desktop = XInternAtom(display, "_NET_CURRENT_DESKTOP", False);
303   net_desktop_names = XInternAtom(display, "_NET_DESKTOP_NAMES", False);
304   net_active_window = XInternAtom(display, "_NET_ACTIVE_WINDOW", False);
305   net_workarea = XInternAtom(display, "_NET_WORKAREA", False);
306   net_supporting_wm_check = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
307   net_virtual_roots = XInternAtom(display, "_NET_VIRTUAL_ROOTS", False);
308
309   net_close_window = XInternAtom(display, "_NET_CLOSE_WINDOW", False);
310   net_wm_moveresize = XInternAtom(display, "_NET_WM_MOVERESIZE", False);
311
312   net_properties = XInternAtom(display, "_NET_PROPERTIES", False);
313   net_wm_name = XInternAtom(display, "_NET_WM_NAME", False);
314   net_wm_desktop = XInternAtom(display, "_NET_WM_DESKTOP", False);
315   net_wm_window_type = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False);
316   net_wm_state = XInternAtom(display, "_NET_WM_STATE", False);
317   net_wm_strut = XInternAtom(display, "_NET_WM_STRUT", False);
318   net_wm_icon_geometry = XInternAtom(display, "_NET_WM_ICON_GEOMETRY", False);
319   net_wm_icon = XInternAtom(display, "_NET_WM_ICON", False);
320   net_wm_pid = XInternAtom(display, "_NET_WM_PID", False);
321   net_wm_handled_icons = XInternAtom(display, "_NET_WM_HANDLED_ICONS", False);
322
323   net_wm_ping = XInternAtom(display, "_NET_WM_PING", False);
324
325 #endif // NEWWMSPEC
326
327   cursor.session = XCreateFontCursor(display, XC_left_ptr);
328   cursor.move = XCreateFontCursor(display, XC_fleur);
329   cursor.ll_angle = XCreateFontCursor(display, XC_ll_angle);
330   cursor.lr_angle = XCreateFontCursor(display, XC_lr_angle);
331   cursor.ul_angle = XCreateFontCursor(display, XC_ul_angle);
332   cursor.ur_angle = XCreateFontCursor(display, XC_ur_angle);
333
334   XSetErrorHandler((XErrorHandler) handleXErrors);
335
336   timerList = new LinkedList<BTimer>;
337
338   screenInfoList = new LinkedList<ScreenInfo>;
339   for (int i = 0; i < number_of_screens; i++) {
340     ScreenInfo *screeninfo = new ScreenInfo(*this, i);
341     screenInfoList->insert(screeninfo);
342   }
343
344 #ifndef   NOCLOBBER
345   NumLockMask = ScrollLockMask = 0;
346
347   const XModifierKeymap* const modmap = XGetModifierMapping(display);
348   if (modmap && modmap->max_keypermod > 0) {
349     const int mask_table[] = {
350       ShiftMask, LockMask, ControlMask, Mod1Mask,
351       Mod2Mask, Mod3Mask, Mod4Mask, Mod5Mask
352     };
353     const size_t size = (sizeof(mask_table) / sizeof(mask_table[0])) *
354       modmap->max_keypermod;
355     // get the values of the keyboard lock modifiers
356     // Note: Caps lock is not retrieved the same way as Scroll and Num lock
357     // since it doesn't need to be.
358     const KeyCode num_lock_code = XKeysymToKeycode(display, XK_Num_Lock);
359     const KeyCode scroll_lock_code = XKeysymToKeycode(display, XK_Scroll_Lock);
360     
361     for (size_t cnt = 0; cnt < size; ++cnt) {
362       if (! modmap->modifiermap[cnt]) continue;
363
364       if (num_lock_code == modmap->modifiermap[cnt])
365         NumLockMask = mask_table[cnt / modmap->max_keypermod];
366       if (scroll_lock_code == modmap->modifiermap[cnt])
367         ScrollLockMask = mask_table[cnt / modmap->max_keypermod];
368     }
369   }
370
371   MaskList[0] = 0;
372   MaskList[1] = LockMask;
373   MaskList[2] = NumLockMask;
374   MaskList[3] = ScrollLockMask;
375   MaskList[4] = LockMask | NumLockMask;
376   MaskList[5] = NumLockMask  | ScrollLockMask;
377   MaskList[6] = LockMask | ScrollLockMask;
378   MaskList[7] = LockMask | NumLockMask | ScrollLockMask;
379   MaskListLength = sizeof(MaskList) / sizeof(MaskList[0]);
380   
381   if (modmap) XFreeModifiermap(const_cast<XModifierKeymap*>(modmap));
382 #else
383   NumLockMask = Mod2Mask;
384   ScrollLockMask = Mod5Mask;
385 #endif // NOCLOBBER
386 }
387
388
389 BaseDisplay::~BaseDisplay(void) {
390   while (screenInfoList->count()) {
391     ScreenInfo *si = screenInfoList->first();
392
393     screenInfoList->remove(si);
394     delete si;
395   }
396
397   delete screenInfoList;
398
399   // we don't create the BTimers, we don't delete them
400   while (timerList->count())
401     timerList->remove(0);
402
403   delete timerList;
404
405   XCloseDisplay(display);
406 }
407
408
409 void BaseDisplay::eventLoop(void) {
410   run();
411
412   int xfd = ConnectionNumber(display);
413
414   while ((! _shutdown) && (! internal_error)) {
415     if (XPending(display)) {
416       XEvent e;
417       XNextEvent(display, &e);
418
419       if (last_bad_window != None && e.xany.window == last_bad_window) {
420 #ifdef    DEBUG
421       fprintf(stderr, i18n->getMessage(BaseDisplaySet,
422                                        BaseDisplayBadWindowRemove,
423                          "BaseDisplay::eventLoop(): removing bad window "
424                          "from event queue\n"));
425 #endif // DEBUG
426       } else {
427         last_bad_window = None;
428         process_event(&e);
429       }
430     } else {
431       fd_set rfds;
432       timeval now, tm, *timeout = (timeval *) 0;
433
434       FD_ZERO(&rfds);
435       FD_SET(xfd, &rfds);
436
437       if (timerList->count()) {
438         gettimeofday(&now, 0);
439
440         tm.tv_sec = tm.tv_usec = 0l;
441
442         BTimer *timer = timerList->first();
443
444         tm.tv_sec = timer->getStartTime().tv_sec +
445           timer->getTimeout().tv_sec - now.tv_sec;
446         tm.tv_usec = timer->getStartTime().tv_usec +
447           timer->getTimeout().tv_usec - now.tv_usec;
448
449         while (tm.tv_usec >= 1000000) {
450           tm.tv_sec++;
451           tm.tv_usec -= 1000000;
452         }
453
454         while (tm.tv_usec < 0) {
455           if (tm.tv_sec > 0) {
456             tm.tv_sec--;
457             tm.tv_usec += 1000000;
458           } else {
459             tm.tv_usec = 0;
460             break;
461           }
462         }
463
464         timeout = &tm;
465       }
466
467       select(xfd + 1, &rfds, 0, 0, timeout);
468
469       // check for timer timeout
470       gettimeofday(&now, 0);
471
472       LinkedListIterator<BTimer> it(timerList);
473       for(BTimer *timer = it.current(); timer; it++, timer = it.current()) {
474         tm.tv_sec = timer->getStartTime().tv_sec +
475           timer->getTimeout().tv_sec;
476         tm.tv_usec = timer->getStartTime().tv_usec +
477           timer->getTimeout().tv_usec;
478
479         if ((now.tv_sec < tm.tv_sec) ||
480             (now.tv_sec == tm.tv_sec && now.tv_usec < tm.tv_usec))
481           break;
482
483         timer->fireTimeout();
484
485         // restart the current timer so that the start time is updated
486         if (! timer->doOnce()) timer->start();
487         else timer->stop();
488       }
489     }
490   }
491 }
492
493
494 const Bool BaseDisplay::validateWindow(Window window) {
495   XEvent event;
496   if (XCheckTypedWindowEvent(display, window, DestroyNotify, &event)) {
497     XPutBackEvent(display, &event);
498
499     return False;
500   }
501
502   return True;
503 }
504
505
506 void BaseDisplay::grab(void) {
507   if (! server_grabs++)
508     XGrabServer(display);
509 }
510
511
512 void BaseDisplay::ungrab(void) {
513   if (! --server_grabs)
514     XUngrabServer(display);
515
516   if (server_grabs < 0) server_grabs = 0;
517 }
518
519
520 void BaseDisplay::addTimer(BTimer *timer) {
521   if (! timer) return;
522
523   LinkedListIterator<BTimer> it(timerList);
524   int index = 0;
525   for (BTimer *tmp = it.current(); tmp; it++, index++, tmp = it.current())
526     if ((tmp->getTimeout().tv_sec > timer->getTimeout().tv_sec) ||
527         ((tmp->getTimeout().tv_sec == timer->getTimeout().tv_sec) &&
528          (tmp->getTimeout().tv_usec >= timer->getTimeout().tv_usec)))
529       break;
530
531   timerList->insert(timer, index);
532 }
533
534
535 void BaseDisplay::removeTimer(BTimer *timer) {
536   timerList->remove(timer);
537 }
538
539
540 /*
541  * Grabs a button, but also grabs the button in every possible combination with
542  * the keyboard lock keys, so that they do not cancel out the event.
543  */
544 void BaseDisplay::grabButton(unsigned int button, unsigned int modifiers,
545                              Window grab_window, Bool owner_events,
546                              unsigned int event_mask, int pointer_mode,
547                              int keybaord_mode, Window confine_to,
548                              Cursor cursor) const
549 {
550 #ifndef   NOCLOBBER
551   for (size_t cnt = 0; cnt < MaskListLength; ++cnt)
552     XGrabButton(display, button, modifiers | MaskList[cnt], grab_window,
553                 owner_events, event_mask, pointer_mode, keybaord_mode,
554                 confine_to, cursor);
555 #else  // NOCLOBBER
556     XGrabButton(display, button, modifiers, grab_window,
557                 owner_events, event_mask, pointer_mode, keybaord_mode,
558                 confine_to, cursor);
559 #endif // NOCLOBBER
560 }
561
562 /*
563  * Releases the grab on a button, and ungrabs all possible combinations of the
564  * keyboard lock keys.
565  */
566 void BaseDisplay::ungrabButton(unsigned int button, unsigned int modifiers,
567                                Window grab_window) const {
568 #ifndef   NOCLOBBER
569   for (size_t cnt = 0; cnt < MaskListLength; ++cnt)
570     XUngrabButton(display, button, modifiers | MaskList[cnt], grab_window);
571 #else  // NOCLOBBER
572     XUngrabButton(display, button, modifiers, grab_window);
573 #endif // NOCLOBBER
574 }
575
576
577 ScreenInfo::ScreenInfo(BaseDisplay &d, int num) : basedisplay(d) {
578   screen_number = num;
579
580   root_window = RootWindow(basedisplay.getXDisplay(), screen_number);
581   depth = DefaultDepth(basedisplay.getXDisplay(), screen_number);
582
583   width =
584     WidthOfScreen(ScreenOfDisplay(basedisplay.getXDisplay(), screen_number));
585   height =
586     HeightOfScreen(ScreenOfDisplay(basedisplay.getXDisplay(), screen_number));
587
588   // search for a TrueColor Visual... if we can't find one... we will use the
589   // default visual for the screen
590   XVisualInfo vinfo_template, *vinfo_return;
591   int vinfo_nitems;
592
593   vinfo_template.screen = screen_number;
594   vinfo_template.c_class = TrueColor;
595
596   visual = (Visual *) 0;
597
598   if ((vinfo_return = XGetVisualInfo(basedisplay.getXDisplay(),
599                                      VisualScreenMask | VisualClassMask,
600                                      &vinfo_template, &vinfo_nitems)) &&
601       vinfo_nitems > 0) {
602     for (int i = 0; i < vinfo_nitems; i++) {
603       if (depth < (vinfo_return + i)->depth) {
604         depth = (vinfo_return + i)->depth;
605         visual = (vinfo_return + i)->visual;
606       }
607     }
608
609     XFree(vinfo_return);
610   }
611
612   if (visual) {
613     colormap = XCreateColormap(basedisplay.getXDisplay(), root_window,
614                                visual, AllocNone);
615   } else {
616     visual = DefaultVisual(basedisplay.getXDisplay(), screen_number);
617     colormap = DefaultColormap(basedisplay.getXDisplay(), screen_number);
618   }
619 }