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