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