]> icculus.org git repositories - dana/openbox.git/blob - src/Screen.cc
add the resource for the window snapping offset
[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   
688   if (! config->getValue(screenstr + "edgeSnapThreshold",
689                         resource.snap_threshold))
690     resource.snap_threshold = 4;
691   
692   if (! config->getValue(screenstr + "resistanceSize",
693                         resource.resistance_size))
694     resource.resistance_size = 12;
695   
696   if (config->getValue(screenstr + "rowPlacementDirection", s) &&
697       s == "RightToLeft")
698     resource.row_direction = RightLeft;
699   else
700     resource.row_direction = LeftRight;
701
702   if (config->getValue(screenstr + "colPlacementDirection", s) &&
703       s == "BottomToTop")
704     resource.col_direction = BottomTop;
705   else
706     resource.col_direction = TopBottom;
707
708   if (config->getValue(screenstr + "workspaceNames", s)) {
709     XAtom::StringVect workspaceNames;
710
711     string::const_iterator it = s.begin(), end = s.end();
712     while(1) {
713       string::const_iterator tmp = it;     // current string.begin()
714       it = std::find(tmp, end, ',');       // look for comma between tmp and end
715       workspaceNames.push_back(string(tmp, it)); // s[tmp:it]
716       if (it == end)
717         break;
718       ++it;
719     }
720
721     xatom->setValue(getRootWindow(), XAtom::net_desktop_names, XAtom::utf8,
722                     workspaceNames);
723   }
724
725   resource.sloppy_focus = true;
726   resource.auto_raise = false;
727   resource.click_raise = false;
728   if (config->getValue(screenstr + "focusModel", s)) {
729     if (s.find("ClickToFocus") != string::npos) {
730       resource.sloppy_focus = false;
731     } else {
732       // must be sloppy
733       if (s.find("AutoRaise") != string::npos)
734         resource.auto_raise = true;
735       if (s.find("ClickRaise") != string::npos)
736         resource.click_raise = true;
737     }
738   }
739
740   if (config->getValue(screenstr + "windowPlacement", s)) {
741     if (s == "CascadePlacement")
742       resource.placement_policy = CascadePlacement;
743     else if (s == "UnderMousePlacement")
744       resource.placement_policy = UnderMousePlacement;
745     else if (s == "ClickMousePlacement")
746       resource.placement_policy = ClickMousePlacement;
747     else if (s == "ColSmartPlacement")
748       resource.placement_policy = ColSmartPlacement;
749     else //if (s == "RowSmartPlacement")
750       resource.placement_policy = RowSmartPlacement;
751   } else
752     resource.placement_policy = RowSmartPlacement;
753
754 #ifdef    HAVE_STRFTIME
755   if (! config->getValue(screenstr + "strftimeFormat",
756                          resource.strftime_format))
757     resource.strftime_format = "%I:%M %p";
758 #else // !HAVE_STRFTIME
759   long l;
760
761   if (config->getValue(screenstr + "dateFormat", s) && s == "European")
762     resource.date_format = B_EuropeanDate;
763  else
764     resource.date_format = B_AmericanDate;
765
766   if (! config->getValue(screenstr + "clockFormat", l))
767     l = 12;
768   resource.clock24hour = l == 24;
769 #endif // HAVE_STRFTIME
770   
771   if (! config->getValue(screenstr + "placementIgnoreShaded",
772                          resource.ignore_shaded))
773     resource.ignore_shaded = true;
774
775   if (! config->getValue(screenstr + "placementIgnoreMaximized",
776                          resource.ignore_maximized))
777     resource.ignore_maximized = true;
778
779   if (! config->getValue(screenstr + "disableBindingsWithScrollLock",
780                        resource.allow_scroll_lock))
781     resource.allow_scroll_lock = false;
782
783   if (! config->getValue(screenstr + "workspaceWarping",
784                          resource.workspace_warping))
785     resource.workspace_warping = false;
786
787   resource.root_scroll = NormalScroll;
788   if (config->getValue(screenstr + "rootScrollDirection", s)) {
789     if (s == "None")
790       resource.root_scroll = NoScroll;
791     else if (s == "Reverse")
792       resource.root_scroll = ReverseScroll;
793   }
794 }
795
796
797 void BScreen::changeWorkspaceCount(unsigned int new_count) {
798   assert(new_count > 0);
799
800   if (new_count < workspacesList.size()) {
801     // shrink
802     for (unsigned int i = workspacesList.size(); i > new_count; --i)
803       removeLastWorkspace();
804     // removeLast already sets the current workspace to the 
805     // last available one.
806   } else if (new_count > workspacesList.size()) {
807     // grow
808     for(unsigned int i = workspacesList.size(); i < new_count; ++i)
809       addWorkspace();
810   }
811 }
812
813
814 void BScreen::reconfigure(void) {
815   // don't reconfigure while saving the initial rc file, it's a waste and it
816   // breaks somethings (workspace names)
817   if (blackbox->isStartup()) return;
818
819   load_rc();
820   toolbar->load_rc();
821   slit->load_rc();
822   LoadStyle();
823
824   // we need to do this explicitly, because just loading this value from the rc
825   // does nothing
826   changeWorkspaceCount(resource.workspaces);
827
828   XGCValues gcv;
829   gcv.foreground = WhitePixel(blackbox->getXDisplay(),
830                               getScreenNumber());
831   gcv.function = GXinvert;
832   gcv.subwindow_mode = IncludeInferiors;
833   XChangeGC(blackbox->getXDisplay(), opGC,
834             GCForeground | GCFunction | GCSubwindowMode, &gcv);
835
836   const char *s = i18n(ScreenSet, ScreenPositionLength,
837                        "0: 0000 x 0: 0000");
838
839   geom_w = resource.wstyle.font->measureString(s) + resource.bevel_width * 2;
840   geom_h = resource.wstyle.font->height() + resource.bevel_width * 2;
841
842   BTexture* texture = &(resource.wstyle.l_focus);
843   geom_pixmap = texture->render(geom_w, geom_h, geom_pixmap);
844   if (geom_pixmap == ParentRelative) {
845     texture = &(resource.wstyle.t_focus);
846     geom_pixmap = texture->render(geom_w, geom_h, geom_pixmap);
847   }
848   if (! geom_pixmap)
849     XSetWindowBackground(blackbox->getXDisplay(), geom_window,
850                          texture->color().pixel());
851   else
852     XSetWindowBackgroundPixmap(blackbox->getXDisplay(),
853                                geom_window, geom_pixmap);
854
855   XSetWindowBorderWidth(blackbox->getXDisplay(), geom_window,
856                         resource.border_width);
857   XSetWindowBorder(blackbox->getXDisplay(), geom_window,
858                    resource.border_color.pixel());
859
860   workspacemenu->reconfigure();
861   iconmenu->reconfigure();
862
863   typedef std::vector<int> SubList;
864   SubList remember_subs;
865
866   // save the current open menus
867   Basemenu *menu = rootmenu;
868   int submenu;
869   while ((submenu = menu->getCurrentSubmenu()) >= 0) {
870     remember_subs.push_back(submenu);
871     menu = menu->find(submenu)->submenu();
872     assert(menu);
873   }
874   
875   InitMenu();
876   raiseWindows(0, 0);
877   rootmenu->reconfigure();
878
879   // reopen the saved menus
880   menu = rootmenu;
881   const SubList::iterator subs_end = remember_subs.end();
882   for (SubList::iterator it = remember_subs.begin(); it != subs_end; ++it) {
883     menu->drawSubmenu(*it);
884     menu = menu->find(*it)->submenu();
885     if (! menu)
886       break;
887   }
888
889   configmenu->reconfigure();
890
891   toolbar->reconfigure();
892
893   slit->reconfigure();
894
895   std::for_each(workspacesList.begin(), workspacesList.end(),
896                 std::mem_fun(&Workspace::reconfigure));
897
898   BlackboxWindowList::iterator iit = iconList.begin();
899   for (; iit != iconList.end(); ++iit) {
900     BlackboxWindow *bw = *iit;
901     if (bw->validateClient())
902       bw->reconfigure();
903   }
904
905   image_control->timeout();
906 }
907
908
909 void BScreen::rereadMenu(void) {
910   InitMenu();
911   raiseWindows(0, 0);
912
913   rootmenu->reconfigure();
914 }
915
916
917 void BScreen::LoadStyle(void) {
918   Configuration style(False);
919
920   const char *sfile = blackbox->getStyleFilename();
921   if (sfile != NULL) {
922     style.setFile(sfile);
923     if (! style.load()) {
924       style.setFile(DEFAULTSTYLE);
925       if (! style.load())
926         style.create();  // hardcoded default values will be used.
927     }
928   }
929
930   // merge in the rc file
931   style.merge(config->file(), True);
932
933   string s;
934
935   // load fonts/fontsets
936   if (resource.wstyle.font)
937     delete resource.wstyle.font;
938   if (resource.tstyle.font)
939     delete resource.tstyle.font;
940   if (resource.mstyle.f_font)
941     delete resource.mstyle.f_font;
942   if (resource.mstyle.t_font)
943     delete resource.mstyle.t_font;
944   resource.wstyle.font = resource.tstyle.font = resource.mstyle.f_font =
945     resource.mstyle.t_font = (BFont *) 0;
946
947   resource.wstyle.font = readDatabaseFont("window.", style);
948   resource.tstyle.font = readDatabaseFont("toolbar.", style);
949   resource.mstyle.t_font = readDatabaseFont("menu.title.", style);
950   resource.mstyle.f_font = readDatabaseFont("menu.frame.", style);
951
952   // load window config
953   resource.wstyle.t_focus =
954     readDatabaseTexture("window.title.focus", "white", style);
955   resource.wstyle.t_unfocus =
956     readDatabaseTexture("window.title.unfocus", "black", style);
957   resource.wstyle.l_focus =
958     readDatabaseTexture("window.label.focus", "white", style);
959   resource.wstyle.l_unfocus =
960     readDatabaseTexture("window.label.unfocus", "black", style);
961   resource.wstyle.h_focus =
962     readDatabaseTexture("window.handle.focus", "white", style);
963   resource.wstyle.h_unfocus =
964     readDatabaseTexture("window.handle.unfocus", "black", style);
965   resource.wstyle.g_focus =
966     readDatabaseTexture("window.grip.focus", "white", style);
967   resource.wstyle.g_unfocus =
968     readDatabaseTexture("window.grip.unfocus", "black", style);
969   resource.wstyle.b_focus =
970     readDatabaseTexture("window.button.focus", "white", style);
971   resource.wstyle.b_unfocus =
972     readDatabaseTexture("window.button.unfocus", "black", style);
973   resource.wstyle.b_pressed =
974     readDatabaseTexture("window.button.pressed", "black", style);
975   resource.wstyle.f_focus =
976     readDatabaseColor("window.frame.focusColor", "white", style);
977   resource.wstyle.f_unfocus =
978     readDatabaseColor("window.frame.unfocusColor", "black", style);
979   resource.wstyle.l_text_focus =
980     readDatabaseColor("window.label.focus.textColor", "black", style);
981   resource.wstyle.l_text_unfocus =
982     readDatabaseColor("window.label.unfocus.textColor", "white", style);
983   resource.wstyle.b_pic_focus =
984     readDatabaseColor("window.button.focus.picColor", "black", style);
985   resource.wstyle.b_pic_unfocus =
986     readDatabaseColor("window.button.unfocus.picColor", "white", style);
987
988   resource.wstyle.justify = LeftJustify;
989   if (style.getValue("window.justify", s)) {
990     if (s == "right" || s == "Right")
991       resource.wstyle.justify = RightJustify;
992     else if (s == "center" || s == "Center")
993       resource.wstyle.justify = CenterJustify;
994   }
995
996   // load toolbar config
997   resource.tstyle.toolbar =
998     readDatabaseTexture("toolbar", "black", style);
999   resource.tstyle.label =
1000     readDatabaseTexture("toolbar.label", "black", style);
1001   resource.tstyle.window =
1002     readDatabaseTexture("toolbar.windowLabel", "black", style);
1003   resource.tstyle.button =
1004     readDatabaseTexture("toolbar.button", "white", style);
1005   resource.tstyle.pressed =
1006     readDatabaseTexture("toolbar.button.pressed", "black", style);
1007   resource.tstyle.clock =
1008     readDatabaseTexture("toolbar.clock", "black", style);
1009   resource.tstyle.l_text =
1010     readDatabaseColor("toolbar.label.textColor", "white", style);
1011   resource.tstyle.w_text =
1012     readDatabaseColor("toolbar.windowLabel.textColor", "white", style);
1013   resource.tstyle.c_text =
1014     readDatabaseColor("toolbar.clock.textColor", "white", style);
1015   resource.tstyle.b_pic =
1016     readDatabaseColor("toolbar.button.picColor", "black", style);
1017
1018   resource.tstyle.justify = LeftJustify;
1019   if (style.getValue("toolbar.justify", s)) {
1020     if (s == "right" || s == "Right")
1021       resource.tstyle.justify = RightJustify;
1022     else if (s == "center" || s == "Center")
1023       resource.tstyle.justify = CenterJustify;
1024   }
1025
1026   // load menu config
1027   resource.mstyle.title =
1028     readDatabaseTexture("menu.title", "white", style);
1029   resource.mstyle.frame =
1030     readDatabaseTexture("menu.frame", "black", style);
1031   resource.mstyle.hilite =
1032     readDatabaseTexture("menu.hilite", "white", style);
1033   resource.mstyle.t_text =
1034     readDatabaseColor("menu.title.textColor", "black", style);
1035   resource.mstyle.f_text =
1036     readDatabaseColor("menu.frame.textColor", "white", style);
1037   resource.mstyle.d_text =
1038     readDatabaseColor("menu.frame.disableColor", "black", style);
1039   resource.mstyle.h_text =
1040     readDatabaseColor("menu.hilite.textColor", "black", style);
1041
1042   resource.mstyle.t_justify = LeftJustify;
1043   if (style.getValue("menu.title.justify", s)) {
1044     if (s == "right" || s == "Right")
1045       resource.mstyle.t_justify = RightJustify;
1046     else if (s == "center" || s == "Center")
1047       resource.mstyle.t_justify = CenterJustify;
1048   }
1049
1050   resource.mstyle.f_justify = LeftJustify;
1051   if (style.getValue("menu.frame.justify", s)) {
1052     if (s == "right" || s == "Right")
1053       resource.mstyle.f_justify = RightJustify;
1054     else if (s == "center" || s == "Center")
1055       resource.mstyle.f_justify = CenterJustify;
1056   }
1057
1058   resource.mstyle.bullet = Basemenu::Triangle;
1059   if (style.getValue("menu.bullet", s)) {
1060     if (s == "empty" || s == "Empty")
1061       resource.mstyle.bullet = Basemenu::Empty;
1062     else if (s == "square" || s == "Square")
1063       resource.mstyle.bullet = Basemenu::Square;
1064     else if (s == "diamond" || s == "Diamond")
1065       resource.mstyle.bullet = Basemenu::Diamond;
1066   }
1067
1068   resource.mstyle.bullet_pos = Basemenu::Left;
1069   if (style.getValue("menu.bullet.position", s)) {
1070     if (s == "right" || s == "Right")
1071       resource.mstyle.bullet_pos = Basemenu::Right;
1072   }
1073
1074   resource.border_color =
1075     readDatabaseColor("borderColor", "black", style);
1076
1077   // load bevel, border and handle widths
1078   if (! style.getValue("handleWidth", resource.handle_width) ||
1079       resource.handle_width > (getWidth() / 2) || resource.handle_width == 0)
1080     resource.handle_width = 6;
1081
1082   if (! style.getValue("borderWidth", resource.border_width))
1083     resource.border_width = 1;
1084
1085   if (! style.getValue("bevelWidth", resource.bevel_width) ||
1086       resource.bevel_width > (getWidth() / 2) || resource.bevel_width == 0)
1087     resource.bevel_width = 3;
1088
1089   if (! style.getValue("frameWidth", resource.frame_width) ||
1090       resource.frame_width > (getWidth() / 2))
1091     resource.frame_width = resource.bevel_width;
1092
1093   if (style.getValue("rootCommand", s))
1094     bexec(s, displayString());
1095 }
1096
1097
1098 void BScreen::addIcon(BlackboxWindow *w) {
1099   if (! w) return;
1100
1101   w->setWorkspace(BSENTINEL);
1102   w->setWindowNumber(iconList.size());
1103
1104   iconList.push_back(w);
1105
1106   const char* title = w->getIconTitle();
1107   iconmenu->insert(title);
1108   iconmenu->update();
1109 }
1110
1111
1112 void BScreen::removeIcon(BlackboxWindow *w) {
1113   if (! w) return;
1114
1115   iconList.remove(w);
1116
1117   iconmenu->remove(w->getWindowNumber());
1118   iconmenu->update();
1119
1120   BlackboxWindowList::iterator it = iconList.begin(),
1121     end = iconList.end();
1122   for (int i = 0; it != end; ++it)
1123     (*it)->setWindowNumber(i++);
1124 }
1125
1126
1127 BlackboxWindow *BScreen::getIcon(unsigned int index) {
1128   if (index < iconList.size()) {
1129     BlackboxWindowList::iterator it = iconList.begin();
1130     for (; index > 0; --index, ++it) ; /* increment to index */
1131     return *it;
1132   }
1133
1134   return (BlackboxWindow *) 0;
1135 }
1136
1137
1138 unsigned int BScreen::addWorkspace(void) {
1139   Workspace *wkspc = new Workspace(this, workspacesList.size());
1140   workspacesList.push_back(wkspc);
1141   saveWorkspaces(getWorkspaceCount());
1142   saveWorkspaceNames();
1143
1144   workspacemenu->insertWorkspace(wkspc);
1145   workspacemenu->update();
1146
1147   toolbar->reconfigure();
1148
1149   updateNetizenWorkspaceCount();
1150
1151   return workspacesList.size();
1152 }
1153
1154
1155 unsigned int BScreen::removeLastWorkspace(void) {
1156   if (workspacesList.size() == 1)
1157     return 1;
1158
1159   Workspace *wkspc = workspacesList.back();
1160
1161   if (current_workspace->getID() == wkspc->getID())
1162     changeWorkspaceID(current_workspace->getID() - 1);
1163
1164   wkspc->removeAll();
1165
1166   workspacemenu->removeWorkspace(wkspc);
1167   workspacemenu->update();
1168
1169   workspacesList.pop_back();
1170   delete wkspc;
1171
1172   saveWorkspaces(getWorkspaceCount());
1173   saveWorkspaceNames();
1174
1175   toolbar->reconfigure();
1176
1177   updateNetizenWorkspaceCount();
1178
1179   return workspacesList.size();
1180 }
1181
1182
1183 void BScreen::changeWorkspaceID(unsigned int id) {
1184   if (! current_workspace || id == current_workspace->getID()) return;
1185
1186   BlackboxWindow *focused = blackbox->getFocusedWindow();
1187   if (focused && focused->getScreen() == this) {
1188     assert(focused->isStuck() ||
1189            focused->getWorkspaceNumber() == current_workspace->getID());
1190
1191     current_workspace->setLastFocusedWindow(focused);
1192   } else {
1193     // if no window had focus, no need to store a last focus
1194     current_workspace->setLastFocusedWindow((BlackboxWindow *) 0);
1195   }
1196
1197   // when we switch workspaces, unfocus whatever was focused
1198   blackbox->setFocusedWindow((BlackboxWindow *) 0);
1199     
1200   current_workspace->hideAll();
1201   workspacemenu->setItemSelected(current_workspace->getID() + 2, False);
1202
1203   current_workspace = getWorkspace(id);
1204
1205   xatom->setValue(getRootWindow(), XAtom::net_current_desktop,
1206                   XAtom::cardinal, id);
1207
1208   workspacemenu->setItemSelected(current_workspace->getID() + 2, True);
1209   toolbar->redrawWorkspaceLabel(True);
1210
1211   current_workspace->showAll();
1212
1213   if (resource.focus_last && current_workspace->getLastFocusedWindow()) {
1214     XSync(blackbox->getXDisplay(), False);
1215     current_workspace->getLastFocusedWindow()->setInputFocus();
1216   }
1217
1218   updateNetizenCurrentWorkspace();
1219 }
1220
1221
1222 /*
1223  * Set the _NET_CLIENT_LIST root window property.
1224  */
1225 void BScreen::updateClientList(void) {
1226   if (windowList.size() > 0) {
1227     Window *windows = new Window[windowList.size()];
1228     Window *win_it = windows;
1229     BlackboxWindowList::iterator it = windowList.begin();
1230     const BlackboxWindowList::iterator end = windowList.end();
1231     for (; it != end; ++it, ++win_it)
1232       *win_it = (*it)->getClientWindow();
1233     xatom->setValue(getRootWindow(), XAtom::net_client_list, XAtom::window,
1234                     windows, windowList.size());
1235     delete [] windows;
1236   } else
1237     xatom->setValue(getRootWindow(), XAtom::net_client_list, XAtom::window,
1238                     0, 0);
1239
1240   updateStackingList();
1241 }
1242
1243
1244 /*
1245  * Set the _NET_CLIENT_LIST_STACKING root window property.
1246  */
1247 void BScreen::updateStackingList(void) {
1248
1249   BlackboxWindowList stack_order;
1250
1251   /*
1252    * Get the stacking order from all of the workspaces.
1253    * We start with the current workspace so that the sticky windows will be
1254    * in the right order on the current workspace.
1255    * XXX: Do we need to have sticky windows in the list once for each workspace?
1256    */
1257   getCurrentWorkspace()->appendStackOrder(stack_order);
1258   for (unsigned int i = 0; i < getWorkspaceCount(); ++i)
1259     if (i != getCurrentWorkspaceID())
1260       getWorkspace(i)->appendStackOrder(stack_order);
1261
1262   if (stack_order.size() > 0) {
1263     // set the client list atoms
1264     Window *windows = new Window[stack_order.size()];
1265     Window *win_it = windows;
1266     BlackboxWindowList::iterator it = stack_order.begin(),
1267                                  end = stack_order.end();
1268     for (; it != end; ++it, ++win_it)
1269       *win_it = (*it)->getClientWindow();
1270     xatom->setValue(getRootWindow(), XAtom::net_client_list_stacking,
1271                     XAtom::window, windows, stack_order.size());
1272     delete [] windows;
1273   } else
1274     xatom->setValue(getRootWindow(), XAtom::net_client_list_stacking,
1275                     XAtom::window, 0, 0);
1276 }
1277
1278
1279 void BScreen::addSystrayWindow(Window window) {
1280   systrayWindowList.push_back(window);
1281   xatom->setValue(getRootWindow(), XAtom::kde_net_system_tray_windows,
1282                   XAtom::window,
1283                   &systrayWindowList[0], systrayWindowList.size());
1284   blackbox->saveSystrayWindowSearch(window, this);
1285 }
1286
1287
1288 void BScreen::removeSystrayWindow(Window window) {
1289   WindowList::iterator it = systrayWindowList.begin();
1290   const WindowList::iterator end = systrayWindowList.end();
1291   for (; it != end; ++it)
1292     if (*it == window) {
1293       systrayWindowList.erase(it);
1294       xatom->setValue(getRootWindow(), XAtom::kde_net_system_tray_windows,
1295                       XAtom::window,
1296                       &systrayWindowList[0], systrayWindowList.size());
1297       blackbox->removeSystrayWindowSearch(window);
1298       break;
1299     }
1300 }
1301
1302
1303 void BScreen::manageWindow(Window w) {
1304   // is the window a KDE systray window?
1305   Window systray;
1306   if (xatom->getValue(w, XAtom::kde_net_wm_system_tray_window_for,
1307                       XAtom::window, systray) && systray) {
1308     addSystrayWindow(w);
1309     return;
1310   }
1311
1312   // is the window a docking app
1313   XWMHints *wmhint = XGetWMHints(blackbox->getXDisplay(), w);
1314   if (wmhint && (wmhint->flags & StateHint) &&
1315       wmhint->initial_state == WithdrawnState) {
1316     slit->addClient(w);
1317     return;
1318   }
1319
1320   new BlackboxWindow(blackbox, w, this);
1321
1322   BlackboxWindow *win = blackbox->searchWindow(w);
1323   if (! win)
1324     return;
1325
1326
1327   if (win->isNormal()) {
1328     // don't list non-normal windows as managed windows
1329     windowList.push_back(win);
1330     updateClientList();
1331   } else if (win->isDesktop()) {
1332     desktopWindowList.push_back(win->getFrameWindow());
1333   }
1334
1335   XMapRequestEvent mre;
1336   mre.window = w;
1337   if (blackbox->isStartup() && win->isNormal()) win->restoreAttributes();
1338   win->mapRequestEvent(&mre);
1339 }
1340
1341
1342 void BScreen::unmanageWindow(BlackboxWindow *w, bool remap) {
1343   w->restore(remap);
1344
1345   // Remove the modality so that its parent won't try to re-focus the window
1346   if (w->isModal()) w->setModal(False);
1347   
1348   if (w->getWorkspaceNumber() != BSENTINEL &&
1349       w->getWindowNumber() != BSENTINEL) {
1350     getWorkspace(w->getWorkspaceNumber())->removeWindow(w);
1351     if (w->isStuck()) {
1352       for (unsigned int i = 0; i < getNumberOfWorkspaces(); ++i)
1353         if (i != w->getWorkspaceNumber())
1354           getWorkspace(i)->removeWindow(w, True);
1355     }
1356   } else if (w->isIconic())
1357     removeIcon(w);
1358
1359   if (w->isNormal()) {
1360     // we don't list non-normal windows as managed windows
1361     windowList.remove(w);
1362     updateClientList();
1363   } else if (w->isDesktop()) {
1364     WindowList::iterator it = desktopWindowList.begin();
1365     const WindowList::iterator end = desktopWindowList.end();
1366     for (; it != end; ++it)
1367       if (*it == w->getFrameWindow()) {
1368         desktopWindowList.erase(it);
1369         break;
1370       }
1371     assert(it != end);  // the window wasnt a desktop window?
1372   }
1373
1374   if (blackbox->getFocusedWindow() == w)
1375     blackbox->setFocusedWindow((BlackboxWindow *) 0);
1376
1377   removeNetizen(w->getClientWindow());
1378
1379   /*
1380     some managed windows can also be window group controllers.  when
1381     unmanaging such windows, we should also delete the window group.
1382   */
1383   BWindowGroup *group = blackbox->searchGroup(w->getClientWindow());
1384   delete group;
1385
1386   delete w;
1387 }
1388
1389
1390 void BScreen::addNetizen(Netizen *n) {
1391   netizenList.push_back(n);
1392
1393   n->sendWorkspaceCount();
1394   n->sendCurrentWorkspace();
1395
1396   WorkspaceList::iterator it = workspacesList.begin();
1397   const WorkspaceList::iterator end = workspacesList.end();
1398   for (; it != end; ++it)
1399     (*it)->sendWindowList(*n);
1400
1401   Window f = ((blackbox->getFocusedWindow()) ?
1402               blackbox->getFocusedWindow()->getClientWindow() : None);
1403   n->sendWindowFocus(f);
1404 }
1405
1406
1407 void BScreen::removeNetizen(Window w) {
1408   NetizenList::iterator it = netizenList.begin();
1409   for (; it != netizenList.end(); ++it) {
1410     if ((*it)->getWindowID() == w) {
1411       delete *it;
1412       netizenList.erase(it);
1413       break;
1414     }
1415   }
1416 }
1417
1418
1419 void BScreen::updateWorkArea(void) {
1420   if (workspacesList.size() > 0) {
1421     unsigned long *dims = new unsigned long[4 * workspacesList.size()];
1422     for (unsigned int i = 0, m = workspacesList.size(); i < m; ++i) {
1423       // XXX: this could be different for each workspace
1424       const Rect &area = availableArea();
1425       dims[(i * 4) + 0] = area.x();
1426       dims[(i * 4) + 1] = area.y();
1427       dims[(i * 4) + 2] = area.width();
1428       dims[(i * 4) + 3] = area.height();
1429     }
1430     xatom->setValue(getRootWindow(), XAtom::net_workarea, XAtom::cardinal,
1431                     dims, 4 * workspacesList.size());
1432     delete [] dims;
1433   } else
1434     xatom->setValue(getRootWindow(), XAtom::net_workarea, XAtom::cardinal,
1435                     0, 0);
1436 }
1437
1438
1439 void BScreen::updateNetizenCurrentWorkspace(void) {
1440   std::for_each(netizenList.begin(), netizenList.end(),
1441                 std::mem_fun(&Netizen::sendCurrentWorkspace));
1442 }
1443
1444
1445 void BScreen::updateNetizenWorkspaceCount(void) {
1446   xatom->setValue(getRootWindow(), XAtom::net_number_of_desktops,
1447                   XAtom::cardinal, workspacesList.size());
1448
1449   updateWorkArea();
1450   
1451   std::for_each(netizenList.begin(), netizenList.end(),
1452                 std::mem_fun(&Netizen::sendWorkspaceCount));
1453 }
1454
1455
1456 void BScreen::updateNetizenWindowFocus(void) {
1457   Window f = ((blackbox->getFocusedWindow()) ?
1458               blackbox->getFocusedWindow()->getClientWindow() : None);
1459
1460   xatom->setValue(getRootWindow(), XAtom::net_active_window,
1461                   XAtom::window, f);
1462
1463   NetizenList::iterator it = netizenList.begin();
1464   for (; it != netizenList.end(); ++it)
1465     (*it)->sendWindowFocus(f);
1466 }
1467
1468
1469 void BScreen::updateNetizenWindowAdd(Window w, unsigned long p) {
1470   NetizenList::iterator it = netizenList.begin();
1471   for (; it != netizenList.end(); ++it) {
1472     (*it)->sendWindowAdd(w, p);
1473   }
1474 }
1475
1476
1477 void BScreen::updateNetizenWindowDel(Window w) {
1478   NetizenList::iterator it = netizenList.begin();
1479   for (; it != netizenList.end(); ++it)
1480     (*it)->sendWindowDel(w);
1481 }
1482
1483
1484 void BScreen::updateNetizenWindowRaise(Window w) {
1485   NetizenList::iterator it = netizenList.begin();
1486   for (; it != netizenList.end(); ++it)
1487     (*it)->sendWindowRaise(w);
1488 }
1489
1490
1491 void BScreen::updateNetizenWindowLower(Window w) {
1492   NetizenList::iterator it = netizenList.begin();
1493   for (; it != netizenList.end(); ++it)
1494     (*it)->sendWindowLower(w);
1495 }
1496
1497
1498 void BScreen::updateNetizenConfigNotify(XEvent *e) {
1499   NetizenList::iterator it = netizenList.begin();
1500   for (; it != netizenList.end(); ++it)
1501     (*it)->sendConfigNotify(e);
1502 }
1503
1504
1505 void BScreen::raiseWindows(Window *workspace_stack, unsigned int num) {
1506   // the 13 represents the number of blackbox windows such as menus
1507   int bbwins = 15;
1508 #ifdef    XINERAMA
1509   ++bbwins;
1510 #endif // XINERAMA
1511
1512   Window *session_stack = new
1513     Window[(num + workspacesList.size() + rootmenuList.size() + bbwins)];
1514   unsigned int i = 0, k = num;
1515
1516   XRaiseWindow(blackbox->getXDisplay(), iconmenu->getWindowID());
1517   *(session_stack + i++) = iconmenu->getWindowID();
1518
1519   WorkspaceList::iterator wit = workspacesList.begin();
1520   const WorkspaceList::iterator w_end = workspacesList.end();
1521   for (; wit != w_end; ++wit)
1522     *(session_stack + i++) = (*wit)->getMenu()->getWindowID();
1523
1524   *(session_stack + i++) = workspacemenu->getWindowID();
1525
1526   *(session_stack + i++) = configmenu->getFocusmenu()->getWindowID();
1527   *(session_stack + i++) = configmenu->getPlacementmenu()->getWindowID();
1528   *(session_stack + i++) = configmenu->getWindowSnapmenu()->getWindowID();
1529   *(session_stack + i++) = configmenu->getEdgeSnapmenu()->getWindowID();
1530 #ifdef    XINERAMA
1531   *(session_stack + i++) = configmenu->getXineramamenu()->getWindowID();
1532 #endif // XINERAMA
1533   *(session_stack + i++) = configmenu->getWindowID();
1534
1535   *(session_stack + i++) = slit->getMenu()->getDirectionmenu()->getWindowID();
1536   *(session_stack + i++) = slit->getMenu()->getPlacementmenu()->getWindowID();
1537   *(session_stack + i++) = slit->getMenu()->getWindowID();
1538
1539   *(session_stack + i++) =
1540     toolbar->getMenu()->getPlacementmenu()->getWindowID();
1541   *(session_stack + i++) = toolbar->getMenu()->getWindowID();
1542
1543   RootmenuList::iterator rit = rootmenuList.begin();
1544   for (; rit != rootmenuList.end(); ++rit)
1545     *(session_stack + i++) = (*rit)->getWindowID();
1546   *(session_stack + i++) = rootmenu->getWindowID();
1547
1548   if (toolbar->isOnTop())
1549     *(session_stack + i++) = toolbar->getWindowID();
1550
1551   if (slit->isOnTop())
1552     *(session_stack + i++) = slit->getWindowID();
1553
1554   while (k--)
1555     *(session_stack + i++) = *(workspace_stack + k);
1556
1557   XRestackWindows(blackbox->getXDisplay(), session_stack, i);
1558
1559   delete [] session_stack;
1560
1561   updateStackingList();
1562 }
1563
1564
1565 void BScreen::lowerWindows(Window *workspace_stack, unsigned int num) {
1566   assert(num > 0);  // this would cause trouble in the XRaiseWindow call
1567
1568   Window *session_stack = new Window[(num + desktopWindowList.size())];
1569   unsigned int i = 0, k = num;
1570
1571   XLowerWindow(blackbox->getXDisplay(), workspace_stack[0]);
1572
1573   while (k--)
1574     *(session_stack + i++) = *(workspace_stack + k);
1575
1576   WindowList::iterator dit = desktopWindowList.begin();
1577   const WindowList::iterator d_end = desktopWindowList.end();
1578   for (; dit != d_end; ++dit)
1579     *(session_stack + i++) = *dit;
1580
1581   XRestackWindows(blackbox->getXDisplay(), session_stack, i);
1582
1583   delete [] session_stack;
1584
1585   updateStackingList();
1586 }
1587
1588
1589 void BScreen::reassociateWindow(BlackboxWindow *w, unsigned int wkspc_id,
1590                                 bool ignore_sticky) {
1591   if (! w) return;
1592
1593   if (wkspc_id == BSENTINEL)
1594     wkspc_id = current_workspace->getID();
1595
1596   if (w->getWorkspaceNumber() == wkspc_id)
1597     return;
1598
1599   if (w->isIconic()) {
1600     removeIcon(w);
1601     getWorkspace(wkspc_id)->addWindow(w);
1602     if (w->isStuck())
1603       for (unsigned int i = 0; i < getNumberOfWorkspaces(); ++i)
1604         if (i != w->getWorkspaceNumber())
1605           getWorkspace(i)->addWindow(w, True);
1606   } else if (ignore_sticky || ! w->isStuck()) {
1607     if (w->isStuck())
1608       w->stick();
1609     getWorkspace(w->getWorkspaceNumber())->removeWindow(w);
1610     getWorkspace(wkspc_id)->addWindow(w);
1611   }
1612   updateStackingList();
1613 }
1614
1615
1616 void BScreen::propagateWindowName(const BlackboxWindow *bw) {
1617   if (bw->isIconic()) {
1618     iconmenu->changeItemLabel(bw->getWindowNumber(), bw->getIconTitle());
1619     iconmenu->update();
1620   }
1621   else {
1622     Clientmenu *clientmenu = getWorkspace(bw->getWorkspaceNumber())->getMenu();
1623     clientmenu->changeItemLabel(bw->getWindowNumber(), bw->getTitle());
1624     clientmenu->update();
1625
1626     if (blackbox->getFocusedWindow() == bw)
1627       toolbar->redrawWindowLabel(True);
1628   }
1629 }
1630
1631
1632 void BScreen::nextFocus(void) {
1633   BlackboxWindow *focused = blackbox->getFocusedWindow(),
1634     *next = focused;
1635
1636   if (focused) {
1637     // if window is not on this screen, ignore it
1638     if (focused->getScreen()->getScreenNumber() != getScreenNumber())
1639       focused = (BlackboxWindow*) 0;
1640   }
1641
1642   if (focused && current_workspace->getCount() > 1) {
1643     // next is the next window to recieve focus, current is a place holder
1644     BlackboxWindow *current;
1645     do {
1646       current = next;
1647       next = current_workspace->getNextWindowInList(current);
1648     } while(! next->setInputFocus() && next != focused);
1649
1650     if (next != focused)
1651       current_workspace->raiseWindow(next);
1652   } else if (current_workspace->getCount() >= 1) {
1653     next = current_workspace->getTopWindowOnStack();
1654
1655     current_workspace->raiseWindow(next);
1656     next->setInputFocus();
1657   }
1658 }
1659
1660
1661 void BScreen::prevFocus(void) {
1662   BlackboxWindow *focused = blackbox->getFocusedWindow(),
1663     *next = focused;
1664
1665   if (focused) {
1666     // if window is not on this screen, ignore it
1667     if (focused->getScreen()->getScreenNumber() != getScreenNumber())
1668       focused = (BlackboxWindow*) 0;
1669   }
1670
1671   if (focused && current_workspace->getCount() > 1) {
1672     // next is the next window to recieve focus, current is a place holder
1673     BlackboxWindow *current;
1674     do {
1675       current = next;
1676       next = current_workspace->getPrevWindowInList(current);
1677     } while(! next->setInputFocus() && next != focused);
1678
1679     if (next != focused)
1680       current_workspace->raiseWindow(next);
1681   } else if (current_workspace->getCount() >= 1) {
1682     next = current_workspace->getTopWindowOnStack();
1683
1684     current_workspace->raiseWindow(next);
1685     next->setInputFocus();
1686   }
1687 }
1688
1689
1690 void BScreen::raiseFocus(void) {
1691   BlackboxWindow *focused = blackbox->getFocusedWindow();
1692   if (! focused)
1693     return;
1694
1695   // if on this Screen, raise it
1696   if (focused->getScreen()->getScreenNumber() == getScreenNumber()) {
1697     Workspace *workspace = getWorkspace(focused->getWorkspaceNumber());
1698     workspace->raiseWindow(focused);
1699   }
1700 }
1701
1702
1703 void BScreen::InitMenu(void) {
1704   if (rootmenu) {
1705     rootmenuList.clear();
1706
1707     while (rootmenu->getCount())
1708       rootmenu->remove(0);
1709   } else {
1710     rootmenu = new Rootmenu(this);
1711   }
1712   bool defaultMenu = True;
1713
1714   FILE *menu_file = (FILE *) 0;
1715   const char *menu_filename = blackbox->getMenuFilename();
1716
1717   if (menu_filename) 
1718     if (! (menu_file = fopen(menu_filename, "r")))
1719       perror(menu_filename);
1720   if (! menu_file) {     // opening the menu file failed, try the default menu
1721     menu_filename = DEFAULTMENU;
1722     if (! (menu_file = fopen(menu_filename, "r")))
1723       perror(menu_filename);
1724   } 
1725
1726   if (menu_file) {
1727     if (feof(menu_file)) {
1728       fprintf(stderr, i18n(ScreenSet, ScreenEmptyMenuFile,
1729                            "%s: Empty menu file"),
1730               menu_filename);
1731     } else {
1732       char line[1024], label[1024];
1733       memset(line, 0, 1024);
1734       memset(label, 0, 1024);
1735
1736       while (fgets(line, 1024, menu_file) && ! feof(menu_file)) {
1737         if (line[0] == '#')
1738           continue;
1739
1740         int i, key = 0, index = -1, len = strlen(line);
1741
1742         for (i = 0; i < len; i++) {
1743           if (line[i] == '[') index = 0;
1744           else if (line[i] == ']') break;
1745           else if (line[i] != ' ')
1746             if (index++ >= 0)
1747               key += tolower(line[i]);
1748         }
1749
1750         if (key == 517) { // [begin]
1751           index = -1;
1752           for (i = index; i < len; i++) {
1753             if (line[i] == '(') index = 0;
1754             else if (line[i] == ')') break;
1755             else if (index++ >= 0) {
1756               if (line[i] == '\\' && i < len - 1) i++;
1757               label[index - 1] = line[i];
1758             }
1759           }
1760
1761           if (index == -1) index = 0;
1762           label[index] = '\0';
1763
1764           rootmenu->setLabel(label);
1765           defaultMenu = parseMenuFile(menu_file, rootmenu);
1766           if (! defaultMenu)
1767             blackbox->addMenuTimestamp(menu_filename);
1768           break;
1769         }
1770       }
1771     }
1772     fclose(menu_file);
1773   }
1774
1775   if (defaultMenu) {
1776     rootmenu->setInternalMenu();
1777     rootmenu->insert(i18n(ScreenSet, Screenxterm, "xterm"),
1778                      BScreen::Execute,
1779                      i18n(ScreenSet, Screenxterm, "xterm"));
1780     rootmenu->insert(i18n(ScreenSet, ScreenRestart, "Restart"),
1781                      BScreen::Restart);
1782     rootmenu->insert(i18n(ScreenSet, ScreenExit, "Exit"),
1783                      BScreen::Exit);
1784     rootmenu->setLabel(i18n(BasemenuSet, BasemenuBlackboxMenu,
1785                             "Openbox Menu"));
1786   }
1787 }
1788
1789
1790 static
1791 void string_within(char begin, char end, const char *input, size_t length,
1792                    char *output) {
1793   bool parse = False;
1794   size_t index = 0;
1795
1796   for (size_t i = 0; i < length; ++i) {
1797     if (input[i] == begin) {
1798       parse = True;
1799     } else if (input[i] == end) {
1800       break;
1801     } else if (parse) {
1802       if (input[i] == '\\' && i < length - 1) i++;
1803       output[index++] = input[i];
1804     } 
1805   }
1806
1807   if (parse)
1808     output[index] = '\0';
1809   else
1810     output[0] = '\0';
1811 }
1812
1813
1814 bool BScreen::parseMenuFile(FILE *file, Rootmenu *menu) {
1815   char line[1024], keyword[1024], label[1024], command[1024];
1816   bool done = False;
1817
1818   while (! (done || feof(file))) {
1819     memset(line, 0, 1024);
1820     memset(label, 0, 1024);
1821     memset(command, 0, 1024);
1822
1823     if (! fgets(line, 1024, file))
1824       continue;
1825
1826     if (line[0] == '#') // comment, skip it
1827       continue;
1828
1829     size_t line_length = strlen(line);
1830     unsigned int key = 0;
1831
1832     // get the keyword enclosed in []'s
1833     string_within('[', ']', line, line_length, keyword);
1834
1835     if (keyword[0] == '\0') {  // no keyword, no menu entry
1836       continue;
1837     } else {
1838       size_t len = strlen(keyword);
1839       for (size_t i = 0; i < len; ++i) {
1840         if (keyword[i] != ' ')
1841           key += tolower(keyword[i]);
1842       }
1843     }
1844
1845     // get the label enclosed in ()'s
1846     string_within('(', ')', line, line_length, label);
1847
1848     // get the command enclosed in {}'s
1849     string_within('{', '}', line, line_length, command);
1850
1851     switch (key) {
1852     case 311: // end
1853       done = True;
1854
1855       break;
1856
1857     case 333: // nop
1858       if (! *label)
1859         label[0] = '\0';
1860       menu->insert(label);
1861
1862       break;
1863
1864     case 421: // exec
1865       if (! (*label && *command)) {
1866         fprintf(stderr, i18n(ScreenSet, ScreenEXECError,
1867                              "BScreen::parseMenuFile: [exec] error, "
1868                              "no menu label and/or command defined\n"));
1869         continue;
1870       }
1871
1872       menu->insert(label, BScreen::Execute, command);
1873
1874       break;
1875
1876     case 442: // exit
1877       if (! *label) {
1878         fprintf(stderr, i18n(ScreenSet, ScreenEXITError,
1879                              "BScreen::parseMenuFile: [exit] error, "
1880                              "no menu label defined\n"));
1881         continue;
1882       }
1883
1884       menu->insert(label, BScreen::Exit);
1885
1886       break;
1887
1888     case 561: { // style
1889       if (! (*label && *command)) {
1890         fprintf(stderr,
1891                 i18n(ScreenSet, ScreenSTYLEError,
1892                      "BScreen::parseMenuFile: [style] error, "
1893                      "no menu label and/or filename defined\n"));
1894         continue;
1895       }
1896
1897       string style = expandTilde(command);
1898
1899       menu->insert(label, BScreen::SetStyle, style.c_str());
1900     }
1901       break;
1902
1903     case 630: // config
1904       if (! *label) {
1905         fprintf(stderr, i18n(ScreenSet, ScreenCONFIGError,
1906                              "BScreen::parseMenufile: [config] error, "
1907                              "no label defined"));
1908         continue;
1909       }
1910
1911       menu->insert(label, configmenu);
1912
1913       break;
1914
1915     case 740: { // include
1916       if (! *label) {
1917         fprintf(stderr, i18n(ScreenSet, ScreenINCLUDEError,
1918                              "BScreen::parseMenuFile: [include] error, "
1919                              "no filename defined\n"));
1920         continue;
1921       }
1922
1923       string newfile = expandTilde(label);
1924       FILE *submenufile = fopen(newfile.c_str(), "r");
1925
1926       if (! submenufile) {
1927         perror(newfile.c_str());
1928         continue;
1929       }
1930
1931       struct stat buf;
1932       if (fstat(fileno(submenufile), &buf) ||
1933           ! S_ISREG(buf.st_mode)) {
1934         fprintf(stderr,
1935                 i18n(ScreenSet, ScreenINCLUDEErrorReg,
1936                      "BScreen::parseMenuFile: [include] error: "
1937                      "'%s' is not a regular file\n"), newfile.c_str());
1938         break;
1939       }
1940
1941       if (! feof(submenufile)) {
1942         if (! parseMenuFile(submenufile, menu))
1943           blackbox->addMenuTimestamp(newfile);
1944
1945         fclose(submenufile);
1946       }
1947     }
1948
1949       break;
1950
1951     case 767: { // submenu
1952       if (! *label) {
1953         fprintf(stderr, i18n(ScreenSet, ScreenSUBMENUError,
1954                              "BScreen::parseMenuFile: [submenu] error, "
1955                              "no menu label defined\n"));
1956         continue;
1957       }
1958
1959       Rootmenu *submenu = new Rootmenu(this);
1960
1961       if (*command)
1962         submenu->setLabel(command);
1963       else
1964         submenu->setLabel(label);
1965
1966       parseMenuFile(file, submenu);
1967       submenu->update();
1968       menu->insert(label, submenu);
1969       rootmenuList.push_back(submenu);
1970     }
1971
1972       break;
1973
1974     case 773: { // restart
1975       if (! *label) {
1976         fprintf(stderr, i18n(ScreenSet, ScreenRESTARTError,
1977                              "BScreen::parseMenuFile: [restart] error, "
1978                              "no menu label defined\n"));
1979         continue;
1980       }
1981
1982       if (*command)
1983         menu->insert(label, BScreen::RestartOther, command);
1984       else
1985         menu->insert(label, BScreen::Restart);
1986     }
1987
1988       break;
1989
1990     case 845: { // reconfig
1991       if (! *label) {
1992         fprintf(stderr,
1993                 i18n(ScreenSet, ScreenRECONFIGError,
1994                      "BScreen::parseMenuFile: [reconfig] error, "
1995                      "no menu label defined\n"));
1996         continue;
1997       }
1998
1999       menu->insert(label, BScreen::Reconfigure);
2000     }
2001
2002       break;
2003
2004     case 995:    // stylesdir
2005     case 1113: { // stylesmenu
2006       bool newmenu = ((key == 1113) ? True : False);
2007
2008       if (! *label || (! *command && newmenu)) {
2009         fprintf(stderr,
2010                 i18n(ScreenSet, ScreenSTYLESDIRError,
2011                      "BScreen::parseMenuFile: [stylesdir/stylesmenu]"
2012                      " error, no directory defined\n"));
2013         continue;
2014       }
2015
2016       char *directory = ((newmenu) ? command : label);
2017
2018       string stylesdir = expandTilde(directory);
2019
2020       struct stat statbuf;
2021
2022       if (stat(stylesdir.c_str(), &statbuf) == -1) {
2023         fprintf(stderr,
2024                 i18n(ScreenSet, ScreenSTYLESDIRErrorNoExist,
2025                      "BScreen::parseMenuFile: [stylesdir/stylesmenu]"
2026                      " error, %s does not exist\n"), stylesdir.c_str());
2027         continue;
2028       }
2029       if (! S_ISDIR(statbuf.st_mode)) {
2030         fprintf(stderr,
2031                 i18n(ScreenSet, ScreenSTYLESDIRErrorNotDir,
2032                      "BScreen::parseMenuFile:"
2033                      " [stylesdir/stylesmenu] error, %s is not a"
2034                      " directory\n"), stylesdir.c_str());
2035         continue;
2036       }
2037
2038       Rootmenu *stylesmenu;
2039
2040       if (newmenu)
2041         stylesmenu = new Rootmenu(this);
2042       else
2043         stylesmenu = menu;
2044
2045       DIR *d = opendir(stylesdir.c_str());
2046       struct dirent *p;
2047       std::vector<string> ls;
2048
2049       while((p = readdir(d)))
2050         ls.push_back(p->d_name);
2051
2052       closedir(d);
2053
2054       std::sort(ls.begin(), ls.end());
2055
2056       std::vector<string>::iterator it = ls.begin(),
2057         end = ls.end();
2058       for (; it != end; ++it) {
2059         const string& fname = *it;
2060
2061         if (fname[fname.size()-1] == '~')
2062           continue;
2063
2064         string style = stylesdir;
2065         style += '/';
2066         style += fname;
2067
2068         if (! stat(style.c_str(), &statbuf) && S_ISREG(statbuf.st_mode))
2069           stylesmenu->insert(fname, BScreen::SetStyle, style);
2070       }
2071
2072       stylesmenu->update();
2073
2074       if (newmenu) {
2075         stylesmenu->setLabel(label);
2076         menu->insert(label, stylesmenu);
2077         rootmenuList.push_back(stylesmenu);
2078       }
2079
2080       blackbox->addMenuTimestamp(stylesdir);
2081     }
2082       break;
2083
2084     case 1090: { // workspaces
2085       if (! *label) {
2086         fprintf(stderr,
2087                 i18n(ScreenSet, ScreenWORKSPACESError,
2088                      "BScreen:parseMenuFile: [workspaces] error, "
2089                      "no menu label defined\n"));
2090         continue;
2091       }
2092
2093       menu->insert(label, workspacemenu);
2094     }
2095       break;
2096     }
2097   }
2098
2099   return ((menu->getCount() == 0) ? True : False);
2100 }
2101
2102
2103 void BScreen::shutdown(void) {
2104   XSelectInput(blackbox->getXDisplay(), getRootWindow(), NoEventMask);
2105   XSync(blackbox->getXDisplay(), False);
2106
2107   while(! windowList.empty())
2108     unmanageWindow(windowList.front(), True);
2109
2110   slit->shutdown();
2111 }
2112
2113
2114 void BScreen::showPosition(int x, int y) {
2115   if (! geom_visible) {
2116     XMoveResizeWindow(blackbox->getXDisplay(), geom_window,
2117                       (getWidth() - geom_w) / 2,
2118                       (getHeight() - geom_h) / 2, geom_w, geom_h);
2119     XMapWindow(blackbox->getXDisplay(), geom_window);
2120     XRaiseWindow(blackbox->getXDisplay(), geom_window);
2121
2122     geom_visible = True;
2123   }
2124
2125   char label[1024];
2126
2127   sprintf(label, i18n(ScreenSet, ScreenPositionFormat,
2128                       "X: %4d x Y: %4d"), x, y);
2129
2130   XClearWindow(blackbox->getXDisplay(), geom_window);
2131
2132   resource.wstyle.font->drawString(geom_window,
2133                                    resource.bevel_width, resource.bevel_width,
2134                                    resource.wstyle.l_text_focus,
2135                                    label);
2136 }
2137
2138
2139 void BScreen::showGeometry(unsigned int gx, unsigned int gy) {
2140   if (! geom_visible) {
2141     XMoveResizeWindow(blackbox->getXDisplay(), geom_window,
2142                       (getWidth() - geom_w) / 2,
2143                       (getHeight() - geom_h) / 2, geom_w, geom_h);
2144     XMapWindow(blackbox->getXDisplay(), geom_window);
2145     XRaiseWindow(blackbox->getXDisplay(), geom_window);
2146
2147     geom_visible = True;
2148   }
2149
2150   char label[1024];
2151
2152   sprintf(label, i18n(ScreenSet, ScreenGeometryFormat,
2153                       "W: %4d x H: %4d"), gx, gy);
2154
2155   XClearWindow(blackbox->getXDisplay(), geom_window);
2156
2157   resource.wstyle.font->drawString(geom_window,
2158                                    resource.bevel_width, resource.bevel_width,
2159                                    resource.wstyle.l_text_focus,
2160                                    label);
2161 }
2162
2163
2164 void BScreen::hideGeometry(void) {
2165   if (geom_visible) {
2166     XUnmapWindow(blackbox->getXDisplay(), geom_window);
2167     geom_visible = False;
2168   }
2169 }
2170
2171
2172 void BScreen::addStrut(Strut *strut) {
2173   strutList.push_back(strut);
2174 }
2175
2176
2177 void BScreen::removeStrut(Strut *strut) {
2178   strutList.remove(strut);
2179 }
2180
2181
2182 const Rect& BScreen::availableArea(void) const {
2183   if (doFullMax())
2184     return getRect(); // return the full screen
2185   return usableArea;
2186 }
2187
2188
2189 #ifdef    XINERAMA
2190 const RectList& BScreen::allAvailableAreas(void) const {
2191   assert(isXineramaActive());
2192   assert(xineramaUsableArea.size() > 0);
2193   fprintf(stderr, "1found x %d y %d w %d h %d\n",
2194           xineramaUsableArea[0].x(), xineramaUsableArea[0].y(),
2195           xineramaUsableArea[0].width(), xineramaUsableArea[0].height());
2196   return xineramaUsableArea;
2197 }
2198 #endif // XINERAMA
2199
2200
2201 void BScreen::updateAvailableArea(void) {
2202   Rect old_area = usableArea;
2203   usableArea = getRect(); // reset to full screen
2204
2205 #ifdef    XINERAMA
2206   // reset to the full areas
2207   if (isXineramaActive())
2208     xineramaUsableArea = getXineramaAreas();
2209 #endif // XINERAMA
2210
2211   /* these values represent offsets from the screen edge
2212    * we look for the biggest offset on each edge and then apply them
2213    * all at once
2214    * do not be confused by the similarity to the names of Rect's members
2215    */
2216   unsigned int current_left = 0, current_right = 0, current_top = 0,
2217     current_bottom = 0;
2218
2219   StrutList::const_iterator it = strutList.begin(), end = strutList.end();
2220
2221   for(; it != end; ++it) {
2222     Strut *strut = *it;
2223     if (strut->left > current_left)
2224       current_left = strut->left;
2225     if (strut->top > current_top)
2226       current_top = strut->top;
2227     if (strut->right > current_right)
2228       current_right = strut->right;
2229     if (strut->bottom > current_bottom)
2230       current_bottom = strut->bottom;
2231   }
2232
2233   usableArea.setPos(current_left, current_top);
2234   usableArea.setSize(usableArea.width() - (current_left + current_right),
2235                      usableArea.height() - (current_top + current_bottom));
2236
2237 #ifdef    XINERAMA
2238   if (isXineramaActive()) {
2239     // keep each of the ximerama-defined areas inside the strut
2240     RectList::iterator xit, xend = xineramaUsableArea.end();
2241     for (xit = xineramaUsableArea.begin(); xit != xend; ++xit) {
2242       if (xit->x() < usableArea.x()) {
2243         xit->setX(usableArea.x());
2244         xit->setWidth(xit->width() - usableArea.x());
2245       }
2246       if (xit->y() < usableArea.y()) {
2247         xit->setY(usableArea.y());
2248         xit->setHeight(xit->height() - usableArea.y());
2249       }
2250       if (xit->x() + xit->width() > usableArea.width())
2251         xit->setWidth(usableArea.width() - xit->x());
2252       if (xit->y() + xit->height() > usableArea.height())
2253         xit->setHeight(usableArea.height() - xit->y());
2254     }
2255   }
2256 #endif // XINERAMA
2257
2258   if (old_area != usableArea) {
2259     BlackboxWindowList::iterator it = windowList.begin(),
2260       end = windowList.end();
2261     for (; it != end; ++it)
2262       if ((*it)->isMaximized()) (*it)->remaximize();
2263   }
2264
2265   updateWorkArea();  
2266 }
2267
2268
2269 Workspace* BScreen::getWorkspace(unsigned int index) {
2270   assert(index < workspacesList.size());
2271   return workspacesList[index];
2272 }
2273
2274
2275 void BScreen::buttonPressEvent(const XButtonEvent *xbutton) {
2276   if (xbutton->button == 1) {
2277     if (! isRootColormapInstalled())
2278       image_control->installRootColormap();
2279
2280     if (workspacemenu->isVisible())
2281       workspacemenu->hide();
2282
2283     if (rootmenu->isVisible())
2284       rootmenu->hide();
2285   } else if (xbutton->button == 2) {
2286     int mx = xbutton->x_root - (workspacemenu->getWidth() / 2);
2287     int my = xbutton->y_root - (workspacemenu->getTitleHeight() / 2);
2288
2289     if (mx < 0) mx = 0;
2290     if (my < 0) my = 0;
2291
2292     if (mx + workspacemenu->getWidth() > getWidth())
2293       mx = getWidth() - workspacemenu->getWidth() - getBorderWidth();
2294
2295     if (my + workspacemenu->getHeight() > getHeight())
2296       my = getHeight() - workspacemenu->getHeight() - getBorderWidth();
2297
2298     workspacemenu->move(mx, my);
2299
2300     if (! workspacemenu->isVisible()) {
2301       workspacemenu->removeParent();
2302       workspacemenu->show();
2303     }
2304   } else if (xbutton->button == 3) {
2305     int mx = xbutton->x_root - (rootmenu->getWidth() / 2);
2306     int my = xbutton->y_root - (rootmenu->getTitleHeight() / 2);
2307
2308     if (mx < 0) mx = 0;
2309     if (my < 0) my = 0;
2310
2311     if (mx + rootmenu->getWidth() > getWidth())
2312       mx = getWidth() - rootmenu->getWidth() - getBorderWidth();
2313
2314     if (my + rootmenu->getHeight() > getHeight())
2315       my = getHeight() - rootmenu->getHeight() - getBorderWidth();
2316
2317     rootmenu->move(mx, my);
2318
2319     if (! rootmenu->isVisible()) {
2320       blackbox->checkMenu();
2321       rootmenu->show();
2322     }
2323   // mouse wheel up
2324   } else if ((xbutton->button == 4 && resource.root_scroll == NormalScroll) ||
2325              (xbutton->button == 5 && resource.root_scroll == ReverseScroll)) {
2326     if (getCurrentWorkspaceID() >= getWorkspaceCount() - 1)
2327       changeWorkspaceID(0);
2328     else
2329       changeWorkspaceID(getCurrentWorkspaceID() + 1);
2330   // mouse wheel down
2331   } else if ((xbutton->button == 5 && resource.root_scroll == NormalScroll) ||
2332              (xbutton->button == 4 && resource.root_scroll == ReverseScroll)) {
2333     if (getCurrentWorkspaceID() == 0)
2334       changeWorkspaceID(getWorkspaceCount() - 1);
2335     else
2336       changeWorkspaceID(getCurrentWorkspaceID() - 1);
2337   }
2338 }
2339
2340
2341 void BScreen::propertyNotifyEvent(const XPropertyEvent *pe) {
2342   if (pe->atom == xatom->getAtom(XAtom::net_desktop_names)) {
2343     // _NET_WM_DESKTOP_NAMES
2344     WorkspaceList::iterator it = workspacesList.begin();
2345     const WorkspaceList::iterator end = workspacesList.end();
2346     for (; it != end; ++it) {
2347       (*it)->readName(); // re-read its name from the window property
2348       workspacemenu->changeWorkspaceLabel((*it)->getID(), (*it)->getName());
2349     }
2350     workspacemenu->update();
2351     toolbar->reconfigure();
2352     saveWorkspaceNames();
2353   }
2354 }
2355
2356
2357 void BScreen::toggleFocusModel(FocusModel model) {
2358   std::for_each(windowList.begin(), windowList.end(),
2359                 std::mem_fun(&BlackboxWindow::ungrabButtons));
2360
2361   if (model == SloppyFocus) {
2362     saveSloppyFocus(True);
2363   } else {
2364     // we're cheating here to save writing the config file 3 times
2365     resource.auto_raise = False;
2366     resource.click_raise = False;
2367     saveSloppyFocus(False);
2368   }
2369
2370   std::for_each(windowList.begin(), windowList.end(),
2371                 std::mem_fun(&BlackboxWindow::grabButtons));
2372 }
2373
2374
2375 BTexture BScreen::readDatabaseTexture(const string &rname,
2376                                       const string &default_color,
2377                                       const Configuration &style) {
2378   BTexture texture;
2379   string s;
2380
2381   if (style.getValue(rname, s))
2382     texture = BTexture(s);
2383   else
2384     texture.setTexture(BTexture::Solid | BTexture::Flat);
2385
2386   // associate this texture with this screen
2387   texture.setDisplay(getBaseDisplay(), getScreenNumber());
2388   texture.setImageControl(image_control);
2389
2390   if (texture.texture() & BTexture::Solid) {
2391     texture.setColor(readDatabaseColor(rname + ".color",
2392                                        default_color, style));
2393     texture.setColorTo(readDatabaseColor(rname + ".colorTo",
2394                                          default_color, style));
2395   } else if (texture.texture() & BTexture::Gradient) {
2396     texture.setColor(readDatabaseColor(rname + ".color",
2397                                        default_color, style));
2398     texture.setColorTo(readDatabaseColor(rname + ".colorTo",
2399                                          default_color, style));
2400   }
2401
2402   return texture;
2403 }
2404
2405
2406 BColor BScreen::readDatabaseColor(const string &rname,
2407                                   const string &default_color,
2408                                   const Configuration &style) {
2409   BColor color;
2410   string s;
2411   if (style.getValue(rname, s))
2412     color = BColor(s, getBaseDisplay(), getScreenNumber());
2413   else
2414     color = BColor(default_color, getBaseDisplay(), getScreenNumber());
2415   return color;
2416 }
2417
2418
2419 BFont *BScreen::readDatabaseFont(const string &rbasename,
2420                                  const Configuration &style) {
2421   string fontname;
2422
2423   string s;
2424
2425 #ifdef    XFT
2426   int i;
2427   if (style.getValue(rbasename + "xft.font", s) &&
2428       style.getValue(rbasename + "xft.size", i)) {
2429     string family = s;
2430     bool bold = False;
2431     bool italic = False;
2432     if (style.getValue(rbasename + "xft.flags", s)) {
2433       if (s.find("bold") != string::npos)
2434         bold = True;
2435       if (s.find("italic") != string::npos)
2436         italic = True;
2437     }
2438     
2439     BFont *b = new BFont(blackbox->getXDisplay(), this, family, i, bold,
2440                          italic, resource.aa_fonts);
2441     if (b->valid())
2442       return b;
2443     else
2444       delete b; // fall back to the normal X font stuff
2445   }
2446 #endif // XFT
2447
2448   style.getValue(rbasename + "font", s);
2449   // if this fails, a blank string will be used, which will cause the fallback
2450   // font to load.
2451
2452   BFont *b = new BFont(blackbox->getXDisplay(), this, s);
2453   if (! b->valid())
2454     exit(2);  // can't continue without a font
2455   return b;
2456 }