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