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