]> icculus.org git repositories - mikachu/openbox.git/blob - util/epist/screen.cc
Big fat merge for epist.
[mikachu/openbox.git] / util / epist / screen.cc
1 // -*- mode: C++; indent-tabs-mode: nil; -*-
2 // screen.cc for Epistophy - a key handler for NETWM/EWMH window managers.
3 // Copyright (c) 2002 - 2002 Ben Jansens <ben at orodu.net>
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining a
6 // copy of this software and associated documentation files (the "Software"),
7 // to deal in the Software without restriction, including without limitation
8 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 // and/or sell copies of the Software, and to permit persons to whom the
10 // Software is furnished to do so, subject to the following conditions:
11 //
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
14 //
15 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18 // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 // DEALINGS IN THE SOFTWARE.
22
23 #ifdef    HAVE_CONFIG_H
24 #  include "../../config.h"
25 #endif // HAVE_CONFIG_H
26
27 extern "C" {
28 #ifdef    HAVE_STDIO_H
29 #  include <stdio.h>
30 #endif // HAVE_STDIO_H
31
32 #ifdef    HAVE_UNISTD_H
33 #  include <sys/types.h>
34 #  include <unistd.h>
35 #endif // HAVE_UNISTD_H
36 }
37
38 #include <iostream>
39 #include <string>
40
41 using std::cout;
42 using std::endl;
43 using std::hex;
44 using std::dec;
45 using std::string;
46
47 #include "../../src/BaseDisplay.hh"
48 #include "../../src/XAtom.hh"
49 #include "screen.hh"
50 #include "epist.hh"
51
52
53 screen::screen(epist *epist, int number) 
54   : _clients(epist->clientsList()),
55     _active(epist->activeWindow()) {
56   _epist = epist;
57   _xatom = _epist->xatom();
58   _last_active = _clients.end();
59   _number = number;
60   _info = _epist->getScreenInfo(_number);
61   _root = _info->getRootWindow();
62   
63   // find a window manager supporting NETWM, waiting for it to load if we must
64   int count = 20;  // try for 20 seconds
65   _managed = false;
66   while (! (_epist->doShutdown() || _managed || count <= 0)) {
67     if (! (_managed = findSupportingWM()))
68       sleep(1);
69     --count;
70   }
71   if (_managed)
72     cout << "Found compatible window manager '" << _wm_name << "' for screen "
73       << _number << ".\n";
74   else {
75     cout << "Unable to find a compatible window manager for screen " <<
76       _number << ".\n";
77     return;
78   }
79  
80   XSelectInput(_epist->getXDisplay(), _root, PropertyChangeMask);
81 }
82
83 screen::~screen() {
84   if (_managed)
85     XSelectInput(_epist->getXDisplay(), _root, None);
86 }
87
88
89 bool screen::findSupportingWM() {
90   Window support_win;
91   if (! _xatom->getValue(_root, XAtom::net_supporting_wm_check, XAtom::window,
92                          support_win) || support_win == None)
93     return false;
94
95   string title;
96   _xatom->getValue(support_win, XAtom::net_wm_name, XAtom::utf8, title);
97   _wm_name = title;
98   return true;
99 }
100
101
102 XWindow *screen::findWindow(const XEvent &e) const {
103   assert(_managed);
104
105   WindowList::const_iterator it, end = _clients.end();
106   for (it = _clients.begin(); it != end; ++it)
107     if (**it == e.xany.window)
108       break;
109   if(it == end)
110     return 0;
111   return *it;
112 }
113
114
115 void screen::processEvent(const XEvent &e) {
116   assert(_managed);
117   assert(e.xany.window == _root);
118
119   switch (e.type) {
120   case PropertyNotify:
121     // root window
122     if (e.xproperty.atom == _xatom->getAtom(XAtom::net_number_of_desktops))
123       updateNumDesktops();
124     if (e.xproperty.atom == _xatom->getAtom(XAtom::net_current_desktop))
125       updateActiveDesktop();
126     if (e.xproperty.atom == _xatom->getAtom(XAtom::net_active_window))
127       updateActiveWindow();
128     if (e.xproperty.atom == _xatom->getAtom(XAtom::net_client_list)) {
129       // catch any window unmaps first
130       XEvent ev;
131       if (XCheckTypedWindowEvent(_epist->getXDisplay(), e.xany.window,
132                                  DestroyNotify, &ev) ||
133           XCheckTypedWindowEvent(_epist->getXDisplay(), e.xany.window,
134                                  UnmapNotify, &ev)) {
135         processEvent(ev);
136       }
137
138       updateClientList();
139     }
140     break;
141   case KeyPress:
142     handleKeypress(e);
143     break;
144   }
145 }
146
147 void screen::handleKeypress(const XEvent &e) {
148   int scrolllockMask, numlockMask;
149   _epist->getLockModifiers(numlockMask, scrolllockMask);
150   
151   // Mask out the lock modifiers. We want our keys to always work
152   // This should be made an option
153   unsigned int state = e.xkey.state & ~(LockMask|scrolllockMask|numlockMask);
154   const Action *it = _epist->getKeyTree().getAction(e, state, this);
155   
156   if (!it)
157       return;
158
159   switch (it->type()) {
160   case Action::nextScreen:
161       _epist->cycleScreen(_number, true);
162       return;
163
164   case Action::prevScreen:
165       _epist->cycleScreen(_number, false);
166       return;
167
168   case Action::nextWorkspace:
169       cycleWorkspace(true);
170       return;
171
172   case Action::prevWorkspace:
173       cycleWorkspace(false);
174       return;
175
176   case Action::nextWindow:
177       cycleWindow(true);
178       return;
179
180   case Action::prevWindow:
181       cycleWindow(false);
182       return;
183
184   case Action::nextWindowOnAllWorkspaces:
185       cycleWindow(true, false, true);
186       return;
187
188   case Action::prevWindowOnAllWorkspaces:
189       cycleWindow(false, false, true);
190       return;
191
192   case Action::nextWindowOnAllScreens:
193       cycleWindow(true, true);
194       return;
195
196   case Action::prevWindowOnAllScreens:
197       cycleWindow(false, true);
198       return;
199
200   case Action::nextWindowOfClass:
201       cycleWindow(true, false, false, true, it->string());
202       return;
203
204   case Action::prevWindowOfClass:
205       cycleWindow(false, false, false, true, it->string());
206       return;
207       
208   case Action::nextWindowOfClassOnAllWorkspaces:
209       cycleWindow(true, false, true, true, it->string());
210       return;
211       
212   case Action::prevWindowOfClassOnAllWorkspaces:
213       cycleWindow(false, false, true, true, it->string());
214       return;
215
216   case Action::changeWorkspace:
217     // we subtract one so counting starts at 1 in the config file
218       changeWorkspace(it->number() - 1);
219       return;
220
221   case Action::execute:
222       execCommand(it->string());
223       return;
224
225   default:
226       break;
227   }
228
229   // these actions require an active window
230   if (_active != _clients.end()) {
231       XWindow *window = *_active;
232       
233       switch (it->type()) {
234       case Action::iconify:
235           window->iconify();
236           return;
237
238       case Action::close:
239           window->close();
240           return;
241
242       case Action::raise:
243           window->raise();
244           return;
245
246       case Action::lower:
247           window->lower();
248           return;
249
250       case Action::sendToWorkspace:
251           window->sendTo(it->number());
252           return;
253
254       case Action::toggleomnipresent:
255           if (window->desktop() == 0xffffffff)
256             window->sendTo(_active_desktop);
257           else
258             window->sendTo(0xffffffff);
259           return;
260
261       case Action::moveWindowUp:
262           window->move(window->x(), window->y() - it->number());
263           return;
264       
265       case Action::moveWindowDown:
266           window->move(window->x(), window->y() + it->number());
267           return;
268       
269       case Action::moveWindowLeft:
270           window->move(window->x() - it->number(), window->y());
271           return;
272       
273       case Action::moveWindowRight:
274           window->move(window->x() + it->number(), window->y());
275           return;
276       
277       case Action::resizeWindowWidth:
278           window->resize(window->width() + it->number(), window->height());
279           return;
280       
281       case Action::resizeWindowHeight:
282           window->resize(window->width(), window->height() + it->number());
283           return;
284       
285       case Action::toggleshade:
286           window->shade(! window->shaded());
287           return;
288       
289       case Action::toggleMaximizeHorizontal:
290           window->toggleMaximize(XWindow::Max_Horz);
291           return;
292       
293       case Action::toggleMaximizeVertical:
294           window->toggleMaximize(XWindow::Max_Vert);
295           return;
296       
297       case Action::toggleMaximizeFull:
298           window->toggleMaximize(XWindow::Max_Full);
299           return;
300       
301       default:
302           assert(false);  // unhandled action type!
303           break;
304       }
305   }
306 }
307
308 // do we want to add this window to our list?
309 bool screen::doAddWindow(Window window) const {
310   assert(_managed);
311
312   Atom type;
313   if (! _xatom->getValue(window, XAtom::net_wm_window_type, XAtom::atom,
314                          type))
315     return True;
316
317   if (type == _xatom->getAtom(XAtom::net_wm_window_type_dock) ||
318       type == _xatom->getAtom(XAtom::net_wm_window_type_menu))
319     return False;
320
321   return True;
322 }
323
324
325 void screen::updateEverything() {
326   updateNumDesktops();
327   updateActiveDesktop();
328   updateClientList();
329   updateActiveWindow();
330 }
331
332
333 void screen::updateNumDesktops() {
334   assert(_managed);
335
336   if (! _xatom->getValue(_root, XAtom::net_number_of_desktops, XAtom::cardinal,
337                          (unsigned long)_num_desktops))
338     _num_desktops = 1;  // assume that there is at least 1 desktop!
339 }
340
341
342 void screen::updateActiveDesktop() {
343   assert(_managed);
344
345   if (! _xatom->getValue(_root, XAtom::net_current_desktop, XAtom::cardinal,
346                          (unsigned long)_active_desktop))
347     _active_desktop = 0;  // there must be at least one desktop, and it must
348                           // be the current one
349 }
350
351
352 void screen::updateClientList() {
353   assert(_managed);
354
355   WindowList::iterator insert_point = _active;
356   if (insert_point != _clients.end())
357     ++insert_point; // get to the item client the focused client
358   
359   // get the client list from the root window
360   Window *rootclients = 0;
361   unsigned long num = (unsigned) -1;
362   if (! _xatom->getValue(_root, XAtom::net_client_list, XAtom::window, num,
363                          &rootclients))
364     num = 0;
365
366   WindowList::iterator it;
367   const WindowList::iterator end = _clients.end();
368   unsigned long i;
369   
370   // insert new clients after the active window
371   for (i = 0; i < num; ++i) {
372     for (it = _clients.begin(); it != end; ++it)
373       if (**it == rootclients[i])
374         break;
375     if (it == end) {  // didn't already exist
376       if (doAddWindow(rootclients[i])) {
377 //        cout << "Added window: 0x" << hex << rootclients[i] << dec << endl;
378         _clients.insert(insert_point, new XWindow(_epist, this,
379                                                   rootclients[i]));
380       }
381     }
382   }
383
384   // remove clients that no longer exist (that belong to this screen)
385   for (it = _clients.begin(); it != end;) {
386     WindowList::iterator it2 = it;
387     ++it;
388
389     // is on another screen?
390     if ((*it2)->getScreen() != this)
391       continue;
392
393     for (i = 0; i < num; ++i)
394       if (**it2 == rootclients[i])
395         break;
396     if (i == num)  { // no longer exists
397 //      cout << "Removed window: 0x" << hex << (*it2)->window() << dec << endl;
398       // watch for the active and last-active window
399       if (it2 == _active)
400         _active = _clients.end();
401       if (it2 == _last_active)
402         _last_active = _clients.end();
403       delete *it2;
404       _clients.erase(it2);
405     }
406   }
407
408   if (rootclients) delete [] rootclients;
409 }
410
411
412 const XWindow *screen::lastActiveWindow() const {
413   if (_last_active != _clients.end())
414     return *_last_active;
415
416   // find a window if one exists
417   WindowList::const_iterator it, end = _clients.end();
418   for (it = _clients.begin(); it != end; ++it)
419     if ((*it)->getScreen() == this && ! (*it)->iconic() &&
420         ((*it)->desktop() == 0xffffffff || (*it)->desktop() == _active_desktop))
421       return *it;
422
423   // no windows on this screen
424   return 0;
425 }
426
427
428 void screen::updateActiveWindow() {
429   assert(_managed);
430
431   Window a = None;
432   _xatom->getValue(_root, XAtom::net_active_window, XAtom::window, a);
433   
434   WindowList::iterator it, end = _clients.end();
435   for (it = _clients.begin(); it != end; ++it) {
436     if (**it == a) {
437       if ((*it)->getScreen() != this)
438         return;
439       break;
440     }
441   }
442   _active = it;
443   if (it != end)
444     _last_active = it;
445
446 /*  cout << "Active window is now: ";
447   if (_active == _clients.end()) cout << "None\n";
448   else cout << "0x" << hex << (*_active)->window() << dec << endl;
449 */
450 }
451
452
453 void screen::execCommand(const string &cmd) const {
454   pid_t pid;
455   if ((pid = fork()) == 0) {
456     // make the command run on the correct screen
457     if (putenv(const_cast<char*>(_info->displayString().c_str()))) {
458       cout << "warning: couldn't set environment variable 'DISPLAY'\n";
459       perror("putenv()");
460     }
461     execl("/bin/sh", "sh", "-c", cmd.c_str(), NULL);
462     exit(-1);
463   } else if (pid == -1) {
464     cout << _epist->getApplicationName() <<
465       ": Could not fork a process for executing a command\n";
466   }
467 }
468
469
470 void screen::cycleWindow(const bool forward, const bool allscreens,
471                          const bool alldesktops, const bool sameclass,
472                          const string &cn) const {
473   assert(_managed);
474
475   if (_clients.empty()) return;
476   
477   string classname(cn);
478   if (sameclass && classname.empty() && _active != _clients.end())
479     classname = (*_active)->appClass();
480
481   WindowList::const_iterator target = _active,
482                              begin = _clients.begin(),
483                              end = _clients.end();
484  
485   while (1) {
486     if (forward) {
487       if (target == end) {
488         target = begin;
489       } else {
490         ++target;
491       }
492     } else {
493       if (target == begin)
494         target = end;
495       --target;
496     }
497
498     // must be no window to focus
499     if (target == _active)
500       return;
501
502     // start back at the beginning of the loop
503     if (target == end)
504       continue;
505
506     // determine if this window is invalid for cycling to
507     const XWindow *t = *target;
508     if (t->iconic()) continue;
509     if (! allscreens && t->getScreen() != this) continue;
510     if (! alldesktops && ! (t->desktop() == _active_desktop ||
511                             t->desktop() == 0xffffffff)) continue;
512     if (sameclass && ! classname.empty() &&
513         t->appClass() != classname) continue;
514     if (! t->canFocus()) continue;
515
516     // found a good window!
517     t->focus();
518     return;
519   }
520 }
521
522
523 void screen::cycleWorkspace(const bool forward, const bool loop) const {
524   assert(_managed);
525
526   unsigned int destination = _active_desktop;
527
528   if (forward) {
529     if (destination < _num_desktops - 1)
530       ++destination;
531     else if (loop)
532       destination = 0;
533   } else {
534     if (destination > 0)
535       --destination;
536     else if (loop)
537       destination = _num_desktops - 1;
538   }
539
540   if (destination != _active_desktop) 
541     changeWorkspace(destination);
542 }
543
544
545 void screen::changeWorkspace(const int num) const {
546   assert(_managed);
547
548   _xatom->sendClientMessage(_root, XAtom::net_current_desktop, _root, num);
549 }
550
551 void screen::grabKey(const KeyCode keyCode, const int modifierMask) const {
552
553   Display *display = _epist->getXDisplay();
554   int numlockMask, scrolllockMask;
555
556   _epist->getLockModifiers(numlockMask, scrolllockMask);
557
558   XGrabKey(display, keyCode, modifierMask,
559            _root, True, GrabModeAsync, GrabModeAsync);
560   XGrabKey(display, keyCode, 
561            modifierMask|LockMask,
562            _root, True, GrabModeAsync, GrabModeAsync);
563   XGrabKey(display, keyCode, 
564            modifierMask|scrolllockMask,
565            _root, True, GrabModeAsync, GrabModeAsync);
566   XGrabKey(display, keyCode, 
567            modifierMask|numlockMask,
568            _root, True, GrabModeAsync, GrabModeAsync);
569     
570   XGrabKey(display, keyCode, 
571            modifierMask|LockMask|scrolllockMask,
572            _root, True, GrabModeAsync, GrabModeAsync);
573   XGrabKey(display, keyCode, 
574            modifierMask|scrolllockMask|numlockMask,
575            _root, True, GrabModeAsync, GrabModeAsync);
576   XGrabKey(display, keyCode, 
577            modifierMask|numlockMask|LockMask,
578            _root, True, GrabModeAsync, GrabModeAsync);
579     
580   XGrabKey(display, keyCode, 
581            modifierMask|numlockMask|LockMask|scrolllockMask,
582            _root, True, GrabModeAsync, GrabModeAsync);
583 }
584
585 void screen::ungrabKey(const KeyCode keyCode, const int modifierMask) const {
586
587   Display *display = _epist->getXDisplay();
588   int numlockMask, scrolllockMask;
589
590   _epist->getLockModifiers(numlockMask, scrolllockMask);
591
592   XUngrabKey(display, keyCode, modifierMask, _root);
593   XUngrabKey(display, keyCode, modifierMask|LockMask, _root);
594   XUngrabKey(display, keyCode, modifierMask|scrolllockMask, _root);
595   XUngrabKey(display, keyCode, modifierMask|numlockMask, _root);
596   XUngrabKey(display, keyCode, modifierMask|LockMask|scrolllockMask, _root);
597   XUngrabKey(display, keyCode, modifierMask|scrolllockMask|numlockMask, _root);
598   XUngrabKey(display, keyCode, modifierMask|numlockMask|LockMask, _root);
599   XUngrabKey(display, keyCode, modifierMask|numlockMask|LockMask|
600              scrolllockMask, _root);
601 }