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