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>
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.
25 #include "../config.h"
30 #endif // HAVE_STDIO_H
33 # include <sys/types.h>
35 #endif // HAVE_UNISTD_H
37 #include <X11/keysym.h>
41 #include "ScreenHandler.h"
45 //--------------------------------------------------------
46 // Constructor/Destructor
47 //--------------------------------------------------------
48 ScreenHandler::ScreenHandler (KeyClient
* k
, unsigned int number
)
49 : _managed(true), _screenNumber(number
),
50 _screenInfo(k
->display().screenInfo(number
)),
51 _clients(k
->clientsList()), _active(k
->activeWindow())
54 _netclient
= k
->getNetclient();
55 _config
= k
->getConfig();
56 _display
= k
->XDisplay();
57 _last_active
= _clients
.end();
58 _keyGrabber
= k
->getKeyGrabber();
59 _keybindings
= k
->getKeybindings();
60 _root
= _screenInfo
.rootWindow();
62 // get our lockmasks from bt::Application
63 k
->getLockModifiers(_numlockMask
, _scrolllockMask
);
65 // find a window manager supporting NETWM, waiting for it to load if we must
66 int count
= 20; // try 20 times
68 while (! (_keyClient
->shuttingDown() || _managed
|| count
<= 0)) {
69 if (! (_managed
= findSupportingWM()))
75 cout
<< "ScreenHandler: Unable to find a "
76 << "compatible window manager for screen: [" << number
<< "].\n";
80 bt::Netwm::AtomList atoms
;
81 if (_netclient
->readSupported(_root
, atoms
)) {
82 cout
<< "ScreenHandler: Supported atoms: [" << atoms
.size() << "].\n";
84 cout
<< "ScreenHandler: No supported ewmh hints. Not able to be managed.\n";
89 XSelectInput(_display
, _root
,
90 PropertyChangeMask
| KeyPressMask
| KeyReleaseMask
);
92 // add an event handler for our root window
93 k
->insertEventHandler(_root
, this);
95 // get configuration options
96 _honor_modifiers
= _config
->getBoolValue("honormodifiers", false);
97 _raise_while_cycling
= _config
->getBoolValue("raisewhilecycling", 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);
106 // our popup window list menu
107 _windowmenu
= new WindowlistMenu(this);
110 ScreenHandler::~ScreenHandler ()
112 _keyClient
->removeEventHandler( _root
);
114 _keyGrabber
->ungrabAll(_root
);
117 XSelectInput(_display
, _root
, None
);
120 void ScreenHandler::initialize()
122 _keybindings
->grabDefaults(this);
124 updateActiveDesktop();
127 updateActiveWindow();
129 // load graphics resource from config file
130 bt::Resource
res(_config
->getStringValue("stylefile", DEFAULTSTYLE
));
131 bt::MenuStyle::get(_keyClient
->getMainApplication(),
132 _screenNumber
)->load(res
);
137 bool ScreenHandler::findSupportingWM() {
140 cout
<< endl
<< "ScreenHandler: in findSupportingWM."<< endl
;
145 res
= _netclient
->readSupportingWMCheck(_root
, &client
);
148 cout
<< "ScreenHandler: first readSupportingWMCheck failed." << endl
;
153 cout
<< "ScreenHandler: first readSupportingWMCheck succeeded." << endl
;
155 res
= _netclient
->readSupportingWMCheck(client
, &tmp
);
156 if (!res
|| client
!= tmp
) {
158 cout
<< "ScreenHandler: second readSupportingWMCheck failed." << endl
;
163 cout
<< "ScreenHandler: second readSupportingWMCheck worked." << endl
;
165 // now try to get the name of the window manager, using utf8 first
166 // and falling back to ansi if that fails
170 if (! _netclient
->getValue(client
, _netclient
->wmName(),
171 Netclient::utf8
, _wm_name
)) {
173 cout
<< "ScreenHandler: first try at getting wmName failed." << endl
;
175 _netclient
->getValue(client
, XA_WM_NAME
, Netclient::ansi
, _wm_name
);
178 if (_wm_name
.empty()) {
180 cout
<< "ScreenHandler: couldn't get wm's name. letting it slide this time...." << endl
;
181 _wm_name
= "beats the heck out of me";
184 cout
<< "ScreenHandler: Found compatible "
185 << "window manager: [" << _wm_name
<< "] for screen: ["
186 << _screenNumber
<< "].\n";
192 void ScreenHandler::grabKey(const KeyCode keyCode
,
193 const int modifierMask
) const {
194 _keyGrabber
->grab(keyCode
, modifierMask
, _root
);
197 void ScreenHandler::ungrabKey(const KeyCode keyCode
,
198 const int modifierMask
) const {
199 _keyGrabber
->ungrab(keyCode
, modifierMask
, _root
);
202 void ScreenHandler::keyPressEvent (const XKeyEvent
* const e
)
204 unsigned int state
= e
->state
;
206 // Mask out the lock modifiers unless our user doesn't want this
207 if (! _honor_modifiers
) {
208 state
= e
->state
& ~(LockMask
|_scrolllockMask
|_numlockMask
);
211 // first, check to see if we're in the middle of a window cycling
212 // loop-de-loop and we're getting a cancel....
213 if (_cycling
&& e
->keycode
== XKeysymToKeycode(_display
, XK_Escape
)) {
215 // we've been told to cancel out of a cycleWindow loop, so we turn
216 // off cycling, ungrab the keyboard, then raise the last-active
217 // window for our user
219 XUngrabKeyboard(_display
, CurrentTime
);
221 const XWindow
* la
= lastActiveWindow();
223 if (la
) la
->focus(true);
228 // if we've made it this far, handle the action....
229 const Action
*it
= _keybindings
->getAction(e
, state
, this);
234 switch (it
->type()) {
237 // if we're doing a chain, then keytree has done everything for us...
241 case Action::nextScreen
:
242 _keyClient
->cycleScreen(_screenNumber
, true);
245 case Action::prevScreen
:
246 _keyClient
->cycleScreen(_screenNumber
, false);
249 case Action::nextWorkspace
:
250 cycleWorkspace(true, it
->number() != 0 ? it
->number(): 1);
253 case Action::prevWorkspace
:
254 cycleWorkspace(false, it
->number() != 0 ? it
->number(): 1);
257 case Action::nextWindow
:
258 cycleWindow(state
, true, it
->number() != 0 ? it
->number(): 1);
261 case Action::prevWindow
:
262 cycleWindow(state
, false, it
->number() != 0 ? it
->number(): 1);
265 case Action::nextWindowOnAllWorkspaces
:
266 cycleWindow(state
, true, it
->number() != 0 ? it
->number(): 1, false, true);
269 case Action::prevWindowOnAllWorkspaces
:
270 cycleWindow(state
, false, it
->number() != 0 ? it
->number(): 1, false, true);
273 case Action::nextWindowOnAllScreens
:
274 cycleWindow(state
, true, it
->number() != 0 ? it
->number(): 1, true);
277 case Action::prevWindowOnAllScreens
:
278 cycleWindow(state
, false, it
->number() != 0 ? it
->number(): 1, true);
281 case Action::nextWindowOfClass
:
282 cycleWindow(state
, true, it
->number() != 0 ? it
->number(): 1,
283 false, false, true, it
->string());
286 case Action::prevWindowOfClass
:
287 cycleWindow(state
, false, it
->number() != 0 ? it
->number(): 1,
288 false, false, true, it
->string());
291 case Action::nextWindowOfClassOnAllWorkspaces
:
292 cycleWindow(state
, true, it
->number() != 0 ? it
->number(): 1,
293 false, true, true, it
->string());
296 case Action::prevWindowOfClassOnAllWorkspaces
:
297 cycleWindow(state
, false, it
->number() != 0 ? it
->number(): 1,
298 false, true, true, it
->string());
301 case Action::changeWorkspace
:
302 changeWorkspace(it
->number());
305 case Action::upWorkspace
:
306 changeWorkspaceVert(-1);
309 case Action::downWorkspace
:
310 changeWorkspaceVert(1);
313 case Action::leftWorkspace
:
314 changeWorkspaceHorz(-1);
317 case Action::rightWorkspace
:
318 changeWorkspaceHorz(1);
321 case Action::execute
:
322 execCommand(it
->string());
325 case Action::showRootMenu
:
326 _netclient
->sendClientMessage(_root
, _netclient
->xaOpenboxShowRootMenu(),
330 case Action::showWorkspaceMenu
:
331 _netclient
->sendClientMessage(_root
, _netclient
->xaOpenboxShowWorkspaceMenu(),
335 case Action::toggleGrabs
: {
337 _keybindings
->ungrabDefaults(this);
340 _keybindings
->grabDefaults(this);
350 // these actions require an active window
351 if (_active
!= _clients
.end()) {
352 XWindow
*window
= *_active
;
354 switch (it
->type()) {
355 case Action::iconify
:
371 case Action::sendToWorkspace
:
372 window
->sendTo(it
->number());
375 case Action::toggleOmnipresent
:
376 if (window
->desktop() == 0xffffffff)
377 window
->sendTo(_active_desktop
);
379 window
->sendTo(0xffffffff);
382 case Action::moveWindowUp
:
383 window
->move(0, -(it
->number() != 0 ? it
->number(): 1));
386 case Action::moveWindowDown
:
387 window
->move(0, it
->number() != 0 ? it
->number(): 1);
390 case Action::moveWindowLeft
:
391 window
->move(-(it
->number() != 0 ? it
->number(): 1), 0);
394 case Action::moveWindowRight
:
395 window
->move(it
->number() != 0 ? it
->number(): 1,0);
398 case Action::resizeWindowWidth
:
399 window
->resizeRel(it
->number(), 0);
402 case Action::resizeWindowHeight
:
403 window
->resizeRel(0, it
->number());
406 case Action::toggleShade
:
407 window
->shade(! window
->shaded());
410 case Action::toggleMaximizeHorizontal
:
411 window
->toggleMaximize(XWindow::Max_Horz
);
414 case Action::toggleMaximizeVertical
:
415 window
->toggleMaximize(XWindow::Max_Vert
);
418 case Action::toggleMaximizeFull
:
419 window
->toggleMaximize(XWindow::Max_Full
);
422 case Action::toggleDecorations
:
423 window
->decorate(! window
->decorated());
427 assert(false); // unhandled action type!
433 void ScreenHandler::keyReleaseEvent (const XKeyEvent
* const e
)
435 // the only keyrelease event we care about (for now) is when we do window
436 // cycling and the modifier is released
437 if ( _cycling
&& nothingIsPressed()) {
438 // all modifiers have been released. ungrab the keyboard, move the
439 // focused window to the top of the Z-order and raise it
440 XUngrabKeyboard(_display
, CurrentTime
);
442 if (_active
!= _clients
.end()) {
443 XWindow
*w
= *_active
;
444 bool e
= _last_active
== _active
;
446 _clients
.push_front(w
);
447 _active
= _clients
.begin();
448 if (!e
) _last_active
= _active
;
456 void ScreenHandler::propertyNotifyEvent(const XPropertyEvent
* const e
)
458 if (e
->atom
== _netclient
->numberOfDesktops()) {
460 } else if (e
->atom
== _netclient
->currentDesktop()) {
461 updateActiveDesktop();
462 } else if (e
->atom
== _netclient
->activeWindow()) {
463 updateActiveWindow();
464 } else if (e
->atom
== _netclient
->clientList()) {
469 void ScreenHandler::updateNumDesktops()
473 if (! _netclient
->readNumberOfDesktops(_root
, & _num_desktops
))
474 _num_desktops
= 1; // assume that there is at least 1 desktop!
478 void ScreenHandler::updateActiveDesktop()
482 if (! _netclient
->readCurrentDesktop(_root
, & _active_desktop
))
483 _active_desktop
= 0; // there must be at least one desktop, and it must
484 // be the current one
488 void ScreenHandler::updateActiveWindow()
493 _netclient
->getValue(_root
, _netclient
->activeWindow(), XA_WINDOW
, a
);
499 WindowList::iterator it
, end
= _clients
.end();
500 for (it
= _clients
.begin(); it
!= end
; ++it
) {
501 if ( (*it
)->window() == a
) {
502 if ( (*it
)->getScreenNumber() != _screenNumber
)
510 if (_active
!= end
) {
511 /* if we're not cycling and a window gets focus, add it to the top of the
516 XWindow
*win
= *_active
;
517 _clients
.remove(win
);
518 _clients
.push_front(win
);
519 _active
= _clients
.begin();
521 _last_active
= _active
;
524 cout
<<"active window now: [" <<(*_active
)->title() <<"]" <<endl
;
531 void ScreenHandler::updateClientList()
536 WindowList::iterator insert_point
= _active
;
537 if (insert_point
!= _clients
.end())
538 ++insert_point
; // get to the item client the focused client
540 // get the client list from the root window
541 Netclient::WindowList rootclients
;
542 unsigned long num
= (unsigned) -1;
544 if ( ! _netclient
->readClientList(_root
, rootclients
) ) {
545 cerr
<< "couldn't get client list from WM.\n";
548 num
= rootclients
.size();
551 WindowList::iterator it
;
552 const WindowList::iterator end
= _clients
.end();
555 for (i
= 0; i
< num
; ++i
) {
556 for (it
= _clients
.begin(); it
!= end
; ++it
)
557 if (**it
== rootclients
[i
])
559 if (it
== end
) { // didn't already exist
560 if (careAboutWindow(rootclients
[i
])) {
561 XWindow
* wTmp
= new XWindow( rootclients
[i
], _netclient
, _screenInfo
, *_keyClient
);
562 _clients
.insert(insert_point
, wTmp
);
567 // remove clients that no longer exist (that belong to this screen)
568 for (it
= _clients
.begin(); it
!= end
;) {
569 WindowList::iterator it2
= it
;
572 // is on another screen?
573 if ((*it2
)->getScreenNumber() != _screenNumber
)
576 for (i
= 0; i
< num
; ++i
)
577 if (**it2
== rootclients
[i
])
579 if (i
== num
) { // no longer exists
580 // watch for the active and last-active window
582 _active
= _clients
.end();
583 if (it2
== _last_active
)
584 _last_active
= _clients
.end();
593 // do we care about this window as a client?
594 bool ScreenHandler::careAboutWindow(Window window
) const
599 if (! _netclient
->getValue(window
, _netclient
->wmWindowType(), XA_ATOM
,
604 if (type
== _netclient
->wmWindowTypeDock() ||
605 type
== _netclient
->wmWindowTypeMenu() ) {
612 XWindow
* ScreenHandler::findWindow(Window window
) const {
615 WindowList::const_iterator it
, end
= _clients
.end();
616 for (it
= _clients
.begin(); it
!= end
; ++it
)
624 void ScreenHandler::execCommand(const string
&cmd
) const {
626 if ((pid
= fork()) == 0) {
627 // disconnect the child from this session and the tty
628 if (setsid() == -1) {
629 cout
<< "warning: could not start a new process group\n";
633 // make the command run on the correct screen
634 if (putenv(const_cast<char*>(_screenInfo
.displayString().c_str()))) {
635 cout
<< "warning: couldn't set environment variable 'DISPLAY'\n";
638 execl("/bin/sh", "sh", "-c", cmd
.c_str(), NULL
);
640 } else if (pid
== -1) {
641 cout
<< ": Could not fork a process for executing a command\n";
645 WindowList
ScreenHandler::getCycleWindowList(unsigned int state
, const bool forward
,
646 const int increment
, const bool allscreens
,
647 const bool alldesktops
, const bool sameclass
,
651 assert(increment
> 0);
655 if (_clients
.empty()) return theList
;
657 string
classname(cn
);
658 if (sameclass
&& classname
.empty() && _active
!= _clients
.end())
659 classname
= (*_active
)->appClass();
662 WindowList::const_iterator it
= _clients
.begin();
663 const WindowList::const_iterator end
= _clients
.end();
665 for (; it
!= end
; ++it
) {
668 // determine if this window is invalid for cycling to
669 if (t
->iconic()) continue;
670 if (! allscreens
&& t
->getScreenNumber() != _screenNumber
) continue;
671 if (! alldesktops
&& ! (t
->desktop() == _active_desktop
||
672 t
->desktop() == 0xffffffff)) continue;
673 if (sameclass
&& ! classname
.empty() &&
674 t
->appClass() != classname
) continue;
675 if (! t
->canFocus()) continue;
676 if (t
->skipPager()) continue;
678 // found a focusable window
679 theList
.push_back(t
);
686 void ScreenHandler::cycleWindow(unsigned int state
, const bool forward
,
687 const int increment
, const bool allscreens
,
688 const bool alldesktops
, const bool sameclass
,
692 assert(increment
> 0);
694 if (_clients
.empty()) return;
696 // if our user wants the window cycling menu to show (who wouldn't!!
697 // =:) ) and if it's not already showing...
698 if ( _show_cycle_menu
&& ! _windowmenu
->isVisible() ) {
700 std::cout
<< "ScreenHandler: menu not visible. loading and showing..." << std::endl
;
703 WindowList theList
= getCycleWindowList(state
, forward
, increment
,
704 allscreens
, alldesktops
,
706 // can't show the window list if there's not even one window =:)
707 if (theList
.size() >= 1)
708 _windowmenu
->showCycleMenu(theList
);
714 string
classname(cn
);
715 if (sameclass
&& classname
.empty() && _active
!= _clients
.end())
716 classname
= (*_active
)->appClass();
718 WindowList::const_iterator target
= _active
,
719 begin
= _clients
.begin(),
720 end
= _clients
.end();
724 for (int x
= 0; x
< increment
; ++x
) {
738 // must be no window to focus
739 if (target
== _active
)
742 // start back at the beginning of the loop
746 // determine if this window is invalid for cycling to
748 if (t
->iconic()) continue;
749 if (! allscreens
&& t
->getScreenNumber() != _screenNumber
) continue;
750 if (! alldesktops
&& ! (t
->desktop() == _active_desktop
||
751 t
->desktop() == 0xffffffff)) continue;
752 if (sameclass
&& ! classname
.empty() &&
753 t
->appClass() != classname
) continue;
754 if (! t
->canFocus()) continue;
755 if (t
->skipPager()) continue;
757 // found a good window so break out of the while, and perhaps continue
763 // phew. we found the window, so focus it.
766 // grab keyboard so we can intercept KeyReleases from it
767 XGrabKeyboard(_display
, _root
, True
, GrabModeAsync
,
768 GrabModeAsync
, CurrentTime
);
772 // if the window is on another desktop, we can't use XSetInputFocus, since
773 // it doesn't imply a workspace change.
774 if ( t
->desktop() != _active_desktop
&&
775 t
->desktop() != 0xffffffff)
778 t
->focus(false); // don't raise
786 void ScreenHandler::cycleWorkspace(const bool forward
, const int increment
,
787 const bool loop
) const {
789 assert(increment
> 0);
791 unsigned int destination
= _active_desktop
;
793 for (int x
= 0; x
< increment
; ++x
) {
795 if (destination
< _num_desktops
- 1)
803 destination
= _num_desktops
- 1;
807 if (destination
!= _active_desktop
)
808 changeWorkspace(destination
);
812 void ScreenHandler::changeWorkspace(const int num
) const {
815 _netclient
->sendClientMessage(_root
, _netclient
->currentDesktop(), _root
, num
);
818 void ScreenHandler::changeWorkspaceVert(const int num
) const {
820 int width
= _workspace_columns
;
821 int total
= (signed)_num_desktops
;
822 int n
= (signed)_active_desktop
;
825 // if the # of rows is greater than the # of desktops or <= 0, or
826 // if we're not dealing with a rectangle here, return (invalid condition)
827 if ( width
> total
|| width
<= 0 ||
828 ( total
% width
) != 0 )
831 bool moveUp
= (num
< 0);
832 if (moveUp
) { // we go up...
833 wnum
= (n
< width
) // if we're on the first row
834 ? n
+ (total
- width
) // go to the same position in the last row
835 : n
- width
; // else, just go up one row
837 } else { // we go down...
838 wnum
= (n
< (total
- width
)) // if we're not on the last row
839 ? n
+ width
// go down one row
840 : n
- (total
- width
); // else go to the same position in the
844 changeWorkspace(wnum
);
847 void ScreenHandler::changeWorkspaceHorz(const int num
) const {
849 int width
= _workspace_columns
;
850 int total
= (signed)_num_desktops
;
851 int n
= (signed)_active_desktop
;
854 int curx
= (n
% width
);
856 // if the # of rows is greater than the # of desktops or <= 0, or
857 // if we're not dealing with a rectangle here, return (invalid condition)
858 if ( width
> total
|| width
<= 0 ||
859 ( total
% width
) != 0 )
862 bool moveLeft
= (num
< 0);
864 wnum
= (curx
% width
== 0) // if we're on the left edge already
865 ? n
+ (width
-1) // move to the far right side
866 : n
-1; // else, just move once left
868 wnum
= (curx
< width
-1) // if we're not on the right side
869 ? n
+ 1 // move once to the right
870 : n
- (width
-1); // else move all the way to the left
872 changeWorkspace(wnum
);
875 bool ScreenHandler::nothingIsPressed(void) const
878 XQueryKeymap(_display
, keys
);
880 for (int i
= 0; i
< 32; ++i
) {
888 const XWindow
*ScreenHandler::lastActiveWindow() const {
889 if (_last_active
!= _clients
.end())
890 return *_last_active
;
892 // find a window if one exists
893 WindowList::const_iterator it
, end
= _clients
.end();
894 for (it
= _clients
.begin(); it
!= end
; ++it
)
895 if ((*it
)->getScreenNumber() == _screenNumber
&& ! (*it
)->iconic() &&
897 ((*it
)->desktop() == 0xffffffff ||
898 (*it
)->desktop() == _active_desktop
))
901 // no windows on this screen
905 void ScreenHandler::p()
907 cout
<< "\nNOW LISTING CLIENTS!!!" << endl
;
909 WindowList::const_iterator it
= _clients
.begin();
910 const WindowList::const_iterator end
= _clients
.end();
912 for (; it
!= end
; ++it
)
915 << "], window: [" << (*it
)->title() << "]" << endl
;