]> icculus.org git repositories - mikachu/openbox.git/blob - src/Screen.cc
synched with bb-cvs. couple bug fixes.
[mikachu/openbox.git] / src / Screen.cc
1 // -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 2; -*-
2 // Screen.cc for Blackbox - an X11 Window manager
3 // Copyright (c) 2001 - 2002 Sean 'Shaleh' Perry <shaleh@debian.org>
4 // Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining a
7 // copy of this software and associated documentation files (the "Software"),
8 // to deal in the Software without restriction, including without limitation
9 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 // and/or sell copies of the Software, and to permit persons to whom the
11 // Software is furnished to do so, subject to the following conditions:
12 //
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 // DEALINGS IN THE SOFTWARE.
23
24 #include "../config.h"
25
26 extern "C" {
27 #include <X11/Xatom.h>
28 #include <X11/keysym.h>
29
30 // for strcasestr()
31 #ifndef _GNU_SOURCE
32 #  define   _GNU_SOURCE
33 #endif // _GNU_SOURCE
34
35 #ifdef HAVE_STDLIB_H
36 #  include <stdlib.h>
37 #endif // HAVE_STDLIB_H
38
39 #ifdef HAVE_STRING_H
40 #  include <string.h>
41 #endif // HAVE_STRING_H
42
43 #ifdef    HAVE_CTYPE_H
44 #  include <ctype.h>
45 #endif // HAVE_CTYPE_H
46
47 #ifdef    HAVE_UNISTD_H
48 #  include <sys/types.h>
49 #  include <unistd.h>
50 #endif // HAVE_UNISTD_H
51
52 #ifdef    HAVE_DIRENT_H
53 #  include <dirent.h>
54 #endif // HAVE_DIRENT_H
55
56 #ifdef    HAVE_LOCALE_H
57 #  include <locale.h>
58 #endif // HAVE_LOCALE_H
59
60 #ifdef    HAVE_SYS_STAT_H
61 #  include <sys/stat.h>
62 #endif // HAVE_SYS_STAT_H
63
64 #ifdef    HAVE_STDARG_H
65 #  include <stdarg.h>
66 #endif // HAVE_STDARG_H
67 }
68
69 #include <assert.h>
70
71 #include <algorithm>
72 #include <functional>
73 #include <string>
74 using std::string;
75
76 #include "i18n.hh"
77 #include "blackbox.hh"
78 #include "Clientmenu.hh"
79 #include "GCCache.hh"
80 #include "Iconmenu.hh"
81 #include "Image.hh"
82 #include "Screen.hh"
83 #include "Slit.hh"
84 #include "Rootmenu.hh"
85 #include "Toolbar.hh"
86 #include "Util.hh"
87 #include "Window.hh"
88 #include "Workspace.hh"
89 #include "Workspacemenu.hh"
90 #include "XAtom.hh"
91
92 #ifndef   FONT_ELEMENT_SIZE
93 #define   FONT_ELEMENT_SIZE 50
94 #endif // FONT_ELEMENT_SIZE
95
96
97 static bool running = True;
98
99 static int anotherWMRunning(Display *display, XErrorEvent *) {
100   fprintf(stderr, i18n(ScreenSet, ScreenAnotherWMRunning,
101           "BScreen::BScreen: an error occured while querying the X server.\n"
102           "  another window manager already running on display %s.\n"),
103           DisplayString(display));
104
105   running = False;
106
107   return(-1);
108 }
109
110
111 BScreen::BScreen(Blackbox *bb, unsigned int scrn) : ScreenInfo(bb, scrn) {
112   blackbox = bb;
113   screenstr = (string)"session.screen" + itostring(scrn) + '.';
114   config = blackbox->getConfig();
115   xatom = blackbox->getXAtom();
116
117   event_mask = ColormapChangeMask | EnterWindowMask | PropertyChangeMask |
118     SubstructureRedirectMask | ButtonPressMask | ButtonReleaseMask;
119
120   XErrorHandler old = XSetErrorHandler((XErrorHandler) anotherWMRunning);
121   XSelectInput(getBaseDisplay()->getXDisplay(), getRootWindow(), event_mask);
122   XSync(getBaseDisplay()->getXDisplay(), False);
123   XSetErrorHandler((XErrorHandler) old);
124
125   managed = running;
126   if (! managed) return;
127
128   fprintf(stderr, i18n(ScreenSet, ScreenManagingScreen,
129                        "BScreen::BScreen: managing screen %d "
130                        "using visual 0x%lx, depth %d\n"),
131           getScreenNumber(), XVisualIDFromVisual(getVisual()),
132           getDepth());
133
134   rootmenu = 0;
135
136   resource.mstyle.t_fontset = resource.mstyle.f_fontset =
137     resource.tstyle.fontset = resource.wstyle.fontset = (XFontSet) 0;
138   resource.mstyle.t_font = resource.mstyle.f_font = resource.tstyle.font =
139     resource.wstyle.font = (XFontStruct *) 0;
140
141   xatom->setSupported(this);    // set-up netwm support
142 #ifdef    HAVE_GETPID
143   xatom->setValue(getRootWindow(), XAtom::blackbox_pid, XAtom::cardinal,
144                   (unsigned long) getpid());
145 #endif // HAVE_GETPID
146
147   XDefineCursor(blackbox->getXDisplay(), getRootWindow(),
148                 blackbox->getSessionCursor());
149
150   // start off full screen, top left.
151   usableArea.setSize(getWidth(), getHeight());
152
153   image_control =
154     new BImageControl(blackbox, this, True, blackbox->getColorsPerChannel(),
155                       blackbox->getCacheLife(), blackbox->getCacheMax());
156   image_control->installRootColormap();
157   root_colormap_installed = True;
158
159   load_rc();
160   LoadStyle();
161
162   XGCValues gcv;
163   unsigned long gc_value_mask = GCForeground;
164   if (! i18n.multibyte()) gc_value_mask |= GCFont;
165
166   gcv.foreground = WhitePixel(blackbox->getXDisplay(), getScreenNumber())
167     ^ BlackPixel(blackbox->getXDisplay(), getScreenNumber());
168   gcv.function = GXxor;
169   gcv.subwindow_mode = IncludeInferiors;
170   opGC = XCreateGC(blackbox->getXDisplay(), getRootWindow(),
171                    GCForeground | GCFunction | GCSubwindowMode, &gcv);
172
173   const char *s =  i18n(ScreenSet, ScreenPositionLength,
174                         "0: 0000 x 0: 0000");
175   int l = strlen(s);
176
177   if (i18n.multibyte()) {
178     XRectangle ink, logical;
179     XmbTextExtents(resource.wstyle.fontset, s, l, &ink, &logical);
180     geom_w = logical.width;
181
182     geom_h = resource.wstyle.fontset_extents->max_ink_extent.height;
183   } else {
184     geom_h = resource.wstyle.font->ascent +
185       resource.wstyle.font->descent;
186
187     geom_w = XTextWidth(resource.wstyle.font, s, l);
188   }
189
190   geom_w += (resource.bevel_width * 2);
191   geom_h += (resource.bevel_width * 2);
192
193   XSetWindowAttributes attrib;
194   unsigned long mask = CWBorderPixel | CWColormap | CWSaveUnder;
195   attrib.border_pixel = getBorderColor()->pixel();
196   attrib.colormap = getColormap();
197   attrib.save_under = True;
198
199   geom_window = XCreateWindow(blackbox->getXDisplay(), getRootWindow(),
200                               0, 0, geom_w, geom_h, resource.border_width,
201                               getDepth(), InputOutput, getVisual(),
202                               mask, &attrib);
203   geom_visible = False;
204
205   BTexture* texture = &(resource.wstyle.l_focus);
206   geom_pixmap = texture->render(geom_w, geom_h, geom_pixmap);
207   if (geom_pixmap == ParentRelative) {
208     texture = &(resource.wstyle.t_focus);
209     geom_pixmap = texture->render(geom_w, geom_h, geom_pixmap);
210   }
211   if (! geom_pixmap)
212     XSetWindowBackground(blackbox->getXDisplay(), geom_window,
213                          texture->color().pixel());
214   else
215     XSetWindowBackgroundPixmap(blackbox->getXDisplay(),
216                                geom_window, geom_pixmap);
217
218   workspacemenu = new Workspacemenu(this);
219   iconmenu = new Iconmenu(this);
220   configmenu = new Configmenu(this);
221
222   Workspace *wkspc = (Workspace *) 0;
223   if (resource.workspaces != 0) {
224     for (unsigned int i = 0; i < resource.workspaces; ++i) {
225       wkspc = new Workspace(this, workspacesList.size());
226       workspacesList.push_back(wkspc);
227       workspacemenu->insert(wkspc->getName(), wkspc->getMenu());
228     }
229   } else {
230     wkspc = new Workspace(this, workspacesList.size());
231     workspacesList.push_back(wkspc);
232     workspacemenu->insert(wkspc->getName(), wkspc->getMenu());
233   }
234   saveWorkspaceNames();
235
236   updateNetizenWorkspaceCount();
237
238   workspacemenu->insert(i18n(IconSet, IconIcons, "Icons"), iconmenu);
239   workspacemenu->update();
240
241   current_workspace = workspacesList.front();
242   
243   xatom->setValue(getRootWindow(), XAtom::net_current_desktop,
244                   XAtom::cardinal, 0); //first workspace
245
246   workspacemenu->setItemSelected(2, True);
247
248   toolbar = new Toolbar(this);
249
250   slit = new Slit(this);
251
252   InitMenu();
253
254   raiseWindows(0, 0);
255   rootmenu->update();
256
257   updateAvailableArea();
258
259   changeWorkspaceID(0);
260
261   unsigned int i, j, nchild;
262   Window r, p, *children;
263   XQueryTree(blackbox->getXDisplay(), getRootWindow(), &r, &p,
264              &children, &nchild);
265
266   // preen the window list of all icon windows... for better dockapp support
267   for (i = 0; i < nchild; i++) {
268     if (children[i] == None) continue;
269
270     XWMHints *wmhints = XGetWMHints(blackbox->getXDisplay(),
271                                     children[i]);
272
273     if (wmhints) {
274       if ((wmhints->flags & IconWindowHint) &&
275           (wmhints->icon_window != children[i])) {
276         for (j = 0; j < nchild; j++) {
277           if (children[j] == wmhints->icon_window) {
278             children[j] = None;
279             break;
280           }
281         }
282       }
283
284       XFree(wmhints);
285     }
286   }
287
288   // manage shown windows
289   for (i = 0; i < nchild; ++i) {
290     if (children[i] == None || (! blackbox->validateWindow(children[i])))
291       continue;
292
293     XWindowAttributes attrib;
294     if (XGetWindowAttributes(blackbox->getXDisplay(), children[i], &attrib)) {
295       if (attrib.override_redirect) continue;
296
297       if (attrib.map_state != IsUnmapped) {
298         manageWindow(children[i]);
299       }
300     }
301   }
302
303   XFree(children);
304
305   // call this again just in case a window we found updates the Strut list
306   updateAvailableArea();
307 }
308
309
310 BScreen::~BScreen(void) {
311   if (! managed) return;
312
313   if (geom_pixmap != None)
314     image_control->removeImage(geom_pixmap);
315
316   if (geom_window != None)
317     XDestroyWindow(blackbox->getXDisplay(), geom_window);
318
319   std::for_each(workspacesList.begin(), workspacesList.end(),
320                 PointerAssassin());
321
322   std::for_each(iconList.begin(), iconList.end(), PointerAssassin());
323
324   std::for_each(netizenList.begin(), netizenList.end(), PointerAssassin());
325
326   delete rootmenu;
327   delete workspacemenu;
328   delete iconmenu;
329   delete configmenu;
330   delete slit;
331   delete toolbar;
332   delete image_control;
333
334   if (resource.wstyle.fontset)
335     XFreeFontSet(blackbox->getXDisplay(), resource.wstyle.fontset);
336   if (resource.mstyle.t_fontset)
337     XFreeFontSet(blackbox->getXDisplay(), resource.mstyle.t_fontset);
338   if (resource.mstyle.f_fontset)
339     XFreeFontSet(blackbox->getXDisplay(), resource.mstyle.f_fontset);
340   if (resource.tstyle.fontset)
341     XFreeFontSet(blackbox->getXDisplay(), resource.tstyle.fontset);
342
343   if (resource.wstyle.font)
344     XFreeFont(blackbox->getXDisplay(), resource.wstyle.font);
345   if (resource.mstyle.t_font)
346     XFreeFont(blackbox->getXDisplay(), resource.mstyle.t_font);
347   if (resource.mstyle.f_font)
348     XFreeFont(blackbox->getXDisplay(), resource.mstyle.f_font);
349   if (resource.tstyle.font)
350     XFreeFont(blackbox->getXDisplay(), resource.tstyle.font);
351
352   XFreeGC(blackbox->getXDisplay(), opGC);
353 }
354
355
356 void BScreen::removeWorkspaceNames(void) {
357   workspaceNames.clear();
358 }
359   
360 void BScreen::saveSloppyFocus(bool s) {
361   resource.sloppy_focus = s;
362
363   string fmodel;
364   if (resource.sloppy_focus) {
365     fmodel = "SloppyFocus";
366     if (resource.auto_raise) fmodel += " AutoRaise";
367     if (resource.click_raise) fmodel += " ClickRaise";
368   } else {
369     fmodel = "ClickToFocus";
370   }
371   config->setValue(screenstr + "focusModel", fmodel);
372 }
373
374
375 void BScreen::saveAutoRaise(bool a) {
376   resource.auto_raise = a;
377   saveSloppyFocus(resource.sloppy_focus);
378 }
379
380
381 void BScreen::saveClickRaise(bool c) {
382   resource.click_raise = c;
383   saveSloppyFocus(resource.sloppy_focus);
384 }
385
386
387 void BScreen::saveImageDither(bool d) {
388   image_control->setDither(d);
389   config->setValue(screenstr + "imageDither", doImageDither());
390 }
391
392
393 void BScreen::saveOpaqueMove(bool o) {
394   resource.opaque_move = o;
395   config->setValue(screenstr + "opaqueMove", resource.opaque_move);
396 }
397
398
399 void BScreen::saveFullMax(bool f) {
400   resource.full_max = f;
401   config->setValue(screenstr + "fullMaximization", resource.full_max);
402 }
403
404
405 void BScreen::saveFocusNew(bool f) {
406   resource.focus_new = f;
407   config->setValue(screenstr + "focusNewWindows", resource.focus_new);
408 }
409
410
411 void BScreen::saveFocusLast(bool f) {
412   resource.focus_last = f;
413   config->setValue(screenstr + "focusLastWindow", resource.focus_last);
414 }
415
416
417 void BScreen::saveHideToolbar(bool h) {
418   resource.hide_toolbar = h;
419   if (resource.hide_toolbar)
420     toolbar->unmapToolbar();
421   else
422     toolbar->mapToolbar();
423   config->setValue(screenstr + "hideToolbar", resource.hide_toolbar);
424 }
425
426
427 void BScreen::saveWorkspaces(unsigned int w) {
428   resource.workspaces = w;
429   config->setValue(screenstr + "workspaces", resource.workspaces);
430 }
431
432
433 void BScreen::savePlacementPolicy(int p) {
434   resource.placement_policy = p; 
435   const char *placement;
436   switch (resource.placement_policy) {
437   case CascadePlacement: placement = "CascadePlacement"; break;
438   case ColSmartPlacement: placement = "ColSmartPlacement"; break;
439   case RowSmartPlacement: default: placement = "RowSmartPlacement"; break;
440   }
441   config->setValue(screenstr + "windowPlacement", placement);
442 }
443
444
445 void BScreen::saveEdgeSnapThreshold(int t) {
446   resource.edge_snap_threshold = t;
447   config->setValue(screenstr + "edgeSnapThreshold",
448                    resource.edge_snap_threshold);
449 }
450
451
452 void BScreen::saveRowPlacementDirection(int d) {
453   resource.row_direction = d;
454   config->setValue(screenstr + "rowPlacementDirection",
455                    resource.row_direction == LeftRight ?
456                    "LeftToRight" : "RightToLeft");
457 }
458
459
460 void BScreen::saveColPlacementDirection(int d) {
461   resource.col_direction = d;
462   config->setValue(screenstr + "colPlacementDirection",
463                    resource.col_direction == TopBottom ?
464                    "TopToBottom" : "BottomToTop");
465 }
466
467
468 #ifdef    HAVE_STRFTIME
469 void BScreen::saveStrftimeFormat(const std::string& format) {
470   resource.strftime_format = format;
471   config->setValue(screenstr + "strftimeFormat", resource.strftime_format);
472 }
473
474 #else // !HAVE_STRFTIME
475
476 void BScreen::saveDateFormat(int f) {
477   resource.date_format = f;
478   config->setValue(screenstr + "dateFormat",
479                    resource.date_format == B_EuropeanDate ?
480                    "European" : "American");
481 }
482
483
484 void BScreen::saveClock24Hour(Bool c) {
485   resource.clock24hour = c;
486   config->setValue(screenstr + "clockFormat", resource.clock24hour ? 24 : 12);
487 }
488 #endif // HAVE_STRFTIME
489
490
491 void BScreen::saveWorkspaceNames() {
492   string names;
493   WorkspaceList::iterator it;
494   WorkspaceList::iterator last = workspacesList.end() - 1;
495   for (it = workspacesList.begin(); it != workspacesList.end(); ++it) {
496     names += (*it)->getName();
497     if (it != last)
498       names += ',';
499   }
500   config->setValue(screenstr + "workspaceNames", names);
501 }
502
503
504 void BScreen::save_rc(void) {
505   saveSloppyFocus(resource.sloppy_focus);
506   saveAutoRaise(resource.auto_raise);
507   saveImageDither(doImageDither());
508   saveOpaqueMove(resource.opaque_move);
509   saveFullMax(resource.full_max);
510   saveFocusNew(resource.focus_new);
511   saveFocusLast(resource.focus_last);
512   saveHideToolbar(resource.hide_toolbar);
513   saveWorkspaces(resource.workspaces);
514   savePlacementPolicy(resource.placement_policy);
515   saveEdgeSnapThreshold(resource.edge_snap_threshold);
516   saveRowPlacementDirection(resource.row_direction);
517   saveColPlacementDirection(resource.col_direction);
518 #ifdef    HAVE_STRFTIME
519   saveStrftimeFormat(resource.strftime_format); 
520 #else // !HAVE_STRFTIME
521   saveDateFormat(resource.date_format);
522   savwClock24Hour(resource.clock24hour);
523 #endif // HAVE_STRFTIME
524
525   toolbar->save_rc();
526   slit->save_rc();
527 }
528
529
530 void BScreen::load_rc(void) {
531   std::string s;
532   bool b;
533
534   if (! config->getValue(screenstr + "fullMaximization", resource.full_max))
535     resource.full_max = false;
536
537   if (! config->getValue(screenstr + "focusNewWindows", resource.focus_new))
538     resource.focus_new = false;
539
540   if (! config->getValue(screenstr + "focusLastWindow", resource.focus_last))
541     resource.focus_last = false;
542
543   if (! config->getValue(screenstr + "workspaces", resource.workspaces))
544     resource.workspaces = 1;
545
546   if (! config->getValue(screenstr + "opaqueMove", resource.opaque_move))
547     resource.opaque_move = false;
548
549   if (! config->getValue(screenstr + "hideToolbar", resource.hide_toolbar))
550     resource.hide_toolbar = false;
551
552   if (! config->getValue(screenstr + "imageDither", b))
553     b = true;
554   image_control->setDither(b);
555
556   if (! config->getValue(screenstr + "edgeSnapThreshold",
557                         resource.edge_snap_threshold))
558     resource.edge_snap_threshold = 4;
559   
560   if (config->getValue(screenstr + "rowPlacementDirection", s) &&
561       s == "RightToLeft")
562     resource.row_direction = RightLeft;
563   else
564     resource.row_direction = LeftRight;
565
566   if (config->getValue(screenstr + "colPlacementDirection", s) &&
567       s == "BottomToTop")
568     resource.col_direction = BottomTop;
569   else
570     resource.col_direction = TopBottom;
571
572   removeWorkspaceNames();
573   if (config->getValue(screenstr + "workspaceNames", s)) {
574     string::const_iterator it = s.begin(), end = s.end();
575     while(1) {
576       string::const_iterator tmp = it;     // current string.begin()
577       it = std::find(tmp, end, ',');       // look for comma between tmp and end
578       addWorkspaceName(string(tmp, it));   // s[tmp:it]
579       if (it == end)
580         break;
581       ++it;
582     }
583   }
584
585   resource.sloppy_focus = true;
586   resource.auto_raise = false;
587   resource.click_raise = false;
588   if (config->getValue(screenstr + "focusModel", s)) {
589     if (s.find("ClickToFocus") != string::npos) {
590       resource.sloppy_focus = false;
591     } else {
592       // must be sloppy
593       if (s.find("AutoRaise") != string::npos)
594         resource.auto_raise = true;
595       if (s.find("ClickRaise") != string::npos)
596         resource.click_raise = true;
597     }
598   }
599
600   if (config->getValue(screenstr + "windowPlacement", s)) {
601     if (s == "CascadePlacement")
602       resource.placement_policy = CascadePlacement;
603     else if (s == "ColSmartPlacement")
604       resource.placement_policy = ColSmartPlacement;
605     else //if (s == "RowSmartPlacement")
606       resource.placement_policy = RowSmartPlacement;
607   } else
608     resource.placement_policy = RowSmartPlacement;
609
610 #ifdef    HAVE_STRFTIME
611   if (config->getValue(screenstr + "strftimeFormat", s))
612     resource.strftime_format = s;
613   else
614     resource.strftime_format = "%I:%M %p";
615 #else // !HAVE_STRFTIME
616   long l;
617
618   if (config->getValue(screenstr + "dateFormat", s) && s == "European")
619     resource.date_format = B_EuropeanDate;
620  else
621     resource.date_format = B_AmericanDate;
622
623   if (! config->getValue(screenstr + "clockFormat", l))
624     l = 12;
625   resource.clock24hour = l == 24;
626 #endif // HAVE_STRFTIME
627 }
628
629
630 void BScreen::reconfigure(void) {
631   load_rc();
632   toolbar->load_rc();
633   slit->load_rc();
634   LoadStyle();
635
636   XGCValues gcv;
637   unsigned long gc_value_mask = GCForeground;
638   if (! i18n.multibyte()) gc_value_mask |= GCFont;
639
640   gcv.foreground = WhitePixel(blackbox->getXDisplay(),
641                               getScreenNumber());
642   gcv.function = GXinvert;
643   gcv.subwindow_mode = IncludeInferiors;
644   XChangeGC(blackbox->getXDisplay(), opGC,
645             GCForeground | GCFunction | GCSubwindowMode, &gcv);
646
647   const char *s = i18n(ScreenSet, ScreenPositionLength,
648                        "0: 0000 x 0: 0000");
649   int l = strlen(s);
650
651   if (i18n.multibyte()) {
652     XRectangle ink, logical;
653     XmbTextExtents(resource.wstyle.fontset, s, l, &ink, &logical);
654     geom_w = logical.width;
655
656     geom_h = resource.wstyle.fontset_extents->max_ink_extent.height;
657   } else {
658     geom_w = XTextWidth(resource.wstyle.font, s, l);
659
660     geom_h = resource.wstyle.font->ascent + resource.wstyle.font->descent;
661   }
662
663   geom_w += (resource.bevel_width * 2);
664   geom_h += (resource.bevel_width * 2);
665
666   BTexture* texture = &(resource.wstyle.l_focus);
667   geom_pixmap = texture->render(geom_w, geom_h, geom_pixmap);
668   if (geom_pixmap == ParentRelative) {
669     texture = &(resource.wstyle.t_focus);
670     geom_pixmap = texture->render(geom_w, geom_h, geom_pixmap);
671   }
672   if (! geom_pixmap)
673     XSetWindowBackground(blackbox->getXDisplay(), geom_window,
674                          texture->color().pixel());
675   else
676     XSetWindowBackgroundPixmap(blackbox->getXDisplay(),
677                                geom_window, geom_pixmap);
678
679   XSetWindowBorderWidth(blackbox->getXDisplay(), geom_window,
680                         resource.border_width);
681   XSetWindowBorder(blackbox->getXDisplay(), geom_window,
682                    resource.border_color.pixel());
683
684   workspacemenu->reconfigure();
685   iconmenu->reconfigure();
686
687   typedef std::vector<int> SubList;
688   SubList remember_subs;
689
690   // save the current open menus
691   Basemenu *menu = rootmenu;
692   int submenu;
693   while ((submenu = menu->getCurrentSubmenu()) >= 0) {
694     remember_subs.push_back(submenu);
695     menu = menu->find(submenu)->submenu();
696     assert(menu);
697   }
698   
699   InitMenu();
700   raiseWindows(0, 0);
701   rootmenu->reconfigure();
702
703   // reopen the saved menus
704   menu = rootmenu;
705   const SubList::iterator subs_end = remember_subs.end();
706   for (SubList::iterator it = remember_subs.begin(); it != subs_end; ++it) {
707     menu->drawSubmenu(*it);
708     menu = menu->find(*it)->submenu();
709     if (! menu)
710       break;
711   }
712
713   configmenu->reconfigure();
714
715   toolbar->reconfigure();
716
717   slit->reconfigure();
718
719   std::for_each(workspacesList.begin(), workspacesList.end(),
720                 std::mem_fun(&Workspace::reconfigure));
721
722   BlackboxWindowList::iterator iit = iconList.begin();
723   for (; iit != iconList.end(); ++iit) {
724     BlackboxWindow *bw = *iit;
725     if (bw->validateClient())
726       bw->reconfigure();
727   }
728
729   image_control->timeout();
730 }
731
732
733 void BScreen::rereadMenu(void) {
734   InitMenu();
735   raiseWindows(0, 0);
736
737   rootmenu->reconfigure();
738 }
739
740
741 void BScreen::LoadStyle(void) {
742   Configuration style;
743
744   const char *sfile = blackbox->getStyleFilename();
745   if (sfile != NULL) {
746     style.setFile(sfile);
747     if (! style.load()) {
748       style.setFile(DEFAULTSTYLE);
749       if (! style.load())
750         style.create();  // hardcoded default values will be used.
751     }
752   }
753
754   string s;
755
756   // load fonts/fontsets
757   if (resource.wstyle.fontset)
758     XFreeFontSet(blackbox->getXDisplay(), resource.wstyle.fontset);
759   if (resource.tstyle.fontset)
760     XFreeFontSet(blackbox->getXDisplay(), resource.tstyle.fontset);
761   if (resource.mstyle.f_fontset)
762     XFreeFontSet(blackbox->getXDisplay(), resource.mstyle.f_fontset);
763   if (resource.mstyle.t_fontset)
764     XFreeFontSet(blackbox->getXDisplay(), resource.mstyle.t_fontset);
765   resource.wstyle.fontset = 0;
766   resource.tstyle.fontset = 0;
767   resource.mstyle.f_fontset = 0;
768   resource.mstyle.t_fontset = 0;
769   if (resource.wstyle.font)
770     XFreeFont(blackbox->getXDisplay(), resource.wstyle.font);
771   if (resource.tstyle.font)
772     XFreeFont(blackbox->getXDisplay(), resource.tstyle.font);
773   if (resource.mstyle.f_font)
774     XFreeFont(blackbox->getXDisplay(), resource.mstyle.f_font);
775   if (resource.mstyle.t_font)
776     XFreeFont(blackbox->getXDisplay(), resource.mstyle.t_font);
777   resource.wstyle.font = 0;
778   resource.tstyle.font = 0;
779   resource.mstyle.f_font = 0;
780   resource.mstyle.t_font = 0;
781
782   if (i18n.multibyte()) {
783     resource.wstyle.fontset = readDatabaseFontSet("window.font", style);
784     resource.tstyle.fontset = readDatabaseFontSet("toolbar.font", style);
785     resource.mstyle.t_fontset = readDatabaseFontSet("menu.title.font", style);
786     resource.mstyle.f_fontset = readDatabaseFontSet("menu.frame.font", style);
787
788     resource.mstyle.t_fontset_extents =
789       XExtentsOfFontSet(resource.mstyle.t_fontset);
790     resource.mstyle.f_fontset_extents =
791       XExtentsOfFontSet(resource.mstyle.f_fontset);
792     resource.tstyle.fontset_extents =
793       XExtentsOfFontSet(resource.tstyle.fontset);
794     resource.wstyle.fontset_extents =
795       XExtentsOfFontSet(resource.wstyle.fontset);
796   } else {
797     resource.wstyle.font = readDatabaseFont("window.font", style);
798     resource.tstyle.font = readDatabaseFont("toolbar.font", style);
799     resource.mstyle.t_font = readDatabaseFont("menu.title.font", style);
800     resource.mstyle.f_font = readDatabaseFont("menu.frame.font", style);
801   }
802
803   // load window config
804   resource.wstyle.t_focus =
805     readDatabaseTexture("window.title.focus", "white", style);
806   resource.wstyle.t_unfocus =
807     readDatabaseTexture("window.title.unfocus", "black", style);
808   resource.wstyle.l_focus =
809     readDatabaseTexture("window.label.focus", "white", style);
810   resource.wstyle.l_unfocus =
811     readDatabaseTexture("window.label.unfocus", "black", style);
812   resource.wstyle.h_focus =
813     readDatabaseTexture("window.handle.focus", "white", style);
814   resource.wstyle.h_unfocus =
815     readDatabaseTexture("window.handle.unfocus", "black", style);
816   resource.wstyle.g_focus =
817     readDatabaseTexture("window.grip.focus", "white", style);
818   resource.wstyle.g_unfocus =
819     readDatabaseTexture("window.grip.unfocus", "black", style);
820   resource.wstyle.b_focus =
821     readDatabaseTexture("window.button.focus", "white", style);
822   resource.wstyle.b_unfocus =
823     readDatabaseTexture("window.button.unfocus", "black", style);
824   resource.wstyle.b_pressed =
825     readDatabaseTexture("window.button.pressed", "black", style);
826   resource.wstyle.f_focus =
827     readDatabaseColor("window.frame.focusColor", "white", style);
828   resource.wstyle.f_unfocus =
829     readDatabaseColor("window.frame.unfocusColor", "black", style);
830   resource.wstyle.l_text_focus =
831     readDatabaseColor("window.label.focus.textColor", "black", style);
832   resource.wstyle.l_text_unfocus =
833     readDatabaseColor("window.label.unfocus.textColor", "white", style);
834   resource.wstyle.b_pic_focus =
835     readDatabaseColor("window.button.focus.picColor", "black", style);
836   resource.wstyle.b_pic_unfocus =
837     readDatabaseColor("window.button.unfocus.picColor", "white", style);
838
839   resource.wstyle.justify = LeftJustify;
840   if (style.getValue("window.justify", s)) {
841     if (s == "right" || s == "Right")
842       resource.wstyle.justify = RightJustify;
843     else if (s == "center" || s == "Center")
844       resource.wstyle.justify = CenterJustify;
845   }
846
847   // load toolbar config
848   resource.tstyle.toolbar =
849     readDatabaseTexture("toolbar", "black", style);
850   resource.tstyle.label =
851     readDatabaseTexture("toolbar.label", "black", style);
852   resource.tstyle.window =
853     readDatabaseTexture("toolbar.windowLabel", "black", style);
854   resource.tstyle.button =
855     readDatabaseTexture("toolbar.button", "white", style);
856   resource.tstyle.pressed =
857     readDatabaseTexture("toolbar.button.pressed", "black", style);
858   resource.tstyle.clock =
859     readDatabaseTexture("toolbar.clock", "black", style);
860   resource.tstyle.l_text =
861     readDatabaseColor("toolbar.label.textColor", "white", style);
862   resource.tstyle.w_text =
863     readDatabaseColor("toolbar.windowLabel.textColor", "white", style);
864   resource.tstyle.c_text =
865     readDatabaseColor("toolbar.clock.textColor", "white", style);
866   resource.tstyle.b_pic =
867     readDatabaseColor("toolbar.button.picColor", "black", style);
868
869   resource.tstyle.justify = LeftJustify;
870   if (style.getValue("toolbar.justify", s)) {
871     if (s == "right" || s == "Right")
872       resource.tstyle.justify = RightJustify;
873     else if (s == "center" || s == "Center")
874       resource.tstyle.justify = CenterJustify;
875   }
876
877   // load menu config
878   resource.mstyle.title =
879     readDatabaseTexture("menu.title", "white", style);
880   resource.mstyle.frame =
881     readDatabaseTexture("menu.frame", "black", style);
882   resource.mstyle.hilite =
883     readDatabaseTexture("menu.hilite", "white", style);
884   resource.mstyle.t_text =
885     readDatabaseColor("menu.title.textColor", "black", style);
886   resource.mstyle.f_text =
887     readDatabaseColor("menu.frame.textColor", "white", style);
888   resource.mstyle.d_text =
889     readDatabaseColor("menu.frame.disableColor", "black", style);
890   resource.mstyle.h_text =
891     readDatabaseColor("menu.hilite.textColor", "black", style);
892
893   resource.mstyle.t_justify = LeftJustify;
894   if (style.getValue("menu.title.justify", s)) {
895     if (s == "right" || s == "Right")
896       resource.mstyle.t_justify = RightJustify;
897     else if (s == "center" || s == "Center")
898       resource.mstyle.t_justify = CenterJustify;
899   }
900
901   resource.mstyle.f_justify = LeftJustify;
902   if (style.getValue("menu.frame.justify", s)) {
903     if (s == "right" || s == "Right")
904       resource.mstyle.f_justify = RightJustify;
905     else if (s == "center" || s == "Center")
906       resource.mstyle.f_justify = CenterJustify;
907   }
908
909   resource.mstyle.bullet = Basemenu::Triangle;
910   if (style.getValue("menu.bullet", s)) {
911     if (s == "empty" || s == "Empty")
912       resource.mstyle.bullet = Basemenu::Empty;
913     else if (s == "square" || s == "Square")
914       resource.mstyle.bullet = Basemenu::Square;
915     else if (s == "diamond" || s == "Diamond")
916       resource.mstyle.bullet = Basemenu::Diamond;
917   }
918
919   resource.mstyle.bullet_pos = Basemenu::Left;
920   if (style.getValue("menu.bullet.position", s)) {
921     if (s == "right" || s == "Right")
922       resource.mstyle.bullet_pos = Basemenu::Right;
923   }
924
925   resource.border_color =
926     readDatabaseColor("borderColor", "black", style);
927
928   // load bevel, border and handle widths
929   if (! style.getValue("handleWidth", resource.handle_width) ||
930       resource.handle_width > (getWidth() / 2) || resource.handle_width == 0)
931     resource.handle_width = 6;
932
933   if (! style.getValue("borderWidth", resource.border_width))
934     resource.border_width = 1;
935
936   if (! style.getValue("bevelWidth", resource.bevel_width) ||
937       resource.bevel_width > (getWidth() / 2) || resource.bevel_width == 0)
938     resource.bevel_width = 3;
939
940   if (! style.getValue("frameWidth", resource.frame_width) ||
941       resource.frame_width > (getWidth() / 2))
942     resource.frame_width = resource.bevel_width;
943
944   if (style.getValue("rootCommand", s))
945     bexec(s, displayString());
946 }
947
948
949 void BScreen::addIcon(BlackboxWindow *w) {
950   if (! w) return;
951
952   w->setWorkspace(BSENTINEL);
953   w->setWindowNumber(iconList.size());
954
955   iconList.push_back(w);
956
957   const char* title = w->getIconTitle();
958   iconmenu->insert(title);
959   iconmenu->update();
960 }
961
962
963 void BScreen::removeIcon(BlackboxWindow *w) {
964   if (! w) return;
965
966   iconList.remove(w);
967
968   iconmenu->remove(w->getWindowNumber());
969   iconmenu->update();
970
971   BlackboxWindowList::iterator it = iconList.begin(),
972     end = iconList.end();
973   for (int i = 0; it != end; ++it)
974     (*it)->setWindowNumber(i++);
975 }
976
977
978 BlackboxWindow *BScreen::getIcon(unsigned int index) {
979   if (index < iconList.size()) {
980     BlackboxWindowList::iterator it = iconList.begin();
981     for (; index > 0; --index, ++it) ; /* increment to index */
982     return *it;
983   }
984
985   return (BlackboxWindow *) 0;
986 }
987
988
989 unsigned int BScreen::addWorkspace(void) {
990   Workspace *wkspc = new Workspace(this, workspacesList.size());
991   workspacesList.push_back(wkspc);
992   saveWorkspaces(getWorkspaceCount());
993   saveWorkspaceNames();
994
995   workspacemenu->insert(wkspc->getName(), wkspc->getMenu(),
996                         wkspc->getID() + 2);
997   workspacemenu->update();
998
999   toolbar->reconfigure();
1000
1001   updateNetizenWorkspaceCount();
1002
1003   return workspacesList.size();
1004 }
1005
1006
1007 unsigned int BScreen::removeLastWorkspace(void) {
1008   if (workspacesList.size() == 1)
1009     return 1;
1010
1011   Workspace *wkspc = workspacesList.back();
1012
1013   if (current_workspace->getID() == wkspc->getID())
1014     changeWorkspaceID(current_workspace->getID() - 1);
1015
1016   wkspc->removeAll();
1017
1018   workspacemenu->remove(wkspc->getID() + 2);
1019   workspacemenu->update();
1020
1021   workspacesList.pop_back();
1022   delete wkspc;
1023
1024   saveWorkspaces(getWorkspaceCount());
1025   saveWorkspaceNames();
1026
1027   toolbar->reconfigure();
1028
1029   updateNetizenWorkspaceCount();
1030
1031   return workspacesList.size();
1032 }
1033
1034
1035 void BScreen::changeWorkspaceID(unsigned int id) {
1036   if (! current_workspace) return;
1037
1038   if (id != current_workspace->getID()) {
1039     current_workspace->hideAll();
1040
1041     workspacemenu->setItemSelected(current_workspace->getID() + 2, False);
1042
1043     BlackboxWindow *focused = blackbox->getFocusedWindow();
1044     if (focused && focused->getScreen() == this && ! focused->isStuck()) {
1045       if (focused->getWorkspaceNumber() != current_workspace->getID()) {
1046         fprintf(stderr, "%s is on the wrong workspace, aborting\n",
1047                 focused->getTitle());
1048         abort();
1049       }
1050       current_workspace->setLastFocusedWindow(focused);
1051       blackbox->setFocusedWindow((BlackboxWindow *) 0);
1052     }
1053
1054     current_workspace = getWorkspace(id);
1055
1056     xatom->setValue(getRootWindow(), XAtom::net_current_desktop,
1057                     XAtom::cardinal, id);
1058     printf("%d\n", id);
1059
1060     workspacemenu->setItemSelected(current_workspace->getID() + 2, True);
1061     toolbar->redrawWorkspaceLabel(True);
1062
1063     current_workspace->showAll();
1064
1065     if (resource.focus_last && current_workspace->getLastFocusedWindow()) {
1066       XSync(blackbox->getXDisplay(), False);
1067       current_workspace->getLastFocusedWindow()->setInputFocus();
1068     }
1069   }
1070
1071   updateNetizenCurrentWorkspace();
1072 }
1073
1074
1075 void BScreen::manageWindow(Window w) {
1076   new BlackboxWindow(blackbox, w, this);
1077
1078   BlackboxWindow *win = blackbox->searchWindow(w);
1079   if (! win)
1080     return;
1081
1082   windowList.push_back(win);
1083
1084   XMapRequestEvent mre;
1085   mre.window = w;
1086   if (blackbox->isStartup())
1087     win->restoreAttributes();
1088   win->mapRequestEvent(&mre);
1089 }
1090
1091
1092 void BScreen::unmanageWindow(BlackboxWindow *w, bool remap) {
1093   w->restore(remap);
1094
1095   if (w->getWorkspaceNumber() != BSENTINEL &&
1096       w->getWindowNumber() != BSENTINEL)
1097     getWorkspace(w->getWorkspaceNumber())->removeWindow(w);
1098   else if (w->isIconic())
1099     removeIcon(w);
1100
1101   windowList.remove(w);
1102
1103   if (blackbox->getFocusedWindow() == w)
1104     blackbox->setFocusedWindow((BlackboxWindow *) 0);
1105
1106   removeNetizen(w->getClientWindow());
1107
1108   /*
1109     some managed windows can also be window group controllers.  when
1110     unmanaging such windows, we should also delete the window group.
1111   */
1112   BWindowGroup *group = blackbox->searchGroup(w->getClientWindow());
1113   delete group;
1114
1115   delete w;
1116 }
1117
1118
1119 void BScreen::addNetizen(Netizen *n) {
1120   netizenList.push_back(n);
1121
1122   n->sendWorkspaceCount();
1123   n->sendCurrentWorkspace();
1124
1125   WorkspaceList::iterator it = workspacesList.begin();
1126   const WorkspaceList::iterator end = workspacesList.end();
1127   for (; it != end; ++it)
1128     (*it)->sendWindowList(*n);
1129
1130   Window f = ((blackbox->getFocusedWindow()) ?
1131               blackbox->getFocusedWindow()->getClientWindow() : None);
1132   n->sendWindowFocus(f);
1133 }
1134
1135
1136 void BScreen::removeNetizen(Window w) {
1137   NetizenList::iterator it = netizenList.begin();
1138   for (; it != netizenList.end(); ++it) {
1139     if ((*it)->getWindowID() == w) {
1140       delete *it;
1141       netizenList.erase(it);
1142       break;
1143     }
1144   }
1145 }
1146
1147
1148 void BScreen::updateNetizenCurrentWorkspace(void) {
1149   std::for_each(netizenList.begin(), netizenList.end(),
1150                 std::mem_fun(&Netizen::sendCurrentWorkspace));
1151 }
1152
1153
1154 void BScreen::updateNetizenWorkspaceCount(void) {
1155   xatom->setValue(getRootWindow(), XAtom::net_number_of_desktops,
1156                   XAtom::cardinal, workspacesList.size());
1157
1158   std::for_each(netizenList.begin(), netizenList.end(),
1159                 std::mem_fun(&Netizen::sendWorkspaceCount));
1160 }
1161
1162
1163 void BScreen::updateNetizenWindowFocus(void) {
1164   Window f = ((blackbox->getFocusedWindow()) ?
1165               blackbox->getFocusedWindow()->getClientWindow() : None);
1166   NetizenList::iterator it = netizenList.begin();
1167   for (; it != netizenList.end(); ++it)
1168     (*it)->sendWindowFocus(f);
1169 }
1170
1171
1172 void BScreen::updateNetizenWindowAdd(Window w, unsigned long p) {
1173   NetizenList::iterator it = netizenList.begin();
1174   for (; it != netizenList.end(); ++it) {
1175     (*it)->sendWindowAdd(w, p);
1176   }
1177 }
1178
1179
1180 void BScreen::updateNetizenWindowDel(Window w) {
1181   NetizenList::iterator it = netizenList.begin();
1182   for (; it != netizenList.end(); ++it)
1183     (*it)->sendWindowDel(w);
1184 }
1185
1186
1187 void BScreen::updateNetizenWindowRaise(Window w) {
1188   NetizenList::iterator it = netizenList.begin();
1189   for (; it != netizenList.end(); ++it)
1190     (*it)->sendWindowRaise(w);
1191 }
1192
1193
1194 void BScreen::updateNetizenWindowLower(Window w) {
1195   NetizenList::iterator it = netizenList.begin();
1196   for (; it != netizenList.end(); ++it)
1197     (*it)->sendWindowLower(w);
1198 }
1199
1200
1201 void BScreen::updateNetizenConfigNotify(XEvent *e) {
1202   NetizenList::iterator it = netizenList.begin();
1203   for (; it != netizenList.end(); ++it)
1204     (*it)->sendConfigNotify(e);
1205 }
1206
1207
1208 void BScreen::raiseWindows(Window *workspace_stack, unsigned int num) {
1209   // XXX: why 13??
1210   Window *session_stack = new
1211     Window[(num + workspacesList.size() + rootmenuList.size() + 13)];
1212   unsigned int i = 0, k = num;
1213
1214   XRaiseWindow(blackbox->getXDisplay(), iconmenu->getWindowID());
1215   *(session_stack + i++) = iconmenu->getWindowID();
1216
1217   WorkspaceList::iterator wit = workspacesList.begin();
1218   const WorkspaceList::iterator w_end = workspacesList.end();
1219   for (; wit != w_end; ++wit)
1220     *(session_stack + i++) = (*wit)->getMenu()->getWindowID();
1221
1222   *(session_stack + i++) = workspacemenu->getWindowID();
1223
1224   *(session_stack + i++) = configmenu->getFocusmenu()->getWindowID();
1225   *(session_stack + i++) = configmenu->getPlacementmenu()->getWindowID();
1226   *(session_stack + i++) = configmenu->getWindowID();
1227
1228   *(session_stack + i++) = slit->getMenu()->getDirectionmenu()->getWindowID();
1229   *(session_stack + i++) = slit->getMenu()->getPlacementmenu()->getWindowID();
1230   *(session_stack + i++) = slit->getMenu()->getWindowID();
1231
1232   *(session_stack + i++) =
1233     toolbar->getMenu()->getPlacementmenu()->getWindowID();
1234   *(session_stack + i++) = toolbar->getMenu()->getWindowID();
1235
1236   RootmenuList::iterator rit = rootmenuList.begin();
1237   for (; rit != rootmenuList.end(); ++rit)
1238     *(session_stack + i++) = (*rit)->getWindowID();
1239   *(session_stack + i++) = rootmenu->getWindowID();
1240
1241   if (toolbar->isOnTop())
1242     *(session_stack + i++) = toolbar->getWindowID();
1243
1244   if (slit->isOnTop())
1245     *(session_stack + i++) = slit->getWindowID();
1246
1247   while (k--)
1248     *(session_stack + i++) = *(workspace_stack + k);
1249
1250   XRestackWindows(blackbox->getXDisplay(), session_stack, i);
1251
1252   delete [] session_stack;
1253 }
1254
1255
1256 void BScreen::addWorkspaceName(const string& name) {
1257   workspaceNames.push_back(name);
1258 }
1259
1260
1261 /*
1262  * I would love to kill this function and the accompanying workspaceNames
1263  * list.  However, we have a chicken and egg situation.  The names are read
1264  * in during load_rc() which happens before the workspaces are created.
1265  * The current solution is to read the names into a list, then use the list
1266  * later for constructing the workspaces.  It is only used during initial
1267  * BScreen creation.
1268  */
1269 const string BScreen::getNameOfWorkspace(unsigned int id) {
1270   if (id < workspaceNames.size())
1271     return workspaceNames[id];
1272   return string("");
1273 }
1274
1275
1276 void BScreen::reassociateWindow(BlackboxWindow *w, unsigned int wkspc_id,
1277                                 bool ignore_sticky) {
1278   if (! w) return;
1279
1280   if (wkspc_id == BSENTINEL)
1281     wkspc_id = current_workspace->getID();
1282
1283   if (w->getWorkspaceNumber() == wkspc_id)
1284     return;
1285
1286   if (w->isIconic()) {
1287     removeIcon(w);
1288     getWorkspace(wkspc_id)->addWindow(w);
1289   } else if (ignore_sticky || ! w->isStuck()) {
1290     getWorkspace(w->getWorkspaceNumber())->removeWindow(w);
1291     getWorkspace(wkspc_id)->addWindow(w);
1292   }
1293 }
1294
1295
1296 void BScreen::propagateWindowName(const BlackboxWindow *bw) {
1297   if (bw->isIconic()) {
1298     iconmenu->changeItemLabel(bw->getWindowNumber(), bw->getIconTitle());
1299     iconmenu->update();
1300   }
1301   else {
1302     Clientmenu *clientmenu = getWorkspace(bw->getWorkspaceNumber())->getMenu();
1303     clientmenu->changeItemLabel(bw->getWindowNumber(), bw->getTitle());
1304     clientmenu->update();
1305
1306     if (blackbox->getFocusedWindow() == bw)
1307       toolbar->redrawWindowLabel(True);
1308   }
1309 }
1310
1311
1312 void BScreen::nextFocus(void) {
1313   BlackboxWindow *focused = blackbox->getFocusedWindow(),
1314     *next = focused;
1315
1316   if (focused) {
1317     // if window is not on this screen, ignore it
1318     if (focused->getScreen()->getScreenNumber() != getScreenNumber())
1319       focused = (BlackboxWindow*) 0;
1320   }
1321
1322   if (focused && current_workspace->getCount() > 1) {
1323     // next is the next window to recieve focus, current is a place holder
1324     BlackboxWindow *current;
1325     do {
1326       current = next;
1327       next = current_workspace->getNextWindowInList(current);
1328     } while(! next->setInputFocus() && next != focused);
1329
1330     if (next != focused)
1331       current_workspace->raiseWindow(next);
1332   } else if (current_workspace->getCount() >= 1) {
1333     next = current_workspace->getTopWindowOnStack();
1334
1335     current_workspace->raiseWindow(next);
1336     next->setInputFocus();
1337   }
1338 }
1339
1340
1341 void BScreen::prevFocus(void) {
1342   BlackboxWindow *focused = blackbox->getFocusedWindow(),
1343     *next = focused;
1344
1345   if (focused) {
1346     // if window is not on this screen, ignore it
1347     if (focused->getScreen()->getScreenNumber() != getScreenNumber())
1348       focused = (BlackboxWindow*) 0;
1349   }
1350
1351   if (focused && current_workspace->getCount() > 1) {
1352     // next is the next window to recieve focus, current is a place holder
1353     BlackboxWindow *current;
1354     do {
1355       current = next;
1356       next = current_workspace->getPrevWindowInList(current);
1357     } while(! next->setInputFocus() && next != focused);
1358
1359     if (next != focused)
1360       current_workspace->raiseWindow(next);
1361   } else if (current_workspace->getCount() >= 1) {
1362     next = current_workspace->getTopWindowOnStack();
1363
1364     current_workspace->raiseWindow(next);
1365     next->setInputFocus();
1366   }
1367 }
1368
1369
1370 void BScreen::raiseFocus(void) {
1371   BlackboxWindow *focused = blackbox->getFocusedWindow();
1372   if (! focused)
1373     return;
1374
1375   // if on this Screen, raise it
1376   if (focused->getScreen()->getScreenNumber() == getScreenNumber()) {
1377     Workspace *workspace = getWorkspace(focused->getWorkspaceNumber());
1378     workspace->raiseWindow(focused);
1379   }
1380 }
1381
1382
1383 void BScreen::InitMenu(void) {
1384   if (rootmenu) {
1385     rootmenuList.clear();
1386
1387     while (rootmenu->getCount())
1388       rootmenu->remove(0);
1389   } else {
1390     rootmenu = new Rootmenu(this);
1391   }
1392   bool defaultMenu = True;
1393
1394   FILE *menu_file = (FILE *) 0;
1395   const char *menu_filename = blackbox->getMenuFilename();
1396
1397   if (menu_filename) 
1398     if (! (menu_file = fopen(menu_filename, "r")))
1399       perror(menu_filename);
1400   if (! menu_file) {     // opening the menu file failed, try the default menu
1401     menu_filename = DEFAULTMENU;
1402     if (! (menu_file = fopen(menu_filename, "r")))
1403       perror(menu_filename);
1404   } 
1405
1406   if (menu_file) {
1407     if (feof(menu_file)) {
1408       fprintf(stderr, i18n(ScreenSet, ScreenEmptyMenuFile,
1409                            "%s: Empty menu file"),
1410               menu_filename);
1411     } else {
1412       char line[1024], label[1024];
1413       memset(line, 0, 1024);
1414       memset(label, 0, 1024);
1415
1416       while (fgets(line, 1024, menu_file) && ! feof(menu_file)) {
1417         if (line[0] != '#') {
1418           int i, key = 0, index = -1, len = strlen(line);
1419
1420           for (i = 0; i < len; i++) {
1421             if (line[i] == '[') index = 0;
1422             else if (line[i] == ']') break;
1423             else if (line[i] != ' ')
1424               if (index++ >= 0)
1425                 key += tolower(line[i]);
1426           }
1427
1428           if (key == 517) { // [begin]
1429             index = -1;
1430             for (i = index; i < len; i++) {
1431               if (line[i] == '(') index = 0;
1432               else if (line[i] == ')') break;
1433               else if (index++ >= 0) {
1434                 if (line[i] == '\\' && i < len - 1) i++;
1435                 label[index - 1] = line[i];
1436               }
1437             }
1438
1439             if (index == -1) index = 0;
1440             label[index] = '\0';
1441
1442             rootmenu->setLabel(label);
1443             defaultMenu = parseMenuFile(menu_file, rootmenu);
1444             if (! defaultMenu)
1445               blackbox->addMenuTimestamp(menu_filename);
1446             break;
1447           }
1448         }
1449       }
1450     }
1451     fclose(menu_file);
1452   }
1453
1454   if (defaultMenu) {
1455     rootmenu->setInternalMenu();
1456     rootmenu->insert(i18n(ScreenSet, Screenxterm, "xterm"),
1457                      BScreen::Execute,
1458                      i18n(ScreenSet, Screenxterm, "xterm"));
1459     rootmenu->insert(i18n(ScreenSet, ScreenRestart, "Restart"),
1460                      BScreen::Restart);
1461     rootmenu->insert(i18n(ScreenSet, ScreenExit, "Exit"),
1462                      BScreen::Exit);
1463     rootmenu->setLabel(i18n(BasemenuSet, BasemenuBlackboxMenu,
1464                             "Openbox Menu"));
1465   }
1466 }
1467
1468
1469 bool BScreen::parseMenuFile(FILE *file, Rootmenu *menu) {
1470   char line[1024], label[1024], command[1024];
1471
1472   while (! feof(file)) {
1473     memset(line, 0, 1024);
1474     memset(label, 0, 1024);
1475     memset(command, 0, 1024);
1476
1477     if (fgets(line, 1024, file)) {
1478       if (line[0] != '#') {
1479         int i, key = 0, parse = 0, index = -1, line_length = strlen(line);
1480
1481         // determine the keyword
1482         for (i = 0; i < line_length; i++) {
1483           if (line[i] == '[') parse = 1;
1484           else if (line[i] == ']') break;
1485           else if (line[i] != ' ')
1486             if (parse)
1487               key += tolower(line[i]);
1488         }
1489
1490         // get the label enclosed in ()'s
1491         parse = 0;
1492
1493         for (i = 0; i < line_length; i++) {
1494           if (line[i] == '(') {
1495             index = 0;
1496             parse = 1;
1497           } else if (line[i] == ')') break;
1498           else if (index++ >= 0) {
1499             if (line[i] == '\\' && i < line_length - 1) i++;
1500             label[index - 1] = line[i];
1501           }
1502         }
1503
1504         if (parse) {
1505           label[index] = '\0';
1506         } else {
1507           label[0] = '\0';
1508         }
1509
1510         // get the command enclosed in {}'s
1511         parse = 0;
1512         index = -1;
1513         for (i = 0; i < line_length; i++) {
1514           if (line[i] == '{') {
1515             index = 0;
1516             parse = 1;
1517           } else if (line[i] == '}') break;
1518           else if (index++ >= 0) {
1519             if (line[i] == '\\' && i < line_length - 1) i++;
1520             command[index - 1] = line[i];
1521           }
1522         }
1523
1524         if (parse) {
1525           command[index] = '\0';
1526         } else {
1527           command[0] = '\0';
1528         }
1529
1530         switch (key) {
1531         case 311: // end
1532           return ((menu->getCount() == 0) ? True : False);
1533
1534           break;
1535
1536         case 333: // nop
1537           if (! *label)
1538             label[0] = '\0';
1539           menu->insert(label);
1540
1541           break;
1542
1543         case 421: // exec
1544           if ((! *label) && (! *command)) {
1545             fprintf(stderr, i18n(ScreenSet, ScreenEXECError,
1546                                  "BScreen::parseMenuFile: [exec] error, "
1547                                  "no menu label and/or command defined\n"));
1548             continue;
1549           }
1550
1551           menu->insert(label, BScreen::Execute, command);
1552
1553           break;
1554
1555         case 442: // exit
1556           if (! *label) {
1557             fprintf(stderr, i18n(ScreenSet, ScreenEXITError,
1558                                  "BScreen::parseMenuFile: [exit] error, "
1559                                  "no menu label defined\n"));
1560             continue;
1561           }
1562
1563           menu->insert(label, BScreen::Exit);
1564
1565           break;
1566
1567         case 561: // style
1568           {
1569             if ((! *label) || (! *command)) {
1570               fprintf(stderr,
1571                       i18n(ScreenSet, ScreenSTYLEError,
1572                            "BScreen::parseMenuFile: [style] error, "
1573                            "no menu label and/or filename defined\n"));
1574               continue;
1575             }
1576
1577             string style = expandTilde(command);
1578
1579             menu->insert(label, BScreen::SetStyle, style.c_str());
1580           }
1581
1582           break;
1583
1584         case 630: // config
1585           if (! *label) {
1586             fprintf(stderr, i18n(ScreenSet, ScreenCONFIGError,
1587                                  "BScreen::parseMenufile: [config] error, "
1588                                  "no label defined"));
1589             continue;
1590           }
1591
1592           menu->insert(label, configmenu);
1593
1594           break;
1595
1596         case 740: // include
1597           {
1598             if (! *label) {
1599               fprintf(stderr, i18n(ScreenSet, ScreenINCLUDEError,
1600                                    "BScreen::parseMenuFile: [include] error, "
1601                                    "no filename defined\n"));
1602               continue;
1603             }
1604
1605             string newfile = expandTilde(label);
1606             FILE *submenufile = fopen(newfile.c_str(), "r");
1607
1608             if (submenufile) {
1609               struct stat buf;
1610               if (fstat(fileno(submenufile), &buf) ||
1611                   (! S_ISREG(buf.st_mode))) {
1612                 fprintf(stderr,
1613                         i18n(ScreenSet, ScreenINCLUDEErrorReg,
1614                              "BScreen::parseMenuFile: [include] error: "
1615                              "'%s' is not a regular file\n"), newfile.c_str());
1616                 break;
1617               }
1618
1619               if (! feof(submenufile)) {
1620                 if (! parseMenuFile(submenufile, menu))
1621                   blackbox->addMenuTimestamp(newfile);
1622
1623                 fclose(submenufile);
1624               }
1625             } else {
1626               perror(newfile.c_str());
1627             }
1628           }
1629
1630           break;
1631
1632         case 767: // submenu
1633           {
1634             if (! *label) {
1635               fprintf(stderr, i18n(ScreenSet, ScreenSUBMENUError,
1636                                    "BScreen::parseMenuFile: [submenu] error, "
1637                                    "no menu label defined\n"));
1638               continue;
1639             }
1640
1641             Rootmenu *submenu = new Rootmenu(this);
1642
1643             if (*command)
1644               submenu->setLabel(command);
1645             else
1646               submenu->setLabel(label);
1647
1648             parseMenuFile(file, submenu);
1649             submenu->update();
1650             menu->insert(label, submenu);
1651             rootmenuList.push_back(submenu);
1652           }
1653
1654           break;
1655
1656         case 773: // restart
1657           {
1658             if (! *label) {
1659               fprintf(stderr, i18n(ScreenSet, ScreenRESTARTError,
1660                                    "BScreen::parseMenuFile: [restart] error, "
1661                                    "no menu label defined\n"));
1662               continue;
1663             }
1664
1665             if (*command)
1666               menu->insert(label, BScreen::RestartOther, command);
1667             else
1668               menu->insert(label, BScreen::Restart);
1669           }
1670
1671           break;
1672
1673         case 845: // reconfig
1674           {
1675             if (! *label) {
1676               fprintf(stderr,
1677                       i18n(ScreenSet, ScreenRECONFIGError,
1678                            "BScreen::parseMenuFile: [reconfig] error, "
1679                            "no menu label defined\n"));
1680               continue;
1681             }
1682
1683             menu->insert(label, BScreen::Reconfigure);
1684           }
1685
1686           break;
1687
1688         case 995: // stylesdir
1689         case 1113: // stylesmenu
1690           {
1691             bool newmenu = ((key == 1113) ? True : False);
1692
1693             if ((! *label) || ((! *command) && newmenu)) {
1694               fprintf(stderr,
1695                       i18n(ScreenSet, ScreenSTYLESDIRError,
1696                            "BScreen::parseMenuFile: [stylesdir/stylesmenu]"
1697                            " error, no directory defined\n"));
1698               continue;
1699             }
1700
1701             char *directory = ((newmenu) ? command : label);
1702
1703             string stylesdir = expandTilde(directory);
1704
1705             struct stat statbuf;
1706
1707             if (! stat(stylesdir.c_str(), &statbuf)) {
1708               if (S_ISDIR(statbuf.st_mode)) {
1709                 Rootmenu *stylesmenu;
1710
1711                 if (newmenu)
1712                   stylesmenu = new Rootmenu(this);
1713                 else
1714                   stylesmenu = menu;
1715
1716                 DIR *d = opendir(stylesdir.c_str());
1717                 struct dirent *p;
1718                 std::vector<string> ls;
1719
1720                 while((p = readdir(d)))
1721                   ls.push_back(p->d_name);
1722
1723                 closedir(d);
1724
1725                 std::sort(ls.begin(), ls.end());
1726
1727                 std::vector<string>::iterator it = ls.begin(),
1728                   end = ls.end();
1729                 for (; it != end; ++it) {
1730                   const string& fname = *it;
1731
1732                   if (fname[fname.size()-1] == '~')
1733                     continue;
1734
1735                   string style = stylesdir;
1736                   style += '/';
1737                   style += fname;
1738
1739                   if ((! stat(style.c_str(), &statbuf)) &&
1740                       S_ISREG(statbuf.st_mode))
1741                     stylesmenu->insert(fname, BScreen::SetStyle, style);
1742                 }
1743
1744                 stylesmenu->update();
1745
1746                 if (newmenu) {
1747                   stylesmenu->setLabel(label);
1748                   menu->insert(label, stylesmenu);
1749                   rootmenuList.push_back(stylesmenu);
1750                 }
1751
1752                 blackbox->addMenuTimestamp(stylesdir);
1753               } else {
1754                 fprintf(stderr,
1755                         i18n(ScreenSet, ScreenSTYLESDIRErrorNotDir,
1756                              "BScreen::parseMenuFile:"
1757                              " [stylesdir/stylesmenu] error, %s is not a"
1758                              " directory\n"), stylesdir.c_str());
1759               }
1760             } else {
1761               fprintf(stderr,
1762                       i18n(ScreenSet, ScreenSTYLESDIRErrorNoExist,
1763                            "BScreen::parseMenuFile: [stylesdir/stylesmenu]"
1764                            " error, %s does not exist\n"), stylesdir.c_str());
1765             }
1766             break;
1767           }
1768
1769         case 1090: // workspaces
1770           {
1771             if (! *label) {
1772               fprintf(stderr,
1773                       i18n(ScreenSet, ScreenWORKSPACESError,
1774                            "BScreen:parseMenuFile: [workspaces] error, "
1775                            "no menu label defined\n"));
1776               continue;
1777             }
1778
1779             menu->insert(label, workspacemenu);
1780
1781             break;
1782           }
1783         }
1784       }
1785     }
1786   }
1787
1788   return ((menu->getCount() == 0) ? True : False);
1789 }
1790
1791
1792 void BScreen::shutdown(void) {
1793   XSelectInput(blackbox->getXDisplay(), getRootWindow(), NoEventMask);
1794   XSync(blackbox->getXDisplay(), False);
1795
1796   while(! windowList.empty())
1797     unmanageWindow(windowList.front(), True);
1798
1799   slit->shutdown();
1800 }
1801
1802
1803 void BScreen::showPosition(int x, int y) {
1804   if (! geom_visible) {
1805     XMoveResizeWindow(blackbox->getXDisplay(), geom_window,
1806                       (getWidth() - geom_w) / 2,
1807                       (getHeight() - geom_h) / 2, geom_w, geom_h);
1808     XMapWindow(blackbox->getXDisplay(), geom_window);
1809     XRaiseWindow(blackbox->getXDisplay(), geom_window);
1810
1811     geom_visible = True;
1812   }
1813
1814   char label[1024];
1815
1816   sprintf(label, i18n(ScreenSet, ScreenPositionFormat,
1817                       "X: %4d x Y: %4d"), x, y);
1818
1819   XClearWindow(blackbox->getXDisplay(), geom_window);
1820
1821   BPen pen(resource.wstyle.l_text_focus, resource.wstyle.font);
1822   if (i18n.multibyte()) {
1823     XmbDrawString(blackbox->getXDisplay(), geom_window,
1824                   resource.wstyle.fontset, pen.gc(),
1825                   resource.bevel_width, resource.bevel_width -
1826                   resource.wstyle.fontset_extents->max_ink_extent.y,
1827                   label, strlen(label));
1828   } else {
1829     XDrawString(blackbox->getXDisplay(), geom_window,
1830                 pen.gc(), resource.bevel_width,
1831                 resource.wstyle.font->ascent + resource.bevel_width,
1832                 label, strlen(label));
1833   }
1834 }
1835
1836
1837 void BScreen::showGeometry(unsigned int gx, unsigned int gy) {
1838   if (! geom_visible) {
1839     XMoveResizeWindow(blackbox->getXDisplay(), geom_window,
1840                       (getWidth() - geom_w) / 2,
1841                       (getHeight() - geom_h) / 2, geom_w, geom_h);
1842     XMapWindow(blackbox->getXDisplay(), geom_window);
1843     XRaiseWindow(blackbox->getXDisplay(), geom_window);
1844
1845     geom_visible = True;
1846   }
1847
1848   char label[1024];
1849
1850   sprintf(label, i18n(ScreenSet, ScreenGeometryFormat,
1851                       "W: %4d x H: %4d"), gx, gy);
1852
1853   XClearWindow(blackbox->getXDisplay(), geom_window);
1854
1855   BPen pen(resource.wstyle.l_text_focus, resource.wstyle.font);
1856   if (i18n.multibyte()) {
1857     XmbDrawString(blackbox->getXDisplay(), geom_window,
1858                   resource.wstyle.fontset, pen.gc(),
1859                   resource.bevel_width, resource.bevel_width -
1860                   resource.wstyle.fontset_extents->max_ink_extent.y,
1861                   label, strlen(label));
1862   } else {
1863     XDrawString(blackbox->getXDisplay(), geom_window,
1864                 pen.gc(), resource.bevel_width,
1865                 resource.wstyle.font->ascent +
1866                 resource.bevel_width, label, strlen(label));
1867   }
1868 }
1869
1870
1871 void BScreen::hideGeometry(void) {
1872   if (geom_visible) {
1873     XUnmapWindow(blackbox->getXDisplay(), geom_window);
1874     geom_visible = False;
1875   }
1876 }
1877
1878
1879 void BScreen::addStrut(Strut *strut) {
1880   strutList.push_back(strut);
1881 }
1882
1883
1884 void BScreen::removeStrut(Strut *strut) {
1885   strutList.remove(strut);
1886 }
1887
1888
1889 const Rect& BScreen::availableArea(void) const {
1890   if (doFullMax())
1891     return getRect(); // return the full screen
1892   return usableArea;
1893 }
1894
1895
1896 void BScreen::updateAvailableArea(void) {
1897   Rect old_area = usableArea;
1898   usableArea = getRect(); // reset to full screen
1899
1900   /* these values represent offsets from the screen edge
1901    * we look for the biggest offset on each edge and then apply them
1902    * all at once
1903    * do not be confused by the similarity to the names of Rect's members
1904    */
1905   unsigned int current_left = 0, current_right = 0, current_top = 0,
1906     current_bottom = 0;
1907
1908   StrutList::const_iterator it = strutList.begin(), end = strutList.end();
1909
1910   for(; it != end; ++it) {
1911     Strut *strut = *it;
1912     if (strut->left > current_left)
1913       current_left = strut->left;
1914     if (strut->top > current_top)
1915       current_top = strut->top;
1916     if (strut->right > current_right)
1917       current_right = strut->right;
1918     if (strut->bottom > current_bottom)
1919       current_bottom = strut->bottom;
1920   }
1921
1922   usableArea.setPos(current_left, current_top);
1923   usableArea.setSize(usableArea.width() - (current_left + current_right),
1924                      usableArea.height() - (current_top + current_bottom));
1925
1926   if (old_area != usableArea) {
1927     BlackboxWindowList::iterator it = windowList.begin(),
1928       end = windowList.end();
1929     for (; it != end; ++it)
1930       if ((*it)->isMaximized()) (*it)->remaximize();
1931   }
1932 }
1933
1934
1935 Workspace* BScreen::getWorkspace(unsigned int index) {
1936   assert(index < workspacesList.size());
1937   return workspacesList[index];
1938 }
1939
1940
1941 void BScreen::buttonPressEvent(XButtonEvent *xbutton) {
1942   if (xbutton->button == 1) {
1943     if (! isRootColormapInstalled())
1944       image_control->installRootColormap();
1945
1946     if (workspacemenu->isVisible())
1947       workspacemenu->hide();
1948
1949     if (rootmenu->isVisible())
1950       rootmenu->hide();
1951   } else if (xbutton->button == 2) {
1952     int mx = xbutton->x_root - (workspacemenu->getWidth() / 2);
1953     int my = xbutton->y_root - (workspacemenu->getTitleHeight() / 2);
1954
1955     if (mx < 0) mx = 0;
1956     if (my < 0) my = 0;
1957
1958     if (mx + workspacemenu->getWidth() > getWidth())
1959       mx = getWidth() - workspacemenu->getWidth() - getBorderWidth();
1960
1961     if (my + workspacemenu->getHeight() > getHeight())
1962       my = getHeight() - workspacemenu->getHeight() - getBorderWidth();
1963
1964     workspacemenu->move(mx, my);
1965
1966     if (! workspacemenu->isVisible()) {
1967       workspacemenu->removeParent();
1968       workspacemenu->show();
1969     }
1970   } else if (xbutton->button == 3) {
1971     int mx = xbutton->x_root - (rootmenu->getWidth() / 2);
1972     int my = xbutton->y_root - (rootmenu->getTitleHeight() / 2);
1973
1974     if (mx < 0) mx = 0;
1975     if (my < 0) my = 0;
1976
1977     if (mx + rootmenu->getWidth() > getWidth())
1978       mx = getWidth() - rootmenu->getWidth() - getBorderWidth();
1979
1980     if (my + rootmenu->getHeight() > getHeight())
1981       my = getHeight() - rootmenu->getHeight() - getBorderWidth();
1982
1983     rootmenu->move(mx, my);
1984
1985     if (! rootmenu->isVisible()) {
1986       blackbox->checkMenu();
1987       rootmenu->show();
1988     }
1989   // mouse wheel up
1990   } else if (xbutton->button == 4) {
1991     if (getCurrentWorkspaceID() >= getWorkspaceCount() - 1)
1992       changeWorkspaceID(0);
1993     else
1994       changeWorkspaceID(getCurrentWorkspaceID() + 1);
1995   // mouse wheel down
1996   } else if (xbutton->button == 5) {
1997     if (getCurrentWorkspaceID() == 0)
1998       changeWorkspaceID(getWorkspaceCount() - 1);
1999     else
2000       changeWorkspaceID(getCurrentWorkspaceID() - 1);
2001   }
2002 }
2003
2004
2005 void BScreen::toggleFocusModel(FocusModel model) {
2006   if (model == SloppyFocus) {
2007     saveSloppyFocus(True);
2008   } else {
2009     saveSloppyFocus(False);
2010     saveAutoRaise(False);
2011     saveClickRaise(False);
2012   }
2013
2014   updateFocusModel();
2015 }
2016
2017
2018 void BScreen::updateFocusModel()
2019 {
2020   std::for_each(workspacesList.begin(), workspacesList.end(),
2021                 std::mem_fun(&Workspace::updateFocusModel));
2022 }
2023
2024
2025 BTexture BScreen::readDatabaseTexture(const string &rname,
2026                                       const string &default_color,
2027                                       Configuration &style) {
2028   BTexture texture;
2029   string s;
2030
2031   if (style.getValue(rname, s))
2032     texture = BTexture(s);
2033   else
2034     texture.setTexture(BTexture::Solid | BTexture::Flat);
2035
2036   // associate this texture with this screen
2037   texture.setDisplay(getBaseDisplay(), getScreenNumber());
2038   texture.setImageControl(image_control);
2039
2040   if (texture.texture() & BTexture::Solid) {
2041     texture.setColor(readDatabaseColor(rname + ".color",
2042                                        default_color, style));
2043     texture.setColorTo(readDatabaseColor(rname + ".colorTo",
2044                                          default_color, style));
2045   } else if (texture.texture() & BTexture::Gradient) {
2046     texture.setColor(readDatabaseColor(rname + ".color",
2047                                        default_color, style));
2048     texture.setColorTo(readDatabaseColor(rname + ".colorTo",
2049                                          default_color, style));
2050   }
2051
2052   return texture;
2053 }
2054
2055
2056 BColor BScreen::readDatabaseColor(const string &rname,
2057                                   const string &default_color,
2058                                   Configuration &style) {
2059   BColor color;
2060   string s;
2061   if (style.getValue(rname, s))
2062     color = BColor(s, getBaseDisplay(), getScreenNumber());
2063   else
2064     color = BColor(default_color, getBaseDisplay(), getScreenNumber());
2065   return color;
2066 }
2067
2068
2069 XFontSet BScreen::readDatabaseFontSet(const string &rname,
2070                                       Configuration &style) {
2071   char *defaultFont = "fixed";
2072
2073   bool load_default = True;
2074   string s;
2075   XFontSet fontset = 0;
2076   if (style.getValue(rname, s) && (fontset = createFontSet(s)))
2077     load_default = False;
2078
2079   if (load_default) {
2080     fontset = createFontSet(defaultFont);
2081
2082     if (! fontset) {
2083       fprintf(stderr,
2084               i18n(ScreenSet, ScreenDefaultFontLoadFail,
2085                    "BScreen::setCurrentStyle(): couldn't load default font.\n"));
2086       exit(2);
2087     }
2088   }
2089
2090   return fontset;
2091 }
2092
2093
2094 XFontStruct *BScreen::readDatabaseFont(const string &rname,
2095                                        Configuration &style) {
2096   char *defaultFont = "fixed";
2097
2098   bool load_default = False;
2099   string s;
2100   XFontStruct *font = 0;
2101   if (style.getValue(rname, s)) {
2102     if ((font = XLoadQueryFont(blackbox->getXDisplay(), s.c_str())) == NULL) {
2103       fprintf(stderr,
2104               i18n(ScreenSet, ScreenFontLoadFail,
2105                    "BScreen::setCurrentStyle(): couldn't load font '%s'\n"),
2106               s.c_str());
2107
2108       load_default = True;
2109     }
2110   } else {
2111     load_default = True;
2112   }
2113
2114   if (load_default) {
2115     font = XLoadQueryFont(blackbox->getXDisplay(), defaultFont);
2116     if (font == NULL) {
2117       fprintf(stderr,
2118               i18n(ScreenSet, ScreenDefaultFontLoadFail,
2119                    "BScreen::setCurrentStyle(): couldn't load default font.\n"));
2120       exit(2);
2121     }
2122   }
2123
2124   return font;
2125 }
2126
2127
2128 #ifndef    HAVE_STRCASESTR
2129 static const char * strcasestr(const char *str, const char *ptn) {
2130   const char *s2, *p2;
2131   for(; *str; str++) {
2132     for(s2=str,p2=ptn; ; s2++,p2++) {
2133       if (! *p2) return str;
2134       if (toupper(*s2) != toupper(*p2)) break;
2135     }
2136   }
2137   return NULL;
2138 }
2139 #endif // HAVE_STRCASESTR
2140
2141
2142 static const char *getFontElement(const char *pattern, char *buf,
2143                                   int bufsiz, ...) {
2144   const char *p, *v;
2145   char *p2;
2146   va_list va;
2147
2148   va_start(va, bufsiz);
2149   buf[bufsiz-1] = 0;
2150   buf[bufsiz-2] = '*';
2151   while((v = va_arg(va, char *)) != NULL) {
2152     p = strcasestr(pattern, v);
2153     if (p) {
2154       strncpy(buf, p+1, bufsiz-2);
2155       p2 = strchr(buf, '-');
2156       if (p2) *p2=0;
2157       va_end(va);
2158       return p;
2159     }
2160   }
2161   va_end(va);
2162   strncpy(buf, "*", bufsiz);
2163   return NULL;
2164 }
2165
2166
2167 static const char *getFontSize(const char *pattern, int *size) {
2168   const char *p;
2169   const char *p2=NULL;
2170   int n=0;
2171
2172   for (p=pattern; 1; p++) {
2173     if (! *p) {
2174       if (p2!=NULL && n>1 && n<72) {
2175         *size = n; return p2+1;
2176       } else {
2177         *size = 16; return NULL;
2178       }
2179     } else if (*p=='-') {
2180       if (n>1 && n<72 && p2!=NULL) {
2181         *size = n;
2182         return p2+1;
2183       }
2184       p2=p; n=0;
2185     } else if (*p>='0' && *p<='9' && p2!=NULL) {
2186       n *= 10;
2187       n += *p-'0';
2188     } else {
2189       p2=NULL; n=0;
2190     }
2191   }
2192 }
2193
2194
2195 XFontSet BScreen::createFontSet(const string &fontname) {
2196   XFontSet fs;
2197   char **missing, *def = "-";
2198   int nmissing, pixel_size = 0, buf_size = 0;
2199   char weight[FONT_ELEMENT_SIZE], slant[FONT_ELEMENT_SIZE];
2200
2201   fs = XCreateFontSet(blackbox->getXDisplay(),
2202                       fontname.c_str(), &missing, &nmissing, &def);
2203   if (fs && (! nmissing))
2204     return fs;
2205
2206   const char *nfontname = fontname.c_str();
2207 #ifdef    HAVE_SETLOCALE
2208   if (! fs) {
2209     if (nmissing) XFreeStringList(missing);
2210
2211     setlocale(LC_CTYPE, "C");
2212     fs = XCreateFontSet(blackbox->getXDisplay(), fontname.c_str(),
2213                         &missing, &nmissing, &def);
2214     setlocale(LC_CTYPE, "");
2215   }
2216 #endif // HAVE_SETLOCALE
2217
2218   if (fs) {
2219     XFontStruct **fontstructs;
2220     char **fontnames;
2221     XFontsOfFontSet(fs, &fontstructs, &fontnames);
2222     nfontname = fontnames[0];
2223   }
2224
2225   getFontElement(nfontname, weight, FONT_ELEMENT_SIZE,
2226                  "-medium-", "-bold-", "-demibold-", "-regular-", NULL);
2227   getFontElement(nfontname, slant, FONT_ELEMENT_SIZE,
2228                  "-r-", "-i-", "-o-", "-ri-", "-ro-", NULL);
2229   getFontSize(nfontname, &pixel_size);
2230
2231   if (! strcmp(weight, "*"))
2232     strncpy(weight, "medium", FONT_ELEMENT_SIZE);
2233   if (! strcmp(slant, "*"))
2234     strncpy(slant, "r", FONT_ELEMENT_SIZE);
2235   if (pixel_size < 3)
2236     pixel_size = 3;
2237   else if (pixel_size > 97)
2238     pixel_size = 97;
2239
2240   buf_size = strlen(nfontname) + (FONT_ELEMENT_SIZE * 2) + 64;
2241   char *pattern2 = new char[buf_size];
2242   sprintf(pattern2,
2243            "%s,"
2244            "-*-*-%s-%s-*-*-%d-*-*-*-*-*-*-*,"
2245            "-*-*-*-*-*-*-%d-*-*-*-*-*-*-*,*",
2246            nfontname, weight, slant, pixel_size, pixel_size);
2247   nfontname = pattern2;
2248
2249   if (nmissing)
2250     XFreeStringList(missing);
2251   if (fs)
2252     XFreeFontSet(blackbox->getXDisplay(), fs);
2253
2254   fs = XCreateFontSet(blackbox->getXDisplay(), nfontname, &missing,
2255                       &nmissing, &def);
2256
2257   delete [] pattern2;
2258
2259   return fs;
2260 }