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