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