]> icculus.org git repositories - mikachu/openbox.git/blob - src/Screen.cc
on reconfigure, save all of the open submenus instead of just one, and then reopen...
[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 <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   typedef std::vector<int> SubList;
685   SubList remember_subs;
686
687   // save the current open menus
688   Basemenu *menu = rootmenu;
689   int submenu;
690   while ((submenu = menu->getCurrentSubmenu()) >= 0) {
691     remember_subs.push_back(submenu);
692     menu = menu->find(submenu)->submenu();
693     assert(menu);
694   }
695   
696   InitMenu();
697   raiseWindows(0, 0);
698   rootmenu->reconfigure();
699
700   // reopen the saved menus
701   menu = rootmenu;
702   const SubList::iterator subs_end = remember_subs.end();
703   for (SubList::iterator it = remember_subs.begin(); it != subs_end; ++it) {
704     menu->drawSubmenu(*it);
705     menu = menu->find(*it)->submenu();
706     if (! menu)
707       break;
708   }
709
710   configmenu->reconfigure();
711
712   toolbar->reconfigure();
713
714   slit->reconfigure();
715
716   std::for_each(workspacesList.begin(), workspacesList.end(),
717                 std::mem_fun(&Workspace::reconfigure));
718
719   BlackboxWindowList::iterator iit = iconList.begin();
720   for (; iit != iconList.end(); ++iit) {
721     BlackboxWindow *bw = *iit;
722     if (bw->validateClient())
723       bw->reconfigure();
724   }
725
726   image_control->timeout();
727 }
728
729
730 void BScreen::rereadMenu(void) {
731   InitMenu();
732   raiseWindows(0, 0);
733
734   rootmenu->reconfigure();
735 }
736
737
738 void BScreen::LoadStyle(void) {
739   Configuration style;
740
741   const char *sfile = blackbox->getStyleFilename();
742   if (sfile != NULL) {
743     style.setFile(sfile);
744     if (! style.load()) {
745       style.setFile(DEFAULTSTYLE);
746       if (! style.load())
747         style.create();  // hardcoded default values will be used.
748     }
749   }
750
751   string s;
752
753   // load fonts/fontsets
754   if (resource.wstyle.fontset)
755     XFreeFontSet(blackbox->getXDisplay(), resource.wstyle.fontset);
756   if (resource.tstyle.fontset)
757     XFreeFontSet(blackbox->getXDisplay(), resource.tstyle.fontset);
758   if (resource.mstyle.f_fontset)
759     XFreeFontSet(blackbox->getXDisplay(), resource.mstyle.f_fontset);
760   if (resource.mstyle.t_fontset)
761     XFreeFontSet(blackbox->getXDisplay(), resource.mstyle.t_fontset);
762   resource.wstyle.fontset = 0;
763   resource.tstyle.fontset = 0;
764   resource.mstyle.f_fontset = 0;
765   resource.mstyle.t_fontset = 0;
766   if (resource.wstyle.font)
767     XFreeFont(blackbox->getXDisplay(), resource.wstyle.font);
768   if (resource.tstyle.font)
769     XFreeFont(blackbox->getXDisplay(), resource.tstyle.font);
770   if (resource.mstyle.f_font)
771     XFreeFont(blackbox->getXDisplay(), resource.mstyle.f_font);
772   if (resource.mstyle.t_font)
773     XFreeFont(blackbox->getXDisplay(), resource.mstyle.t_font);
774   resource.wstyle.font = 0;
775   resource.tstyle.font = 0;
776   resource.mstyle.f_font = 0;
777   resource.mstyle.t_font = 0;
778
779   if (i18n.multibyte()) {
780     resource.wstyle.fontset = readDatabaseFontSet("window.font", style);
781     resource.tstyle.fontset = readDatabaseFontSet("toolbar.font", style);
782     resource.mstyle.t_fontset = readDatabaseFontSet("menu.title.font", style);
783     resource.mstyle.f_fontset = readDatabaseFontSet("menu.frame.font", style);
784
785     resource.mstyle.t_fontset_extents =
786       XExtentsOfFontSet(resource.mstyle.t_fontset);
787     resource.mstyle.f_fontset_extents =
788       XExtentsOfFontSet(resource.mstyle.f_fontset);
789     resource.tstyle.fontset_extents =
790       XExtentsOfFontSet(resource.tstyle.fontset);
791     resource.wstyle.fontset_extents =
792       XExtentsOfFontSet(resource.wstyle.fontset);
793   } else {
794     resource.wstyle.font = readDatabaseFont("window.font", style);
795     resource.tstyle.font = readDatabaseFont("toolbar.font", style);
796     resource.mstyle.t_font = readDatabaseFont("menu.title.font", style);
797     resource.mstyle.f_font = readDatabaseFont("menu.frame.font", style);
798   }
799
800   // load window config
801   resource.wstyle.t_focus =
802     readDatabaseTexture("window.title.focus", "white", style);
803   resource.wstyle.t_unfocus =
804     readDatabaseTexture("window.title.unfocus", "black", style);
805   resource.wstyle.l_focus =
806     readDatabaseTexture("window.label.focus", "white", style);
807   resource.wstyle.l_unfocus =
808     readDatabaseTexture("window.label.unfocus", "black", style);
809   resource.wstyle.h_focus =
810     readDatabaseTexture("window.handle.focus", "white", style);
811   resource.wstyle.h_unfocus =
812     readDatabaseTexture("window.handle.unfocus", "black", style);
813   resource.wstyle.g_focus =
814     readDatabaseTexture("window.grip.focus", "white", style);
815   resource.wstyle.g_unfocus =
816     readDatabaseTexture("window.grip.unfocus", "black", style);
817   resource.wstyle.b_focus =
818     readDatabaseTexture("window.button.focus", "white", style);
819   resource.wstyle.b_unfocus =
820     readDatabaseTexture("window.button.unfocus", "black", style);
821   resource.wstyle.b_pressed =
822     readDatabaseTexture("window.button.pressed", "black", style);
823   resource.wstyle.f_focus =
824     readDatabaseColor("window.frame.focusColor", "white", style);
825   resource.wstyle.f_unfocus =
826     readDatabaseColor("window.frame.unfocusColor", "black", style);
827   resource.wstyle.l_text_focus =
828     readDatabaseColor("window.label.focus.textColor", "black", style);
829   resource.wstyle.l_text_unfocus =
830     readDatabaseColor("window.label.unfocus.textColor", "white", style);
831   resource.wstyle.b_pic_focus =
832     readDatabaseColor("window.button.focus.picColor", "black", style);
833   resource.wstyle.b_pic_unfocus =
834     readDatabaseColor("window.button.unfocus.picColor", "white", style);
835
836   resource.wstyle.justify = LeftJustify;
837   if (style.getValue("window.justify", s)) {
838     if (s == "right" || s == "Right")
839       resource.wstyle.justify = RightJustify;
840     else if (s == "center" || s == "Center")
841       resource.wstyle.justify = CenterJustify;
842   }
843
844   // load toolbar config
845   resource.tstyle.toolbar =
846     readDatabaseTexture("toolbar", "black", style);
847   resource.tstyle.label =
848     readDatabaseTexture("toolbar.label", "black", style);
849   resource.tstyle.window =
850     readDatabaseTexture("toolbar.windowLabel", "black", style);
851   resource.tstyle.button =
852     readDatabaseTexture("toolbar.button", "white", style);
853   resource.tstyle.pressed =
854     readDatabaseTexture("toolbar.button.pressed", "black", style);
855   resource.tstyle.clock =
856     readDatabaseTexture("toolbar.clock", "black", style);
857   resource.tstyle.l_text =
858     readDatabaseColor("toolbar.label.textColor", "white", style);
859   resource.tstyle.w_text =
860     readDatabaseColor("toolbar.windowLabel.textColor", "white", style);
861   resource.tstyle.c_text =
862     readDatabaseColor("toolbar.clock.textColor", "white", style);
863   resource.tstyle.b_pic =
864     readDatabaseColor("toolbar.button.picColor", "black", style);
865
866   resource.tstyle.justify = LeftJustify;
867   if (style.getValue("toolbar.justify", s)) {
868     if (s == "right" || s == "Right")
869       resource.tstyle.justify = RightJustify;
870     else if (s == "center" || s == "Center")
871       resource.tstyle.justify = CenterJustify;
872   }
873
874   // load menu config
875   resource.mstyle.title =
876     readDatabaseTexture("menu.title", "white", style);
877   resource.mstyle.frame =
878     readDatabaseTexture("menu.frame", "black", style);
879   resource.mstyle.hilite =
880     readDatabaseTexture("menu.hilite", "white", style);
881   resource.mstyle.t_text =
882     readDatabaseColor("menu.title.textColor", "black", style);
883   resource.mstyle.f_text =
884     readDatabaseColor("menu.frame.textColor", "white", style);
885   resource.mstyle.d_text =
886     readDatabaseColor("menu.frame.disableColor", "black", style);
887   resource.mstyle.h_text =
888     readDatabaseColor("menu.hilite.textColor", "black", style);
889
890   resource.mstyle.t_justify = LeftJustify;
891   if (style.getValue("menu.title.justify", s)) {
892     if (s == "right" || s == "Right")
893       resource.mstyle.t_justify = RightJustify;
894     else if (s == "center" || s == "Center")
895       resource.mstyle.t_justify = CenterJustify;
896   }
897
898   resource.mstyle.f_justify = LeftJustify;
899   if (style.getValue("menu.frame.justify", s)) {
900     if (s == "right" || s == "Right")
901       resource.mstyle.f_justify = RightJustify;
902     else if (s == "center" || s == "Center")
903       resource.mstyle.f_justify = CenterJustify;
904   }
905
906   resource.mstyle.bullet = Basemenu::Triangle;
907   if (style.getValue("menu.bullet", s)) {
908     if (s == "empty" || s == "Empty")
909       resource.mstyle.bullet = Basemenu::Empty;
910     else if (s == "square" || s == "Square")
911       resource.mstyle.bullet = Basemenu::Square;
912     else if (s == "diamond" || s == "Diamond")
913       resource.mstyle.bullet = Basemenu::Diamond;
914   }
915
916   resource.mstyle.bullet_pos = Basemenu::Left;
917   if (style.getValue("menu.bullet.position", s)) {
918     if (s == "right" || s == "Right")
919       resource.mstyle.bullet_pos = Basemenu::Right;
920   }
921
922   resource.border_color =
923     readDatabaseColor("borderColor", "black", style);
924
925   // load bevel, border and handle widths
926   if (! style.getValue("handleWidth", resource.handle_width) ||
927       resource.handle_width > (getWidth() / 2) || resource.handle_width == 0)
928     resource.handle_width = 6;
929
930   if (! style.getValue("borderWidth", resource.border_width))
931     resource.border_width = 1;
932
933   if (! style.getValue("bevelWidth", resource.bevel_width) ||
934       resource.bevel_width > (getWidth() / 2) || resource.bevel_width == 0)
935     resource.bevel_width = 3;
936
937   if (! style.getValue("frameWidth", resource.frame_width) ||
938       resource.frame_width > (getWidth() / 2))
939     resource.frame_width = resource.bevel_width;
940
941   if (style.getValue("rootCommand", s))
942     bexec(s, displayString());
943 }
944
945
946 void BScreen::addIcon(BlackboxWindow *w) {
947   if (! w) return;
948
949   w->setWorkspace(BSENTINEL);
950   w->setWindowNumber(iconList.size());
951
952   iconList.push_back(w);
953
954   const char* title = w->getIconTitle();
955   iconmenu->insert(title);
956   iconmenu->update();
957 }
958
959
960 void BScreen::removeIcon(BlackboxWindow *w) {
961   if (! w) return;
962
963   iconList.remove(w);
964
965   iconmenu->remove(w->getWindowNumber());
966   iconmenu->update();
967
968   BlackboxWindowList::iterator it = iconList.begin(),
969     end = iconList.end();
970   for (int i = 0; it != end; ++it)
971     (*it)->setWindowNumber(i++);
972 }
973
974
975 BlackboxWindow *BScreen::getIcon(unsigned int index) {
976   if (index < iconList.size()) {
977     BlackboxWindowList::iterator it = iconList.begin();
978     for (; index > 0; --index, ++it) ; /* increment to index */
979     return *it;
980   }
981
982   return (BlackboxWindow *) 0;
983 }
984
985
986 unsigned int BScreen::addWorkspace(void) {
987   Workspace *wkspc = new Workspace(this, workspacesList.size());
988   workspacesList.push_back(wkspc);
989   saveWorkspaces(getWorkspaceCount());
990   saveWorkspaceNames();
991
992   workspacemenu->insert(wkspc->getName(), wkspc->getMenu(),
993                         wkspc->getID() + 2);
994   workspacemenu->update();
995
996   toolbar->reconfigure();
997
998   updateNetizenWorkspaceCount();
999
1000   return workspacesList.size();
1001 }
1002
1003
1004 unsigned int BScreen::removeLastWorkspace(void) {
1005   if (workspacesList.size() == 1)
1006     return 1;
1007
1008   Workspace *wkspc = workspacesList.back();
1009
1010   if (current_workspace->getID() == wkspc->getID())
1011     changeWorkspaceID(current_workspace->getID() - 1);
1012
1013   wkspc->removeAll();
1014
1015   workspacemenu->remove(wkspc->getID() + 2);
1016   workspacemenu->update();
1017
1018   workspacesList.pop_back();
1019   delete wkspc;
1020
1021   saveWorkspaces(getWorkspaceCount());
1022   saveWorkspaceNames();
1023
1024   toolbar->reconfigure();
1025
1026   updateNetizenWorkspaceCount();
1027
1028   return workspacesList.size();
1029 }
1030
1031
1032 void BScreen::changeWorkspaceID(unsigned int id) {
1033   if (! current_workspace) return;
1034
1035   if (id != current_workspace->getID()) {
1036     current_workspace->hideAll();
1037
1038     workspacemenu->setItemSelected(current_workspace->getID() + 2, False);
1039
1040     if (blackbox->getFocusedWindow() &&
1041         blackbox->getFocusedWindow()->getScreen() == this &&
1042         (! blackbox->getFocusedWindow()->isStuck())) {
1043       current_workspace->setLastFocusedWindow(blackbox->getFocusedWindow());
1044       blackbox->setFocusedWindow((BlackboxWindow *) 0);
1045     }
1046
1047     current_workspace = getWorkspace(id);
1048
1049     xatom->setValue(getRootWindow(), XAtom::net_current_desktop,
1050                     XAtom::cardinal, id);
1051     printf("%d\n", id);
1052
1053     workspacemenu->setItemSelected(current_workspace->getID() + 2, True);
1054     toolbar->redrawWorkspaceLabel(True);
1055
1056     current_workspace->showAll();
1057
1058     if (resource.focus_last && current_workspace->getLastFocusedWindow()) {
1059       XSync(blackbox->getXDisplay(), False);
1060       current_workspace->getLastFocusedWindow()->setInputFocus();
1061     }
1062   }
1063
1064   updateNetizenCurrentWorkspace();
1065 }
1066
1067
1068 void BScreen::manageWindow(Window w) {
1069   new BlackboxWindow(blackbox, w, this);
1070
1071   BlackboxWindow *win = blackbox->searchWindow(w);
1072   if (! win)
1073     return;
1074
1075   windowList.push_back(win);
1076
1077   XMapRequestEvent mre;
1078   mre.window = w;
1079   win->restoreAttributes();
1080   win->mapRequestEvent(&mre);
1081 }
1082
1083
1084 void BScreen::unmanageWindow(BlackboxWindow *w, bool remap) {
1085   w->restore(remap);
1086
1087   if (w->getWorkspaceNumber() != BSENTINEL &&
1088       w->getWindowNumber() != BSENTINEL)
1089     getWorkspace(w->getWorkspaceNumber())->removeWindow(w);
1090   else if (w->isIconic())
1091     removeIcon(w);
1092
1093   windowList.remove(w);
1094
1095   if (blackbox->getFocusedWindow() == w)
1096     blackbox->setFocusedWindow((BlackboxWindow *) 0);
1097
1098   removeNetizen(w->getClientWindow());
1099
1100   /*
1101     some managed windows can also be window group controllers.  when
1102     unmanaging such windows, we should also delete the window group.
1103   */
1104   BWindowGroup *group = blackbox->searchGroup(w->getClientWindow());
1105   delete group;
1106
1107   delete w;
1108 }
1109
1110
1111 void BScreen::addNetizen(Netizen *n) {
1112   netizenList.push_back(n);
1113
1114   n->sendWorkspaceCount();
1115   n->sendCurrentWorkspace();
1116
1117   WorkspaceList::iterator it = workspacesList.begin();
1118   const WorkspaceList::iterator end = workspacesList.end();
1119   for (; it != end; ++it)
1120     (*it)->sendWindowList(*n);
1121
1122   Window f = ((blackbox->getFocusedWindow()) ?
1123               blackbox->getFocusedWindow()->getClientWindow() : None);
1124   n->sendWindowFocus(f);
1125 }
1126
1127
1128 void BScreen::removeNetizen(Window w) {
1129   NetizenList::iterator it = netizenList.begin();
1130   for (; it != netizenList.end(); ++it) {
1131     if ((*it)->getWindowID() == w) {
1132       delete *it;
1133       netizenList.erase(it);
1134       break;
1135     }
1136   }
1137 }
1138
1139
1140 void BScreen::updateNetizenCurrentWorkspace(void) {
1141   std::for_each(netizenList.begin(), netizenList.end(),
1142                 std::mem_fun(&Netizen::sendCurrentWorkspace));
1143 }
1144
1145
1146 void BScreen::updateNetizenWorkspaceCount(void) {
1147   xatom->setValue(getRootWindow(), XAtom::net_number_of_desktops,
1148                   XAtom::cardinal, workspacesList.size());
1149
1150   std::for_each(netizenList.begin(), netizenList.end(),
1151                 std::mem_fun(&Netizen::sendWorkspaceCount));
1152 }
1153
1154
1155 void BScreen::updateNetizenWindowFocus(void) {
1156   Window f = ((blackbox->getFocusedWindow()) ?
1157               blackbox->getFocusedWindow()->getClientWindow() : None);
1158   NetizenList::iterator it = netizenList.begin();
1159   for (; it != netizenList.end(); ++it)
1160     (*it)->sendWindowFocus(f);
1161 }
1162
1163
1164 void BScreen::updateNetizenWindowAdd(Window w, unsigned long p) {
1165   NetizenList::iterator it = netizenList.begin();
1166   for (; it != netizenList.end(); ++it) {
1167     (*it)->sendWindowAdd(w, p);
1168   }
1169 }
1170
1171
1172 void BScreen::updateNetizenWindowDel(Window w) {
1173   NetizenList::iterator it = netizenList.begin();
1174   for (; it != netizenList.end(); ++it)
1175     (*it)->sendWindowDel(w);
1176 }
1177
1178
1179 void BScreen::updateNetizenWindowRaise(Window w) {
1180   NetizenList::iterator it = netizenList.begin();
1181   for (; it != netizenList.end(); ++it)
1182     (*it)->sendWindowRaise(w);
1183 }
1184
1185
1186 void BScreen::updateNetizenWindowLower(Window w) {
1187   NetizenList::iterator it = netizenList.begin();
1188   for (; it != netizenList.end(); ++it)
1189     (*it)->sendWindowLower(w);
1190 }
1191
1192
1193 void BScreen::updateNetizenConfigNotify(XEvent *e) {
1194   NetizenList::iterator it = netizenList.begin();
1195   for (; it != netizenList.end(); ++it)
1196     (*it)->sendConfigNotify(e);
1197 }
1198
1199
1200 void BScreen::raiseWindows(Window *workspace_stack, unsigned int num) {
1201   // XXX: why 13??
1202   Window *session_stack = new
1203     Window[(num + workspacesList.size() + rootmenuList.size() + 13)];
1204   unsigned int i = 0, k = num;
1205
1206   XRaiseWindow(blackbox->getXDisplay(), iconmenu->getWindowID());
1207   *(session_stack + i++) = iconmenu->getWindowID();
1208
1209   WorkspaceList::iterator wit = workspacesList.begin();
1210   const WorkspaceList::iterator w_end = workspacesList.end();
1211   for (; wit != w_end; ++wit)
1212     *(session_stack + i++) = (*wit)->getMenu()->getWindowID();
1213
1214   *(session_stack + i++) = workspacemenu->getWindowID();
1215
1216   *(session_stack + i++) = configmenu->getFocusmenu()->getWindowID();
1217   *(session_stack + i++) = configmenu->getPlacementmenu()->getWindowID();
1218   *(session_stack + i++) = configmenu->getWindowID();
1219
1220   *(session_stack + i++) = slit->getMenu()->getDirectionmenu()->getWindowID();
1221   *(session_stack + i++) = slit->getMenu()->getPlacementmenu()->getWindowID();
1222   *(session_stack + i++) = slit->getMenu()->getWindowID();
1223
1224   *(session_stack + i++) =
1225     toolbar->getMenu()->getPlacementmenu()->getWindowID();
1226   *(session_stack + i++) = toolbar->getMenu()->getWindowID();
1227
1228   RootmenuList::iterator rit = rootmenuList.begin();
1229   for (; rit != rootmenuList.end(); ++rit)
1230     *(session_stack + i++) = (*rit)->getWindowID();
1231   *(session_stack + i++) = rootmenu->getWindowID();
1232
1233   if (toolbar->isOnTop())
1234     *(session_stack + i++) = toolbar->getWindowID();
1235
1236   if (slit->isOnTop())
1237     *(session_stack + i++) = slit->getWindowID();
1238
1239   while (k--)
1240     *(session_stack + i++) = *(workspace_stack + k);
1241
1242   XRestackWindows(blackbox->getXDisplay(), session_stack, i);
1243
1244   delete [] session_stack;
1245 }
1246
1247
1248 void BScreen::addWorkspaceName(const string& name) {
1249   workspaceNames.push_back(name);
1250 }
1251
1252
1253 /*
1254  * I would love to kill this function and the accompanying workspaceNames
1255  * list.  However, we have a chicken and egg situation.  The names are read
1256  * in during load_rc() which happens before the workspaces are created.
1257  * The current solution is to read the names into a list, then use the list
1258  * later for constructing the workspaces.  It is only used during initial
1259  * BScreen creation.
1260  */
1261 const string BScreen::getNameOfWorkspace(unsigned int id) {
1262   if (id < workspaceNames.size())
1263     return workspaceNames[id];
1264   return string("");
1265 }
1266
1267
1268 void BScreen::reassociateWindow(BlackboxWindow *w, unsigned int wkspc_id,
1269                                 bool ignore_sticky) {
1270   if (! w) return;
1271
1272   if (wkspc_id == BSENTINEL)
1273     wkspc_id = current_workspace->getID();
1274
1275   if (w->getWorkspaceNumber() == wkspc_id)
1276     return;
1277
1278   if (w->isIconic()) {
1279     removeIcon(w);
1280     getWorkspace(wkspc_id)->addWindow(w);
1281   } else if (ignore_sticky || ! w->isStuck()) {
1282     getWorkspace(w->getWorkspaceNumber())->removeWindow(w);
1283     getWorkspace(wkspc_id)->addWindow(w);
1284   }
1285 }
1286
1287
1288 void BScreen::propagateWindowName(const BlackboxWindow *bw) {
1289   if (bw->isIconic()) {
1290     iconmenu->changeItemLabel(bw->getWindowNumber(), bw->getIconTitle());
1291     iconmenu->update();
1292   }
1293   else {
1294     Clientmenu *clientmenu = getWorkspace(bw->getWorkspaceNumber())->getMenu();
1295     clientmenu->changeItemLabel(bw->getWindowNumber(), bw->getTitle());
1296     clientmenu->update();
1297
1298     if (blackbox->getFocusedWindow() == bw)
1299       toolbar->redrawWindowLabel(True);
1300   }
1301 }
1302
1303
1304 void BScreen::nextFocus(void) {
1305   BlackboxWindow *focused = blackbox->getFocusedWindow(),
1306     *next = focused;
1307
1308   if (focused) {
1309     // if window is not on this screen, ignore it
1310     if (focused->getScreen()->getScreenNumber() != getScreenNumber())
1311       focused = (BlackboxWindow*) 0;
1312   }
1313
1314   if (focused && current_workspace->getCount() > 1) {
1315     // next is the next window to recieve focus, current is a place holder
1316     BlackboxWindow *current;
1317     do {
1318       current = next;
1319       next = current_workspace->getNextWindowInList(current);
1320     } while(! next->setInputFocus() && next != focused);
1321
1322     if (next != focused)
1323       current_workspace->raiseWindow(next);
1324   } else if (current_workspace->getCount() >= 1) {
1325     next = current_workspace->getTopWindowOnStack();
1326
1327     current_workspace->raiseWindow(next);
1328     next->setInputFocus();
1329   }
1330 }
1331
1332
1333 void BScreen::prevFocus(void) {
1334   BlackboxWindow *focused = blackbox->getFocusedWindow(),
1335     *next = focused;
1336
1337   if (focused) {
1338     // if window is not on this screen, ignore it
1339     if (focused->getScreen()->getScreenNumber() != getScreenNumber())
1340       focused = (BlackboxWindow*) 0;
1341   }
1342
1343   if (focused && current_workspace->getCount() > 1) {
1344     // next is the next window to recieve focus, current is a place holder
1345     BlackboxWindow *current;
1346     do {
1347       current = next;
1348       next = current_workspace->getPrevWindowInList(current);
1349     } while(! next->setInputFocus() && next != focused);
1350
1351     if (next != focused)
1352       current_workspace->raiseWindow(next);
1353   } else if (current_workspace->getCount() >= 1) {
1354     next = current_workspace->getTopWindowOnStack();
1355
1356     current_workspace->raiseWindow(next);
1357     next->setInputFocus();
1358   }
1359 }
1360
1361
1362 void BScreen::raiseFocus(void) {
1363   BlackboxWindow *focused = blackbox->getFocusedWindow();
1364   if (! focused)
1365     return;
1366
1367   // if on this Screen, raise it
1368   if (focused->getScreen()->getScreenNumber() == getScreenNumber()) {
1369     Workspace *workspace = getWorkspace(focused->getWorkspaceNumber());
1370     workspace->raiseWindow(focused);
1371   }
1372 }
1373
1374
1375 void BScreen::InitMenu(void) {
1376   if (rootmenu) {
1377     rootmenuList.clear();
1378
1379     while (rootmenu->getCount())
1380       rootmenu->remove(0);
1381   } else {
1382     rootmenu = new Rootmenu(this);
1383   }
1384   bool defaultMenu = True;
1385
1386   FILE *menu_file = (FILE *) 0;
1387   const char *menu_filename = blackbox->getMenuFilename();
1388
1389   if (menu_filename) 
1390     if (! (menu_file = fopen(menu_filename, "r")))
1391       perror(menu_filename);
1392   if (! menu_file) {     // opening the menu file failed, try the default menu
1393     menu_filename = DEFAULTMENU;
1394     if (! (menu_file = fopen(menu_filename, "r")))
1395       perror(menu_filename);
1396   } 
1397
1398   if (menu_file) {
1399     if (feof(menu_file)) {
1400       fprintf(stderr, i18n(ScreenSet, ScreenEmptyMenuFile,
1401                            "%s: Empty menu file"),
1402               menu_filename);
1403     } else {
1404       char line[1024], label[1024];
1405       memset(line, 0, 1024);
1406       memset(label, 0, 1024);
1407
1408       while (fgets(line, 1024, menu_file) && ! feof(menu_file)) {
1409         if (line[0] != '#') {
1410           int i, key = 0, index = -1, len = strlen(line);
1411
1412           for (i = 0; i < len; i++) {
1413             if (line[i] == '[') index = 0;
1414             else if (line[i] == ']') break;
1415             else if (line[i] != ' ')
1416               if (index++ >= 0)
1417                 key += tolower(line[i]);
1418           }
1419
1420           if (key == 517) { // [begin]
1421             index = -1;
1422             for (i = index; i < len; i++) {
1423               if (line[i] == '(') index = 0;
1424               else if (line[i] == ')') break;
1425               else if (index++ >= 0) {
1426                 if (line[i] == '\\' && i < len - 1) i++;
1427                 label[index - 1] = line[i];
1428               }
1429             }
1430
1431             if (index == -1) index = 0;
1432             label[index] = '\0';
1433
1434             rootmenu->setLabel(label);
1435             defaultMenu = parseMenuFile(menu_file, rootmenu);
1436             if (! defaultMenu)
1437               blackbox->addMenuTimestamp(menu_filename);
1438             break;
1439           }
1440         }
1441       }
1442     }
1443     fclose(menu_file);
1444   }
1445
1446   if (defaultMenu) {
1447     rootmenu->setInternalMenu();
1448     rootmenu->insert(i18n(ScreenSet, Screenxterm, "xterm"),
1449                      BScreen::Execute,
1450                      i18n(ScreenSet, Screenxterm, "xterm"));
1451     rootmenu->insert(i18n(ScreenSet, ScreenRestart, "Restart"),
1452                      BScreen::Restart);
1453     rootmenu->insert(i18n(ScreenSet, ScreenExit, "Exit"),
1454                      BScreen::Exit);
1455     rootmenu->setLabel(i18n(BasemenuSet, BasemenuBlackboxMenu,
1456                             "Openbox Menu"));
1457   }
1458 }
1459
1460
1461 bool BScreen::parseMenuFile(FILE *file, Rootmenu *menu) {
1462   char line[1024], label[1024], command[1024];
1463
1464   while (! feof(file)) {
1465     memset(line, 0, 1024);
1466     memset(label, 0, 1024);
1467     memset(command, 0, 1024);
1468
1469     if (fgets(line, 1024, file)) {
1470       if (line[0] != '#') {
1471         int i, key = 0, parse = 0, index = -1, line_length = strlen(line);
1472
1473         // determine the keyword
1474         for (i = 0; i < line_length; i++) {
1475           if (line[i] == '[') parse = 1;
1476           else if (line[i] == ']') break;
1477           else if (line[i] != ' ')
1478             if (parse)
1479               key += tolower(line[i]);
1480         }
1481
1482         // get the label enclosed in ()'s
1483         parse = 0;
1484
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             label[index - 1] = line[i];
1493           }
1494         }
1495
1496         if (parse) {
1497           label[index] = '\0';
1498         } else {
1499           label[0] = '\0';
1500         }
1501
1502         // get the command enclosed in {}'s
1503         parse = 0;
1504         index = -1;
1505         for (i = 0; i < line_length; i++) {
1506           if (line[i] == '{') {
1507             index = 0;
1508             parse = 1;
1509           } else if (line[i] == '}') break;
1510           else if (index++ >= 0) {
1511             if (line[i] == '\\' && i < line_length - 1) i++;
1512             command[index - 1] = line[i];
1513           }
1514         }
1515
1516         if (parse) {
1517           command[index] = '\0';
1518         } else {
1519           command[0] = '\0';
1520         }
1521
1522         switch (key) {
1523         case 311: // end
1524           return ((menu->getCount() == 0) ? True : False);
1525
1526           break;
1527
1528         case 333: // nop
1529           if (! *label)
1530             label[0] = '\0';
1531           menu->insert(label);
1532
1533           break;
1534
1535         case 421: // exec
1536           if ((! *label) && (! *command)) {
1537             fprintf(stderr, i18n(ScreenSet, ScreenEXECError,
1538                                  "BScreen::parseMenuFile: [exec] error, "
1539                                  "no menu label and/or command defined\n"));
1540             continue;
1541           }
1542
1543           menu->insert(label, BScreen::Execute, command);
1544
1545           break;
1546
1547         case 442: // exit
1548           if (! *label) {
1549             fprintf(stderr, i18n(ScreenSet, ScreenEXITError,
1550                                  "BScreen::parseMenuFile: [exit] error, "
1551                                  "no menu label defined\n"));
1552             continue;
1553           }
1554
1555           menu->insert(label, BScreen::Exit);
1556
1557           break;
1558
1559         case 561: // style
1560           {
1561             if ((! *label) || (! *command)) {
1562               fprintf(stderr,
1563                       i18n(ScreenSet, ScreenSTYLEError,
1564                            "BScreen::parseMenuFile: [style] error, "
1565                            "no menu label and/or filename defined\n"));
1566               continue;
1567             }
1568
1569             string style = expandTilde(command);
1570
1571             menu->insert(label, BScreen::SetStyle, style.c_str());
1572           }
1573
1574           break;
1575
1576         case 630: // config
1577           if (! *label) {
1578             fprintf(stderr, i18n(ScreenSet, ScreenCONFIGError,
1579                                  "BScreen::parseMenufile: [config] error, "
1580                                  "no label defined"));
1581             continue;
1582           }
1583
1584           menu->insert(label, configmenu);
1585
1586           break;
1587
1588         case 740: // include
1589           {
1590             if (! *label) {
1591               fprintf(stderr, i18n(ScreenSet, ScreenINCLUDEError,
1592                                    "BScreen::parseMenuFile: [include] error, "
1593                                    "no filename defined\n"));
1594               continue;
1595             }
1596
1597             string newfile = expandTilde(label);
1598             FILE *submenufile = fopen(newfile.c_str(), "r");
1599
1600             if (submenufile) {
1601               struct stat buf;
1602               if (fstat(fileno(submenufile), &buf) ||
1603                   (! S_ISREG(buf.st_mode))) {
1604                 fprintf(stderr,
1605                         i18n(ScreenSet, ScreenINCLUDEErrorReg,
1606                              "BScreen::parseMenuFile: [include] error: "
1607                              "'%s' is not a regular file\n"), newfile.c_str());
1608                 break;
1609               }
1610
1611               if (! feof(submenufile)) {
1612                 if (! parseMenuFile(submenufile, menu))
1613                   blackbox->addMenuTimestamp(newfile);
1614
1615                 fclose(submenufile);
1616               }
1617             } else {
1618               perror(newfile.c_str());
1619             }
1620           }
1621
1622           break;
1623
1624         case 767: // submenu
1625           {
1626             if (! *label) {
1627               fprintf(stderr, i18n(ScreenSet, ScreenSUBMENUError,
1628                                    "BScreen::parseMenuFile: [submenu] error, "
1629                                    "no menu label defined\n"));
1630               continue;
1631             }
1632
1633             Rootmenu *submenu = new Rootmenu(this);
1634
1635             if (*command)
1636               submenu->setLabel(command);
1637             else
1638               submenu->setLabel(label);
1639
1640             parseMenuFile(file, submenu);
1641             submenu->update();
1642             menu->insert(label, submenu);
1643             rootmenuList.push_back(submenu);
1644           }
1645
1646           break;
1647
1648         case 773: // restart
1649           {
1650             if (! *label) {
1651               fprintf(stderr, i18n(ScreenSet, ScreenRESTARTError,
1652                                    "BScreen::parseMenuFile: [restart] error, "
1653                                    "no menu label defined\n"));
1654               continue;
1655             }
1656
1657             if (*command)
1658               menu->insert(label, BScreen::RestartOther, command);
1659             else
1660               menu->insert(label, BScreen::Restart);
1661           }
1662
1663           break;
1664
1665         case 845: // reconfig
1666           {
1667             if (! *label) {
1668               fprintf(stderr,
1669                       i18n(ScreenSet, ScreenRECONFIGError,
1670                            "BScreen::parseMenuFile: [reconfig] error, "
1671                            "no menu label defined\n"));
1672               continue;
1673             }
1674
1675             menu->insert(label, BScreen::Reconfigure);
1676           }
1677
1678           break;
1679
1680         case 995: // stylesdir
1681         case 1113: // stylesmenu
1682           {
1683             bool newmenu = ((key == 1113) ? True : False);
1684
1685             if ((! *label) || ((! *command) && newmenu)) {
1686               fprintf(stderr,
1687                       i18n(ScreenSet, ScreenSTYLESDIRError,
1688                            "BScreen::parseMenuFile: [stylesdir/stylesmenu]"
1689                            " error, no directory defined\n"));
1690               continue;
1691             }
1692
1693             char *directory = ((newmenu) ? command : label);
1694
1695             string stylesdir = expandTilde(directory);
1696
1697             struct stat statbuf;
1698
1699             if (! stat(stylesdir.c_str(), &statbuf)) {
1700               if (S_ISDIR(statbuf.st_mode)) {
1701                 Rootmenu *stylesmenu;
1702
1703                 if (newmenu)
1704                   stylesmenu = new Rootmenu(this);
1705                 else
1706                   stylesmenu = menu;
1707
1708                 DIR *d = opendir(stylesdir.c_str());
1709                 struct dirent *p;
1710                 std::vector<string> ls;
1711
1712                 while((p = readdir(d)))
1713                   ls.push_back(p->d_name);
1714
1715                 closedir(d);
1716
1717                 std::sort(ls.begin(), ls.end());
1718
1719                 std::vector<string>::iterator it = ls.begin(),
1720                   end = ls.end();
1721                 for (; it != end; ++it) {
1722                   const string& fname = *it;
1723
1724                   if (fname[fname.size()-1] == '~')
1725                     continue;
1726
1727                   string style = stylesdir;
1728                   style += '/';
1729                   style += fname;
1730
1731                   if ((! stat(style.c_str(), &statbuf)) &&
1732                       S_ISREG(statbuf.st_mode))
1733                     stylesmenu->insert(fname, BScreen::SetStyle, style);
1734                 }
1735
1736                 stylesmenu->update();
1737
1738                 if (newmenu) {
1739                   stylesmenu->setLabel(label);
1740                   menu->insert(label, stylesmenu);
1741                   rootmenuList.push_back(stylesmenu);
1742                 }
1743
1744                 blackbox->addMenuTimestamp(stylesdir);
1745               } else {
1746                 fprintf(stderr,
1747                         i18n(ScreenSet, ScreenSTYLESDIRErrorNotDir,
1748                              "BScreen::parseMenuFile:"
1749                              " [stylesdir/stylesmenu] error, %s is not a"
1750                              " directory\n"), stylesdir.c_str());
1751               }
1752             } else {
1753               fprintf(stderr,
1754                       i18n(ScreenSet, ScreenSTYLESDIRErrorNoExist,
1755                            "BScreen::parseMenuFile: [stylesdir/stylesmenu]"
1756                            " error, %s does not exist\n"), stylesdir.c_str());
1757             }
1758             break;
1759           }
1760
1761         case 1090: // workspaces
1762           {
1763             if (! *label) {
1764               fprintf(stderr,
1765                       i18n(ScreenSet, ScreenWORKSPACESError,
1766                            "BScreen:parseMenuFile: [workspaces] error, "
1767                            "no menu label defined\n"));
1768               continue;
1769             }
1770
1771             menu->insert(label, workspacemenu);
1772
1773             break;
1774           }
1775         }
1776       }
1777     }
1778   }
1779
1780   return ((menu->getCount() == 0) ? True : False);
1781 }
1782
1783
1784 void BScreen::shutdown(void) {
1785   XSelectInput(blackbox->getXDisplay(), getRootWindow(), NoEventMask);
1786   XSync(blackbox->getXDisplay(), False);
1787
1788   while(! windowList.empty())
1789     unmanageWindow(windowList.front(), True);
1790
1791   slit->shutdown();
1792 }
1793
1794
1795 void BScreen::showPosition(int x, int y) {
1796   if (! geom_visible) {
1797     XMoveResizeWindow(blackbox->getXDisplay(), geom_window,
1798                       (getWidth() - geom_w) / 2,
1799                       (getHeight() - geom_h) / 2, geom_w, geom_h);
1800     XMapWindow(blackbox->getXDisplay(), geom_window);
1801     XRaiseWindow(blackbox->getXDisplay(), geom_window);
1802
1803     geom_visible = True;
1804   }
1805
1806   char label[1024];
1807
1808   sprintf(label, i18n(ScreenSet, ScreenPositionFormat,
1809                       "X: %4d x Y: %4d"), x, y);
1810
1811   XClearWindow(blackbox->getXDisplay(), geom_window);
1812
1813   BPen pen(resource.wstyle.l_text_focus, resource.wstyle.font);
1814   if (i18n.multibyte()) {
1815     XmbDrawString(blackbox->getXDisplay(), geom_window,
1816                   resource.wstyle.fontset, pen.gc(),
1817                   resource.bevel_width, resource.bevel_width -
1818                   resource.wstyle.fontset_extents->max_ink_extent.y,
1819                   label, strlen(label));
1820   } else {
1821     XDrawString(blackbox->getXDisplay(), geom_window,
1822                 pen.gc(), resource.bevel_width,
1823                 resource.wstyle.font->ascent + resource.bevel_width,
1824                 label, strlen(label));
1825   }
1826 }
1827
1828
1829 void BScreen::showGeometry(unsigned int gx, unsigned int gy) {
1830   if (! geom_visible) {
1831     XMoveResizeWindow(blackbox->getXDisplay(), geom_window,
1832                       (getWidth() - geom_w) / 2,
1833                       (getHeight() - geom_h) / 2, geom_w, geom_h);
1834     XMapWindow(blackbox->getXDisplay(), geom_window);
1835     XRaiseWindow(blackbox->getXDisplay(), geom_window);
1836
1837     geom_visible = True;
1838   }
1839
1840   char label[1024];
1841
1842   sprintf(label, i18n(ScreenSet, ScreenGeometryFormat,
1843                       "W: %4d x H: %4d"), gx, gy);
1844
1845   XClearWindow(blackbox->getXDisplay(), geom_window);
1846
1847   BPen pen(resource.wstyle.l_text_focus, resource.wstyle.font);
1848   if (i18n.multibyte()) {
1849     XmbDrawString(blackbox->getXDisplay(), geom_window,
1850                   resource.wstyle.fontset, pen.gc(),
1851                   resource.bevel_width, resource.bevel_width -
1852                   resource.wstyle.fontset_extents->max_ink_extent.y,
1853                   label, strlen(label));
1854   } else {
1855     XDrawString(blackbox->getXDisplay(), geom_window,
1856                 pen.gc(), resource.bevel_width,
1857                 resource.wstyle.font->ascent +
1858                 resource.bevel_width, label, strlen(label));
1859   }
1860 }
1861
1862
1863 void BScreen::hideGeometry(void) {
1864   if (geom_visible) {
1865     XUnmapWindow(blackbox->getXDisplay(), geom_window);
1866     geom_visible = False;
1867   }
1868 }
1869
1870
1871 void BScreen::addStrut(Strut *strut) {
1872   strutList.push_back(strut);
1873 }
1874
1875
1876 void BScreen::removeStrut(Strut *strut) {
1877   strutList.remove(strut);
1878 }
1879
1880
1881 const Rect& BScreen::availableArea(void) const {
1882   if (doFullMax())
1883     return getRect(); // return the full screen
1884   return usableArea;
1885 }
1886
1887
1888 void BScreen::updateAvailableArea(void) {
1889   Rect old_area = usableArea;
1890   usableArea = getRect(); // reset to full screen
1891
1892   /* these values represent offsets from the screen edge
1893    * we look for the biggest offset on each edge and then apply them
1894    * all at once
1895    * do not be confused by the similarity to the names of Rect's members
1896    */
1897   unsigned int current_left = 0, current_right = 0, current_top = 0,
1898     current_bottom = 0;
1899
1900   StrutList::const_iterator it = strutList.begin(), end = strutList.end();
1901
1902   for(; it != end; ++it) {
1903     Strut *strut = *it;
1904     if (strut->left > current_left)
1905       current_left = strut->left;
1906     if (strut->top > current_top)
1907       current_top = strut->top;
1908     if (strut->right > current_right)
1909       current_right = strut->right;
1910     if (strut->bottom > current_bottom)
1911       current_bottom = strut->bottom;
1912   }
1913
1914   usableArea.setPos(current_left, current_top);
1915   usableArea.setSize(usableArea.width() - (current_left + current_right),
1916                      usableArea.height() - (current_top + current_bottom));
1917
1918   if (old_area != usableArea) {
1919     BlackboxWindowList::iterator it = windowList.begin(),
1920       end = windowList.end();
1921     for (; it != end; ++it)
1922       if ((*it)->isMaximized()) (*it)->remaximize();
1923   }
1924 }
1925
1926
1927 Workspace* BScreen::getWorkspace(unsigned int index) {
1928   assert(index < workspacesList.size());
1929   return workspacesList[index];
1930 }
1931
1932
1933 void BScreen::buttonPressEvent(XButtonEvent *xbutton) {
1934   if (xbutton->button == 1) {
1935     if (! isRootColormapInstalled())
1936       image_control->installRootColormap();
1937
1938     if (workspacemenu->isVisible())
1939       workspacemenu->hide();
1940
1941     if (rootmenu->isVisible())
1942       rootmenu->hide();
1943   } else if (xbutton->button == 2) {
1944     int mx = xbutton->x_root - (workspacemenu->getWidth() / 2);
1945     int my = xbutton->y_root - (workspacemenu->getTitleHeight() / 2);
1946
1947     if (mx < 0) mx = 0;
1948     if (my < 0) my = 0;
1949
1950     if (mx + workspacemenu->getWidth() > getWidth())
1951       mx = getWidth() - workspacemenu->getWidth() - getBorderWidth();
1952
1953     if (my + workspacemenu->getHeight() > getHeight())
1954       my = getHeight() - workspacemenu->getHeight() - getBorderWidth();
1955
1956     workspacemenu->move(mx, my);
1957
1958     if (! workspacemenu->isVisible()) {
1959       workspacemenu->removeParent();
1960       workspacemenu->show();
1961     }
1962   } else if (xbutton->button == 3) {
1963     int mx = xbutton->x_root - (rootmenu->getWidth() / 2);
1964     int my = xbutton->y_root - (rootmenu->getTitleHeight() / 2);
1965
1966     if (mx < 0) mx = 0;
1967     if (my < 0) my = 0;
1968
1969     if (mx + rootmenu->getWidth() > getWidth())
1970       mx = getWidth() - rootmenu->getWidth() - getBorderWidth();
1971
1972     if (my + rootmenu->getHeight() > getHeight())
1973       my = getHeight() - rootmenu->getHeight() - getBorderWidth();
1974
1975     rootmenu->move(mx, my);
1976
1977     if (! rootmenu->isVisible()) {
1978       blackbox->checkMenu();
1979       rootmenu->show();
1980     }
1981   // mouse wheel up
1982   } else if (xbutton->button == 4) {
1983     if (getCurrentWorkspaceID() >= getWorkspaceCount() - 1)
1984       changeWorkspaceID(0);
1985     else
1986       changeWorkspaceID(getCurrentWorkspaceID() + 1);
1987   // mouse wheel down
1988   } else if (xbutton->button == 5) {
1989     if (getCurrentWorkspaceID() == 0)
1990       changeWorkspaceID(getWorkspaceCount() - 1);
1991     else
1992       changeWorkspaceID(getCurrentWorkspaceID() - 1);
1993   }
1994 }
1995
1996
1997 void BScreen::toggleFocusModel(FocusModel model) {
1998   if (model == SloppyFocus) {
1999     saveSloppyFocus(True);
2000   } else {
2001     saveSloppyFocus(False);
2002     saveAutoRaise(False);
2003     saveClickRaise(False);
2004   }
2005
2006   updateFocusModel();
2007 }
2008
2009
2010 void BScreen::updateFocusModel()
2011 {
2012   std::for_each(workspacesList.begin(), workspacesList.end(),
2013                 std::mem_fun(&Workspace::updateFocusModel));
2014 }
2015
2016
2017 BTexture BScreen::readDatabaseTexture(const string &rname,
2018                                       const string &default_color,
2019                                       Configuration &style) {
2020   BTexture texture;
2021   string s;
2022
2023   if (style.getValue(rname, s))
2024     texture = BTexture(s);
2025   else
2026     texture.setTexture(BTexture::Solid | BTexture::Flat);
2027
2028   // associate this texture with this screen
2029   texture.setDisplay(getBaseDisplay(), getScreenNumber());
2030   texture.setImageControl(image_control);
2031
2032   if (texture.texture() & BTexture::Solid) {
2033     texture.setColor(readDatabaseColor(rname + ".color",
2034                                        default_color, style));
2035     texture.setColorTo(readDatabaseColor(rname + ".colorTo",
2036                                          default_color, style));
2037   } else if (texture.texture() & BTexture::Gradient) {
2038     texture.setColor(readDatabaseColor(rname + ".color",
2039                                        default_color, style));
2040     texture.setColorTo(readDatabaseColor(rname + ".colorTo",
2041                                          default_color, style));
2042   }
2043
2044   return texture;
2045 }
2046
2047
2048 BColor BScreen::readDatabaseColor(const string &rname,
2049                                   const string &default_color,
2050                                   Configuration &style) {
2051   BColor color;
2052   string s;
2053   if (style.getValue(rname, s))
2054     color = BColor(s, getBaseDisplay(), getScreenNumber());
2055   else
2056     color = BColor(default_color, getBaseDisplay(), getScreenNumber());
2057   return color;
2058 }
2059
2060
2061 XFontSet BScreen::readDatabaseFontSet(const string &rname,
2062                                       Configuration &style) {
2063   char *defaultFont = "fixed";
2064
2065   bool load_default = True;
2066   string s;
2067   XFontSet fontset = 0;
2068   if (style.getValue(rname, s) && (fontset = createFontSet(s)))
2069     load_default = False;
2070
2071   if (load_default) {
2072     fontset = createFontSet(defaultFont);
2073
2074     if (! fontset) {
2075       fprintf(stderr,
2076               i18n(ScreenSet, ScreenDefaultFontLoadFail,
2077                    "BScreen::setCurrentStyle(): couldn't load default font.\n"));
2078       exit(2);
2079     }
2080   }
2081
2082   return fontset;
2083 }
2084
2085
2086 XFontStruct *BScreen::readDatabaseFont(const string &rname,
2087                                        Configuration &style) {
2088   char *defaultFont = "fixed";
2089
2090   bool load_default = False;
2091   string s;
2092   XFontStruct *font = 0;
2093   if (style.getValue(rname, s)) {
2094     if ((font = XLoadQueryFont(blackbox->getXDisplay(), s.c_str())) == NULL) {
2095       fprintf(stderr,
2096               i18n(ScreenSet, ScreenFontLoadFail,
2097                    "BScreen::setCurrentStyle(): couldn't load font '%s'\n"),
2098               s.c_str());
2099
2100       load_default = True;
2101     }
2102   } else {
2103     load_default = True;
2104   }
2105
2106   if (load_default) {
2107     font = XLoadQueryFont(blackbox->getXDisplay(), defaultFont);
2108     if (font == NULL) {
2109       fprintf(stderr,
2110               i18n(ScreenSet, ScreenDefaultFontLoadFail,
2111                    "BScreen::setCurrentStyle(): couldn't load default font.\n"));
2112       exit(2);
2113     }
2114   }
2115
2116   return font;
2117 }
2118
2119
2120 #ifndef    HAVE_STRCASESTR
2121 static const char * strcasestr(const char *str, const char *ptn) {
2122   const char *s2, *p2;
2123   for(; *str; str++) {
2124     for(s2=str,p2=ptn; ; s2++,p2++) {
2125       if (! *p2) return str;
2126       if (toupper(*s2) != toupper(*p2)) break;
2127     }
2128   }
2129   return NULL;
2130 }
2131 #endif // HAVE_STRCASESTR
2132
2133
2134 static const char *getFontElement(const char *pattern, char *buf,
2135                                   int bufsiz, ...) {
2136   const char *p, *v;
2137   char *p2;
2138   va_list va;
2139
2140   va_start(va, bufsiz);
2141   buf[bufsiz-1] = 0;
2142   buf[bufsiz-2] = '*';
2143   while((v = va_arg(va, char *)) != NULL) {
2144     p = strcasestr(pattern, v);
2145     if (p) {
2146       strncpy(buf, p+1, bufsiz-2);
2147       p2 = strchr(buf, '-');
2148       if (p2) *p2=0;
2149       va_end(va);
2150       return p;
2151     }
2152   }
2153   va_end(va);
2154   strncpy(buf, "*", bufsiz);
2155   return NULL;
2156 }
2157
2158
2159 static const char *getFontSize(const char *pattern, int *size) {
2160   const char *p;
2161   const char *p2=NULL;
2162   int n=0;
2163
2164   for (p=pattern; 1; p++) {
2165     if (! *p) {
2166       if (p2!=NULL && n>1 && n<72) {
2167         *size = n; return p2+1;
2168       } else {
2169         *size = 16; return NULL;
2170       }
2171     } else if (*p=='-') {
2172       if (n>1 && n<72 && p2!=NULL) {
2173         *size = n;
2174         return p2+1;
2175       }
2176       p2=p; n=0;
2177     } else if (*p>='0' && *p<='9' && p2!=NULL) {
2178       n *= 10;
2179       n += *p-'0';
2180     } else {
2181       p2=NULL; n=0;
2182     }
2183   }
2184 }
2185
2186
2187 XFontSet BScreen::createFontSet(const string &fontname) {
2188   XFontSet fs;
2189   char **missing, *def = "-";
2190   int nmissing, pixel_size = 0, buf_size = 0;
2191   char weight[FONT_ELEMENT_SIZE], slant[FONT_ELEMENT_SIZE];
2192
2193   fs = XCreateFontSet(blackbox->getXDisplay(),
2194                       fontname.c_str(), &missing, &nmissing, &def);
2195   if (fs && (! nmissing))
2196     return fs;
2197
2198   const char *nfontname = fontname.c_str();
2199 #ifdef    HAVE_SETLOCALE
2200   if (! fs) {
2201     if (nmissing) XFreeStringList(missing);
2202
2203     setlocale(LC_CTYPE, "C");
2204     fs = XCreateFontSet(blackbox->getXDisplay(), fontname.c_str(),
2205                         &missing, &nmissing, &def);
2206     setlocale(LC_CTYPE, "");
2207   }
2208 #endif // HAVE_SETLOCALE
2209
2210   if (fs) {
2211     XFontStruct **fontstructs;
2212     char **fontnames;
2213     XFontsOfFontSet(fs, &fontstructs, &fontnames);
2214     nfontname = fontnames[0];
2215   }
2216
2217   getFontElement(nfontname, weight, FONT_ELEMENT_SIZE,
2218                  "-medium-", "-bold-", "-demibold-", "-regular-", NULL);
2219   getFontElement(nfontname, slant, FONT_ELEMENT_SIZE,
2220                  "-r-", "-i-", "-o-", "-ri-", "-ro-", NULL);
2221   getFontSize(nfontname, &pixel_size);
2222
2223   if (! strcmp(weight, "*"))
2224     strncpy(weight, "medium", FONT_ELEMENT_SIZE);
2225   if (! strcmp(slant, "*"))
2226     strncpy(slant, "r", FONT_ELEMENT_SIZE);
2227   if (pixel_size < 3)
2228     pixel_size = 3;
2229   else if (pixel_size > 97)
2230     pixel_size = 97;
2231
2232   buf_size = strlen(nfontname) + (FONT_ELEMENT_SIZE * 2) + 64;
2233   char *pattern2 = new char[buf_size];
2234   sprintf(pattern2,
2235            "%s,"
2236            "-*-*-%s-%s-*-*-%d-*-*-*-*-*-*-*,"
2237            "-*-*-*-*-*-*-%d-*-*-*-*-*-*-*,*",
2238            nfontname, weight, slant, pixel_size, pixel_size);
2239   nfontname = pattern2;
2240
2241   if (nmissing)
2242     XFreeStringList(missing);
2243   if (fs)
2244     XFreeFontSet(blackbox->getXDisplay(), fs);
2245
2246   fs = XCreateFontSet(blackbox->getXDisplay(), nfontname, &missing,
2247                       &nmissing, &def);
2248
2249   delete [] pattern2;
2250
2251   return fs;
2252 }