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