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