]> icculus.org git repositories - mikachu/openbox.git/blob - util/epist/screen.cc
handle events on the right screen
[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   _epist = epist;
55   _xatom = _epist->xatom();
56   _number = number;
57   _active = _clients.end();
58   _info = _epist->getScreenInfo(_number);
59   _root = _info->getRootWindow();
60   
61   // find a window manager supporting NETWM, waiting for it to load if we must
62   int count = 20;  // try for 20 seconds
63   _managed = false;
64   while (! (_epist->doShutdown() || _managed || count <= 0)) {
65     if (! (_managed = findSupportingWM()))
66       usleep(1000);
67     --count;
68   }
69   if (_managed)
70     cout << "Found compatible window manager '" << _wm_name << "' for screen "
71       << _number << ".\n";
72   else {
73     cout << "Unable to find a compatible window manager for screen " <<
74       _number << ".\n";
75     return;
76   }
77  
78   XSelectInput(_epist->getXDisplay(), _root, PropertyChangeMask);
79
80   updateNumDesktops();
81   updateActiveDesktop();
82   updateClientList();
83   updateActiveWindow();
84 }
85
86
87 screen::~screen() {
88   if (_managed)
89     XSelectInput(_epist->getXDisplay(), _root, None);
90 }
91
92
93 bool screen::findSupportingWM() {
94   Window support_win;
95   if (! _xatom->getValue(_root, XAtom::net_supporting_wm_check, XAtom::window,
96                          support_win) || support_win == None)
97     return false;
98
99   string title;
100   _xatom->getValue(support_win, XAtom::net_wm_name, XAtom::utf8, title);
101   _wm_name = title;
102   return true;
103 }
104
105
106 XWindow *screen::findWindow(const XEvent &e) const {
107   assert(_managed);
108
109   WindowList::const_iterator it, end = _clients.end();
110   for (it = _clients.begin(); it != end; ++it)
111     if (**it == e.xany.window)
112       break;
113   if(it == end)
114     return 0;
115   return *it;
116 }
117
118
119 void screen::processEvent(const XEvent &e) {
120   assert(_managed);
121   assert(e.xany.window == _root);
122
123   switch (e.type) {
124   case PropertyNotify:
125     // root window
126     if (e.xproperty.atom == _xatom->getAtom(XAtom::net_number_of_desktops))
127       updateNumDesktops();
128     if (e.xproperty.atom == _xatom->getAtom(XAtom::net_current_desktop))
129       updateActiveDesktop();
130     if (e.xproperty.atom == _xatom->getAtom(XAtom::net_active_window))
131       updateActiveWindow();
132     if (e.xproperty.atom == _xatom->getAtom(XAtom::net_client_list)) {
133       // catch any window unmaps first
134       XEvent ev;
135       if (XCheckTypedWindowEvent(_epist->getXDisplay(), e.xany.window,
136                                  DestroyNotify, &ev) ||
137           XCheckTypedWindowEvent(_epist->getXDisplay(), e.xany.window,
138                                  UnmapNotify, &ev)) {
139         processEvent(ev);
140       }
141
142       updateClientList();
143     }
144     break;
145   case KeyPress:
146     handleKeypress(e);
147     break;
148   }
149 }
150
151 void screen::handleKeypress(const XEvent &e) {
152   int scrolllockMask, numlockMask;
153
154   ActionList::const_iterator it = _epist->actions().begin();
155   ActionList::const_iterator end = _epist->actions().end();
156
157   _epist->getLockModifiers(numlockMask, scrolllockMask);
158   
159   for (; it != end; ++it) {
160     unsigned int state = e.xkey.state & ~(LockMask|scrolllockMask|numlockMask);
161     
162     if (e.xkey.keycode == it->keycode() &&
163         state == it->modifierMask()) {
164       switch (it->type()) {
165       case Action::nextWorkspace:
166         cycleWorkspace(true);
167         return;
168
169       case Action::prevWorkspace:
170         cycleWorkspace(false);
171         return;
172
173       case Action::nextWindow:
174         cycleWindow(true);
175         return;
176
177       case Action::prevWindow:
178         cycleWindow(false);
179         return;
180
181       case Action::nextWindowOnAllWorkspaces:
182         cycleWindow(true, true);
183         return;
184
185       case Action::prevWindowOnAllWorkspaces:
186         cycleWindow(false, true);
187         return;
188
189       case Action::nextWindowOfClass:
190         cycleWindow(true, false, true, it->string());
191         return;
192
193       case Action::prevWindowOfClass:
194         cycleWindow(false, false, true, it->string());
195         return;
196
197       case Action::nextWindowOfClassOnAllWorkspaces:
198         cycleWindow(true, true, true, it->string());
199         return;
200
201       case Action::prevWindowOfClassOnAllWorkspaces:
202         cycleWindow(false, true, true, it->string());
203         return;
204
205       case Action::changeWorkspace:
206         changeWorkspace(it->number());
207         return;
208
209       case Action::execute:
210         execCommand(it->string());
211         return;
212
213       default:
214         break;
215       }
216
217       // these actions require an active window
218       if (_active != _clients.end()) {
219         XWindow *window = *_active;
220
221         switch (it->type()) {
222         case Action::iconify:
223           window->iconify();
224           return;
225
226         case Action::close:
227           window->close();
228           return;
229
230         case Action::raise:
231           window->raise();
232           return;
233
234         case Action::lower:
235           window->lower();
236           return;
237
238         case Action::sendToWorkspace:
239           window->sendTo(it->number());
240           return;
241
242         case Action::toggleomnipresent:
243           if (window->desktop() == 0xffffffff)
244             window->sendTo(_active_desktop);
245           else
246             window->sendTo(0xffffffff);
247           return;
248
249         case Action::moveWindowUp:
250           window->move(window->x(), window->y() - it->number());
251           return;
252       
253         case Action::moveWindowDown:
254           window->move(window->x(), window->y() + it->number());
255           return;
256       
257         case Action::moveWindowLeft:
258           window->move(window->x() - it->number(), window->y());
259           return;
260       
261         case Action::moveWindowRight:
262           window->move(window->x() + it->number(), window->y());
263           return;
264       
265         case Action::resizeWindowWidth:
266           window->resize(window->width() + it->number(), window->height());
267           return;
268       
269         case Action::resizeWindowHeight:
270           window->resize(window->width(), window->height() + it->number());
271           return;
272       
273         case Action::toggleshade:
274           window->shade(! window->shaded());
275           return;
276       
277         case Action::toggleMaximizeHorizontal:
278           window->toggleMaximize(XWindow::Max_Horz);
279           return;
280       
281         case Action::toggleMaximizeVertical:
282           window->toggleMaximize(XWindow::Max_Vert);
283           return;
284       
285         case Action::toggleMaximizeFull:
286           window->toggleMaximize(XWindow::Max_Full);
287           return;
288       
289         default:
290           assert(false);  // unhandled action type!
291           break;
292         }
293       }
294     }
295   }
296 }
297
298 // do we want to add this window to our list?
299 bool screen::doAddWindow(Window window) const {
300   assert(_managed);
301
302   Atom type;
303   if (! _xatom->getValue(window, XAtom::net_wm_window_type, XAtom::atom,
304                          type))
305     return True;
306
307   if (type == _xatom->getAtom(XAtom::net_wm_window_type_dock) ||
308       type == _xatom->getAtom(XAtom::net_wm_window_type_menu))
309     return False;
310
311   return True;
312 }
313
314
315 void screen::updateNumDesktops() {
316   assert(_managed);
317
318   if (! _xatom->getValue(_root, XAtom::net_number_of_desktops, XAtom::cardinal,
319                          (unsigned long)_num_desktops))
320     _num_desktops = 1;  // assume that there is at least 1 desktop!
321 }
322
323
324 void screen::updateActiveDesktop() {
325   assert(_managed);
326
327   if (! _xatom->getValue(_root, XAtom::net_current_desktop, XAtom::cardinal,
328                          (unsigned long)_active_desktop))
329     _active_desktop = 0;  // there must be at least one desktop, and it must
330                           // be the current one
331 }
332
333
334 void screen::updateClientList() {
335   assert(_managed);
336
337   WindowList::iterator insert_point = _active;
338   if (insert_point != _clients.end())
339     ++insert_point; // get to the item client the focused client
340   
341   // get the client list from the root window
342   Window *rootclients = 0;
343   unsigned long num = (unsigned) -1;
344   if (! _xatom->getValue(_root, XAtom::net_client_list, XAtom::window, num,
345                          &rootclients)) {
346     while (! _clients.empty()) {
347       delete _clients.front();
348       _clients.erase(_clients.begin());
349     }
350     if (rootclients) delete [] rootclients;
351     return;
352   }
353   
354   WindowList::iterator it, end = _clients.end();
355   unsigned long i;
356   
357   // insert new clients after the active window
358   for (i = 0; i < num; ++i) {
359     for (it = _clients.begin(); it != end; ++it)
360       if (**it == rootclients[i])
361         break;
362     if (it == end) {  // didn't already exist
363       if (doAddWindow(rootclients[i])) {
364         //cout << "Added window: 0x" << hex << rootclients[i] << dec << endl;
365         _clients.insert(insert_point, new XWindow(_epist, this,
366                                                   rootclients[i]));
367       }
368     }
369   }
370
371   // remove clients that no longer exist
372   for (it = _clients.begin(); it != end;) {
373     WindowList::iterator it2 = it++;
374     for (i = 0; i < num; ++i)
375       if (**it2 == rootclients[i])
376         break;
377     if (i == num)  { // no longer exists
378       //cout << "Removed window: 0x" << hex << (*it2)->window() << dec << endl;
379       delete *it2;
380       _clients.erase(it2);
381     }
382   }
383
384   if (rootclients) delete [] rootclients;
385 }
386
387
388 void screen::updateActiveWindow() {
389   assert(_managed);
390
391   Window a = None;
392   _xatom->getValue(_root, XAtom::net_active_window, XAtom::window, a);
393   
394   WindowList::iterator it, end = _clients.end();
395   for (it = _clients.begin(); it != end; ++it) {
396     if (**it == a)
397       break;
398   }
399   _active = it;
400
401   //cout << "Active window is now: ";
402   //if (_active == _clients.end()) cout << "None\n";
403   //else cout << "0x" << hex << (*_active)->window() << dec << endl;
404 }
405
406
407 void screen::execCommand(const std::string &cmd) const {
408   pid_t pid;
409   if ((pid = fork()) == 0) {
410     extern char **environ;
411
412     char *const argv[] = {
413       "sh",
414       "-c",
415       const_cast<char *>(cmd.c_str()),
416       0
417     };
418     // make the command run on the correct screen
419     if (putenv(const_cast<char*>(_info->displayString().c_str()))) {
420       cout << "warning: couldn't set environment variable 'DISPLAY'\n";
421       perror("putenv()");
422     }
423     execve("/bin/sh", argv, environ);
424     exit(127);
425   } else if (pid == -1) {
426     cout << _epist->getApplicationName() <<
427       ": Could not fork a process for executing a command\n";
428   }
429 }
430
431
432 void screen::cycleWindow(const bool forward, const bool alldesktops,
433                          const bool sameclass, const string &cn) const {
434   assert(_managed);
435
436   if (_clients.empty()) return;
437     
438   WindowList::const_iterator target = _active;
439
440   string classname = cn;
441   if (sameclass && classname.empty() && target != _clients.end())
442     classname = (*target)->appClass();
443
444   if (target == _clients.end())
445     target = _clients.begin();
446  
447   do {
448     if (forward) {
449       ++target;
450       if (target == _clients.end())
451         target = _clients.begin();
452     } else {
453       if (target == _clients.begin())
454         target = _clients.end();
455       --target;
456     }
457   } while (target == _clients.end() ||
458            (*target)->iconic() ||
459            (! alldesktops && (*target)->desktop() != _active_desktop) ||
460            (sameclass && ! classname.empty() &&
461             (*target)->appClass() != classname));
462   
463   if (target != _clients.end())
464     (*target)->focus();
465 }
466
467
468 void screen::cycleWorkspace(const bool forward, const bool loop) const {
469   assert(_managed);
470
471   unsigned int destination = _active_desktop;
472
473   if (forward) {
474     if (destination < _num_desktops - 1)
475       ++destination;
476     else if (loop)
477       destination = 0;
478   } else {
479     if (destination > 0)
480       --destination;
481     else if (loop)
482       destination = _num_desktops - 1;
483   }
484
485   if (destination != _active_desktop) 
486     changeWorkspace(destination);
487 }
488
489
490 void screen::changeWorkspace(const int num) const {
491   assert(_managed);
492
493   _xatom->sendClientMessage(_root, XAtom::net_current_desktop, _root, num);
494 }
495
496 void screen::grabKey(const KeyCode keyCode, const int modifierMask) const {
497
498   Display *display = _epist->getXDisplay();
499   int numlockMask, scrolllockMask;
500
501   _epist->getLockModifiers(numlockMask, scrolllockMask);
502
503   XGrabKey(display, keyCode, modifierMask,
504            _root, True, GrabModeAsync, GrabModeAsync);
505   XGrabKey(display, keyCode, 
506            modifierMask|LockMask,
507            _root, True, GrabModeAsync, GrabModeAsync);
508   XGrabKey(display, keyCode, 
509            modifierMask|scrolllockMask,
510            _root, True, GrabModeAsync, GrabModeAsync);
511   XGrabKey(display, keyCode, 
512            modifierMask|numlockMask,
513            _root, True, GrabModeAsync, GrabModeAsync);
514     
515   XGrabKey(display, keyCode, 
516            modifierMask|LockMask|scrolllockMask,
517            _root, True, GrabModeAsync, GrabModeAsync);
518   XGrabKey(display, keyCode, 
519            modifierMask|scrolllockMask|numlockMask,
520            _root, True, GrabModeAsync, GrabModeAsync);
521   XGrabKey(display, keyCode, 
522            modifierMask|numlockMask|LockMask,
523            _root, True, GrabModeAsync, GrabModeAsync);
524     
525   XGrabKey(display, keyCode, 
526            modifierMask|numlockMask|LockMask|scrolllockMask,
527            _root, True, GrabModeAsync, GrabModeAsync);
528 }