]> icculus.org git repositories - mikachu/openbox.git/blob - util/epist/screen.cc
fixed spelling mistake
[mikachu/openbox.git] / util / epist / screen.cc
1 // -*- mode: C++; indent-tabs-mode: nil; -*-
2 // screen.cc for Epistrophy - 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     changeWorkspace(it->number());
218     return;
219
220   case Action::execute:
221     execCommand(it->string());
222     return;
223
224   default:
225     break;
226   }
227
228   // these actions require an active window
229   if (_active != _clients.end()) {
230     XWindow *window = *_active;
231       
232     switch (it->type()) {
233     case Action::iconify:
234       window->iconify();
235       return;
236
237     case Action::close:
238       window->close();
239       return;
240
241     case Action::raise:
242       window->raise();
243       return;
244
245     case Action::lower:
246       window->lower();
247       return;
248
249     case Action::sendToWorkspace:
250       window->sendTo(it->number());
251       return;
252
253     case Action::toggleomnipresent:
254       if (window->desktop() == 0xffffffff)
255         window->sendTo(_active_desktop);
256       else
257         window->sendTo(0xffffffff);
258       return;
259
260     case Action::moveWindowUp:
261       window->move(window->x(), window->y() - it->number());
262       return;
263       
264     case Action::moveWindowDown:
265       window->move(window->x(), window->y() + it->number());
266       return;
267       
268     case Action::moveWindowLeft:
269       window->move(window->x() - it->number(), window->y());
270       return;
271       
272     case Action::moveWindowRight:
273       window->move(window->x() + it->number(), window->y());
274       return;
275       
276     case Action::resizeWindowWidth:
277       window->resizeRel(it->number(), 0);
278       return;
279       
280     case Action::resizeWindowHeight:
281       window->resizeRel(0, it->number());
282       return;
283       
284     case Action::toggleshade:
285       window->shade(! window->shaded());
286       return;
287       
288     case Action::toggleMaximizeHorizontal:
289       window->toggleMaximize(XWindow::Max_Horz);
290       return;
291       
292     case Action::toggleMaximizeVertical:
293       window->toggleMaximize(XWindow::Max_Vert);
294       return;
295       
296     case Action::toggleMaximizeFull:
297       window->toggleMaximize(XWindow::Max_Full);
298       return;
299       
300     default:
301       assert(false);  // unhandled action type!
302       break;
303     }
304   }
305 }
306
307 // do we want to add this window to our list?
308 bool screen::doAddWindow(Window window) const {
309   assert(_managed);
310
311   Atom type;
312   if (! _xatom->getValue(window, XAtom::net_wm_window_type, XAtom::atom,
313                          type))
314     return True;
315
316   if (type == _xatom->getAtom(XAtom::net_wm_window_type_dock) ||
317       type == _xatom->getAtom(XAtom::net_wm_window_type_menu))
318     return False;
319
320   return True;
321 }
322
323
324 void screen::updateEverything() {
325   updateNumDesktops();
326   updateActiveDesktop();
327   updateClientList();
328   updateActiveWindow();
329 }
330
331
332 void screen::updateNumDesktops() {
333   assert(_managed);
334
335   if (! _xatom->getValue(_root, XAtom::net_number_of_desktops, XAtom::cardinal,
336                          (unsigned long)_num_desktops))
337     _num_desktops = 1;  // assume that there is at least 1 desktop!
338 }
339
340
341 void screen::updateActiveDesktop() {
342   assert(_managed);
343
344   if (! _xatom->getValue(_root, XAtom::net_current_desktop, XAtom::cardinal,
345                          (unsigned long)_active_desktop))
346     _active_desktop = 0;  // there must be at least one desktop, and it must
347                           // be the current one
348 }
349
350
351 void screen::updateClientList() {
352   assert(_managed);
353
354   WindowList::iterator insert_point = _active;
355   if (insert_point != _clients.end())
356     ++insert_point; // get to the item client the focused client
357   
358   // get the client list from the root window
359   Window *rootclients = 0;
360   unsigned long num = (unsigned) -1;
361   if (! _xatom->getValue(_root, XAtom::net_client_list, XAtom::window, num,
362                          &rootclients))
363     num = 0;
364
365   WindowList::iterator it;
366   const WindowList::iterator end = _clients.end();
367   unsigned long i;
368   
369   // insert new clients after the active window
370   for (i = 0; i < num; ++i) {
371     for (it = _clients.begin(); it != end; ++it)
372       if (**it == rootclients[i])
373         break;
374     if (it == end) {  // didn't already exist
375       if (doAddWindow(rootclients[i])) {
376         //        cout << "Added window: 0x" << hex << rootclients[i] << dec << endl;
377         _clients.insert(insert_point, new XWindow(_epist, this,
378                                                   rootclients[i]));
379       }
380     }
381   }
382
383   // remove clients that no longer exist (that belong to this screen)
384   for (it = _clients.begin(); it != end;) {
385     WindowList::iterator it2 = it;
386     ++it;
387
388     // is on another screen?
389     if ((*it2)->getScreen() != this)
390       continue;
391
392     for (i = 0; i < num; ++i)
393       if (**it2 == rootclients[i])
394         break;
395     if (i == num)  { // no longer exists
396       //      cout << "Removed window: 0x" << hex << (*it2)->window() << dec << endl;
397       // watch for the active and last-active window
398       if (it2 == _active)
399         _active = _clients.end();
400       if (it2 == _last_active)
401         _last_active = _clients.end();
402       delete *it2;
403       _clients.erase(it2);
404     }
405   }
406
407   if (rootclients) delete [] rootclients;
408 }
409
410
411 const XWindow *screen::lastActiveWindow() const {
412   if (_last_active != _clients.end())
413     return *_last_active;
414
415   // find a window if one exists
416   WindowList::const_iterator it, end = _clients.end();
417   for (it = _clients.begin(); it != end; ++it)
418     if ((*it)->getScreen() == this && ! (*it)->iconic() &&
419         ((*it)->desktop() == 0xffffffff || (*it)->desktop() == _active_desktop))
420       return *it;
421
422   // no windows on this screen
423   return 0;
424 }
425
426
427 void screen::updateActiveWindow() {
428   assert(_managed);
429
430   Window a = None;
431   _xatom->getValue(_root, XAtom::net_active_window, XAtom::window, a);
432   
433   WindowList::iterator it, end = _clients.end();
434   for (it = _clients.begin(); it != end; ++it) {
435     if (**it == a) {
436       if ((*it)->getScreen() != this)
437         return;
438       break;
439     }
440   }
441   _active = it;
442   if (it != end)
443     _last_active = it;
444
445   /*  cout << "Active window is now: ";
446       if (_active == _clients.end()) cout << "None\n";
447       else cout << "0x" << hex << (*_active)->window() << dec << endl;
448   */
449 }
450
451
452 void screen::execCommand(const string &cmd) const {
453   pid_t pid;
454   if ((pid = fork()) == 0) {
455     // make the command run on the correct screen
456     if (putenv(const_cast<char*>(_info->displayString().c_str()))) {
457       cout << "warning: couldn't set environment variable 'DISPLAY'\n";
458       perror("putenv()");
459     }
460     execl("/bin/sh", "sh", "-c", cmd.c_str(), NULL);
461     exit(-1);
462   } else if (pid == -1) {
463     cout << _epist->getApplicationName() <<
464       ": Could not fork a process for executing a command\n";
465   }
466 }
467
468
469 void screen::cycleWindow(const bool forward, const bool allscreens,
470                          const bool alldesktops, const bool sameclass,
471                          const string &cn) const {
472   assert(_managed);
473
474   if (_clients.empty()) return;
475   
476   string classname(cn);
477   if (sameclass && classname.empty() && _active != _clients.end())
478     classname = (*_active)->appClass();
479
480   WindowList::const_iterator target = _active,
481     begin = _clients.begin(),
482     end = _clients.end();
483  
484   while (1) {
485     if (forward) {
486       if (target == end) {
487         target = begin;
488       } else {
489         ++target;
490       }
491     } else {
492       if (target == begin)
493         target = end;
494       --target;
495     }
496
497     // must be no window to focus
498     if (target == _active)
499       return;
500
501     // start back at the beginning of the loop
502     if (target == end)
503       continue;
504
505     // determine if this window is invalid for cycling to
506     const XWindow *t = *target;
507     if (t->iconic()) continue;
508     if (! allscreens && t->getScreen() != this) continue;
509     if (! alldesktops && ! (t->desktop() == _active_desktop ||
510                             t->desktop() == 0xffffffff)) continue;
511     if (sameclass && ! classname.empty() &&
512         t->appClass() != classname) continue;
513     if (! t->canFocus()) continue;
514
515     // found a good window!
516     t->focus();
517     return;
518   }
519 }
520
521
522 void screen::cycleWorkspace(const bool forward, const bool loop) const {
523   assert(_managed);
524
525   unsigned int destination = _active_desktop;
526
527   if (forward) {
528     if (destination < _num_desktops - 1)
529       ++destination;
530     else if (loop)
531       destination = 0;
532   } else {
533     if (destination > 0)
534       --destination;
535     else if (loop)
536       destination = _num_desktops - 1;
537   }
538
539   if (destination != _active_desktop) 
540     changeWorkspace(destination);
541 }
542
543
544 void screen::changeWorkspace(const int num) const {
545   assert(_managed);
546
547   _xatom->sendClientMessage(_root, XAtom::net_current_desktop, _root, num);
548 }
549
550 void screen::grabKey(const KeyCode keyCode, const int modifierMask) const {
551
552   Display *display = _epist->getXDisplay();
553   int numlockMask, scrolllockMask;
554
555   _epist->getLockModifiers(numlockMask, scrolllockMask);
556
557   XGrabKey(display, keyCode, modifierMask,
558            _root, True, GrabModeAsync, GrabModeAsync);
559   XGrabKey(display, keyCode, 
560            modifierMask|LockMask,
561            _root, True, GrabModeAsync, GrabModeAsync);
562   XGrabKey(display, keyCode, 
563            modifierMask|scrolllockMask,
564            _root, True, GrabModeAsync, GrabModeAsync);
565   XGrabKey(display, keyCode, 
566            modifierMask|numlockMask,
567            _root, True, GrabModeAsync, GrabModeAsync);
568     
569   XGrabKey(display, keyCode, 
570            modifierMask|LockMask|scrolllockMask,
571            _root, True, GrabModeAsync, GrabModeAsync);
572   XGrabKey(display, keyCode, 
573            modifierMask|scrolllockMask|numlockMask,
574            _root, True, GrabModeAsync, GrabModeAsync);
575   XGrabKey(display, keyCode, 
576            modifierMask|numlockMask|LockMask,
577            _root, True, GrabModeAsync, GrabModeAsync);
578     
579   XGrabKey(display, keyCode, 
580            modifierMask|numlockMask|LockMask|scrolllockMask,
581            _root, True, GrabModeAsync, GrabModeAsync);
582 }
583
584 void screen::ungrabKey(const KeyCode keyCode, const int modifierMask) const {
585
586   Display *display = _epist->getXDisplay();
587   int numlockMask, scrolllockMask;
588
589   _epist->getLockModifiers(numlockMask, scrolllockMask);
590
591   XUngrabKey(display, keyCode, modifierMask, _root);
592   XUngrabKey(display, keyCode, modifierMask|LockMask, _root);
593   XUngrabKey(display, keyCode, modifierMask|scrolllockMask, _root);
594   XUngrabKey(display, keyCode, modifierMask|numlockMask, _root);
595   XUngrabKey(display, keyCode, modifierMask|LockMask|scrolllockMask, _root);
596   XUngrabKey(display, keyCode, modifierMask|scrolllockMask|numlockMask, _root);
597   XUngrabKey(display, keyCode, modifierMask|numlockMask|LockMask, _root);
598   XUngrabKey(display, keyCode, modifierMask|numlockMask|LockMask|
599              scrolllockMask, _root);
600 }