]> icculus.org git repositories - dana/openbox.git/blob - src/screen.cc
add support for desktop layouts specified by pagers
[dana/openbox.git] / src / screen.cc
1 // -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 2; -*-
2
3 #include "config.h"
4
5 extern "C" {
6 #ifdef    HAVE_UNISTD_H
7 #  include <sys/types.h>
8 #  include <unistd.h>
9 #endif // HAVE_UNISTD_H
10
11 #include "gettext.h"
12 #define _(str) gettext(str)
13 }
14
15 #include "screen.hh"
16 #include "client.hh"
17 #include "openbox.hh"
18 #include "frame.hh"
19 #include "bindings.hh"
20 #include "python.hh"
21 #include "otk/display.hh"
22 #include "otk/property.hh"
23
24 #include <vector>
25 #include <algorithm>
26 #include <cstdio>
27 #include <cstring>
28
29 static bool running;
30 static int anotherWMRunning(Display *display, XErrorEvent *) {
31   printf(_("Another window manager already running on display %s.\n"),
32          DisplayString(display));
33   running = true;
34   return -1;
35 }
36
37
38 namespace ob {
39
40
41 Screen::Screen(int screen)
42   : _number(screen)
43 {
44   assert(screen >= 0); assert(screen < ScreenCount(**otk::display));
45   _info = otk::display->screenInfo(screen);
46
47   ::running = false;
48   XErrorHandler old = XSetErrorHandler(::anotherWMRunning);
49   XSelectInput(**otk::display, _info->rootWindow(),
50                Screen::event_mask);
51   XSync(**otk::display, false);
52   XSetErrorHandler(old);
53
54   _managed = !::running;
55   if (! _managed) return; // was unable to manage the screen
56
57 #ifdef DEBUG
58   printf(_("Managing screen %d: visual 0x%lx, depth %d\n"),
59          _number, XVisualIDFromVisual(_info->visual()), _info->depth());
60 #endif
61
62   otk::Property::set(_info->rootWindow(), otk::Property::atoms.openbox_pid,
63                      otk::Property::atoms.cardinal, (unsigned long) getpid());
64
65   // set the mouse cursor for the root window (the default cursor)
66   XDefineCursor(**otk::display, _info->rootWindow(),
67                 openbox->cursors().session);
68
69   // XXX: initialize the screen's style
70   /*
71   otk::ustring stylepath;
72   python_get_string("THEME", &stylepath);
73   otk::Configuration sconfig(false);
74   sconfig.setFile(otk::expandTilde(stylepath.c_str()));
75   if (!sconfig.load()) {
76     sconfig.setFile(otk::expandTilde(DEFAULTSTYLE));
77     if (!sconfig.load()) {
78       printf(_("Unable to load default style: %s. Aborting.\n"), DEFAULTSTYLE);
79       ::exit(1);
80     }
81   }
82   _style.load(sconfig);
83   */
84   otk::display->renderControl(_number)->
85     drawRoot(*otk::RenderStyle::style(_number)->rootColor());
86
87   // set up notification of netwm support
88   changeSupportedAtoms();
89
90   // Set the netwm properties for geometry
91   unsigned long geometry[] = { _info->size().width(),
92                                _info->size().height() };
93   otk::Property::set(_info->rootWindow(),
94                      otk::Property::atoms.net_desktop_geometry,
95                      otk::Property::atoms.cardinal, geometry, 2);
96
97   // Set the net_desktop_names property
98   std::vector<otk::ustring> names;
99   python_get_stringlist("DESKTOP_NAMES", &names);
100   otk::Property::set(_info->rootWindow(),
101                      otk::Property::atoms.net_desktop_names,
102                      otk::Property::utf8, names);
103   // the above set() will cause the updateDesktopNames to fire right away so
104   // we have a list of desktop names
105
106   _desktop = 0;
107   
108   if (!python_get_long("NUMBER_OF_DESKTOPS", (long*)&_num_desktops))
109     _num_desktops = 1;
110   changeNumDesktops(_num_desktops); // set the hint
111
112   changeDesktop(0); // set the hint
113
114   // create the window which gets focus when no clients get it
115   XSetWindowAttributes attr;
116   attr.override_redirect = true;
117   _focuswindow = XCreateWindow(**otk::display, _info->rootWindow(),
118                                -100, -100, 1, 1, 0, 0, InputOnly,
119                                _info->visual(), CWOverrideRedirect, &attr);
120   XMapRaised(**otk::display, _focuswindow);
121   
122   // these may be further updated if any pre-existing windows are found in
123   // the manageExising() function
124   changeClientList();  // initialize the client lists, which will be empty
125
126   updateDesktopLayout();
127
128   // register this class as the event handler for the root window
129   openbox->registerHandler(_info->rootWindow(), this);
130
131   // call the python Startup callbacks
132   EventData data(_number, 0, EventAction::Startup, 0);
133   openbox->bindings()->fireEvent(&data);
134 }
135
136
137 Screen::~Screen()
138 {
139   if (! _managed) return;
140
141   XSelectInput(**otk::display, _info->rootWindow(), NoEventMask);
142   
143   // unmanage all windows
144   while (!clients.empty())
145     unmanageWindow(clients.front());
146
147   // call the python Shutdown callbacks
148   EventData data(_number, 0, EventAction::Shutdown, 0);
149   openbox->bindings()->fireEvent(&data);
150
151   XDestroyWindow(**otk::display, _focuswindow);
152   XDestroyWindow(**otk::display, _supportwindow);
153 }
154
155
156 void Screen::manageExisting()
157 {
158   unsigned int i, j, nchild;
159   Window r, p, *children;
160   XQueryTree(**otk::display, _info->rootWindow(), &r, &p,
161              &children, &nchild);
162
163   // preen the window list of all icon windows... for better dockapp support
164   for (i = 0; i < nchild; i++) {
165     if (children[i] == None) continue;
166
167     XWMHints *wmhints = XGetWMHints(**otk::display,
168                                     children[i]);
169
170     if (wmhints) {
171       if ((wmhints->flags & IconWindowHint) &&
172           (wmhints->icon_window != children[i])) {
173         for (j = 0; j < nchild; j++) {
174           if (children[j] == wmhints->icon_window) {
175             children[j] = None;
176             break;
177           }
178         }
179       }
180
181       XFree(wmhints);
182     }
183   }
184
185   // manage shown windows
186   for (i = 0; i < nchild; ++i) {
187     if (children[i] == None)
188       continue;
189
190     XWindowAttributes attrib;
191     if (XGetWindowAttributes(**otk::display, children[i], &attrib)) {
192       if (attrib.override_redirect) continue;
193
194       if (attrib.map_state != IsUnmapped) {
195         manageWindow(children[i]);
196       }
197     }
198   }
199
200   XFree(children);
201 }
202
203 void Screen::updateDesktopLayout()
204 {
205   //const unsigned long _NET_WM_ORIENTATION_HORZ = 0;
206   const unsigned long _NET_WM_ORIENTATION_VERT = 1;
207   //const unsigned long _NET_WM_TOPLEFT = 0;
208   const unsigned long _NET_WM_TOPRIGHT = 1;
209   const unsigned long _NET_WM_BOTTOMRIGHT = 2;
210   const unsigned long _NET_WM_BOTTOMLEFT = 3;
211   
212   // defaults
213   _layout.orientation = DesktopLayout::Horizontal;
214   _layout.start_corner = DesktopLayout::TopLeft;
215   _layout.rows = 1;
216   _layout.columns = _num_desktops;
217
218   unsigned long *data, num = 4;
219   if (otk::Property::get(_info->rootWindow(),
220                          otk::Property::atoms.net_desktop_layout,
221                          otk::Property::atoms.cardinal,
222                          &num, &data)) {
223     if (num >= 4) {
224       if (data[0] == _NET_WM_ORIENTATION_VERT)
225         _layout.orientation = DesktopLayout::Vertical;
226       if (data[3] == _NET_WM_TOPRIGHT)
227         _layout.start_corner = DesktopLayout::TopRight;
228       else if (data[3] == _NET_WM_BOTTOMRIGHT)
229         _layout.start_corner = DesktopLayout::BottomRight;
230       else if (data[3] == _NET_WM_BOTTOMLEFT)
231         _layout.start_corner = DesktopLayout::BottomLeft;
232
233       // fill in a zero rows/columns
234       if (!(data[1] == 0 && data[2] == 0)) { // both 0's is bad data..
235         if (data[1] == 0) {
236           data[1] = (_num_desktops + _num_desktops % data[2]) / data[2];
237         } else if (data[2] == 0) {
238           data[2] = (_num_desktops + _num_desktops % data[1]) / data[1];
239         }
240         _layout.columns = data[1];
241         _layout.rows = data[2];
242       }
243
244       // bounds checking
245       if (_layout.orientation == DesktopLayout::Horizontal) {
246         if (_layout.rows > _num_desktops) _layout.rows = _num_desktops;
247         if (_layout.columns > (_num_desktops + _num_desktops % _layout.rows) /
248             _layout.rows)
249           _layout.columns = (_num_desktops + _num_desktops % _layout.rows) /
250             _layout.rows;
251       } else {
252         if (_layout.columns > _num_desktops) _layout.columns = _num_desktops;
253         if (_layout.rows > (_num_desktops + _num_desktops % _layout.columns) /
254             _layout.columns)
255           _layout.rows = (_num_desktops + _num_desktops % _layout.columns) /
256             _layout.columns;
257       }
258     }
259     delete [] data;
260   }
261 }
262
263 void Screen::updateStruts()
264 {
265   struct ApplyStrut {
266     void operator()(otk::Strut &self, const otk::Strut &other) {
267       self.left = std::max(self.left, other.left);
268       self.right = std::max(self.right, other.right);
269       self.top = std::max(self.top, other.top);
270       self.bottom = std::max(self.bottom, other.bottom);
271     }
272   } apply;
273
274   StrutList::iterator sit, send = _struts.end();
275   // reset them all
276   for (sit = _struts.begin(); sit != send; ++sit)
277     sit->left = sit->right = sit->top = sit->bottom = 0;
278
279   ClientList::const_iterator it, end = clients.end();
280   for (it = clients.begin(); it != end; ++it) {
281     if ((*it)->iconic()) continue; // these dont count in the strut
282     
283     unsigned int desk = (*it)->desktop();
284     const otk::Strut &s = (*it)->strut();
285
286     if (desk == 0xffffffff)
287       for (unsigned int i = 0, e = _struts.size(); i < e; ++i)
288         apply(_struts[i], s);
289     else if (desk < _struts.size())
290       apply(_struts[desk], s);
291     else
292       assert(false); // invalid desktop otherwise..
293     // apply to the 'all desktops' strut
294     apply(_struts.back(), s);
295   }
296   changeWorkArea();
297 }
298
299
300 void Screen::changeWorkArea()
301 {
302   unsigned long *dims = new unsigned long[4 * _num_desktops];
303   for (unsigned int i = 0; i < _num_desktops + 1; ++i) {
304     otk::Rect old_area = _area[i];
305 /*
306 #ifdef    XINERAMA
307   // reset to the full areas
308   if (isXineramaActive())
309     xineramaUsableArea = getXineramaAreas();
310 #endif // XINERAMA
311 */
312   
313     _area[i] = otk::Rect(_struts[i].left, _struts[i].top,
314                          _info->size().width() - (_struts[i].left +
315                                                   _struts[i].right),
316                          _info->size().height() - (_struts[i].top +
317                                                    _struts[i].bottom));
318     
319 /*
320 #ifdef    XINERAMA
321   if (isXineramaActive()) {
322     // keep each of the ximerama-defined areas inside the strut
323     RectList::iterator xit, xend = xineramaUsableArea.end();
324     for (xit = xineramaUsableArea.begin(); xit != xend; ++xit) {
325       if (xit->x() < usableArea.x()) {
326         xit->setX(usableArea.x());
327         xit->setWidth(xit->width() - usableArea.x());
328       }
329       if (xit->y() < usableArea.y()) {
330         xit->setY(usableArea.y());
331         xit->setHeight(xit->height() - usableArea.y());
332       }
333       if (xit->x() + xit->width() > usableArea.width())
334         xit->setWidth(usableArea.width() - xit->x());
335       if (xit->y() + xit->height() > usableArea.height())
336         xit->setHeight(usableArea.height() - xit->y());
337     }
338   }
339 #endif // XINERAMA
340 */
341     if (old_area != _area[i]) {
342       // the area has changed, adjust all the maximized windows
343       ClientList::iterator it, end = clients.end();
344       for (it = clients.begin(); it != end; ++it)
345         if (i < _num_desktops) {
346           if ((*it)->desktop() == i)
347             (*it)->remaximize();
348         } else {
349           // the 'all desktops' size
350           if ((*it)->desktop() == 0xffffffff)
351             (*it)->remaximize();
352         }
353     }
354
355     // don't set these for the 'all desktops' area
356     if (i < _num_desktops) {
357       dims[(i * 4) + 0] = _area[i].x();
358       dims[(i * 4) + 1] = _area[i].y();
359       dims[(i * 4) + 2] = _area[i].width();
360       dims[(i * 4) + 3] = _area[i].height();
361     }
362   }
363   otk::Property::set(_info->rootWindow(), otk::Property::atoms.net_workarea,
364                      otk::Property::atoms.cardinal, dims, 4 * _num_desktops);
365   delete [] dims;
366 }
367
368
369 void Screen::changeSupportedAtoms()
370 {
371   // create the netwm support window
372   _supportwindow = XCreateSimpleWindow(**otk::display,
373                                        _info->rootWindow(),
374                                        0, 0, 1, 1, 0, 0, 0);
375
376   // set supporting window
377   otk::Property::set(_info->rootWindow(),
378                      otk::Property::atoms.net_supporting_wm_check,
379                      otk::Property::atoms.window, _supportwindow);
380
381   //set properties on the supporting window
382   otk::Property::set(_supportwindow, otk::Property::atoms.net_wm_name,
383                      otk::Property::utf8, "Openbox");
384   otk::Property::set(_supportwindow,
385                      otk::Property::atoms.net_supporting_wm_check,
386                      otk::Property::atoms.window, _supportwindow);
387
388   
389   Atom supported[] = {
390     otk::Property::atoms.net_current_desktop,
391     otk::Property::atoms.net_number_of_desktops,
392     otk::Property::atoms.net_desktop_geometry,
393     otk::Property::atoms.net_desktop_viewport,
394     otk::Property::atoms.net_active_window,
395     otk::Property::atoms.net_workarea,
396     otk::Property::atoms.net_client_list,
397     otk::Property::atoms.net_client_list_stacking,
398     otk::Property::atoms.net_desktop_names,
399     otk::Property::atoms.net_close_window,
400     otk::Property::atoms.net_wm_name,
401     otk::Property::atoms.net_wm_visible_name,
402     otk::Property::atoms.net_wm_icon_name,
403     otk::Property::atoms.net_wm_visible_icon_name,
404 /*
405     otk::Property::atoms.net_wm_desktop,
406 */
407     otk::Property::atoms.net_wm_strut,
408     otk::Property::atoms.net_wm_window_type,
409     otk::Property::atoms.net_wm_window_type_desktop,
410     otk::Property::atoms.net_wm_window_type_dock,
411     otk::Property::atoms.net_wm_window_type_toolbar,
412     otk::Property::atoms.net_wm_window_type_menu,
413     otk::Property::atoms.net_wm_window_type_utility,
414     otk::Property::atoms.net_wm_window_type_splash,
415     otk::Property::atoms.net_wm_window_type_dialog,
416     otk::Property::atoms.net_wm_window_type_normal,
417 /*
418     otk::Property::atoms.net_wm_moveresize,
419     otk::Property::atoms.net_wm_moveresize_size_topleft,
420     otk::Property::atoms.net_wm_moveresize_size_topright,
421     otk::Property::atoms.net_wm_moveresize_size_bottomleft,
422     otk::Property::atoms.net_wm_moveresize_size_bottomright,
423     otk::Property::atoms.net_wm_moveresize_move,
424 */
425     otk::Property::atoms.net_wm_allowed_actions,
426     otk::Property::atoms.net_wm_action_move,
427     otk::Property::atoms.net_wm_action_resize,
428     otk::Property::atoms.net_wm_action_minimize,
429     otk::Property::atoms.net_wm_action_shade,
430 /*    otk::Property::atoms.net_wm_action_stick,*/
431     otk::Property::atoms.net_wm_action_maximize_horz,
432     otk::Property::atoms.net_wm_action_maximize_vert,
433     otk::Property::atoms.net_wm_action_fullscreen,
434     otk::Property::atoms.net_wm_action_change_desktop,
435     otk::Property::atoms.net_wm_action_close,
436
437     otk::Property::atoms.net_wm_state,
438     otk::Property::atoms.net_wm_state_modal,
439     otk::Property::atoms.net_wm_state_maximized_vert,
440     otk::Property::atoms.net_wm_state_maximized_horz,
441     otk::Property::atoms.net_wm_state_shaded,
442     otk::Property::atoms.net_wm_state_skip_taskbar,
443     otk::Property::atoms.net_wm_state_skip_pager,
444     otk::Property::atoms.net_wm_state_hidden,
445     otk::Property::atoms.net_wm_state_fullscreen,
446     otk::Property::atoms.net_wm_state_above,
447     otk::Property::atoms.net_wm_state_below,
448   };
449   const int num_supported = sizeof(supported)/sizeof(Atom);
450
451   otk::Property::set(_info->rootWindow(), otk::Property::atoms.net_supported,
452                      otk::Property::atoms.atom, supported, num_supported);
453 }
454
455
456 void Screen::changeClientList()
457 {
458   Window *windows;
459   unsigned int size = clients.size();
460
461   // create an array of the window ids
462   if (size > 0) {
463     Window *win_it;
464     
465     windows = new Window[size];
466     win_it = windows;
467     ClientList::const_iterator it = clients.begin();
468     const ClientList::const_iterator end = clients.end();
469     for (; it != end; ++it, ++win_it)
470       *win_it = (*it)->window();
471   } else
472     windows = (Window*) 0;
473
474   otk::Property::set(_info->rootWindow(), otk::Property::atoms.net_client_list,
475                      otk::Property::atoms.window, windows, size);
476
477   if (size)
478     delete [] windows;
479
480   changeStackingList();
481 }
482
483
484 void Screen::changeStackingList()
485 {
486   Window *windows;
487   unsigned int size = _stacking.size();
488
489   assert(size == clients.size()); // just making sure.. :)
490
491   
492   // create an array of the window ids (from bottom to top, reverse order!)
493   if (size > 0) {
494     Window *win_it;
495     
496     windows = new Window[size];
497     win_it = windows;
498     ClientList::const_reverse_iterator it = _stacking.rbegin();
499     const ClientList::const_reverse_iterator end = _stacking.rend();
500     for (; it != end; ++it, ++win_it)
501       *win_it = (*it)->window();
502   } else
503     windows = (Window*) 0;
504
505   otk::Property::set(_info->rootWindow(),
506                      otk::Property::atoms.net_client_list_stacking,
507                      otk::Property::atoms.window, windows, size);
508
509   if (size)
510     delete [] windows;
511 }
512
513
514 void Screen::manageWindow(Window window)
515 {
516   Client *client = 0;
517   XWMHints *wmhint;
518   XSetWindowAttributes attrib_set;
519   XEvent e;
520   XWindowAttributes attrib;
521
522   otk::display->grab();
523
524   // check if it has already been unmapped by the time we started mapping
525   // the grab does a sync so we don't have to here
526   if (XCheckTypedWindowEvent(**otk::display, window, DestroyNotify, &e) ||
527       XCheckTypedWindowEvent(**otk::display, window, UnmapNotify, &e)) {
528     XPutBackEvent(**otk::display, &e);
529     
530     otk::display->ungrab();
531     return; // don't manage it
532   }
533   
534   if (!XGetWindowAttributes(**otk::display, window, &attrib) ||
535       attrib.override_redirect) {
536     otk::display->ungrab();
537     return; // don't manage it
538   }
539   
540   // is the window a docking app
541   if ((wmhint = XGetWMHints(**otk::display, window))) {
542     if ((wmhint->flags & StateHint) &&
543         wmhint->initial_state == WithdrawnState) {
544       //slit->addClient(w); // XXX: make dock apps work!
545
546       otk::display->ungrab();
547       XFree(wmhint);
548       return;
549     }
550     XFree(wmhint);
551   }
552
553   // choose the events we want to receive on the CLIENT window
554   attrib_set.event_mask = Client::event_mask;
555   attrib_set.do_not_propagate_mask = Client::no_propagate_mask;
556   XChangeWindowAttributes(**otk::display, window,
557                           CWEventMask|CWDontPropagate, &attrib_set);
558
559   // create the Client class, which gets all of the hints on the window
560   client = new Client(_number, window);
561   // register for events
562   openbox->registerHandler(window, client);
563   // add to the wm's map
564   openbox->addClient(window, client);
565
566   // we dont want a border on the client
567   client->toggleClientBorder(false);
568   
569   // specify that if we exit, the window should not be destroyed and should be
570   // reparented back to root automatically
571   XChangeSaveSet(**otk::display, window, SetModeInsert);
572
573   // create the decoration frame for the client window
574   client->frame = new Frame(client);
575   // register the plate for events (map req's)
576   // this involves removing itself from the handler list first, since it is
577   // auto added to the list, being a widget. we won't get any events on the
578   // plate except for events for the client (SubstructureRedirectMask)
579   openbox->clearHandler(client->frame->plate());
580   openbox->registerHandler(client->frame->plate(), client);
581
582   // add to the wm's map
583   Window *w = client->frame->allWindows();
584   for (unsigned int i = 0; w[i]; ++i)
585     openbox->addClient(w[i], client);
586   delete [] w;
587
588   // reparent the client to the frame
589   client->frame->grabClient();
590
591   if (openbox->state() != Openbox::State_Starting) {
592     // position the window intelligenty .. hopefully :)
593     // call the python PLACEWINDOW binding
594     EventData data(_number, client, EventAction::PlaceWindow, 0);
595     openbox->bindings()->fireEvent(&data);
596   }
597
598   EventData ddata(_number, client, EventAction::DisplayingWindow, 0);
599   openbox->bindings()->fireEvent(&ddata);
600
601   client->showhide();
602
603   client->applyStartupState();
604
605   otk::display->ungrab();
606
607   // add to the screen's list
608   clients.push_back(client);
609   // once the client is in the list, update our strut to include the new
610   // client's (it is good that this happens after window placement!)
611   updateStruts();
612   // this puts into the stacking order, then raises it
613   _stacking.push_back(client);
614   raiseWindow(client);
615   // update the root properties
616   changeClientList();
617
618   openbox->bindings()->grabButtons(true, client);
619
620   EventData ndata(_number, client, EventAction::NewWindow, 0);
621   openbox->bindings()->fireEvent(&ndata);
622
623 #ifdef DEBUG
624   printf("Managed window 0x%lx frame 0x%lx\n",
625          window, client->frame->window());
626 #endif
627 }
628
629
630 void Screen::unmanageWindow(Client *client)
631 {
632   Frame *frame = client->frame;
633
634   // call the python CLOSEWINDOW binding 
635   EventData data(_number, client, EventAction::CloseWindow, 0);
636   openbox->bindings()->fireEvent(&data);
637
638   openbox->bindings()->grabButtons(false, client);
639
640   // remove from the wm's map
641   openbox->removeClient(client->window());
642   Window *w = frame->allWindows();
643   for (unsigned int i = 0; w[i]; ++i)
644     openbox->addClient(w[i], client);
645   delete [] w;
646   // unregister for handling events
647   openbox->clearHandler(client->window());
648   
649   // remove the window from our save set
650   XChangeSaveSet(**otk::display, client->window(), SetModeDelete);
651
652   // we dont want events no more
653   XSelectInput(**otk::display, client->window(), NoEventMask);
654
655   frame->hide();
656
657   // give the client its border back
658   client->toggleClientBorder(true);
659
660   // reparent the window out of the frame
661   frame->releaseClient();
662
663 #ifdef DEBUG
664   Window framewin = client->frame->window();
665 #endif
666   delete client->frame;
667   client->frame = 0;
668
669   // remove from the stacking order
670   _stacking.remove(client);
671
672   // remove from the screen's list
673   clients.remove(client);
674
675   // once the client is out of the list, update our strut to remove it's
676   // influence
677   updateStruts();
678
679   // unset modal before dropping our focus
680   client->_modal = false;
681   
682   // unfocus the client (calls the focus callbacks)
683   client->unfocus();
684
685 #ifdef DEBUG
686   printf("Unmanaged window 0x%lx frame 0x%lx\n", client->window(), framewin);
687 #endif
688   
689   delete client;
690
691   // update the root properties
692   changeClientList();
693 }
694
695 void Screen::lowerWindow(Client *client)
696 {
697   Window wins[2];  // only ever restack 2 windows.
698
699   assert(!_stacking.empty()); // this would be bad
700
701   ClientList::iterator it = --_stacking.end();
702   const ClientList::iterator end = _stacking.begin();
703
704   if (client->modal() && client->transientFor()) {
705     // don't let a modal window lower below its transient_for
706     it = std::find(_stacking.begin(), _stacking.end(), client->transientFor());
707     assert(it != _stacking.end());
708
709     wins[0] = (it == _stacking.begin() ? _focuswindow :
710                ((*(--ClientList::const_iterator(it)))->frame->window()));
711     wins[1] = client->frame->window();
712     if (wins[0] == wins[1]) return; // already right above the window
713
714     _stacking.remove(client);
715     _stacking.insert(it, client);
716   } else {
717     for (; it != end && (*it)->layer() < client->layer(); --it);
718     if (*it == client) return;          // already the bottom, return
719
720     wins[0] = (*it)->frame->window();
721     wins[1] = client->frame->window();
722
723     _stacking.remove(client);
724     _stacking.insert(++it, client);
725   }
726
727   XRestackWindows(**otk::display, wins, 2);
728   changeStackingList();
729 }
730
731 void Screen::raiseWindow(Client *client)
732 {
733   Window wins[2];  // only ever restack 2 windows.
734
735   assert(!_stacking.empty()); // this would be bad
736
737   Client *m = client->findModalChild();
738   // if we have a modal child, raise it instead, we'll go along tho later
739   if (m) raiseWindow(m);
740   
741   // remove the client before looking so we can't run into ourselves
742   _stacking.remove(client);
743   
744   ClientList::iterator it = _stacking.begin();
745   const ClientList::iterator end = _stacking.end();
746
747   // the stacking list is from highest to lowest
748 //  for (;it != end, ++it) {
749 //    if ((*it)->layer() <= client->layer() && m != *it) break;
750 //  }
751   for (; it != end && ((*it)->layer() > client->layer() || m == *it); ++it);
752
753   /*
754     if our new position is the top, we want to stack under the _focuswindow
755     otherwise, we want to stack under the previous window in the stack.
756   */
757   wins[0] = (it == _stacking.begin() ? _focuswindow :
758              ((*(--ClientList::const_iterator(it)))->frame->window()));
759   wins[1] = client->frame->window();
760
761   _stacking.insert(it, client);
762
763   XRestackWindows(**otk::display, wins, 2);
764
765   changeStackingList(); 
766 }
767
768 void Screen::changeDesktop(unsigned int desktop)
769 {
770   if (desktop >= _num_desktops) return;
771
772   printf("Moving to desktop %u\n", desktop);
773   
774   unsigned int old = _desktop;
775   
776   _desktop = desktop;
777   otk::Property::set(_info->rootWindow(),
778                      otk::Property::atoms.net_current_desktop,
779                      otk::Property::atoms.cardinal, _desktop);
780
781   if (old == _desktop) return;
782
783   ClientList::iterator it, end = clients.end();
784   for (it = clients.begin(); it != end; ++it)
785     (*it)->showhide();
786
787   // force the callbacks to fire
788   if (!openbox->focusedClient())
789     openbox->setFocusedClient(0);
790 }
791
792 void Screen::changeNumDesktops(unsigned int num)
793 {
794   assert(num > 0);
795   
796   if (!(num > 0)) return;
797
798   // move windows on desktops that will no longer exist!
799   ClientList::iterator it, end = clients.end();
800   for (it = clients.begin(); it != end; ++it) {
801     unsigned int d = (*it)->desktop();
802     if (d >= num && d != 0xffffffff) {
803       XEvent ce;
804       ce.xclient.type = ClientMessage;
805       ce.xclient.message_type = otk::Property::atoms.net_wm_desktop;
806       ce.xclient.display = **otk::display;
807       ce.xclient.window = (*it)->window();
808       ce.xclient.format = 32;
809       ce.xclient.data.l[0] = num - 1;
810       XSendEvent(**otk::display, _info->rootWindow(), False,
811                  SubstructureNotifyMask | SubstructureRedirectMask, &ce);
812     }
813   }
814
815   _num_desktops = num;
816   otk::Property::set(_info->rootWindow(),
817                      otk::Property::atoms.net_number_of_desktops,
818                      otk::Property::atoms.cardinal, _num_desktops);
819
820   // set the viewport hint
821   unsigned long *viewport = new unsigned long[_num_desktops * 2];
822   memset(viewport, 0, sizeof(unsigned long) * _num_desktops * 2);
823   otk::Property::set(_info->rootWindow(),
824                      otk::Property::atoms.net_desktop_viewport,
825                      otk::Property::atoms.cardinal,
826                      viewport, _num_desktops * 2);
827   delete [] viewport;
828
829   // change our struts/area to match
830   _area.resize(_num_desktops + 1);
831   _struts.resize(_num_desktops + 1);
832   updateStruts();
833
834   // the number of rows/columns will differ
835   updateDesktopLayout();
836
837   // change our desktop if we're on one that no longer exists!
838   if (_desktop >= _num_desktops)
839     changeDesktop(_num_desktops - 1);
840 }
841
842
843 void Screen::updateDesktopNames()
844 {
845   unsigned long num = (unsigned) -1;
846   
847   if (!otk::Property::get(_info->rootWindow(),
848                           otk::Property::atoms.net_desktop_names,
849                           otk::Property::utf8, &num, &_desktop_names))
850     _desktop_names.clear();
851   while (_desktop_names.size() < _num_desktops)
852     _desktop_names.push_back("Unnamed");
853 }
854
855
856 void Screen::setDesktopName(unsigned int i, const otk::ustring &name)
857 {
858   if (i >= _num_desktops) return;
859
860   otk::Property::StringVect newnames = _desktop_names;
861   newnames[i] = name;
862   otk::Property::set(_info->rootWindow(),
863                      otk::Property::atoms.net_desktop_names,
864                      otk::Property::utf8, newnames);
865 }
866
867
868 const otk::Rect& Screen::area(unsigned int desktop) const {
869   assert(desktop < _num_desktops || desktop == 0xffffffff);
870   if (desktop < _num_desktops)
871     return _area[desktop];
872   else
873     return _area[_num_desktops];
874 }
875
876 void Screen::installColormap(bool install) const
877 {
878   if (install)
879     XInstallColormap(**otk::display, _info->colormap());
880   else
881     XUninstallColormap(**otk::display, _info->colormap());
882 }
883
884
885 void Screen::propertyHandler(const XPropertyEvent &e)
886 {
887   otk::EventHandler::propertyHandler(e);
888
889   // compress changes to a single property into a single change
890   XEvent ce;
891   while (XCheckTypedWindowEvent(**otk::display, _info->rootWindow(),
892                                 e.type, &ce)) {
893     // XXX: it would be nice to compress ALL changes to a property, not just
894     //      changes in a row without other props between.
895     if (ce.xproperty.atom != e.atom) {
896       XPutBackEvent(**otk::display, &ce);
897       break;
898     }
899   }
900
901   if (e.atom == otk::Property::atoms.net_desktop_names)
902     updateDesktopNames();
903   else if (e.atom == otk::Property::atoms.net_desktop_layout)
904     updateDesktopLayout();
905 }
906
907
908 void Screen::clientMessageHandler(const XClientMessageEvent &e)
909 {
910   otk::EventHandler::clientMessageHandler(e);
911
912   if (e.format != 32) return;
913
914   if (e.message_type == otk::Property::atoms.net_current_desktop) {
915     changeDesktop(e.data.l[0]);
916   } else if (e.message_type == otk::Property::atoms.net_number_of_desktops) {
917     changeNumDesktops(e.data.l[0]);
918   }
919 }
920
921
922 void Screen::mapRequestHandler(const XMapRequestEvent &e)
923 {
924   otk::EventHandler::mapRequestHandler(e);
925
926 #ifdef    DEBUG
927   printf("MapRequest for 0x%lx\n", e.window);
928 #endif // DEBUG
929
930   Client *c = openbox->findClient(e.window);
931   if (c) {
932 #ifdef DEBUG
933     printf("DEBUG: MAP REQUEST CAUGHT IN SCREEN. IGNORED.\n");
934 #endif
935   } else
936     manageWindow(e.window);
937 }
938
939 }