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