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