]> icculus.org git repositories - mikachu/openbox.git/blob - src/Screen.cc
add the functionality for window-window snapping
[mikachu/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   if (desktopWindowList.empty()) return;
1435
1436   XLowerWindow(blackbox->getXDisplay(), desktopWindowList[0]);
1437   if (desktopWindowList.size() > 1)
1438     XRestackWindows(blackbox->getXDisplay(), &desktopWindowList[0],
1439                     desktopWindowList.size());
1440 }
1441
1442
1443 void BScreen::addWorkspaceName(const string& name) {
1444   workspaceNames.push_back(name);
1445   updateDesktopNames();
1446 }
1447
1448
1449 void BScreen::updateDesktopNames(){
1450   XAtom::StringVect names;
1451
1452   WorkspaceList::iterator it = workspacesList.begin();
1453   const WorkspaceList::iterator end = workspacesList.end();
1454   for (; it != end; ++it)
1455     names.push_back((*it)->getName());
1456
1457   xatom->setValue(getRootWindow(), XAtom::net_desktop_names,
1458                   XAtom::utf8, names);
1459 }
1460
1461
1462 /*
1463  * I would love to kill this function and the accompanying workspaceNames
1464  * list.  However, we have a chicken and egg situation.  The names are read
1465  * in during load_rc() which happens before the workspaces are created.
1466  * The current solution is to read the names into a list, then use the list
1467  * later for constructing the workspaces.  It is only used during initial
1468  * BScreen creation.
1469  */
1470 const string BScreen::getNameOfWorkspace(unsigned int id) {
1471   if (id < workspaceNames.size())
1472     return workspaceNames[id];
1473   return string("");
1474 }
1475
1476
1477 void BScreen::reassociateWindow(BlackboxWindow *w, unsigned int wkspc_id,
1478                                 bool ignore_sticky) {
1479   if (! w) return;
1480
1481   if (wkspc_id == BSENTINEL)
1482     wkspc_id = current_workspace->getID();
1483
1484   if (w->getWorkspaceNumber() == wkspc_id)
1485     return;
1486
1487   if (w->isIconic()) {
1488     removeIcon(w);
1489     getWorkspace(wkspc_id)->addWindow(w);
1490   } else if (ignore_sticky || ! w->isStuck()) {
1491     getWorkspace(w->getWorkspaceNumber())->removeWindow(w);
1492     getWorkspace(wkspc_id)->addWindow(w);
1493   }
1494 }
1495
1496
1497 void BScreen::propagateWindowName(const BlackboxWindow *bw) {
1498   if (bw->isIconic()) {
1499     iconmenu->changeItemLabel(bw->getWindowNumber(), bw->getIconTitle());
1500     iconmenu->update();
1501   }
1502   else {
1503     Clientmenu *clientmenu = getWorkspace(bw->getWorkspaceNumber())->getMenu();
1504     clientmenu->changeItemLabel(bw->getWindowNumber(), bw->getTitle());
1505     clientmenu->update();
1506
1507     if (blackbox->getFocusedWindow() == bw)
1508       toolbar->redrawWindowLabel(True);
1509   }
1510 }
1511
1512
1513 void BScreen::nextFocus(void) {
1514   BlackboxWindow *focused = blackbox->getFocusedWindow(),
1515     *next = focused;
1516
1517   if (focused) {
1518     // if window is not on this screen, ignore it
1519     if (focused->getScreen()->getScreenNumber() != getScreenNumber())
1520       focused = (BlackboxWindow*) 0;
1521   }
1522
1523   if (focused && current_workspace->getCount() > 1) {
1524     // next is the next window to recieve focus, current is a place holder
1525     BlackboxWindow *current;
1526     do {
1527       current = next;
1528       next = current_workspace->getNextWindowInList(current);
1529     } while(! next->setInputFocus() && next != focused);
1530
1531     if (next != focused)
1532       current_workspace->raiseWindow(next);
1533   } else if (current_workspace->getCount() >= 1) {
1534     next = current_workspace->getTopWindowOnStack();
1535
1536     current_workspace->raiseWindow(next);
1537     next->setInputFocus();
1538   }
1539 }
1540
1541
1542 void BScreen::prevFocus(void) {
1543   BlackboxWindow *focused = blackbox->getFocusedWindow(),
1544     *next = focused;
1545
1546   if (focused) {
1547     // if window is not on this screen, ignore it
1548     if (focused->getScreen()->getScreenNumber() != getScreenNumber())
1549       focused = (BlackboxWindow*) 0;
1550   }
1551
1552   if (focused && current_workspace->getCount() > 1) {
1553     // next is the next window to recieve focus, current is a place holder
1554     BlackboxWindow *current;
1555     do {
1556       current = next;
1557       next = current_workspace->getPrevWindowInList(current);
1558     } while(! next->setInputFocus() && next != focused);
1559
1560     if (next != focused)
1561       current_workspace->raiseWindow(next);
1562   } else if (current_workspace->getCount() >= 1) {
1563     next = current_workspace->getTopWindowOnStack();
1564
1565     current_workspace->raiseWindow(next);
1566     next->setInputFocus();
1567   }
1568 }
1569
1570
1571 void BScreen::raiseFocus(void) {
1572   BlackboxWindow *focused = blackbox->getFocusedWindow();
1573   if (! focused)
1574     return;
1575
1576   // if on this Screen, raise it
1577   if (focused->getScreen()->getScreenNumber() == getScreenNumber()) {
1578     Workspace *workspace = getWorkspace(focused->getWorkspaceNumber());
1579     workspace->raiseWindow(focused);
1580   }
1581 }
1582
1583
1584 void BScreen::InitMenu(void) {
1585   if (rootmenu) {
1586     rootmenuList.clear();
1587
1588     while (rootmenu->getCount())
1589       rootmenu->remove(0);
1590   } else {
1591     rootmenu = new Rootmenu(this);
1592   }
1593   bool defaultMenu = True;
1594
1595   FILE *menu_file = (FILE *) 0;
1596   const char *menu_filename = blackbox->getMenuFilename();
1597
1598   if (menu_filename) 
1599     if (! (menu_file = fopen(menu_filename, "r")))
1600       perror(menu_filename);
1601   if (! menu_file) {     // opening the menu file failed, try the default menu
1602     menu_filename = DEFAULTMENU;
1603     if (! (menu_file = fopen(menu_filename, "r")))
1604       perror(menu_filename);
1605   } 
1606
1607   if (menu_file) {
1608     if (feof(menu_file)) {
1609       fprintf(stderr, i18n(ScreenSet, ScreenEmptyMenuFile,
1610                            "%s: Empty menu file"),
1611               menu_filename);
1612     } else {
1613       char line[1024], label[1024];
1614       memset(line, 0, 1024);
1615       memset(label, 0, 1024);
1616
1617       while (fgets(line, 1024, menu_file) && ! feof(menu_file)) {
1618         if (line[0] != '#') {
1619           int i, key = 0, index = -1, len = strlen(line);
1620
1621           for (i = 0; i < len; i++) {
1622             if (line[i] == '[') index = 0;
1623             else if (line[i] == ']') break;
1624             else if (line[i] != ' ')
1625               if (index++ >= 0)
1626                 key += tolower(line[i]);
1627           }
1628
1629           if (key == 517) { // [begin]
1630             index = -1;
1631             for (i = index; i < len; i++) {
1632               if (line[i] == '(') index = 0;
1633               else if (line[i] == ')') break;
1634               else if (index++ >= 0) {
1635                 if (line[i] == '\\' && i < len - 1) i++;
1636                 label[index - 1] = line[i];
1637               }
1638             }
1639
1640             if (index == -1) index = 0;
1641             label[index] = '\0';
1642
1643             rootmenu->setLabel(label);
1644             defaultMenu = parseMenuFile(menu_file, rootmenu);
1645             if (! defaultMenu)
1646               blackbox->addMenuTimestamp(menu_filename);
1647             break;
1648           }
1649         }
1650       }
1651     }
1652     fclose(menu_file);
1653   }
1654
1655   if (defaultMenu) {
1656     rootmenu->setInternalMenu();
1657     rootmenu->insert(i18n(ScreenSet, Screenxterm, "xterm"),
1658                      BScreen::Execute,
1659                      i18n(ScreenSet, Screenxterm, "xterm"));
1660     rootmenu->insert(i18n(ScreenSet, ScreenRestart, "Restart"),
1661                      BScreen::Restart);
1662     rootmenu->insert(i18n(ScreenSet, ScreenExit, "Exit"),
1663                      BScreen::Exit);
1664     rootmenu->setLabel(i18n(BasemenuSet, BasemenuBlackboxMenu,
1665                             "Openbox Menu"));
1666   }
1667 }
1668
1669
1670 bool BScreen::parseMenuFile(FILE *file, Rootmenu *menu) {
1671   char line[1024], label[1024], command[1024];
1672
1673   while (! feof(file)) {
1674     memset(line, 0, 1024);
1675     memset(label, 0, 1024);
1676     memset(command, 0, 1024);
1677
1678     if (fgets(line, 1024, file)) {
1679       if (line[0] != '#') {
1680         int i, key = 0, parse = 0, index = -1, line_length = strlen(line);
1681
1682         // determine the keyword
1683         for (i = 0; i < line_length; i++) {
1684           if (line[i] == '[') parse = 1;
1685           else if (line[i] == ']') break;
1686           else if (line[i] != ' ')
1687             if (parse)
1688               key += tolower(line[i]);
1689         }
1690
1691         // get the label enclosed in ()'s
1692         parse = 0;
1693
1694         for (i = 0; i < line_length; i++) {
1695           if (line[i] == '(') {
1696             index = 0;
1697             parse = 1;
1698           } else if (line[i] == ')') break;
1699           else if (index++ >= 0) {
1700             if (line[i] == '\\' && i < line_length - 1) i++;
1701             label[index - 1] = line[i];
1702           }
1703         }
1704
1705         if (parse) {
1706           label[index] = '\0';
1707         } else {
1708           label[0] = '\0';
1709         }
1710
1711         // get the command enclosed in {}'s
1712         parse = 0;
1713         index = -1;
1714         for (i = 0; i < line_length; i++) {
1715           if (line[i] == '{') {
1716             index = 0;
1717             parse = 1;
1718           } else if (line[i] == '}') break;
1719           else if (index++ >= 0) {
1720             if (line[i] == '\\' && i < line_length - 1) i++;
1721             command[index - 1] = line[i];
1722           }
1723         }
1724
1725         if (parse) {
1726           command[index] = '\0';
1727         } else {
1728           command[0] = '\0';
1729         }
1730
1731         switch (key) {
1732         case 311: // end
1733           return ((menu->getCount() == 0) ? True : False);
1734
1735           break;
1736
1737         case 333: // nop
1738           if (! *label)
1739             label[0] = '\0';
1740           menu->insert(label);
1741
1742           break;
1743
1744         case 421: // exec
1745           if ((! *label) && (! *command)) {
1746             fprintf(stderr, i18n(ScreenSet, ScreenEXECError,
1747                                  "BScreen::parseMenuFile: [exec] error, "
1748                                  "no menu label and/or command defined\n"));
1749             continue;
1750           }
1751
1752           menu->insert(label, BScreen::Execute, command);
1753
1754           break;
1755
1756         case 442: // exit
1757           if (! *label) {
1758             fprintf(stderr, i18n(ScreenSet, ScreenEXITError,
1759                                  "BScreen::parseMenuFile: [exit] error, "
1760                                  "no menu label defined\n"));
1761             continue;
1762           }
1763
1764           menu->insert(label, BScreen::Exit);
1765
1766           break;
1767
1768         case 561: // style
1769           {
1770             if ((! *label) || (! *command)) {
1771               fprintf(stderr,
1772                       i18n(ScreenSet, ScreenSTYLEError,
1773                            "BScreen::parseMenuFile: [style] error, "
1774                            "no menu label and/or filename defined\n"));
1775               continue;
1776             }
1777
1778             string style = expandTilde(command);
1779
1780             menu->insert(label, BScreen::SetStyle, style.c_str());
1781           }
1782
1783           break;
1784
1785         case 630: // config
1786           if (! *label) {
1787             fprintf(stderr, i18n(ScreenSet, ScreenCONFIGError,
1788                                  "BScreen::parseMenufile: [config] error, "
1789                                  "no label defined"));
1790             continue;
1791           }
1792
1793           menu->insert(label, configmenu);
1794
1795           break;
1796
1797         case 740: // include
1798           {
1799             if (! *label) {
1800               fprintf(stderr, i18n(ScreenSet, ScreenINCLUDEError,
1801                                    "BScreen::parseMenuFile: [include] error, "
1802                                    "no filename defined\n"));
1803               continue;
1804             }
1805
1806             string newfile = expandTilde(label);
1807             FILE *submenufile = fopen(newfile.c_str(), "r");
1808
1809             if (submenufile) {
1810               struct stat buf;
1811               if (fstat(fileno(submenufile), &buf) ||
1812                   (! S_ISREG(buf.st_mode))) {
1813                 fprintf(stderr,
1814                         i18n(ScreenSet, ScreenINCLUDEErrorReg,
1815                              "BScreen::parseMenuFile: [include] error: "
1816                              "'%s' is not a regular file\n"), newfile.c_str());
1817                 break;
1818               }
1819
1820               if (! feof(submenufile)) {
1821                 if (! parseMenuFile(submenufile, menu))
1822                   blackbox->addMenuTimestamp(newfile);
1823
1824                 fclose(submenufile);
1825               }
1826             } else {
1827               perror(newfile.c_str());
1828             }
1829           }
1830
1831           break;
1832
1833         case 767: // submenu
1834           {
1835             if (! *label) {
1836               fprintf(stderr, i18n(ScreenSet, ScreenSUBMENUError,
1837                                    "BScreen::parseMenuFile: [submenu] error, "
1838                                    "no menu label defined\n"));
1839               continue;
1840             }
1841
1842             Rootmenu *submenu = new Rootmenu(this);
1843
1844             if (*command)
1845               submenu->setLabel(command);
1846             else
1847               submenu->setLabel(label);
1848
1849             parseMenuFile(file, submenu);
1850             submenu->update();
1851             menu->insert(label, submenu);
1852             rootmenuList.push_back(submenu);
1853           }
1854
1855           break;
1856
1857         case 773: // restart
1858           {
1859             if (! *label) {
1860               fprintf(stderr, i18n(ScreenSet, ScreenRESTARTError,
1861                                    "BScreen::parseMenuFile: [restart] error, "
1862                                    "no menu label defined\n"));
1863               continue;
1864             }
1865
1866             if (*command)
1867               menu->insert(label, BScreen::RestartOther, command);
1868             else
1869               menu->insert(label, BScreen::Restart);
1870           }
1871
1872           break;
1873
1874         case 845: // reconfig
1875           {
1876             if (! *label) {
1877               fprintf(stderr,
1878                       i18n(ScreenSet, ScreenRECONFIGError,
1879                            "BScreen::parseMenuFile: [reconfig] error, "
1880                            "no menu label defined\n"));
1881               continue;
1882             }
1883
1884             menu->insert(label, BScreen::Reconfigure);
1885           }
1886
1887           break;
1888
1889         case 995: // stylesdir
1890         case 1113: // stylesmenu
1891           {
1892             bool newmenu = ((key == 1113) ? True : False);
1893
1894             if ((! *label) || ((! *command) && newmenu)) {
1895               fprintf(stderr,
1896                       i18n(ScreenSet, ScreenSTYLESDIRError,
1897                            "BScreen::parseMenuFile: [stylesdir/stylesmenu]"
1898                            " error, no directory defined\n"));
1899               continue;
1900             }
1901
1902             char *directory = ((newmenu) ? command : label);
1903
1904             string stylesdir = expandTilde(directory);
1905
1906             struct stat statbuf;
1907
1908             if (! stat(stylesdir.c_str(), &statbuf)) {
1909               if (S_ISDIR(statbuf.st_mode)) {
1910                 Rootmenu *stylesmenu;
1911
1912                 if (newmenu)
1913                   stylesmenu = new Rootmenu(this);
1914                 else
1915                   stylesmenu = menu;
1916
1917                 DIR *d = opendir(stylesdir.c_str());
1918                 struct dirent *p;
1919                 std::vector<string> ls;
1920
1921                 while((p = readdir(d)))
1922                   ls.push_back(p->d_name);
1923
1924                 closedir(d);
1925
1926                 std::sort(ls.begin(), ls.end());
1927
1928                 std::vector<string>::iterator it = ls.begin(),
1929                   end = ls.end();
1930                 for (; it != end; ++it) {
1931                   const string& fname = *it;
1932
1933                   if (fname[fname.size()-1] == '~')
1934                     continue;
1935
1936                   string style = stylesdir;
1937                   style += '/';
1938                   style += fname;
1939
1940                   if ((! stat(style.c_str(), &statbuf)) &&
1941                       S_ISREG(statbuf.st_mode))
1942                     stylesmenu->insert(fname, BScreen::SetStyle, style);
1943                 }
1944
1945                 stylesmenu->update();
1946
1947                 if (newmenu) {
1948                   stylesmenu->setLabel(label);
1949                   menu->insert(label, stylesmenu);
1950                   rootmenuList.push_back(stylesmenu);
1951                 }
1952
1953                 blackbox->addMenuTimestamp(stylesdir);
1954               } else {
1955                 fprintf(stderr,
1956                         i18n(ScreenSet, ScreenSTYLESDIRErrorNotDir,
1957                              "BScreen::parseMenuFile:"
1958                              " [stylesdir/stylesmenu] error, %s is not a"
1959                              " directory\n"), stylesdir.c_str());
1960               }
1961             } else {
1962               fprintf(stderr,
1963                       i18n(ScreenSet, ScreenSTYLESDIRErrorNoExist,
1964                            "BScreen::parseMenuFile: [stylesdir/stylesmenu]"
1965                            " error, %s does not exist\n"), stylesdir.c_str());
1966             }
1967             break;
1968           }
1969
1970         case 1090: // workspaces
1971           {
1972             if (! *label) {
1973               fprintf(stderr,
1974                       i18n(ScreenSet, ScreenWORKSPACESError,
1975                            "BScreen:parseMenuFile: [workspaces] error, "
1976                            "no menu label defined\n"));
1977               continue;
1978             }
1979
1980             menu->insert(label, workspacemenu);
1981
1982             break;
1983           }
1984         }
1985       }
1986     }
1987   }
1988
1989   return ((menu->getCount() == 0) ? True : False);
1990 }
1991
1992
1993 void BScreen::shutdown(void) {
1994   XSelectInput(blackbox->getXDisplay(), getRootWindow(), NoEventMask);
1995   XSync(blackbox->getXDisplay(), False);
1996
1997   while(! windowList.empty())
1998     unmanageWindow(windowList.front(), True);
1999
2000   slit->shutdown();
2001 }
2002
2003
2004 void BScreen::showPosition(int x, int y) {
2005   if (! geom_visible) {
2006     XMoveResizeWindow(blackbox->getXDisplay(), geom_window,
2007                       (getWidth() - geom_w) / 2,
2008                       (getHeight() - geom_h) / 2, geom_w, geom_h);
2009     XMapWindow(blackbox->getXDisplay(), geom_window);
2010     XRaiseWindow(blackbox->getXDisplay(), geom_window);
2011
2012     geom_visible = True;
2013   }
2014
2015   char label[1024];
2016
2017   sprintf(label, i18n(ScreenSet, ScreenPositionFormat,
2018                       "X: %4d x Y: %4d"), x, y);
2019
2020   XClearWindow(blackbox->getXDisplay(), geom_window);
2021
2022   BPen pen(resource.wstyle.l_text_focus, resource.wstyle.font);
2023   if (i18n.multibyte()) {
2024     XmbDrawString(blackbox->getXDisplay(), geom_window,
2025                   resource.wstyle.fontset, pen.gc(),
2026                   resource.bevel_width, resource.bevel_width -
2027                   resource.wstyle.fontset_extents->max_ink_extent.y,
2028                   label, strlen(label));
2029   } else {
2030     XDrawString(blackbox->getXDisplay(), geom_window,
2031                 pen.gc(), resource.bevel_width,
2032                 resource.wstyle.font->ascent + resource.bevel_width,
2033                 label, strlen(label));
2034   }
2035 }
2036
2037
2038 void BScreen::showGeometry(unsigned int gx, unsigned int gy) {
2039   if (! geom_visible) {
2040     XMoveResizeWindow(blackbox->getXDisplay(), geom_window,
2041                       (getWidth() - geom_w) / 2,
2042                       (getHeight() - geom_h) / 2, geom_w, geom_h);
2043     XMapWindow(blackbox->getXDisplay(), geom_window);
2044     XRaiseWindow(blackbox->getXDisplay(), geom_window);
2045
2046     geom_visible = True;
2047   }
2048
2049   char label[1024];
2050
2051   sprintf(label, i18n(ScreenSet, ScreenGeometryFormat,
2052                       "W: %4d x H: %4d"), gx, gy);
2053
2054   XClearWindow(blackbox->getXDisplay(), geom_window);
2055
2056   BPen pen(resource.wstyle.l_text_focus, resource.wstyle.font);
2057   if (i18n.multibyte()) {
2058     XmbDrawString(blackbox->getXDisplay(), geom_window,
2059                   resource.wstyle.fontset, pen.gc(),
2060                   resource.bevel_width, resource.bevel_width -
2061                   resource.wstyle.fontset_extents->max_ink_extent.y,
2062                   label, strlen(label));
2063   } else {
2064     XDrawString(blackbox->getXDisplay(), geom_window,
2065                 pen.gc(), resource.bevel_width,
2066                 resource.wstyle.font->ascent +
2067                 resource.bevel_width, label, strlen(label));
2068   }
2069 }
2070
2071
2072 void BScreen::hideGeometry(void) {
2073   if (geom_visible) {
2074     XUnmapWindow(blackbox->getXDisplay(), geom_window);
2075     geom_visible = False;
2076   }
2077 }
2078
2079
2080 void BScreen::addStrut(Strut *strut) {
2081   strutList.push_back(strut);
2082 }
2083
2084
2085 void BScreen::removeStrut(Strut *strut) {
2086   strutList.remove(strut);
2087 }
2088
2089
2090 const Rect& BScreen::availableArea(void) const {
2091   if (doFullMax())
2092     return getRect(); // return the full screen
2093   return usableArea;
2094 }
2095
2096
2097 void BScreen::updateAvailableArea(void) {
2098   Rect old_area = usableArea;
2099   usableArea = getRect(); // reset to full screen
2100
2101   /* these values represent offsets from the screen edge
2102    * we look for the biggest offset on each edge and then apply them
2103    * all at once
2104    * do not be confused by the similarity to the names of Rect's members
2105    */
2106   unsigned int current_left = 0, current_right = 0, current_top = 0,
2107     current_bottom = 0;
2108
2109   StrutList::const_iterator it = strutList.begin(), end = strutList.end();
2110
2111   for(; it != end; ++it) {
2112     Strut *strut = *it;
2113     if (strut->left > current_left)
2114       current_left = strut->left;
2115     if (strut->top > current_top)
2116       current_top = strut->top;
2117     if (strut->right > current_right)
2118       current_right = strut->right;
2119     if (strut->bottom > current_bottom)
2120       current_bottom = strut->bottom;
2121   }
2122
2123   usableArea.setPos(current_left, current_top);
2124   usableArea.setSize(usableArea.width() - (current_left + current_right),
2125                      usableArea.height() - (current_top + current_bottom));
2126
2127   if (old_area != usableArea) {
2128     BlackboxWindowList::iterator it = windowList.begin(),
2129       end = windowList.end();
2130     for (; it != end; ++it)
2131       if ((*it)->isMaximized()) (*it)->remaximize();
2132   }
2133
2134   updateWorkArea();  
2135 }
2136
2137
2138 Workspace* BScreen::getWorkspace(unsigned int index) {
2139   assert(index < workspacesList.size());
2140   return workspacesList[index];
2141 }
2142
2143
2144 void BScreen::buttonPressEvent(XButtonEvent *xbutton) {
2145   if (xbutton->button == 1) {
2146     if (! isRootColormapInstalled())
2147       image_control->installRootColormap();
2148
2149     if (workspacemenu->isVisible())
2150       workspacemenu->hide();
2151
2152     if (rootmenu->isVisible())
2153       rootmenu->hide();
2154   } else if (xbutton->button == 2) {
2155     int mx = xbutton->x_root - (workspacemenu->getWidth() / 2);
2156     int my = xbutton->y_root - (workspacemenu->getTitleHeight() / 2);
2157
2158     if (mx < 0) mx = 0;
2159     if (my < 0) my = 0;
2160
2161     if (mx + workspacemenu->getWidth() > getWidth())
2162       mx = getWidth() - workspacemenu->getWidth() - getBorderWidth();
2163
2164     if (my + workspacemenu->getHeight() > getHeight())
2165       my = getHeight() - workspacemenu->getHeight() - getBorderWidth();
2166
2167     workspacemenu->move(mx, my);
2168
2169     if (! workspacemenu->isVisible()) {
2170       workspacemenu->removeParent();
2171       workspacemenu->show();
2172     }
2173   } else if (xbutton->button == 3) {
2174     int mx = xbutton->x_root - (rootmenu->getWidth() / 2);
2175     int my = xbutton->y_root - (rootmenu->getTitleHeight() / 2);
2176
2177     if (mx < 0) mx = 0;
2178     if (my < 0) my = 0;
2179
2180     if (mx + rootmenu->getWidth() > getWidth())
2181       mx = getWidth() - rootmenu->getWidth() - getBorderWidth();
2182
2183     if (my + rootmenu->getHeight() > getHeight())
2184       my = getHeight() - rootmenu->getHeight() - getBorderWidth();
2185
2186     rootmenu->move(mx, my);
2187
2188     if (! rootmenu->isVisible()) {
2189       blackbox->checkMenu();
2190       rootmenu->show();
2191     }
2192   // mouse wheel up
2193   } else if (xbutton->button == 4) {
2194     if (getCurrentWorkspaceID() >= getWorkspaceCount() - 1)
2195       changeWorkspaceID(0);
2196     else
2197       changeWorkspaceID(getCurrentWorkspaceID() + 1);
2198   // mouse wheel down
2199   } else if (xbutton->button == 5) {
2200     if (getCurrentWorkspaceID() == 0)
2201       changeWorkspaceID(getWorkspaceCount() - 1);
2202     else
2203       changeWorkspaceID(getCurrentWorkspaceID() - 1);
2204   }
2205 }
2206
2207
2208 void BScreen::toggleFocusModel(FocusModel model) {
2209   if (model == SloppyFocus) {
2210     saveSloppyFocus(True);
2211   } else {
2212     saveSloppyFocus(False);
2213     saveAutoRaise(False);
2214     saveClickRaise(False);
2215   }
2216
2217   updateFocusModel();
2218 }
2219
2220
2221 void BScreen::updateFocusModel()
2222 {
2223   std::for_each(workspacesList.begin(), workspacesList.end(),
2224                 std::mem_fun(&Workspace::updateFocusModel));
2225 }
2226
2227
2228 BTexture BScreen::readDatabaseTexture(const string &rname,
2229                                       const string &default_color,
2230                                       Configuration &style) {
2231   BTexture texture;
2232   string s;
2233
2234   if (style.getValue(rname, s))
2235     texture = BTexture(s);
2236   else
2237     texture.setTexture(BTexture::Solid | BTexture::Flat);
2238
2239   // associate this texture with this screen
2240   texture.setDisplay(getBaseDisplay(), getScreenNumber());
2241   texture.setImageControl(image_control);
2242
2243   if (texture.texture() & BTexture::Solid) {
2244     texture.setColor(readDatabaseColor(rname + ".color",
2245                                        default_color, style));
2246     texture.setColorTo(readDatabaseColor(rname + ".colorTo",
2247                                          default_color, style));
2248   } else if (texture.texture() & BTexture::Gradient) {
2249     texture.setColor(readDatabaseColor(rname + ".color",
2250                                        default_color, style));
2251     texture.setColorTo(readDatabaseColor(rname + ".colorTo",
2252                                          default_color, style));
2253   }
2254
2255   return texture;
2256 }
2257
2258
2259 BColor BScreen::readDatabaseColor(const string &rname,
2260                                   const string &default_color,
2261                                   Configuration &style) {
2262   BColor color;
2263   string s;
2264   if (style.getValue(rname, s))
2265     color = BColor(s, getBaseDisplay(), getScreenNumber());
2266   else
2267     color = BColor(default_color, getBaseDisplay(), getScreenNumber());
2268   return color;
2269 }
2270
2271
2272 XFontSet BScreen::readDatabaseFontSet(const string &rname,
2273                                       Configuration &style) {
2274   char *defaultFont = "fixed";
2275
2276   bool load_default = True;
2277   string s;
2278   XFontSet fontset = 0;
2279   if (style.getValue(rname, s) && (fontset = createFontSet(s)))
2280     load_default = False;
2281
2282   if (load_default) {
2283     fontset = createFontSet(defaultFont);
2284
2285     if (! fontset) {
2286       fprintf(stderr,
2287               i18n(ScreenSet, ScreenDefaultFontLoadFail,
2288                    "BScreen::setCurrentStyle(): couldn't load default font.\n"));
2289       exit(2);
2290     }
2291   }
2292
2293   return fontset;
2294 }
2295
2296
2297 XFontStruct *BScreen::readDatabaseFont(const string &rname,
2298                                        Configuration &style) {
2299   char *defaultFont = "fixed";
2300
2301   bool load_default = False;
2302   string s;
2303   XFontStruct *font = 0;
2304   if (style.getValue(rname, s)) {
2305     if ((font = XLoadQueryFont(blackbox->getXDisplay(), s.c_str())) == NULL) {
2306       fprintf(stderr,
2307               i18n(ScreenSet, ScreenFontLoadFail,
2308                    "BScreen::setCurrentStyle(): couldn't load font '%s'\n"),
2309               s.c_str());
2310
2311       load_default = True;
2312     }
2313   } else {
2314     load_default = True;
2315   }
2316
2317   if (load_default) {
2318     font = XLoadQueryFont(blackbox->getXDisplay(), defaultFont);
2319     if (font == NULL) {
2320       fprintf(stderr,
2321               i18n(ScreenSet, ScreenDefaultFontLoadFail,
2322                    "BScreen::setCurrentStyle(): couldn't load default font.\n"));
2323       exit(2);
2324     }
2325   }
2326
2327   return font;
2328 }
2329
2330
2331 #ifndef    HAVE_STRCASESTR
2332 static const char * strcasestr(const char *str, const char *ptn) {
2333   const char *s2, *p2;
2334   for(; *str; str++) {
2335     for(s2=str,p2=ptn; ; s2++,p2++) {
2336       if (! *p2) return str;
2337       if (toupper(*s2) != toupper(*p2)) break;
2338     }
2339   }
2340   return NULL;
2341 }
2342 #endif // HAVE_STRCASESTR
2343
2344
2345 static const char *getFontElement(const char *pattern, char *buf,
2346                                   int bufsiz, ...) {
2347   const char *p, *v;
2348   char *p2;
2349   va_list va;
2350
2351   va_start(va, bufsiz);
2352   buf[bufsiz-1] = 0;
2353   buf[bufsiz-2] = '*';
2354   while((v = va_arg(va, char *)) != NULL) {
2355     p = strcasestr(pattern, v);
2356     if (p) {
2357       strncpy(buf, p+1, bufsiz-2);
2358       p2 = strchr(buf, '-');
2359       if (p2) *p2=0;
2360       va_end(va);
2361       return p;
2362     }
2363   }
2364   va_end(va);
2365   strncpy(buf, "*", bufsiz);
2366   return NULL;
2367 }
2368
2369
2370 static const char *getFontSize(const char *pattern, int *size) {
2371   const char *p;
2372   const char *p2=NULL;
2373   int n=0;
2374
2375   for (p=pattern; 1; p++) {
2376     if (! *p) {
2377       if (p2!=NULL && n>1 && n<72) {
2378         *size = n; return p2+1;
2379       } else {
2380         *size = 16; return NULL;
2381       }
2382     } else if (*p=='-') {
2383       if (n>1 && n<72 && p2!=NULL) {
2384         *size = n;
2385         return p2+1;
2386       }
2387       p2=p; n=0;
2388     } else if (*p>='0' && *p<='9' && p2!=NULL) {
2389       n *= 10;
2390       n += *p-'0';
2391     } else {
2392       p2=NULL; n=0;
2393     }
2394   }
2395 }
2396
2397
2398 XFontSet BScreen::createFontSet(const string &fontname) {
2399   XFontSet fs;
2400   char **missing, *def = "-";
2401   int nmissing, pixel_size = 0, buf_size = 0;
2402   char weight[FONT_ELEMENT_SIZE], slant[FONT_ELEMENT_SIZE];
2403
2404   fs = XCreateFontSet(blackbox->getXDisplay(),
2405                       fontname.c_str(), &missing, &nmissing, &def);
2406   if (fs && (! nmissing))
2407     return fs;
2408
2409   const char *nfontname = fontname.c_str();
2410 #ifdef    HAVE_SETLOCALE
2411   if (! fs) {
2412     if (nmissing) XFreeStringList(missing);
2413
2414     setlocale(LC_CTYPE, "C");
2415     fs = XCreateFontSet(blackbox->getXDisplay(), fontname.c_str(),
2416                         &missing, &nmissing, &def);
2417     setlocale(LC_CTYPE, "");
2418   }
2419 #endif // HAVE_SETLOCALE
2420
2421   if (fs) {
2422     XFontStruct **fontstructs;
2423     char **fontnames;
2424     XFontsOfFontSet(fs, &fontstructs, &fontnames);
2425     nfontname = fontnames[0];
2426   }
2427
2428   getFontElement(nfontname, weight, FONT_ELEMENT_SIZE,
2429                  "-medium-", "-bold-", "-demibold-", "-regular-", NULL);
2430   getFontElement(nfontname, slant, FONT_ELEMENT_SIZE,
2431                  "-r-", "-i-", "-o-", "-ri-", "-ro-", NULL);
2432   getFontSize(nfontname, &pixel_size);
2433
2434   if (! strcmp(weight, "*"))
2435     strncpy(weight, "medium", FONT_ELEMENT_SIZE);
2436   if (! strcmp(slant, "*"))
2437     strncpy(slant, "r", FONT_ELEMENT_SIZE);
2438   if (pixel_size < 3)
2439     pixel_size = 3;
2440   else if (pixel_size > 97)
2441     pixel_size = 97;
2442
2443   buf_size = strlen(nfontname) + (FONT_ELEMENT_SIZE * 2) + 64;
2444   char *pattern2 = new char[buf_size];
2445   sprintf(pattern2,
2446            "%s,"
2447            "-*-*-%s-%s-*-*-%d-*-*-*-*-*-*-*,"
2448            "-*-*-*-*-*-*-%d-*-*-*-*-*-*-*,*",
2449            nfontname, weight, slant, pixel_size, pixel_size);
2450   nfontname = pattern2;
2451
2452   if (nmissing)
2453     XFreeStringList(missing);
2454   if (fs)
2455     XFreeFontSet(blackbox->getXDisplay(), fs);
2456
2457   fs = XCreateFontSet(blackbox->getXDisplay(), nfontname, &missing,
2458                       &nmissing, &def);
2459
2460   delete [] pattern2;
2461
2462   return fs;
2463 }