diff --git a/events.cpp b/events.cpp index 400134733..b18e2caa0 100644 --- a/events.cpp +++ b/events.cpp @@ -1,1672 +1,1671 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 Lubos Lunak This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ /* This file contains things relevant to handling incoming events. */ #include #include "client.h" #include "workspace.h" #include "atoms.h" #ifdef KWIN_BUILD_TABBOX #include "tabbox.h" #endif #include "group.h" #include "overlaywindow.h" #include "rules.h" #include "unmanaged.h" #include "effects.h" #include #include #include #include #include #include #include #include namespace KWin { extern int currentRefreshRate(); // **************************************** // WinInfo // **************************************** WinInfo::WinInfo(Client * c, Display * display, Window window, Window rwin, const unsigned long pr[], int pr_size) : NETWinInfo2(display, window, rwin, pr, pr_size, NET::WindowManager), m_client(c) { } void WinInfo::changeDesktop(int desktop) { m_client->workspace()->sendClientToDesktop(m_client, desktop, true); } void WinInfo::changeFullscreenMonitors(NETFullscreenMonitors topology) { m_client->updateFullscreenMonitors(topology); } void WinInfo::changeState(unsigned long state, unsigned long mask) { mask &= ~NET::Sticky; // KWin doesn't support large desktops, ignore mask &= ~NET::Hidden; // clients are not allowed to change this directly state &= mask; // for safety, clear all other bits if ((mask & NET::FullScreen) != 0 && (state & NET::FullScreen) == 0) m_client->setFullScreen(false, false); if ((mask & NET::Max) == NET::Max) m_client->setMaximize(state & NET::MaxVert, state & NET::MaxHoriz); else if (mask & NET::MaxVert) m_client->setMaximize(state & NET::MaxVert, m_client->maximizeMode() & Client::MaximizeHorizontal); else if (mask & NET::MaxHoriz) m_client->setMaximize(m_client->maximizeMode() & Client::MaximizeVertical, state & NET::MaxHoriz); if (mask & NET::Shaded) m_client->setShade(state & NET::Shaded ? ShadeNormal : ShadeNone); if (mask & NET::KeepAbove) m_client->setKeepAbove((state & NET::KeepAbove) != 0); if (mask & NET::KeepBelow) m_client->setKeepBelow((state & NET::KeepBelow) != 0); if (mask & NET::SkipTaskbar) m_client->setSkipTaskbar((state & NET::SkipTaskbar) != 0, true); if (mask & NET::SkipPager) m_client->setSkipPager((state & NET::SkipPager) != 0); if (mask & NET::DemandsAttention) m_client->demandAttention((state & NET::DemandsAttention) != 0); if (mask & NET::Modal) m_client->setModal((state & NET::Modal) != 0); // unsetting fullscreen first, setting it last (because e.g. maximize works only for !isFullScreen() ) if ((mask & NET::FullScreen) != 0 && (state & NET::FullScreen) != 0) m_client->setFullScreen(true, false); } void WinInfo::disable() { m_client = NULL; // only used when the object is passed to Deleted } // **************************************** // RootInfo // **************************************** RootInfo::RootInfo(Workspace* ws, Display *dpy, Window w, const char *name, unsigned long pr[], int pr_num, int scr) : NETRootInfo(dpy, w, name, pr, pr_num, scr) { workspace = ws; } void RootInfo::changeNumberOfDesktops(int n) { workspace->setNumberOfDesktops(n); } void RootInfo::changeCurrentDesktop(int d) { workspace->setCurrentDesktop(d); } void RootInfo::changeActiveWindow(Window w, NET::RequestSource src, Time timestamp, Window active_window) { if (Client* c = workspace->findClient(WindowMatchPredicate(w))) { if (timestamp == CurrentTime) timestamp = c->userTime(); if (src != NET::FromApplication && src != FromTool) src = NET::FromTool; if (src == NET::FromTool) workspace->activateClient(c, true); // force else { // NET::FromApplication Client* c2; if (workspace->allowClientActivation(c, timestamp, false, true)) workspace->activateClient(c); // if activation of the requestor's window would be allowed, allow activation too else if (active_window != None && (c2 = workspace->findClient(WindowMatchPredicate(active_window))) != NULL && workspace->allowClientActivation(c2, timestampCompare(timestamp, c2->userTime() > 0 ? timestamp : c2->userTime()), false, true)) { workspace->activateClient(c); } else c->demandAttention(); } } } void RootInfo::restackWindow(Window w, RequestSource src, Window above, int detail, Time timestamp) { if (Client* c = workspace->findClient(WindowMatchPredicate(w))) { if (timestamp == CurrentTime) timestamp = c->userTime(); if (src != NET::FromApplication && src != FromTool) src = NET::FromTool; c->restackWindow(above, detail, src, timestamp, true); } } void RootInfo::gotTakeActivity(Window w, Time timestamp, long flags) { if (Client* c = workspace->findClient(WindowMatchPredicate(w))) workspace->handleTakeActivity(c, timestamp, flags); } void RootInfo::closeWindow(Window w) { Client* c = workspace->findClient(WindowMatchPredicate(w)); if (c) c->closeWindow(); } void RootInfo::moveResize(Window w, int x_root, int y_root, unsigned long direction) { Client* c = workspace->findClient(WindowMatchPredicate(w)); if (c) { updateXTime(); // otherwise grabbing may have old timestamp - this message should include timestamp c->NETMoveResize(x_root, y_root, (Direction)direction); } } void RootInfo::moveResizeWindow(Window w, int flags, int x, int y, int width, int height) { Client* c = workspace->findClient(WindowMatchPredicate(w)); if (c) c->NETMoveResizeWindow(flags, x, y, width, height); } void RootInfo::gotPing(Window w, Time timestamp) { if (Client* c = workspace->findClient(WindowMatchPredicate(w))) c->gotPing(timestamp); } void RootInfo::changeShowingDesktop(bool showing) { workspace->setShowingDesktop(showing); } // **************************************** // Workspace // **************************************** /*! Handles workspace specific XEvents */ bool Workspace::workspaceEvent(XEvent * e) { if (effects && static_cast< EffectsHandlerImpl* >(effects)->hasKeyboardGrab() && (e->type == KeyPress || e->type == KeyRelease)) return false; // let Qt process it, it'll be intercepted again in eventFilter() if (e->type == PropertyNotify || e->type == ClientMessage) { unsigned long dirty[ NETRootInfo::PROPERTIES_SIZE ]; rootInfo->event(e, dirty, NETRootInfo::PROPERTIES_SIZE); if (dirty[ NETRootInfo::PROTOCOLS ] & NET::DesktopNames) saveDesktopSettings(); if (dirty[ NETRootInfo::PROTOCOLS2 ] & NET::WM2DesktopLayout) updateDesktopLayout(); } // events that should be handled before Clients can get them switch(e->type) { case ButtonPress: case ButtonRelease: was_user_interaction = true; // fallthrough case MotionNotify: #ifdef KWIN_BUILD_TABBOX if (tabBox()->isGrabbed()) { - tab_box->handleMouseEvent(e); - return true; + return tab_box->handleMouseEvent(e); } #endif if (effects && static_cast(effects)->checkInputWindowEvent(e)) return true; break; case KeyPress: { was_user_interaction = true; int keyQt; KKeyServer::xEventToQt(e, &keyQt); // kDebug(125) << "Workspace::keyPress( " << keyQt << " )"; if (movingClient) { movingClient->keyPressEvent(keyQt); return true; } #ifdef KWIN_BUILD_TABBOX if (tabBox()->isGrabbed()) { tabBox()->keyPress(keyQt); return true; } #endif break; } case KeyRelease: was_user_interaction = true; #ifdef KWIN_BUILD_TABBOX if (tabBox()->isGrabbed()) { tabBox()->keyRelease(e->xkey); return true; } #endif break; case ConfigureNotify: if (e->xconfigure.event == rootWindow()) x_stacking_dirty = true; break; }; if (Client* c = findClient(WindowMatchPredicate(e->xany.window))) { if (c->windowEvent(e)) return true; } else if (Client* c = findClient(WrapperIdMatchPredicate(e->xany.window))) { if (c->windowEvent(e)) return true; } else if (Client* c = findClient(FrameIdMatchPredicate(e->xany.window))) { if (c->windowEvent(e)) return true; } else if (Unmanaged* c = findUnmanaged(WindowMatchPredicate(e->xany.window))) { if (c->windowEvent(e)) return true; } else { Window special = findSpecialEventWindow(e); if (special != None) if (Client* c = findClient(WindowMatchPredicate(special))) { if (c->windowEvent(e)) return true; } // We want to pass root window property events to effects if (e->type == PropertyNotify && e->xany.window == rootWindow()) { XPropertyEvent* re = &e->xproperty; emit propertyNotify(re->atom); } } if (movingClient != NULL && movingClient->moveResizeGrabWindow() == e->xany.window && (e->type == MotionNotify || e->type == ButtonPress || e->type == ButtonRelease)) { if (movingClient->windowEvent(e)) return true; } switch(e->type) { case CreateNotify: if (e->xcreatewindow.parent == rootWindow() && !QWidget::find(e->xcreatewindow.window) && !e->xcreatewindow.override_redirect) { // see comments for allowClientActivation() Time t = xTime(); XChangeProperty(display(), e->xcreatewindow.window, atoms->kde_net_wm_user_creation_time, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&t, 1); } break; case UnmapNotify: { return (e->xunmap.event != e->xunmap.window); // hide wm typical event from Qt } case ReparentNotify: { //do not confuse Qt with these events. After all, _we_ are the //window manager who does the reparenting. return true; } case DestroyNotify: { return false; } case MapRequest: { updateXTime(); // e->xmaprequest.window is different from e->xany.window // TODO this shouldn't be necessary now Client* c = findClient(WindowMatchPredicate(e->xmaprequest.window)); if (!c) { // don't check for the parent being the root window, this breaks when some app unmaps // a window, changes something and immediately maps it back, without giving KWin // a chance to reparent it back to root // since KWin can get MapRequest only for root window children and // children of WindowWrapper (=clients), the check is AFAIK useless anyway // Note: Now the save-set support in Client::mapRequestEvent() actually requires that // this code doesn't check the parent to be root. // if ( e->xmaprequest.parent == root ) { c = createClient(e->xmaprequest.window, false); if (c == NULL) // refused to manage, simply map it (most probably override redirect) XMapRaised(display(), e->xmaprequest.window); return true; } if (c) { c->windowEvent(e); updateFocusChains(c, FocusChainUpdate); return true; } break; } case MapNotify: { if (e->xmap.override_redirect) { Unmanaged* c = findUnmanaged(WindowMatchPredicate(e->xmap.window)); if (c == NULL) c = createUnmanaged(e->xmap.window); if (c) return c->windowEvent(e); } return (e->xmap.event != e->xmap.window); // hide wm typical event from Qt } case EnterNotify: { if (QWhatsThis::inWhatsThisMode()) { QWidget* w = QWidget::find(e->xcrossing.window); if (w) QWhatsThis::leaveWhatsThisMode(); } #ifdef KWIN_BUILD_SCREENEDGES if (m_screenEdge.isEntered(e)) return true; #endif break; } case LeaveNotify: { if (!QWhatsThis::inWhatsThisMode()) break; // TODO is this cliente ever found, given that client events are searched above? Client* c = findClient(FrameIdMatchPredicate(e->xcrossing.window)); if (c && e->xcrossing.detail != NotifyInferior) QWhatsThis::leaveWhatsThisMode(); break; } case ConfigureRequest: { if (e->xconfigurerequest.parent == rootWindow()) { XWindowChanges wc; wc.border_width = e->xconfigurerequest.border_width; wc.x = e->xconfigurerequest.x; wc.y = e->xconfigurerequest.y; wc.width = e->xconfigurerequest.width; wc.height = e->xconfigurerequest.height; wc.sibling = None; wc.stack_mode = Above; unsigned int value_mask = e->xconfigurerequest.value_mask & (CWX | CWY | CWWidth | CWHeight | CWBorderWidth); XConfigureWindow(display(), e->xconfigurerequest.window, value_mask, &wc); return true; } break; } case FocusIn: if (e->xfocus.window == rootWindow() && (e->xfocus.detail == NotifyDetailNone || e->xfocus.detail == NotifyPointerRoot)) { updateXTime(); // focusToNull() uses xTime(), which is old now (FocusIn has no timestamp) Window focus; int revert; XGetInputFocus(display(), &focus, &revert); if (focus == None || focus == PointerRoot) { //kWarning( 1212 ) << "X focus set to None/PointerRoot, reseting focus" ; Client *c = mostRecentlyActivatedClient(); if (c != NULL) requestFocus(c, true); else if (activateNextClient(NULL)) ; // ok, activated else focusToNull(); } } // fall through case FocusOut: return true; // always eat these, they would tell Qt that KWin is the active app case ClientMessage: #ifdef KWIN_BUILD_SCREENEDGES if (m_screenEdge.isEntered(e)) return true; #endif break; case Expose: if (compositing() && (e->xexpose.window == rootWindow() // root window needs repainting || (scene->overlayWindow()->window() != None && e->xexpose.window == scene->overlayWindow()->window()))) { // overlay needs repainting addRepaint(e->xexpose.x, e->xexpose.y, e->xexpose.width, e->xexpose.height); } break; case VisibilityNotify: if (compositing() && scene->overlayWindow()->window() != None && e->xvisibility.window == scene->overlayWindow()->window()) { bool was_visible = scene->overlayWindow()->isVisible(); scene->overlayWindow()->setVisibility((e->xvisibility.state != VisibilityFullyObscured)); if (!was_visible && scene->overlayWindow()->isVisible()) { // hack for #154825 addRepaintFull(); QTimer::singleShot(2000, this, SLOT(addRepaintFull())); } checkCompositeTimer(); } break; default: if (e->type == Extensions::randrNotifyEvent() && Extensions::randrAvailable()) { XRRUpdateConfiguration(e); if (compositing()) { // desktopResized() should take care of when the size or // shape of the desktop has changed, but we also want to // catch refresh rate changes if (xrrRefreshRate != currentRefreshRate()) compositeResetTimer.start(0); } } else if (e->type == Extensions::syncAlarmNotifyEvent() && Extensions::syncAvailable()) { #ifdef HAVE_XSYNC foreach (Client * c, clients) c->syncEvent(reinterpret_cast< XSyncAlarmNotifyEvent* >(e)); foreach (Client * c, desktops) c->syncEvent(reinterpret_cast< XSyncAlarmNotifyEvent* >(e)); #endif } break; } return false; } // Used only to filter events that need to be processed by Qt first // (e.g. keyboard input to be composed), otherwise events are // handle by the XEvent filter above bool Workspace::workspaceEvent(QEvent* e) { if ((e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease || e->type() == QEvent::ShortcutOverride) && effects && static_cast< EffectsHandlerImpl* >(effects)->hasKeyboardGrab()) { static_cast< EffectsHandlerImpl* >(effects)->grabbedKeyboardEvent(static_cast< QKeyEvent* >(e)); return true; } return false; } // Some events don't have the actual window which caused the event // as e->xany.window (e.g. ConfigureRequest), but as some other // field in the XEvent structure. Window Workspace::findSpecialEventWindow(XEvent* e) { switch(e->type) { case CreateNotify: return e->xcreatewindow.window; case DestroyNotify: return e->xdestroywindow.window; case UnmapNotify: return e->xunmap.window; case MapNotify: return e->xmap.window; case MapRequest: return e->xmaprequest.window; case ReparentNotify: return e->xreparent.window; case ConfigureNotify: return e->xconfigure.window; case GravityNotify: return e->xgravity.window; case ConfigureRequest: return e->xconfigurerequest.window; case CirculateNotify: return e->xcirculate.window; case CirculateRequest: return e->xcirculaterequest.window; default: return None; }; } // **************************************** // Client // **************************************** /*! General handler for XEvents concerning the client window */ bool Client::windowEvent(XEvent* e) { if (e->xany.window == window()) { // avoid doing stuff on frame or wrapper unsigned long dirty[ 2 ]; double old_opacity = opacity(); info->event(e, dirty, 2); // pass through the NET stuff if ((dirty[ WinInfo::PROTOCOLS ] & NET::WMName) != 0) fetchName(); if ((dirty[ WinInfo::PROTOCOLS ] & NET::WMIconName) != 0) fetchIconicName(); if ((dirty[ WinInfo::PROTOCOLS ] & NET::WMStrut) != 0 || (dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2ExtendedStrut) != 0) { workspace()->updateClientArea(); } if ((dirty[ WinInfo::PROTOCOLS ] & NET::WMIcon) != 0) getIcons(); // Note there's a difference between userTime() and info->userTime() // info->userTime() is the value of the property, userTime() also includes // updates of the time done by KWin (ButtonPress on windowrapper etc.). if ((dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2UserTime) != 0) { workspace()->setWasUserInteraction(); updateUserTime(info->userTime()); } if ((dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2StartupId) != 0) startupIdChanged(); if (dirty[ WinInfo::PROTOCOLS ] & NET::WMIconGeometry) { if (demandAttentionKNotifyTimer != NULL) demandAttentionKNotify(); } if (dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2Opacity) { if (compositing()) { addRepaintFull(); emit opacityChanged(this, old_opacity); } else { // forward to the frame if there's possibly another compositing manager running NETWinInfo2 i(display(), frameId(), rootWindow(), 0); i.setOpacity(info->opacity()); } } if (dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2FrameOverlap) { // ### Inform the decoration } } switch(e->type) { case UnmapNotify: unmapNotifyEvent(&e->xunmap); break; case DestroyNotify: destroyNotifyEvent(&e->xdestroywindow); break; case MapRequest: // this one may pass the event to workspace return mapRequestEvent(&e->xmaprequest); case ConfigureRequest: configureRequestEvent(&e->xconfigurerequest); break; case PropertyNotify: propertyNotifyEvent(&e->xproperty); break; case KeyPress: updateUserTime(); workspace()->setWasUserInteraction(); break; case ButtonPress: updateUserTime(); workspace()->setWasUserInteraction(); buttonPressEvent(e->xbutton.window, e->xbutton.button, e->xbutton.state, e->xbutton.x, e->xbutton.y, e->xbutton.x_root, e->xbutton.y_root); break; case KeyRelease: // don't update user time on releases // e.g. if the user presses Alt+F2, the Alt release // would appear as user input to the currently active window break; case ButtonRelease: // don't update user time on releases // e.g. if the user presses Alt+F2, the Alt release // would appear as user input to the currently active window buttonReleaseEvent(e->xbutton.window, e->xbutton.button, e->xbutton.state, e->xbutton.x, e->xbutton.y, e->xbutton.x_root, e->xbutton.y_root); break; case MotionNotify: motionNotifyEvent(e->xmotion.window, e->xmotion.state, e->xmotion.x, e->xmotion.y, e->xmotion.x_root, e->xmotion.y_root); workspace()->updateFocusMousePosition(QPoint(e->xmotion.x_root, e->xmotion.y_root)); break; case EnterNotify: enterNotifyEvent(&e->xcrossing); // MotionNotify is guaranteed to be generated only if the mouse // move start and ends in the window; for cases when it only // starts or only ends there, Enter/LeaveNotify are generated. // Fake a MotionEvent in such cases to make handle of mouse // events simpler (Qt does that too). motionNotifyEvent(e->xcrossing.window, e->xcrossing.state, e->xcrossing.x, e->xcrossing.y, e->xcrossing.x_root, e->xcrossing.y_root); workspace()->updateFocusMousePosition(QPoint(e->xcrossing.x_root, e->xcrossing.y_root)); break; case LeaveNotify: motionNotifyEvent(e->xcrossing.window, e->xcrossing.state, e->xcrossing.x, e->xcrossing.y, e->xcrossing.x_root, e->xcrossing.y_root); leaveNotifyEvent(&e->xcrossing); // not here, it'd break following enter notify handling // workspace()->updateFocusMousePosition( QPoint( e->xcrossing.x_root, e->xcrossing.y_root )); break; case FocusIn: focusInEvent(&e->xfocus); break; case FocusOut: focusOutEvent(&e->xfocus); break; case ReparentNotify: break; case ClientMessage: clientMessageEvent(&e->xclient); break; case ColormapChangeMask: if (e->xany.window == window()) { cmap = e->xcolormap.colormap; if (isActive()) workspace()->updateColormap(); } break; default: if (e->xany.window == window()) { if (e->type == Extensions::shapeNotifyEvent()) { detectShape(window()); // workaround for #19644 updateShape(); } } if (e->xany.window == frameId()) { if (e->type == Extensions::damageNotifyEvent()) damageNotifyEvent(reinterpret_cast< XDamageNotifyEvent* >(e)); } break; } return true; // eat all events } /*! Handles map requests of the client window */ bool Client::mapRequestEvent(XMapRequestEvent* e) { if (e->window != window()) { // Special support for the save-set feature, which is a bit broken. // If there's a window from one client embedded in another one, // e.g. using XEMBED, and the embedder suddenly loses its X connection, // save-set will reparent the embedded window to its closest ancestor // that will remains. Unfortunately, with reparenting window managers, // this is not the root window, but the frame (or in KWin's case, // it's the wrapper for the client window). In this case, // the wrapper will get ReparentNotify for a window it won't know, // which will be ignored, and then it gets MapRequest, as save-set // always maps. Returning true here means that Workspace::workspaceEvent() // will handle this MapRequest and manage this window (i.e. act as if // it was reparented to root window). if (e->parent == wrapperId()) return false; return true; // no messing with frame etc. } // also copied in clientMessage() if (isMinimized()) unminimize(); if (isShade()) setShade(ShadeNone); if (!isOnCurrentDesktop()) { if (workspace()->allowClientActivation(this)) workspace()->activateClient(this); else demandAttention(); } return true; } /*! Handles unmap notify events of the client window */ void Client::unmapNotifyEvent(XUnmapEvent* e) { if (e->window != window()) return; if (e->event != wrapperId()) { // most probably event from root window when initially reparenting bool ignore = true; if (e->event == rootWindow() && e->send_event) ignore = false; // XWithdrawWindow() if (ignore) return; } releaseWindow(); } void Client::destroyNotifyEvent(XDestroyWindowEvent* e) { if (e->window != window()) return; destroyClient(); } /*! Handles client messages for the client window */ void Client::clientMessageEvent(XClientMessageEvent* e) { if (e->window != window()) return; // ignore frame/wrapper // WM_STATE if (e->message_type == atoms->kde_wm_change_state) { bool avoid_animation = (e->data.l[ 1 ]); if (e->data.l[ 0 ] == IconicState) minimize(); else if (e->data.l[ 0 ] == NormalState) { // copied from mapRequest() if (isMinimized()) unminimize(avoid_animation); if (isShade()) setShade(ShadeNone); if (!isOnCurrentDesktop()) { if (workspace()->allowClientActivation(this)) workspace()->activateClient(this); else demandAttention(); } } } else if (e->message_type == atoms->wm_change_state) { if (e->data.l[0] == IconicState) minimize(); return; } } /*! Handles configure requests of the client window */ void Client::configureRequestEvent(XConfigureRequestEvent* e) { if (e->window != window()) return; // ignore frame/wrapper if (isResize() || isMove()) return; // we have better things to do right now if (fullscreen_mode == FullScreenNormal) { // refuse resizing of fullscreen windows // but allow resizing fullscreen hacks in order to let them cancel fullscreen mode sendSyntheticConfigureNotify(); return; } if (isSplash()) { // no manipulations with splashscreens either sendSyntheticConfigureNotify(); return; } if (e->value_mask & CWBorderWidth) { // first, get rid of a window border XWindowChanges wc; unsigned int value_mask = 0; wc.border_width = 0; value_mask = CWBorderWidth; XConfigureWindow(display(), window(), value_mask, & wc); } if (e->value_mask & (CWX | CWY | CWHeight | CWWidth)) configureRequest(e->value_mask, e->x, e->y, e->width, e->height, 0, false); if (e->value_mask & CWStackMode) restackWindow(e->above, e->detail, NET::FromApplication, userTime(), false); // Sending a synthetic configure notify always is fine, even in cases where // the ICCCM doesn't require this - it can be though of as 'the WM decided to move // the window later'. The client should not cause that many configure request, // so this should not have any significant impact. With user moving/resizing // the it should be optimized though (see also Client::setGeometry()/plainResize()/move()). sendSyntheticConfigureNotify(); // SELI TODO accept configure requests for isDesktop windows (because kdesktop // may get XRANDR resize event before kwin), but check it's still at the bottom? } /*! Handles property changes of the client window */ void Client::propertyNotifyEvent(XPropertyEvent* e) { Toplevel::propertyNotifyEvent(e); if (e->window != window()) return; // ignore frame/wrapper switch(e->atom) { case XA_WM_NORMAL_HINTS: getWmNormalHints(); break; case XA_WM_NAME: fetchName(); break; case XA_WM_ICON_NAME: fetchIconicName(); break; case XA_WM_TRANSIENT_FOR: readTransient(); break; case XA_WM_HINTS: getWMHints(); getIcons(); // because KWin::icon() uses WMHints as fallback break; default: if (e->atom == atoms->wm_protocols) getWindowProtocols(); else if (e->atom == atoms->motif_wm_hints) getMotifHints(); else if (e->atom == atoms->net_wm_sync_request_counter) getSyncCounter(); else if (e->atom == atoms->activities) checkActivities(); else if (e->atom == atoms->kde_net_wm_block_compositing) updateCompositeBlocking(true); break; } } void Client::enterNotifyEvent(XCrossingEvent* e) { if (e->window != frameId()) return; // care only about entering the whole frame if (e->mode == NotifyNormal || (!options->focusPolicyIsReasonable() && e->mode == NotifyUngrab)) { if (options->shadeHover) { cancelShadeHoverTimer(); if (isShade()) { shadeHoverTimer = new QTimer(this); connect(shadeHoverTimer, SIGNAL(timeout()), this, SLOT(shadeHover())); shadeHoverTimer->setSingleShot(true); shadeHoverTimer->start(options->shadeHoverInterval); } } if (options->focusPolicy == Options::ClickToFocus) return; if (options->autoRaise && !isDesktop() && !isDock() && workspace()->focusChangeEnabled() && workspace()->topClientOnDesktop(workspace()->currentDesktop(), options->separateScreenFocus ? screen() : -1) != this) { delete autoRaiseTimer; autoRaiseTimer = new QTimer(this); connect(autoRaiseTimer, SIGNAL(timeout()), this, SLOT(autoRaise())); autoRaiseTimer->setSingleShot(true); autoRaiseTimer->start(options->autoRaiseInterval); } QPoint currentPos(e->x_root, e->y_root); if (options->focusPolicy != Options::FocusStrictlyUnderMouse && (isDesktop() || isDock())) return; // for FocusFollowsMouse, change focus only if the mouse has actually been moved, not if the focus // change came because of window changes (e.g. closing a window) - #92290 if (options->focusPolicy != Options::FocusFollowsMouse || currentPos != workspace()->focusMousePosition()) { if (options->delayFocus) workspace()->requestDelayFocus(this); else workspace()->requestFocus(this); } return; } } void Client::leaveNotifyEvent(XCrossingEvent* e) { if (e->window != frameId()) return; // care only about leaving the whole frame if (e->mode == NotifyNormal) { if (!buttonDown) { mode = PositionCenter; updateCursor(); } bool lostMouse = !rect().contains(QPoint(e->x, e->y)); // 'lostMouse' wouldn't work with e.g. B2 or Keramik, which have non-rectangular decorations // (i.e. the LeaveNotify event comes before leaving the rect and no LeaveNotify event // comes after leaving the rect) - so lets check if the pointer is really outside the window // TODO this still sucks if a window appears above this one - it should lose the mouse // if this window is another client, but not if it's a popup ... maybe after KDE3.1 :( // (repeat after me 'AARGHL!') if (!lostMouse && e->detail != NotifyInferior) { int d1, d2, d3, d4; unsigned int d5; Window w, child; if (XQueryPointer(display(), frameId(), &w, &child, &d1, &d2, &d3, &d4, &d5) == False || child == None) lostMouse = true; // really lost the mouse } if (lostMouse) { cancelAutoRaise(); workspace()->cancelDelayFocus(); cancelShadeHoverTimer(); if (shade_mode == ShadeHover && !moveResizeMode && !buttonDown) { shadeHoverTimer = new QTimer(this); connect(shadeHoverTimer, SIGNAL(timeout()), this, SLOT(shadeUnhover())); shadeHoverTimer->setSingleShot(true); shadeHoverTimer->start(options->shadeHoverInterval); } } if (options->focusPolicy == Options::FocusStrictlyUnderMouse) if (isActive() && lostMouse) workspace()->requestFocus(0) ; return; } } #define XCapL KKeyServer::modXLock() #define XNumL KKeyServer::modXNumLock() #define XScrL KKeyServer::modXScrollLock() void Client::grabButton(int modifier) { unsigned int mods[ 8 ] = { 0, XCapL, XNumL, XNumL | XCapL, XScrL, XScrL | XCapL, XScrL | XNumL, XScrL | XNumL | XCapL }; for (int i = 0; i < 8; ++i) XGrabButton(display(), AnyButton, modifier | mods[ i ], wrapperId(), false, ButtonPressMask, GrabModeSync, GrabModeAsync, None, None); } void Client::ungrabButton(int modifier) { unsigned int mods[ 8 ] = { 0, XCapL, XNumL, XNumL | XCapL, XScrL, XScrL | XCapL, XScrL | XNumL, XScrL | XNumL | XCapL }; for (int i = 0; i < 8; ++i) XUngrabButton(display(), AnyButton, modifier | mods[ i ], wrapperId()); } #undef XCapL #undef XNumL #undef XScrL /* Releases the passive grab for some modifier combinations when a window becomes active. This helps broken X programs that missinterpret LeaveNotify events in grab mode to work properly (Motif, AWT, Tk, ...) */ void Client::updateMouseGrab() { if (workspace()->globalShortcutsDisabled()) { XUngrabButton(display(), AnyButton, AnyModifier, wrapperId()); // keep grab for the simple click without modifiers if needed (see below) bool not_obscured = workspace()->topClientOnDesktop(workspace()->currentDesktop(), -1, true, false) == this; if (!(!options->clickRaise || not_obscured)) grabButton(None); return; } if (isActive() && !workspace()->forcedGlobalMouseGrab()) { // see Workspace::establishTabBoxGrab() // first grab all modifier combinations XGrabButton(display(), AnyButton, AnyModifier, wrapperId(), false, ButtonPressMask, GrabModeSync, GrabModeAsync, None, None); // remove the grab for no modifiers only if the window // is unobscured or if the user doesn't want click raise // (it is unobscured if it the topmost in the unconstrained stacking order, i.e. it is // the most recently raised window) bool not_obscured = workspace()->topClientOnDesktop(workspace()->currentDesktop(), -1, true, false) == this; if (!options->clickRaise || not_obscured) ungrabButton(None); else grabButton(None); ungrabButton(ShiftMask); ungrabButton(ControlMask); ungrabButton(ControlMask | ShiftMask); } else { XUngrabButton(display(), AnyButton, AnyModifier, wrapperId()); // simply grab all modifier combinations XGrabButton(display(), AnyButton, AnyModifier, wrapperId(), false, ButtonPressMask, GrabModeSync, GrabModeAsync, None, None); } } // Qt propagates mouse events up the widget hierachy, which means events // for the decoration window cannot be (easily) intercepted as X11 events bool Client::eventFilter(QObject* o, QEvent* e) { if (decoration == NULL || o != decoration->widget()) return false; if (e->type() == QEvent::MouseButtonPress) { QMouseEvent* ev = static_cast< QMouseEvent* >(e); return buttonPressEvent(decorationId(), qtToX11Button(ev->button()), qtToX11State(ev->buttons(), ev->modifiers()), ev->x(), ev->y(), ev->globalX(), ev->globalY()); } if (e->type() == QEvent::MouseButtonRelease) { QMouseEvent* ev = static_cast< QMouseEvent* >(e); return buttonReleaseEvent(decorationId(), qtToX11Button(ev->button()), qtToX11State(ev->buttons(), ev->modifiers()), ev->x(), ev->y(), ev->globalX(), ev->globalY()); } if (e->type() == QEvent::MouseMove) { // FRAME i fake z enter/leave? QMouseEvent* ev = static_cast< QMouseEvent* >(e); return motionNotifyEvent(decorationId(), qtToX11State(ev->buttons(), ev->modifiers()), ev->x(), ev->y(), ev->globalX(), ev->globalY()); } if (e->type() == QEvent::Wheel) { QWheelEvent* ev = static_cast< QWheelEvent* >(e); bool r = buttonPressEvent(decorationId(), ev->delta() > 0 ? Button4 : Button5, qtToX11State(ev->buttons(), ev->modifiers()), ev->x(), ev->y(), ev->globalX(), ev->globalY()); r = r || buttonReleaseEvent(decorationId(), ev->delta() > 0 ? Button4 : Button5, qtToX11State(ev->buttons(), ev->modifiers()), ev->x(), ev->y(), ev->globalX(), ev->globalY()); return r; } if (e->type() == QEvent::Resize) { QResizeEvent* ev = static_cast< QResizeEvent* >(e); // Filter out resize events that inform about size different than frame size. // This will ensure that decoration->width() etc. and decoration->widget()->width() will be in sync. // These events only seem to be delayed events from initial resizing before show() was called // on the decoration widget. if (ev->size() != (size() + QSize(padding_left + padding_right, padding_top + padding_bottom))) return true; // HACK: Avoid decoration redraw delays. On resize Qt sets WA_WStateConfigPending // which delays all painting until a matching ConfigureNotify event comes. // But this process itself is the window manager, so it's not needed // to wait for that event, the geometry is known. // Note that if Qt in the future changes how this flag is handled and what it // triggers then this may potentionally break things. See mainly QETWidget::translateConfigEvent(). decoration->widget()->setAttribute(Qt::WA_WState_ConfigPending, false); decoration->widget()->update(); return false; } return false; } // return value matters only when filtering events before decoration gets them bool Client::buttonPressEvent(Window w, int button, int state, int x, int y, int x_root, int y_root) { if (buttonDown) { if (w == wrapperId()) XAllowEvents(display(), SyncPointer, CurrentTime); //xTime()); return true; } if (w == wrapperId() || w == frameId() || w == decorationId()) { // FRAME neco s tohohle by se melo zpracovat, nez to dostane dekorace updateUserTime(); workspace()->setWasUserInteraction(); uint keyModX = (options->keyCmdAllModKey() == Qt::Key_Meta) ? KKeyServer::modXMeta() : KKeyServer::modXAlt(); bool bModKeyHeld = keyModX != 0 && (state & KKeyServer::accelModMaskX()) == keyModX; if (isSplash() && button == Button1 && !bModKeyHeld) { // hide splashwindow if the user clicks on it hideClient(true); if (w == wrapperId()) XAllowEvents(display(), SyncPointer, CurrentTime); //xTime()); return true; } Options::MouseCommand com = Options::MouseNothing; bool was_action = false; bool perform_handled = false; if (bModKeyHeld) { was_action = true; switch(button) { case Button1: com = options->commandAll1(); break; case Button2: com = options->commandAll2(); break; case Button3: com = options->commandAll3(); break; case Button4: case Button5: com = options->operationWindowMouseWheel(button == Button4 ? 120 : -120); break; } } else { // inactive inner window if (!isActive() && w == wrapperId() && button < 6) { was_action = true; perform_handled = true; switch(button) { case Button1: com = options->commandWindow1(); break; case Button2: com = options->commandWindow2(); break; case Button3: com = options->commandWindow3(); break; case Button4: case Button5: com = options->commandWindowWheel(); break; } } // active inner window if (isActive() && w == wrapperId() && options->clickRaise && button < 4) { // exclude wheel com = Options::MouseActivateRaiseAndPassClick; was_action = true; perform_handled = true; } } if (was_action) { bool replay = performMouseCommand(com, QPoint(x_root, y_root), perform_handled); if (isSpecialWindow()) replay = true; if (w == wrapperId()) // these can come only from a grab XAllowEvents(display(), replay ? ReplayPointer : SyncPointer, CurrentTime); //xTime()); return true; } } if (w == wrapperId()) { // these can come only from a grab XAllowEvents(display(), ReplayPointer, CurrentTime); //xTime()); return true; } if (w == decorationId()) { if (dynamic_cast(decoration)) // New API processes core events FIRST and only passes unused ones to the decoration return processDecorationButtonPress(button, state, x, y, x_root, y_root, true); else return false; // Don't eat old API decoration events } if (w == frameId()) processDecorationButtonPress(button, state, x, y, x_root, y_root); return true; } // this function processes button press events only after decoration decides not to handle them, // unlike buttonPressEvent(), which (when the window is decoration) filters events before decoration gets them bool Client::processDecorationButtonPress(int button, int /*state*/, int x, int y, int x_root, int y_root, bool ignoreMenu) { Options::MouseCommand com = Options::MouseNothing; bool active = isActive(); if (!wantsInput()) // we cannot be active, use it anyway active = true; if (button == Button1) com = active ? options->commandActiveTitlebar1() : options->commandInactiveTitlebar1(); else if (button == Button2) com = active ? options->commandActiveTitlebar2() : options->commandInactiveTitlebar2(); else if (button == Button3) com = active ? options->commandActiveTitlebar3() : options->commandInactiveTitlebar3(); if (button == Button1 && com != Options::MouseOperationsMenu // actions where it's not possible to get the matching && com != Options::MouseMinimize // mouse release event && com != Options::MouseClientGroupDrag) { mode = mousePosition(QPoint(x, y)); buttonDown = true; moveOffset = QPoint(x - padding_left, y - padding_top); invertedMoveOffset = rect().bottomRight() - moveOffset; unrestrictedMoveResize = false; startDelayedMoveResize(); updateCursor(); } // In the new API the decoration may process the menu action to display an inactive tab's menu. // If the event is unhandled then the core will create one for the active window in the group. if (!ignoreMenu || com != Options::MouseOperationsMenu) performMouseCommand(com, QPoint(x_root, y_root)); return !( // Return events that should be passed to the decoration in the new API com == Options::MouseRaise || com == Options::MouseOperationsMenu || com == Options::MouseActivateAndRaise || com == Options::MouseActivate || com == Options::MouseActivateRaiseAndPassClick || com == Options::MouseActivateAndPassClick || com == Options::MouseClientGroupDrag || com == Options::MouseNothing); } // called from decoration void Client::processMousePressEvent(QMouseEvent* e) { if (e->type() != QEvent::MouseButtonPress) { kWarning(1212) << "processMousePressEvent()" ; return; } int button; switch(e->button()) { case Qt::LeftButton: button = Button1; break; case Qt::MidButton: button = Button2; break; case Qt::RightButton: button = Button3; break; default: return; } processDecorationButtonPress(button, e->buttons(), e->x(), e->y(), e->globalX(), e->globalY()); } // return value matters only when filtering events before decoration gets them bool Client::buttonReleaseEvent(Window w, int /*button*/, int state, int x, int y, int x_root, int y_root) { if (w == decorationId() && !buttonDown) return false; if (w == wrapperId()) { XAllowEvents(display(), SyncPointer, CurrentTime); //xTime()); return true; } if (w != frameId() && w != decorationId() && w != moveResizeGrabWindow()) return true; x = this->x(); // translate from grab window to local coords y = this->y(); if ((state & (Button1Mask & Button2Mask & Button3Mask)) == 0) { buttonDown = false; stopDelayedMoveResize(); if (moveResizeMode) { finishMoveResize(false); // mouse position is still relative to old Client position, adjust it QPoint mousepos(x_root - x + padding_left, y_root - y + padding_top); mode = mousePosition(mousepos); } else if (workspace()->decorationSupportsClientGrouping()) return false; updateCursor(); } return true; } static bool was_motion = false; static Time next_motion_time = CurrentTime; // Check whole incoming X queue for MotionNotify events // checking whole queue is done by always returning False in the predicate. // If there are more MotionNotify events in the queue, all until the last // one may be safely discarded (if a ButtonRelease event comes, a MotionNotify // will be faked from it, so there's no need to check other events). // This helps avoiding being overloaded by being flooded from many events // from the XServer. static Bool motion_predicate(Display*, XEvent* ev, XPointer) { if (ev->type == MotionNotify) { was_motion = true; next_motion_time = ev->xmotion.time; // for setting time } return False; } static bool waitingMotionEvent() { // The queue doesn't need to be checked until the X timestamp // of processes events reaches the timestamp of the last suitable // MotionNotify event in the queue. if (next_motion_time != CurrentTime && timestampCompare(xTime(), next_motion_time) < 0) return true; was_motion = false; XSync(display(), False); // this helps to discard more MotionNotify events XEvent dummy; XCheckIfEvent(display(), &dummy, motion_predicate, NULL); return was_motion; } // Checks if the mouse cursor is near the edge of the screen and if so activates quick tiling or maximization void Client::checkQuickTilingMaximizationZones(int xroot, int yroot) { QuickTileMode mode = QuickTileNone; foreach (Kephal::Screen * screen, Kephal::Screens::self()->screens()) { const QRect &area = screen->geom(); if (!area.contains(QPoint(xroot, yroot))) continue; if (options->electricBorderTiling()) { if (xroot <= screen->geom().x() + 20) mode |= QuickTileLeft; else if (xroot >= area.x() + area.width() - 20) mode |= QuickTileRight; } if (mode != QuickTileNone) { if (yroot <= area.y() + area.height() / 4) mode |= QuickTileTop; else if (yroot >= area.y() + area.height() - area.height() / 4) mode |= QuickTileBottom; } else if (options->electricBorderMaximize() && yroot <= area.y() + 5 && isMaximizable()) mode = QuickTileMaximize; break; // no point in checking other screens to contain this... "point"... } setElectricBorderMode(mode); setElectricBorderMaximizing(mode != QuickTileNone); } // return value matters only when filtering events before decoration gets them bool Client::motionNotifyEvent(Window w, int /*state*/, int x, int y, int x_root, int y_root) { if (w != frameId() && w != decorationId() && w != moveResizeGrabWindow()) return true; // care only about the whole frame if (!buttonDown) { QPoint mousePos(x, y); if (w == frameId()) mousePos += QPoint(padding_left, padding_top); Position newmode = mousePosition(mousePos); if (newmode != mode) { mode = newmode; updateCursor(); } // reset the timestamp for the optimization, otherwise with long passivity // the option in waitingMotionEvent() may be always true next_motion_time = CurrentTime; return false; } if (w == moveResizeGrabWindow()) { x = this->x(); // translate from grab window to local coords y = this->y(); } if (!waitingMotionEvent()) { handleMoveResize(x, y, x_root, y_root); if (isMove() && isResizable()) checkQuickTilingMaximizationZones(x_root, y_root); } return true; } void Client::focusInEvent(XFocusInEvent* e) { if (e->window != window()) return; // only window gets focus if (e->mode == NotifyUngrab) return; // we don't care if (e->detail == NotifyPointer) return; // we don't care if (!isShown(false) || !isOnCurrentDesktop()) // we unmapped it, but it got focus meanwhile -> return; // activateNextClient() already transferred focus elsewhere // check if this client is in should_get_focus list or if activation is allowed bool activate = workspace()->allowClientActivation(this, -1U, true); workspace()->gotFocusIn(this); // remove from should_get_focus list if (activate) setActive(true); else { workspace()->restoreFocus(); demandAttention(); } } // When a client loses focus, FocusOut events are usually immediatelly // followed by FocusIn events for another client that gains the focus // (unless the focus goes to another screen, or to the nofocus widget). // Without this check, the former focused client would have to be // deactivated, and after that, the new one would be activated, with // a short time when there would be no active client. This can cause // flicker sometimes, e.g. when a fullscreen is shown, and focus is transferred // from it to its transient, the fullscreen would be kept in the Active layer // at the beginning and at the end, but not in the middle, when the active // client would be temporarily none (see Client::belongToLayer() ). // Therefore, the events queue is checked, whether it contains the matching // FocusIn event, and if yes, deactivation of the previous client will // be skipped, as activation of the new one will automatically deactivate // previously active client. static bool follows_focusin = false; static bool follows_focusin_failed = false; static Bool predicate_follows_focusin(Display*, XEvent* e, XPointer arg) { if (follows_focusin || follows_focusin_failed) return False; Client* c = (Client*) arg; if (e->type == FocusIn && c->workspace()->findClient(WindowMatchPredicate(e->xfocus.window))) { // found FocusIn follows_focusin = true; return False; } // events that may be in the queue before the FocusIn event that's being // searched for if (e->type == FocusIn || e->type == FocusOut || e->type == KeymapNotify) return False; follows_focusin_failed = true; // a different event - stop search return False; } static bool check_follows_focusin(Client* c) { follows_focusin = follows_focusin_failed = false; XEvent dummy; // XCheckIfEvent() is used to make the search non-blocking, the predicate // always returns False, so nothing is removed from the events queue. // XPeekIfEvent() would block. XCheckIfEvent(display(), &dummy, predicate_follows_focusin, (XPointer)c); return follows_focusin; } void Client::focusOutEvent(XFocusOutEvent* e) { if (e->window != window()) return; // only window gets focus if (e->mode == NotifyGrab) return; // we don't care if (isShade()) return; // here neither if (e->detail != NotifyNonlinear && e->detail != NotifyNonlinearVirtual) // SELI check all this return; // hack for motif apps like netscape if (QApplication::activePopupWidget()) return; if (!check_follows_focusin(this)) setActive(false); } // performs _NET_WM_MOVERESIZE void Client::NETMoveResize(int x_root, int y_root, NET::Direction direction) { if (direction == NET::Move) performMouseCommand(Options::MouseMove, QPoint(x_root, y_root)); else if (moveResizeMode && direction == NET::MoveResizeCancel) { finishMoveResize(true); buttonDown = false; updateCursor(); } else if (direction >= NET::TopLeft && direction <= NET::Left) { static const Position convert[] = { PositionTopLeft, PositionTop, PositionTopRight, PositionRight, PositionBottomRight, PositionBottom, PositionBottomLeft, PositionLeft }; if (!isResizable() || isShade()) return; if (moveResizeMode) finishMoveResize(false); buttonDown = true; moveOffset = QPoint(x_root - x(), y_root - y()); // map from global invertedMoveOffset = rect().bottomRight() - moveOffset; unrestrictedMoveResize = false; mode = convert[ direction ]; if (!startMoveResize()) buttonDown = false; updateCursor(); } else if (direction == NET::KeyboardMove) { // ignore mouse coordinates given in the message, mouse position is used by the moving algorithm QCursor::setPos(geometry().center()); performMouseCommand(Options::MouseUnrestrictedMove, geometry().center()); } else if (direction == NET::KeyboardSize) { // ignore mouse coordinates given in the message, mouse position is used by the resizing algorithm QCursor::setPos(geometry().bottomRight()); performMouseCommand(Options::MouseUnrestrictedResize, geometry().bottomRight()); } } void Client::keyPressEvent(uint key_code) { updateUserTime(); if (!isMove() && !isResize()) return; bool is_control = key_code & Qt::CTRL; bool is_alt = key_code & Qt::ALT; key_code = key_code & ~Qt::KeyboardModifierMask; int delta = is_control ? 1 : is_alt ? 32 : 8; QPoint pos = cursorPos(); switch(key_code) { case Qt::Key_Left: pos.rx() -= delta; break; case Qt::Key_Right: pos.rx() += delta; break; case Qt::Key_Up: pos.ry() -= delta; break; case Qt::Key_Down: pos.ry() += delta; break; case Qt::Key_Space: case Qt::Key_Return: case Qt::Key_Enter: finishMoveResize(false); buttonDown = false; updateCursor(); break; case Qt::Key_Escape: finishMoveResize(true); buttonDown = false; updateCursor(); break; default: return; } QCursor::setPos(pos); } #ifdef HAVE_XSYNC void Client::syncEvent(XSyncAlarmNotifyEvent* e) { if (e->alarm == syncRequest.alarm && XSyncValueEqual(e->counter_value, syncRequest.value)) { ready_for_painting = true; syncRequest.isPending = false; if (syncRequest.failsafeTimeout) syncRequest.failsafeTimeout->stop(); if (isResize()) { if (syncRequest.timeout) syncRequest.timeout->stop(); performMoveResize(); } else addRepaintFull(); } } #endif // **************************************** // Unmanaged // **************************************** bool Unmanaged::windowEvent(XEvent* e) { double old_opacity = opacity(); unsigned long dirty[ 2 ]; info->event(e, dirty, 2); // pass through the NET stuff if (dirty[ NETWinInfo::PROTOCOLS2 ] & NET::WM2Opacity) { if (compositing()) { addRepaintFull(); emit opacityChanged(this, old_opacity); } } switch(e->type) { case UnmapNotify: unmapNotifyEvent(&e->xunmap); break; case MapNotify: mapNotifyEvent(&e->xmap); break; case ConfigureNotify: configureNotifyEvent(&e->xconfigure); break; case PropertyNotify: propertyNotifyEvent(&e->xproperty); break; default: { if (e->type == Extensions::shapeNotifyEvent()) { detectShape(window()); addRepaintFull(); addWorkspaceRepaint(geometry()); // in case shape change removes part of this window emit geometryShapeChanged(this, geometry()); } if (e->type == Extensions::damageNotifyEvent()) damageNotifyEvent(reinterpret_cast< XDamageNotifyEvent* >(e)); break; } } return false; // don't eat events, even our own unmanaged widgets are tracked } void Unmanaged::mapNotifyEvent(XMapEvent*) { } void Unmanaged::unmapNotifyEvent(XUnmapEvent*) { release(); } void Unmanaged::configureNotifyEvent(XConfigureEvent* e) { if (effects) static_cast(effects)->checkInputWindowStacking(); // keep them on top QRect newgeom(e->x, e->y, e->width, e->height); if (newgeom != geom) { addWorkspaceRepaint(visibleRect()); // damage old area QRect old = geom; geom = newgeom; addRepaintFull(); if (old.size() != geom.size()) discardWindowPixmap(); emit geometryShapeChanged(this, old); } } // **************************************** // Toplevel // **************************************** void Toplevel::propertyNotifyEvent(XPropertyEvent* e) { if (e->window != window()) return; // ignore frame/wrapper switch(e->atom) { default: if (e->atom == atoms->wm_client_leader) getWmClientLeader(); else if (e->atom == atoms->wm_window_role) getWindowRole(); else if (e->atom == atoms->kde_net_wm_shadow) getShadow(); else if (e->atom == atoms->kde_net_wm_opaque_region) getWmOpaqueRegion(); break; } emit propertyNotify(this, e->atom); } // **************************************** // Group // **************************************** bool Group::groupEvent(XEvent* e) { unsigned long dirty[ 2 ]; leader_info->event(e, dirty, 2); // pass through the NET stuff if ((dirty[ WinInfo::PROTOCOLS2 ] & NET::WM2StartupId) != 0) startupIdChanged(); return false; } } // namespace diff --git a/tabbox/declarative.cpp b/tabbox/declarative.cpp index 156749713..1567964d9 100644 --- a/tabbox/declarative.cpp +++ b/tabbox/declarative.cpp @@ -1,195 +1,201 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2011 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ // own #include "declarative.h" #include "tabboxhandler.h" #include "clientmodel.h" // Qt #include #include #include #include #include // include KDE #include #include #include #include #include #include #include #include #include namespace KWin { namespace TabBox { ImageProvider::ImageProvider(QAbstractItemModel *model) : QDeclarativeImageProvider(QDeclarativeImageProvider::Pixmap) , m_model(model) { } QPixmap ImageProvider::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) { bool ok = false; QStringList parts = id.split('/'); const int row = parts.first().toInt(&ok); if (!ok) { return QDeclarativeImageProvider::requestPixmap(id, size, requestedSize); } const QModelIndex index = m_model->index(row, 0); if (!index.isValid()) { return QDeclarativeImageProvider::requestPixmap(id, size, requestedSize); } TabBoxClient* client = static_cast< TabBoxClient* >(index.model()->data(index, ClientModel::ClientRole).value()); QSize s(32, 32); if (requestedSize.isValid()) { s = requestedSize; } *size = s; QPixmap icon = client->icon(s); if (parts.size() > 2) { KIconEffect *effect = KIconLoader::global()->iconEffect(); KIconLoader::States state = KIconLoader::DefaultState; if (parts.at(2) == QLatin1String("selected")) { state = KIconLoader::ActiveState; } else if (parts.at(2) == QLatin1String("disabled")) { state = KIconLoader::DisabledState; } icon = effect->apply(icon, KIconLoader::Desktop, state); } return icon; } DeclarativeView::DeclarativeView(QAbstractItemModel *model, QWidget *parent) : QDeclarativeView(parent) , m_model(model) , m_currentScreenGeometry() , m_frame(new Plasma::FrameSvg(this)) , m_currentLayout() { setAttribute(Qt::WA_TranslucentBackground); setWindowFlags(Qt::X11BypassWindowManagerHint); setResizeMode(QDeclarativeView::SizeViewToRootObject); QPalette pal = palette(); pal.setColor(backgroundRole(), Qt::transparent); setPalette(pal); foreach (const QString &importPath, KGlobal::dirs()->findDirs("module", "imports")) { engine()->addImportPath(importPath); } engine()->addImageProvider(QLatin1String("client"), new ImageProvider(model)); KDeclarative kdeclarative; kdeclarative.setDeclarativeEngine(engine()); kdeclarative.initialize(); kdeclarative.setupBindings(); rootContext()->setContextProperty("clientModel", model); updateQmlSource(); // FrameSvg m_frame->setImagePath("dialogs/background"); m_frame->setCacheAllRenderedFrames(true); m_frame->setEnabledBorders(Plasma::FrameSvg::AllBorders); connect(tabBox, SIGNAL(configChanged()), SLOT(updateQmlSource())); } void DeclarativeView::showEvent(QShowEvent *event) { m_currentScreenGeometry = Kephal::ScreenUtils::screenGeometry(tabBox->activeScreen()); rootObject()->setProperty("screenWidth", m_currentScreenGeometry.width()); rootObject()->setProperty("screenHeight", m_currentScreenGeometry.height()); rootObject()->setProperty("allDesktops", tabBox->config().tabBoxMode() == TabBoxConfig::ClientTabBox && ((tabBox->config().clientListMode() == TabBoxConfig::AllDesktopsClientList) || (tabBox->config().clientListMode() == TabBoxConfig::AllDesktopsApplicationList))); rootObject()->setProperty("longestCaption", static_cast(m_model)->longestCaption()); if (QObject *item = rootObject()->findChild("listView")) { item->setProperty("currentIndex", tabBox->first().row()); + connect(item, SIGNAL(currentIndexChanged(int)), SLOT(currentIndexChanged(int))); } slotUpdateGeometry(); QGraphicsView::showEvent(event); } void DeclarativeView::resizeEvent(QResizeEvent *event) { m_frame->resizeFrame(event->size()); if (Plasma::Theme::defaultTheme()->windowTranslucencyEnabled()) { // blur background Plasma::WindowEffects::enableBlurBehind(winId(), true, m_frame->mask()); Plasma::WindowEffects::overrideShadow(winId(), true); } else { // do not trim to mask with compositing enabled, otherwise shadows are cropped setMask(m_frame->mask()); } QDeclarativeView::resizeEvent(event); } void DeclarativeView::slotUpdateGeometry() { const int width = rootObject()->property("width").toInt(); const int height = rootObject()->property("height").toInt(); setGeometry(m_currentScreenGeometry.x() + static_cast(m_currentScreenGeometry.width()) * 0.5 - static_cast(width) * 0.5, m_currentScreenGeometry.y() + static_cast(m_currentScreenGeometry.height()) * 0.5 - static_cast(height) * 0.5, width, height); } void DeclarativeView::setCurrentIndex(const QModelIndex &index) { if (QObject *item = rootObject()->findChild("listView")) { item->setProperty("currentIndex", index.row()); } } QModelIndex DeclarativeView::indexAt(const QPoint &pos) const { if (QObject *item = rootObject()->findChild("listView")) { QVariant returnedValue; QVariant xPos(pos.x()); QVariant yPos(pos.y()); QMetaObject::invokeMethod(item, "indexAtMousePos", Q_RETURN_ARG(QVariant, returnedValue), Q_ARG(QVariant, QVariant(pos))); if (!returnedValue.canConvert()) { return QModelIndex(); } return m_model->index(returnedValue.toInt(), 0); } return QModelIndex(); } +void DeclarativeView::currentIndexChanged(int row) +{ + tabBox->setCurrentIndex(m_model->index(row, 0)); +} + void DeclarativeView::updateQmlSource() { if (tabBox->config().layoutName() == m_currentLayout) { return; } m_currentLayout = tabBox->config().layoutName(); setSource(QUrl(KStandardDirs::locate("data", "kwin/tabbox/tabbox.qml"))); QString file = KStandardDirs::locate("data", "kwin/tabbox/" + m_currentLayout.toLower().replace(' ', '_') + ".qml"); if (file.isNull()) { // fallback to default file = KStandardDirs::locate("data", "kwin/tabbox/informative.qml"); } rootObject()->setProperty("source", QUrl(file)); } } // namespace TabBox } // namespace KWin diff --git a/tabbox/declarative.h b/tabbox/declarative.h index b9befb588..56740549e 100644 --- a/tabbox/declarative.h +++ b/tabbox/declarative.h @@ -1,77 +1,78 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2011 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_TABBOX_DECLARATIVE_H #define KWIN_TABBOX_DECLARATIVE_H // includes #include #include // forward declaration class QAbstractItemModel; class QModelIndex; class QPos; namespace Plasma { class FrameSvg; } namespace KWin { namespace TabBox { class ImageProvider : public QDeclarativeImageProvider { public: ImageProvider(QAbstractItemModel *model); virtual QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize); private: QAbstractItemModel *m_model; }; class DeclarativeView : public QDeclarativeView { Q_OBJECT public: DeclarativeView(QAbstractItemModel *model, QWidget *parent = NULL); virtual void showEvent(QShowEvent *event); virtual void resizeEvent(QResizeEvent *event); void setCurrentIndex(const QModelIndex &index); QModelIndex indexAt(const QPoint &pos) const; public Q_SLOTS: void slotUpdateGeometry(); private Q_SLOTS: void updateQmlSource(); + void currentIndexChanged(int row); private: QAbstractItemModel *m_model; QRect m_currentScreenGeometry; /** * Background Frame required for setting the blur mask */ Plasma::FrameSvg* m_frame; QString m_currentLayout; }; } // namespace TabBox } // namespace KWin #endif diff --git a/tabbox/qml/IconTabBox.qml b/tabbox/qml/IconTabBox.qml index 9f5a2c85e..298068f3c 100644 --- a/tabbox/qml/IconTabBox.qml +++ b/tabbox/qml/IconTabBox.qml @@ -1,106 +1,110 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2011 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ import QtQuick 1.0 import org.kde.plasma.core 0.1 as PlasmaCore import org.kde.qtextracomponents 0.1 Item { id: iconsTabBox property int iconSize property int imagePathPrefix: (new Date()).getTime() property alias count: iconsListView.count property alias margins: hoverItem.margins function setModel(model) { iconsListView.model = model; iconsListView.imageId++; } function modelChanged() { iconsListView.imageId++; } PlasmaCore.Theme { id: theme } // just to get the margin sizes PlasmaCore.FrameSvgItem { id: hoverItem imagePath: "widgets/viewitem" prefix: "hover" visible: false } // delegate Component { id: listDelegate Item { id: delegateItem width: iconSize + hoverItem.margins.left + hoverItem.margins.right height: iconSize + hoverItem.margins.top + hoverItem.margins.bottom Image { id: iconItem source: "image://client/" + index + "/" + iconsTabBox.imagePathPrefix + "-" + iconsListView.imageId + (index == iconsListView.currentIndex ? "/selected" : "") sourceSize { width: iconSize height: iconSize } anchors { fill: parent leftMargin: hoverItem.margins.left rightMargin: hoverItem.margins.right topMargin: hoverItem.margins.top bottomMargin: hoverItem.margins.bottom } } } } ListView { /** * Called from C++ to get the index at a mouse pos. **/ function indexAtMousePos(pos) { return iconsListView.indexAt(pos.x, pos.y); } + signal currentIndexChanged(int index) id: iconsListView objectName: "listView" orientation: ListView.Horizontal // used for image provider URL to trick Qt into reloading icons when the model changes property int imageId: 0 anchors { fill: parent } clip: true delegate: listDelegate highlight: PlasmaCore.FrameSvgItem { id: highlightItem imagePath: "widgets/viewitem" prefix: "hover" width: iconSize + margins.left + margins.right height: iconSize + margins.top + margins.bottom } MouseArea { anchors.fill: parent - onClicked: iconsListView.currentIndex = iconsListView.indexAt(mouse.x, mouse.y) + onClicked: { + iconsListView.currentIndex = iconsListView.indexAt(mouse.x, mouse.y); + iconsListView.currentIndexChanged(iconsListView.currentIndex); + } } } } diff --git a/tabbox/qml/compact.qml b/tabbox/qml/compact.qml index 3e57c7e18..0d8469d36 100644 --- a/tabbox/qml/compact.qml +++ b/tabbox/qml/compact.qml @@ -1,195 +1,199 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2011 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ import QtQuick 1.0 import org.kde.plasma.core 0.1 as PlasmaCore import org.kde.qtextracomponents 0.1 Item { id: compactTabBox property int screenWidth : 0 property int screenHeight : 0 property string longestCaption: "" property int imagePathPrefix: (new Date()).getTime() property int optimalWidth: compactListView.maxRowWidth property int optimalHeight: compactListView.rowHeight * compactListView.count + background.margins.top + background.margins.bottom property bool canStretchX: true property bool canStretchY: false width: Math.min(Math.max(screenWidth * 0.2, optimalWidth), screenWidth * 0.8) height: Math.min(Math.max(screenHeight * 0.2, optimalHeight), screenHeight * 0.8) property int textMargin: 2 onLongestCaptionChanged: { compactListView.maxRowWidth = compactListView.calculateMaxRowWidth(); } function setModel(model) { compactListView.model = model; compactListView.maxRowWidth = compactListView.calculateMaxRowWidth(); compactListView.imageId++; } function modelChanged() { compactListView.imageId++; } /** * Returns the caption with adjustments for minimized items. * @param caption the original caption * @param mimized whether the item is minimized * @return Caption adjusted for minimized state **/ function itemCaption(caption, minimized) { var text = caption; if (minimized) { text = "(" + text + ")"; } return text; } PlasmaCore.Theme { id: theme } // just to get the margin sizes PlasmaCore.FrameSvgItem { id: hoverItem imagePath: "widgets/viewitem" prefix: "hover" visible: false } PlasmaCore.FrameSvgItem { id: background anchors.fill: parent imagePath: "dialogs/background" } // delegate Component { id: listDelegate Item { id: delegateItem width: compactListView.width height: compactListView.rowHeight Image { id: iconItem source: "image://client/" + index + "/" + compactTabBox.imagePathPrefix + "-" + compactListView.imageId + (index == compactListView.currentIndex ? "/selected" : "/disabled") width: 16 height: 16 sourceSize { width: 16 height: 16 } anchors { verticalCenter: parent.verticalCenter left: parent.left leftMargin: hoverItem.margins.left } } Text { id: captionItem horizontalAlignment: Text.AlignLeft verticalAlignment: Text.AlignBottom text: itemCaption(caption, minimized) font.bold: true font.italic: minimized color: theme.textColor elide: Text.ElideMiddle anchors { left: iconItem.right right: parent.right top: parent.top bottom: parent.bottom topMargin: hoverItem.margins.top rightMargin: hoverItem.margins.right bottomMargin: hoverItem.margins.bottom leftMargin: 2 * compactTabBox.textMargin } } } } ListView { function calculateMaxRowWidth() { var width = 0; var textElement = Qt.createQmlObject( 'import Qt 4.7;' + 'Text {\n' + ' text: "' + itemCaption(compactTabBox.longestCaption, true) + '"\n' + ' font.bold: true\n' + ' visible: false\n' + '}', compactListView, "calculateMaxRowWidth"); width = Math.max(textElement.width, width); textElement.destroy(); return width + 16 + 2 * compactTabBox.textMargin + hoverItem.margins.right + hoverItem.margins.left + background.margins.left + background.margins.right; } /** * Calculates the height of one row based on the text height and icon size. * @return Row height **/ function calcRowHeight() { var textElement = Qt.createQmlObject( 'import Qt 4.7;' + 'Text {\n' + ' text: "Some Text"\n' + ' font.bold: true\n' + ' visible: false\n' + '}', compactListView, "calcRowHeight"); var height = textElement.height; textElement.destroy(); // icon size or two text elements and margins and hoverItem margins return Math.max(16, height + hoverItem.margins.top + hoverItem.margins.bottom); } /** * Called from C++ to get the index at a mouse pos. **/ function indexAtMousePos(pos) { return compactListView.indexAt(pos.x, pos.y); } + signal currentIndexChanged(int index) id: compactListView objectName: "listView" // the maximum text width + icon item width (32 + 4 margin) + margins for hover item + margins for background property int maxRowWidth: calculateMaxRowWidth() property int rowHeight: calcRowHeight() // used for image provider URL to trick Qt into reloading icons when the model changes property int imageId: 0 anchors { fill: parent topMargin: background.margins.top leftMargin: background.margins.left rightMargin: background.margins.right bottomMargin: background.margins.bottom } clip: true delegate: listDelegate highlight: PlasmaCore.FrameSvgItem { id: highlightItem imagePath: "widgets/viewitem" prefix: "hover" width: compactListView.width } MouseArea { anchors.fill: parent - onClicked: compactListView.currentIndex = compactListView.indexAt(mouse.x, mouse.y) + onClicked: { + compactListView.currentIndex = compactListView.indexAt(mouse.x, mouse.y); + compactListView.currentIndexChanged(compactListView.currentIndex); + } } } } diff --git a/tabbox/qml/informative.qml b/tabbox/qml/informative.qml index e65d0e33f..b2a9f5eb9 100644 --- a/tabbox/qml/informative.qml +++ b/tabbox/qml/informative.qml @@ -1,211 +1,215 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2011 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ import QtQuick 1.0 import org.kde.plasma.core 0.1 as PlasmaCore import org.kde.qtextracomponents 0.1 Item { id: informativeTabBox property int screenWidth : 0 property int screenHeight : 0 property bool allDesktops: true property string longestCaption: "" property int imagePathPrefix: (new Date()).getTime() property int optimalWidth: listView.maxRowWidth property int optimalHeight: listView.rowHeight * listView.count + background.margins.top + background.margins.bottom property bool canStretchX: true property bool canStretchY: false width: Math.min(Math.max(screenWidth * 0.2, optimalWidth), screenWidth * 0.8) height: Math.min(Math.max(screenHeight * 0.2, optimalHeight), screenHeight * 0.8) property int textMargin: 2 onLongestCaptionChanged: { listView.maxRowWidth = listView.calculateMaxRowWidth(); } function setModel(model) { listView.model = model; listView.maxRowWidth = listView.calculateMaxRowWidth(); listView.imageId++; } function modelChanged() { listView.imageId++; } /** * Returns the caption with adjustments for minimized items. * @param caption the original caption * @param mimized whether the item is minimized * @return Caption adjusted for minimized state **/ function itemCaption(caption, minimized) { var text = caption; if (minimized) { text = "(" + text + ")"; } return text; } PlasmaCore.Theme { id: theme } // just to get the margin sizes PlasmaCore.FrameSvgItem { id: hoverItem imagePath: "widgets/viewitem" prefix: "hover" visible: false } PlasmaCore.FrameSvgItem { id: background anchors.fill: parent imagePath: "dialogs/background" } // delegate Component { id: listDelegate Item { id: delegateItem width: listView.width height: listView.rowHeight Image { id: iconItem source: "image://client/" + index + "/" + informativeTabBox.imagePathPrefix + "-" + listView.imageId + (index == listView.currentIndex ? "/selected" : "/disabled") width: 32 height: 32 sourceSize { width: 32 height: 32 } anchors { verticalCenter: parent.verticalCenter left: parent.left leftMargin: hoverItem.margins.left } } Text { id: captionItem horizontalAlignment: Text.AlignHCenter text: itemCaption(caption, minimized) font.bold: true font.italic: minimized color: theme.textColor elide: Text.ElideMiddle anchors { left: iconItem.right right: parent.right top: parent.top topMargin: informativeTabBox.textMargin + hoverItem.margins.top rightMargin: hoverItem.margins.right } } Text { id: desktopNameItem horizontalAlignment: Text.AlignHCenter text: desktopName font.bold: false font.italic: true color: theme.textColor elide: Text.ElideMiddle visible: informativeTabBox.allDesktops anchors { left: iconItem.right right: parent.right top: captionItem.bottom topMargin: informativeTabBox.textMargin bottom: parent.bottom bottomMargin: informativeTabBox.textMargin + hoverItem.margins.bottom rightMargin: hoverItem.margins.right } } } } ListView { function calculateMaxRowWidth() { var width = 0; var textElement = Qt.createQmlObject( 'import Qt 4.7;' + 'Text {\n' + ' text: "' + itemCaption(informativeTabBox.longestCaption, true) + '"\n' + ' font.bold: true\n' + ' visible: false\n' + '}', listView, "calculateMaxRowWidth"); width = Math.max(textElement.width, width); textElement.destroy(); return width + 32 + hoverItem.margins.right + hoverItem.margins.left + background.margins.left + background.margins.right; } /** * Calculates the height of one row based on the text height and icon size. * @return Row height **/ function calcRowHeight() { var textElement = Qt.createQmlObject( 'import Qt 4.7;' + 'Text {\n' + ' text: "Some Text"\n' + ' font.bold: true\n' + ' visible: false\n' + '}', listView, "calcRowHeight"); var height = textElement.height; textElement.destroy(); // icon size or two text elements and margins and hoverItem margins return Math.max(32, height*2 + informativeTabBox.textMargin * 3 + hoverItem.margins.top + hoverItem.margins.bottom); } /** * Called from C++ to get the index at a mouse pos. **/ function indexAtMousePos(pos) { return listView.indexAt(pos.x, pos.y); } + signal currentIndexChanged(int index) id: listView objectName: "listView" // the maximum text width + icon item width (32 + 4 margin) + margins for hover item + margins for background property int maxRowWidth: calculateMaxRowWidth() property int rowHeight: calcRowHeight() // used for image provider URL to trick Qt into reloading icons when the model changes property int imageId: 0 anchors { fill: parent topMargin: background.margins.top leftMargin: background.margins.left rightMargin: background.margins.right bottomMargin: background.margins.bottom } clip: true delegate: listDelegate highlight: PlasmaCore.FrameSvgItem { id: highlightItem imagePath: "widgets/viewitem" prefix: "hover" width: listView.width } MouseArea { anchors.fill: parent - onClicked: listView.currentIndex = listView.indexAt(mouse.x, mouse.y) + onClicked: { + listView.currentIndex = listView.indexAt(mouse.x, mouse.y); + listView.currentIndexChanged(listView.currentIndex); + } } } } diff --git a/tabbox/qml/text.qml b/tabbox/qml/text.qml index 7c5ed6434..1539f6cf7 100644 --- a/tabbox/qml/text.qml +++ b/tabbox/qml/text.qml @@ -1,160 +1,164 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2011 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ import QtQuick 1.0 import org.kde.plasma.core 0.1 as PlasmaCore import org.kde.qtextracomponents 0.1 Item { id: textTabBox property int screenWidth : 0 property int screenHeight : 0 property string longestCaption: "" property int optimalWidth: textListView.maxRowWidth property int optimalHeight: textListView.rowHeight * textListView.count + background.margins.top + background.margins.bottom property bool canStretchX: true property bool canStretchY: false width: Math.min(Math.max(screenWidth * 0.2, optimalWidth), screenWidth * 0.8) height: Math.min(Math.max(screenHeight * 0.2, optimalHeight), screenHeight * 0.8) property int textMargin: 2 onLongestCaptionChanged: { textListView.maxRowWidth = textListView.calculateMaxRowWidth(); } function setModel(model) { textListView.model = model; textListView.maxRowWidth = textListView.calculateMaxRowWidth(); textListView.imageId++; } function modelChanged() { textListView.imageId++; } PlasmaCore.Theme { id: theme } // just to get the margin sizes PlasmaCore.FrameSvgItem { id: hoverItem imagePath: "widgets/viewitem" prefix: "hover" visible: false } PlasmaCore.FrameSvgItem { id: background anchors.fill: parent imagePath: "dialogs/background" } // delegate Component { id: listDelegate Item { id: delegateItem width: textListView.width height: textListView.rowHeight Text { id: captionItem horizontalAlignment: Text.AlignHCenter text: caption color: theme.textColor elide: Text.ElideMiddle anchors { left: parent.left right: parent.right top: parent.top bottom: parent.bottom topMargin: hoverItem.margins.top rightMargin: hoverItem.margins.right bottomMargin: hoverItem.margins.bottom leftMargin: hoverItem.margins.left } } } } ListView { function calculateMaxRowWidth() { var width = 0; var textElement = Qt.createQmlObject( 'import Qt 4.7;' + 'Text {\n' + ' text: "' + textTabBox.longestCaption + '"\n' + ' visible: false\n' + '}', textListView, "calculateMaxRowWidth"); width = Math.max(textElement.width, width); textElement.destroy(); return width + hoverItem.margins.right + hoverItem.margins.left + background.margins.left + background.margins.right; } /** * Calculates the height of one row based on the text height and icon size. * @return Row height **/ function calcRowHeight() { var textElement = Qt.createQmlObject( 'import Qt 4.7;' + 'Text {\n' + ' text: "Some Text"\n' + ' visible: false\n' + '}', textListView, "calcRowHeight"); var height = textElement.height; textElement.destroy(); // icon size or two text elements and margins and hoverItem margins return height + hoverItem.margins.top + hoverItem.margins.bottom; } /** * Called from C++ to get the index at a mouse pos. **/ function indexAtMousePos(pos) { return textListView.indexAt(pos.x, pos.y); } + signal currentIndexChanged(int index) id: textListView objectName: "listView" // the maximum text width + icon item width (32 + 4 margin) + margins for hover item + margins for background property int maxRowWidth: calculateMaxRowWidth() property int rowHeight: calcRowHeight() // used for image provider URL to trick Qt into reloading icons when the model changes property int imageId: 0 anchors { fill: parent topMargin: background.margins.top leftMargin: background.margins.left rightMargin: background.margins.right bottomMargin: background.margins.bottom } clip: true delegate: listDelegate highlight: PlasmaCore.FrameSvgItem { id: highlightItem imagePath: "widgets/viewitem" prefix: "hover" width: textListView.width } MouseArea { anchors.fill: parent - onClicked: textListView.currentIndex = textListView.indexAt(mouse.x, mouse.y) + onClicked: { + textListView.currentIndex = textListView.indexAt(mouse.x, mouse.y); + textListView.currentIndexChanged(textListView.currentIndex); + } } } } diff --git a/tabbox/tabbox.cpp b/tabbox/tabbox.cpp index f75f81fa2..3aa4ab08d 100644 --- a/tabbox/tabbox.cpp +++ b/tabbox/tabbox.cpp @@ -1,1300 +1,1309 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 Lubos Lunak Copyright (C) 2009 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ //#define QT_CLEAN_NAMESPACE // own #include "tabbox.h" // tabbox #include "tabbox/clientmodel.h" #include "tabbox/desktopmodel.h" #include "tabbox/tabboxconfig.h" // kwin #include "client.h" #include "effects.h" #include "workspace.h" // Qt #include #include // KDE #include #include #include #include #include #include #include // X11 #include #include #include #include "outline.h" // specify externals before namespace namespace KWin { extern QPixmap* kwin_get_menu_pix_hack(); namespace TabBox { TabBoxHandlerImpl::TabBoxHandlerImpl(TabBox* tabBox) : TabBoxHandler() , m_tabBox(tabBox) { } TabBoxHandlerImpl::~TabBoxHandlerImpl() { } int TabBoxHandlerImpl::activeScreen() const { return Workspace::self()->activeScreen(); } int TabBoxHandlerImpl::currentDesktop() const { return Workspace::self()->currentDesktop(); } QString TabBoxHandlerImpl::desktopName(TabBoxClient* client) const { if (TabBoxClientImpl* c = static_cast< TabBoxClientImpl* >(client)) { if (!c->client()->isOnAllDesktops()) return Workspace::self()->desktopName(c->client()->desktop()); } return Workspace::self()->desktopName(Workspace::self()->currentDesktop()); } QString TabBoxHandlerImpl::desktopName(int desktop) const { return Workspace::self()->desktopName(desktop); } TabBoxClient* TabBoxHandlerImpl::nextClientFocusChain(TabBoxClient* client) const { if (TabBoxClientImpl* c = static_cast< TabBoxClientImpl* >(client)) { Client* next = Workspace::self()->tabBox()->nextClientFocusChain(c->client()); if (next) return next->tabBoxClient(); } return NULL; } int TabBoxHandlerImpl::nextDesktopFocusChain(int desktop) const { return m_tabBox->nextDesktopFocusChain(desktop); } int TabBoxHandlerImpl::numberOfDesktops() const { return Workspace::self()->numberOfDesktops(); } TabBoxClient* TabBoxHandlerImpl::activeClient() const { if (Workspace::self()->activeClient()) return Workspace::self()->activeClient()->tabBoxClient(); else return NULL; } TabBoxClient* TabBoxHandlerImpl::clientToAddToList(TabBoxClient* client, int desktop, bool allDesktops) const { Workspace* workspace = Workspace::self(); Client* ret = NULL; Client* current = (static_cast< TabBoxClientImpl* >(client))->client(); bool addClient = false; bool applications = (config().clientListMode() == TabBoxConfig::AllDesktopsApplicationList || config().clientListMode() == TabBoxConfig::CurrentDesktopApplicationList); if (allDesktops) addClient = true; else addClient = current->isOnDesktop(desktop); addClient = addClient && current->isOnCurrentActivity(); addClient = addClient && current->wantsTabFocus() && !current->skipSwitcher(); if (addClient) { // don't add windows that have modal dialogs Client* modal = current->findModal(); if (modal == NULL || modal == current) ret = current; else if (!clientList().contains(modal->tabBoxClient())) ret = modal; else { // nothing } if (ret && applications) { // check if the list already contains an entry of this application foreach (TabBoxClient * tabBoxClient, clientList()) { if (TabBoxClientImpl* c = dynamic_cast< TabBoxClientImpl* >(tabBoxClient)) { if (c->client()->resourceClass() == ret->resourceClass()) { ret = NULL; break; } } } } } if (options->separateScreenFocus && options->xineramaEnabled) { if (current->screen() != workspace->activeScreen()) ret = NULL; } if (ret) return ret->tabBoxClient(); else return NULL; } TabBoxClientList TabBoxHandlerImpl::stackingOrder() const { ClientList stacking = Workspace::self()->stackingOrder(); TabBoxClientList ret; foreach (const Client * client, stacking) { ret.append(client->tabBoxClient()); } return ret; } void TabBoxHandlerImpl::raiseClient(TabBoxClient* c) const { Workspace::self()->raiseClient(static_cast(c)->client()); } void TabBoxHandlerImpl::restack(TabBoxClient *c, TabBoxClient *under) { Workspace::self()->restack(static_cast(c)->client(), static_cast(under)->client()); } TabBoxClient* TabBoxHandlerImpl::desktopClient() const { foreach (const Client * client, Workspace::self()->stackingOrder()) { if (client->isDesktop() && client->isOnCurrentDesktop() && client->screen() == Workspace::self()->activeScreen()) { return client->tabBoxClient(); } } return NULL; } void TabBoxHandlerImpl::showOutline(const QRect &outline) { Workspace::self()->outline()->show(outline); } void TabBoxHandlerImpl::hideOutline() { Workspace::self()->outline()->hide(); } QVector< Window > TabBoxHandlerImpl::outlineWindowIds() const { return Workspace::self()->outline()->windowIds(); } /********************************************************* * TabBoxClientImpl *********************************************************/ TabBoxClientImpl::TabBoxClientImpl() : TabBoxClient() { } TabBoxClientImpl::~TabBoxClientImpl() { } QString TabBoxClientImpl::caption() const { if (m_client->isDesktop()) return i18nc("Special entry in alt+tab list for minimizing all windows", "Show Desktop"); return m_client->caption(); } QPixmap TabBoxClientImpl::icon(const QSize& size) const { return m_client->icon(size); } WId TabBoxClientImpl::window() const { return m_client->window(); } bool TabBoxClientImpl::isMinimized() const { return m_client->isMinimized(); } int TabBoxClientImpl::x() const { return m_client->x(); } int TabBoxClientImpl::y() const { return m_client->y(); } int TabBoxClientImpl::width() const { return m_client->width(); } int TabBoxClientImpl::height() const { return m_client->height(); } /********************************************************* * TabBox *********************************************************/ TabBox::TabBox(QObject *parent) : QObject(parent) , m_displayRefcount(0) , m_desktopGrab(false) , m_tabGrab(false) , m_forcedGlobalMouseGrab(false) , m_ready(false) { m_isShown = false; m_defaultConfig = TabBoxConfig(); m_defaultConfig.setTabBoxMode(TabBoxConfig::ClientTabBox); m_defaultConfig.setClientListMode(TabBoxConfig::CurrentDesktopClientList); m_defaultConfig.setClientSwitchingMode(TabBoxConfig::FocusChainSwitching); m_defaultConfig.setLayout(TabBoxConfig::VerticalLayout); m_alternativeConfig = TabBoxConfig(); m_alternativeConfig.setTabBoxMode(TabBoxConfig::ClientTabBox); m_alternativeConfig.setClientListMode(TabBoxConfig::AllDesktopsClientList); m_alternativeConfig.setClientSwitchingMode(TabBoxConfig::FocusChainSwitching); m_alternativeConfig.setLayout(TabBoxConfig::VerticalLayout); m_desktopConfig = TabBoxConfig(); m_desktopConfig.setTabBoxMode(TabBoxConfig::DesktopTabBox); m_desktopConfig.setShowTabBox(true); m_desktopConfig.setShowDesktop(false); m_desktopConfig.setDesktopSwitchingMode(TabBoxConfig::MostRecentlyUsedDesktopSwitching); m_desktopConfig.setLayout(TabBoxConfig::VerticalLayout); m_desktopListConfig = TabBoxConfig(); m_desktopListConfig.setTabBoxMode(TabBoxConfig::DesktopTabBox); m_desktopListConfig.setShowTabBox(true); m_desktopListConfig.setShowDesktop(false); m_desktopListConfig.setDesktopSwitchingMode(TabBoxConfig::StaticDesktopSwitching); m_desktopListConfig.setLayout(TabBoxConfig::VerticalLayout); m_tabBox = new TabBoxHandlerImpl(this); connect(m_tabBox, SIGNAL(ready()), SLOT(handlerReady())); m_tabBoxMode = TabBoxDesktopMode; // init variables connect(&m_delayedShowTimer, SIGNAL(timeout()), this, SLOT(show())); connect(Workspace::self(), SIGNAL(configChanged()), this, SLOT(reconfigure())); } TabBox::~TabBox() { } void TabBox::handlerReady() { m_tabBox->setConfig(m_defaultConfig); reconfigure(); m_ready = true; } void TabBox::initShortcuts(KActionCollection* keys) { KAction *a = NULL; // The setGlobalShortcut(shortcut); shortcut = a->globalShortcut() // sequence is necessary in the case where the user has defined a // custom key binding which KAction::setGlobalShortcut autoloads. #define KEY( name, key, fnSlot, shortcut, shortcutSlot ) \ a = keys->addAction( name ); \ a->setText( i18n(name) ); \ shortcut = KShortcut(key); \ qobject_cast( a )->setGlobalShortcut(shortcut); \ shortcut = a->globalShortcut(); \ connect(a, SIGNAL(triggered(bool)), SLOT(fnSlot)); \ connect(a, SIGNAL(globalShortcutChanged(QKeySequence)), SLOT(shortcutSlot)); KEY(I18N_NOOP("Walk Through Windows"), Qt::ALT + Qt::Key_Tab, slotWalkThroughWindows(), m_cutWalkThroughWindows, slotWalkThroughWindowsKeyChanged(QKeySequence)) KEY(I18N_NOOP("Walk Through Windows (Reverse)"), Qt::ALT + Qt::SHIFT + Qt::Key_Backtab, slotWalkBackThroughWindows(), m_cutWalkThroughWindowsReverse, slotWalkBackThroughWindowsKeyChanged(QKeySequence)) KEY(I18N_NOOP("Walk Through Windows Alternative"), 0, slotWalkThroughWindowsAlternative(), m_cutWalkThroughWindowsAlternative, slotWalkThroughWindowsAlternativeKeyChanged(QKeySequence)) KEY(I18N_NOOP("Walk Through Windows Alternative (Reverse)"), 0, slotWalkBackThroughWindowsAlternative(), m_cutWalkThroughWindowsAlternativeReverse, slotWalkBackThroughWindowsAlternativeKeyChanged(QKeySequence)) KEY(I18N_NOOP("Walk Through Desktops"), 0, slotWalkThroughDesktops(), m_cutWalkThroughDesktops, slotWalkThroughDesktopsKeyChanged(QKeySequence)) KEY(I18N_NOOP("Walk Through Desktops (Reverse)"), 0, slotWalkBackThroughDesktops(), m_cutWalkThroughDesktopsReverse, slotWalkBackThroughDesktopsKeyChanged(QKeySequence)) KEY(I18N_NOOP("Walk Through Desktop List"), 0, slotWalkThroughDesktopList(), m_cutWalkThroughDesktopList, slotWalkThroughDesktopListKeyChanged(QKeySequence)) KEY(I18N_NOOP("Walk Through Desktop List (Reverse)"), 0, slotWalkBackThroughDesktopList(), m_cutWalkThroughDesktopListReverse, slotWalkBackThroughDesktopListKeyChanged(QKeySequence)) #undef KEY } /*! Sets the current mode to \a mode, either TabBoxDesktopListMode or TabBoxWindowsMode \sa mode() */ void TabBox::setMode(TabBoxMode mode) { m_tabBoxMode = mode; switch(mode) { case TabBoxWindowsMode: m_tabBox->setConfig(m_defaultConfig); break; case TabBoxWindowsAlternativeMode: m_tabBox->setConfig(m_alternativeConfig); break; case TabBoxDesktopMode: m_tabBox->setConfig(m_desktopConfig); break; case TabBoxDesktopListMode: m_tabBox->setConfig(m_desktopListConfig); break; } } /*! Resets the tab box to display the active client in TabBoxWindowsMode, or the current desktop in TabBoxDesktopListMode */ void TabBox::reset(bool partial_reset) { switch(m_tabBox->config().tabBoxMode()) { case TabBoxConfig::ClientTabBox: m_tabBox->createModel(partial_reset); if (!partial_reset) { if (Workspace::self()->activeClient()) setCurrentClient(Workspace::self()->activeClient()); // it's possible that the active client is not part of the model // in that case the index is invalid - if (!m_index.isValid()) + if (!m_tabBox->currentIndex().isValid()) setCurrentIndex(m_tabBox->first()); } else { - if (!m_index.isValid() || !m_tabBox->client(m_index)) + if (!m_tabBox->currentIndex().isValid() || !m_tabBox->client(m_tabBox->currentIndex())) setCurrentIndex(m_tabBox->first()); } break; case TabBoxConfig::DesktopTabBox: m_tabBox->createModel(); if (!partial_reset) setCurrentDesktop(Workspace::self()->currentDesktop()); break; } emit tabBoxUpdated(); } /*! Shows the next or previous item, depending on \a next */ void TabBox::nextPrev(bool next) { setCurrentIndex(m_tabBox->nextPrev(next), false); emit tabBoxUpdated(); } /*! Returns the currently displayed client ( only works in TabBoxWindowsMode ). Returns 0 if no client is displayed. */ Client* TabBox::currentClient() { - if (TabBoxClientImpl* client = static_cast< TabBoxClientImpl* >(m_tabBox->client(m_index))) { + if (TabBoxClientImpl* client = static_cast< TabBoxClientImpl* >(m_tabBox->client(m_tabBox->currentIndex()))) { if (!Workspace::self()->hasClient(client->client())) return NULL; return client->client(); } else return NULL; } /*! Returns the list of clients potentially displayed ( only works in TabBoxWindowsMode ). Returns an empty list if no clients are available. */ ClientList TabBox::currentClientList() { TabBoxClientList list = m_tabBox->clientList(); ClientList ret; foreach (const TabBoxClient * client, list) { if (const TabBoxClientImpl* c = static_cast< const TabBoxClientImpl* >(client)) ret.append(c->client()); } return ret; } /*! Returns the currently displayed virtual desktop ( only works in TabBoxDesktopListMode ) Returns -1 if no desktop is displayed. */ int TabBox::currentDesktop() { - return m_tabBox->desktop(m_index); + return m_tabBox->desktop(m_tabBox->currentIndex()); } /*! Returns the list of desktops potentially displayed ( only works in TabBoxDesktopListMode ) Returns an empty list if no are available. */ QList< int > TabBox::currentDesktopList() { return m_tabBox->desktopList(); } /*! Change the currently selected client, and notify the effects. \sa setCurrentDesktop() */ void TabBox::setCurrentClient(Client* newClient) { setCurrentIndex(m_tabBox->index(newClient->tabBoxClient())); } /*! Change the currently selected desktop, and notify the effects. \sa setCurrentClient() */ void TabBox::setCurrentDesktop(int newDesktop) { setCurrentIndex(m_tabBox->desktopIndex(newDesktop)); } void TabBox::setCurrentIndex(QModelIndex index, bool notifyEffects) { if (!index.isValid()) return; - m_index = index; m_tabBox->setCurrentIndex(index); if (notifyEffects) { emit tabBoxUpdated(); } } /*! Notify effects that the tab box is being shown, and only display the default tab box QFrame if no effect has referenced the tab box. */ void TabBox::show() { emit tabBoxAdded(m_tabBoxMode); if (isDisplayed()) { m_isShown = false; return; } reference(); m_isShown = true; m_tabBox->show(); } /*! Notify effects that the tab box is being hidden. */ void TabBox::hide(bool abort) { m_delayedShowTimer.stop(); if (m_isShown) { m_isShown = false; unreference(); } emit tabBoxClosed(); if (isDisplayed()) kDebug(1212) << "Tab box was not properly closed by an effect"; - m_index = QModelIndex(); m_tabBox->hide(abort); QApplication::syncX(); XEvent otherEvent; while (XCheckTypedEvent(display(), EnterNotify, &otherEvent)) ; } void TabBox::reconfigure() { KSharedConfigPtr c(KGlobal::config()); KConfigGroup config = c->group("TabBox"); loadConfig(c->group("TabBox"), m_defaultConfig); loadConfig(c->group("TabBoxAlternative"), m_alternativeConfig); m_tabBox->setConfig(m_defaultConfig); m_delayShow = config.readEntry("ShowDelay", true); m_delayShowTime = config.readEntry("DelayTime", 90); } void TabBox::loadConfig(const KConfigGroup& config, TabBoxConfig& tabBoxConfig) { tabBoxConfig.setClientListMode(TabBoxConfig::ClientListMode( config.readEntry("ListMode", TabBoxConfig::defaultListMode()))); tabBoxConfig.setClientSwitchingMode(TabBoxConfig::ClientSwitchingMode( config.readEntry("SwitchingMode", TabBoxConfig::defaultSwitchingMode()))); tabBoxConfig.setLayout(TabBoxConfig::LayoutMode( config.readEntry("LayoutMode", TabBoxConfig::defaultLayoutMode()))); tabBoxConfig.setSelectedItemViewPosition(TabBoxConfig::SelectedItemViewPosition( config.readEntry("SelectedItem", TabBoxConfig::defaultSelectedItemViewPosition()))); tabBoxConfig.setShowOutline(config.readEntry("ShowOutline", TabBoxConfig::defaultShowOutline())); tabBoxConfig.setShowTabBox(config.readEntry("ShowTabBox", TabBoxConfig::defaultShowTabBox())); tabBoxConfig.setHighlightWindows(config.readEntry("HighlightWindows", TabBoxConfig::defaultHighlightWindow())); tabBoxConfig.setShowDesktop(config.readEntry("ShowDesktop", TabBoxConfig::defaultShowDesktop())); tabBoxConfig.setMinWidth(config.readEntry("MinWidth", TabBoxConfig::defaultMinWidth())); tabBoxConfig.setMinHeight(config.readEntry("MinHeight", TabBoxConfig::defaultMinHeight())); tabBoxConfig.setLayoutName(config.readEntry("LayoutName", TabBoxConfig::defaultLayoutName())); tabBoxConfig.setSelectedItemLayoutName(config.readEntry("SelectedLayoutName", TabBoxConfig::defaultSelectedItemLayoutName())); } /*! Rikkus: please document! (Matthias) Ok, here's the docs :) You call delayedShow() instead of show() directly. If the 'ShowDelay' setting is false, show() is simply called. Otherwise, we start a timer for the delay given in the settings and only do a show() when it times out. This means that you can alt-tab between windows and you don't see the tab box immediately. Not only does this make alt-tabbing faster, it gives less 'flicker' to the eyes. You don't need to see the tab box if you're just quickly switching between 2 or 3 windows. It seems to work quite nicely. */ void TabBox::delayedShow() { if (isDisplayed() || m_delayedShowTimer.isActive()) // already called show - no need to call it twice return; if (!m_delayShowTime) { show(); return; } m_delayedShowTimer.setSingleShot(true); m_delayedShowTimer.start(m_delayShowTime); } -void TabBox::handleMouseEvent(XEvent* e) +bool TabBox::handleMouseEvent(XEvent* e) { XAllowEvents(display(), AsyncPointer, xTime()); if (!m_isShown && isDisplayed()) { // tabbox has been replaced, check effects if (effects && static_cast(effects)->checkInputWindowEvent(e)) - return; + return true; } - if (e->type != ButtonPress) - return; - QPoint pos(e->xbutton.x_root, e->xbutton.y_root); - - if ((!m_isShown && isDisplayed()) - || (!m_tabBox->containsPos(pos) && - (e->xbutton.button == Button1 || e->xbutton.button == Button2 || e->xbutton.button == Button3))) { - close(); // click outside closes tab - return; + if (e->type == ButtonPress) { + // press outside Tabbox? + QPoint pos(e->xbutton.x_root, e->xbutton.y_root); + + if ((!m_isShown && isDisplayed()) + || (!m_tabBox->containsPos(pos) && + (e->xbutton.button == Button1 || e->xbutton.button == Button2 || e->xbutton.button == Button3))) { + close(); // click outside closes tab + return true; + } + } + if (m_tabBoxMode == TabBoxWindowsMode || m_tabBoxMode == TabBoxWindowsAlternativeMode) { + // pass to declarative view + return false; } + // not declarative view + if (e->type != ButtonPress) { + return true; + } + QPoint pos(e->xbutton.x_root, e->xbutton.y_root); QModelIndex index; if (e->xbutton.button == Button1 || e->xbutton.button == Button2 || e->xbutton.button == Button3) { index = m_tabBox->indexAt(pos); if (e->xbutton.button == Button2 && index.isValid()) { if (TabBoxClientImpl* client = static_cast< TabBoxClientImpl* >(m_tabBox->client(index))) { if (Workspace::self()->hasClient(client->client())) { client->client()->closeWindow(); - return; + return true; } } } } else { // mouse wheel event index = m_tabBox->nextPrev(e->xbutton.button == Button5); } if (index.isValid()) setCurrentIndex(index); + return true; } void TabBox::grabbedKeyEvent(QKeyEvent* event) { emit tabBoxKeyEvent(event); if (!m_isShown && isDisplayed()) { // tabbox has been replaced, check effects return; } setCurrentIndex(m_tabBox->grabbedKeyEvent(event)); } /*! Handles alt-tab / control-tab */ static bool areKeySymXsDepressed(bool bAll, const uint keySyms[], int nKeySyms) { char keymap[32]; kDebug(125) << "areKeySymXsDepressed: " << (bAll ? "all of " : "any of ") << nKeySyms; XQueryKeymap(display(), keymap); for (int iKeySym = 0; iKeySym < nKeySyms; iKeySym++) { uint keySymX = keySyms[ iKeySym ]; uchar keyCodeX = XKeysymToKeycode(display(), keySymX); int i = keyCodeX / 8; char mask = 1 << (keyCodeX - (i * 8)); // Abort if bad index value, if (i < 0 || i >= 32) return false; kDebug(125) << iKeySym << ": keySymX=0x" << QString::number(keySymX, 16) << " i=" << i << " mask=0x" << QString::number(mask, 16) << " keymap[i]=0x" << QString::number(keymap[i], 16) << endl; // If ALL keys passed need to be depressed, if (bAll) { if ((keymap[i] & mask) == 0) return false; } else { // If we are looking for ANY key press, and this key is depressed, if (keymap[i] & mask) return true; } } // If we were looking for ANY key press, then none was found, return false, // If we were looking for ALL key presses, then all were found, return true. return bAll; } static bool areModKeysDepressed(const QKeySequence& seq) { uint rgKeySyms[10]; int nKeySyms = 0; if (seq.isEmpty()) return false; int mod = seq[seq.count()-1] & Qt::KeyboardModifierMask; if (mod & Qt::SHIFT) { rgKeySyms[nKeySyms++] = XK_Shift_L; rgKeySyms[nKeySyms++] = XK_Shift_R; } if (mod & Qt::CTRL) { rgKeySyms[nKeySyms++] = XK_Control_L; rgKeySyms[nKeySyms++] = XK_Control_R; } if (mod & Qt::ALT) { rgKeySyms[nKeySyms++] = XK_Alt_L; rgKeySyms[nKeySyms++] = XK_Alt_R; } if (mod & Qt::META) { // It would take some code to determine whether the Win key // is associated with Super or Meta, so check for both. // See bug #140023 for details. rgKeySyms[nKeySyms++] = XK_Super_L; rgKeySyms[nKeySyms++] = XK_Super_R; rgKeySyms[nKeySyms++] = XK_Meta_L; rgKeySyms[nKeySyms++] = XK_Meta_R; } return areKeySymXsDepressed(false, rgKeySyms, nKeySyms); } static bool areModKeysDepressed(const KShortcut& cut) { if (areModKeysDepressed(cut.primary()) || areModKeysDepressed(cut.alternate())) return true; return false; } void TabBox::navigatingThroughWindows(bool forward, const KShortcut& shortcut, TabBoxMode mode) { if (isGrabbed()) return; if (!options->focusPolicyIsReasonable()) { //ungrabXKeyboard(); // need that because of accelerator raw mode // CDE style raise / lower CDEWalkThroughWindows(forward); } else { if (areModKeysDepressed(shortcut)) { if (startKDEWalkThroughWindows(mode)) KDEWalkThroughWindows(forward); } else // if the shortcut has no modifiers, don't show the tabbox, // don't grab, but simply go to the next window KDEOneStepThroughWindows(forward, mode); } } void TabBox::slotWalkThroughWindows() { if (!m_ready){ return; } navigatingThroughWindows(true, m_cutWalkThroughWindows, TabBoxWindowsMode); } void TabBox::slotWalkBackThroughWindows() { if (!m_ready){ return; } navigatingThroughWindows(false, m_cutWalkThroughWindowsReverse, TabBoxWindowsMode); } void TabBox::slotWalkThroughWindowsAlternative() { if (!m_ready){ return; } navigatingThroughWindows(true, m_cutWalkThroughWindowsAlternative, TabBoxWindowsAlternativeMode); } void TabBox::slotWalkBackThroughWindowsAlternative() { if (!m_ready){ return; } navigatingThroughWindows(false, m_cutWalkThroughWindowsAlternativeReverse, TabBoxWindowsAlternativeMode); } void TabBox::slotWalkThroughDesktops() { if (!m_ready){ return; } if (isGrabbed()) return; if (areModKeysDepressed(m_cutWalkThroughDesktops)) { if (startWalkThroughDesktops()) walkThroughDesktops(true); } else { oneStepThroughDesktops(true); } } void TabBox::slotWalkBackThroughDesktops() { if (!m_ready){ return; } if (isGrabbed()) return; if (areModKeysDepressed(m_cutWalkThroughDesktopsReverse)) { if (startWalkThroughDesktops()) walkThroughDesktops(false); } else { oneStepThroughDesktops(false); } } void TabBox::slotWalkThroughDesktopList() { if (!m_ready){ return; } if (isGrabbed()) return; if (areModKeysDepressed(m_cutWalkThroughDesktopList)) { if (startWalkThroughDesktopList()) walkThroughDesktops(true); } else { oneStepThroughDesktopList(true); } } void TabBox::slotWalkBackThroughDesktopList() { if (!m_ready){ return; } if (isGrabbed()) return; if (areModKeysDepressed(m_cutWalkThroughDesktopListReverse)) { if (startWalkThroughDesktopList()) walkThroughDesktops(false); } else { oneStepThroughDesktopList(false); } } void TabBox::slotWalkThroughDesktopsKeyChanged(const QKeySequence& seq) { m_cutWalkThroughDesktops = KShortcut(seq); } void TabBox::slotWalkBackThroughDesktopsKeyChanged(const QKeySequence& seq) { m_cutWalkThroughDesktopsReverse = KShortcut(seq); } void TabBox::slotWalkThroughDesktopListKeyChanged(const QKeySequence& seq) { m_cutWalkThroughDesktopList = KShortcut(seq); } void TabBox::slotWalkBackThroughDesktopListKeyChanged(const QKeySequence& seq) { m_cutWalkThroughDesktopListReverse = KShortcut(seq); } void TabBox::slotWalkThroughWindowsKeyChanged(const QKeySequence& seq) { m_cutWalkThroughWindows = KShortcut(seq); } void TabBox::slotWalkBackThroughWindowsKeyChanged(const QKeySequence& seq) { m_cutWalkThroughWindowsReverse = KShortcut(seq); } void TabBox::slotMoveToTabLeftKeyChanged(const QKeySequence& seq) { m_cutWalkThroughGroupWindows = KShortcut(seq); } void TabBox::slotMoveToTabRightKeyChanged(const QKeySequence& seq) { m_cutWalkThroughGroupWindowsReverse = KShortcut(seq); } void TabBox::slotWalkThroughWindowsAlternativeKeyChanged(const QKeySequence& seq) { m_cutWalkThroughWindowsAlternative = KShortcut(seq); } void TabBox::slotWalkBackThroughWindowsAlternativeKeyChanged(const QKeySequence& seq) { m_cutWalkThroughWindowsAlternativeReverse = KShortcut(seq); } void TabBox::modalActionsSwitch(bool enabled) { QList collections; collections.append(Workspace::self()->actionCollection()); collections.append(Workspace::self()->disableShortcutsKeys()); collections.append(Workspace::self()->clientKeys()); foreach (KActionCollection * collection, collections) foreach (QAction * action, collection->actions()) action->setEnabled(enabled); } bool TabBox::startKDEWalkThroughWindows(TabBoxMode mode) { if (!establishTabBoxGrab()) return false; m_tabGrab = true; modalActionsSwitch(false); setMode(mode); reset(); return true; } bool TabBox::startWalkThroughDesktops(TabBoxMode mode) { if (!establishTabBoxGrab()) return false; m_desktopGrab = true; modalActionsSwitch(false); setMode(mode); reset(); return true; } bool TabBox::startWalkThroughDesktops() { return startWalkThroughDesktops(TabBoxDesktopMode); } bool TabBox::startWalkThroughDesktopList() { return startWalkThroughDesktops(TabBoxDesktopListMode); } void TabBox::KDEWalkThroughWindows(bool forward) { nextPrev(forward); delayedShow(); } void TabBox::walkThroughDesktops(bool forward) { nextPrev(forward); delayedShow(); } void TabBox::CDEWalkThroughWindows(bool forward) { Client* c = NULL; // this function find the first suitable client for unreasonable focus // policies - the topmost one, with some exceptions (can't be keepabove/below, // otherwise it gets stuck on them) // Q_ASSERT(Workspace::self()->block_stacking_updates == 0); for (int i = Workspace::self()->stackingOrder().size() - 1; i >= 0 ; --i) { Client* it = Workspace::self()->stackingOrder().at(i); if (it->isOnCurrentActivity() && it->isOnCurrentDesktop() && !it->isSpecialWindow() && it->isShown(false) && it->wantsTabFocus() && !it->keepAbove() && !it->keepBelow()) { c = it; break; } } Client* nc = c; bool options_traverse_all; { KConfigGroup group(KGlobal::config(), "TabBox"); options_traverse_all = group.readEntry("TraverseAll", false); } Client* firstClient = 0; do { nc = forward ? nextClientStatic(nc) : previousClientStatic(nc); if (!firstClient) { // When we see our first client for the second time, // it's time to stop. firstClient = nc; } else if (nc == firstClient) { // No candidates found. nc = 0; break; } } while (nc && nc != c && ((!options_traverse_all && !nc->isOnDesktop(currentDesktop())) || nc->isMinimized() || !nc->wantsTabFocus() || nc->keepAbove() || nc->keepBelow() || !nc->isOnCurrentActivity())); if (nc) { if (c && c != nc) Workspace::self()->lowerClient(c); if (options->focusPolicyIsReasonable()) { Workspace::self()->activateClient(nc); if (nc->isShade() && options->shadeHover) nc->setShade(ShadeActivated); } else { if (!nc->isOnDesktop(currentDesktop())) setCurrentDesktop(nc->desktop()); Workspace::self()->raiseClient(nc); } } } void TabBox::KDEOneStepThroughWindows(bool forward, TabBoxMode mode) { setMode(mode); reset(); nextPrev(forward); if (Client* c = currentClient()) { Workspace::self()->activateClient(c); if (c->isShade() && options->shadeHover) c->setShade(ShadeActivated); } } void TabBox::oneStepThroughDesktops(bool forward, TabBoxMode mode) { setMode(mode); reset(); nextPrev(forward); if (currentDesktop() != -1) setCurrentDesktop(currentDesktop()); } void TabBox::oneStepThroughDesktops(bool forward) { oneStepThroughDesktops(forward, TabBoxDesktopMode); } void TabBox::oneStepThroughDesktopList(bool forward) { oneStepThroughDesktops(forward, TabBoxDesktopListMode); } /*! Handles holding alt-tab / control-tab */ void TabBox::keyPress(int keyQt) { bool forward = false; bool backward = false; if (m_tabGrab) { KShortcut forwardShortcut; KShortcut backwardShortcut; if (mode() == TabBoxWindowsMode) { forwardShortcut = m_cutWalkThroughWindows; backwardShortcut = m_cutWalkThroughWindowsReverse; } else { forwardShortcut = m_cutWalkThroughWindowsAlternative; backwardShortcut = m_cutWalkThroughWindowsAlternativeReverse; } forward = forwardShortcut.contains(keyQt); backward = backwardShortcut.contains(keyQt); if (forward || backward) { kDebug(125) << "== " << forwardShortcut.toString() << " or " << backwardShortcut.toString() << endl; KDEWalkThroughWindows(forward); } } else if (m_desktopGrab) { forward = m_cutWalkThroughDesktops.contains(keyQt) || m_cutWalkThroughDesktopList.contains(keyQt); backward = m_cutWalkThroughDesktopsReverse.contains(keyQt) || m_cutWalkThroughDesktopListReverse.contains(keyQt); if (forward || backward) walkThroughDesktops(forward); } if (m_desktopGrab || m_tabGrab) { if (((keyQt & ~Qt::KeyboardModifierMask) == Qt::Key_Escape) && !(forward || backward)) { // if Escape is part of the shortcut, don't cancel close(true); } else if (!(forward || backward)) { QKeyEvent* event = new QKeyEvent(QEvent::KeyPress, keyQt & ~Qt::KeyboardModifierMask, Qt::NoModifier); grabbedKeyEvent(event); } } } void TabBox::close(bool abort) { removeTabBoxGrab(); hide(abort); modalActionsSwitch(true); m_tabGrab = false; m_desktopGrab = false; } /*! Handles alt-tab / control-tab releasing */ void TabBox::keyRelease(const XKeyEvent& ev) { unsigned int mk = ev.state & (KKeyServer::modXShift() | KKeyServer::modXCtrl() | KKeyServer::modXAlt() | KKeyServer::modXMeta()); // ev.state is state before the key release, so just checking mk being 0 isn't enough // using XQueryPointer() also doesn't seem to work well, so the check that all // modifiers are released: only one modifier is active and the currently released // key is this modifier - if yes, release the grab int mod_index = -1; for (int i = ShiftMapIndex; i <= Mod5MapIndex; ++i) if ((mk & (1 << i)) != 0) { if (mod_index >= 0) return; mod_index = i; } bool release = false; if (mod_index == -1) release = true; else { XModifierKeymap* xmk = XGetModifierMapping(display()); for (int i = 0; i < xmk->max_keypermod; i++) if (xmk->modifiermap[xmk->max_keypermod * mod_index + i] == ev.keycode) release = true; XFreeModifiermap(xmk); } if (!release) return; if (m_tabGrab) { bool old_control_grab = m_desktopGrab; Client* c = currentClient(); close(); m_desktopGrab = old_control_grab; if (c) { Workspace::self()->activateClient(c); if (c->isShade() && options->shadeHover) c->setShade(ShadeActivated); if (c->isDesktop()) Workspace::self()->setShowingDesktop(!Workspace::self()->showingDesktop()); } } if (m_desktopGrab) { bool old_tab_grab = m_tabGrab; int desktop = currentDesktop(); close(); m_tabGrab = old_tab_grab; if (desktop != -1) { setCurrentDesktop(desktop); Workspace::self()->setCurrentDesktop(desktop); } } } int TabBox::nextDesktopFocusChain(int iDesktop) const { const QVector &desktopFocusChain = Workspace::self()->desktopFocusChain(); int i = desktopFocusChain.indexOf(iDesktop); if (i >= 0 && i + 1 < desktopFocusChain.size()) return desktopFocusChain[i+1]; else if (desktopFocusChain.size() > 0) return desktopFocusChain[ 0 ]; else return 1; } int TabBox::previousDesktopFocusChain(int iDesktop) const { const QVector &desktopFocusChain = Workspace::self()->desktopFocusChain(); int i = desktopFocusChain.indexOf(iDesktop); if (i - 1 >= 0) return desktopFocusChain[i-1]; else if (desktopFocusChain.size() > 0) return desktopFocusChain[desktopFocusChain.size()-1]; else return Workspace::self()->numberOfDesktops(); } int TabBox::nextDesktopStatic(int iDesktop) const { int i = ++iDesktop; if (i > Workspace::self()->numberOfDesktops()) i = 1; return i; } int TabBox::previousDesktopStatic(int iDesktop) const { int i = --iDesktop; if (i < 1) i = Workspace::self()->numberOfDesktops(); return i; } /*! auxiliary functions to travers all clients according to the focus order. Useful for kwms Alt-tab feature. */ Client* TabBox::nextClientFocusChain(Client* c) const { const ClientList &globalFocusChain = Workspace::self()->globalFocusChain(); if (globalFocusChain.isEmpty()) return 0; int pos = globalFocusChain.indexOf(c); if (pos == -1) return globalFocusChain.last(); if (pos == 0) return globalFocusChain.last(); pos--; return globalFocusChain[ pos ]; } /*! auxiliary functions to travers all clients according to the focus order. Useful for kwms Alt-tab feature. */ Client* TabBox::previousClientFocusChain(Client* c) const { const ClientList &globalFocusChain = Workspace::self()->globalFocusChain(); if (globalFocusChain.isEmpty()) return 0; int pos = globalFocusChain.indexOf(c); if (pos == -1) return globalFocusChain.first(); pos++; if (pos == globalFocusChain.count()) return globalFocusChain.first(); return globalFocusChain[ pos ]; } /*! auxiliary functions to travers all clients according to the static order. Useful for the CDE-style Alt-tab feature. */ Client* TabBox::nextClientStatic(Client* c) const { if (!c || Workspace::self()->clientList().isEmpty()) return 0; int pos = Workspace::self()->clientList().indexOf(c); if (pos == -1) return Workspace::self()->clientList().first(); ++pos; if (pos == Workspace::self()->clientList().count()) return Workspace::self()->clientList().first(); return Workspace::self()->clientList()[ pos ]; } /*! auxiliary functions to travers all clients according to the static order. Useful for the CDE-style Alt-tab feature. */ Client* TabBox::previousClientStatic(Client* c) const { if (!c || Workspace::self()->clientList().isEmpty()) return 0; int pos = Workspace::self()->clientList().indexOf(c); if (pos == -1) return Workspace::self()->clientList().last(); if (pos == 0) return Workspace::self()->clientList().last(); --pos; return Workspace::self()->clientList()[ pos ]; } bool TabBox::establishTabBoxGrab() { if (!grabXKeyboard()) return false; // Don't try to establish a global mouse grab using XGrabPointer, as that would prevent // using Alt+Tab while DND (#44972). However force passive grabs on all windows // in order to catch MouseRelease events and close the tabbox (#67416). // All clients already have passive grabs in their wrapper windows, so check only // the active client, which may not have it. assert(!m_forcedGlobalMouseGrab); m_forcedGlobalMouseGrab = true; if (Workspace::self()->activeClient() != NULL) Workspace::self()->activeClient()->updateMouseGrab(); return true; } void TabBox::removeTabBoxGrab() { ungrabXKeyboard(); assert(m_forcedGlobalMouseGrab); m_forcedGlobalMouseGrab = false; if (Workspace::self()->activeClient() != NULL) Workspace::self()->activeClient()->updateMouseGrab(); } } // namespace TabBox } // namespace #include "tabbox.moc" diff --git a/tabbox/tabbox.h b/tabbox/tabbox.h index 498d9e82b..6ab07d69d 100644 --- a/tabbox/tabbox.h +++ b/tabbox/tabbox.h @@ -1,249 +1,248 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 1999, 2000 Matthias Ettrich Copyright (C) 2003 Lubos Lunak Copyright (C) 2009 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef KWIN_TABBOX_H #define KWIN_TABBOX_H #include #include #include "utils.h" #include "tabbox/tabboxhandler.h" class QKeyEvent; namespace KWin { class Workspace; class Client; namespace TabBox { class TabBoxConfig; class TabBox; class TabBoxHandlerImpl : public TabBoxHandler { public: TabBoxHandlerImpl(TabBox* tabBox); virtual ~TabBoxHandlerImpl(); virtual int activeScreen() const; virtual TabBoxClient* activeClient() const; virtual int currentDesktop() const; virtual QString desktopName(TabBoxClient* client) const; virtual QString desktopName(int desktop) const; virtual TabBoxClient* nextClientFocusChain(TabBoxClient* client) const; virtual int nextDesktopFocusChain(int desktop) const; virtual int numberOfDesktops() const; virtual TabBoxClientList stackingOrder() const; virtual void raiseClient(TabBoxClient *client) const; virtual void restack(TabBoxClient *c, TabBoxClient *under); virtual TabBoxClient* clientToAddToList(TabBoxClient* client, int desktop, bool allDesktops) const; virtual TabBoxClient* desktopClient() const; virtual void hideOutline(); virtual void showOutline(const QRect &outline); virtual QVector< Window > outlineWindowIds() const; private: TabBox* m_tabBox; }; class TabBoxClientImpl : public TabBoxClient { public: TabBoxClientImpl(); virtual ~TabBoxClientImpl(); virtual QString caption() const; virtual QPixmap icon(const QSize& size = QSize(32, 32)) const; virtual WId window() const; virtual bool isMinimized() const; virtual int x() const; virtual int y() const; virtual int width() const; virtual int height() const; Client* client() const { return m_client; } void setClient(Client* client) { m_client = client; } private: Client* m_client; }; class TabBox : public QObject { Q_OBJECT public: TabBox(QObject *parent = NULL); ~TabBox(); Client* currentClient(); ClientList currentClientList(); int currentDesktop(); QList< int > currentDesktopList(); void setCurrentClient(Client* newClient); void setCurrentDesktop(int newDesktop); void setMode(TabBoxMode mode); TabBoxMode mode() const { return m_tabBoxMode; } void reset(bool partial_reset = false); void nextPrev(bool next = true); void delayedShow(); void hide(bool abort = false); /*! Increase the reference count, preventing the default tabbox from showing. \sa unreference(), isDisplayed() */ void reference() { ++m_displayRefcount; } /*! Decrease the reference count. Only when the reference count is 0 will the default tab box be shown. */ void unreference() { --m_displayRefcount; } /*! Returns whether the tab box is being displayed, either natively or by an effect. \sa reference(), unreference() */ bool isDisplayed() const { return m_displayRefcount > 0; }; - void handleMouseEvent(XEvent*); + bool handleMouseEvent(XEvent* e); void grabbedKeyEvent(QKeyEvent* event); bool isGrabbed() const { return m_tabGrab || m_desktopGrab; }; void initShortcuts(KActionCollection* keys); Client* nextClientFocusChain(Client*) const; Client* previousClientFocusChain(Client*) const; Client* nextClientStatic(Client*) const; Client* previousClientStatic(Client*) const; int nextDesktopFocusChain(int iDesktop) const; int previousDesktopFocusChain(int iDesktop) const; int nextDesktopStatic(int iDesktop) const; int previousDesktopStatic(int iDesktop) const; void close(bool abort = false); void keyPress(int key); void keyRelease(const XKeyEvent& ev); public slots: void show(); void slotWalkThroughDesktops(); void slotWalkBackThroughDesktops(); void slotWalkThroughDesktopList(); void slotWalkBackThroughDesktopList(); void slotWalkThroughWindows(); void slotWalkBackThroughWindows(); void slotWalkThroughWindowsAlternative(); void slotWalkBackThroughWindowsAlternative(); void slotWalkThroughDesktopsKeyChanged(const QKeySequence& seq); void slotWalkBackThroughDesktopsKeyChanged(const QKeySequence& seq); void slotWalkThroughDesktopListKeyChanged(const QKeySequence& seq); void slotWalkBackThroughDesktopListKeyChanged(const QKeySequence& seq); void slotWalkThroughWindowsKeyChanged(const QKeySequence& seq); void slotWalkBackThroughWindowsKeyChanged(const QKeySequence& seq); void slotMoveToTabLeftKeyChanged(const QKeySequence& seq); void slotMoveToTabRightKeyChanged(const QKeySequence& seq); void slotWalkThroughWindowsAlternativeKeyChanged(const QKeySequence& seq); void slotWalkBackThroughWindowsAlternativeKeyChanged(const QKeySequence& seq); void handlerReady(); signals: void tabBoxAdded(int); void tabBoxClosed(); void tabBoxUpdated(); void tabBoxKeyEvent(QKeyEvent*); private: void setCurrentIndex(QModelIndex index, bool notifyEffects = true); void loadConfig(const KConfigGroup& config, TabBoxConfig& tabBoxConfig); bool startKDEWalkThroughWindows(TabBoxMode mode); // TabBoxWindowsMode | TabBoxWindowsAlternativeMode bool startWalkThroughDesktops(TabBoxMode mode); // TabBoxDesktopMode | TabBoxDesktopListMode bool startWalkThroughDesktops(); bool startWalkThroughDesktopList(); void navigatingThroughWindows(bool forward, const KShortcut& shortcut, TabBoxMode mode); // TabBoxWindowsMode | TabBoxWindowsAlternativeMode void KDEWalkThroughWindows(bool forward); void CDEWalkThroughWindows(bool forward); void walkThroughDesktops(bool forward); void KDEOneStepThroughWindows(bool forward, TabBoxMode mode); // TabBoxWindowsMode | TabBoxWindowsAlternativeMode void oneStepThroughDesktops(bool forward, TabBoxMode mode); // TabBoxDesktopMode | TabBoxDesktopListMode void oneStepThroughDesktops(bool forward); void oneStepThroughDesktopList(bool forward); bool establishTabBoxGrab(); void removeTabBoxGrab(); void modalActionsSwitch(bool enabled); private Q_SLOTS: void reconfigure(); private: TabBoxMode m_tabBoxMode; - QModelIndex m_index; TabBoxHandlerImpl* m_tabBox; bool m_delayShow; int m_delayShowTime; QTimer m_delayedShowTimer; int m_displayRefcount; TabBoxConfig m_defaultConfig; TabBoxConfig m_alternativeConfig; TabBoxConfig m_desktopConfig; TabBoxConfig m_desktopListConfig; // false if an effect has referenced the tabbox // true if tabbox is active (independent on showTabbox setting) bool m_isShown; bool m_desktopGrab; bool m_tabGrab; KShortcut m_cutWalkThroughDesktops, m_cutWalkThroughDesktopsReverse; KShortcut m_cutWalkThroughDesktopList, m_cutWalkThroughDesktopListReverse; KShortcut m_cutWalkThroughWindows, m_cutWalkThroughWindowsReverse; KShortcut m_cutWalkThroughGroupWindows, m_cutWalkThroughGroupWindowsReverse; KShortcut m_cutWalkThroughWindowsAlternative, m_cutWalkThroughWindowsAlternativeReverse; bool m_forcedGlobalMouseGrab; bool m_ready; // indicates whether the config is completely loaded }; } // namespace TabBox } // namespace #endif diff --git a/tabbox/tabboxhandler.cpp b/tabbox/tabboxhandler.cpp index 3e22dffe5..57b6dafb8 100644 --- a/tabbox/tabboxhandler.cpp +++ b/tabbox/tabboxhandler.cpp @@ -1,699 +1,707 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ // own #include "tabboxhandler.h" // tabbox #include "clientitemdelegate.h" #include "clientmodel.h" #include "declarative.h" #include "desktopitemdelegate.h" #include "desktopmodel.h" #include "itemlayoutconfig.h" #include "tabboxconfig.h" #include "tabboxview.h" // Qt #include #include #include #include #include #include #include #include #include // KDE #include #include #include namespace KWin { namespace TabBox { class TabBoxHandlerPrivate { public: TabBoxHandlerPrivate(TabBoxHandler *q); ~TabBoxHandlerPrivate(); /** * Updates the currently shown outline. */ void updateOutline(); /** * Updates the current highlight window state */ void updateHighlightWindows(); /** * Ends window highlighting */ void endHighlightWindows(bool abort = false); ClientModel* clientModel() const; DesktopModel* desktopModel() const; void createView(); void parseConfig(const QString& fileName); TabBoxHandler *q; // public pointer // members TabBoxConfig config; TabBoxView* view; DeclarativeView *m_declarativeView; ClientModel* m_clientModel; DesktopModel* m_desktopModel; QModelIndex index; /** * Indicates if the tabbox is shown. * Used to determine if the outline has to be updated, etc. */ bool isShown; QMap< QString, ItemLayoutConfig > tabBoxLayouts; TabBoxClient *lastRaisedClient, *lastRaisedClientSucc; }; TabBoxHandlerPrivate::TabBoxHandlerPrivate(TabBoxHandler *q) : view(NULL) , m_declarativeView(NULL) { this->q = q; isShown = false; lastRaisedClient = 0; lastRaisedClientSucc = 0; config = TabBoxConfig(); m_clientModel = new ClientModel(q); m_desktopModel = new DesktopModel(q); // load the layouts QFuture< void> future = QtConcurrent::run(this, &TabBoxHandlerPrivate::parseConfig, KStandardDirs::locate("data", "kwin/DefaultTabBoxLayouts.xml")); QFutureWatcher< void > *watcher = new QFutureWatcher< void >(q); watcher->setFuture(future); q->connect(watcher, SIGNAL(finished()), q, SIGNAL(ready())); } TabBoxHandlerPrivate::~TabBoxHandlerPrivate() { delete view; delete m_declarativeView; } void TabBoxHandlerPrivate::createView() { view = new TabBoxView(m_clientModel, m_desktopModel); if (tabBoxLayouts.contains(config.layoutName())) { view->clientDelegate()->setConfig(tabBoxLayouts.value(config.layoutName())); view->desktopDelegate()->setConfig(tabBoxLayouts.value(config.layoutName())); } else { view->clientDelegate()->setConfig(tabBoxLayouts.value("Default")); view->desktopDelegate()->setConfig(tabBoxLayouts.value("Desktop")); } if (tabBoxLayouts.contains(config.selectedItemLayoutName())) { view->additionalClientDelegate()->setConfig(tabBoxLayouts.value(config.selectedItemLayoutName())); } else { view->additionalClientDelegate()->setConfig(tabBoxLayouts.value("Text")); } view->desktopDelegate()->setLayouts(tabBoxLayouts); emit q->configChanged(); view->setCurrentIndex(index); } ClientModel* TabBoxHandlerPrivate::clientModel() const { return m_clientModel; } DesktopModel* TabBoxHandlerPrivate::desktopModel() const { return m_desktopModel; } void TabBoxHandlerPrivate::updateOutline() { if (config.tabBoxMode() != TabBoxConfig::ClientTabBox) return; // if ( c == NULL || !m_isShown || !c->isShown( true ) || !c->isOnCurrentDesktop()) if (!isShown || clientModel()->data(index, ClientModel::EmptyRole).toBool()) { q->hideOutline(); return; } TabBoxClient* c = static_cast< TabBoxClient* >(m_clientModel->data(index, ClientModel::ClientRole).value()); q->showOutline(QRect(c->x(), c->y(), c->width(), c->height())); } void TabBoxHandlerPrivate::updateHighlightWindows() { if (!isShown || config.tabBoxMode() != TabBoxConfig::ClientTabBox) return; Display *dpy = QX11Info::display(); TabBoxClient *currentClient = q->client(index); if (!KWindowSystem::compositingActive()) { if (lastRaisedClient) { if (lastRaisedClientSucc) q->restack(lastRaisedClient, lastRaisedClientSucc); // TODO lastRaisedClient->setMinimized( lastRaisedClientWasMinimized ); } lastRaisedClient = currentClient; if (lastRaisedClient) { // TODO if ( (lastRaisedClientWasMinimized = lastRaisedClient->isMinimized()) ) // lastRaisedClient->setMinimized( false ); TabBoxClientList order = q->stackingOrder(); int succIdx = order.indexOf(lastRaisedClient) + 1; // this is likely related to the index parameter?! lastRaisedClientSucc = (succIdx < order.count()) ? order.at(succIdx) : 0; q->raiseClient(lastRaisedClient); } } WId wId; QVector< WId > data; QWidget *w = NULL; if (view && view->isVisible()) { w = view; } else if (m_declarativeView && m_declarativeView->isVisible()) { w = m_declarativeView; } if (config.isShowTabBox() && w) { wId = w->winId(); data.resize(2); data[ 1 ] = wId; } else { wId = QX11Info::appRootWindow(); data.resize(1); } data[ 0 ] = currentClient ? currentClient->window() : 0L; if (config.isShowOutline()) { QVector outlineWindows = q->outlineWindowIds(); data.resize(2+outlineWindows.size()); for (int i=0; i(data.data()), data.size()); } void TabBoxHandlerPrivate::endHighlightWindows(bool abort) { if (abort && lastRaisedClient && lastRaisedClientSucc) q->restack(lastRaisedClient, lastRaisedClientSucc); lastRaisedClient = 0; lastRaisedClientSucc = 0; // highlight windows Display *dpy = QX11Info::display(); Atom atom = XInternAtom(dpy, "_KDE_WINDOW_HIGHLIGHT", False); XDeleteProperty(dpy, config.isShowTabBox() && view ? view->winId() : QX11Info::appRootWindow(), atom); } /*********************************************************** * Based on the implementation of Kopete's * contaclistlayoutmanager.cpp by Nikolaj Hald Nielsen and * Roman Jarosz ***********************************************************/ void TabBoxHandlerPrivate::parseConfig(const QString& fileName) { // open the file if (!QFile::exists(fileName)) { kDebug(1212) << "File " << fileName << " does not exist"; return; } QDomDocument doc("Layouts"); QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { kDebug(1212) << "Error reading file " << fileName; return; } if (!doc.setContent(&file)) { kDebug(1212) << "Error parsing file " << fileName; file.close(); return; } file.close(); QDomElement layouts_element = doc.firstChildElement("tabbox_layouts"); QDomNodeList layouts = layouts_element.elementsByTagName("layout"); for (int i = 0; i < layouts.size(); i++) { QDomNode layout = layouts.item(i); ItemLayoutConfig currentLayout; // parse top elements QDomElement element = layout.toElement(); QString layoutName = element.attribute("name", ""); const bool highlightIcon = (element.attribute("highlight_selected_icon", "true").compare("true", Qt::CaseInsensitive) == 0); currentLayout.setHighlightSelectedIcons(highlightIcon); const bool grayscaleIcon = (element.attribute("grayscale_deselected_icon", "false").compare("true", Qt::CaseInsensitive) == 0); currentLayout.setGrayscaleDeselectedIcons(grayscaleIcon); // rows QDomNodeList rows = element.elementsByTagName("row"); for (int j = 0; j < rows.size(); j++) { QDomNode rowNode = rows.item(j); ItemLayoutConfigRow row; QDomNodeList elements = rowNode.toElement().elementsByTagName("element"); for (int k = 0; k < elements.size(); k++) { QDomNode elementNode = elements.item(k); QDomElement currentElement = elementNode.toElement(); ItemLayoutConfigRowElement::ElementType type = ItemLayoutConfigRowElement::ElementType(currentElement.attribute( "type", int(ItemLayoutConfigRowElement::ElementClientName)).toInt()); ItemLayoutConfigRowElement currentRowElement; currentRowElement.setType(type); // width - used by all types qreal width = currentElement.attribute("width", "0.0").toDouble(); currentRowElement.setWidth(width); switch(type) { case ItemLayoutConfigRowElement::ElementEmpty: row.addElement(currentRowElement); break; case ItemLayoutConfigRowElement::ElementIcon: { qreal iconWidth = currentElement.attribute("icon_size", "16.0").toDouble(); currentRowElement.setIconSize(QSizeF(iconWidth, iconWidth)); currentRowElement.setRowSpan(currentElement.attribute("row_span", "true").compare( "true", Qt::CaseInsensitive) == 0); row.addElement(currentRowElement); break; } case ItemLayoutConfigRowElement::ElementClientList: { currentRowElement.setStretch(currentElement.attribute("stretch", "false").compare( "true", Qt::CaseInsensitive) == 0); currentRowElement.setClientListLayoutName(currentElement.attribute("layout_name", "")); QString layoutMode = currentElement.attribute("layout_mode", "horizontal"); if (layoutMode.compare("horizontal", Qt::CaseInsensitive) == 0) currentRowElement.setClientListLayoutMode(TabBoxConfig::HorizontalLayout); else if (layoutMode.compare("vertical", Qt::CaseInsensitive) == 0) currentRowElement.setClientListLayoutMode(TabBoxConfig::VerticalLayout); else if (layoutMode.compare("tabular", Qt::CaseInsensitive) == 0) currentRowElement.setClientListLayoutMode(TabBoxConfig::HorizontalVerticalLayout); row.addElement(currentRowElement); break; } default: { // text elements currentRowElement.setStretch(currentElement.attribute("stretch", "false").compare( "true", Qt::CaseInsensitive) == 0); currentRowElement.setSmallTextSize(currentElement.attribute("small", "false").compare( "true", Qt::CaseInsensitive) == 0); currentRowElement.setBold(currentElement.attribute("bold", "false").compare( "true", Qt::CaseInsensitive) == 0); currentRowElement.setItalic(currentElement.attribute("italic", "false").compare( "true", Qt::CaseInsensitive) == 0); currentRowElement.setItalicMinimized(currentElement.attribute("italic_minimized", "true").compare( "true", Qt::CaseInsensitive) == 0); currentRowElement.setPrefix(currentElement.attribute("prefix", "")); currentRowElement.setSuffix(currentElement.attribute("suffix", "")); currentRowElement.setPrefixMinimized(currentElement.attribute("prefix_minimized", "")); currentRowElement.setSuffixMinimzed(currentElement.attribute("suffix_minimized", "")); QString halign = currentElement.attribute("horizontal_alignment", "left"); Qt::Alignment alignment; if (halign.compare("left", Qt::CaseInsensitive) == 0) alignment = Qt::AlignLeft; else if (halign.compare("right", Qt::CaseInsensitive) == 0) alignment = Qt::AlignRight; else alignment = Qt::AlignCenter; QString valign = currentElement.attribute("vertical_alignment", "center"); if (valign.compare("top", Qt::CaseInsensitive) == 0) alignment = alignment | Qt::AlignTop; else if (valign.compare("bottom", Qt::CaseInsensitive) == 0) alignment = alignment | Qt::AlignBottom; else alignment = alignment | Qt::AlignVCenter; currentRowElement.setAlignment(alignment); row.addElement(currentRowElement); break; }// case default } // switch type } // for loop elements currentLayout.addRow(row); } // for loop rows if (!layoutName.isEmpty()) { tabBoxLayouts.insert(layoutName, currentLayout); } } // for loop layouts } /*********************************************** * TabBoxHandler ***********************************************/ TabBoxHandler::TabBoxHandler() : QObject() { KWin::TabBox::tabBox = this; d = new TabBoxHandlerPrivate(this); } TabBoxHandler::~TabBoxHandler() { delete d; } const KWin::TabBox::TabBoxConfig& TabBoxHandler::config() const { return d->config; } void TabBoxHandler::setConfig(const TabBoxConfig& config) { if (config.layoutName() != d->config.layoutName()) { // new item layout config if (d->tabBoxLayouts.contains(config.layoutName()) && d->view) { d->view->clientDelegate()->setConfig(d->tabBoxLayouts.value(config.layoutName())); d->view->desktopDelegate()->setConfig(d->tabBoxLayouts.value(config.layoutName())); } } if (config.selectedItemLayoutName() != d->config.selectedItemLayoutName()) { // TODO: desktop layouts if (d->tabBoxLayouts.contains(config.selectedItemLayoutName()) && d->view) d->view->additionalClientDelegate()->setConfig(d->tabBoxLayouts.value(config.selectedItemLayoutName())); } d->config = config; emit configChanged(); } void TabBoxHandler::show() { d->isShown = true; d->lastRaisedClient = 0; d->lastRaisedClientSucc = 0; // show the outline if (d->config.isShowOutline()) { d->updateOutline(); } if (d->config.isShowTabBox()) { if (d->config.tabBoxMode() == TabBoxConfig::ClientTabBox) { // use declarative view if (!d->m_declarativeView) { d->m_declarativeView = new DeclarativeView(d->clientModel()); } d->m_declarativeView->show(); d->m_declarativeView->setCurrentIndex(d->index); } else { if (!d->view) { d->createView(); } d->view->show(); d->view->updateGeometry(); } } if (d->config.isHighlightWindows()) { d->updateHighlightWindows(); } } void TabBoxHandler::hide(bool abort) { d->isShown = false; if (d->config.isHighlightWindows()) { d->endHighlightWindows(abort); } if (d->config.isShowOutline()) { hideOutline(); } if (d->view) { d->view->hide(); } if (d->m_declarativeView) { d->m_declarativeView->hide(); } } QModelIndex TabBoxHandler::nextPrev(bool forward) const { QModelIndex ret; QAbstractItemModel* model; switch(d->config.tabBoxMode()) { case TabBoxConfig::ClientTabBox: model = d->clientModel(); break; case TabBoxConfig::DesktopTabBox: model = d->desktopModel(); break; default: return d->index; } if (forward) { int column = d->index.column() + 1; int row = d->index.row(); if (column == model->columnCount()) { column = 0; row++; if (row == model->rowCount()) row = 0; } ret = model->index(row, column); if (!ret.isValid()) ret = model->index(0, 0); } else { int column = d->index.column() - 1; int row = d->index.row(); if (column < 0) { column = model->columnCount() - 1; row--; if (row < 0) row = model->rowCount() - 1; } ret = model->index(row, column); if (!ret.isValid()) { row = model->rowCount() - 1; for (int i = model->columnCount() - 1; i >= 0; i--) { ret = model->index(row, i); if (ret.isValid()) break; } } } if (ret.isValid()) return ret; else return d->index; } QModelIndex TabBoxHandler::desktopIndex(int desktop) const { if (d->config.tabBoxMode() != TabBoxConfig::DesktopTabBox) return QModelIndex(); return d->desktopModel()->desktopIndex(desktop); } QList< int > TabBoxHandler::desktopList() const { if (d->config.tabBoxMode() != TabBoxConfig::DesktopTabBox) return QList< int >(); return d->desktopModel()->desktopList(); } int TabBoxHandler::desktop(const QModelIndex& index) const { if (!index.isValid() || (d->config.tabBoxMode() != TabBoxConfig::DesktopTabBox)) return -1; QVariant ret = d->desktopModel()->data(index, DesktopModel::DesktopRole); if (ret.isValid()) return ret.toInt(); else return -1; } int TabBoxHandler::currentSelectedDesktop() const { return desktop(d->index); } void TabBoxHandler::setCurrentIndex(const QModelIndex& index) { + if (d->index == index) { + return; + } if (d->view) { d->view->setCurrentIndex(index); } if (d->m_declarativeView) { d->m_declarativeView->setCurrentIndex(index); } d->index = index; if (d->config.tabBoxMode() == TabBoxConfig::ClientTabBox) { if (d->config.isShowOutline()) { d->updateOutline(); } if (d->config.isHighlightWindows()) { d->updateHighlightWindows(); } } } +const QModelIndex& TabBoxHandler::currentIndex() const +{ + return d->index; +} + QModelIndex TabBoxHandler::grabbedKeyEvent(QKeyEvent* event) const { QModelIndex ret; QAbstractItemModel* model; switch(d->config.tabBoxMode()) { case TabBoxConfig::ClientTabBox: model = d->clientModel(); break; case TabBoxConfig::DesktopTabBox: model = d->desktopModel(); break; default: return d->index; } int column = d->index.column(); int row = d->index.row(); switch(event->key()) { case Qt::Key_Left: column--; if (column < 0) column = model->columnCount() - 1; break; case Qt::Key_Right: column++; if (column >= model->columnCount()) column = 0; break; case Qt::Key_Up: row--; if (row < 0) row = model->rowCount() - 1; break; case Qt::Key_Down: row++; if (row >= model->rowCount()) row = 0; break; default: // do not do anything for any other key break; } ret = model->index(row, column); if (ret.isValid()) return ret; else return d->index; } bool TabBoxHandler::containsPos(const QPoint& pos) const { QWidget *w = NULL; if (d->view && d->view->isVisible()) { w = d->view; } else if (d->m_declarativeView && d->m_declarativeView->isVisible()) { w = d->m_declarativeView; } else { return false; } return w->geometry().contains(pos); } QModelIndex TabBoxHandler::indexAt(const QPoint& pos) const { if (d->view && d->view->isVisible()) { QPoint widgetPos = d->view->mapFromGlobal(pos); return d->view->indexAt(widgetPos); } else if (d->m_declarativeView && d->m_declarativeView->isVisible()) { QPoint widgetPos = d->m_declarativeView->mapFromGlobal(pos); return d->m_declarativeView->indexAt(widgetPos); } return QModelIndex(); } QModelIndex TabBoxHandler::index(KWin::TabBox::TabBoxClient* client) const { return d->clientModel()->index(client); } TabBoxClientList TabBoxHandler::clientList() const { if (d->config.tabBoxMode() != TabBoxConfig::ClientTabBox) return TabBoxClientList(); return d->clientModel()->clientList(); } TabBoxClient* TabBoxHandler::client(const QModelIndex& index) const { if ((!index.isValid()) || (d->config.tabBoxMode() != TabBoxConfig::ClientTabBox) || (d->clientModel()->data(index, ClientModel::EmptyRole).toBool())) return NULL; TabBoxClient* c = static_cast< TabBoxClient* >( d->clientModel()->data(index, ClientModel::ClientRole).value()); return c; } void TabBoxHandler::createModel(bool partialReset) { switch(d->config.tabBoxMode()) { case TabBoxConfig::ClientTabBox: d->clientModel()->createClientList(partialReset); if (d->lastRaisedClient && !stackingOrder().contains(d->lastRaisedClient)) d->lastRaisedClient = 0; if (d->lastRaisedClientSucc && !stackingOrder().contains(d->lastRaisedClientSucc)) d->lastRaisedClientSucc = 0; break; case TabBoxConfig::DesktopTabBox: d->desktopModel()->createDesktopList(); break; } if (d->view) { d->view->updateGeometry(); } } QModelIndex TabBoxHandler::first() const { QAbstractItemModel* model; switch(d->config.tabBoxMode()) { case TabBoxConfig::ClientTabBox: model = d->clientModel(); break; case TabBoxConfig::DesktopTabBox: model = d->desktopModel(); break; default: return QModelIndex(); } return model->index(0, 0); } QWidget* TabBoxHandler::tabBoxView() const { return d->view; } TabBoxHandler* tabBox = 0; TabBoxClient::TabBoxClient() { } TabBoxClient::~TabBoxClient() { } } // namespace TabBox } // namespace KWin diff --git a/tabbox/tabboxhandler.h b/tabbox/tabboxhandler.h index cefec5f58..bf9fecdee 100644 --- a/tabbox/tabboxhandler.h +++ b/tabbox/tabboxhandler.h @@ -1,393 +1,397 @@ /******************************************************************** KWin - the KDE window manager This file is part of the KDE project. Copyright (C) 2009 Martin Gräßlin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . *********************************************************************/ #ifndef TABBOXHANDLER_H #define TABBOXHANDLER_H #include "tabboxconfig.h" #include #include #include #include #include /** * @file * This file contains the classes which hide KWin core from tabbox. * It defines the pure virtual classes TabBoxHandler and TabBoxClient. * The classes have to be implemented in KWin Core. * * @author Martin Gräßlin * @since 4.4 */ class QKeyEvent; namespace KWin { /** * The TabBox is a model based view for displaying a list while switching windows or desktops. * This functionality is mostly referred as Alt+Tab. TabBox itself does not provide support for * switching windows or desktops. This has to be done outside of TabBox inside an independent controller. * * The main entrance point to TabBox is the class TabBoxHandler, which has to be subclassed and implemented. * The class TabBoxClient, which represents a window client inside TabBox, has to be implemented as well. * * The behavior of the TabBox is defined by the TabBoxConfig and has to be set in the TabBoxHandler. * If the TabBox should be used to switch desktops as well as clients it is sufficient to just provide * different TabBoxConfig objects instead of creating an own handler for each mode. * * In order to use the TabBox the TabBoxConfig has to be set. This defines if the model for desktops or for * clients will be used. The model has to be initialized by calling TabBoxHandler::createModel(), as the * model is undefined when the TabBox is not active. The TabBox is activated by TabBoxHandler::show(). * Depending on the current set TabBoxConfig it is possible that an additional outline is shown, the * highlight windows effect activated and that the view is not displayed at all. As already mentioned * the TabBox does not handle any updating of the selected item. This has to be done by invoking * TabBoxHandler::setCurrentIndex(). Nevertheless the TabBoxHandler provides methods to query for the * model index or the next or previous item, for a cursor position or for a given item (that is * TabBoxClient or desktop). By invoking TabBoxHandler::hide() the view, the optional outline and the * optional highlight windows effect are removed. The model is invalidated immediately. So if it is * necessary to retrieve the last selected item this has to be done before calling the hide method. * * The layout of the TabBox View and the items is completely customizable. Therefore TabBox provides * a widget LayoutConfig which includes a live preview (in kcmkwin/kwintabbox). The layout of items * can be defined by an xml document. That way the user is able to define own custom layouts. The view * itself is made up of two widgets: one to show the complete list and one to show only the selected * item. This way it is possible to have a view which shows for example a list containing only small * icons and nevertheless show the title of the currently selected client. */ namespace TabBox { class DesktopModel; class ClientModel; class TabBoxConfig; class TabBoxClient; class TabBoxView; class TabBoxHandlerPrivate; typedef QList< TabBoxClient* > TabBoxClientList; /** * This class is a wrapper around KWin Workspace. It is used for accessing the * required core methods from inside TabBox and has to be implemented in KWin core. * * @author Martin Gräßlin * @since 4.4 */ class TabBoxHandler : public QObject { Q_OBJECT public: TabBoxHandler(); virtual ~TabBoxHandler(); /** * @return The id of the active screen */ virtual int activeScreen() const = 0; /** * @return The current active TabBoxClient or NULL * if there is no active client. */ virtual TabBoxClient* activeClient() const = 0; /** * @param client The client which is starting point to find the next client * @return The next TabBoxClient in focus chain */ virtual TabBoxClient* nextClientFocusChain(TabBoxClient* client) const = 0; /** * @param client The client whose desktop name should be retrieved * @return The desktop name of the given TabBoxClient. If the client is * on all desktops the name of current desktop will be returned. */ virtual QString desktopName(TabBoxClient* client) const = 0; /** * @param desktop The desktop whose name should be retrieved * @return The desktop name of given desktop */ virtual QString desktopName(int desktop) const = 0; /** * @return The number of current desktop */ virtual int currentDesktop() const = 0; /** * @return The number of virtual desktops */ virtual int numberOfDesktops() const = 0; /** * @param desktop The desktop which is the starting point to find the next desktop * @return The next desktop in the current focus chain. */ virtual int nextDesktopFocusChain(int desktop) const = 0; /** * Raise a client (w/o activating it) */ virtual void raiseClient(TabBoxClient* c) const = 0; /** * @param c The client to be restacked * @param under The client the other one will be placed below */ virtual void restack(TabBoxClient *c, TabBoxClient *under) = 0; /** * @return The current stacking order of TabBoxClients */ virtual TabBoxClientList stackingOrder() const = 0; /** * Determines if given client will be added to the list: *
    *
  • Depends on desktop
  • *
  • if the client wants to have tab focus.
  • *
  • The client won't be added if it has modal dialogs
  • *
  • In that case the modal dialog will be returned if it isn't already * included
  • *
  • Won't be added if it isn't on active screen when using separate * screen focus
  • *
* @param client The client to be checked for inclusion * @param desktop The desktop the client should be on. This is irrelevant if allDesktops is set * @param allDesktops Add clients from all desktops or only from current * @return The client to be included in the list or NULL if it isn't to be included */ virtual TabBoxClient* clientToAddToList(TabBoxClient* client, int desktop, bool allDesktops) const = 0; /** * @return The first desktop window in the stacking order. */ virtual TabBoxClient* desktopClient() const = 0; /** * @return The currently used TabBoxConfig */ const TabBoxConfig& config() const; /** * Call this method when you want to change the currently used TabBoxConfig. * It fires the signal configChanged. * @param config Updates the currently used TabBoxConfig to config */ void setConfig(const TabBoxConfig& config); /** * Call this method to show the TabBoxView. Depending on current * configuration this method might not do anything. * If highlight windows effect is to be used it will be activated. * If the outline has to be shown, it will be shown. * Highlight windows and outline are not shown if * TabBoxConfig::TabBoxMode is TabBoxConfig::DesktopTabBox. * @see TabBoxConfig::isShowTabBox * @see TabBoxConfig::isHighlightWindows * @see TabBoxConfig::showOutline */ void show(); /** * Hides the TabBoxView if shown. * Deactivates highlight windows effect if active. * Removes the outline if active. * @see show */ void hide(bool abort = false); /** * Sets the current model index in the view and updates * highlight windows and outline if active. * @param index The current Model index */ void setCurrentIndex(const QModelIndex& index); + /** + * @returns the current index + **/ + const QModelIndex ¤tIndex() const; /** * Retrieves the next or previous item of the current item. * @param forward next or previous item * @return The next or previous item. If there is no matching item * the current item will be returned. */ QModelIndex nextPrev(bool forward) const; /** * Initializes the model based on the current config. * This method has to be invoked before showing the TabBox. * It can also be invoked when clients are added or removed. * In that case partialReset has to be true. * * @param partialReset Keep the currently selected item or regenerate everything */ void createModel(bool partialReset = false); /** * @param desktop The desktop whose index should be retrieved * @return The model index of given desktop. If TabBoxMode is not * TabBoxConfig::DesktopTabBox an invalid model index will be returned. */ QModelIndex desktopIndex(int desktop) const; /** * @return The current list of desktops. * If TabBoxMode is not TabBoxConfig::DesktopTabBox an empty list will * be returned. * @see DesktopModel::desktopList */ QList< int > desktopList() const; /** * @return The desktop for given model index. If the index is not valid * or TabBoxMode is not TabBoxConfig::DesktopTabBox -1 will be returned. * @see DesktopModel::desktopIndex */ int desktop(const QModelIndex& index) const; /** * @return The current selected desktop. If there is no selected desktop * or TabBoxMode is not TabBoxConfig::DesktopTabBox -1 will be returned. */ int currentSelectedDesktop() const; /** * Handles additional grabbed key events by the TabBox controller. * It is able to handle cursor key presses and to find the item * left/right/above/below of current item. * @param event The key event which has been grabbed * @return Returns the model index of the left, right, above or * below item, if a cursor key has been pressed. If there is no * such item the current item is returned. */ virtual QModelIndex grabbedKeyEvent(QKeyEvent* event) const; /** * @param pos The position to be tested in global coordinates * @return True if the view contains the point, otherwise false. */ bool containsPos(const QPoint& pos) const; /** * Returns the index at the given position in global coordinates * of the view. * @param pos The position in global coordinates * @return The model index at given position. If there is no item * at the position or the position is not in the view an invalid * model index will be returned; */ QModelIndex indexAt(const QPoint& pos) const; /** * @param client The TabBoxClient whose index should be returned * @return Returns the ModelIndex of given TabBoxClient or an invalid ModelIndex * if the model does not contain the given TabBoxClient. * @see ClientModel::index */ QModelIndex index(TabBoxClient* client) const; /** * @return Returns the current list of TabBoxClients. * If TabBoxMode is not TabBoxConfig::ClientTabBox an empty list will * be returned. * @see ClientModel::clientList */ TabBoxClientList clientList() const; /** * @param index The index of the client to be returned * @return Returns the TabBoxClient at given model index. If * the index is invalid, does not point to a Client or the list * is empty, NULL will be returned. */ TabBoxClient* client(const QModelIndex& index) const; /** * @return The first model index. That is the model index at position 0, 0. * It is valid, as desktop has at least one desktop and if there are no * clients an empty item is created. */ QModelIndex first() const; /** * @return The tabBoxView Widget */ QWidget* tabBoxView() const; protected: /** * Show the outline of the current selected window * @param outline The geometry of the window the outline will be shown * @since 4.7 **/ virtual void showOutline(const QRect &outline) = 0; /** * Hide previously shown outline * @since 4.7 **/ virtual void hideOutline() = 0; /** * Return outline window ids * @return The outline window ids given in the order left, top, right, bottom * @since 4.7 **/ virtual QVector outlineWindowIds() const = 0; signals: /** * This signal is fired when the TabBoxConfig changes * @see setConfig */ void configChanged(); void ready(); private: friend class TabBoxHandlerPrivate; TabBoxHandlerPrivate* d; }; /** * This class is a wrapper around a KWin Client. It is used for accessing the * required client methods from inside TabBox and has to be implemented in KWin core. * * @author Martin Gräßlin * @since 4.4 */ class TabBoxClient { public: TabBoxClient(); virtual ~TabBoxClient(); /** * @return The caption of the client */ virtual QString caption() const = 0; /** * @param size Requested size of the icon * @return The icon of the client */ virtual QPixmap icon(const QSize& size = QSize(32, 32)) const = 0; /** * @return The window Id of the client */ virtual WId window() const = 0; /** * @return Minimized state of the client */ virtual bool isMinimized() const = 0; virtual int x() const = 0; virtual int y() const = 0; virtual int width() const = 0; virtual int height() const = 0; }; /** * Pointer to the global TabBoxHandler object. **/ extern TabBoxHandler* tabBox; } // namespace TabBox } // namespace KWin #endif // TABBOXHANDLER_H