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