]> icculus.org git repositories - dana/openbox.git/blob - util/epist/screen.cc
fixed unsigned/signed comparison warnings
[dana/openbox.git] / util / epist / screen.cc
1 // -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 2; -*-
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 #include "config.hh"
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     else if (e.xproperty.atom == _xatom->getAtom(XAtom::net_current_desktop))
125       updateActiveDesktop();
126     else if (e.xproperty.atom == _xatom->getAtom(XAtom::net_active_window))
127       updateActiveWindow();
128     else 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, it->number() != 0 ? it->number(): 1);
170     return;
171
172   case Action::prevWorkspace:
173     cycleWorkspace(false, it->number() != 0 ? it->number(): 1);
174     return;
175
176   case Action::nextWindow:
177     
178     cycleWindow(true, it->number() != 0 ? it->number(): 1);
179     return;
180
181   case Action::prevWindow:
182     cycleWindow(false, it->number() != 0 ? it->number(): 1);
183     return;
184
185   case Action::nextWindowOnAllWorkspaces:
186     cycleWindow(true, it->number() != 0 ? it->number(): 1,  false, true);
187     return;
188
189   case Action::prevWindowOnAllWorkspaces:
190     cycleWindow(false, it->number() != 0 ? it->number(): 1, false, true);
191     return;
192
193   case Action::nextWindowOnAllScreens:
194     cycleWindow(true, it->number() != 0 ? it->number(): 1, true);
195     return;
196
197   case Action::prevWindowOnAllScreens:
198     cycleWindow(false, it->number() != 0 ? it->number(): 1, true);
199     return;
200
201   case Action::nextWindowOfClass:
202     cycleWindow(true, it->number() != 0 ? it->number(): 1,
203                 false, false, true, it->string());
204     return;
205
206   case Action::prevWindowOfClass:
207     cycleWindow(false, it->number() != 0 ? it->number(): 1,
208                 false, false, true, it->string());
209     return;
210       
211   case Action::nextWindowOfClassOnAllWorkspaces:
212     cycleWindow(true, it->number() != 0 ? it->number(): 1,
213                 false, true, true, it->string());
214     return;
215       
216   case Action::prevWindowOfClassOnAllWorkspaces:
217     cycleWindow(false, it->number() != 0 ? it->number(): 1,
218                 false, true, true, it->string());
219     return;
220
221   case Action::changeWorkspace:
222     changeWorkspace(it->number());
223     return;
224
225   case Action::upWorkspace:
226     changeWorkspaceVert(-1);
227     return;
228
229   case Action::downWorkspace:
230     changeWorkspaceVert(1);
231     return;
232
233   case Action::leftWorkspace:
234     changeWorkspaceHorz(-1);
235     return;
236
237   case Action::rightWorkspace:
238     changeWorkspaceHorz(1);
239     return;
240
241   case Action::execute:
242     execCommand(it->string());
243     return;
244
245   case Action::showRootMenu:
246     _xatom->sendClientMessage(rootWindow(), XAtom::openbox_show_root_menu,
247                               None);
248     return;
249
250   case Action::showWorkspaceMenu:
251     _xatom->sendClientMessage(rootWindow(), XAtom::openbox_show_workspace_menu,
252                               None);
253     return;
254
255   default:
256     break;
257   }
258
259   // these actions require an active window
260   if (_active != _clients.end()) {
261     XWindow *window = *_active;
262       
263     switch (it->type()) {
264     case Action::iconify:
265       window->iconify();
266       return;
267
268     case Action::close:
269       window->close();
270       return;
271
272     case Action::raise:
273       window->raise();
274       return;
275
276     case Action::lower:
277       window->lower();
278       return;
279
280     case Action::sendToWorkspace:
281       window->sendTo(it->number());
282       return;
283
284     case Action::toggleomnipresent:
285       if (window->desktop() == 0xffffffff)
286         window->sendTo(_active_desktop);
287       else
288         window->sendTo(0xffffffff);
289       return;
290
291     case Action::moveWindowUp:
292       window->move(window->x(), window->y() -
293                    (it->number() != 0 ? it->number(): 1));
294       return;
295       
296     case Action::moveWindowDown:
297       window->move(window->x(), window->y() +
298                    (it->number() != 0 ? it->number(): 1));
299       return;
300       
301     case Action::moveWindowLeft:
302       window->move(window->x() - (it->number() != 0 ? it->number(): 1),
303                    window->y());
304       return;
305       
306     case Action::moveWindowRight:
307       window->move(window->x() + (it->number() != 0 ? it->number(): 1),
308                    window->y());
309       return;
310       
311     case Action::resizeWindowWidth:
312       window->resizeRel(it->number(), 0);
313       return;
314       
315     case Action::resizeWindowHeight:
316       window->resizeRel(0, it->number());
317       return;
318       
319     case Action::toggleshade:
320       window->shade(! window->shaded());
321       return;
322       
323     case Action::toggleMaximizeHorizontal:
324       window->toggleMaximize(XWindow::Max_Horz);
325       return;
326       
327     case Action::toggleMaximizeVertical:
328       window->toggleMaximize(XWindow::Max_Vert);
329       return;
330       
331     case Action::toggleMaximizeFull:
332       window->toggleMaximize(XWindow::Max_Full);
333       return;
334
335     case Action::toggleDecorations:
336       window->decorate(! window->decorated());
337       return;
338       
339     default:
340       assert(false);  // unhandled action type!
341       break;
342     }
343   }
344 }
345
346 // do we want to add this window to our list?
347 bool screen::doAddWindow(Window window) const {
348   assert(_managed);
349
350   Atom type;
351   if (! _xatom->getValue(window, XAtom::net_wm_window_type, XAtom::atom,
352                          type))
353     return True;
354
355   if (type == _xatom->getAtom(XAtom::net_wm_window_type_dock) ||
356       type == _xatom->getAtom(XAtom::net_wm_window_type_menu))
357     return False;
358
359   return True;
360 }
361
362
363 void screen::updateEverything() {
364   updateNumDesktops();
365   updateActiveDesktop();
366   updateClientList();
367   updateActiveWindow();
368 }
369
370
371 void screen::updateNumDesktops() {
372   assert(_managed);
373
374   if (! _xatom->getValue(_root, XAtom::net_number_of_desktops, XAtom::cardinal,
375                          (unsigned long)_num_desktops))
376     _num_desktops = 1;  // assume that there is at least 1 desktop!
377 }
378
379
380 void screen::updateActiveDesktop() {
381   assert(_managed);
382
383   if (! _xatom->getValue(_root, XAtom::net_current_desktop, XAtom::cardinal,
384                          (unsigned long)_active_desktop))
385     _active_desktop = 0;  // there must be at least one desktop, and it must
386                           // be the current one
387 }
388
389
390 void screen::updateClientList() {
391   assert(_managed);
392
393   WindowList::iterator insert_point = _active;
394   if (insert_point != _clients.end())
395     ++insert_point; // get to the item client the focused client
396   
397   // get the client list from the root window
398   Window *rootclients = 0;
399   unsigned long num = (unsigned) -1;
400   if (! _xatom->getValue(_root, XAtom::net_client_list, XAtom::window, num,
401                          &rootclients))
402     num = 0;
403
404   WindowList::iterator it;
405   const WindowList::iterator end = _clients.end();
406   unsigned long i;
407   
408   // insert new clients after the active window
409   for (i = 0; i < num; ++i) {
410     for (it = _clients.begin(); it != end; ++it)
411       if (**it == rootclients[i])
412         break;
413     if (it == end) {  // didn't already exist
414       if (doAddWindow(rootclients[i])) {
415         //        cout << "Added window: 0x" << hex << rootclients[i] << dec << endl;
416         _clients.insert(insert_point, new XWindow(_epist, this,
417                                                   rootclients[i]));
418       }
419     }
420   }
421
422   // remove clients that no longer exist (that belong to this screen)
423   for (it = _clients.begin(); it != end;) {
424     WindowList::iterator it2 = it;
425     ++it;
426
427     // is on another screen?
428     if ((*it2)->getScreen() != this)
429       continue;
430
431     for (i = 0; i < num; ++i)
432       if (**it2 == rootclients[i])
433         break;
434     if (i == num)  { // no longer exists
435       //      cout << "Removed window: 0x" << hex << (*it2)->window() << dec << endl;
436       // watch for the active and last-active window
437       if (it2 == _active)
438         _active = _clients.end();
439       if (it2 == _last_active)
440         _last_active = _clients.end();
441       delete *it2;
442       _clients.erase(it2);
443     }
444   }
445
446   if (rootclients) delete [] rootclients;
447 }
448
449
450 const XWindow *screen::lastActiveWindow() const {
451   if (_last_active != _clients.end())
452     return *_last_active;
453
454   // find a window if one exists
455   WindowList::const_iterator it, end = _clients.end();
456   for (it = _clients.begin(); it != end; ++it)
457     if ((*it)->getScreen() == this && ! (*it)->iconic() &&
458         ((*it)->desktop() == 0xffffffff || (*it)->desktop() == _active_desktop))
459       return *it;
460
461   // no windows on this screen
462   return 0;
463 }
464
465
466 void screen::updateActiveWindow() {
467   assert(_managed);
468
469   Window a = None;
470   _xatom->getValue(_root, XAtom::net_active_window, XAtom::window, a);
471   
472   WindowList::iterator it, end = _clients.end();
473   for (it = _clients.begin(); it != end; ++it) {
474     if (**it == a) {
475       if ((*it)->getScreen() != this)
476         return;
477       break;
478     }
479   }
480   _active = it;
481   if (it != end)
482     _last_active = it;
483
484   /*  cout << "Active window is now: ";
485       if (_active == _clients.end()) cout << "None\n";
486       else cout << "0x" << hex << (*_active)->window() << dec << endl;
487   */
488 }
489
490
491 void screen::execCommand(const string &cmd) const {
492   pid_t pid;
493   if ((pid = fork()) == 0) {
494     // make the command run on the correct screen
495     if (putenv(const_cast<char*>(_info->displayString().c_str()))) {
496       cout << "warning: couldn't set environment variable 'DISPLAY'\n";
497       perror("putenv()");
498     }
499     execl("/bin/sh", "sh", "-c", cmd.c_str(), NULL);
500     exit(-1);
501   } else if (pid == -1) {
502     cout << _epist->getApplicationName() <<
503       ": Could not fork a process for executing a command\n";
504   }
505 }
506
507
508 void screen::cycleWindow(const bool forward, const int increment,
509                          const bool allscreens, const bool alldesktops,
510                          const bool sameclass, const string &cn) const {
511   assert(_managed);
512   assert(increment > 0);
513
514   if (_clients.empty()) return;
515
516   string classname(cn);
517   if (sameclass && classname.empty() && _active != _clients.end())
518     classname = (*_active)->appClass();
519
520   WindowList::const_iterator target = _active,
521     begin = _clients.begin(),
522     end = _clients.end();
523
524   const XWindow *t = 0;
525   
526   for (int x = 0; x < increment; ++x) {
527     while (1) {
528       if (forward) {
529         if (target == end) {
530           target = begin;
531         } else {
532           ++target;
533         }
534       } else {
535         if (target == begin)
536           target = end;
537         --target;
538       }
539
540       // must be no window to focus
541       if (target == _active)
542         return;
543
544       // start back at the beginning of the loop
545       if (target == end)
546         continue;
547
548       // determine if this window is invalid for cycling to
549       t = *target;
550       if (t->iconic()) continue;
551       if (! allscreens && t->getScreen() != this) continue;
552       if (! alldesktops && ! (t->desktop() == _active_desktop ||
553                               t->desktop() == 0xffffffff)) continue;
554       if (sameclass && ! classname.empty() &&
555           t->appClass() != classname) continue;
556       if (! t->canFocus()) continue;
557
558       // found a good window so break out of the while, and perhaps continue
559       // with the for loop
560       break;
561     }
562   }
563
564   // phew. we found the window, so focus it.
565   t->focus();
566 }
567
568
569 void screen::cycleWorkspace(const bool forward, const int increment,
570                             const bool loop) const {
571   assert(_managed);
572   assert(increment > 0);
573
574   unsigned int destination = _active_desktop;
575
576   for (int x = 0; x < increment; ++x) {
577     if (forward) {
578       if (destination < _num_desktops - 1)
579         ++destination;
580       else if (loop)
581         destination = 0;
582     } else {
583       if (destination > 0)
584         --destination;
585       else if (loop)
586         destination = _num_desktops - 1;
587     }
588   }
589
590   if (destination != _active_desktop) 
591     changeWorkspace(destination);
592 }
593
594
595 void screen::changeWorkspace(const int num) const {
596   assert(_managed);
597
598   _xatom->sendClientMessage(_root, XAtom::net_current_desktop, _root, num);
599 }
600
601 void screen::changeWorkspaceVert(const int num) const {
602   assert(_managed);
603   const Config *conf = _epist->getConfig();
604   int width = conf->getNumberValue(Config::workspaceColumns);
605   int num_desktops = (signed)_num_desktops;
606   int active_desktop = (signed)_active_desktop;
607   int wnum = 0;
608
609   if (width > num_desktops || width <= 0)
610     return;
611
612   // a cookie to the person that makes this pretty
613   if (num < 0) {
614     wnum = active_desktop - width;
615     if (wnum < 0) {
616       wnum = num_desktops/width * width + active_desktop;
617       if (wnum >= num_desktops)
618         wnum = num_desktops - 1;
619     }
620   }
621   else {
622     wnum = active_desktop + width;
623     if (wnum >= num_desktops) {
624       wnum = (active_desktop + width) % num_desktops - 1;
625       if (wnum < 0)
626         wnum = 0;
627     }
628   }
629   changeWorkspace(wnum);
630 }
631
632 void screen::changeWorkspaceHorz(const int num) const {
633   assert(_managed);
634   const Config *conf = _epist->getConfig();
635   int width = conf->getNumberValue(Config::workspaceColumns);
636   int num_desktops = (signed)_num_desktops;
637   int active_desktop = (signed)_active_desktop;
638   int wnum = 0;
639   
640   if (width > num_desktops || width <= 0)
641     return;
642
643   if (num < 0) {
644     if (active_desktop % width != 0)
645       changeWorkspace(active_desktop - 1);
646     else {
647       wnum = active_desktop + width - 1;
648       if (wnum >= num_desktops)
649         wnum = num_desktops - 1;
650     }
651   }
652   else {
653     if (active_desktop % width != width - 1) {
654       wnum = active_desktop + 1;
655       if (wnum >= num_desktops)
656         wnum = num_desktops / width * width;
657     }
658     else
659       wnum = active_desktop - width + 1;
660   }
661   changeWorkspace(wnum);
662 }
663
664 void screen::grabKey(const KeyCode keyCode, const int modifierMask) const {
665
666   Display *display = _epist->getXDisplay();
667   int numlockMask, scrolllockMask;
668
669   _epist->getLockModifiers(numlockMask, scrolllockMask);
670
671   XGrabKey(display, keyCode, modifierMask,
672            _root, True, GrabModeAsync, GrabModeAsync);
673   XGrabKey(display, keyCode, 
674            modifierMask|LockMask,
675            _root, True, GrabModeAsync, GrabModeAsync);
676   XGrabKey(display, keyCode, 
677            modifierMask|scrolllockMask,
678            _root, True, GrabModeAsync, GrabModeAsync);
679   XGrabKey(display, keyCode, 
680            modifierMask|numlockMask,
681            _root, True, GrabModeAsync, GrabModeAsync);
682     
683   XGrabKey(display, keyCode, 
684            modifierMask|LockMask|scrolllockMask,
685            _root, True, GrabModeAsync, GrabModeAsync);
686   XGrabKey(display, keyCode, 
687            modifierMask|scrolllockMask|numlockMask,
688            _root, True, GrabModeAsync, GrabModeAsync);
689   XGrabKey(display, keyCode, 
690            modifierMask|numlockMask|LockMask,
691            _root, True, GrabModeAsync, GrabModeAsync);
692     
693   XGrabKey(display, keyCode, 
694            modifierMask|numlockMask|LockMask|scrolllockMask,
695            _root, True, GrabModeAsync, GrabModeAsync);
696 }
697
698 void screen::ungrabKey(const KeyCode keyCode, const int modifierMask) const {
699
700   Display *display = _epist->getXDisplay();
701   int numlockMask, scrolllockMask;
702
703   _epist->getLockModifiers(numlockMask, scrolllockMask);
704
705   XUngrabKey(display, keyCode, modifierMask, _root);
706   XUngrabKey(display, keyCode, modifierMask|LockMask, _root);
707   XUngrabKey(display, keyCode, modifierMask|scrolllockMask, _root);
708   XUngrabKey(display, keyCode, modifierMask|numlockMask, _root);
709   XUngrabKey(display, keyCode, modifierMask|LockMask|scrolllockMask, _root);
710   XUngrabKey(display, keyCode, modifierMask|scrolllockMask|numlockMask, _root);
711   XUngrabKey(display, keyCode, modifierMask|numlockMask|LockMask, _root);
712   XUngrabKey(display, keyCode, modifierMask|numlockMask|LockMask|
713              scrolllockMask, _root);
714 }