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