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