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