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