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