better focusing. support for the take_focus protocol
[mikachu/openbox.git] / src / screen.cc
1 // -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 2; -*-
2
3 #ifdef HAVE_CONFIG_H
4 # include "../config.h"
5 #endif
6
7 extern "C" {
8 #ifdef    HAVE_STDIO_H
9 #  include <stdio.h>
10 #endif // HAVE_STDIO_H
11
12 #ifdef    HAVE_UNISTD_H
13 #  include <sys/types.h>
14 #  include <unistd.h>
15 #endif // HAVE_UNISTD_H
16
17 #include "gettext.h"
18 #define _(str) gettext(str)
19 }
20
21 #include "screen.hh"
22 #include "client.hh"
23 #include "openbox.hh"
24 #include "frame.hh"
25 #include "bindings.hh"
26 #include "python.hh"
27 #include "otk/display.hh"
28
29 #include <vector>
30
31 static bool running;
32 static int anotherWMRunning(Display *display, XErrorEvent *) {
33   printf(_("Another window manager already running on display %s.\n"),
34          DisplayString(display));
35   running = true;
36   return -1;
37 }
38
39
40 namespace ob {
41
42
43 OBScreen::OBScreen(int screen)
44   : _number(screen),
45     _root(screen)
46 {
47   assert(screen >= 0); assert(screen < ScreenCount(otk::OBDisplay::display));
48   _info = otk::OBDisplay::screenInfo(screen);
49
50   ::running = false;
51   XErrorHandler old = XSetErrorHandler(::anotherWMRunning);
52   XSelectInput(otk::OBDisplay::display, _info->rootWindow(),
53                OBScreen::event_mask);
54   XSync(otk::OBDisplay::display, false);
55   XSetErrorHandler(old);
56
57   _managed = !::running;
58   if (! _managed) return; // was unable to manage the screen
59
60   printf(_("Managing screen %d: visual 0x%lx, depth %d\n"),
61          _number, XVisualIDFromVisual(_info->visual()), _info->depth());
62
63   Openbox::instance->property()->set(_info->rootWindow(),
64                                      otk::OBProperty::openbox_pid,
65                                      otk::OBProperty::Atom_Cardinal,
66                                      (unsigned long) getpid());
67
68   // set the mouse cursor for the root window (the default cursor)
69   XDefineCursor(otk::OBDisplay::display, _info->rootWindow(),
70                 Openbox::instance->cursors().session);
71
72   // initialize the shit that is used for all drawing on the screen
73   _image_control = new otk::BImageControl(Openbox::instance->timerManager(),
74                                           _info, true);
75   _image_control->installRootColormap();
76   _root_cmap_installed = True;
77
78   // initialize the screen's style
79   _style.setImageControl(_image_control);
80   std::string stylepath;
81   python_get_string("theme", &stylepath);
82   otk::Configuration sconfig(false);
83   sconfig.setFile(otk::expandTilde(stylepath));
84   if (!sconfig.load()) {
85     sconfig.setFile(otk::expandTilde(DEFAULTSTYLE));
86     if (!sconfig.load()) {
87       printf(_("Unable to load default style: %s. Aborting.\n"), DEFAULTSTYLE);
88       ::exit(1);
89     }
90   }
91   _style.load(sconfig);
92
93   // set up notification of netwm support
94   setSupportedAtoms();
95
96   // Set the netwm atoms for geomtery and viewport
97   unsigned long geometry[] = { _info->width(),
98                                _info->height() };
99   Openbox::instance->property()->set(_info->rootWindow(),
100                                      otk::OBProperty::net_desktop_geometry,
101                                      otk::OBProperty::Atom_Cardinal,
102                                      geometry, 2);
103   unsigned long viewport[] = { 0, 0 };
104   Openbox::instance->property()->set(_info->rootWindow(),
105                                      otk::OBProperty::net_desktop_viewport,
106                                      otk::OBProperty::Atom_Cardinal,
107                                      viewport, 2);
108
109   // create the window which gets focus when no clients get it
110   XSetWindowAttributes attr;
111   attr.override_redirect = true;
112   _focuswindow = XCreateWindow(otk::OBDisplay::display, _info->rootWindow(),
113                                -100, -100, 1, 1, 0, 0, InputOnly,
114                                _info->visual(), CWOverrideRedirect, &attr);
115   XMapWindow(otk::OBDisplay::display, _focuswindow);
116   
117   // these may be further updated if any pre-existing windows are found in
118   // the manageExising() function
119   setClientList();     // initialize the client lists, which will be empty
120   calcArea();          // initialize the available working area
121 }
122
123
124 OBScreen::~OBScreen()
125 {
126   if (! _managed) return;
127
128   XSelectInput(otk::OBDisplay::display, _info->rootWindow(), NoEventMask);
129   
130   // unmanage all windows
131   while (!clients.empty())
132     unmanageWindow(clients.front());
133
134   XDestroyWindow(otk::OBDisplay::display, _focuswindow);
135   XDestroyWindow(otk::OBDisplay::display, _supportwindow);
136
137   delete _image_control;
138 }
139
140
141 void OBScreen::manageExisting()
142 {
143   unsigned int i, j, nchild;
144   Window r, p, *children;
145   XQueryTree(otk::OBDisplay::display, _info->rootWindow(), &r, &p,
146              &children, &nchild);
147
148   // preen the window list of all icon windows... for better dockapp support
149   for (i = 0; i < nchild; i++) {
150     if (children[i] == None) continue;
151
152     XWMHints *wmhints = XGetWMHints(otk::OBDisplay::display,
153                                     children[i]);
154
155     if (wmhints) {
156       if ((wmhints->flags & IconWindowHint) &&
157           (wmhints->icon_window != children[i])) {
158         for (j = 0; j < nchild; j++) {
159           if (children[j] == wmhints->icon_window) {
160             children[j] = None;
161             break;
162           }
163         }
164       }
165
166       XFree(wmhints);
167     }
168   }
169
170   // manage shown windows
171   for (i = 0; i < nchild; ++i) {
172     if (children[i] == None)
173       continue;
174
175     XWindowAttributes attrib;
176     if (XGetWindowAttributes(otk::OBDisplay::display, children[i], &attrib)) {
177       if (attrib.override_redirect) continue;
178
179       if (attrib.map_state != IsUnmapped) {
180         manageWindow(children[i]);
181       }
182     }
183   }
184
185   XFree(children);
186 }
187
188
189 //! Adds a window's strut to the screen's list of reserved spaces
190 void OBScreen::addStrut(otk::Strut *strut)
191 {
192   _struts.push_back(strut);
193 }
194
195
196 //! Removes a window's strut from the screen's list of reserved spaces
197 void OBScreen::removeStrut(otk::Strut *strut)
198 {
199   _struts.remove(strut);
200 }
201
202
203 void OBScreen::calcArea()
204 {
205   otk::Rect old_area = _area;
206
207 /*
208 #ifdef    XINERAMA
209   // reset to the full areas
210   if (isXineramaActive())
211     xineramaUsableArea = getXineramaAreas();
212 #endif // XINERAMA
213 */
214   
215   /* these values represent offsets from the screen edge
216    * we look for the biggest offset on each edge and then apply them
217    * all at once
218    * do not be confused by the similarity to the names of Rect's members
219    */
220   unsigned int current_left = 0, current_right = 0, current_top = 0,
221     current_bottom = 0;
222
223   StrutList::const_iterator it = _struts.begin(), end = _struts.end();
224
225   for(; it != end; ++it) {
226     otk::Strut *strut = *it;
227     if (strut->left > current_left)
228       current_left = strut->left;
229     if (strut->top > current_top)
230       current_top = strut->top;
231     if (strut->right > current_right)
232       current_right = strut->right;
233     if (strut->bottom > current_bottom)
234       current_bottom = strut->bottom;
235   }
236
237   _area.setRect(current_left, current_top,
238                 _info->width() - (current_left + current_right),
239                 _info->height() - (current_top + current_bottom));
240
241 /*
242 #ifdef    XINERAMA
243   if (isXineramaActive()) {
244     // keep each of the ximerama-defined areas inside the strut
245     RectList::iterator xit, xend = xineramaUsableArea.end();
246     for (xit = xineramaUsableArea.begin(); xit != xend; ++xit) {
247       if (xit->x() < usableArea.x()) {
248         xit->setX(usableArea.x());
249         xit->setWidth(xit->width() - usableArea.x());
250       }
251       if (xit->y() < usableArea.y()) {
252         xit->setY(usableArea.y());
253         xit->setHeight(xit->height() - usableArea.y());
254       }
255       if (xit->x() + xit->width() > usableArea.width())
256         xit->setWidth(usableArea.width() - xit->x());
257       if (xit->y() + xit->height() > usableArea.height())
258         xit->setHeight(usableArea.height() - xit->y());
259     }
260   }
261 #endif // XINERAMA
262 */
263   
264   if (old_area != _area)
265     // XXX: re-maximize windows
266
267   setWorkArea();
268 }
269
270
271 void OBScreen::setSupportedAtoms()
272 {
273   // create the netwm support window
274   _supportwindow = XCreateSimpleWindow(otk::OBDisplay::display,
275                                        _info->rootWindow(),
276                                        0, 0, 1, 1, 0, 0, 0);
277   assert(_supportwindow != None);
278
279   // set supporting window
280   Openbox::instance->property()->set(_info->rootWindow(),
281                                      otk::OBProperty::net_supporting_wm_check,
282                                      otk::OBProperty::Atom_Window,
283                                      _supportwindow);
284
285   //set properties on the supporting window
286   Openbox::instance->property()->set(_supportwindow,
287                                      otk::OBProperty::net_wm_name,
288                                      otk::OBProperty::utf8,
289                                      "Openbox");
290   Openbox::instance->property()->set(_supportwindow,
291                                      otk::OBProperty::net_supporting_wm_check,
292                                      otk::OBProperty::Atom_Window,
293                                      _supportwindow);
294
295   
296   Atom supported[] = {
297 /*
298       otk::OBProperty::net_current_desktop,
299       otk::OBProperty::net_number_of_desktops,
300 */
301       otk::OBProperty::net_desktop_geometry,
302       otk::OBProperty::net_desktop_viewport,
303       otk::OBProperty::net_active_window,
304       otk::OBProperty::net_workarea,
305       otk::OBProperty::net_client_list,
306       otk::OBProperty::net_client_list_stacking,
307 /*
308       otk::OBProperty::net_desktop_names,
309 */
310       otk::OBProperty::net_close_window,
311       otk::OBProperty::net_wm_name,
312       otk::OBProperty::net_wm_visible_name,
313       otk::OBProperty::net_wm_icon_name,
314       otk::OBProperty::net_wm_visible_icon_name,
315 /*
316       otk::OBProperty::net_wm_desktop,
317 */
318 /*
319       otk::OBProperty::net_wm_strut,
320 */
321       otk::OBProperty::net_wm_window_type,
322       otk::OBProperty::net_wm_window_type_desktop,
323       otk::OBProperty::net_wm_window_type_dock,
324       otk::OBProperty::net_wm_window_type_toolbar,
325       otk::OBProperty::net_wm_window_type_menu,
326       otk::OBProperty::net_wm_window_type_utility,
327       otk::OBProperty::net_wm_window_type_splash,
328       otk::OBProperty::net_wm_window_type_dialog,
329       otk::OBProperty::net_wm_window_type_normal,
330 /*
331       otk::OBProperty::net_wm_moveresize,
332       otk::OBProperty::net_wm_moveresize_size_topleft,
333       otk::OBProperty::net_wm_moveresize_size_topright,
334       otk::OBProperty::net_wm_moveresize_size_bottomleft,
335       otk::OBProperty::net_wm_moveresize_size_bottomright,
336       otk::OBProperty::net_wm_moveresize_move,
337 */
338 /*
339       otk::OBProperty::net_wm_allowed_actions,
340       otk::OBProperty::net_wm_action_move,
341       otk::OBProperty::net_wm_action_resize,
342       otk::OBProperty::net_wm_action_shade,
343       otk::OBProperty::net_wm_action_maximize_horz,
344       otk::OBProperty::net_wm_action_maximize_vert,
345       otk::OBProperty::net_wm_action_change_desktop,
346       otk::OBProperty::net_wm_action_close,
347 */
348       otk::OBProperty::net_wm_state,
349       otk::OBProperty::net_wm_state_modal,
350       otk::OBProperty::net_wm_state_maximized_vert,
351       otk::OBProperty::net_wm_state_maximized_horz,
352       otk::OBProperty::net_wm_state_shaded,
353       otk::OBProperty::net_wm_state_skip_taskbar,
354       otk::OBProperty::net_wm_state_skip_pager,
355       otk::OBProperty::net_wm_state_hidden,
356       otk::OBProperty::net_wm_state_fullscreen,
357       otk::OBProperty::net_wm_state_above,
358       otk::OBProperty::net_wm_state_below,
359     };
360   const int num_supported = sizeof(supported)/sizeof(Atom);
361
362   // convert to the atom values
363   for (int i = 0; i < num_supported; ++i)
364     supported[i] =
365       Openbox::instance->property()->atom((otk::OBProperty::Atoms)supported[i]);
366   
367   Openbox::instance->property()->set(_info->rootWindow(),
368                                      otk::OBProperty::net_supported,
369                                      otk::OBProperty::Atom_Atom,
370                                      supported, num_supported);
371 }
372
373
374 void OBScreen::setClientList()
375 {
376   Window *windows;
377   unsigned int size = clients.size();
378
379   // create an array of the window ids
380   if (size > 0) {
381     Window *win_it;
382     
383     windows = new Window[size];
384     win_it = windows;
385     ClientList::const_iterator it = clients.begin();
386     const ClientList::const_iterator end = clients.end();
387     for (; it != end; ++it, ++win_it)
388       *win_it = (*it)->window();
389   } else
390     windows = (Window*) 0;
391
392   Openbox::instance->property()->set(_info->rootWindow(),
393                                      otk::OBProperty::net_client_list,
394                                      otk::OBProperty::Atom_Window,
395                                      windows, size);
396
397   if (size)
398     delete [] windows;
399
400   setStackingList();
401 }
402
403
404 void OBScreen::setStackingList()
405 {
406   Window *windows;
407   unsigned int size = _stacking.size();
408
409   assert(size == clients.size()); // just making sure.. :)
410
411   
412   // create an array of the window ids
413   if (size > 0) {
414     Window *win_it;
415     
416     windows = new Window[size];
417     win_it = windows;
418     ClientList::const_iterator it = _stacking.begin();
419     const ClientList::const_iterator end = _stacking.end();
420     for (; it != end; ++it, ++win_it)
421       *win_it = (*it)->window();
422   } else
423     windows = (Window*) 0;
424
425   Openbox::instance->property()->set(_info->rootWindow(),
426                                      otk::OBProperty::net_client_list_stacking,
427                                      otk::OBProperty::Atom_Window,
428                                      windows, size);
429
430   if (size)
431     delete [] windows;
432 }
433
434
435 void OBScreen::setWorkArea() {
436   unsigned long area[] = { _area.x(), _area.y(),
437                            _area.width(), _area.height() };
438   Openbox::instance->property()->set(_info->rootWindow(),
439                                      otk::OBProperty::net_workarea,
440                                      otk::OBProperty::Atom_Cardinal,
441                                      area, 4);
442   /*
443   if (workspacesList.size() > 0) {
444     unsigned long *dims = new unsigned long[4 * workspacesList.size()];
445     for (unsigned int i = 0, m = workspacesList.size(); i < m; ++i) {
446       // XXX: this could be different for each workspace
447       const otk::Rect &area = availableArea();
448       dims[(i * 4) + 0] = area.x();
449       dims[(i * 4) + 1] = area.y();
450       dims[(i * 4) + 2] = area.width();
451       dims[(i * 4) + 3] = area.height();
452     }
453     xatom->set(getRootWindow(), otk::OBProperty::net_workarea,
454                otk::OBProperty::Atom_Cardinal,
455                dims, 4 * workspacesList.size());
456     delete [] dims;
457   } else
458     xatom->set(getRootWindow(), otk::OBProperty::net_workarea,
459                otk::OBProperty::Atom_Cardinal, 0, 0);
460   */
461 }
462
463
464 void OBScreen::manageWindow(Window window)
465 {
466   OBClient *client = 0;
467   XWMHints *wmhint;
468   XSetWindowAttributes attrib_set;
469
470   // is the window a docking app
471   if ((wmhint = XGetWMHints(otk::OBDisplay::display, window))) {
472     if ((wmhint->flags & StateHint) &&
473         wmhint->initial_state == WithdrawnState) {
474       //slit->addClient(w); // XXX: make dock apps work!
475       XFree(wmhint);
476       return;
477     }
478     XFree(wmhint);
479   }
480
481   otk::OBDisplay::grab();
482
483   // choose the events we want to receive on the CLIENT window
484   attrib_set.event_mask = OBClient::event_mask;
485   attrib_set.do_not_propagate_mask = OBClient::no_propagate_mask;
486   XChangeWindowAttributes(otk::OBDisplay::display, window,
487                           CWEventMask|CWDontPropagate, &attrib_set);
488
489   // create the OBClient class, which gets all of the hints on the window
490   client = new OBClient(_number, window);
491   // register for events
492   Openbox::instance->registerHandler(window, client);
493   // add to the wm's map
494   Openbox::instance->addClient(window, client);
495
496   // we dont want a border on the client
497   client->toggleClientBorder(false);
498   
499   // specify that if we exit, the window should not be destroyed and should be
500   // reparented back to root automatically
501   XChangeSaveSet(otk::OBDisplay::display, window, SetModeInsert);
502
503   if (!client->positionRequested()) {
504     // XXX: position the window intelligenty
505   }
506
507   // create the decoration frame for the client window
508   client->frame = new OBFrame(client, &_style);
509
510   // add to the wm's map
511   Openbox::instance->addClient(client->frame->window(), client);
512   Openbox::instance->addClient(client->frame->plate(), client);
513   Openbox::instance->addClient(client->frame->titlebar(), client);
514   Openbox::instance->addClient(client->frame->label(), client);
515   Openbox::instance->addClient(client->frame->button_max(), client);
516   Openbox::instance->addClient(client->frame->button_iconify(), client);
517   Openbox::instance->addClient(client->frame->button_stick(), client);
518   Openbox::instance->addClient(client->frame->button_close(), client);
519   Openbox::instance->addClient(client->frame->handle(), client);
520   Openbox::instance->addClient(client->frame->grip_left(), client);
521   Openbox::instance->addClient(client->frame->grip_right(), client);
522
523   // XXX: if on the current desktop..
524   client->frame->show();
525  
526   // XXX: handle any requested states such as shaded/maximized
527
528   otk::OBDisplay::ungrab();
529
530   // add to the screen's list
531   clients.push_back(client);
532   // this puts into the stacking order, then raises it
533   _stacking.push_back(client);
534   restack(true, client);
535   // update the root properties
536   setClientList();
537
538   Openbox::instance->bindings()->grabButtons(true, client);
539 }
540
541
542 void OBScreen::unmanageWindow(OBClient *client)
543 {
544   OBFrame *frame = client->frame;
545
546   Openbox::instance->bindings()->grabButtons(false, client);
547
548   // remove from the stacking order
549   _stacking.remove(client);
550   
551   // pass around focus if this window was focused XXX do this better!
552   if (Openbox::instance->focusedClient() == client) {
553     OBClient *newfocus = 0;
554     if (!_stacking.empty())
555       newfocus = _stacking.front();
556     if (! (newfocus && newfocus->focus()))
557       client->unfocus();
558   }
559
560   // remove from the wm's map
561   Openbox::instance->removeClient(client->window());
562   Openbox::instance->removeClient(frame->window());
563   Openbox::instance->removeClient(frame->plate());
564   Openbox::instance->removeClient(frame->titlebar());
565   Openbox::instance->removeClient(frame->label());
566   Openbox::instance->removeClient(frame->button_max());
567   Openbox::instance->removeClient(frame->button_iconify());
568   Openbox::instance->removeClient(frame->button_stick());
569   Openbox::instance->removeClient(frame->button_close());
570   Openbox::instance->removeClient(frame->handle());
571   Openbox::instance->removeClient(frame->grip_left());
572   Openbox::instance->removeClient(frame->grip_right());
573   // unregister for handling events
574   Openbox::instance->clearHandler(client->window());
575   
576   // remove the window from our save set
577   XChangeSaveSet(otk::OBDisplay::display, client->window(), SetModeDelete);
578
579   // we dont want events no more
580   XSelectInput(otk::OBDisplay::display, client->window(), NoEventMask);
581
582   frame->hide();
583
584   // give the client its border back
585   client->toggleClientBorder(true);
586
587   delete client->frame;
588   client->frame = 0;
589
590   // remove from the screen's list
591   clients.remove(client);
592   delete client;
593
594   // update the root properties
595   setClientList();
596 }
597
598 void OBScreen::restack(bool raise, OBClient *client)
599 {
600   const int layer = client->layer();
601   std::vector<Window> wins;
602
603   _stacking.remove(client);
604
605   // the stacking list is from highest to lowest
606   
607   ClientList::iterator it = _stacking.begin(), end = _stacking.end();
608   // insert the windows above this window
609   for (; it != end; ++it) {
610     if ((*it)->layer() < layer || (raise && (*it)->layer() == layer))
611       break;
612     wins.push_back((*it)->frame->window());
613   }
614   // insert our client
615   wins.push_back(client->frame->window());
616   _stacking.insert(it, client);
617   // insert the remaining below this window
618   for (; it != end; ++it)
619     wins.push_back((*it)->frame->window());
620
621   XRestackWindows(otk::OBDisplay::display, &wins[0], wins.size());
622   setStackingList();
623 }
624
625 }