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