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