]> icculus.org git repositories - mikachu/openbox.git/blob - src/Screen.cc
fix off-by-ones in window-to-window snapping. move the property from the blackbox...
[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::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())
1111     win->restoreAttributes();
1112   win->mapRequestEvent(&mre);
1113 }
1114
1115
1116 void BScreen::unmanageWindow(BlackboxWindow *w, bool remap) {
1117   w->restore(remap);
1118
1119   if (w->getWorkspaceNumber() != BSENTINEL &&
1120       w->getWindowNumber() != BSENTINEL)
1121     getWorkspace(w->getWorkspaceNumber())->removeWindow(w);
1122   else if (w->isIconic())
1123     removeIcon(w);
1124
1125   windowList.remove(w);
1126
1127   if (blackbox->getFocusedWindow() == w)
1128     blackbox->setFocusedWindow((BlackboxWindow *) 0);
1129
1130   removeNetizen(w->getClientWindow());
1131
1132   /*
1133     some managed windows can also be window group controllers.  when
1134     unmanaging such windows, we should also delete the window group.
1135   */
1136   BWindowGroup *group = blackbox->searchGroup(w->getClientWindow());
1137   delete group;
1138
1139   delete w;
1140 }
1141
1142
1143 void BScreen::addNetizen(Netizen *n) {
1144   netizenList.push_back(n);
1145
1146   n->sendWorkspaceCount();
1147   n->sendCurrentWorkspace();
1148
1149   WorkspaceList::iterator it = workspacesList.begin();
1150   const WorkspaceList::iterator end = workspacesList.end();
1151   for (; it != end; ++it)
1152     (*it)->sendWindowList(*n);
1153
1154   Window f = ((blackbox->getFocusedWindow()) ?
1155               blackbox->getFocusedWindow()->getClientWindow() : None);
1156   n->sendWindowFocus(f);
1157 }
1158
1159
1160 void BScreen::removeNetizen(Window w) {
1161   NetizenList::iterator it = netizenList.begin();
1162   for (; it != netizenList.end(); ++it) {
1163     if ((*it)->getWindowID() == w) {
1164       delete *it;
1165       netizenList.erase(it);
1166       break;
1167     }
1168   }
1169 }
1170
1171
1172 void BScreen::updateNetizenCurrentWorkspace(void) {
1173   std::for_each(netizenList.begin(), netizenList.end(),
1174                 std::mem_fun(&Netizen::sendCurrentWorkspace));
1175 }
1176
1177
1178 void BScreen::updateNetizenWorkspaceCount(void) {
1179   xatom->setValue(getRootWindow(), XAtom::net_number_of_desktops,
1180                   XAtom::cardinal, workspacesList.size());
1181
1182   std::for_each(netizenList.begin(), netizenList.end(),
1183                 std::mem_fun(&Netizen::sendWorkspaceCount));
1184 }
1185
1186
1187 void BScreen::updateNetizenWindowFocus(void) {
1188   Window f = ((blackbox->getFocusedWindow()) ?
1189               blackbox->getFocusedWindow()->getClientWindow() : None);
1190   NetizenList::iterator it = netizenList.begin();
1191   for (; it != netizenList.end(); ++it)
1192     (*it)->sendWindowFocus(f);
1193 }
1194
1195
1196 void BScreen::updateNetizenWindowAdd(Window w, unsigned long p) {
1197   NetizenList::iterator it = netizenList.begin();
1198   for (; it != netizenList.end(); ++it) {
1199     (*it)->sendWindowAdd(w, p);
1200   }
1201 }
1202
1203
1204 void BScreen::updateNetizenWindowDel(Window w) {
1205   NetizenList::iterator it = netizenList.begin();
1206   for (; it != netizenList.end(); ++it)
1207     (*it)->sendWindowDel(w);
1208 }
1209
1210
1211 void BScreen::updateNetizenWindowRaise(Window w) {
1212   NetizenList::iterator it = netizenList.begin();
1213   for (; it != netizenList.end(); ++it)
1214     (*it)->sendWindowRaise(w);
1215 }
1216
1217
1218 void BScreen::updateNetizenWindowLower(Window w) {
1219   NetizenList::iterator it = netizenList.begin();
1220   for (; it != netizenList.end(); ++it)
1221     (*it)->sendWindowLower(w);
1222 }
1223
1224
1225 void BScreen::updateNetizenConfigNotify(XEvent *e) {
1226   NetizenList::iterator it = netizenList.begin();
1227   for (; it != netizenList.end(); ++it)
1228     (*it)->sendConfigNotify(e);
1229 }
1230
1231
1232 void BScreen::raiseWindows(Window *workspace_stack, unsigned int num) {
1233   // XXX: why 13??
1234   Window *session_stack = new
1235     Window[(num + workspacesList.size() + rootmenuList.size() + 13)];
1236   unsigned int i = 0, k = num;
1237
1238   XRaiseWindow(blackbox->getXDisplay(), iconmenu->getWindowID());
1239   *(session_stack + i++) = iconmenu->getWindowID();
1240
1241   WorkspaceList::iterator wit = workspacesList.begin();
1242   const WorkspaceList::iterator w_end = workspacesList.end();
1243   for (; wit != w_end; ++wit)
1244     *(session_stack + i++) = (*wit)->getMenu()->getWindowID();
1245
1246   *(session_stack + i++) = workspacemenu->getWindowID();
1247
1248   *(session_stack + i++) = configmenu->getFocusmenu()->getWindowID();
1249   *(session_stack + i++) = configmenu->getPlacementmenu()->getWindowID();
1250   *(session_stack + i++) = configmenu->getWindowID();
1251
1252   *(session_stack + i++) = slit->getMenu()->getDirectionmenu()->getWindowID();
1253   *(session_stack + i++) = slit->getMenu()->getPlacementmenu()->getWindowID();
1254   *(session_stack + i++) = slit->getMenu()->getWindowID();
1255
1256   *(session_stack + i++) =
1257     toolbar->getMenu()->getPlacementmenu()->getWindowID();
1258   *(session_stack + i++) = toolbar->getMenu()->getWindowID();
1259
1260   RootmenuList::iterator rit = rootmenuList.begin();
1261   for (; rit != rootmenuList.end(); ++rit)
1262     *(session_stack + i++) = (*rit)->getWindowID();
1263   *(session_stack + i++) = rootmenu->getWindowID();
1264
1265   if (toolbar->isOnTop())
1266     *(session_stack + i++) = toolbar->getWindowID();
1267
1268   if (slit->isOnTop())
1269     *(session_stack + i++) = slit->getWindowID();
1270
1271   while (k--)
1272     *(session_stack + i++) = *(workspace_stack + k);
1273
1274   XRestackWindows(blackbox->getXDisplay(), session_stack, i);
1275
1276   delete [] session_stack;
1277 }
1278
1279
1280 void BScreen::addWorkspaceName(const string& name) {
1281   workspaceNames.push_back(name);
1282 }
1283
1284
1285 /*
1286  * I would love to kill this function and the accompanying workspaceNames
1287  * list.  However, we have a chicken and egg situation.  The names are read
1288  * in during load_rc() which happens before the workspaces are created.
1289  * The current solution is to read the names into a list, then use the list
1290  * later for constructing the workspaces.  It is only used during initial
1291  * BScreen creation.
1292  */
1293 const string BScreen::getNameOfWorkspace(unsigned int id) {
1294   if (id < workspaceNames.size())
1295     return workspaceNames[id];
1296   return string("");
1297 }
1298
1299
1300 void BScreen::reassociateWindow(BlackboxWindow *w, unsigned int wkspc_id,
1301                                 bool ignore_sticky) {
1302   if (! w) return;
1303
1304   if (wkspc_id == BSENTINEL)
1305     wkspc_id = current_workspace->getID();
1306
1307   if (w->getWorkspaceNumber() == wkspc_id)
1308     return;
1309
1310   if (w->isIconic()) {
1311     removeIcon(w);
1312     getWorkspace(wkspc_id)->addWindow(w);
1313   } else if (ignore_sticky || ! w->isStuck()) {
1314     getWorkspace(w->getWorkspaceNumber())->removeWindow(w);
1315     getWorkspace(wkspc_id)->addWindow(w);
1316   }
1317 }
1318
1319
1320 void BScreen::propagateWindowName(const BlackboxWindow *bw) {
1321   if (bw->isIconic()) {
1322     iconmenu->changeItemLabel(bw->getWindowNumber(), bw->getIconTitle());
1323     iconmenu->update();
1324   }
1325   else {
1326     Clientmenu *clientmenu = getWorkspace(bw->getWorkspaceNumber())->getMenu();
1327     clientmenu->changeItemLabel(bw->getWindowNumber(), bw->getTitle());
1328     clientmenu->update();
1329
1330     if (blackbox->getFocusedWindow() == bw)
1331       toolbar->redrawWindowLabel(True);
1332   }
1333 }
1334
1335
1336 void BScreen::nextFocus(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->getNextWindowInList(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::prevFocus(void) {
1366   BlackboxWindow *focused = blackbox->getFocusedWindow(),
1367     *next = focused;
1368
1369   if (focused) {
1370     // if window is not on this screen, ignore it
1371     if (focused->getScreen()->getScreenNumber() != getScreenNumber())
1372       focused = (BlackboxWindow*) 0;
1373   }
1374
1375   if (focused && current_workspace->getCount() > 1) {
1376     // next is the next window to recieve focus, current is a place holder
1377     BlackboxWindow *current;
1378     do {
1379       current = next;
1380       next = current_workspace->getPrevWindowInList(current);
1381     } while(! next->setInputFocus() && next != focused);
1382
1383     if (next != focused)
1384       current_workspace->raiseWindow(next);
1385   } else if (current_workspace->getCount() >= 1) {
1386     next = current_workspace->getTopWindowOnStack();
1387
1388     current_workspace->raiseWindow(next);
1389     next->setInputFocus();
1390   }
1391 }
1392
1393
1394 void BScreen::raiseFocus(void) {
1395   BlackboxWindow *focused = blackbox->getFocusedWindow();
1396   if (! focused)
1397     return;
1398
1399   // if on this Screen, raise it
1400   if (focused->getScreen()->getScreenNumber() == getScreenNumber()) {
1401     Workspace *workspace = getWorkspace(focused->getWorkspaceNumber());
1402     workspace->raiseWindow(focused);
1403   }
1404 }
1405
1406
1407 void BScreen::InitMenu(void) {
1408   if (rootmenu) {
1409     rootmenuList.clear();
1410
1411     while (rootmenu->getCount())
1412       rootmenu->remove(0);
1413   } else {
1414     rootmenu = new Rootmenu(this);
1415   }
1416   bool defaultMenu = True;
1417
1418   FILE *menu_file = (FILE *) 0;
1419   const char *menu_filename = blackbox->getMenuFilename();
1420
1421   if (menu_filename) 
1422     if (! (menu_file = fopen(menu_filename, "r")))
1423       perror(menu_filename);
1424   if (! menu_file) {     // opening the menu file failed, try the default menu
1425     menu_filename = DEFAULTMENU;
1426     if (! (menu_file = fopen(menu_filename, "r")))
1427       perror(menu_filename);
1428   } 
1429
1430   if (menu_file) {
1431     if (feof(menu_file)) {
1432       fprintf(stderr, i18n(ScreenSet, ScreenEmptyMenuFile,
1433                            "%s: Empty menu file"),
1434               menu_filename);
1435     } else {
1436       char line[1024], label[1024];
1437       memset(line, 0, 1024);
1438       memset(label, 0, 1024);
1439
1440       while (fgets(line, 1024, menu_file) && ! feof(menu_file)) {
1441         if (line[0] != '#') {
1442           int i, key = 0, index = -1, len = strlen(line);
1443
1444           for (i = 0; i < len; i++) {
1445             if (line[i] == '[') index = 0;
1446             else if (line[i] == ']') break;
1447             else if (line[i] != ' ')
1448               if (index++ >= 0)
1449                 key += tolower(line[i]);
1450           }
1451
1452           if (key == 517) { // [begin]
1453             index = -1;
1454             for (i = index; i < len; i++) {
1455               if (line[i] == '(') index = 0;
1456               else if (line[i] == ')') break;
1457               else if (index++ >= 0) {
1458                 if (line[i] == '\\' && i < len - 1) i++;
1459                 label[index - 1] = line[i];
1460               }
1461             }
1462
1463             if (index == -1) index = 0;
1464             label[index] = '\0';
1465
1466             rootmenu->setLabel(label);
1467             defaultMenu = parseMenuFile(menu_file, rootmenu);
1468             if (! defaultMenu)
1469               blackbox->addMenuTimestamp(menu_filename);
1470             break;
1471           }
1472         }
1473       }
1474     }
1475     fclose(menu_file);
1476   }
1477
1478   if (defaultMenu) {
1479     rootmenu->setInternalMenu();
1480     rootmenu->insert(i18n(ScreenSet, Screenxterm, "xterm"),
1481                      BScreen::Execute,
1482                      i18n(ScreenSet, Screenxterm, "xterm"));
1483     rootmenu->insert(i18n(ScreenSet, ScreenRestart, "Restart"),
1484                      BScreen::Restart);
1485     rootmenu->insert(i18n(ScreenSet, ScreenExit, "Exit"),
1486                      BScreen::Exit);
1487     rootmenu->setLabel(i18n(BasemenuSet, BasemenuBlackboxMenu,
1488                             "Openbox Menu"));
1489   }
1490 }
1491
1492
1493 bool BScreen::parseMenuFile(FILE *file, Rootmenu *menu) {
1494   char line[1024], label[1024], command[1024];
1495
1496   while (! feof(file)) {
1497     memset(line, 0, 1024);
1498     memset(label, 0, 1024);
1499     memset(command, 0, 1024);
1500
1501     if (fgets(line, 1024, file)) {
1502       if (line[0] != '#') {
1503         int i, key = 0, parse = 0, index = -1, line_length = strlen(line);
1504
1505         // determine the keyword
1506         for (i = 0; i < line_length; i++) {
1507           if (line[i] == '[') parse = 1;
1508           else if (line[i] == ']') break;
1509           else if (line[i] != ' ')
1510             if (parse)
1511               key += tolower(line[i]);
1512         }
1513
1514         // get the label enclosed in ()'s
1515         parse = 0;
1516
1517         for (i = 0; i < line_length; i++) {
1518           if (line[i] == '(') {
1519             index = 0;
1520             parse = 1;
1521           } else if (line[i] == ')') break;
1522           else if (index++ >= 0) {
1523             if (line[i] == '\\' && i < line_length - 1) i++;
1524             label[index - 1] = line[i];
1525           }
1526         }
1527
1528         if (parse) {
1529           label[index] = '\0';
1530         } else {
1531           label[0] = '\0';
1532         }
1533
1534         // get the command enclosed in {}'s
1535         parse = 0;
1536         index = -1;
1537         for (i = 0; i < line_length; i++) {
1538           if (line[i] == '{') {
1539             index = 0;
1540             parse = 1;
1541           } else if (line[i] == '}') break;
1542           else if (index++ >= 0) {
1543             if (line[i] == '\\' && i < line_length - 1) i++;
1544             command[index - 1] = line[i];
1545           }
1546         }
1547
1548         if (parse) {
1549           command[index] = '\0';
1550         } else {
1551           command[0] = '\0';
1552         }
1553
1554         switch (key) {
1555         case 311: // end
1556           return ((menu->getCount() == 0) ? True : False);
1557
1558           break;
1559
1560         case 333: // nop
1561           if (! *label)
1562             label[0] = '\0';
1563           menu->insert(label);
1564
1565           break;
1566
1567         case 421: // exec
1568           if ((! *label) && (! *command)) {
1569             fprintf(stderr, i18n(ScreenSet, ScreenEXECError,
1570                                  "BScreen::parseMenuFile: [exec] error, "
1571                                  "no menu label and/or command defined\n"));
1572             continue;
1573           }
1574
1575           menu->insert(label, BScreen::Execute, command);
1576
1577           break;
1578
1579         case 442: // exit
1580           if (! *label) {
1581             fprintf(stderr, i18n(ScreenSet, ScreenEXITError,
1582                                  "BScreen::parseMenuFile: [exit] error, "
1583                                  "no menu label defined\n"));
1584             continue;
1585           }
1586
1587           menu->insert(label, BScreen::Exit);
1588
1589           break;
1590
1591         case 561: // style
1592           {
1593             if ((! *label) || (! *command)) {
1594               fprintf(stderr,
1595                       i18n(ScreenSet, ScreenSTYLEError,
1596                            "BScreen::parseMenuFile: [style] error, "
1597                            "no menu label and/or filename defined\n"));
1598               continue;
1599             }
1600
1601             string style = expandTilde(command);
1602
1603             menu->insert(label, BScreen::SetStyle, style.c_str());
1604           }
1605
1606           break;
1607
1608         case 630: // config
1609           if (! *label) {
1610             fprintf(stderr, i18n(ScreenSet, ScreenCONFIGError,
1611                                  "BScreen::parseMenufile: [config] error, "
1612                                  "no label defined"));
1613             continue;
1614           }
1615
1616           menu->insert(label, configmenu);
1617
1618           break;
1619
1620         case 740: // include
1621           {
1622             if (! *label) {
1623               fprintf(stderr, i18n(ScreenSet, ScreenINCLUDEError,
1624                                    "BScreen::parseMenuFile: [include] error, "
1625                                    "no filename defined\n"));
1626               continue;
1627             }
1628
1629             string newfile = expandTilde(label);
1630             FILE *submenufile = fopen(newfile.c_str(), "r");
1631
1632             if (submenufile) {
1633               struct stat buf;
1634               if (fstat(fileno(submenufile), &buf) ||
1635                   (! S_ISREG(buf.st_mode))) {
1636                 fprintf(stderr,
1637                         i18n(ScreenSet, ScreenINCLUDEErrorReg,
1638                              "BScreen::parseMenuFile: [include] error: "
1639                              "'%s' is not a regular file\n"), newfile.c_str());
1640                 break;
1641               }
1642
1643               if (! feof(submenufile)) {
1644                 if (! parseMenuFile(submenufile, menu))
1645                   blackbox->addMenuTimestamp(newfile);
1646
1647                 fclose(submenufile);
1648               }
1649             } else {
1650               perror(newfile.c_str());
1651             }
1652           }
1653
1654           break;
1655
1656         case 767: // submenu
1657           {
1658             if (! *label) {
1659               fprintf(stderr, i18n(ScreenSet, ScreenSUBMENUError,
1660                                    "BScreen::parseMenuFile: [submenu] error, "
1661                                    "no menu label defined\n"));
1662               continue;
1663             }
1664
1665             Rootmenu *submenu = new Rootmenu(this);
1666
1667             if (*command)
1668               submenu->setLabel(command);
1669             else
1670               submenu->setLabel(label);
1671
1672             parseMenuFile(file, submenu);
1673             submenu->update();
1674             menu->insert(label, submenu);
1675             rootmenuList.push_back(submenu);
1676           }
1677
1678           break;
1679
1680         case 773: // restart
1681           {
1682             if (! *label) {
1683               fprintf(stderr, i18n(ScreenSet, ScreenRESTARTError,
1684                                    "BScreen::parseMenuFile: [restart] error, "
1685                                    "no menu label defined\n"));
1686               continue;
1687             }
1688
1689             if (*command)
1690               menu->insert(label, BScreen::RestartOther, command);
1691             else
1692               menu->insert(label, BScreen::Restart);
1693           }
1694
1695           break;
1696
1697         case 845: // reconfig
1698           {
1699             if (! *label) {
1700               fprintf(stderr,
1701                       i18n(ScreenSet, ScreenRECONFIGError,
1702                            "BScreen::parseMenuFile: [reconfig] error, "
1703                            "no menu label defined\n"));
1704               continue;
1705             }
1706
1707             menu->insert(label, BScreen::Reconfigure);
1708           }
1709
1710           break;
1711
1712         case 995: // stylesdir
1713         case 1113: // stylesmenu
1714           {
1715             bool newmenu = ((key == 1113) ? True : False);
1716
1717             if ((! *label) || ((! *command) && newmenu)) {
1718               fprintf(stderr,
1719                       i18n(ScreenSet, ScreenSTYLESDIRError,
1720                            "BScreen::parseMenuFile: [stylesdir/stylesmenu]"
1721                            " error, no directory defined\n"));
1722               continue;
1723             }
1724
1725             char *directory = ((newmenu) ? command : label);
1726
1727             string stylesdir = expandTilde(directory);
1728
1729             struct stat statbuf;
1730
1731             if (! stat(stylesdir.c_str(), &statbuf)) {
1732               if (S_ISDIR(statbuf.st_mode)) {
1733                 Rootmenu *stylesmenu;
1734
1735                 if (newmenu)
1736                   stylesmenu = new Rootmenu(this);
1737                 else
1738                   stylesmenu = menu;
1739
1740                 DIR *d = opendir(stylesdir.c_str());
1741                 struct dirent *p;
1742                 std::vector<string> ls;
1743
1744                 while((p = readdir(d)))
1745                   ls.push_back(p->d_name);
1746
1747                 closedir(d);
1748
1749                 std::sort(ls.begin(), ls.end());
1750
1751                 std::vector<string>::iterator it = ls.begin(),
1752                   end = ls.end();
1753                 for (; it != end; ++it) {
1754                   const string& fname = *it;
1755
1756                   if (fname[fname.size()-1] == '~')
1757                     continue;
1758
1759                   string style = stylesdir;
1760                   style += '/';
1761                   style += fname;
1762
1763                   if ((! stat(style.c_str(), &statbuf)) &&
1764                       S_ISREG(statbuf.st_mode))
1765                     stylesmenu->insert(fname, BScreen::SetStyle, style);
1766                 }
1767
1768                 stylesmenu->update();
1769
1770                 if (newmenu) {
1771                   stylesmenu->setLabel(label);
1772                   menu->insert(label, stylesmenu);
1773                   rootmenuList.push_back(stylesmenu);
1774                 }
1775
1776                 blackbox->addMenuTimestamp(stylesdir);
1777               } else {
1778                 fprintf(stderr,
1779                         i18n(ScreenSet, ScreenSTYLESDIRErrorNotDir,
1780                              "BScreen::parseMenuFile:"
1781                              " [stylesdir/stylesmenu] error, %s is not a"
1782                              " directory\n"), stylesdir.c_str());
1783               }
1784             } else {
1785               fprintf(stderr,
1786                       i18n(ScreenSet, ScreenSTYLESDIRErrorNoExist,
1787                            "BScreen::parseMenuFile: [stylesdir/stylesmenu]"
1788                            " error, %s does not exist\n"), stylesdir.c_str());
1789             }
1790             break;
1791           }
1792
1793         case 1090: // workspaces
1794           {
1795             if (! *label) {
1796               fprintf(stderr,
1797                       i18n(ScreenSet, ScreenWORKSPACESError,
1798                            "BScreen:parseMenuFile: [workspaces] error, "
1799                            "no menu label defined\n"));
1800               continue;
1801             }
1802
1803             menu->insert(label, workspacemenu);
1804
1805             break;
1806           }
1807         }
1808       }
1809     }
1810   }
1811
1812   return ((menu->getCount() == 0) ? True : False);
1813 }
1814
1815
1816 void BScreen::shutdown(void) {
1817   XSelectInput(blackbox->getXDisplay(), getRootWindow(), NoEventMask);
1818   XSync(blackbox->getXDisplay(), False);
1819
1820   while(! windowList.empty())
1821     unmanageWindow(windowList.front(), True);
1822
1823   slit->shutdown();
1824 }
1825
1826
1827 void BScreen::showPosition(int x, int y) {
1828   if (! geom_visible) {
1829     XMoveResizeWindow(blackbox->getXDisplay(), geom_window,
1830                       (getWidth() - geom_w) / 2,
1831                       (getHeight() - geom_h) / 2, geom_w, geom_h);
1832     XMapWindow(blackbox->getXDisplay(), geom_window);
1833     XRaiseWindow(blackbox->getXDisplay(), geom_window);
1834
1835     geom_visible = True;
1836   }
1837
1838   char label[1024];
1839
1840   sprintf(label, i18n(ScreenSet, ScreenPositionFormat,
1841                       "X: %4d x Y: %4d"), x, y);
1842
1843   XClearWindow(blackbox->getXDisplay(), geom_window);
1844
1845   BPen pen(resource.wstyle.l_text_focus, resource.wstyle.font);
1846   if (i18n.multibyte()) {
1847     XmbDrawString(blackbox->getXDisplay(), geom_window,
1848                   resource.wstyle.fontset, pen.gc(),
1849                   resource.bevel_width, resource.bevel_width -
1850                   resource.wstyle.fontset_extents->max_ink_extent.y,
1851                   label, strlen(label));
1852   } else {
1853     XDrawString(blackbox->getXDisplay(), geom_window,
1854                 pen.gc(), resource.bevel_width,
1855                 resource.wstyle.font->ascent + resource.bevel_width,
1856                 label, strlen(label));
1857   }
1858 }
1859
1860
1861 void BScreen::showGeometry(unsigned int gx, unsigned int gy) {
1862   if (! geom_visible) {
1863     XMoveResizeWindow(blackbox->getXDisplay(), geom_window,
1864                       (getWidth() - geom_w) / 2,
1865                       (getHeight() - geom_h) / 2, geom_w, geom_h);
1866     XMapWindow(blackbox->getXDisplay(), geom_window);
1867     XRaiseWindow(blackbox->getXDisplay(), geom_window);
1868
1869     geom_visible = True;
1870   }
1871
1872   char label[1024];
1873
1874   sprintf(label, i18n(ScreenSet, ScreenGeometryFormat,
1875                       "W: %4d x H: %4d"), gx, gy);
1876
1877   XClearWindow(blackbox->getXDisplay(), geom_window);
1878
1879   BPen pen(resource.wstyle.l_text_focus, resource.wstyle.font);
1880   if (i18n.multibyte()) {
1881     XmbDrawString(blackbox->getXDisplay(), geom_window,
1882                   resource.wstyle.fontset, pen.gc(),
1883                   resource.bevel_width, resource.bevel_width -
1884                   resource.wstyle.fontset_extents->max_ink_extent.y,
1885                   label, strlen(label));
1886   } else {
1887     XDrawString(blackbox->getXDisplay(), geom_window,
1888                 pen.gc(), resource.bevel_width,
1889                 resource.wstyle.font->ascent +
1890                 resource.bevel_width, label, strlen(label));
1891   }
1892 }
1893
1894
1895 void BScreen::hideGeometry(void) {
1896   if (geom_visible) {
1897     XUnmapWindow(blackbox->getXDisplay(), geom_window);
1898     geom_visible = False;
1899   }
1900 }
1901
1902
1903 void BScreen::addStrut(Strut *strut) {
1904   strutList.push_back(strut);
1905 }
1906
1907
1908 void BScreen::removeStrut(Strut *strut) {
1909   strutList.remove(strut);
1910 }
1911
1912
1913 const Rect& BScreen::availableArea(void) const {
1914   if (doFullMax())
1915     return getRect(); // return the full screen
1916   return usableArea;
1917 }
1918
1919
1920 void BScreen::updateAvailableArea(void) {
1921   Rect old_area = usableArea;
1922   usableArea = getRect(); // reset to full screen
1923
1924   /* these values represent offsets from the screen edge
1925    * we look for the biggest offset on each edge and then apply them
1926    * all at once
1927    * do not be confused by the similarity to the names of Rect's members
1928    */
1929   unsigned int current_left = 0, current_right = 0, current_top = 0,
1930     current_bottom = 0;
1931
1932   StrutList::const_iterator it = strutList.begin(), end = strutList.end();
1933
1934   for(; it != end; ++it) {
1935     Strut *strut = *it;
1936     if (strut->left > current_left)
1937       current_left = strut->left;
1938     if (strut->top > current_top)
1939       current_top = strut->top;
1940     if (strut->right > current_right)
1941       current_right = strut->right;
1942     if (strut->bottom > current_bottom)
1943       current_bottom = strut->bottom;
1944   }
1945
1946   usableArea.setPos(current_left, current_top);
1947   usableArea.setSize(usableArea.width() - (current_left + current_right),
1948                      usableArea.height() - (current_top + current_bottom));
1949
1950   if (old_area != usableArea) {
1951     BlackboxWindowList::iterator it = windowList.begin(),
1952       end = windowList.end();
1953     for (; it != end; ++it)
1954       if ((*it)->isMaximized()) (*it)->remaximize();
1955   }
1956 }
1957
1958
1959 Workspace* BScreen::getWorkspace(unsigned int index) {
1960   assert(index < workspacesList.size());
1961   return workspacesList[index];
1962 }
1963
1964
1965 void BScreen::buttonPressEvent(XButtonEvent *xbutton) {
1966   if (xbutton->button == 1) {
1967     if (! isRootColormapInstalled())
1968       image_control->installRootColormap();
1969
1970     if (workspacemenu->isVisible())
1971       workspacemenu->hide();
1972
1973     if (rootmenu->isVisible())
1974       rootmenu->hide();
1975   } else if (xbutton->button == 2) {
1976     int mx = xbutton->x_root - (workspacemenu->getWidth() / 2);
1977     int my = xbutton->y_root - (workspacemenu->getTitleHeight() / 2);
1978
1979     if (mx < 0) mx = 0;
1980     if (my < 0) my = 0;
1981
1982     if (mx + workspacemenu->getWidth() > getWidth())
1983       mx = getWidth() - workspacemenu->getWidth() - getBorderWidth();
1984
1985     if (my + workspacemenu->getHeight() > getHeight())
1986       my = getHeight() - workspacemenu->getHeight() - getBorderWidth();
1987
1988     workspacemenu->move(mx, my);
1989
1990     if (! workspacemenu->isVisible()) {
1991       workspacemenu->removeParent();
1992       workspacemenu->show();
1993     }
1994   } else if (xbutton->button == 3) {
1995     int mx = xbutton->x_root - (rootmenu->getWidth() / 2);
1996     int my = xbutton->y_root - (rootmenu->getTitleHeight() / 2);
1997
1998     if (mx < 0) mx = 0;
1999     if (my < 0) my = 0;
2000
2001     if (mx + rootmenu->getWidth() > getWidth())
2002       mx = getWidth() - rootmenu->getWidth() - getBorderWidth();
2003
2004     if (my + rootmenu->getHeight() > getHeight())
2005       my = getHeight() - rootmenu->getHeight() - getBorderWidth();
2006
2007     rootmenu->move(mx, my);
2008
2009     if (! rootmenu->isVisible()) {
2010       blackbox->checkMenu();
2011       rootmenu->show();
2012     }
2013   // mouse wheel up
2014   } else if (xbutton->button == 4) {
2015     if (getCurrentWorkspaceID() >= getWorkspaceCount() - 1)
2016       changeWorkspaceID(0);
2017     else
2018       changeWorkspaceID(getCurrentWorkspaceID() + 1);
2019   // mouse wheel down
2020   } else if (xbutton->button == 5) {
2021     if (getCurrentWorkspaceID() == 0)
2022       changeWorkspaceID(getWorkspaceCount() - 1);
2023     else
2024       changeWorkspaceID(getCurrentWorkspaceID() - 1);
2025   }
2026 }
2027
2028
2029 void BScreen::toggleFocusModel(FocusModel model) {
2030   if (model == SloppyFocus) {
2031     saveSloppyFocus(True);
2032   } else {
2033     saveSloppyFocus(False);
2034     saveAutoRaise(False);
2035     saveClickRaise(False);
2036   }
2037
2038   updateFocusModel();
2039 }
2040
2041
2042 void BScreen::updateFocusModel()
2043 {
2044   std::for_each(workspacesList.begin(), workspacesList.end(),
2045                 std::mem_fun(&Workspace::updateFocusModel));
2046 }
2047
2048
2049 BTexture BScreen::readDatabaseTexture(const string &rname,
2050                                       const string &default_color,
2051                                       Configuration &style) {
2052   BTexture texture;
2053   string s;
2054
2055   if (style.getValue(rname, s))
2056     texture = BTexture(s);
2057   else
2058     texture.setTexture(BTexture::Solid | BTexture::Flat);
2059
2060   // associate this texture with this screen
2061   texture.setDisplay(getBaseDisplay(), getScreenNumber());
2062   texture.setImageControl(image_control);
2063
2064   if (texture.texture() & BTexture::Solid) {
2065     texture.setColor(readDatabaseColor(rname + ".color",
2066                                        default_color, style));
2067     texture.setColorTo(readDatabaseColor(rname + ".colorTo",
2068                                          default_color, style));
2069   } else if (texture.texture() & BTexture::Gradient) {
2070     texture.setColor(readDatabaseColor(rname + ".color",
2071                                        default_color, style));
2072     texture.setColorTo(readDatabaseColor(rname + ".colorTo",
2073                                          default_color, style));
2074   }
2075
2076   return texture;
2077 }
2078
2079
2080 BColor BScreen::readDatabaseColor(const string &rname,
2081                                   const string &default_color,
2082                                   Configuration &style) {
2083   BColor color;
2084   string s;
2085   if (style.getValue(rname, s))
2086     color = BColor(s, getBaseDisplay(), getScreenNumber());
2087   else
2088     color = BColor(default_color, getBaseDisplay(), getScreenNumber());
2089   return color;
2090 }
2091
2092
2093 XFontSet BScreen::readDatabaseFontSet(const string &rname,
2094                                       Configuration &style) {
2095   char *defaultFont = "fixed";
2096
2097   bool load_default = True;
2098   string s;
2099   XFontSet fontset = 0;
2100   if (style.getValue(rname, s) && (fontset = createFontSet(s)))
2101     load_default = False;
2102
2103   if (load_default) {
2104     fontset = createFontSet(defaultFont);
2105
2106     if (! fontset) {
2107       fprintf(stderr,
2108               i18n(ScreenSet, ScreenDefaultFontLoadFail,
2109                    "BScreen::setCurrentStyle(): couldn't load default font.\n"));
2110       exit(2);
2111     }
2112   }
2113
2114   return fontset;
2115 }
2116
2117
2118 XFontStruct *BScreen::readDatabaseFont(const string &rname,
2119                                        Configuration &style) {
2120   char *defaultFont = "fixed";
2121
2122   bool load_default = False;
2123   string s;
2124   XFontStruct *font = 0;
2125   if (style.getValue(rname, s)) {
2126     if ((font = XLoadQueryFont(blackbox->getXDisplay(), s.c_str())) == NULL) {
2127       fprintf(stderr,
2128               i18n(ScreenSet, ScreenFontLoadFail,
2129                    "BScreen::setCurrentStyle(): couldn't load font '%s'\n"),
2130               s.c_str());
2131
2132       load_default = True;
2133     }
2134   } else {
2135     load_default = True;
2136   }
2137
2138   if (load_default) {
2139     font = XLoadQueryFont(blackbox->getXDisplay(), defaultFont);
2140     if (font == NULL) {
2141       fprintf(stderr,
2142               i18n(ScreenSet, ScreenDefaultFontLoadFail,
2143                    "BScreen::setCurrentStyle(): couldn't load default font.\n"));
2144       exit(2);
2145     }
2146   }
2147
2148   return font;
2149 }
2150
2151
2152 #ifndef    HAVE_STRCASESTR
2153 static const char * strcasestr(const char *str, const char *ptn) {
2154   const char *s2, *p2;
2155   for(; *str; str++) {
2156     for(s2=str,p2=ptn; ; s2++,p2++) {
2157       if (! *p2) return str;
2158       if (toupper(*s2) != toupper(*p2)) break;
2159     }
2160   }
2161   return NULL;
2162 }
2163 #endif // HAVE_STRCASESTR
2164
2165
2166 static const char *getFontElement(const char *pattern, char *buf,
2167                                   int bufsiz, ...) {
2168   const char *p, *v;
2169   char *p2;
2170   va_list va;
2171
2172   va_start(va, bufsiz);
2173   buf[bufsiz-1] = 0;
2174   buf[bufsiz-2] = '*';
2175   while((v = va_arg(va, char *)) != NULL) {
2176     p = strcasestr(pattern, v);
2177     if (p) {
2178       strncpy(buf, p+1, bufsiz-2);
2179       p2 = strchr(buf, '-');
2180       if (p2) *p2=0;
2181       va_end(va);
2182       return p;
2183     }
2184   }
2185   va_end(va);
2186   strncpy(buf, "*", bufsiz);
2187   return NULL;
2188 }
2189
2190
2191 static const char *getFontSize(const char *pattern, int *size) {
2192   const char *p;
2193   const char *p2=NULL;
2194   int n=0;
2195
2196   for (p=pattern; 1; p++) {
2197     if (! *p) {
2198       if (p2!=NULL && n>1 && n<72) {
2199         *size = n; return p2+1;
2200       } else {
2201         *size = 16; return NULL;
2202       }
2203     } else if (*p=='-') {
2204       if (n>1 && n<72 && p2!=NULL) {
2205         *size = n;
2206         return p2+1;
2207       }
2208       p2=p; n=0;
2209     } else if (*p>='0' && *p<='9' && p2!=NULL) {
2210       n *= 10;
2211       n += *p-'0';
2212     } else {
2213       p2=NULL; n=0;
2214     }
2215   }
2216 }
2217
2218
2219 XFontSet BScreen::createFontSet(const string &fontname) {
2220   XFontSet fs;
2221   char **missing, *def = "-";
2222   int nmissing, pixel_size = 0, buf_size = 0;
2223   char weight[FONT_ELEMENT_SIZE], slant[FONT_ELEMENT_SIZE];
2224
2225   fs = XCreateFontSet(blackbox->getXDisplay(),
2226                       fontname.c_str(), &missing, &nmissing, &def);
2227   if (fs && (! nmissing))
2228     return fs;
2229
2230   const char *nfontname = fontname.c_str();
2231 #ifdef    HAVE_SETLOCALE
2232   if (! fs) {
2233     if (nmissing) XFreeStringList(missing);
2234
2235     setlocale(LC_CTYPE, "C");
2236     fs = XCreateFontSet(blackbox->getXDisplay(), fontname.c_str(),
2237                         &missing, &nmissing, &def);
2238     setlocale(LC_CTYPE, "");
2239   }
2240 #endif // HAVE_SETLOCALE
2241
2242   if (fs) {
2243     XFontStruct **fontstructs;
2244     char **fontnames;
2245     XFontsOfFontSet(fs, &fontstructs, &fontnames);
2246     nfontname = fontnames[0];
2247   }
2248
2249   getFontElement(nfontname, weight, FONT_ELEMENT_SIZE,
2250                  "-medium-", "-bold-", "-demibold-", "-regular-", NULL);
2251   getFontElement(nfontname, slant, FONT_ELEMENT_SIZE,
2252                  "-r-", "-i-", "-o-", "-ri-", "-ro-", NULL);
2253   getFontSize(nfontname, &pixel_size);
2254
2255   if (! strcmp(weight, "*"))
2256     strncpy(weight, "medium", FONT_ELEMENT_SIZE);
2257   if (! strcmp(slant, "*"))
2258     strncpy(slant, "r", FONT_ELEMENT_SIZE);
2259   if (pixel_size < 3)
2260     pixel_size = 3;
2261   else if (pixel_size > 97)
2262     pixel_size = 97;
2263
2264   buf_size = strlen(nfontname) + (FONT_ELEMENT_SIZE * 2) + 64;
2265   char *pattern2 = new char[buf_size];
2266   sprintf(pattern2,
2267            "%s,"
2268            "-*-*-%s-%s-*-*-%d-*-*-*-*-*-*-*,"
2269            "-*-*-*-*-*-*-%d-*-*-*-*-*-*-*,*",
2270            nfontname, weight, slant, pixel_size, pixel_size);
2271   nfontname = pattern2;
2272
2273   if (nmissing)
2274     XFreeStringList(missing);
2275   if (fs)
2276     XFreeFontSet(blackbox->getXDisplay(), fs);
2277
2278   fs = XCreateFontSet(blackbox->getXDisplay(), nfontname, &missing,
2279                       &nmissing, &def);
2280
2281   delete [] pattern2;
2282
2283   return fs;
2284 }