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