Initial revision
[bbkeys.git] / src / ScreenHandler.cpp
blob2304fdea20a2275443e3a51c7cb8b521669cc8f8
1 // -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 2; -*-
2 // -- ScreenHandler.cpp --
3 // Copyright (c) 2001 - 2003 Jason 'vanRijn' Kasper <vR at movingparts dot 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:
12 // The above copyright notice and this permission notice shall be included in
13 // all copies or substantial portions of the Software.
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.
23 // E_O_H_VR
25 #include "../config.h"
27 extern "C" {
28 #ifdef HAVE_STDIO_H
29 # include <stdio.h>
30 #endif // HAVE_STDIO_H
32 #ifdef HAVE_UNISTD_H
33 # include <sys/types.h>
34 # include <unistd.h>
35 #endif // HAVE_UNISTD_H
37 #include <X11/keysym.h>
40 #include "ScreenHandler.h"
42 using std::cout;
44 //--------------------------------------------------------
45 // Constructor/Destructor
46 //--------------------------------------------------------
47 ScreenHandler::ScreenHandler (KeyClient * k, unsigned int number)
48 : _managed(true), _screenNumber(number),
49 _screenInfo(k->display().screenInfo(number)),
50 _clients(k->clientsList()), _active(k->activeWindow())
52 _keyClient = k;
53 _netclient = k->getNetclient();
54 _config = k->getConfig();
55 _display = k->XDisplay();
56 _last_active = _clients.end();
57 _keyGrabber = k->getKeyGrabber();
58 _keybindings = k->getKeybindings();
59 _root = _screenInfo.rootWindow();
61 // get our lockmasks from bt::Application
62 k->getLockModifiers(_numlockMask, _scrolllockMask);
64 // find a window manager supporting NETWM, waiting for it to load if we must
65 int count = 20; // try for 20 seconds
66 _managed = false;
67 while (! (_keyClient->doShutdown() || _managed || count <= 0)) {
68 if (! (_managed = findSupportingWM()))
69 sleep(1);
70 --count;
73 if (!_managed) {
74 cout << "ScreenHandler: Unable to find a "
75 << "compatible window manager for screen: [" << number << "].\n";
76 return;
79 bt::Netwm::AtomList atoms;
80 if (_netclient->readSupported(_root, atoms)) {
81 cout << "ScreenHandler: Supported atoms: [" << atoms.size() << "].\n";
82 } else {
83 cout << "ScreenHandler: No supported ewmh hints. Not able to be managed.\n";
84 _managed = false;
85 return;
88 XSelectInput(_display, _root,
89 PropertyChangeMask | KeyPressMask | KeyReleaseMask);
91 // add an event handler for our root window
92 k->insertEventHandler(_root, this);
94 // get configuration options
95 _honor_modifiers = _config->getBoolValue("honormodifiers", false);
96 _stacked_cycling = _config->getBoolValue("stackedcycling", true);
97 _stacked_raise = _config->getBoolValue("stackedraise", true);
98 _show_cycle_menu = _config->getBoolValue("showcyclemenu", true);
99 _menu_text_justify = _config->getStringValue("menutextjustify", "left");
100 _workspace_columns = _config->getNumberValue("workspacecolumns", 0);
101 _workspace_rows = _config->getNumberValue("workspacerows", 0);
102 _debug = _config->getBoolValue("debug", false);
104 _cycling = false;
107 ScreenHandler::~ScreenHandler ()
109 _keyClient->removeEventHandler( _root );
111 _keyGrabber->ungrabAll(_root);
113 if (_managed)
114 XSelectInput(_display, _root, None);
117 void ScreenHandler::initialize()
119 _keybindings->grabDefaults(this);
121 updateActiveDesktop();
122 updateNumDesktops();
123 updateClientList();
124 updateActiveWindow();
128 bool ScreenHandler::findSupportingWM() {
130 Window client, tmp;
131 if (! (_netclient->readSupportingWMCheck(_root, &client) &&
132 _netclient->readSupportingWMCheck(client, &tmp) && client == tmp &&
133 _netclient->readWMName(client, _wm_name))) {
134 return false;
135 } else {
136 cout << "ScreenHandler: Found compatible "
137 << "window manager: [" << _wm_name << "] for screen: ["
138 << _screenNumber << "].\n";
139 return true;
144 void ScreenHandler::grabKey(const KeyCode keyCode,
145 const int modifierMask) const {
146 _keyGrabber->grab(keyCode, modifierMask, _root );
149 void ScreenHandler::ungrabKey(const KeyCode keyCode,
150 const int modifierMask) const {
151 _keyGrabber->ungrab(keyCode, modifierMask, _root );
154 void ScreenHandler::keyPressEvent (const XKeyEvent * const e)
156 unsigned int state = e->state;
158 // Mask out the lock modifiers unless our user doesn't want this
159 if (! _honor_modifiers) {
160 state= e->state & ~(LockMask|_scrolllockMask|_numlockMask);
163 // first, check to see if we're in the middle of a stacked cycling
164 // loop-de-loop and we're getting a cancel....
165 if (_stacked_cycling && _cycling &&
166 e->keycode == XKeysymToKeycode(_display, XK_Escape)) {
168 // we've been told to cancel out of a cycleWindow loop, so we turn
169 // off cycling, ungrab the keyboard, then raise the last-active
170 // window for our user
171 _cycling = false;
172 XUngrabKeyboard(_display, CurrentTime);
174 const XWindow * la = lastActiveWindow();
176 if (la) la->focus(_stacked_raise);
178 return;
181 // if we've made it this far, handle the action....
182 const Action *it = _keybindings->getAction(e, state, this);
184 if (!it)
185 return;
187 switch (it->type()) {
189 case Action::nextScreen:
190 _keyClient->cycleScreen(_screenNumber, true);
191 return;
193 case Action::prevScreen:
194 _keyClient->cycleScreen(_screenNumber, false);
195 return;
197 case Action::nextWorkspace:
198 cycleWorkspace(true, it->number() != 0 ? it->number(): 1);
199 return;
201 case Action::prevWorkspace:
202 cycleWorkspace(false, it->number() != 0 ? it->number(): 1);
203 return;
205 case Action::nextWindow:
206 cycleWindow(state, true, it->number() != 0 ? it->number(): 1);
207 return;
209 case Action::prevWindow:
210 cycleWindow(state, false, it->number() != 0 ? it->number(): 1);
211 return;
213 case Action::nextWindowOnAllWorkspaces:
214 cycleWindow(state, true, it->number() != 0 ? it->number(): 1, false, true);
215 return;
217 case Action::prevWindowOnAllWorkspaces:
218 cycleWindow(state, false, it->number() != 0 ? it->number(): 1, false, true);
219 return;
221 case Action::nextWindowOnAllScreens:
222 cycleWindow(state, true, it->number() != 0 ? it->number(): 1, true);
223 return;
225 case Action::prevWindowOnAllScreens:
226 cycleWindow(state, false, it->number() != 0 ? it->number(): 1, true);
227 return;
229 case Action::nextWindowOfClass:
230 cycleWindow(state, true, it->number() != 0 ? it->number(): 1,
231 false, false, true, it->string());
232 return;
234 case Action::prevWindowOfClass:
235 cycleWindow(state, false, it->number() != 0 ? it->number(): 1,
236 false, false, true, it->string());
237 return;
239 case Action::nextWindowOfClassOnAllWorkspaces:
240 cycleWindow(state, true, it->number() != 0 ? it->number(): 1,
241 false, true, true, it->string());
242 return;
244 case Action::prevWindowOfClassOnAllWorkspaces:
245 cycleWindow(state, false, it->number() != 0 ? it->number(): 1,
246 false, true, true, it->string());
247 return;
249 case Action::changeWorkspace:
250 changeWorkspace(it->number());
251 return;
253 case Action::upWorkspace:
254 changeWorkspaceVert(-1);
255 return;
257 case Action::downWorkspace:
258 changeWorkspaceVert(1);
259 return;
261 case Action::leftWorkspace:
262 changeWorkspaceHorz(-1);
263 return;
265 case Action::rightWorkspace:
266 changeWorkspaceHorz(1);
267 return;
269 case Action::execute:
270 execCommand(it->string());
271 return;
273 case Action::showRootMenu:
274 _netclient->sendClientMessage(_root, _netclient->xaOpenboxShowRootMenu(),
275 None);
276 return;
278 case Action::showWorkspaceMenu:
279 _netclient->sendClientMessage(_root, _netclient->xaOpenboxShowWorkspaceMenu(),
280 None);
281 return;
283 case Action::toggleGrabs: {
284 if (_grabbed) {
285 _keybindings->ungrabDefaults(this);
286 _grabbed = false;
287 } else {
288 _keybindings->grabDefaults(this);
289 _grabbed = true;
291 return;
294 default:
295 break;
298 // these actions require an active window
299 if (_active != _clients.end()) {
300 XWindow *window = *_active;
302 switch (it->type()) {
303 case Action::iconify:
304 window->iconify();
305 return;
307 case Action::close:
308 window->close();
309 return;
311 case Action::raise:
312 window->raise();
313 return;
315 case Action::lower:
316 window->lower();
317 return;
319 case Action::sendToWorkspace:
320 window->sendTo(it->number());
321 return;
323 case Action::toggleOmnipresent:
324 if (window->desktop() == 0xffffffff)
325 window->sendTo(_active_desktop);
326 else
327 window->sendTo(0xffffffff);
328 return;
330 case Action::moveWindowUp:
331 window->move(window->x(), window->y() -
332 (it->number() != 0 ? it->number(): 1));
333 return;
335 case Action::moveWindowDown:
336 window->move(window->x(), window->y() +
337 (it->number() != 0 ? it->number(): 1));
338 return;
340 case Action::moveWindowLeft:
341 window->move(window->x() - (it->number() != 0 ? it->number(): 1),
342 window->y());
343 return;
345 case Action::moveWindowRight:
346 window->move(window->x() + (it->number() != 0 ? it->number(): 1),
347 window->y());
348 return;
350 case Action::resizeWindowWidth:
351 window->resizeRel(it->number(), 0);
352 return;
354 case Action::resizeWindowHeight:
355 window->resizeRel(0, it->number());
356 return;
358 case Action::toggleShade:
359 window->shade(! window->shaded());
360 return;
362 case Action::toggleMaximizeHorizontal:
363 window->toggleMaximize(XWindow::Max_Horz);
364 return;
366 case Action::toggleMaximizeVertical:
367 window->toggleMaximize(XWindow::Max_Vert);
368 return;
370 case Action::toggleMaximizeFull:
371 window->toggleMaximize(XWindow::Max_Full);
372 return;
374 case Action::toggleDecorations:
375 window->decorate(! window->decorated());
376 return;
378 default:
379 assert(false); // unhandled action type!
380 break;
385 void ScreenHandler::keyReleaseEvent (const XKeyEvent * const e)
387 // the only keyrelease event we care about (for now) is when we do stacked
388 // cycling and the modifier is released
389 if (_stacked_cycling && _cycling && nothingIsPressed()) {
390 // all modifiers have been released. ungrab the keyboard, move the
391 // focused window to the top of the Z-order and raise it
392 XUngrabKeyboard(_display, CurrentTime);
394 if (_active != _clients.end()) {
395 XWindow *w = *_active;
396 bool e = _last_active == _active;
397 _clients.remove(w);
398 _clients.push_front(w);
399 _active = _clients.begin();
400 if (!e) _last_active = _active;
401 w->raise();
404 _cycling = false;
408 void ScreenHandler::propertyNotifyEvent(const XPropertyEvent * const e)
410 if (e->atom == _netclient->numberOfDesktops()) {
411 updateNumDesktops();
412 } else if (e->atom == _netclient->currentDesktop()) {
413 updateActiveDesktop();
414 } else if (e->atom == _netclient->activeWindow()) {
415 updateActiveWindow();
416 } else if (e->atom == _netclient->clientList()) {
417 updateClientList();
421 void ScreenHandler::updateNumDesktops()
423 assert(_managed);
425 if (! _netclient->readNumberOfDesktops(_root, & _num_desktops))
426 _num_desktops = 1; // assume that there is at least 1 desktop!
430 void ScreenHandler::updateActiveDesktop()
432 assert(_managed);
434 if (! _netclient->readCurrentDesktop(_root, & _active_desktop))
435 _active_desktop = 0; // there must be at least one desktop, and it must
436 // be the current one
440 void ScreenHandler::updateActiveWindow()
442 assert(_managed);
444 Window a = None;
445 _netclient->getValue(_root, _netclient->activeWindow(), XA_WINDOW, a);
447 if ( None == a ) {
448 return;
451 WindowList::iterator it, end = _clients.end();
452 for (it = _clients.begin(); it != end; ++it) {
453 if ( (*it)->window() == a) {
454 if ( (*it)->getScreenNumber() != _screenNumber )
455 return;
456 break;
460 _active = it;
462 if (_active != end) {
463 /* if we're not cycling and a window gets focus, add it to the top of the
464 * cycle stack.
467 if (_stacked_cycling && !_cycling) {
468 XWindow *win = *_active;
469 _clients.remove(win);
470 _clients.push_front(win);
471 _active = _clients.begin();
473 _last_active = _active;
475 if ( _debug )
476 cout <<"active window now: [" <<(*_active)->title() <<"]" <<endl;
483 void ScreenHandler::updateClientList()
485 assert(_managed);
487 // read the list of windows that our friendly neighborhood window
488 // manager knows about
489 Netclient::WindowList windowList;
491 if ( ! _netclient->readClientList(_root, windowList) ) {
492 cerr << "couldn't get client list from WM.\n";
493 return;
496 // where do we add new windows? if we're asked to do stacked
497 // cycling, then it should be at the top of the stack, otherwise,
498 // it's after the currently focused window
499 WindowList::iterator insert_point = _active;
500 if (! _stacked_cycling) {
501 if (insert_point != _clients.end() )
502 ++insert_point;
505 Netclient::WindowList::const_iterator wlIt = windowList.begin();
506 const Netclient::WindowList::const_iterator wlEnd = windowList.end();
508 // first, add all windows that we care about and didn't know about
509 for (; wlIt != wlEnd; ++wlIt) {
510 if ( careAboutWindow( (*wlIt)) && ( findWindow( (*wlIt) ) == 0) ) {
512 _clients.insert(insert_point,
513 new XWindow( (*wlIt), _netclient, _screenInfo , *_keyClient ) );
517 // now clean up and remove any windows that we have in our list that
518 // don't exist in our window manager's list
519 WindowList::iterator it;
520 bool found;
522 for (it = _clients.begin(); it != _clients.end();) {
523 WindowList::iterator it2 = it;
524 ++it;
526 assert ( (*it2) );
527 // is it on another screen?
528 if ((*it2)->getScreenNumber() != _screenNumber)
529 continue;
531 found = false;
532 for (wlIt = windowList.begin(); wlIt != wlEnd; ++wlIt) {
533 if ((*it2)->window() == (*wlIt) ) {
534 found = true;
535 break;
539 if (!found) {
540 delete *it2;
541 _clients.erase(it2);
549 // do we care about this window as a client?
550 bool ScreenHandler::careAboutWindow(Window window) const
552 assert(_managed);
554 Atom type;
555 if (! _netclient->getValue(window, _netclient->wmWindowType(), XA_ATOM,
556 type)) {
557 return True;
560 if (type == _netclient->wmWindowTypeDock() ||
561 type == _netclient->wmWindowTypeMenu() ) {
562 return False;
563 } else {
564 return True;
568 XWindow * ScreenHandler::findWindow(Window window) const {
569 assert(_managed);
571 WindowList::const_iterator it, end = _clients.end();
572 for (it = _clients.begin(); it != end; ++it)
573 if (**it == window)
574 break;
575 if(it == end)
576 return 0;
577 return *it;
580 void ScreenHandler::execCommand(const string &cmd) const {
581 pid_t pid;
582 if ((pid = fork()) == 0) {
583 // disconnect the child from epist's session and the tty
584 if (setsid() == -1) {
585 cout << "warning: could not start a new process group\n";
586 perror("setsid");
589 // make the command run on the correct screen
590 if (putenv(const_cast<char*>(_screenInfo.displayString().c_str()))) {
591 cout << "warning: couldn't set environment variable 'DISPLAY'\n";
592 perror("putenv()");
594 execl("/bin/sh", "sh", "-c", cmd.c_str(), NULL);
595 exit(-1);
596 } else if (pid == -1) {
597 cout << ": Could not fork a process for executing a command\n";
601 void ScreenHandler::cycleWindow(unsigned int state, const bool forward,
602 const int increment, const bool allscreens,
603 const bool alldesktops, const bool sameclass,
604 const string &cn)
606 assert(_managed);
607 assert(increment > 0);
609 if (_clients.empty()) return;
611 string classname(cn);
612 if (sameclass && classname.empty() && _active != _clients.end())
613 classname = (*_active)->appClass();
615 WindowList::const_iterator target = _active,
616 begin = _clients.begin(),
617 end = _clients.end();
619 XWindow *t = 0;
621 for (int x = 0; x < increment; ++x) {
622 while (1) {
623 if (forward) {
624 if (target == end)
625 target = begin;
626 else
627 ++target;
628 } else {
629 if (target == begin)
630 target = end;
631 else
632 --target;
635 // must be no window to focus
636 if (target == _active)
637 return;
639 // start back at the beginning of the loop
640 if (target == end)
641 continue;
643 // determine if this window is invalid for cycling to
644 t = *target;
645 if (t->iconic()) continue;
646 if (! allscreens && t->getScreenNumber() != _screenNumber) continue;
647 if (! alldesktops && ! (t->desktop() == _active_desktop ||
648 t->desktop() == 0xffffffff)) continue;
649 if (sameclass && ! classname.empty() &&
650 t->appClass() != classname) continue;
651 if (! t->canFocus()) continue;
653 // found a good window so break out of the while, and perhaps continue
654 // with the for loop
655 break;
659 // phew. we found the window, so focus it.
660 if (_stacked_cycling && state) {
661 if (!_cycling) {
662 // grab keyboard so we can intercept KeyReleases from it
663 XGrabKeyboard(_display, _root, True, GrabModeAsync,
664 GrabModeAsync, CurrentTime);
665 _cycling = true;
668 // if the window is on another desktop, we can't use XSetInputFocus, since
669 // it doesn't imply a workspace change.
670 if (_stacked_raise || (t->desktop() != _active_desktop &&
671 t->desktop() != 0xffffffff))
672 t->focus(); // raise
673 else
674 t->focus(false); // don't raise
676 else {
677 t->focus();
682 void ScreenHandler::cycleWorkspace(const bool forward, const int increment,
683 const bool loop) const {
684 assert(_managed);
685 assert(increment > 0);
687 unsigned int destination = _active_desktop;
689 for (int x = 0; x < increment; ++x) {
690 if (forward) {
691 if (destination < _num_desktops - 1)
692 ++destination;
693 else if (loop)
694 destination = 0;
695 } else {
696 if (destination > 0)
697 --destination;
698 else if (loop)
699 destination = _num_desktops - 1;
703 if (destination != _active_desktop)
704 changeWorkspace(destination);
708 void ScreenHandler::changeWorkspace(const int num) const {
709 assert(_managed);
711 _netclient->sendClientMessage(_root, _netclient->currentDesktop(), _root, num);
714 void ScreenHandler::changeWorkspaceVert(const int num) const {
715 assert(_managed);
716 int width = _workspace_columns;
717 int num_desktops = (signed)_num_desktops;
718 int active_desktop = (signed)_active_desktop;
719 int wnum = 0;
721 if (width > num_desktops || width <= 0)
722 return;
724 // a cookie to the person that makes this pretty
725 if (num < 0) {
726 wnum = active_desktop - width;
727 if (wnum < 0) {
728 wnum = num_desktops/width * width + active_desktop;
729 if (wnum >= num_desktops)
730 wnum = num_desktops - 1;
733 else {
734 wnum = active_desktop + width;
735 if (wnum >= num_desktops) {
736 wnum = (active_desktop + width) % num_desktops - 1;
737 if (wnum < 0)
738 wnum = 0;
741 changeWorkspace(wnum);
744 void ScreenHandler::changeWorkspaceHorz(const int num) const {
745 assert(_managed);
746 int width = _workspace_columns;
747 int num_desktops = (signed)_num_desktops;
748 int active_desktop = (signed)_active_desktop;
749 int wnum = 0;
751 if (width > num_desktops || width <= 0)
752 return;
754 if (num < 0) {
755 if (active_desktop % width != 0)
756 changeWorkspace(active_desktop - 1);
757 else {
758 wnum = active_desktop + width - 1;
759 if (wnum >= num_desktops)
760 wnum = num_desktops - 1;
763 else {
764 if (active_desktop % width != width - 1) {
765 wnum = active_desktop + 1;
766 if (wnum >= num_desktops)
767 wnum = num_desktops / width * width;
769 else
770 wnum = active_desktop - width + 1;
772 changeWorkspace(wnum);
775 bool ScreenHandler::nothingIsPressed(void) const
777 char keys[32];
778 XQueryKeymap(_display, keys);
780 for (int i = 0; i < 32; ++i) {
781 if (keys[i] != 0)
782 return false;
785 return true;
788 const XWindow *ScreenHandler::lastActiveWindow() const {
789 if (_last_active != _clients.end())
790 return *_last_active;
792 // find a window if one exists
793 WindowList::const_iterator it, end = _clients.end();
794 for (it = _clients.begin(); it != end; ++it)
795 if ((*it)->getScreenNumber() == _screenNumber && ! (*it)->iconic() &&
796 (*it)->canFocus() &&
797 ((*it)->desktop() == 0xffffffff ||
798 (*it)->desktop() == _active_desktop))
799 return *it;
801 // no windows on this screen
802 return 0;
805 void ScreenHandler::p()
807 cout << "\nNOW LISTING CLIENTS!!!" << endl;
809 WindowList::const_iterator it = _clients.begin();
810 const WindowList::const_iterator end = _clients.end();
812 for (; it != end; ++it)
813 cout << "desktop: ["
814 << (*it)->desktop()
815 << "], window: [" << (*it)->title() << "]" << endl;